]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
Update years in copyright notice; nfc.
[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, Inc.
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.04
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.04
85 ;; - Cleanup tags display in agenda.
86 ;; - Bug fixes.
87 ;;
88 ;; Version 4.03
89 ;; - Table alignment fixed for use with wide characters.
90 ;; - `C-c -' leaves cursor in current table line.
91 ;; - The current TAG can be incorporated into the agenda prefix.
92 ;; See option `org-agenda-prefix-format' for details.
93 ;;
94 ;; Version 4.02
95 ;; - Minor bug fixes and improvements around tag searches.
96 ;; - XEmacs compatibility fixes.
97 ;;
98 ;; Version 4.01
99 ;; - Tags can also be set remotely from agenda buffer.
100 ;; - Boolean logic for tag searches.
101 ;; - Additional agenda commands can be configured through the variable
102 ;; `org-agenda-custom-commands'.
103 ;; - Minor bug fixes.
104 ;;
105 ;;; Code:
106
107 (eval-when-compile (require 'cl) (require 'calendar))
108 (require 'outline)
109 (require 'time-date)
110 (require 'easymenu)
111
112 (defvar calc-embedded-close-formula)
113 (defvar calc-embedded-open-formula)
114 (defvar font-lock-unfontify-region-function)
115
116 ;;; Customization variables
117
118 (defvar org-version "4.04"
119 "The version number of the file org.el.")
120 (defun org-version ()
121 (interactive)
122 (message "Org-mode version %s" org-version))
123
124 ;; The following two constants are for compatibility with different Emacs
125 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
126 ;; The compatibility code in org.el is based on these two constants.
127 (defconst org-xemacs-p (featurep 'xemacs)
128 "Are we running xemacs?")
129 (defconst org-noutline-p (featurep 'noutline)
130 "Are we using the new outline mode?")
131
132 (defgroup org nil
133 "Outline-based notes management and organizer."
134 :tag "Org"
135 :group 'outlines
136 :group 'hypermedia
137 :group 'calendar)
138
139 (defgroup org-startup nil
140 "Options concerning startup of Org-mode."
141 :tag "Org Startup"
142 :group 'org)
143
144 (defcustom org-CUA-compatible nil
145 "Non-nil means use alternative key bindings for S-<cursor movement>.
146 Org-mode used S-<cursor movement> for changing timestamps and priorities.
147 S-<cursor movement> is also used for example by `CUA-mode' to select text.
148 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
149 alternative bindings. Setting this variable to t will replace the following
150 keys both in Org-mode and in the Org-agenda buffer.
151
152 S-RET -> C-S-RET
153 S-up -> M-p
154 S-down -> M-n
155 S-left -> M--
156 S-right -> M-+
157
158 If you do not like the alternative keys, take a look at the variable
159 `org-disputed-keys'.
160
161 This option is only relevant at load-time of Org-mode. Changing it requires
162 a restart of Emacs to become effective."
163 :group 'org-startup
164 :type 'boolean)
165
166 (defvar org-disputed-keys
167 '((S-up [(shift up)] [(meta ?p)])
168 (S-down [(shift down)] [(meta ?n)])
169 (S-left [(shift left)] [(meta ?-)])
170 (S-right [(shift right)] [(meta ?+)])
171 (S-return [(shift return)] [(control shift return)]))
172 "Keys for which Org-mode and other modes compete.
173 This is an alist, cars are symbols for lookup, 1st element is the default key,
174 second element will be used when `org-CUA-compatible' is t.")
175
176 (defun org-key (key)
177 "Select a key according to `org-CUA-compatible'."
178 (nth (if org-CUA-compatible 2 1)
179 (or (assq key org-disputed-keys)
180 (error "Invalid Key %s in `org-key'" key))))
181
182 (defcustom org-startup-folded t
183 "Non-nil means, entering Org-mode will switch to OVERVIEW.
184 This can also be configured on a per-file basis by adding one of
185 the following lines anywhere in the buffer:
186
187 #+STARTUP: fold
188 #+STARTUP: nofold
189 #+STARTUP: content"
190 :group 'org-startup
191 :type '(choice
192 (const :tag "nofold: show all" nil)
193 (const :tag "fold: overview" t)
194 (const :tag "content: all headlines" content)))
195
196 (defcustom org-startup-truncated t
197 "Non-nil means, entering Org-mode will set `truncate-lines'.
198 This is useful since some lines containing links can be very long and
199 uninteresting. Also tables look terrible when wrapped."
200 :group 'org-startup
201 :type 'boolean)
202
203 (defcustom org-startup-with-deadline-check nil
204 "Non-nil means, entering Org-mode will run the deadline check.
205 This means, if you start editing an org file, you will get an
206 immediate reminder of any due deadlines.
207 This can also be configured on a per-file basis by adding one of
208 the following lines anywhere in the buffer:
209
210 #+STARTUP: dlcheck
211 #+STARTUP: nodlcheck"
212 :group 'org-startup
213 :type 'boolean)
214
215 (defcustom org-insert-mode-line-in-empty-file nil
216 "Non-nil means insert the first line setting Org-mode in empty files.
217 When the function `org-mode' is called interactively in an empty file, this
218 normally means that the file name does not automatically trigger Org-mode.
219 To ensure that the file will always be in Org-mode in the future, a
220 line enforcing Org-mode will be inserted into the buffer, if this option
221 has been set."
222 :group 'org-startup
223 :type 'boolean)
224
225 (defgroup org-keywords nil
226 "Options concerning TODO items in Org-mode."
227 :tag "Org Keywords"
228 :group 'org)
229
230 (defcustom org-todo-keywords '("TODO" "DONE")
231 "List of TODO entry keywords.
232 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
233 considered to mean that the entry is \"done\". All the other mean that
234 action is required, and will make the entry show up in todo lists, diaries
235 etc.
236 The command \\[org-todo] cycles an entry through these states, and an
237 additional state where no keyword is present. For details about this
238 cycling, see also the variable `org-todo-interpretation'
239 Changes become only effective after restarting Emacs."
240 :group 'org-keywords
241 :type '(repeat (string :tag "Keyword")))
242
243 (defcustom org-todo-interpretation 'sequence
244 "Controls how TODO keywords are interpreted.
245 \\<org-mode-map>Possible values are `sequence' and `type'.
246 This variable is only relevant if `org-todo-keywords' contains more than two
247 states. There are two ways how these keywords can be used:
248
249 - As a sequence in the process of working on a TODO item, for example
250 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
251 org-todo-interpretation 'sequence)
252
253 - As different types of TODO items, for example
254 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
255 org-todo-interpretation 'type)
256
257 When the states are interpreted as a sequence, \\[org-todo] always cycles
258 to the next state, in order to walk through all different states. So with
259 \\[org-todo], you turn an empty entry into the state TODO. When you started
260 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
261 later to VERIFY and finally to DONE.
262
263 When the states are interpreted as types, \\[org-todo] still cycles through
264 when it is called several times in direct succession, in order to initially
265 select the type. However, if not called immediately after a previous
266 \\[org-todo], it switches from each type directly to DONE. So with the
267 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
268 RELAXED. If you later return to this entry and press \\[org-todo] again,
269 RELAXED will not be changed REMIND, but directly to DONE.
270
271 You can create a large number of types. To initially select a
272 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
273 type with completion. Of course, you can also type the keyword
274 directly into the buffer. M-TAB completes TODO keywords at the
275 beginning of a headline."
276 :group 'org-keywords
277 :type '(choice (const sequence)
278 (const type)))
279
280 (defcustom org-default-priority ?B
281 "The default priority of TODO items.
282 This is the priority an item get if no explicit priority is given."
283 :group 'org-keywords
284 :type 'character)
285
286 (defcustom org-lowest-priority ?C
287 "The lowest priority of TODO items. A character like ?A, ?B etc."
288 :group 'org-keywords
289 :type 'character)
290
291 (defcustom org-deadline-string "DEADLINE:"
292 "String to mark deadline entries.
293 A deadline is this string, followed by a time stamp. Should be a word,
294 terminated by a colon. You can insert a schedule keyword and
295 a timestamp with \\[org-deadline].
296 Changes become only effective after restarting Emacs."
297 :group 'org-keywords
298 :type 'string)
299
300 (defcustom org-scheduled-string "SCHEDULED:"
301 "String to mark scheduled TODO entries.
302 A schedule is this string, followed by a time stamp. Should be a word,
303 terminated by a colon. You can insert a schedule keyword and
304 a timestamp with \\[org-schedule].
305 Changes become only effective after restarting Emacs."
306 :group 'org-keywords
307 :type 'string)
308
309 (defcustom org-closed-string "CLOSED:"
310 "String used as the prefix for timestamps logging closing a TODO entry."
311 :group 'org-keywords
312 :type 'string)
313
314 (defcustom org-comment-string "COMMENT"
315 "Entries starting with this keyword will never be exported.
316 An entry can be toggled between COMMENT and normal with
317 \\[org-toggle-comment].
318 Changes become only effective after restarting Emacs."
319 :group 'org-keywords
320 :type 'string)
321
322 (defcustom org-quote-string "QUOTE"
323 "Entries starting with this keyword will be exported in fixed-width font.
324 Quoting applies only to the text in the entry following the headline, and does
325 not extend beyond the next headline, even if that is lower level.
326 An entry can be toggled between QUOTE and normal with
327 \\[org-toggle-fixed-width-section]."
328 :group 'org-keywords
329 :type 'string)
330
331 (defcustom org-after-todo-state-change-hook nil
332 "Hook which is run after the state of a TODO item was changed.
333 The new state (a string with a TODO keyword, or nil) is available in the
334 Lisp variable `state'."
335 :group 'org-keywords
336 :type 'hook)
337
338 ;; Variables for pre-computed regular expressions, all buffer local
339 (defvar org-todo-kwd-priority-p nil
340 "Do TODO items have priorities?")
341 (make-variable-buffer-local 'org-todo-kwd-priority-p)
342 (defvar org-todo-kwd-max-priority nil
343 "Maximum priority of TODO items.")
344 (make-variable-buffer-local 'org-todo-kwd-max-priority)
345 (defvar org-ds-keyword-length 12
346 "Maximum length of the Deadline and SCHEDULED keywords.")
347 (make-variable-buffer-local 'org-ds-keyword-length)
348 (defvar org-done-string nil
349 "The last string in `org-todo-keywords', indicating an item is DONE.")
350 (make-variable-buffer-local 'org-done-string)
351 (defvar org-todo-regexp nil
352 "Matches any of the TODO state keywords.")
353 (make-variable-buffer-local 'org-todo-regexp)
354 (defvar org-not-done-regexp nil
355 "Matches any of the TODO state keywords except the last one.")
356 (make-variable-buffer-local 'org-not-done-regexp)
357 (defvar org-todo-line-regexp nil
358 "Matches a headline and puts TODO state into group 2 if present.")
359 (make-variable-buffer-local 'org-todo-line-regexp)
360 (defvar org-nl-done-regexp nil
361 "Matches newline followed by a headline with the DONE keyword.")
362 (make-variable-buffer-local 'org-nl-done-regexp)
363 (defvar org-looking-at-done-regexp nil
364 "Matches the DONE keyword a point.")
365 (make-variable-buffer-local 'org-looking-at-done-regexp)
366 (defvar org-deadline-regexp nil
367 "Matches the DEADLINE keyword.")
368 (make-variable-buffer-local 'org-deadline-regexp)
369 (defvar org-deadline-time-regexp nil
370 "Matches the DEADLINE keyword together with a time stamp.")
371 (make-variable-buffer-local 'org-deadline-time-regexp)
372 (defvar org-deadline-line-regexp nil
373 "Matches the DEADLINE keyword and the rest of the line.")
374 (make-variable-buffer-local 'org-deadline-line-regexp)
375 (defvar org-scheduled-regexp nil
376 "Matches the SCHEDULED keyword.")
377 (make-variable-buffer-local 'org-scheduled-regexp)
378 (defvar org-scheduled-time-regexp nil
379 "Matches the SCHEDULED keyword together with a time stamp.")
380 (make-variable-buffer-local 'org-scheduled-time-regexp)
381
382 (defvar org-category nil
383 "Variable used by org files to set a category for agenda display.
384 Such files should use a file variable to set it, for example
385
386 -*- mode: org; org-category: \"ELisp\"
387
388 or contain a special line
389
390 #+CATEGORY: ELisp
391
392 If the file does not specify a category, then file's base name
393 is used instead.")
394 (make-variable-buffer-local 'org-category)
395
396 (defgroup org-time nil
397 "Options concerning time stamps and deadlines in Org-mode."
398 :tag "Org Time"
399 :group 'org)
400
401 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
402 "Formats for `format-time-string' which are used for time stamps.
403 It is not recommended to change this constant.")
404
405
406 (defcustom org-deadline-warning-days 30
407 "No. of days before expiration during which a deadline becomes active.
408 This variable governs the display in the org file."
409 :group 'org-time
410 :type 'number)
411
412 (defcustom org-popup-calendar-for-date-prompt t
413 "Non-nil means, pop up a calendar when prompting for a date.
414 In the calendar, the date can be selected with mouse-1. However, the
415 minibuffer will also be active, and you can simply enter the date as well.
416 When nil, only the minibuffer will be available."
417 :group 'org-time
418 :type 'number)
419
420 (defcustom org-calendar-follow-timestamp-change t
421 "Non-nil means, make the calendar window follow timestamp changes.
422 When a timestamp is modified and the calendar window is visible, it will be
423 moved to the new date."
424 :group 'org-time
425 :type 'boolean)
426
427 (defcustom org-log-done nil
428 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
429 When the state of an entry is changed from nothing to TODO, remove a previous
430 closing date."
431 :group 'org-time
432 :type 'boolean)
433
434 (defgroup org-agenda nil
435 "Options concerning agenda display Org-mode."
436 :tag "Org Agenda"
437 :group 'org)
438
439 (defcustom org-agenda-files nil
440 "A list of org files for agenda/diary display.
441 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
442 \\[org-remove-file]. You can also use customize to edit the list."
443 :group 'org-agenda
444 :type '(repeat file))
445
446 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
447 "Custom commands for the agenda.
448 These commands will be offered on the splash screen displayed by the
449 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
450
451 key The key (a single char as a string) to be associated with the command.
452 type The command type, any of the following symbols:
453 todo Entries with a specific TODO keyword, in all agenda files.
454 tags Tags match in all agenda files.
455 todo-tree Sparse tree of specific TODO keyword in *current* file.
456 tags-tree Sparse tree with all tags matches in *current* file.
457 occur-tree Occur sparse tree for current file.
458 match What to search for:
459 - a single keyword for TODO keyword searches
460 - a tags match expression for tags searches
461 - a regular expression for occur searches"
462 :group 'org-agenda
463 :type '(repeat
464 (list (string :tag "Key")
465 (choice :tag "Type"
466 (const :tag "Tags search in all agenda files" tags)
467 (const :tag "TODO keyword search in all agenda files" todo)
468 (const :tag "Tags sparse tree in current buffer" tags-tree)
469 (const :tag "TODO keyword tree in current buffer" todo-tree)
470 (const :tag "Occur tree in current buffer" occur-tree))
471 (string :tag "Match"))))
472
473 (defcustom org-select-timeline-window t
474 "Non-nil means, after creating a timeline, move cursor into Timeline window.
475 When nil, cursor will remain in the current window."
476 :group 'org-agenda
477 :type 'boolean)
478
479 (defcustom org-select-agenda-window t
480 "Non-nil means, after creating an agenda, move cursor into Agenda window.
481 When nil, cursor will remain in the current window."
482 :group 'org-agenda
483 :type 'boolean)
484
485 (defcustom org-fit-agenda-window t
486 "Non-nil means, change window size of agenda to fit content."
487 :group 'org-agenda
488 :type 'boolean)
489
490 (defcustom org-agenda-show-all-dates t
491 "Non-nil means, `org-agenda' shows every day in the selected range.
492 When nil, only the days which actually have entries are shown."
493 :group 'org-agenda
494 :type 'boolean)
495
496 ;; FIXME: First day of month works only for current month because it would
497 ;; require a variable ndays treatment.
498 (defcustom org-agenda-start-on-weekday 1
499 "Non-nil means, start the overview always on the specified weekday.
500 0 Denotes Sunday, 1 denotes Monday etc.
501 When nil, always start on the current day."
502 :group 'org-agenda
503 :type '(choice (const :tag "Today" nil)
504 (const :tag "First day of month" t)
505 (number :tag "Weekday No.")))
506
507 (defcustom org-agenda-ndays 7
508 "Number of days to include in overview display."
509 :group 'org-agenda
510 :type 'number)
511
512 (defcustom org-agenda-include-all-todo t
513 "Non-nil means, the agenda will always contain all TODO entries.
514 When nil, date-less entries will only be shown if `org-agenda' is called
515 with a prefix argument.
516 When non-nil, the TODO entries will be listed at the top of the agenda, before
517 the entries for specific days."
518 :group 'org-agenda
519 :type 'boolean)
520
521 (defcustom org-agenda-include-diary nil
522 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
523 :group 'org-agenda
524 :type 'boolean)
525
526 (defcustom org-calendar-to-agenda-key [?c]
527 "The key to be installed in `calendar-mode-map' for switching to the agenda.
528 The command `org-calendar-goto-agenda' will be bound to this key. The
529 default is the character `c' because then `c' can be used to switch back and
530 forth between agenda and calendar."
531 :group 'org-agenda
532 :type 'sexp)
533
534 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
535 "Sorting structure for the agenda items of a single day.
536 This is a list of symbols which will be used in sequence to determine
537 if an entry should be listed before another entry. The following
538 symbols are recognized:
539
540 time-up Put entries with time-of-day indications first, early first
541 time-down Put entries with time-of-day indications first, late first
542 category-keep Keep the default order of categories, corresponding to the
543 sequence in `org-agenda-files'.
544 category-up Sort alphabetically by category, A-Z.
545 category-down Sort alphabetically by category, Z-A.
546 priority-up Sort numerically by priority, high priority last.
547 priority-down Sort numerically by priority, high priority first.
548
549 The different possibilities will be tried in sequence, and testing stops
550 if one comparison returns a \"not-equal\". For example, the default
551 '(time-up category-keep priority-down)
552 means: Pull out all entries having a specified time of day and sort them,
553 in order to make a time schedule for the current day the first thing in the
554 agenda listing for the day. Of the entries without a time indication, keep
555 the grouped in categories, don't sort the categories, but keep them in
556 the sequence given in `org-agenda-files'. Within each category sort by
557 priority.
558
559 Leaving out `category-keep' would mean that items will be sorted across
560 categories by priority."
561 :group 'org-agenda
562 :type '(repeat
563 (choice
564 (const time-up)
565 (const time-down)
566 (const category-keep)
567 (const category-up)
568 (const category-down)
569 (const priority-up)
570 (const priority-down))))
571
572 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
573 "Format specification for the prefix of items in the agenda buffer.
574 This format works similar to a printf format, with the following meaning:
575
576 %c the category of the item, \"Diary\" for entries from the diary, or
577 as given by the CATEGORY keyword or derived from the file name.
578 %T the first tag of the item.
579 %t the time-of-day specification if one applies to the entry, in the
580 format HH:MM
581 %s Scheduling/Deadline information, a short string
582
583 All specifiers work basically like the standard `%s' of printf, but may
584 contain two additional characters: A question mark just after the `%' and
585 a whitespace/punctuation character just before the final letter.
586
587 If the first character after `%' is a question mark, the entire field
588 will only be included if the corresponding value applies to the
589 current entry. This is useful for fields which should have fixed
590 width when present, but zero width when absent. For example,
591 \"%?-12t\" will result in a 12 character time field if a time of the
592 day is specified, but will completely disappear in entries which do
593 not contain a time.
594
595 If there is punctuation or whitespace character just before the final
596 format letter, this character will be appended to the field value if
597 the value is not empty. For example, the format \"%-12:c\" leads to
598 \"Diary: \" if the category is \"Diary\". If the category were be
599 empty, no additional colon would be interted.
600
601 The default value of this option is \" %-12:c%?-12t% s\", meaning:
602 - Indent the line with two space characters
603 - Give the category in a 12 chars wide field, padded with whitespace on
604 the right (because of `-'). Append a colon if there is a category
605 (because of `:').
606 - If there is a time-of-day, put it into a 12 chars wide field. If no
607 time, don't put in an empty field, just skip it (because of '?').
608 - Finally, put the scheduling information and append a whitespace.
609
610 As another example, if you don't want the time-of-day of entries in
611 the prefix, you could use:
612
613 (setq org-agenda-prefix-format \" %-11:c% s\")
614
615 See also the variables `org-agenda-remove-times-when-in-prefix' and
616 `org-agenda-remove-tags-when-in-prefix'."
617 :type 'string
618 :group 'org-agenda)
619
620 (defcustom org-timeline-prefix-format " % s"
621 "Like `org-agenda-prefix-format', but for the timeline of a single file."
622 :type 'string
623 :group 'org-agenda)
624
625 (defvar org-prefix-format-compiled nil
626 "The compiled version of the most recently used prefix format.
627 Depending on which command was used last, this may be the compiled version
628 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
629
630 (defcustom org-agenda-use-time-grid t
631 "Non-nil means, show a time grid in the agenda schedule.
632 A time grid is a set of lines for specific times (like every two hours between
633 8:00 and 20:00). The items scheduled for a day at specific times are
634 sorted in between these lines.
635 For details about when the grid will be shown, and what it will look like, see
636 the variable `org-agenda-time-grid'."
637 :group 'org-agenda
638 :type 'boolean)
639
640 (defcustom org-agenda-time-grid
641 '((daily today require-timed)
642 "----------------"
643 (800 1000 1200 1400 1600 1800 2000))
644
645 "The settings for time grid for agenda display.
646 This is a list of three items. The first item is again a list. It contains
647 symbols specifying conditions when the grid should be displayed:
648
649 daily if the agenda shows a single day
650 weekly if the agenda shows an entire week
651 today show grid on current date, independent of daily/weekly display
652 require-timed show grid only if at least on item has a time specification
653
654 The second item is a string which will be places behing the grid time.
655
656 The third item is a list of integers, indicating the times that should have
657 a grid line."
658 :group 'org-agenda
659 :type
660 '(list
661 (set :greedy t :tag "Grid Display Options"
662 (const :tag "Show grid in single day agenda display" daily)
663 (const :tag "Show grid in weekly agenda display" weekly)
664 (const :tag "Always show grid for today" today)
665 (const :tag "Show grid only if any timed entries are present"
666 require-timed)
667 (const :tag "Skip grid times already present in an entry"
668 remove-match))
669 (string :tag "Grid String")
670 (repeat :tag "Grid Times" (integer :tag "Time"))))
671
672 (defcustom org-agenda-remove-times-when-in-prefix t
673 "Non-nil means, remove duplicate time specifications in agenda items.
674 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
675 time-of-day specification in a headline or diary entry is extracted and
676 placed into the prefix. If this option is non-nil, the original specification
677 \(a timestamp or -range, or just a plain time(range) specification like
678 11:30-4pm) will be removed for agenda display. This makes the agenda less
679 cluttered.
680 The option can be t or nil. It may also be the symbol `beg', indicating
681 that the time should only be removed what it is located at the beginning of
682 the headline/diary entry."
683 :group 'org-agenda
684 :type '(choice
685 (const :tag "Always" t)
686 (const :tag "Never" nil)
687 (const :tag "When at beginning of entry" beg)))
688
689 (defcustom org-sort-agenda-notime-is-late t
690 "Non-nil means, items without time are considered late.
691 This is only relevant for sorting. When t, items which have no explicit
692 time like 15:30 will be considered as 24:01, i.e. later than any items which
693 do have a time. When nil, the default time is before 0:00. You can use this
694 option to decide if the schedule for today should come before or after timeless
695 agenda entries."
696 :group 'org-agenda
697 :type 'boolean)
698
699 (defcustom org-agenda-remove-tags-when-in-prefix nil
700 "Non-nil means, the tags from copy of headline in agenda.
701 When this is the symbol `prefix', only remove tags when
702 `org-agenda-prefix-format' contains a `%T' specifier."
703 :group 'org-agenda
704 :type '(choice
705 (const :tag "Always" t)
706 (const :tag "Never" nil)
707 (const :tag "When prefix format contains %T" prefix)))
708
709 (defgroup org-structure nil
710 "Options concerning structure editing in Org-mode."
711 :tag "Org Structure"
712 :group 'org)
713
714 (defcustom org-cycle-include-plain-lists nil
715 "Non-nil means, include plain lists into visibility cycling.
716 This means that during cycling, plain list items will *temporarily* be
717 interpreted as outline headlines with a level given by 1000+i where i is the
718 indentation of the bullet. In all other operations, plain list items are
719 not seen as headlines. For example, you cannot assign a TODO keyword to
720 such an item."
721 :group 'org-structure
722 :type 'boolean)
723
724 (defcustom org-cycle-emulate-tab t
725 "Where should `org-cycle' emulate TAB.
726 nil Never
727 white Only in completely white lines
728 t Everywhere except in headlines"
729 :group 'org-structure
730 :type '(choice (const :tag "Never" nil)
731 (const :tag "Only in completely white lines" white)
732 (const :tag "Everywhere except in headlines" t)
733 ))
734
735 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
736 "Hook that is run after `org-cycle' has changed the buffer visibility.
737 The function(s) in this hook must accept a single argument which indicates
738 the new state that was set by the most recent `org-cycle' command. The
739 argument is a symbol. After a global state change, it can have the values
740 `overview', `content', or `all'. After a local state change, it can have
741 the values `folded', `children', or `subtree'."
742 :group 'org-structure
743 :type 'hook)
744
745 (defcustom org-highlight-sparse-tree-matches t
746 "Non-nil means, highlight all matches that define a sparse tree.
747 The highlights will automatically disappear the next time the buffer is
748 changed by an edit command."
749 :group 'org-structure
750 :type 'boolean)
751
752 (defcustom org-show-hierarchy-above t
753 "Non-nil means, show full hierarchy when showing a spot in the tree.
754 Turning this off makes sparse trees more compact, but also less clear."
755 :group 'org-structure
756 :type 'boolean)
757
758 (defcustom org-show-following-heading t
759 "Non-nil means, show heading following match in `org-occur'.
760 When doing an `org-occur' it is useful to show the headline which
761 follows the match, even if they do not match the regexp. This makes it
762 easier to edit directly inside the sparse tree. However, if you use
763 `org-occur' mainly as an overview, the following headlines are
764 unnecessary clutter."
765 :group 'org-structure
766 :type 'boolean)
767
768 (defcustom org-occur-hook '(org-first-headline-recenter)
769 "Hook that is run after `org-occur' has constructed a sparse tree.
770 This can be used to recenter the window to show as much of the structure
771 as possible."
772 :group 'org-structure
773 :type 'hook)
774
775 (defcustom org-level-color-stars-only nil
776 "Non-nil means fontify only the stars in each headline.
777 When nil, the entire headline is fontified.
778 Changing it requires a restart of Emacs to become effective."
779 :group 'org-structure
780 :type 'boolean)
781
782 (defcustom org-adapt-indentation t
783 "Non-nil means, adapt indentation when promoting and demoting.
784 When this is set and the *entire* text in an entry is indented, the
785 indentation is increased by one space in a demotion command, and
786 decreased by one in a promotion command. If any line in the entry
787 body starts at column 0, indentation is not changed at all."
788 :group 'org-structure
789 :type 'boolean)
790
791 (defcustom org-plain-list-ordered-item-terminator t
792 "The character that makes a line with leading number an ordered list item.
793 Valid values are ?. and ?\). To get both terminators, use t. While
794 ?. may look nicer, it creates the danger that a line with leading
795 number may be incorrectly interpreted as an item. ?\) therefore is
796 the safe choice."
797 :group 'org-structure
798 :type '(choice (const :tag "dot like in \"2.\"" ?.)
799 (const :tag "paren like in \"2)\"" ?\))
800 (const :tab "both" t)))
801
802 (defcustom org-auto-renumber-ordered-lists t
803 "Non-nil means, automatically renumber ordered plain lists.
804 Renumbering happens when the sequence have been changed with
805 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
806 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
807 :group 'org-structure
808 :type 'boolean)
809
810 (defcustom org-enable-fixed-width-editor t
811 "Non-nil means, lines starting with \":\" are treated as fixed-width.
812 This currently only means, they are never auto-wrapped.
813 When nil, such lines will be treated like ordinary lines.
814 See also the QUOTE keyword."
815 :group 'org-structure
816 :type 'boolean)
817
818 (defcustom org-archive-location "%s_archive::"
819 "The location where subtrees should be archived.
820 This string consists of two parts, separated by a double-colon.
821
822 The first part is a file name - when omitted, archiving happens in the same
823 file. %s will be replaced by the current file name (without directory part).
824 Archiving to a different file is useful to keep archived entries from
825 contributing to the Org-mode Agenda.
826
827 The part after the double colon is a headline. The archived entries will be
828 filed under that headline. When omitted, the subtrees are simply filed away
829 at the end of the file, as top-level entries.
830
831 Here are a few examples:
832 \"%s_archive::\"
833 If the current file is Projects.org, archive in file
834 Projects.org_archive, as top-level trees. This is the default.
835
836 \"::* Archived Tasks\"
837 Archive in the current file, under the top-level headline
838 \"* Archived Tasks\".
839
840 \"~/org/archive.org::\"
841 Archive in file ~/org/archive.org (absolute path), as top-level trees.
842
843 \"basement::** Finished Tasks\"
844 Archive in file ./basement (relative path), as level 3 trees
845 below the level 2 heading \"** Finished Tasks\".
846
847 You may set this option on a per-file basis by adding to the buffer a
848 line like
849
850 #+ARCHIVE: basement::** Finished Tasks"
851 :group 'org-structure
852 :type 'string)
853
854 (defcustom org-archive-mark-done t
855 "Non-nil means, mark archived entries as DONE."
856 :group 'org-structure
857 :type 'boolean)
858
859 (defcustom org-archive-stamp-time t
860 "Non-nil means, add a time stamp to archived entries.
861 The time stamp will be added directly after the TODO state keyword in the
862 first line, so it is probably best to use this in combinations with
863 `org-archive-mark-done'."
864 :group 'org-structure
865 :type 'boolean)
866
867 (defgroup org-tags nil
868 "Options concerning startup of Org-mode."
869 :tag "Org Tags"
870 :group 'org)
871
872 (defcustom org-tags-column 48
873 "The column to which tags should be indented in a headline.
874 If this number is positive, it specifies the column. If it is negative,
875 it means that the tags should be flushright to that column. For example,
876 -79 works well for a normal 80 character screen."
877 :group 'org-tags
878 :type 'integer)
879
880 (defcustom org-auto-align-tags t
881 "Non-nil means, realign tags after pro/demotion of TODO state change.
882 These operations change the length of a headline and therefore shift
883 the tags around. With this options turned on, after each such operation
884 the tags are again aligned to `org-tags-column'."
885 :group 'org-tags
886 :type 'boolean)
887
888 (defcustom org-use-tag-inheritance t
889 "Non-nil means, tags in levels apply also for sublevels.
890 When nil, only the tags directly given in a specific line apply there.
891 If you turn off this option, you very likely want to turn on the
892 companion option `org-tags-match-list-sublevels'."
893 :group 'org-tags
894 :type 'boolean)
895
896 (defcustom org-tags-match-list-sublevels nil
897 "Non-nil means list also sublevels of headlines matching tag search.
898 Because of tag inheritance (see variable `org-use-tag-inheritance'),
899 the sublevels of a headline matching a tag search often also match
900 the same search. Listing all of them can create very long lists.
901 Setting this variable to nil causes subtrees to be skipped.
902 This option is off by default, because inheritance in on. If you turn
903 inheritance off, you very likely want to turn this option on.
904
905 As a special case, if the tag search is restricted to TODO items, the
906 value of this variable is ignored and sublevels are always checked, to
907 make sure all corresponding TODO items find their way into the list."
908 :group 'org-tags
909 :type 'boolean)
910
911 (defvar org-tags-history nil
912 "History of minibuffer reads for tags.")
913 (defvar org-last-tags-completion-table nil
914 "The last used completion table for tags.")
915
916 (defgroup org-link nil
917 "Options concerning links in Org-mode."
918 :tag "Org Link"
919 :group 'org)
920
921 (defcustom org-tab-follows-link nil
922 "Non-nil means, on links TAB will follow the link.
923 Needs to be set before org.el is loaded."
924 :group 'org-link
925 :type 'boolean)
926
927 (defcustom org-return-follows-link nil
928 "Non-nil means, on links RET will follow the link.
929 Needs to be set before org.el is loaded."
930 :group 'org-link
931 :type 'boolean)
932
933 (defcustom org-link-format "<%s>"
934 "Default format for linkes in the buffer.
935 This is a format string for printf, %s will be replaced by the link text.
936 If you want to make sure that your link is always properly terminated,
937 include angle brackets into this format, like \"<%s>\". Some people also
938 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
939 :group 'org-link
940 :type '(choice
941 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
942 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
943 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
944 (string :tag "Other" :value "<%s>")))
945
946 (defcustom org-allow-space-in-links t
947 "Non-nil means, file names in links may contain space characters.
948 When nil, it becomes possible to put several links into a line.
949 Note that in tables, a link never extends accross fields, so in a table
950 it is always possible to put several links into a line.
951 Changing this variable requires a restart of Emacs to become effective."
952 :group 'org-link
953 :type 'boolean)
954
955 (defcustom org-context-in-file-links t
956 "Non-nil means, file links from `org-store-link' contain context.
957 The line number will be added to the file name with :: as separator and
958 used to find the context when the link is activated by the command
959 `org-open-at-point'.
960 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
961 negates this setting for the duration of the command."
962 :group 'org-link
963 :type 'boolean)
964
965 (defcustom org-keep-stored-link-after-insertion nil
966 "Non-nil means, keep link in list for entire session.
967
968 The command `org-store-link' adds a link pointing to the current
969 location to an internal list. These links accumulate during a session.
970 The command `org-insert-link' can be used to insert links into any
971 Org-mode file (offering completion for all stored links). When this
972 option is nil, every link which has been inserted once using \\[org-insert-link]
973 will be removed from the list, to make completing the unused links
974 more efficient."
975 :group 'org-link
976 :type 'boolean)
977
978 (defcustom org-link-frame-setup
979 '((vm . vm-visit-folder-other-frame)
980 (gnus . gnus-other-frame)
981 (file . find-file-other-window))
982 "Setup the frame configuration for following links.
983 When following a link with Emacs, it may often be useful to display
984 this link in another window or frame. This variable can be used to
985 set this up for the different types of links.
986 For VM, use any of
987 `vm-visit-folder'
988 `vm-visit-folder-other-frame'
989 For Gnus, use any of
990 `gnus'
991 `gnus-other-frame'
992 For FILE, use any of
993 `find-file'
994 `find-file-other-window'
995 `find-file-other-frame'
996 For the calendar, use the variable `calendar-setup'.
997 For BBDB, it is currently only possible to display the matches in
998 another window."
999 :group 'org-link
1000 :type '(list
1001 (cons (const vm)
1002 (choice
1003 (const vm-visit-folder)
1004 (const vm-visit-folder-other-window)
1005 (const vm-visit-folder-other-frame)))
1006 (cons (const gnus)
1007 (choice
1008 (const gnus)
1009 (const gnus-other-frame)))
1010 (cons (const file)
1011 (choice
1012 (const find-file)
1013 (const find-file-other-window)
1014 (const find-file-other-frame)))))
1015
1016 (defcustom org-usenet-links-prefer-google nil
1017 "Non-nil means, `org-store-link' will create web links to Google groups.
1018 When nil, Gnus will be used for such links.
1019 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1020 negates this setting for the duration of the command."
1021 :group 'org-link
1022 :type 'boolean)
1023
1024 (defcustom org-open-non-existing-files nil
1025 "Non-nil means, `org-open-file' will open non-existing file.
1026 When nil, an error will be generated."
1027 :group 'org-link
1028 :type 'boolean)
1029
1030 (defcustom org-confirm-shell-links t
1031 "Non-nil means, ask for confirmation before executing shell links.
1032 The default is true, to keep new users from shooting into their own foot."
1033 :group 'org-link
1034 :type 'boolean)
1035
1036 (defconst org-file-apps-defaults-gnu
1037 '((t . mailcap))
1038 "Default file applications on a UNIX or GNU/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 marked 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 definitions
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 special keywords."
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 formulas."
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 time grids."
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 (defvar last-arg))
1931
1932
1933 ;;; Define the mode
1934
1935 (defvar org-mode-map (copy-keymap outline-mode-map)
1936 "Keymap for Org-mode.")
1937
1938 (defvar org-struct-menu)
1939 (defvar org-org-menu)
1940 (defvar org-tbl-menu)
1941
1942 ;; We use a before-change function to check if a table might need
1943 ;; an update.
1944 (defvar org-table-may-need-update t
1945 "Indicates that a table might need an update.
1946 This variable is set by `org-before-change-function'. `org-table-align'
1947 sets it back to nil.")
1948 (defvar org-mode-hook nil)
1949 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1950 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
1951
1952
1953 ;;;###autoload
1954 (define-derived-mode org-mode outline-mode "Org"
1955 "Outline-based notes management and organizer, alias
1956 \"Carsten's outline-mode for keeping track of everything.\"
1957
1958 Org-mode develops organizational tasks around a NOTES file which
1959 contains information about projects as plain text. Org-mode is
1960 implemented on top of outline-mode, which is ideal to keep the content
1961 of large files well structured. It supports ToDo items, deadlines and
1962 time stamps, which magically appear in the diary listing of the Emacs
1963 calendar. Tables are easily created with a built-in table editor.
1964 Plain text URL-like links connect to websites, emails (VM), Usenet
1965 messages (Gnus), BBDB entries, and any files related to the project.
1966 For printing and sharing of notes, an Org-mode file (or a part of it)
1967 can be exported as a structured ASCII or HTML file.
1968
1969 The following commands are available:
1970
1971 \\{org-mode-map}"
1972 (easy-menu-add org-org-menu)
1973 (easy-menu-add org-tbl-menu)
1974 (org-install-agenda-files-menu)
1975 (setq outline-regexp "\\*+")
1976 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
1977 (setq outline-level 'org-outline-level)
1978 (if org-startup-truncated (setq truncate-lines t))
1979 (org-set-regexps-and-options)
1980 (set (make-local-variable 'font-lock-unfontify-region-function)
1981 'org-unfontify-region)
1982 ;; Activate before-change-function
1983 (set (make-local-variable 'org-table-may-need-update) t)
1984 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1985 (add-hook 'before-change-functions 'org-before-change-function nil
1986 'local)
1987 ;; FIXME: The following does not work because isearch-mode-end-hook
1988 ;; is called *before* the visibility overlays as removed.
1989 ;; There should be another hook then for me to be used.
1990 ;; (make-local-hook 'isearch-mode-end-hook) ;; needed for XEmacs
1991 ;; (add-hook 'isearch-mode-end-hook 'org-show-hierarchy-above nil
1992 ;; 'local)
1993 ;; Paragraphs and auto-filling
1994 (org-set-autofill-regexps)
1995 ;; Settings for Calc embedded mode
1996 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
1997 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
1998 (if (and org-insert-mode-line-in-empty-file
1999 (interactive-p)
2000 (= (point-min) (point-max)))
2001 (insert " -*- mode: org -*-\n\n"))
2002
2003 ;; Get rid of Outline menus, they are not needed
2004 ;; Need to do this here because define-derived-mode sets up
2005 ;; the keymap so late.
2006 (if org-xemacs-p
2007 (progn
2008 (delete-menu-item '("Headings"))
2009 (delete-menu-item '("Show"))
2010 (delete-menu-item '("Hide"))
2011 (set-menubar-dirty-flag))
2012 (define-key org-mode-map [menu-bar headings] 'undefined)
2013 (define-key org-mode-map [menu-bar hide] 'undefined)
2014 (define-key org-mode-map [menu-bar show] 'undefined))
2015
2016 (unless org-inhibit-startup
2017 (if org-startup-with-deadline-check
2018 (call-interactively 'org-check-deadlines)
2019 (cond
2020 ((eq org-startup-folded t)
2021 (org-cycle '(4)))
2022 ((eq org-startup-folded 'content)
2023 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2024 (org-cycle '(4)) (org-cycle '(4))))))))
2025
2026 (defsubst org-current-line (&optional pos)
2027 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2028
2029
2030 ;; FIXME: Do we need to copy?
2031 (defun org-string-props (string &rest properties)
2032 "Add PROPERTIES to string."
2033 (add-text-properties 0 (length string) properties string)
2034 string)
2035
2036 ;;; Font-Lock stuff
2037
2038 (defvar org-mouse-map (make-sparse-keymap))
2039 (define-key org-mouse-map
2040 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2041 (define-key org-mouse-map
2042 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2043 (when org-tab-follows-link
2044 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2045 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2046 (when org-return-follows-link
2047 (define-key org-mouse-map [(return)] 'org-open-at-point)
2048 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2049
2050 (require 'font-lock)
2051
2052 (defconst org-non-link-chars "\t\n\r|<>\000")
2053 (defconst org-link-regexp
2054 (if org-allow-space-in-links
2055 (concat
2056 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2057 (concat
2058 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2059 )
2060 "Regular expression for matching links.")
2061 (defconst org-link-maybe-angles-regexp
2062 (concat "<?\\(" org-link-regexp "\\)>?")
2063 "Matches a link and optionally surrounding angle brackets.")
2064 (defconst org-protected-link-regexp
2065 (concat "\000" org-link-regexp "\000")
2066 "Matches a link and optionally surrounding angle brackets.")
2067
2068 (defconst org-ts-lengths
2069 (cons (length (format-time-string (car org-time-stamp-formats)))
2070 (length (format-time-string (cdr org-time-stamp-formats))))
2071 "This holds the lengths of the two different time formats.")
2072 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2073 "Regular expression for fast time stamp matching.")
2074 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2075 "Regular expression for fast time stamp matching.")
2076 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2077 "Regular expression matching time strings for analysis.")
2078 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2079 "Regular expression matching time stamps, with groups.")
2080 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2081 "Regular expression matching a time stamp range.")
2082 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2083 org-ts-regexp "\\)?")
2084 "Regular expression matching a time stamp or time stamp range.")
2085
2086 (defun org-activate-links (limit)
2087 "Run through the buffer and add overlays to links."
2088 (if (re-search-forward org-link-regexp limit t)
2089 (progn
2090 (add-text-properties (match-beginning 0) (match-end 0)
2091 (list 'mouse-face 'highlight
2092 'keymap org-mouse-map))
2093 t)))
2094
2095 (defun org-activate-dates (limit)
2096 "Run through the buffer and add overlays to dates."
2097 (if (re-search-forward org-tsr-regexp limit t)
2098 (progn
2099 (add-text-properties (match-beginning 0) (match-end 0)
2100 (list 'mouse-face 'highlight
2101 'keymap org-mouse-map))
2102 t)))
2103
2104 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2105 "Matches CamelCase words, possibly with a star before it.")
2106 (defun org-activate-camels (limit)
2107 "Run through the buffer and add overlays to dates."
2108 (if (re-search-forward org-camel-regexp limit t)
2109 (progn
2110 (add-text-properties (match-beginning 0) (match-end 0)
2111 (list 'mouse-face 'highlight
2112 'keymap org-mouse-map))
2113 t)))
2114
2115 (defun org-activate-tags (limit)
2116 (if (re-search-forward "[ \t]\\(:[A-Za-z_:]+:\\)[ \r\n]" limit t)
2117 (progn
2118 (add-text-properties (match-beginning 1) (match-end 1)
2119 (list 'mouse-face 'highlight
2120 'keymap org-mouse-map))
2121 t)))
2122
2123 (defun org-font-lock-level ()
2124 (save-excursion
2125 (org-back-to-heading t)
2126 (- (match-end 0) (match-beginning 0))))
2127
2128 (defun org-outline-level ()
2129 (save-excursion
2130 (looking-at outline-regexp)
2131 (if (match-beginning 1)
2132 (+ (org-get-string-indentation (match-string 1)) 1000)
2133 (- (match-end 0) (match-beginning 0)))))
2134
2135 (defvar org-font-lock-keywords nil)
2136
2137 (defun org-set-font-lock-defaults ()
2138 (let ((org-font-lock-extra-keywords
2139 (list
2140 '(org-activate-links (0 'org-link t))
2141 '(org-activate-dates (0 'org-link t))
2142 '(org-activate-camels (0 'org-link t))
2143 '(org-activate-tags (1 'org-link t))
2144 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2145 '(1 'org-warning t))
2146 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2147 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2148 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2149 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2150 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2151 ;; (3 'bold))
2152 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2153 ;; (3 'italic))
2154 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2155 ;; (3 'underline))
2156 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2157 ; '(1 'org-warning t))
2158 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2159 "\\|" org-quote-string "\\)\\>")
2160 '(1 'org-special-keyword t))
2161 '("^#.*" (0 'font-lock-comment-face t))
2162 (if org-fontify-done-headline
2163 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2164 '(1 'org-done t) '(2 'org-headline-done t))
2165 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2166 '(1 'org-done t)))
2167 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2168 (1 'org-table t))
2169 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2170 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2171 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2172 )))
2173 (set (make-local-variable 'org-font-lock-keywords)
2174 (append
2175 (if org-noutline-p ; FIXME: I am not sure if eval will work
2176 ; on XEmacs if noutline is ever ported
2177 `((eval . (list "^\\(\\*+\\).*"
2178 ,(if org-level-color-stars-only 1 0)
2179 '(nth
2180 (% (- (match-end 1) (match-beginning 1) 1)
2181 org-n-levels)
2182 org-level-faces)
2183 nil t)))
2184 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2185 (,(if org-level-color-stars-only 2 0)
2186 (nth (% (- (match-end 2) (match-beginning 2) 1)
2187 org-n-levels)
2188 org-level-faces)
2189 nil t))))
2190 org-font-lock-extra-keywords))
2191 (set (make-local-variable 'font-lock-defaults)
2192 '(org-font-lock-keywords t nil nil backward-paragraph))
2193 (kill-local-variable 'font-lock-keywords) nil))
2194
2195 (defun org-unfontify-region (beg end &optional maybe_loudly)
2196 "Remove fontification and activation overlays from links."
2197 (font-lock-default-unfontify-region beg end)
2198 (let* ((buffer-undo-list t)
2199 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2200 (inhibit-modification-hooks t)
2201 deactivate-mark buffer-file-name buffer-file-truename)
2202 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2203
2204 ;;; Visibility cycling
2205
2206 (defvar org-cycle-global-status nil)
2207 (defvar org-cycle-subtree-status nil)
2208 (defun org-cycle (&optional arg)
2209 "Visibility cycling for Org-mode.
2210
2211 - When this function is called with a prefix argument, rotate the entire
2212 buffer through 3 states (global cycling)
2213 1. OVERVIEW: Show only top-level headlines.
2214 2. CONTENTS: Show all headlines of all levels, but no body text.
2215 3. SHOW ALL: Show everything.
2216
2217 - When point is at the beginning of a headline, rotate the subtree started
2218 by this line through 3 different states (local cycling)
2219 1. FOLDED: Only the main headline is shown.
2220 2. CHILDREN: The main headline and the direct children are shown.
2221 From this state, you can move to one of the children
2222 and zoom in further.
2223 3. SUBTREE: Show the entire subtree, including body text.
2224
2225 - When there is a numeric prefix, go up to a heading with level ARG, do
2226 a `show-subtree' and return to the previous cursor position. If ARG
2227 is negative, go up that many levels.
2228
2229 - When point is not at the beginning of a headline, execute
2230 `indent-relative', like TAB normally does. See the option
2231 `org-cycle-emulate-tab' for details.
2232
2233 - Special case: if point is the the beginning of the buffer and there is
2234 no headline in line 1, this function will act as if called with prefix arg."
2235 (interactive "P")
2236
2237 (if (or (and (bobp) (not (looking-at outline-regexp)))
2238 (equal arg '(4)))
2239 ;; special case: use global cycling
2240 (setq arg t))
2241
2242 (let ((outline-regexp
2243 (if org-cycle-include-plain-lists
2244 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2245 outline-regexp)))
2246
2247 (cond
2248
2249 ((org-at-table-p 'any)
2250 ;; Enter the table or move to the next field in the table
2251 (or (org-table-recognize-table.el)
2252 (progn
2253 (org-table-justify-field-maybe)
2254 (org-table-next-field))))
2255
2256 ((eq arg t) ;; Global cycling
2257
2258 (cond
2259 ((and (eq last-command this-command)
2260 (eq org-cycle-global-status 'overview))
2261 ;; We just created the overview - now do table of contents
2262 ;; This can be slow in very large buffers, so indicate action
2263 (message "CONTENTS...")
2264 (save-excursion
2265 ;; Visit all headings and show their offspring
2266 (goto-char (point-max))
2267 (catch 'exit
2268 (while (and (progn (condition-case nil
2269 (outline-previous-visible-heading 1)
2270 (error (goto-char (point-min))))
2271 t)
2272 (looking-at outline-regexp))
2273 (show-branches)
2274 (if (bobp) (throw 'exit nil))))
2275 (message "CONTENTS...done"))
2276 (setq org-cycle-global-status 'contents)
2277 (run-hook-with-args 'org-cycle-hook 'contents))
2278
2279 ((and (eq last-command this-command)
2280 (eq org-cycle-global-status 'contents))
2281 ;; We just showed the table of contents - now show everything
2282 (show-all)
2283 (message "SHOW ALL")
2284 (setq org-cycle-global-status 'all)
2285 (run-hook-with-args 'org-cycle-hook 'all))
2286
2287 (t
2288 ;; Default action: go to overview
2289 (hide-sublevels 1)
2290 (message "OVERVIEW")
2291 (setq org-cycle-global-status 'overview)
2292 (run-hook-with-args 'org-cycle-hook 'overview))))
2293
2294 ((integerp arg)
2295 ;; Show-subtree, ARG levels up from here.
2296 (save-excursion
2297 (org-back-to-heading)
2298 (outline-up-heading (if (< arg 0) (- arg)
2299 (- (outline-level) arg)))
2300 (org-show-subtree)))
2301
2302 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2303 ;; At a heading: rotate between three different views
2304 (org-back-to-heading)
2305 (let ((goal-column 0) eoh eol eos)
2306 ;; First, some boundaries
2307 (save-excursion
2308 (org-back-to-heading)
2309 (save-excursion
2310 (beginning-of-line 2)
2311 (while (and (not (eobp)) ;; this is like `next-line'
2312 (get-char-property (1- (point)) 'invisible))
2313 (beginning-of-line 2)) (setq eol (point)))
2314 (outline-end-of-heading) (setq eoh (point))
2315 (org-end-of-subtree t) (setq eos (point))
2316 (outline-next-heading))
2317 ;; Find out what to do next and set `this-command'
2318 (cond
2319 ((= eos eoh)
2320 ;; Nothing is hidden behind this heading
2321 (message "EMPTY ENTRY")
2322 (setq org-cycle-subtree-status nil))
2323 ((>= eol eos)
2324 ;; Entire subtree is hidden in one line: open it
2325 (org-show-entry)
2326 (show-children)
2327 (message "CHILDREN")
2328 (setq org-cycle-subtree-status 'children)
2329 (run-hook-with-args 'org-cycle-hook 'children))
2330 ((and (eq last-command this-command)
2331 (eq org-cycle-subtree-status 'children))
2332 ;; We just showed the children, now show everything.
2333 (org-show-subtree)
2334 (message "SUBTREE")
2335 (setq org-cycle-subtree-status 'subtree)
2336 (run-hook-with-args 'org-cycle-hook 'subtree))
2337 (t
2338 ;; Default action: hide the subtree.
2339 (hide-subtree)
2340 (message "FOLDED")
2341 (setq org-cycle-subtree-status 'folded)
2342 (run-hook-with-args 'org-cycle-hook 'folded)))))
2343
2344 ;; TAB emulation
2345 (buffer-read-only (org-back-to-heading))
2346 ((if (and (eq org-cycle-emulate-tab 'white)
2347 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2348 t
2349 (eq org-cycle-emulate-tab t))
2350 (if (and (looking-at "[ \n\r\t]")
2351 (string-match "^[ \t]*$" (buffer-substring
2352 (point-at-bol) (point))))
2353 (progn
2354 (beginning-of-line 1)
2355 (and (looking-at "[ \t]+") (replace-match ""))))
2356 (indent-relative))
2357
2358 (t (save-excursion
2359 (org-back-to-heading)
2360 (org-cycle))))))
2361
2362 (defun org-optimize-window-after-visibility-change (state)
2363 "Adjust the window after a change in outline visibility.
2364 This function is the default value of the hook `org-cycle-hook'."
2365 (cond
2366 ((eq state 'overview) (org-first-headline-recenter 1))
2367 ((eq state 'content) nil)
2368 ((eq state 'all) nil)
2369 ((eq state 'folded) nil)
2370 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2371 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2372
2373 (defun org-subtree-end-visible-p ()
2374 "Is the end of the current subtree visible?"
2375 (pos-visible-in-window-p
2376 (save-excursion (org-end-of-subtree t) (point))))
2377
2378 (defun org-first-headline-recenter (&optional N)
2379 "Move cursor to the first headline and recenter the headline.
2380 Optional argument N means, put the headline into the Nth line of the window."
2381 (goto-char (point-min))
2382 (when (re-search-forward (concat "^" outline-regexp) nil t)
2383 (beginning-of-line)
2384 (recenter (prefix-numeric-value N))))
2385
2386 (defvar org-goto-window-configuration nil)
2387 (defvar org-goto-marker nil)
2388 (defvar org-goto-map (make-sparse-keymap))
2389 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2390 (while (setq cmd (pop cmds))
2391 (substitute-key-definition cmd cmd org-goto-map global-map)))
2392 (define-key org-goto-map "\C-m" 'org-goto-ret)
2393 (define-key org-goto-map [(left)] 'org-goto-left)
2394 (define-key org-goto-map [(right)] 'org-goto-right)
2395 (define-key org-goto-map [(?q)] 'org-goto-quit)
2396 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2397 (define-key org-goto-map "\C-i" 'org-cycle)
2398 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2399 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2400 (define-key org-goto-map "n" 'outline-next-visible-heading)
2401 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2402 (define-key org-goto-map "f" 'outline-forward-same-level)
2403 (define-key org-goto-map "b" 'outline-backward-same-level)
2404 (define-key org-goto-map "u" 'outline-up-heading)
2405 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2406 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2407 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2408 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2409 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2410 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2411 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2412
2413 (defconst org-goto-help
2414 "Select a location to jump to, press RET
2415 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2416
2417 (defun org-goto ()
2418 "Go to a different location of the document, keeping current visibility.
2419
2420 When you want to go to a different location in a document, the fastest way
2421 is often to fold the entire buffer and then dive into the tree. This
2422 method has the disadvantage, that the previous location will be folded,
2423 which may not be what you want.
2424
2425 This command works around this by showing a copy of the current buffer in
2426 overview mode. You can dive into the tree in that copy, to find the
2427 location you want to reach. When pressing RET, the command returns to the
2428 original buffer in which the visibility is still unchanged. It then jumps
2429 to the new location, making it and the headline hierarchy above it visible."
2430 (interactive)
2431 (let* ((org-goto-start-pos (point))
2432 (selected-point
2433 (org-get-location (current-buffer) org-goto-help)))
2434 (if selected-point
2435 (progn
2436 (goto-char selected-point)
2437 (if (org-invisible-p) (org-show-hierarchy-above)))
2438 (error "Quit"))))
2439
2440 (defun org-get-location (buf help)
2441 "Let the user select a location in the Org-mode buffer BUF.
2442 This function uses a recursive edit. It returns the selected position
2443 or nil."
2444 (let (org-selected-point)
2445 (save-excursion
2446 (save-window-excursion
2447 (delete-other-windows)
2448 (switch-to-buffer (get-buffer-create "*org-goto*"))
2449 (with-output-to-temp-buffer "*Help*"
2450 (princ help))
2451 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2452 (setq buffer-read-only nil)
2453 (erase-buffer)
2454 (insert-buffer-substring buf)
2455 (let ((org-startup-truncated t)
2456 (org-startup-folded t)
2457 (org-startup-with-deadline-check nil))
2458 (org-mode))
2459 (setq buffer-read-only t)
2460 (if (boundp 'org-goto-start-pos)
2461 (goto-char org-goto-start-pos)
2462 (goto-char (point-min)))
2463 (org-beginning-of-line)
2464 (message "Select location and press RET")
2465 ;; now we make sure that during selection, ony very few keys work
2466 ;; and that it is impossible to switch to another window.
2467 (let ((gm (current-global-map))
2468 (overriding-local-map org-goto-map))
2469 (unwind-protect
2470 (progn
2471 (use-global-map org-goto-map)
2472 (recursive-edit))
2473 (use-global-map gm)))))
2474 (kill-buffer "*org-goto*")
2475 org-selected-point))
2476
2477 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2478 (defun org-goto-ret (&optional arg)
2479 "Finish `org-goto' by going to the new location."
2480 (interactive "P")
2481 (setq org-selected-point (point)
2482 current-prefix-arg arg)
2483 (throw 'exit nil))
2484
2485 (defun org-goto-left ()
2486 "Finish `org-goto' by going to the new location."
2487 (interactive)
2488 (if (org-on-heading-p)
2489 (progn
2490 (beginning-of-line 1)
2491 (setq org-selected-point (point)
2492 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2493 (throw 'exit nil))
2494 (error "Not on a heading")))
2495
2496 (defun org-goto-right ()
2497 "Finish `org-goto' by going to the new location."
2498 (interactive)
2499 (if (org-on-heading-p)
2500 (progn
2501 (outline-end-of-subtree)
2502 (or (eobp) (forward-char 1))
2503 (setq org-selected-point (point)
2504 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2505 (throw 'exit nil))
2506 (error "Not on a heading")))
2507
2508 (defun org-goto-quit ()
2509 "Finish `org-goto' without cursor motion."
2510 (interactive)
2511 (setq org-selected-point nil)
2512 (throw 'exit nil))
2513
2514 ;;; Promotion, Demotion, Inserting new headlines
2515
2516 (defvar org-ignore-region nil
2517 "To temporarily disable the active region.")
2518
2519 (defun org-insert-heading (&optional force-heading)
2520 "Insert a new heading or item with same depth at point."
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, interpreting 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 end 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 next 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'.
3313 By 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 determine 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 stamp 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 months. 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 to 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 "T" 'org-agenda-show-tags)
4190 (define-key org-agenda-mode-map "n" 'next-line)
4191 (define-key org-agenda-mode-map "p" 'previous-line)
4192 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4193 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4194 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4195 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4196 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4197 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4198 (eval-after-load "calendar"
4199 '(define-key calendar-mode-map org-calendar-to-agenda-key
4200 'org-calendar-goto-agenda))
4201 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4202 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4203 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4204 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4205 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4206 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4207 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4208 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4209 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4210 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4211 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4212 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4213 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4214 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4215 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4216 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4217 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4218 "Local keymap for agenda entries from Org-mode.")
4219
4220 (define-key org-agenda-keymap
4221 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4222 (define-key org-agenda-keymap
4223 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4224
4225 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4226 '("Agenda"
4227 ("Agenda Files")
4228 "--"
4229 ["Show" org-agenda-show t]
4230 ["Go To (other window)" org-agenda-goto t]
4231 ["Go To (one window)" org-agenda-switch-to t]
4232 ["Follow Mode" org-agenda-follow-mode
4233 :style toggle :selected org-agenda-follow-mode :active t]
4234 "--"
4235 ["Cycle TODO" org-agenda-todo t]
4236 ("Tags"
4237 ["Show all Tags" org-agenda-show-tags t]
4238 ["Set Tags" org-agenda-set-tags t])
4239 ("Reschedule"
4240 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4241 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4242 "--"
4243 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4244 ("Priority"
4245 ["Set Priority" org-agenda-priority t]
4246 ["Increase Priority" org-agenda-priority-up t]
4247 ["Decrease Priority" org-agenda-priority-down t]
4248 ["Show Priority" org-agenda-show-priority t])
4249 "--"
4250 ;; ["New agenda command" org-agenda t]
4251 ["Rebuild buffer" org-agenda-redo t]
4252 "--"
4253 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4254 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4255 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4256 "--"
4257 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4258 :style radio :selected (equal org-agenda-ndays 1)]
4259 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4260 :style radio :selected (equal org-agenda-ndays 7)]
4261 "--"
4262 ["Show Logbook entries" org-agenda-log-mode
4263 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4264 ["Include Diary" org-agenda-toggle-diary
4265 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4266 ["Use Time Grid" org-agenda-toggle-time-grid
4267 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4268 "--"
4269 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4270 ("Calendar Commands"
4271 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4272 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4273 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4274 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4275 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4276 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4277 "--"
4278 ["Quit" org-agenda-quit t]
4279 ["Exit and Release Buffers" org-agenda-exit t]
4280 ))
4281
4282 ;;;###autoload
4283 (defun org-agenda (arg)
4284 "Dispatch agenda commands to collect entries to the agenda buffer.
4285 Prompts for a character to select a command. Any prefix arg will be passed
4286 on to the selected command. The default selections are:
4287
4288 a Call `org-agenda' to display the agenda for the current day or week.
4289 t Call `org-todo-list' to display the global todo list.
4290 T Call `org-todo-list' to display the global todo list, select only
4291 entries with a specific TODO keyword (the user gets a prompt).
4292 m Call `org-tags-view' to display headlines with tags matching
4293 a condition (the user is prompted for the condition).
4294 M Like `m', but select only TODO entries, no ordinary headlines.
4295
4296 More commands can be added by configuring the variable
4297 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4298 searches can be pre-defined in this way.
4299
4300 If the current buffer is in Org-mode and visiting a file, you can also
4301 first press `1' to indicate that the agenda should be temporarily (until the
4302 next use of \\[org-agenda]) restricted to the current file."
4303 (interactive "P")
4304 (catch 'exit
4305 (let ((restrict-ok (and (buffer-file-name) (eq major-mode 'org-mode)))
4306 (custom org-agenda-custom-commands)
4307 c entry key type string)
4308 (put 'org-agenda-files 'org-restrict nil)
4309 (save-window-excursion
4310 (delete-other-windows)
4311 (switch-to-buffer-other-window " *Agenda Commands*")
4312 (erase-buffer)
4313 (insert
4314 "Press key for an agenda command:
4315 --------------------------------
4316 a Agenda for current week or day
4317 t List of all TODO entries T Entries with special TODO kwd
4318 m Match a TAGS query M Like m, but only TODO entries
4319 C Configure your own agenda commands")
4320 (while (setq entry (pop custom))
4321 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4322 (insert (format "\n%-4s%-14s: %s"
4323 key
4324 (cond
4325 ((eq type 'tags) "Tags query")
4326 ((eq type 'todo) "TODO keyword")
4327 ((eq type 'tags-tree) "Tags tree")
4328 ((eq type 'todo-tree) "TODO kwd tree")
4329 ((eq type 'occur-tree) "Occur tree")
4330 (t "???"))
4331 (org-string-props string 'face 'org-link))))
4332 (goto-char (point-min))
4333 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4334 (message "Press key for agenda command%s"
4335 (if restrict-ok ", or [1] to restrict to current file" ""))
4336 (setq c (read-char-exclusive))
4337 (message "")
4338 (when (equal c ?1)
4339 (if restrict-ok
4340 (put 'org-agenda-files 'org-restrict (list (buffer-file-name)))
4341 (error "Cannot restrict agenda to current buffer"))
4342 (message "Press key for agenda command%s"
4343 (if restrict-ok " (restricted to current file)" ""))
4344 (setq c (read-char-exclusive))
4345 (message "")))
4346 (require 'calendar) ; FIXME: can we avoid this for some commands?
4347 ;; For example the todo list should not need it (but does...)
4348 (cond
4349 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4350 ((equal c ?a) (call-interactively 'org-agenda-list))
4351 ((equal c ?t) (call-interactively 'org-todo-list))
4352 ((equal c ?T)
4353 (setq current-prefix-arg (or arg '(4)))
4354 (call-interactively 'org-todo-list))
4355 ((equal c ?m) (call-interactively 'org-tags-view))
4356 ((equal c ?M)
4357 (setq current-prefix-arg (or arg '(4)))
4358 (call-interactively 'org-tags-view))
4359 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4360 (setq type (nth 1 entry) string (nth 2 entry))
4361 (cond
4362 ((eq type 'tags)
4363 (org-tags-view current-prefix-arg string))
4364 ((eq type 'todo)
4365 (org-todo-list string))
4366 ((eq type 'tags-tree)
4367 (org-check-for-org-mode)
4368 (org-tags-sparse-tree current-prefix-arg string))
4369 ((eq type 'todo-tree)
4370 (org-check-for-org-mode)
4371 (org-occur (concat "^" outline-regexp "[ \t]*"
4372 (regexp-quote string) "\\>")))
4373 ((eq type 'occur-tree)
4374 (org-check-for-org-mode)
4375 (org-occur string))
4376 (t (error "Invalid custom agenda command type %s" type))))
4377 (t (error "Invalid key"))))))
4378
4379 (defun org-check-for-org-mode ()
4380 "Make sure current buffer is in org-mode. Error if not."
4381 (or (eq major-mode 'org-mode)
4382 (error "Cannot execute org-mode agenda command on buffer in %s."
4383 major-mode)))
4384
4385 (defun org-fit-agenda-window ()
4386 "Fit the window to the buffer size."
4387 (and org-fit-agenda-window
4388 (fboundp 'fit-window-to-buffer)
4389 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4390 (/ (frame-height) 2))))
4391
4392 (defun org-agenda-files ()
4393 "Get the list of agenda files."
4394 (or (get 'org-agenda-files 'org-restrict)
4395 org-agenda-files))
4396
4397 (defvar org-agenda-markers nil
4398 "List of all currently active markers created by `org-agenda'.")
4399 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4400 "Creation time of the last agenda marker.")
4401
4402 (defun org-agenda-new-marker (&optional pos)
4403 "Return a new agenda marker.
4404 Org-mode keeps a list of these markers and resets them when they are
4405 no longer in use."
4406 (let ((m (copy-marker (or pos (point)))))
4407 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4408 (push m org-agenda-markers)
4409 m))
4410
4411 (defun org-agenda-maybe-reset-markers (&optional force)
4412 "Reset markers created by `org-agenda'. But only if they are old enough."
4413 (if (or force
4414 (> (- (time-to-seconds (current-time))
4415 org-agenda-last-marker-time)
4416 5))
4417 (while org-agenda-markers
4418 (move-marker (pop org-agenda-markers) nil))))
4419
4420 (defvar org-agenda-new-buffers nil
4421 "Buffers created to visit agenda files.")
4422
4423 (defun org-get-agenda-file-buffer (file)
4424 "Get a buffer visiting FILE. If the buffer needs to be created, add
4425 it to the list of buffers which might be released later."
4426 (let ((buf (find-buffer-visiting file)))
4427 (if buf
4428 buf ; just return it
4429 ;; Make a new buffer and remember it
4430 (setq buf (find-file-noselect file))
4431 (if buf (push buf org-agenda-new-buffers))
4432 buf)))
4433
4434 (defun org-release-buffers (blist)
4435 "Release all buffers in list, asking the user for confirmation when needed.
4436 When a buffer is unmodified, it is just killed. When modified, it is saved
4437 \(if the user agrees) and then killed."
4438 (let (buf file)
4439 (while (setq buf (pop blist))
4440 (setq file (buffer-file-name buf))
4441 (when (and (buffer-modified-p buf)
4442 file
4443 (y-or-n-p (format "Save file %s? " file)))
4444 (with-current-buffer buf (save-buffer)))
4445 (kill-buffer buf))))
4446
4447 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4448
4449 (defun org-timeline (&optional include-all keep-modes)
4450 "Show a time-sorted view of the entries in the current org file.
4451 Only entries with a time stamp of today or later will be listed. With
4452 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4453 under the current date.
4454 If the buffer contains an active region, only check the region for
4455 dates."
4456 (interactive "P")
4457 (require 'calendar)
4458 (org-agenda-maybe-reset-markers 'force)
4459 (org-compile-prefix-format org-timeline-prefix-format)
4460 (let* ((dopast t)
4461 (dotodo include-all)
4462 (doclosed org-agenda-show-log)
4463 (org-agenda-keep-modes keep-modes)
4464 (entry (buffer-file-name))
4465 (org-agenda-files (list (buffer-file-name)))
4466 (date (calendar-current-date))
4467 (win (selected-window))
4468 (pos1 (point))
4469 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4470 (end (if (org-region-active-p) (region-end) (point-max)))
4471 (day-numbers (org-get-all-dates beg end 'no-ranges
4472 t doclosed)) ; always include today
4473 (today (time-to-days (current-time)))
4474 (org-respect-restriction t)
4475 (past t)
4476 args
4477 s e rtn d)
4478 (setq org-agenda-redo-command
4479 (list 'progn
4480 (list 'switch-to-buffer-other-window (current-buffer))
4481 (list 'org-timeline (list 'quote include-all) t)))
4482 (if (not dopast)
4483 ;; Remove past dates from the list of dates.
4484 (setq day-numbers (delq nil (mapcar (lambda(x)
4485 (if (>= x today) x nil))
4486 day-numbers))))
4487 (switch-to-buffer-other-window
4488 (get-buffer-create org-agenda-buffer-name))
4489 (setq buffer-read-only nil)
4490 (erase-buffer)
4491 (org-agenda-mode) (setq buffer-read-only nil)
4492 (set (make-local-variable 'org-agenda-type) 'timeline)
4493 (if doclosed (push :closed args))
4494 (push :timestamp args)
4495 (if dotodo (push :todo args))
4496 (while (setq d (pop day-numbers))
4497 (if (and (>= d today)
4498 dopast
4499 past)
4500 (progn
4501 (setq past nil)
4502 (insert (make-string 79 ?-) "\n")))
4503 (setq date (calendar-gregorian-from-absolute d))
4504 (setq s (point))
4505 (setq rtn (apply 'org-agenda-get-day-entries
4506 entry date args))
4507 (if (or rtn (equal d today))
4508 (progn
4509 (insert (calendar-day-name date) " "
4510 (number-to-string (extract-calendar-day date)) " "
4511 (calendar-month-name (extract-calendar-month date)) " "
4512 (number-to-string (extract-calendar-year date)) "\n")
4513 (put-text-property s (1- (point)) 'face
4514 'org-link)
4515 (if (equal d today)
4516 (put-text-property s (1- (point)) 'org-today t))
4517 (insert (org-finalize-agenda-entries rtn) "\n")
4518 (put-text-property s (1- (point)) 'day d))))
4519 (goto-char (point-min))
4520 (setq buffer-read-only t)
4521 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4522 (point-min)))
4523 (when (not org-select-timeline-window)
4524 (select-window win)
4525 (goto-char pos1))))
4526
4527 ;;;###autoload
4528 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4529 "Produce a weekly view from all files in variable `org-agenda-files'.
4530 The view will be for the current week, but from the overview buffer you
4531 will be able to go to other weeks.
4532 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4533 also be shown, under the current date.
4534 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4535 on the days are also shown. See the variable `org-log-done' for how
4536 to turn on logging.
4537 START-DAY defaults to TODAY, or to the most recent match for the weekday
4538 given in `org-agenda-start-on-weekday'.
4539 NDAYS defaults to `org-agenda-ndays'."
4540 (interactive "P")
4541 (org-agenda-maybe-reset-markers 'force)
4542 (org-compile-prefix-format org-agenda-prefix-format)
4543 (require 'calendar)
4544 (let* ((org-agenda-start-on-weekday
4545 (if (or (equal ndays 1)
4546 (and (null ndays) (equal 1 org-agenda-ndays)))
4547 nil org-agenda-start-on-weekday))
4548 (org-agenda-keep-modes keep-modes)
4549 (files (copy-sequence (org-agenda-files)))
4550 (win (selected-window))
4551 (today (time-to-days (current-time)))
4552 (sd (or start-day today))
4553 (start (if (or (null org-agenda-start-on-weekday)
4554 (< org-agenda-ndays 7))
4555 sd
4556 (let* ((nt (calendar-day-of-week
4557 (calendar-gregorian-from-absolute sd)))
4558 (n1 org-agenda-start-on-weekday)
4559 (d (- nt n1)))
4560 (- sd (+ (if (< d 0) 7 0) d)))))
4561 (day-numbers (list start))
4562 (inhibit-redisplay t)
4563 s e rtn rtnall file date d start-pos end-pos todayp nd)
4564 (setq org-agenda-redo-command
4565 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4566 ;; Make the list of days
4567 (setq ndays (or ndays org-agenda-ndays)
4568 nd ndays)
4569 (while (> ndays 1)
4570 (push (1+ (car day-numbers)) day-numbers)
4571 (setq ndays (1- ndays)))
4572 (setq day-numbers (nreverse day-numbers))
4573 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4574 (progn
4575 (delete-other-windows)
4576 (switch-to-buffer-other-window
4577 (get-buffer-create org-agenda-buffer-name))))
4578 (setq buffer-read-only nil)
4579 (erase-buffer)
4580 (org-agenda-mode) (setq buffer-read-only nil)
4581 (set (make-local-variable 'org-agenda-type) 'agenda)
4582 (set (make-local-variable 'starting-day) (car day-numbers))
4583 (set (make-local-variable 'include-all-loc) include-all)
4584 (when (and (or include-all org-agenda-include-all-todo)
4585 (member today day-numbers))
4586 (setq files (org-agenda-files)
4587 rtnall nil)
4588 (while (setq file (pop files))
4589 (catch 'nextfile
4590 (org-check-agenda-file file)
4591 (setq date (calendar-gregorian-from-absolute today)
4592 rtn (org-agenda-get-day-entries
4593 file date :todo))
4594 (setq rtnall (append rtnall rtn))))
4595 (when rtnall
4596 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4597 (add-text-properties (point-min) (1- (point))
4598 (list 'face 'org-link))
4599 (insert (org-finalize-agenda-entries rtnall) "\n")))
4600 (while (setq d (pop day-numbers))
4601 (setq date (calendar-gregorian-from-absolute d)
4602 s (point))
4603 (if (or (setq todayp (= d today))
4604 (and (not start-pos) (= d sd)))
4605 (setq start-pos (point))
4606 (if (and start-pos (not end-pos))
4607 (setq end-pos (point))))
4608 (setq files (org-agenda-files)
4609 rtnall nil)
4610 (while (setq file (pop files))
4611 (catch 'nextfile
4612 (org-check-agenda-file file)
4613 (if org-agenda-show-log
4614 (setq rtn (org-agenda-get-day-entries
4615 file date
4616 :deadline :scheduled :timestamp :closed))
4617 (setq rtn (org-agenda-get-day-entries
4618 file date
4619 :deadline :scheduled :timestamp)))
4620 (setq rtnall (append rtnall rtn))))
4621 (if org-agenda-include-diary
4622 (progn
4623 (require 'diary-lib)
4624 (setq rtn (org-get-entries-from-diary date))
4625 (setq rtnall (append rtnall rtn))))
4626 (if (or rtnall org-agenda-show-all-dates)
4627 (progn
4628 (insert (format "%-9s %2d %s %4d\n"
4629 (calendar-day-name date)
4630 (extract-calendar-day date)
4631 (calendar-month-name (extract-calendar-month date))
4632 (extract-calendar-year date)))
4633 (put-text-property s (1- (point)) 'face
4634 'org-link)
4635 (if rtnall (insert
4636 (org-finalize-agenda-entries
4637 (org-agenda-add-time-grid-maybe
4638 rtnall nd todayp))
4639 "\n"))
4640 (put-text-property s (1- (point)) 'day d))))
4641 (goto-char (point-min))
4642 (setq buffer-read-only t)
4643 (org-fit-agenda-window)
4644 (unless (and (pos-visible-in-window-p (point-min))
4645 (pos-visible-in-window-p (point-max)))
4646 (goto-char (1- (point-max)))
4647 (recenter -1)
4648 (if (not (pos-visible-in-window-p (or start-pos 1)))
4649 (progn
4650 (goto-char (or start-pos 1))
4651 (recenter 1))))
4652 (goto-char (or start-pos 1))
4653 (if (not org-select-agenda-window) (select-window win))
4654 (message "")))
4655
4656 (defvar org-select-this-todo-keyword nil)
4657
4658 ;;;###autoload
4659 (defun org-todo-list (arg &optional keep-modes)
4660 "Show all TODO entries from all agenda file in a single list.
4661 The prefix arg can be used to select a specific TODO keyword and limit
4662 the list to these. When using \\[universal-argument], you will be prompted
4663 for a keyword. A numeric prefix directly selects the Nth keyword in
4664 `org-todo-keywords'."
4665 (interactive "P")
4666 (org-agenda-maybe-reset-markers 'force)
4667 (org-compile-prefix-format org-agenda-prefix-format)
4668 (let* ((org-agenda-keep-modes keep-modes)
4669 (today (time-to-days (current-time)))
4670 (date (calendar-gregorian-from-absolute today))
4671 (win (selected-window))
4672 (kwds org-todo-keywords)
4673 (completion-ignore-case t)
4674 (org-select-this-todo-keyword
4675 (if (stringp arg) arg
4676 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4677 rtn rtnall files file pos)
4678 (when (equal arg '(4))
4679 (setq org-select-this-todo-keyword
4680 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4681 nil t)))
4682 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4683 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4684 (progn
4685 (delete-other-windows)
4686 (switch-to-buffer-other-window
4687 (get-buffer-create org-agenda-buffer-name))))
4688 (setq buffer-read-only nil)
4689 (erase-buffer)
4690 (org-agenda-mode) (setq buffer-read-only nil)
4691 (set (make-local-variable 'org-agenda-type) 'todo)
4692 (set (make-local-variable 'last-arg) arg)
4693 (set (make-local-variable 'org-todo-keywords) kwds)
4694 (set (make-local-variable 'org-agenda-redo-command)
4695 '(org-todo-list (or current-prefix-arg last-arg) t))
4696 (setq files (org-agenda-files)
4697 rtnall nil)
4698 (while (setq file (pop files))
4699 (catch 'nextfile
4700 (org-check-agenda-file file)
4701 (setq rtn (org-agenda-get-day-entries file date :todo))
4702 (setq rtnall (append rtnall rtn))))
4703 (insert "Global list of TODO items of type: ")
4704 (add-text-properties (point-min) (1- (point))
4705 (list 'face 'org-link))
4706 (setq pos (point))
4707 (insert (or org-select-this-todo-keyword "ALL") "\n")
4708 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4709 (setq pos (point))
4710 (insert
4711 "Available with `N r': (0)ALL "
4712 (let ((n 0))
4713 (mapconcat (lambda (x)
4714 (format "(%d)%s" (setq n (1+ n)) x))
4715 org-todo-keywords " "))
4716 "\n")
4717 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4718 (when rtnall
4719 (insert (org-finalize-agenda-entries rtnall) "\n"))
4720 (goto-char (point-min))
4721 (setq buffer-read-only t)
4722 (org-fit-agenda-window)
4723 (if (not org-select-agenda-window) (select-window win))))
4724
4725 (defun org-check-agenda-file (file)
4726 "Make sure FILE exists. If not, ask user what to do."
4727 ;; FIXME: this does not correctly change the menus
4728 ;; Could probably be fixed by explicitly going to the buffer where
4729 ;; the call originated.
4730 (when (not (file-exists-p file))
4731 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4732 file)
4733 (let ((r (downcase (read-char-exclusive))))
4734 (cond
4735 ((equal r ?r)
4736 (org-remove-file file)
4737 (throw 'nextfile t))
4738 (t (error "Abort"))))))
4739
4740 (defun org-agenda-check-type (error &rest types)
4741 "Check if agenda buffer is of allowed type.
4742 If ERROR is non-nil, throw an error, otherwise just return nil."
4743 (if (memq org-agenda-type types)
4744 t
4745 (if error
4746 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
4747 nil)))
4748
4749 (defun org-agenda-quit ()
4750 "Exit agenda by removing the window or the buffer."
4751 (interactive)
4752 (let ((buf (current-buffer)))
4753 (if (not (one-window-p)) (delete-window))
4754 (kill-buffer buf)
4755 (org-agenda-maybe-reset-markers 'force)))
4756
4757 (defun org-agenda-exit ()
4758 "Exit agenda by removing the window or the buffer.
4759 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4760 Org-mode buffers visited directly by the user will not be touched."
4761 (interactive)
4762 (org-release-buffers org-agenda-new-buffers)
4763 (setq org-agenda-new-buffers nil)
4764 (org-agenda-quit))
4765
4766 (defun org-agenda-redo ()
4767 "Rebuild Agenda.
4768 When this is the global TODO list, a prefix argument will be interpreted."
4769 (interactive)
4770 (message "Rebuilding agenda buffer...")
4771 (eval org-agenda-redo-command)
4772 (message "Rebuilding agenda buffer...done"))
4773
4774 (defun org-agenda-goto-today ()
4775 "Go to today."
4776 (interactive)
4777 (org-agenda-check-type t 'timeline 'agenda)
4778 (if (boundp 'starting-day)
4779 (let ((cmd (car org-agenda-redo-command))
4780 (iall (nth 1 org-agenda-redo-command))
4781 (nday (nth 3 org-agenda-redo-command))
4782 (keep (nth 4 org-agenda-redo-command)))
4783 (eval (list cmd iall nil nday keep)))
4784 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4785 (point-min)))))
4786
4787 (defun org-agenda-later (arg)
4788 "Go forward in time by `org-agenda-ndays' days.
4789 With prefix ARG, go forward that many times `org-agenda-ndays'."
4790 (interactive "p")
4791 (org-agenda-check-type t 'agenda)
4792 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4793 (+ starting-day (* arg org-agenda-ndays)) nil t))
4794
4795 (defun org-agenda-earlier (arg)
4796 "Go back in time by `org-agenda-ndays' days.
4797 With prefix ARG, go back that many times `org-agenda-ndays'."
4798 (interactive "p")
4799 (org-agenda-check-type t 'agenda)
4800 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4801 (- starting-day (* arg org-agenda-ndays)) nil t))
4802
4803 (defun org-agenda-week-view ()
4804 "Switch to weekly view for agenda."
4805 (interactive)
4806 (org-agenda-check-type t 'agenda)
4807 (setq org-agenda-ndays 7)
4808 (org-agenda-list include-all-loc
4809 (or (get-text-property (point) 'day)
4810 starting-day)
4811 nil t)
4812 (org-agenda-set-mode-name)
4813 (message "Switched to week view"))
4814
4815 (defun org-agenda-day-view ()
4816 "Switch to daily view for agenda."
4817 (interactive)
4818 (org-agenda-check-type t 'agenda)
4819 (setq org-agenda-ndays 1)
4820 (org-agenda-list include-all-loc
4821 (or (get-text-property (point) 'day)
4822 starting-day)
4823 nil t)
4824 (org-agenda-set-mode-name)
4825 (message "Switched to day view"))
4826
4827 (defun org-agenda-next-date-line (&optional arg)
4828 "Jump to the next line indicating a date in agenda buffer."
4829 (interactive "p")
4830 (org-agenda-check-type t 'agenda 'timeline)
4831 (beginning-of-line 1)
4832 (if (looking-at "^\\S-") (forward-char 1))
4833 (if (not (re-search-forward "^\\S-" nil t arg))
4834 (progn
4835 (backward-char 1)
4836 (error "No next date after this line in this buffer")))
4837 (goto-char (match-beginning 0)))
4838
4839 (defun org-agenda-previous-date-line (&optional arg)
4840 "Jump to the previous line indicating a date in agenda buffer."
4841 (interactive "p")
4842 (org-agenda-check-type t 'agenda 'timeline)
4843 (beginning-of-line 1)
4844 (if (not (re-search-backward "^\\S-" nil t arg))
4845 (error "No previous date before this line in this buffer")))
4846
4847 ;; Initialize the highlight
4848 (defvar org-hl (org-make-overlay 1 1))
4849 (org-overlay-put org-hl 'face 'highlight)
4850
4851 (defun org-highlight (begin end &optional buffer)
4852 "Highlight a region with overlay."
4853 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4854 org-hl begin end (or buffer (current-buffer))))
4855
4856 (defun org-unhighlight ()
4857 "Detach overlay INDEX."
4858 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4859
4860
4861 (defun org-agenda-follow-mode ()
4862 "Toggle follow mode in an agenda buffer."
4863 (interactive)
4864 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4865 (org-agenda-set-mode-name)
4866 (message "Follow mode is %s"
4867 (if org-agenda-follow-mode "on" "off")))
4868
4869 (defun org-agenda-log-mode ()
4870 "Toggle log mode in an agenda buffer."
4871 (interactive)
4872 (org-agenda-check-type t 'agenda 'timeline)
4873 (setq org-agenda-show-log (not org-agenda-show-log))
4874 (org-agenda-set-mode-name)
4875 (org-agenda-redo)
4876 (message "Log mode is %s"
4877 (if org-agenda-show-log "on" "off")))
4878
4879 (defun org-agenda-toggle-diary ()
4880 "Toggle diary inclusion in an agenda buffer."
4881 (interactive)
4882 (org-agenda-check-type t 'agenda)
4883 (setq org-agenda-include-diary (not org-agenda-include-diary))
4884 (org-agenda-redo)
4885 (org-agenda-set-mode-name)
4886 (message "Diary inclusion turned %s"
4887 (if org-agenda-include-diary "on" "off")))
4888
4889 (defun org-agenda-toggle-time-grid ()
4890 "Toggle time grid in an agenda buffer."
4891 (interactive)
4892 (org-agenda-check-type t 'agenda)
4893 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4894 (org-agenda-redo)
4895 (org-agenda-set-mode-name)
4896 (message "Time-grid turned %s"
4897 (if org-agenda-use-time-grid "on" "off")))
4898
4899 (defun org-agenda-set-mode-name ()
4900 "Set the mode name to indicate all the small mode settings."
4901 (setq mode-name
4902 (concat "Org-Agenda"
4903 (if (equal org-agenda-ndays 1) " Day" "")
4904 (if (equal org-agenda-ndays 7) " Week" "")
4905 (if org-agenda-follow-mode " Follow" "")
4906 (if org-agenda-include-diary " Diary" "")
4907 (if org-agenda-use-time-grid " Grid" "")
4908 (if org-agenda-show-log " Log" "")))
4909 (force-mode-line-update))
4910
4911 (defun org-agenda-post-command-hook ()
4912 (and (eolp) (not (bolp)) (backward-char 1))
4913 (if (and org-agenda-follow-mode
4914 (get-text-property (point) 'org-marker))
4915 (org-agenda-show)))
4916
4917 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4918
4919 (defun org-get-entries-from-diary (date)
4920 "Get the (Emacs Calendar) diary entries for DATE."
4921 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4922 (diary-display-hook '(fancy-diary-display))
4923 (list-diary-entries-hook
4924 (cons 'org-diary-default-entry list-diary-entries-hook))
4925 (diary-file-name-prefix-function nil) ; turn this feature off
4926 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4927 entries
4928 (org-disable-agenda-to-diary t))
4929 (save-excursion
4930 (save-window-excursion
4931 (list-diary-entries date 1)))
4932 (if (not (get-buffer fancy-diary-buffer))
4933 (setq entries nil)
4934 (with-current-buffer fancy-diary-buffer
4935 (setq buffer-read-only nil)
4936 (if (= (point-max) 1)
4937 ;; No entries
4938 (setq entries nil)
4939 ;; Omit the date and other unnecessary stuff
4940 (org-agenda-cleanup-fancy-diary)
4941 ;; Add prefix to each line and extend the text properties
4942 (if (= (point-max) 1)
4943 (setq entries nil)
4944 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4945 (set-buffer-modified-p nil)
4946 (kill-buffer fancy-diary-buffer)))
4947 (when entries
4948 (setq entries (org-split-string entries "\n"))
4949 (setq entries
4950 (mapcar
4951 (lambda (x)
4952 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
4953 ;; Extend the text properties to the beginning of the line
4954 (add-text-properties
4955 0 (length x)
4956 (text-properties-at (1- (length x)) x)
4957 x)
4958 x)
4959 entries)))))
4960
4961 (defun org-agenda-cleanup-fancy-diary ()
4962 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
4963 This gets rid of the date, the underline under the date, and
4964 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4965 date. It also removes lines that contain only whitespace."
4966 (goto-char (point-min))
4967 (if (looking-at ".*?:[ \t]*")
4968 (progn
4969 (replace-match "")
4970 (re-search-forward "\n=+$" nil t)
4971 (replace-match "")
4972 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4973 (re-search-forward "\n=+$" nil t)
4974 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4975 (goto-char (point-min))
4976 (while (re-search-forward "^ +\n" nil t)
4977 (replace-match ""))
4978 (goto-char (point-min))
4979 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4980 (replace-match "")))
4981
4982 ;; Make sure entries from the diary have the right text properties.
4983 (eval-after-load "diary-lib"
4984 '(if (boundp 'diary-modify-entry-list-string-function)
4985 ;; We can rely on the hook, nothing to do
4986 nil
4987 ;; Hook not avaiable, must use advice to make this work
4988 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4989 "Make the position visible."
4990 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4991 (stringp string)
4992 (buffer-file-name))
4993 (setq string (org-modify-diary-entry-string string))))))
4994
4995 (defun org-modify-diary-entry-string (string)
4996 "Add text properties to string, allowing org-mode to act on it."
4997 (add-text-properties
4998 0 (length string)
4999 (list 'mouse-face 'highlight
5000 'keymap org-agenda-keymap
5001 'help-echo
5002 (format
5003 "mouse-2 or RET jump to diary file %s"
5004 (abbreviate-file-name (buffer-file-name)))
5005 'org-agenda-diary-link t
5006 'org-marker (org-agenda-new-marker (point-at-bol)))
5007 string)
5008 string)
5009
5010 (defun org-diary-default-entry ()
5011 "Add a dummy entry to the diary.
5012 Needed to avoid empty dates which mess up holiday display."
5013 ;; Catch the error if dealing with the new add-to-diary-alist
5014 (when org-disable-agenda-to-diary
5015 (condition-case nil
5016 (add-to-diary-list original-date "Org-mode dummy" "")
5017 (error
5018 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5019
5020 (defun org-cycle-agenda-files ()
5021 "Cycle through the files in `org-agenda-files'.
5022 If the current buffer visits an agenda file, find the next one in the list.
5023 If the current buffer does not, find the first agenda file."
5024 (interactive)
5025 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5026 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
5027 file)
5028 (unless files (error "No agenda files"))
5029 (catch 'exit
5030 (while (setq file (pop files))
5031 (if (equal (file-truename file) tcf)
5032 (when (car files)
5033 (find-file (car files))
5034 (throw 'exit t))))
5035 (find-file (car org-agenda-files)))))
5036
5037 (defun org-agenda-file-to-end (&optional file)
5038 "Move/add the current file to the end of the agenda file list.
5039 If the file is not present in the list, it is appended to the list. If it is
5040 present, it is moved there."
5041 (interactive)
5042 (org-agenda-file-to-front 'to-end file))
5043
5044 (defun org-agenda-file-to-front (&optional to-end file)
5045 "Move/add the current file to the top of the agenda file list.
5046 If the file is not present in the list, it is added to the front. If it is
5047 present, it is moved there. With optional argument TO-END, add/move to the
5048 end of the list."
5049 (interactive "P")
5050 (let ((file-alist (mapcar (lambda (x)
5051 (cons (file-truename x) x))
5052 org-agenda-files))
5053 (ctf (file-truename (buffer-file-name)))
5054 x had)
5055 (setq x (assoc ctf file-alist) had x)
5056
5057 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
5058 (if to-end
5059 (setq file-alist (append (delq x file-alist) (list x)))
5060 (setq file-alist (cons x (delq x file-alist))))
5061 (setq org-agenda-files (mapcar 'cdr file-alist))
5062 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5063 (customize-save-variable 'org-agenda-files org-agenda-files))
5064 (org-install-agenda-files-menu)
5065 (message "File %s to %s of agenda file list"
5066 (if had "moved" "added") (if to-end "end" "front"))))
5067
5068 (defun org-remove-file (&optional file)
5069 "Remove current file from the list of files in variable `org-agenda-files'.
5070 These are the files which are being checked for agenda entries.
5071 Optional argument FILE means, use this file instead of the current."
5072 (interactive)
5073 (let* ((file (or file (buffer-file-name)))
5074 (true-file (file-truename file))
5075 (afile (abbreviate-file-name file))
5076 (files (delq nil (mapcar
5077 (lambda (x)
5078 (if (equal true-file
5079 (file-truename x))
5080 nil x))
5081 org-agenda-files))))
5082 (if (not (= (length files) (length org-agenda-files)))
5083 (progn
5084 (setq org-agenda-files files)
5085 (customize-save-variable 'org-agenda-files org-agenda-files)
5086 (org-install-agenda-files-menu)
5087 (message "Removed file: %s" afile))
5088 (message "File was not in list: %s" afile))))
5089
5090 (defun org-file-menu-entry (file)
5091 (vector file (list 'find-file file) t))
5092 ;; FIXME: Maybe we removed a buffer visited through the menu from
5093 ;; org-agenda-new-buffers, so that the buffer will not be removed
5094 ;; when exiting the agenda????
5095
5096 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5097 "Return a list of all relevant day numbers from BEG to END buffer positions.
5098 If NO-RANGES is non-nil, include only the start and end dates of a range,
5099 not every single day in the range. If FORCE-TODAY is non-nil, make
5100 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5101 inactive time stamps (those in square brackets) are included."
5102 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5103 dates date day day1 day2 ts1 ts2)
5104 (if force-today
5105 (setq dates (list (time-to-days (current-time)))))
5106 (save-excursion
5107 (goto-char beg)
5108 (while (re-search-forward re end t)
5109 (setq day (time-to-days (org-time-string-to-time
5110 (substring (match-string 1) 0 10))))
5111 (or (memq day dates) (push day dates)))
5112 (unless no-ranges
5113 (goto-char beg)
5114 (while (re-search-forward org-tr-regexp end t)
5115 (setq ts1 (substring (match-string 1) 0 10)
5116 ts2 (substring (match-string 2) 0 10)
5117 day1 (time-to-days (org-time-string-to-time ts1))
5118 day2 (time-to-days (org-time-string-to-time ts2)))
5119 (while (< (setq day1 (1+ day1)) day2)
5120 (or (memq day1 dates) (push day1 dates)))))
5121 (sort dates '<))))
5122
5123 ;;;###autoload
5124 (defun org-diary (&rest args)
5125 "Return diary information from org-files.
5126 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5127 It accesses org files and extracts information from those files to be
5128 listed in the diary. The function accepts arguments specifying what
5129 items should be listed. The following arguments are allowed:
5130
5131 :timestamp List the headlines of items containing a date stamp or
5132 date range matching the selected date. Deadlines will
5133 also be listed, on the expiration day.
5134
5135 :deadline List any deadlines past due, or due within
5136 `org-deadline-warning-days'. The listing occurs only
5137 in the diary for *today*, not at any other date. If
5138 an entry is marked DONE, it is no longer listed.
5139
5140 :scheduled List all items which are scheduled for the given date.
5141 The diary for *today* also contains items which were
5142 scheduled earlier and are not yet marked DONE.
5143
5144 :todo List all TODO items from the org-file. This may be a
5145 long list - so this is not turned on by default.
5146 Like deadlines, these entries only show up in the
5147 diary for *today*, not at any other date.
5148
5149 The call in the diary file should look like this:
5150
5151 &%%(org-diary) ~/path/to/some/orgfile.org
5152
5153 Use a separate line for each org file to check. Or, if you omit the file name,
5154 all files listed in `org-agenda-files' will be checked automatically:
5155
5156 &%%(org-diary)
5157
5158 If you don't give any arguments (as in the example above), the default
5159 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5160 also be written as
5161
5162 &%%(org-diary :deadline :timestamp :scheduled)
5163
5164 The function expects the lisp variables `entry' and `date' to be provided
5165 by the caller, because this is how the calendar works. Don't use this
5166 function from a program - use `org-agenda-get-day-entries' instead."
5167 (org-agenda-maybe-reset-markers)
5168 (org-compile-prefix-format org-agenda-prefix-format)
5169 (setq args (or args '(:deadline :scheduled :timestamp)))
5170 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5171 (list entry)
5172 org-agenda-files))
5173 file rtn results)
5174 ;; If this is called during org-agenda, don't return any entries to
5175 ;; the calendar. Org Agenda will list these entries itself.
5176 (if org-disable-agenda-to-diary (setq files nil))
5177 (while (setq file (pop files))
5178 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5179 (setq results (append results rtn)))
5180 (if results
5181 (concat (org-finalize-agenda-entries results) "\n"))))
5182 (defvar org-category-table nil)
5183 (defun org-get-category-table ()
5184 "Get the table of categories and positions in current buffer."
5185 (let (tbl)
5186 (save-excursion
5187 (goto-char (point-min))
5188 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5189 (push (cons (point) (org-trim (match-string 2))) tbl)))
5190 tbl))
5191 (defun org-get-category (&optional pos)
5192 "Get the category applying to position POS."
5193 (if (not org-category-table)
5194 (cond
5195 ((null org-category)
5196 (setq org-category
5197 (if (buffer-file-name)
5198 (file-name-sans-extension
5199 (file-name-nondirectory (buffer-file-name)))
5200 "???")))
5201 ((symbolp org-category) (symbol-name org-category))
5202 (t org-category))
5203 (let ((tbl org-category-table)
5204 (pos (or pos (point))))
5205 (while (and tbl (> (caar tbl) pos))
5206 (pop tbl))
5207 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5208 org-category-table))))))
5209
5210 (defun org-agenda-get-day-entries (file date &rest args)
5211 "Does the work for `org-diary' and `org-agenda'.
5212 FILE is the path to a file to be checked for entries. DATE is date like
5213 the one returned by `calendar-current-date'. ARGS are symbols indicating
5214 which kind of entries should be extracted. For details about these, see
5215 the documentation of `org-diary'."
5216 (setq args (or args '(:deadline :scheduled :timestamp)))
5217 (let* ((org-startup-with-deadline-check nil)
5218 (org-startup-folded nil)
5219 (buffer (if (file-exists-p file)
5220 (org-get-agenda-file-buffer file)
5221 (error "No such file %s" file)))
5222 arg results rtn)
5223 (if (not buffer)
5224 ;; If file does not exist, make sure an error message ends up in diary
5225 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5226 (with-current-buffer buffer
5227 (unless (eq major-mode 'org-mode)
5228 (error "Agenda file %s is not in `org-mode'" file))
5229 (setq org-category-table (org-get-category-table))
5230 (let ((case-fold-search nil))
5231 (save-excursion
5232 (save-restriction
5233 (if org-respect-restriction
5234 (if (org-region-active-p)
5235 ;; Respect a region to restrict search
5236 (narrow-to-region (region-beginning) (region-end)))
5237 ;; If we work for the calendar or many files,
5238 ;; get rid of any restriction
5239 (widen))
5240 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5241 (while (setq arg (pop args))
5242 (cond
5243 ((and (eq arg :todo)
5244 (equal date (calendar-current-date)))
5245 (setq rtn (org-agenda-get-todos))
5246 (setq results (append results rtn)))
5247 ((eq arg :timestamp)
5248 (setq rtn (org-agenda-get-blocks))
5249 (setq results (append results rtn))
5250 (setq rtn (org-agenda-get-timestamps))
5251 (setq results (append results rtn)))
5252 ((eq arg :scheduled)
5253 (setq rtn (org-agenda-get-scheduled))
5254 (setq results (append results rtn)))
5255 ((eq arg :closed)
5256 (setq rtn (org-agenda-get-closed))
5257 (setq results (append results rtn)))
5258 ((and (eq arg :deadline)
5259 (equal date (calendar-current-date)))
5260 (setq rtn (org-agenda-get-deadlines))
5261 (setq results (append results rtn))))))))
5262 results))))
5263
5264 (defun org-entry-is-done-p ()
5265 "Is the current entry marked DONE?"
5266 (save-excursion
5267 (and (re-search-backward "[\r\n]\\*" nil t)
5268 (looking-at org-nl-done-regexp))))
5269
5270 (defun org-at-date-range-p ()
5271 "Is the cursor inside a date range?"
5272 (interactive)
5273 (save-excursion
5274 (catch 'exit
5275 (let ((pos (point)))
5276 (skip-chars-backward "^<\r\n")
5277 (skip-chars-backward "<")
5278 (and (looking-at org-tr-regexp)
5279 (>= (match-end 0) pos)
5280 (throw 'exit t))
5281 (skip-chars-backward "^<\r\n")
5282 (skip-chars-backward "<")
5283 (and (looking-at org-tr-regexp)
5284 (>= (match-end 0) pos)
5285 (throw 'exit t)))
5286 nil)))
5287
5288 (defun org-get-tags-at (&optional pos)
5289 "Get a list of all headline targs applicable at POS.
5290 POS defaults to point. If tags are inherited, the list contains
5291 the targets in the same sequence as the headlines appear, i.e.
5292 the tags of the current headline come last."
5293 (interactive)
5294 (let (tags)
5295 (save-excursion
5296 (goto-char (or pos (point)))
5297 (save-match-data
5298 (org-back-to-heading t)
5299 (condition-case nil
5300 (while t
5301 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
5302 (setq tags (append (org-split-string (match-string 1) ":") tags)))
5303 (or org-use-tag-inheritance (error ""))
5304 (org-up-heading-all 1))
5305 (error nil))))
5306 (message "%s" tags)
5307 tags))
5308
5309 (defun org-agenda-get-todos ()
5310 "Return the TODO information for agenda display."
5311 (let* ((props (list 'face nil
5312 'done-face 'org-done
5313 'mouse-face 'highlight
5314 'keymap org-agenda-keymap
5315 'help-echo
5316 (format "mouse-2 or RET jump to org file %s"
5317 (abbreviate-file-name (buffer-file-name)))))
5318 (regexp (concat "[\n\r]\\*+ *\\("
5319 (if org-select-this-todo-keyword
5320 (concat "\\<\\(" org-select-this-todo-keyword
5321 "\\)\\>")
5322 org-not-done-regexp)
5323 "[^\n\r]*\\)"))
5324 marker priority category tags
5325 ee txt)
5326 (goto-char (point-min))
5327 (while (re-search-forward regexp nil t)
5328 (goto-char (match-beginning 1))
5329 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5330 category (org-get-category)
5331 tags (org-get-tags-at (point))
5332 txt (org-format-agenda-item "" (match-string 1) category tags)
5333 priority
5334 (+ (org-get-priority txt)
5335 (if org-todo-kwd-priority-p
5336 (- org-todo-kwd-max-priority -2
5337 (length
5338 (member (match-string 2) org-todo-keywords)))
5339 1)))
5340 (add-text-properties
5341 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5342 'priority priority 'category category)
5343 props)
5344 txt)
5345 (push txt ee)
5346 (goto-char (match-end 1)))
5347 (nreverse ee)))
5348
5349 (defconst org-agenda-no-heading-message
5350 "No heading for this item in buffer or region.")
5351
5352 (defun org-agenda-get-timestamps ()
5353 "Return the date stamp information for agenda display."
5354 (let* ((props (list 'face nil
5355 'mouse-face 'highlight
5356 'keymap org-agenda-keymap
5357 'help-echo
5358 (format "mouse-2 or RET jump to org file %s"
5359 (abbreviate-file-name (buffer-file-name)))))
5360 (regexp (regexp-quote
5361 (substring
5362 (format-time-string
5363 (car org-time-stamp-formats)
5364 (apply 'encode-time ; DATE bound by calendar
5365 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5366 0 11)))
5367 marker hdmarker deadlinep scheduledp donep tmp priority category
5368 ee txt timestr tags)
5369 (goto-char (point-min))
5370 (while (re-search-forward regexp nil t)
5371 (if (not (save-match-data (org-at-date-range-p)))
5372 (progn
5373 (setq marker (org-agenda-new-marker (match-beginning 0))
5374 category (org-get-category (match-beginning 0))
5375 tmp (buffer-substring (max (point-min)
5376 (- (match-beginning 0)
5377 org-ds-keyword-length))
5378 (match-beginning 0))
5379 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5380 deadlinep (string-match org-deadline-regexp tmp)
5381 scheduledp (string-match org-scheduled-regexp tmp)
5382 donep (org-entry-is-done-p))
5383 (if (string-match ">" timestr)
5384 ;; substring should only run to end of time stamp
5385 (setq timestr (substring timestr 0 (match-end 0))))
5386 (save-excursion
5387 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5388 (progn
5389 (goto-char (match-end 1))
5390 (setq hdmarker (org-agenda-new-marker)
5391 tags (org-get-tags-at))
5392 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5393 (setq txt (org-format-agenda-item
5394 (format "%s%s"
5395 (if deadlinep "Deadline: " "")
5396 (if scheduledp "Scheduled: " ""))
5397 (match-string 1) category tags timestr)))
5398 (setq txt org-agenda-no-heading-message))
5399 (setq priority (org-get-priority txt))
5400 (add-text-properties
5401 0 (length txt) (append (list 'org-marker marker
5402 'org-hd-marker hdmarker) props)
5403 txt)
5404 (if deadlinep
5405 (add-text-properties
5406 0 (length txt)
5407 (list 'face
5408 (if donep 'org-done 'org-warning)
5409 'undone-face 'org-warning
5410 'done-face 'org-done
5411 'category category
5412 'priority (+ 100 priority))
5413 txt)
5414 (if scheduledp
5415 (add-text-properties
5416 0 (length txt)
5417 (list 'face 'org-scheduled-today
5418 'undone-face 'org-scheduled-today
5419 'done-face 'org-done
5420 'category category
5421 priority (+ 99 priority))
5422 txt)
5423 (add-text-properties
5424 0 (length txt)
5425 (list 'priority priority 'category category) txt)))
5426 (push txt ee))
5427 (outline-next-heading))))
5428 (nreverse ee)))
5429
5430 (defun org-agenda-get-closed ()
5431 "Return the logged TODO entries for agenda display."
5432 (let* ((props (list 'mouse-face 'highlight
5433 'keymap org-agenda-keymap
5434 'help-echo
5435 (format "mouse-2 or RET jump to org file %s"
5436 (abbreviate-file-name (buffer-file-name)))))
5437 (regexp (concat
5438 "\\<" org-closed-string " *\\["
5439 (regexp-quote
5440 (substring
5441 (format-time-string
5442 (car org-time-stamp-formats)
5443 (apply 'encode-time ; DATE bound by calendar
5444 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5445 1 11))))
5446 marker hdmarker priority category tags
5447 ee txt timestr)
5448 (goto-char (point-min))
5449 (while (re-search-forward regexp nil t)
5450 (if (not (save-match-data (org-at-date-range-p)))
5451 (progn
5452 (setq marker (org-agenda-new-marker (match-beginning 0))
5453 category (org-get-category (match-beginning 0))
5454 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5455 ;; donep (org-entry-is-done-p)
5456 )
5457 (if (string-match "\\]" timestr)
5458 ;; substring should only run to end of time stamp
5459 (setq timestr (substring timestr 0 (match-end 0))))
5460 (save-excursion
5461 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5462 (progn
5463 (goto-char (match-end 1))
5464 (setq hdmarker (org-agenda-new-marker)
5465 tags (org-get-tags-at))
5466 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5467 (setq txt (org-format-agenda-item
5468 "Closed: "
5469 (match-string 1) category tags timestr)))
5470 (setq txt org-agenda-no-heading-message))
5471 (setq priority 100000)
5472 (add-text-properties
5473 0 (length txt) (append (list 'org-marker marker
5474 'org-hd-marker hdmarker
5475 'face 'org-done
5476 'priority priority
5477 'category category
5478 'undone-face 'org-warning
5479 'done-face 'org-done) props)
5480 txt)
5481 (push txt ee))
5482 (outline-next-heading))))
5483 (nreverse ee)))
5484
5485 (defun org-agenda-get-deadlines ()
5486 "Return the deadline information for agenda display."
5487 (let* ((wdays org-deadline-warning-days)
5488 (props (list 'mouse-face 'highlight
5489 'keymap org-agenda-keymap
5490 'help-echo
5491 (format "mouse-2 or RET jump to org file %s"
5492 (abbreviate-file-name (buffer-file-name)))))
5493 (regexp org-deadline-time-regexp)
5494 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5495 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5496 d2 diff pos pos1 category tags
5497 ee txt head)
5498 (goto-char (point-min))
5499 (while (re-search-forward regexp nil t)
5500 (setq pos (1- (match-beginning 1))
5501 d2 (time-to-days
5502 (org-time-string-to-time (match-string 1)))
5503 diff (- d2 d1))
5504 ;; When to show a deadline in the calendar:
5505 ;; If the expiration is within wdays warning time.
5506 ;; Past-due deadlines are only shown on the current date
5507 (if (and (< diff wdays) todayp (not (= diff 0)))
5508 (save-excursion
5509 (setq category (org-get-category))
5510 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5511 (progn
5512 (goto-char (match-end 0))
5513 (setq pos1 (match-end 1))
5514 (setq tags (org-get-tags-at pos1))
5515 (setq head (buffer-substring-no-properties
5516 (point)
5517 (progn (skip-chars-forward "^\r\n")
5518 (point))))
5519 (if (string-match org-looking-at-done-regexp head)
5520 (setq txt nil)
5521 (setq txt (org-format-agenda-item
5522 (format "In %3d d.: " diff) head category tags))))
5523 (setq txt org-agenda-no-heading-message))
5524 (when txt
5525 (add-text-properties
5526 0 (length txt)
5527 (append
5528 (list 'org-marker (org-agenda-new-marker pos)
5529 'org-hd-marker (org-agenda-new-marker pos1)
5530 'priority (+ (- 10 diff) (org-get-priority txt))
5531 'category category
5532 'face (cond ((<= diff 0) 'org-warning)
5533 ((<= diff 5) 'org-scheduled-previously)
5534 (t nil))
5535 'undone-face (cond
5536 ((<= diff 0) 'org-warning)
5537 ((<= diff 5) 'org-scheduled-previously)
5538 (t nil))
5539 'done-face 'org-done)
5540 props)
5541 txt)
5542 (push txt ee)))))
5543 ee))
5544
5545 (defun org-agenda-get-scheduled ()
5546 "Return the scheduled information for agenda display."
5547 (let* ((props (list 'face 'org-scheduled-previously
5548 'undone-face 'org-scheduled-previously
5549 'done-face 'org-done
5550 'mouse-face 'highlight
5551 'keymap org-agenda-keymap
5552 'help-echo
5553 (format "mouse-2 or RET jump to org file %s"
5554 (abbreviate-file-name (buffer-file-name)))))
5555 (regexp org-scheduled-time-regexp)
5556 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5557 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5558 d2 diff pos pos1 category tags
5559 ee txt head)
5560 (goto-char (point-min))
5561 (while (re-search-forward regexp nil t)
5562 (setq pos (1- (match-beginning 1))
5563 d2 (time-to-days
5564 (org-time-string-to-time (match-string 1)))
5565 diff (- d2 d1))
5566 ;; When to show a scheduled item in the calendar:
5567 ;; If it is on or past the date.
5568 (if (and (< diff 0) todayp)
5569 (save-excursion
5570 (setq category (org-get-category))
5571 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5572 (progn
5573 (goto-char (match-end 0))
5574 (setq pos1 (match-end 1))
5575 (setq tags (org-get-tags-at))
5576 (setq head (buffer-substring-no-properties
5577 (point)
5578 (progn (skip-chars-forward "^\r\n") (point))))
5579 (if (string-match org-looking-at-done-regexp head)
5580 (setq txt nil)
5581 (setq txt (org-format-agenda-item
5582 (format "Sched.%2dx: " (- 1 diff)) head
5583 category tags))))
5584 (setq txt org-agenda-no-heading-message))
5585 (when txt
5586 (add-text-properties
5587 0 (length txt)
5588 (append (list 'org-marker (org-agenda-new-marker pos)
5589 'org-hd-marker (org-agenda-new-marker pos1)
5590 'priority (+ (- 5 diff) (org-get-priority txt))
5591 'category category)
5592 props) txt)
5593 (push txt ee)))))
5594 ee))
5595
5596 (defun org-agenda-get-blocks ()
5597 "Return the date-range information for agenda display."
5598 (let* ((props (list 'face nil
5599 'mouse-face 'highlight
5600 'keymap org-agenda-keymap
5601 'help-echo
5602 (format "mouse-2 or RET jump to org file %s"
5603 (abbreviate-file-name (buffer-file-name)))))
5604 (regexp org-tr-regexp)
5605 (d0 (calendar-absolute-from-gregorian date))
5606 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
5607 (goto-char (point-min))
5608 (while (re-search-forward regexp nil t)
5609 (setq timestr (match-string 0)
5610 s1 (match-string 1)
5611 s2 (match-string 2)
5612 d1 (time-to-days (org-time-string-to-time s1))
5613 d2 (time-to-days (org-time-string-to-time s2)))
5614 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5615 ;; Only allow days between the limits, because the normal
5616 ;; date stamps will catch the limits.
5617 (save-excursion
5618 (setq marker (org-agenda-new-marker (point)))
5619 (setq category (org-get-category))
5620 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5621 (progn
5622 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5623 (goto-char (match-end 1))
5624 (setq tags (org-get-tags-at))
5625 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5626 (setq txt (org-format-agenda-item
5627 (format (if (= d1 d2) "" "(%d/%d): ")
5628 (1+ (- d0 d1)) (1+ (- d2 d1)))
5629 (match-string 1) category tags
5630 (if (= d0 d1) timestr))))
5631 (setq txt org-agenda-no-heading-message))
5632 (add-text-properties
5633 0 (length txt) (append (list 'org-marker marker
5634 'org-hd-marker hdmarker
5635 'priority (org-get-priority txt)
5636 'category category)
5637 props)
5638 txt)
5639 (push txt ee)))
5640 (outline-next-heading))
5641 ;; Sort the entries by expiration date.
5642 (nreverse ee)))
5643
5644 (defconst org-plain-time-of-day-regexp
5645 (concat
5646 "\\(\\<[012]?[0-9]"
5647 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5648 "\\(--?"
5649 "\\(\\<[012]?[0-9]"
5650 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5651 "\\)?")
5652 "Regular expression to match a plain time or time range.
5653 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5654 groups carry important information:
5655 0 the full match
5656 1 the first time, range or not
5657 8 the second time, if it is a range.")
5658
5659 (defconst org-stamp-time-of-day-regexp
5660 (concat
5661 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5662 "\\([012][0-9]:[0-5][0-9]\\)>"
5663 "\\(--?"
5664 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5665 "Regular expression to match a timestamp time or time range.
5666 After a match, the following groups carry important information:
5667 0 the full match
5668 1 date plus weekday, for backreferencing to make sure both times on same day
5669 2 the first time, range or not
5670 4 the second time, if it is a range.")
5671
5672 (defvar org-prefix-has-time nil
5673 "A flag, set by `org-compile-prefix-format'.
5674 The flag is set if the currently compiled format contains a `%t'.")
5675 (defvar org-prefix-has-tag nil
5676 "A flag, set by `org-compile-prefix-format'.
5677 The flag is set if the currently compiled format contains a `%T'.")
5678
5679 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
5680 "Format TXT to be inserted into the agenda buffer.
5681 In particular, it adds the prefix and corresponding text properties. EXTRA
5682 must be a string and replaces the `%s' specifier in the prefix format.
5683 CATEGORY (string, symbol or nil) may be used to overrule the default
5684 category taken from local variable or file name. It will replace the `%c'
5685 specifier in the format. DOTIME, when non-nil, indicates that a
5686 time-of-day should be extracted from TXT for sorting of this entry, and for
5687 the `%t' specifier in the format. When DOTIME is a string, this string is
5688 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5689 only the correctly processes TXT should be returned - this is used by
5690 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
5691 (save-match-data
5692 ;; Diary entries sometimes have extra whitespace at the beginning
5693 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5694 (let* ((category (or category
5695 org-category
5696 (if (buffer-file-name)
5697 (file-name-sans-extension
5698 (file-name-nondirectory (buffer-file-name)))
5699 "")))
5700 (tag (or (nth (1- (length tags)) tags) ""))
5701 time ;; needed for the eval of the prefix format
5702 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5703 (time-of-day (and dotime (org-get-time-of-day ts)))
5704 stamp plain s0 s1 s2 rtn)
5705 (when (and dotime time-of-day org-prefix-has-time)
5706 ;; Extract starting and ending time and move them to prefix
5707 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5708 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5709 (setq s0 (match-string 0 ts)
5710 s1 (match-string (if plain 1 2) ts)
5711 s2 (match-string (if plain 8 4) ts))
5712
5713 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5714 ;; them, we might want to remove them there to avoid duplication.
5715 ;; The user can turn this off with a variable.
5716 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5717 (string-match (concat (regexp-quote s0) " *") txt)
5718 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5719 (= (match-beginning 0) 0)
5720 t))
5721 (setq txt (replace-match "" nil nil txt))))
5722 ;; Normalize the time(s) to 24 hour
5723 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5724 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5725
5726 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
5727 (and org-agenda-remove-tags-when-in-prefix
5728 org-prefix-has-tag))
5729 (string-match ":[a-zA-Z_:]+:[ \t]*$" txt))
5730 (setq txt (replace-match "" t t txt)))
5731
5732 ;; Create the final string
5733 (if noprefix
5734 (setq rtn txt)
5735 ;; Prepare the variables needed in the eval of the compiled format
5736 (setq time (cond (s2 (concat s1 "-" s2))
5737 (s1 (concat s1 "......"))
5738 (t ""))
5739 extra (or extra "")
5740 category (if (symbolp category) (symbol-name category) category))
5741 ;; Evaluate the compiled format
5742 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5743
5744 ;; And finally add the text properties
5745 (add-text-properties
5746 0 (length rtn) (list 'category (downcase category)
5747 'tags tags
5748 'prefix-length (- (length rtn) (length txt))
5749 'time-of-day time-of-day
5750 'dotime dotime)
5751 rtn)
5752 rtn)))
5753
5754 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5755 (catch 'exit
5756 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5757 ((and todayp (member 'today (car org-agenda-time-grid))))
5758 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5759 ((member 'weekly (car org-agenda-time-grid)))
5760 (t (throw 'exit list)))
5761 (let* ((have (delq nil (mapcar
5762 (lambda (x) (get-text-property 1 'time-of-day x))
5763 list)))
5764 (string (nth 1 org-agenda-time-grid))
5765 (gridtimes (nth 2 org-agenda-time-grid))
5766 (req (car org-agenda-time-grid))
5767 (remove (member 'remove-match req))
5768 new time)
5769 (if (and (member 'require-timed req) (not have))
5770 ;; don't show empty grid
5771 (throw 'exit list))
5772 (while (setq time (pop gridtimes))
5773 (unless (and remove (member time have))
5774 (setq time (int-to-string time))
5775 (push (org-format-agenda-item
5776 nil string "" nil ;; FIXME: put a category for the grid?
5777 (concat (substring time 0 -2) ":" (substring time -2)))
5778 new)
5779 (put-text-property
5780 1 (length (car new)) 'face 'org-time-grid (car new))))
5781 (if (member 'time-up org-agenda-sorting-strategy)
5782 (append new list)
5783 (append list new)))))
5784
5785 (defun org-compile-prefix-format (format)
5786 "Compile the prefix format into a Lisp form that can be evaluated.
5787 The resulting form is returned and stored in the variable
5788 `org-prefix-format-compiled'."
5789 (setq org-prefix-has-time nil org-prefix-has-tag nil)
5790 (let ((start 0) varform vars var (s format)e c f opt)
5791 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5792 s start)
5793 (setq var (cdr (assoc (match-string 4 s)
5794 '(("c" . category) ("t" . time) ("s" . extra)
5795 ("T" . tag))))
5796 c (or (match-string 3 s) "")
5797 opt (match-beginning 1)
5798 start (1+ (match-beginning 0)))
5799 (if (equal var 'time) (setq org-prefix-has-time t))
5800 (if (equal var 'tag) (setq org-prefix-has-tag t))
5801 (setq f (concat "%" (match-string 2 s) "s"))
5802 (if opt
5803 (setq varform
5804 `(if (equal "" ,var)
5805 ""
5806 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5807 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5808 (setq s (replace-match "%s" t nil s))
5809 (push varform vars))
5810 (setq vars (nreverse vars))
5811 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5812
5813 (defun org-get-time-of-day (s &optional string)
5814 "Check string S for a time of day.
5815 If found, return it as a military time number between 0 and 2400.
5816 If not found, return nil.
5817 The optional STRING argument forces conversion into a 5 character wide string
5818 HH:MM."
5819 (save-match-data
5820 (when
5821 (or
5822 (string-match
5823 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5824 (string-match
5825 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5826 (let* ((t0 (+ (* 100
5827 (+ (string-to-number (match-string 1 s))
5828 (if (and (match-beginning 4)
5829 (equal (downcase (match-string 4 s)) "pm"))
5830 12 0)))
5831 (if (match-beginning 3)
5832 (string-to-number (match-string 3 s))
5833 0)))
5834 (t1 (concat " "
5835 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
5836 (int-to-string t0))))
5837 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
5838
5839 (defun org-finalize-agenda-entries (list)
5840 "Sort and concatenate the agenda items."
5841 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
5842
5843 (defsubst org-cmp-priority (a b)
5844 "Compare the priorities of string A and B."
5845 (let ((pa (or (get-text-property 1 'priority a) 0))
5846 (pb (or (get-text-property 1 'priority b) 0)))
5847 (cond ((> pa pb) +1)
5848 ((< pa pb) -1)
5849 (t nil))))
5850
5851 (defsubst org-cmp-category (a b)
5852 "Compare the string values of categories of strings A and B."
5853 (let ((ca (or (get-text-property 1 'category a) ""))
5854 (cb (or (get-text-property 1 'category b) "")))
5855 (cond ((string-lessp ca cb) -1)
5856 ((string-lessp cb ca) +1)
5857 (t nil))))
5858
5859 (defsubst org-cmp-time (a b)
5860 "Compare the time-of-day values of strings A and B."
5861 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
5862 (ta (or (get-text-property 1 'time-of-day a) def))
5863 (tb (or (get-text-property 1 'time-of-day b) def)))
5864 (cond ((< ta tb) -1)
5865 ((< tb ta) +1)
5866 (t nil))))
5867
5868 (defun org-entries-lessp (a b)
5869 "Predicate for sorting agenda entries."
5870 ;; The following variables will be used when the form is evaluated.
5871 (let* ((time-up (org-cmp-time a b))
5872 (time-down (if time-up (- time-up) nil))
5873 (priority-up (org-cmp-priority a b))
5874 (priority-down (if priority-up (- priority-up) nil))
5875 (category-up (org-cmp-category a b))
5876 (category-down (if category-up (- category-up) nil))
5877 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
5878 (cdr (assoc
5879 (eval (cons 'or org-agenda-sorting-strategy))
5880 '((-1 . t) (1 . nil) (nil . nil))))))
5881
5882 (defun org-agenda-show-priority ()
5883 "Show the priority of the current item.
5884 This priority is composed of the main priority given with the [#A] cookies,
5885 and by additional input from the age of a schedules or deadline entry."
5886 (interactive)
5887 (let* ((pri (get-text-property (point-at-bol) 'priority)))
5888 (message "Priority is %d" (if pri pri -1000))))
5889
5890 (defun org-agenda-show-tags ()
5891 "Show the tags applicable to the current item."
5892 (interactive)
5893 (let* ((tags (get-text-property (point-at-bol) 'tags)))
5894 (if tags
5895 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
5896 (message "No tags associated with this line"))))
5897
5898 (defun org-agenda-goto (&optional highlight)
5899 "Go to the Org-mode file which contains the item at point."
5900 (interactive)
5901 (let* ((marker (or (get-text-property (point) 'org-marker)
5902 (org-agenda-error)))
5903 (buffer (marker-buffer marker))
5904 (pos (marker-position marker)))
5905 (switch-to-buffer-other-window buffer)
5906 (widen)
5907 (goto-char pos)
5908 (when (eq major-mode 'org-mode)
5909 (org-show-hidden-entry)
5910 (save-excursion
5911 (and (outline-next-heading)
5912 (org-flag-heading nil)))) ; show the next heading
5913 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
5914
5915 (defun org-agenda-switch-to ()
5916 "Go to the Org-mode file which contains the item at point."
5917 (interactive)
5918 (let* ((marker (or (get-text-property (point) 'org-marker)
5919 (org-agenda-error)))
5920 (buffer (marker-buffer marker))
5921 (pos (marker-position marker)))
5922 (switch-to-buffer buffer)
5923 (delete-other-windows)
5924 (widen)
5925 (goto-char pos)
5926 (when (eq major-mode 'org-mode)
5927 (org-show-hidden-entry)
5928 (save-excursion
5929 (and (outline-next-heading)
5930 (org-flag-heading nil)))))) ; show the next heading
5931
5932 (defun org-agenda-goto-mouse (ev)
5933 "Go to the Org-mode file which contains the item at the mouse click."
5934 (interactive "e")
5935 (mouse-set-point ev)
5936 (org-agenda-goto))
5937
5938 (defun org-agenda-show ()
5939 "Display the Org-mode file which contains the item at point."
5940 (interactive)
5941 (let ((win (selected-window)))
5942 (org-agenda-goto t)
5943 (select-window win)))
5944
5945 (defun org-agenda-recenter (arg)
5946 "Display the Org-mode file which contains the item at point and recenter."
5947 (interactive "P")
5948 (let ((win (selected-window)))
5949 (org-agenda-goto t)
5950 (recenter arg)
5951 (select-window win)))
5952
5953 (defun org-agenda-show-mouse (ev)
5954 "Display the Org-mode file which contains the item at the mouse click."
5955 (interactive "e")
5956 (mouse-set-point ev)
5957 (org-agenda-show))
5958
5959 (defun org-agenda-check-no-diary ()
5960 "Check if the entry is a diary link and abort if yes."
5961 (if (get-text-property (point) 'org-agenda-diary-link)
5962 (org-agenda-error)))
5963
5964 (defun org-agenda-error ()
5965 (error "Command not allowed in this line"))
5966
5967 (defvar org-last-heading-marker (make-marker)
5968 "Marker pointing to the headline that last changed its TODO state
5969 by a remote command from the agenda.")
5970
5971 (defun org-agenda-todo (&optional arg)
5972 "Cycle TODO state of line at point, also in Org-mode file.
5973 This changes the line at point, all other lines in the agenda referring to
5974 the same tree node, and the headline of the tree node in the Org-mode file."
5975 (interactive "P")
5976 (org-agenda-check-no-diary)
5977 (let* ((col (current-column))
5978 (marker (or (get-text-property (point) 'org-marker)
5979 (org-agenda-error)))
5980 (buffer (marker-buffer marker))
5981 (pos (marker-position marker))
5982 (hdmarker (get-text-property (point) 'org-hd-marker))
5983 (buffer-read-only nil)
5984 newhead)
5985 (with-current-buffer buffer
5986 (widen)
5987 (goto-char pos)
5988 (org-show-hidden-entry)
5989 (save-excursion
5990 (and (outline-next-heading)
5991 (org-flag-heading nil))) ; show the next heading
5992 (org-todo arg)
5993 (forward-char 1)
5994 (setq newhead (org-get-heading))
5995 (save-excursion
5996 (org-back-to-heading)
5997 (move-marker org-last-heading-marker (point))))
5998 (beginning-of-line 1)
5999 (save-excursion
6000 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6001 (move-to-column col)))
6002
6003 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6004 "Change all lines in the agenda buffer which match HDMARKER.
6005 The new content of the line will be NEWHEAD (as modified by
6006 `org-format-agenda-item'). HDMARKER is checked with
6007 `equal' against all `org-hd-marker' text properties in the file.
6008 If FIXFACE is non-nil, the face of each item is modified acording to
6009 the new TODO state."
6010 (let* (props m pl undone-face done-face finish new dotime cat tags)
6011 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6012 (save-excursion
6013 (goto-char (point-max))
6014 (beginning-of-line 1)
6015 (while (not finish)
6016 (setq finish (bobp))
6017 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6018 (equal m hdmarker))
6019 (setq props (text-properties-at (point))
6020 dotime (get-text-property (point) 'dotime)
6021 cat (get-text-property (point) 'category)
6022 tags (get-text-property (point) 'tags)
6023 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6024 pl (get-text-property (point) 'prefix-length)
6025 undone-face (get-text-property (point) 'undone-face)
6026 done-face (get-text-property (point) 'done-face))
6027 (move-to-column pl)
6028 (if (looking-at ".*")
6029 (progn
6030 (replace-match new t t)
6031 (beginning-of-line 1)
6032 (add-text-properties (point-at-bol) (point-at-eol) props)
6033 (if fixface
6034 (add-text-properties
6035 (point-at-bol) (point-at-eol)
6036 (list 'face
6037 (if org-last-todo-state-is-todo
6038 undone-face done-face))))
6039 (beginning-of-line 1))
6040 (error "Line update did not work")))
6041 (beginning-of-line 0)))))
6042
6043 (defun org-agenda-priority-up ()
6044 "Increase the priority of line at point, also in Org-mode file."
6045 (interactive)
6046 (org-agenda-priority 'up))
6047
6048 (defun org-agenda-priority-down ()
6049 "Decrease the priority of line at point, also in Org-mode file."
6050 (interactive)
6051 (org-agenda-priority 'down))
6052
6053 (defun org-agenda-priority (&optional force-direction)
6054 "Set the priority of line at point, also in Org-mode file.
6055 This changes the line at point, all other lines in the agenda referring to
6056 the same tree node, and the headline of the tree node in the Org-mode file."
6057 (interactive)
6058 (org-agenda-check-no-diary)
6059 (let* ((marker (or (get-text-property (point) 'org-marker)
6060 (org-agenda-error)))
6061 (buffer (marker-buffer marker))
6062 (pos (marker-position marker))
6063 (hdmarker (get-text-property (point) 'org-hd-marker))
6064 (buffer-read-only nil)
6065 newhead)
6066 (with-current-buffer buffer
6067 (widen)
6068 (goto-char pos)
6069 (org-show-hidden-entry)
6070 (save-excursion
6071 (and (outline-next-heading)
6072 (org-flag-heading nil))) ; show the next heading
6073 (funcall 'org-priority force-direction)
6074 (end-of-line 1)
6075 (setq newhead (org-get-heading)))
6076 (org-agenda-change-all-lines newhead hdmarker)
6077 (beginning-of-line 1)))
6078
6079 (defun org-agenda-set-tags ()
6080 "Set tags for the current headline."
6081 (interactive)
6082 (org-agenda-check-no-diary)
6083 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6084 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6085 (org-agenda-error)))
6086 (buffer (marker-buffer hdmarker))
6087 (pos (marker-position hdmarker))
6088 (buffer-read-only nil)
6089 newhead)
6090 (with-current-buffer buffer
6091 (widen)
6092 (goto-char pos)
6093 (org-show-hidden-entry)
6094 (save-excursion
6095 (and (outline-next-heading)
6096 (org-flag-heading nil))) ; show the next heading
6097 (call-interactively 'org-set-tags)
6098 (end-of-line 1)
6099 (setq newhead (org-get-heading)))
6100 (org-agenda-change-all-lines newhead hdmarker)
6101 (beginning-of-line 1)))
6102
6103 (defun org-agenda-date-later (arg &optional what)
6104 "Change the date of this item to one day later."
6105 (interactive "p")
6106 (org-agenda-check-type t 'agenda 'timeline)
6107 (org-agenda-check-no-diary)
6108 (let* ((marker (or (get-text-property (point) 'org-marker)
6109 (org-agenda-error)))
6110 (buffer (marker-buffer marker))
6111 (pos (marker-position marker)))
6112 (with-current-buffer buffer
6113 (widen)
6114 (goto-char pos)
6115 (if (not (org-at-timestamp-p))
6116 (error "Cannot find time stamp"))
6117 (org-timestamp-change arg (or what 'day))
6118 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6119
6120 (defun org-agenda-date-earlier (arg &optional what)
6121 "Change the date of this item to one day earlier."
6122 (interactive "p")
6123 (org-agenda-date-later (- arg) what))
6124
6125 (defun org-agenda-date-prompt (arg)
6126 "Change the date of this item. Date is prompted for, with default today.
6127 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6128 be used to request time specification in the time stamp."
6129 (interactive "P")
6130 (org-agenda-check-type t 'agenda 'timeline)
6131 (org-agenda-check-no-diary)
6132 (let* ((marker (or (get-text-property (point) 'org-marker)
6133 (org-agenda-error)))
6134 (buffer (marker-buffer marker))
6135 (pos (marker-position marker)))
6136 (with-current-buffer buffer
6137 (widen)
6138 (goto-char pos)
6139 (if (not (org-at-timestamp-p))
6140 (error "Cannot find time stamp"))
6141 (org-time-stamp arg)
6142 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6143
6144 (defun org-get-heading ()
6145 "Return the heading of the current entry, without the stars."
6146 (save-excursion
6147 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6148 ;;FIXME???????? (and (bolp) (end-of-line 1))
6149 (if (and (re-search-backward "[\r\n]\\*" nil t)
6150 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6151 (match-string 1)
6152 "")))
6153
6154 (defun org-agenda-diary-entry ()
6155 "Make a diary entry, like the `i' command from the calendar.
6156 All the standard commands work: block, weekly etc."
6157 (interactive)
6158 (org-agenda-check-type t 'agenda 'timeline)
6159 (require 'diary-lib)
6160 (let* ((char (progn
6161 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6162 (read-char-exclusive)))
6163 (cmd (cdr (assoc char
6164 '((?d . insert-diary-entry)
6165 (?w . insert-weekly-diary-entry)
6166 (?m . insert-monthly-diary-entry)
6167 (?y . insert-yearly-diary-entry)
6168 (?a . insert-anniversary-diary-entry)
6169 (?b . insert-block-diary-entry)
6170 (?c . insert-cyclic-diary-entry)))))
6171 (oldf (symbol-function 'calendar-cursor-to-date))
6172 (point (point))
6173 (mark (or (mark t) (point))))
6174 (unless cmd
6175 (error "No command associated with <%c>" char))
6176 (unless (and (get-text-property point 'day)
6177 (or (not (equal ?b char))
6178 (get-text-property mark 'day)))
6179 (error "Don't know which date to use for diary entry"))
6180 ;; We implement this by hacking the `calendar-cursor-to-date' function
6181 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6182 (let ((calendar-mark-ring
6183 (list (calendar-gregorian-from-absolute
6184 (or (get-text-property mark 'day)
6185 (get-text-property point 'day))))))
6186 (unwind-protect
6187 (progn
6188 (fset 'calendar-cursor-to-date
6189 (lambda (&optional error)
6190 (calendar-gregorian-from-absolute
6191 (get-text-property point 'day))))
6192 (call-interactively cmd))
6193 (fset 'calendar-cursor-to-date oldf)))))
6194
6195
6196 (defun org-agenda-execute-calendar-command (cmd)
6197 "Execute a calendar command from the agenda, with the date associated to
6198 the cursor position."
6199 (org-agenda-check-type t 'agenda 'timeline)
6200 (require 'diary-lib)
6201 (unless (get-text-property (point) 'day)
6202 (error "Don't know which date to use for calendar command"))
6203 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6204 (point (point))
6205 (date (calendar-gregorian-from-absolute
6206 (get-text-property point 'day)))
6207 (displayed-day (extract-calendar-day date))
6208 (displayed-month (extract-calendar-month date))
6209 (displayed-year (extract-calendar-year date)))
6210 (unwind-protect
6211 (progn
6212 (fset 'calendar-cursor-to-date
6213 (lambda (&optional error)
6214 (calendar-gregorian-from-absolute
6215 (get-text-property point 'day))))
6216 (call-interactively cmd))
6217 (fset 'calendar-cursor-to-date oldf))))
6218
6219 (defun org-agenda-phases-of-moon ()
6220 "Display the phases of the moon for the 3 months around the cursor date."
6221 (interactive)
6222 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6223
6224 (defun org-agenda-holidays ()
6225 "Display the holidays for the 3 months around the cursor date."
6226 (interactive)
6227 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6228
6229 (defun org-agenda-sunrise-sunset (arg)
6230 "Display sunrise and sunset for the cursor date.
6231 Latitude and longitude can be specified with the variables
6232 `calendar-latitude' and `calendar-longitude'. When called with prefix
6233 argument, latitude and longitude will be prompted for."
6234 (interactive "P")
6235 (let ((calendar-longitude (if arg nil calendar-longitude))
6236 (calendar-latitude (if arg nil calendar-latitude))
6237 (calendar-location-name
6238 (if arg "the given coordinates" calendar-location-name)))
6239 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6240
6241 (defun org-agenda-goto-calendar ()
6242 "Open the Emacs calendar with the date at the cursor."
6243 (interactive)
6244 (org-agenda-check-type t 'agenda 'timeline)
6245 (let* ((day (or (get-text-property (point) 'day)
6246 (error "Don't know which date to open in calendar")))
6247 (date (calendar-gregorian-from-absolute day))
6248 (calendar-move-hook nil)
6249 (view-diary-entries-initially nil))
6250 (calendar)
6251 (calendar-goto-date date)))
6252
6253 (defun org-calendar-goto-agenda ()
6254 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6255 This is a command that has to be installed in `calendar-mode-map'."
6256 (interactive)
6257 (org-agenda-list nil (calendar-absolute-from-gregorian
6258 (calendar-cursor-to-date))
6259 nil t))
6260
6261 (defun org-agenda-convert-date ()
6262 (interactive)
6263 (org-agenda-check-type t 'agenda 'timeline)
6264 (let ((day (get-text-property (point) 'day))
6265 date s)
6266 (unless day
6267 (error "Don't know which date to convert"))
6268 (setq date (calendar-gregorian-from-absolute day))
6269 (setq s (concat
6270 "Gregorian: " (calendar-date-string date) "\n"
6271 "ISO: " (calendar-iso-date-string date) "\n"
6272 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6273 "Julian: " (calendar-julian-date-string date) "\n"
6274 "Astron. JD: " (calendar-astro-date-string date)
6275 " (Julian date number at noon UTC)\n"
6276 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6277 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6278 "French: " (calendar-french-date-string date) "\n"
6279 "Mayan: " (calendar-mayan-date-string date) "\n"
6280 "Coptic: " (calendar-coptic-date-string date) "\n"
6281 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6282 "Persian: " (calendar-persian-date-string date) "\n"
6283 "Chinese: " (calendar-chinese-date-string date) "\n"))
6284 (with-output-to-temp-buffer "*Dates*"
6285 (princ s))
6286 (if (fboundp 'fit-window-to-buffer)
6287 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6288
6289 ;;; Tags
6290
6291 (defun org-scan-tags (action matcher &optional todo-only)
6292 "Scan headline tags with inheritance and produce output ACTION.
6293 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6294 evaluated, testing if a given set of tags qualifies a headline for
6295 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6296 are included in the output."
6297 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6298 (mapconcat 'regexp-quote
6299 (nreverse (cdr (reverse org-todo-keywords)))
6300 "\\|")
6301 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_:]+:\\)?[ \t]*[\n\r]"))
6302 (props (list 'face nil
6303 'done-face 'org-done
6304 'undone-face nil
6305 'mouse-face 'highlight
6306 'keymap org-agenda-keymap
6307 'help-echo
6308 (format "mouse-2 or RET jump to org file %s"
6309 (abbreviate-file-name (buffer-file-name)))))
6310 lspos
6311 tags tags-list tags-alist (llast 0) rtn level category i txt
6312 todo marker)
6313
6314 (save-excursion
6315 (goto-char (point-min))
6316 (when (eq action 'sparse-tree) (hide-sublevels 1))
6317 (while (re-search-forward re nil t)
6318 (setq todo (if (match-end 1) (match-string 2))
6319 tags (if (match-end 4) (match-string 4)))
6320 (goto-char (setq lspos (1+ (match-beginning 0))))
6321 (setq level (outline-level)
6322 category (org-get-category))
6323 (setq i llast llast level)
6324 ;; remove tag lists from same and sublevels
6325 (while (>= i level)
6326 (when (setq entry (assoc i tags-alist))
6327 (setq tags-alist (delete entry tags-alist)))
6328 (setq i (1- i)))
6329 ;; add the nex tags
6330 (when tags
6331 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6332 tags-alist
6333 (cons (cons level tags) tags-alist)))
6334 ;; compile tags for current headline
6335 (setq tags-list
6336 (if org-use-tag-inheritance
6337 (apply 'append (mapcar 'cdr tags-alist))
6338 tags))
6339 (when (and (or (not todo-only) todo)
6340 (eval matcher))
6341 ;; list this headline
6342 (if (eq action 'sparse-tree)
6343 (progn
6344 (org-show-hierarchy-above))
6345 (setq txt (org-format-agenda-item
6346 ""
6347 (concat
6348 (if org-tags-match-list-sublevels
6349 (make-string (1- level) ?.) "")
6350 (org-get-heading))
6351 category tags-list))
6352 (goto-char lspos)
6353 (setq marker (org-agenda-new-marker))
6354 (add-text-properties
6355 0 (length txt)
6356 (append (list 'org-marker marker 'org-hd-marker marker
6357 'category category)
6358 props)
6359 txt)
6360 (push txt rtn))
6361 ;; if we are to skip sublevels, jump to end of subtree
6362 (point)
6363 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6364 (nreverse rtn)))
6365
6366 (defun org-tags-sparse-tree (&optional arg match)
6367 "Create a sparse tree according to tags search string MATCH.
6368 MATCH can contain positive and negative selection of tags, like
6369 \"+WORK+URGENT-WITHBOSS\"."
6370 (interactive "P")
6371 (let ((org-show-following-heading nil)
6372 (org-show-hierarchy-above nil))
6373 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6374
6375 (defun org-make-tags-matcher (match)
6376 "Create the TAGS matcher form for the tags-selecting string MATCH."
6377 (unless match
6378 ;; Get a new match request, with completion
6379 (setq org-last-tags-completion-table
6380 (or (org-get-buffer-tags)
6381 org-last-tags-completion-table))
6382 (setq match (completing-read
6383 "Tags: " 'org-tags-completion-function nil nil nil
6384 'org-tags-history)))
6385 ;; parse the string and create a lisp form
6386 (let ((match0 match) minus tag mm matcher orterms term orlist)
6387 (setq orterms (org-split-string match "|"))
6388 (while (setq term (pop orterms))
6389 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_]+\\)" term)
6390 (setq minus (and (match-end 1)
6391 (equal (match-string 1 term) "-"))
6392 tag (match-string 2 term)
6393 term (substring term (match-end 0))
6394 mm (list 'member (downcase tag) 'tags-list)
6395 mm (if minus (list 'not mm) mm))
6396 (push mm matcher))
6397 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6398 orlist)
6399 (setq matcher nil))
6400 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6401 ;; Return the string and lisp forms of the matcher
6402 (cons match0 matcher)))
6403
6404 ;;;###autoload
6405 (defun org-tags-view (&optional todo-only match keep-modes)
6406 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
6407 The prefix arg TODO-ONLY limits the search to TODO entries."
6408 (interactive "P")
6409 (org-agenda-maybe-reset-markers 'force)
6410 (org-compile-prefix-format org-agenda-prefix-format)
6411 (let* ((org-agenda-keep-modes keep-modes)
6412 (org-tags-match-list-sublevels
6413 (if todo-only t org-tags-match-list-sublevels))
6414 (win (selected-window))
6415 (completion-ignore-case t)
6416 rtn rtnall files file pos matcher
6417 buffer)
6418 (setq matcher (org-make-tags-matcher match)
6419 match (car matcher) matcher (cdr matcher))
6420 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6421 (progn
6422 (delete-other-windows)
6423 (switch-to-buffer-other-window
6424 (get-buffer-create org-agenda-buffer-name))))
6425 (setq buffer-read-only nil)
6426 (erase-buffer)
6427 (org-agenda-mode) (setq buffer-read-only nil)
6428 (set (make-local-variable 'org-agenda-type) 'tags)
6429 (set (make-local-variable 'org-agenda-redo-command)
6430 (list 'org-tags-view (list 'quote todo-only)
6431 (list 'if 'current-prefix-arg nil match) t))
6432 (setq files (org-agenda-files)
6433 rtnall nil)
6434 (while (setq file (pop files))
6435 (catch 'nextfile
6436 (org-check-agenda-file file)
6437 (setq buffer (if (file-exists-p file)
6438 (org-get-agenda-file-buffer file)
6439 (error "No such file %s" file)))
6440 (if (not buffer)
6441 ;; If file does not exist, merror message to agenda
6442 (setq rtn (list
6443 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6444 rtnall (append rtnall rtn))
6445 (with-current-buffer buffer
6446 (unless (eq major-mode 'org-mode)
6447 (error "Agenda file %s is not in `org-mode'" file))
6448 (save-excursion
6449 (save-restriction
6450 (if org-respect-restriction
6451 (if (org-region-active-p)
6452 ;; Respect a region to restrict search
6453 (narrow-to-region (region-beginning) (region-end)))
6454 ;; If we work for the calendar or many files,
6455 ;; get rid of any restriction
6456 (widen))
6457 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6458 (setq rtnall (append rtnall rtn))))))))
6459 (insert "Headlines with TAGS match: ")
6460 (add-text-properties (point-min) (1- (point))
6461 (list 'face 'org-link))
6462 (setq pos (point))
6463 (insert match "\n")
6464 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6465 (setq pos (point))
6466 (insert "Press `C-u r' to search again with new search string\n")
6467 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6468 (when rtnall
6469 (insert (mapconcat 'identity rtnall "\n")))
6470 (goto-char (point-min))
6471 (setq buffer-read-only t)
6472 (org-fit-agenda-window)
6473 (if (not org-select-agenda-window) (select-window win))))
6474
6475 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6476 (defun org-set-tags (&optional arg just-align)
6477 "Set the tags for the current headline.
6478 With prefix ARG, realign all tags in headings in the current buffer."
6479 (interactive)
6480 (let* (;(inherit (org-get-inherited-tags))
6481 (re (concat "^" outline-regexp))
6482 (col (current-column))
6483 (current (org-get-tags))
6484 tags hd empty)
6485 (if arg
6486 (save-excursion
6487 (goto-char (point-min))
6488 (while (re-search-forward re nil t)
6489 (org-set-tags nil t))
6490 (message "All tags realigned to column %d" org-tags-column))
6491 (if just-align
6492 (setq tags current)
6493 (setq org-last-tags-completion-table
6494 (or (org-get-buffer-tags)
6495 org-last-tags-completion-table))
6496 (setq tags
6497 (let ((org-add-colon-after-tag-completion t))
6498 (completing-read "Tags: " 'org-tags-completion-function
6499 nil nil current 'org-tags-history)))
6500 (while (string-match "[-+&]+" tags)
6501 (setq tags (replace-match ":" t t tags)))
6502 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6503 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6504 (unless (string-match "^:" tags) (setq tags (concat ":" tags)))))
6505 (if (equal current "")
6506 (progn
6507 (end-of-line 1)
6508 (or empty (insert " ")))
6509 (beginning-of-line 1)
6510 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6511 (setq hd (match-string 1))
6512 (delete-region (match-beginning 0) (match-end 0))
6513 (insert (org-trim hd) (if empty "" " ")))
6514 (unless (equal tags "")
6515 (move-to-column (max (current-column)
6516 (if (> org-tags-column 0)
6517 org-tags-column
6518 (- (- org-tags-column) (length tags))))
6519 t)
6520 (insert tags))
6521 (move-to-column col))))
6522
6523 (defun org-tags-completion-function (string predicate &optional flag)
6524 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6525 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6526 (setq s1 (match-string 1 string)
6527 s2 (match-string 2 string))
6528 (setq s1 "" s2 string))
6529 (cond
6530 ((eq flag nil)
6531 ;; try completion
6532 (setq rtn (try-completion s2 ctable))
6533 (if (stringp rtn)
6534 (concat s1 s2 (substring rtn (length s2))
6535 (if (and org-add-colon-after-tag-completion
6536 (assoc rtn ctable))
6537 ":" "")))
6538 )
6539 ((eq flag t)
6540 ;; all-completions
6541 (all-completions s2 ctable)
6542 )
6543 ((eq flag 'lambda)
6544 ;; exact match?
6545 (assoc s2 ctable)))
6546 ))
6547
6548 (defun org-get-tags ()
6549 "Get the TAGS string in the current headline."
6550 (unless (org-on-heading-p)
6551 (error "Not on a heading"))
6552 (save-excursion
6553 (beginning-of-line 1)
6554 (if (looking-at ".*[ \t]\\(:[A-Za-z_:]+:\\)[ \t]*\\(\r\\|$\\)")
6555 (match-string 1)
6556 "")))
6557
6558 (defun org-get-buffer-tags ()
6559 "Get a table of all tags used in the buffer, for completion."
6560 (let (tags)
6561 (save-excursion
6562 (goto-char (point-min))
6563 (while (re-search-forward "[ \t]:\\([A-Za-z_:]+\\):[ \t\r\n]" nil t)
6564 (mapc (lambda (x) (add-to-list 'tags x))
6565 (org-split-string (match-string 1) ":"))))
6566 (mapcar 'list tags)))
6567
6568 ;;; Link Stuff
6569
6570 (defun org-find-file-at-mouse (ev)
6571 "Open file link or URL at mouse."
6572 (interactive "e")
6573 (mouse-set-point ev)
6574 (org-open-at-point 'in-emacs))
6575
6576 (defun org-open-at-mouse (ev)
6577 "Open file link or URL at mouse."
6578 (interactive "e")
6579 (mouse-set-point ev)
6580 (org-open-at-point))
6581
6582 (defun org-open-at-point (&optional in-emacs)
6583 "Open link at or after point.
6584 If there is no link at point, this function will search forward up to
6585 the end of the current subtree.
6586 Normally, files will be opened by an appropriate application. If the
6587 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6588 (interactive "P")
6589 (org-remove-occur-highlights nil nil t)
6590 (if (org-at-timestamp-p)
6591 (org-agenda-list nil (time-to-days (org-time-string-to-time
6592 (substring (match-string 1) 0 10)))
6593 1)
6594 (let (type path line search (pos (point)))
6595 (catch 'match
6596 (save-excursion
6597 (skip-chars-backward
6598 (concat (if org-allow-space-in-links "^" "^ ")
6599 org-non-link-chars))
6600 (when (or (looking-at org-link-regexp)
6601 (and (re-search-forward org-link-regexp (point-at-eol) t)
6602 (<= (match-beginning 0) pos)
6603 (>= (match-end 0) pos)))
6604 (setq type (match-string 1)
6605 path (match-string 2))
6606 (throw 'match t)))
6607 (save-excursion
6608 (skip-chars-backward "^ \t\n\r")
6609 (when (looking-at "\\(:[A-Za-z_:]+\\):[ \t\r\n]")
6610 (setq type "tags"
6611 path (match-string 1))
6612 (while (string-match ":" path)
6613 (setq path (replace-match "+" t t path)))
6614 (throw 'match t)))
6615 (save-excursion
6616 (skip-chars-backward "a-zA-Z_")
6617 (when (looking-at org-camel-regexp)
6618 (setq type "camel" path (match-string 0))
6619 (if (equal (char-before) ?*)
6620 (setq path (concat "*" path))))
6621 (throw 'match t))
6622 (save-excursion
6623 (when (re-search-forward
6624 org-link-regexp
6625 (save-excursion
6626 (condition-case nil
6627 (progn (outline-end-of-subtree) (max pos (point)))
6628 (error (end-of-line 1) (point))))
6629 t)
6630 (setq type (match-string 1)
6631 path (match-string 2)))))
6632 (unless path
6633 (error "No link found"))
6634 ;; Remove any trailing spaces in path
6635 (if (string-match " +\\'" path)
6636 (setq path (replace-match "" t t path)))
6637
6638 (cond
6639
6640 ((string= type "tags")
6641 (org-tags-view in-emacs path))
6642 ((string= type "camel")
6643 (org-link-search
6644 path
6645 (cond ((equal in-emacs '(4)) 'occur)
6646 ((equal in-emacs '(16)) 'org-occur)
6647 (t nil))))
6648
6649 ((string= type "file")
6650 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6651 (setq line (string-to-number (match-string 1 path))
6652 path (substring path 0 (match-beginning 0)))
6653 (if (string-match "::\\(.+\\)\\'" path)
6654 (setq search (match-string 1 path)
6655 path (substring path 0 (match-beginning 0)))))
6656 (org-open-file path in-emacs line search))
6657
6658 ((string= type "news")
6659 (org-follow-gnus-link path))
6660
6661 ((string= type "bbdb")
6662 (org-follow-bbdb-link path))
6663
6664 ((string= type "gnus")
6665 (let (group article)
6666 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6667 (error "Error in Gnus link"))
6668 (setq group (match-string 1 path)
6669 article (match-string 3 path))
6670 (org-follow-gnus-link group article)))
6671
6672 ((string= type "vm")
6673 (let (folder article)
6674 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6675 (error "Error in VM link"))
6676 (setq folder (match-string 1 path)
6677 article (match-string 3 path))
6678 ;; in-emacs is the prefix arg, will be interpreted as read-only
6679 (org-follow-vm-link folder article in-emacs)))
6680
6681 ((string= type "wl")
6682 (let (folder article)
6683 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6684 (error "Error in Wanderlust link"))
6685 (setq folder (match-string 1 path)
6686 article (match-string 3 path))
6687 (org-follow-wl-link folder article)))
6688
6689 ((string= type "rmail")
6690 (let (folder article)
6691 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6692 (error "Error in RMAIL link"))
6693 (setq folder (match-string 1 path)
6694 article (match-string 3 path))
6695 (org-follow-rmail-link folder article)))
6696
6697 ((string= type "shell")
6698 (let ((cmd path))
6699 (while (string-match "@{" cmd)
6700 (setq cmd (replace-match "<" t t cmd)))
6701 (while (string-match "@}" cmd)
6702 (setq cmd (replace-match ">" t t cmd)))
6703 (if (or (not org-confirm-shell-links)
6704 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6705 (shell-command cmd)
6706 (error "Abort"))))
6707
6708 (t
6709 (browse-url-at-point))))))
6710
6711 (defun org-link-search (s &optional type)
6712 "Search for a link search option.
6713 When S is a CamelCaseWord, search for a target, or for a sentence containing
6714 the words. If S is surrounded by forward slashes, it is interpreted as a
6715 regular expression. In org-mode files, this will create an `org-occur'
6716 sparse tree. In ordinary files, `occur' will be used to list matches.
6717 If the current buffer is in `dired-mode', grep will be used to search
6718 in all files."
6719 (let ((case-fold-search t)
6720 (s0 s)
6721 (pos (point))
6722 (pre "") (post "")
6723 words re0 re1 re2 re3 re4 re5 reall)
6724 (cond ((string-match "^/\\(.*\\)/$" s)
6725 ;; A regular expression
6726 (cond
6727 ((eq major-mode 'org-mode)
6728 (org-occur (match-string 1 s)))
6729 ;;((eq major-mode 'dired-mode)
6730 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6731 (t (org-do-occur (match-string 1 s)))))
6732 ((string-match (concat "^" org-camel-regexp) s)
6733 ;; A camel
6734 (if (equal (string-to-char s) ?*)
6735 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6736 post "[ \t]*$"
6737 s (substring s 1)))
6738 (remove-text-properties
6739 0 (length s)
6740 '(face nil mouse-face nil keymap nil fontified nil) s)
6741 ;; Make a series of regular expressions to find a match
6742 (setq words (org-camel-to-words s)
6743 re0 (concat "<<" (regexp-quote s0) ">>")
6744 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6745 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6746 re1 (concat pre re2 post)
6747 re3 (concat pre re4 post)
6748 re5 (concat pre ".*" re4)
6749 re2 (concat pre re2)
6750 re4 (concat pre re4)
6751 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6752 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6753 re5 "\\)"
6754 ))
6755 (cond
6756 ((eq type 'org-occur) (org-occur reall))
6757 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6758 (t (goto-char (point-min))
6759 (if (or (re-search-forward re0 nil t)
6760 (re-search-forward re1 nil t)
6761 (re-search-forward re2 nil t)
6762 (re-search-forward re3 nil t)
6763 (re-search-forward re4 nil t)
6764 (re-search-forward re5 nil t))
6765 (goto-char (match-beginning 0))
6766 (goto-char pos)
6767 (error "No match")))))
6768 (t
6769 ;; Normal string-search
6770 (goto-char (point-min))
6771 (if (search-forward s nil t)
6772 (goto-char (match-beginning 0))
6773 (error "No match"))))))
6774
6775 (defun org-do-occur (regexp &optional cleanup)
6776 "Call the Emacs command `occur'.
6777 If CLEANUP is non-nil, remove the printout of the regular expression
6778 in the *Occur* buffer. This is useful if the regex is long and not useful
6779 to read."
6780 (occur regexp)
6781 (when cleanup
6782 (let ((cwin (selected-window)) win beg end)
6783 (when (setq win (get-buffer-window "*Occur*"))
6784 (select-window win))
6785 (goto-char (point-min))
6786 (when (re-search-forward "match[a-z]+" nil t)
6787 (setq beg (match-end 0))
6788 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6789 (setq end (1- (match-beginning 0)))))
6790 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
6791 (goto-char (point-min))
6792 (select-window cwin))))
6793
6794 (defun org-camel-to-words (s)
6795 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
6796 (let ((case-fold-search nil)
6797 words)
6798 (while (string-match "[a-z][A-Z]" s)
6799 (push (substring s 0 (1+ (match-beginning 0))) words)
6800 (setq s (substring s (1+ (match-beginning 0)))))
6801 (nreverse (cons s words))))
6802
6803 (defun org-follow-bbdb-link (name)
6804 "Follow a BBDB link to NAME."
6805 (require 'bbdb)
6806 (let ((inhibit-redisplay t))
6807 (catch 'exit
6808 ;; Exact match on name
6809 (bbdb-name (concat "\\`" name "\\'") nil)
6810 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6811 ;; Exact match on name
6812 (bbdb-company (concat "\\`" name "\\'") nil)
6813 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6814 ;; Partial match on name
6815 (bbdb-name name nil)
6816 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6817 ;; Partial match on company
6818 (bbdb-company name nil)
6819 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6820 ;; General match including network address and notes
6821 (bbdb name nil)
6822 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
6823 (delete-window (get-buffer-window "*BBDB*"))
6824 (error "No matching BBDB record")))))
6825
6826 (defun org-follow-gnus-link (&optional group article)
6827 "Follow a Gnus link to GROUP and ARTICLE."
6828 (require 'gnus)
6829 (funcall (cdr (assq 'gnus org-link-frame-setup)))
6830 (if group (gnus-fetch-group group))
6831 (if article
6832 (or (gnus-summary-goto-article article nil 'force)
6833 (if (fboundp 'gnus-summary-insert-cached-articles)
6834 (progn
6835 (gnus-summary-insert-cached-articles)
6836 (gnus-summary-goto-article article nil 'force))
6837 (message "Message could not be found.")))))
6838
6839 (defun org-follow-vm-link (&optional folder article readonly)
6840 "Follow a VM link to FOLDER and ARTICLE."
6841 (require 'vm)
6842 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
6843 ;; ange-ftp or efs or tramp access
6844 (let ((user (or (match-string 1 folder) (user-login-name)))
6845 (host (match-string 2 folder))
6846 (file (match-string 3 folder)))
6847 (cond
6848 ((featurep 'tramp)
6849 ;; use tramp to access the file
6850 (if org-xemacs-p
6851 (setq folder (format "[%s@%s]%s" user host file))
6852 (setq folder (format "/%s@%s:%s" user host file))))
6853 (t
6854 ;; use ange-ftp or efs
6855 (require (if org-xemacs-p 'efs 'ange-ftp))
6856 (setq folder (format "/%s@%s:%s" user host file))))))
6857 (when folder
6858 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
6859 (sit-for 0.1)
6860 (when article
6861 (vm-select-folder-buffer)
6862 (widen)
6863 (let ((case-fold-search t))
6864 (goto-char (point-min))
6865 (if (not (re-search-forward
6866 (concat "^" "message-id: *" (regexp-quote article))))
6867 (error "Could not find the specified message in this folder"))
6868 (vm-isearch-update)
6869 (vm-isearch-narrow)
6870 (vm-beginning-of-message)
6871 (vm-summarize)))))
6872
6873 (defun org-follow-wl-link (folder article)
6874 "Follow a Wanderlust link to FOLDER and ARTICLE."
6875 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
6876 (if article (wl-summary-jump-to-msg-by-message-id article))
6877 (wl-summary-redisplay))
6878
6879 (defun org-follow-rmail-link (folder article)
6880 "Follow an RMAIL link to FOLDER and ARTICLE."
6881 (let (message-number)
6882 (save-excursion
6883 (save-window-excursion
6884 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6885 (setq message-number
6886 (save-restriction
6887 (widen)
6888 (goto-char (point-max))
6889 (if (re-search-backward
6890 (concat "^Message-ID:\\s-+" (regexp-quote
6891 (or article "")))
6892 nil t)
6893 (rmail-what-message))))))
6894 (if message-number
6895 (progn
6896 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6897 (rmail-show-message message-number)
6898 message-number)
6899 (error "Message not found"))))
6900
6901 (defun org-open-file (path &optional in-emacs line search)
6902 "Open the file at PATH.
6903 First, this expands any special file name abbreviations. Then the
6904 configuration variable `org-file-apps' is checked if it contains an
6905 entry for this file type, and if yes, the corresponding command is launched.
6906 If no application is found, Emacs simply visits the file.
6907 With optional argument IN-EMACS, Emacs will visit the file.
6908 Optional LINE specifies a line to go to, optional SEARCH a string to
6909 search for. If LINE or SEARCH is given, the file will always be
6910 opened in Emacs.
6911 If the file does not exist, an error is thrown."
6912 (setq in-emacs (or in-emacs line search))
6913 (let* ((file (if (equal path "")
6914 (buffer-file-name)
6915 (convert-standard-filename (org-expand-file-name path))))
6916 (dfile (downcase file))
6917 ext cmd apps)
6918 (if (and (not (file-exists-p file))
6919 (not org-open-non-existing-files))
6920 (error "No such file: %s" file))
6921 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
6922 (setq ext (match-string 1 dfile))
6923 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
6924 (setq ext (match-string 1 dfile))))
6925 (setq apps (append org-file-apps (org-default-apps)))
6926 (if in-emacs
6927 (setq cmd 'emacs)
6928 (setq cmd (or (cdr (assoc ext apps))
6929 (cdr (assoc t apps)))))
6930 (when (eq cmd 'mailcap)
6931 (require 'mailcap)
6932 (mailcap-parse-mailcaps)
6933 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
6934 (command (mailcap-mime-info mime-type)))
6935 (if (stringp command)
6936 (setq cmd command)
6937 (setq cmd 'emacs))))
6938 (cond
6939 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
6940 (setq cmd (format cmd (concat "\"" file "\"")))
6941 (save-window-excursion
6942 (shell-command (concat cmd " &"))))
6943 ((or (stringp cmd)
6944 (eq cmd 'emacs))
6945 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
6946 (funcall (cdr (assq 'file org-link-frame-setup)) file))
6947 (if line (goto-line line)
6948 (if search (org-link-search search))))
6949 ((consp cmd)
6950 (eval cmd))
6951 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
6952
6953 (defun org-default-apps ()
6954 "Return the default applications for this operating system."
6955 (cond
6956 ((eq system-type 'darwin)
6957 org-file-apps-defaults-macosx)
6958 ((eq system-type 'windows-nt)
6959 org-file-apps-defaults-windowsnt)
6960 (t org-file-apps-defaults-gnu)))
6961
6962 (defun org-expand-file-name (path)
6963 "Replace special path abbreviations and expand the file name."
6964 (expand-file-name path))
6965
6966
6967 (defvar org-insert-link-history nil
6968 "Minibuffer history for links inserted with `org-insert-link'.")
6969
6970 (defvar org-stored-links nil
6971 "Contains the links stored with `org-store-link'.")
6972
6973 ;;;###autoload
6974 (defun org-store-link (arg)
6975 "\\<org-mode-map>Store an org-link to the current location.
6976 This link can later be inserted into an org-buffer with
6977 \\[org-insert-link].
6978 For some link types, a prefix arg is interpreted:
6979 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6980 For file links, arg negates `org-context-in-file-links'."
6981 (interactive "P")
6982 (let (link cpltxt)
6983 (cond
6984
6985 ((eq major-mode 'bbdb-mode)
6986 (setq cpltxt (concat
6987 "bbdb:"
6988 (or (bbdb-record-name (bbdb-current-record))
6989 (bbdb-record-company (bbdb-current-record))))
6990 link (org-make-link cpltxt)))
6991
6992 ((eq major-mode 'calendar-mode)
6993 (let ((cd (calendar-cursor-to-date)))
6994 (setq link
6995 (format-time-string
6996 (car org-time-stamp-formats)
6997 (apply 'encode-time
6998 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6999 nil nil nil))))))
7000
7001 ((or (eq major-mode 'vm-summary-mode)
7002 (eq major-mode 'vm-presentation-mode))
7003 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7004 (vm-follow-summary-cursor)
7005 (save-excursion
7006 (vm-select-folder-buffer)
7007 (let* ((message (car vm-message-pointer))
7008 (folder (buffer-file-name))
7009 (subject (vm-su-subject message))
7010 (author (vm-su-full-name message))
7011 (message-id (vm-su-message-id message)))
7012 (setq folder (abbreviate-file-name folder))
7013 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7014 folder)
7015 (setq folder (replace-match "" t t folder)))
7016 (setq cpltxt (concat author " on: " subject))
7017 (setq link (concat cpltxt "\n "
7018 (org-make-link
7019 "vm:" folder "#" message-id))))))
7020
7021 ((eq major-mode 'wl-summary-mode)
7022 (let* ((msgnum (wl-summary-message-number))
7023 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7024 msgnum 'message-id))
7025 (wl-message-entity (elmo-msgdb-overview-get-entity
7026 msgnum (wl-summary-buffer-msgdb)))
7027 (author (wl-summary-line-from)) ; FIXME: how to get author name?
7028 (subject "???")) ; FIXME: How to get subject of email?
7029 (setq cpltxt (concat author " on: " subject))
7030 (setq link (concat cpltxt "\n "
7031 (org-make-link
7032 "wl:" wl-summary-buffer-folder-name
7033 "#" message-id)))))
7034
7035 ((eq major-mode 'rmail-mode)
7036 (save-excursion
7037 (save-restriction
7038 (rmail-narrow-to-non-pruned-header)
7039 (let ((folder (buffer-file-name))
7040 (message-id (mail-fetch-field "message-id"))
7041 (author (mail-fetch-field "from"))
7042 (subject (mail-fetch-field "subject")))
7043 (setq cpltxt (concat author " on: " subject))
7044 (setq link (concat cpltxt "\n "
7045 (org-make-link
7046 "rmail:" folder "#" message-id)))))))
7047
7048 ((eq major-mode 'gnus-group-mode)
7049 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7050 (gnus-group-group-name)) ; version
7051 ((fboundp 'gnus-group-name)
7052 (gnus-group-name))
7053 (t "???"))))
7054 (setq cpltxt (concat
7055 (if (org-xor arg org-usenet-links-prefer-google)
7056 "http://groups.google.com/groups?group="
7057 "gnus:")
7058 group)
7059 link (org-make-link cpltxt))))
7060
7061 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7062 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7063 (gnus-summary-beginning-of-article)
7064 (let* ((group (car gnus-article-current))
7065 (article (cdr gnus-article-current))
7066 (header (gnus-summary-article-header article))
7067 (author (mail-header-from header))
7068 (message-id (mail-header-id header))
7069 (date (mail-header-date header))
7070 (subject (gnus-summary-subject-string)))
7071 (setq cpltxt (concat author " on: " subject))
7072 (if (org-xor arg org-usenet-links-prefer-google)
7073 (setq link
7074 (concat
7075 cpltxt "\n "
7076 (format "http://groups.google.com/groups?as_umsgid=%s"
7077 (org-fixup-message-id-for-http message-id))))
7078 (setq link (concat cpltxt "\n"
7079 (org-make-link
7080 "gnus:" group
7081 "#" (number-to-string article)))))))
7082
7083 ((eq major-mode 'w3-mode)
7084 (setq cpltxt (url-view-url t)
7085 link (org-make-link cpltxt)))
7086 ((eq major-mode 'w3m-mode)
7087 (setq cpltxt w3m-current-url
7088 link (org-make-link cpltxt)))
7089
7090 ((eq major-mode 'org-mode)
7091 ;; Just link to current headline
7092 (setq cpltxt (concat "file:"
7093 (abbreviate-file-name (buffer-file-name))))
7094 ;; Add a context search string
7095 (when (org-xor org-context-in-file-links arg)
7096 (if (save-excursion
7097 (skip-chars-backward "a-zA-Z<")
7098 (looking-at (concat "<<\\(" org-camel-regexp "\\)>>")))
7099 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7100 (setq cpltxt
7101 (concat cpltxt "::"
7102 (org-make-org-heading-camel
7103 (cond
7104 ((org-on-heading-p) nil)
7105 ((org-region-active-p)
7106 (buffer-substring (region-beginning) (region-end)))
7107 (t (buffer-substring (point-at-bol) (point-at-eol))))
7108 )))))
7109 (setq link (org-make-link cpltxt)))
7110
7111 ((buffer-file-name)
7112 ;; Just link to this file here.
7113 (setq cpltxt (concat "file:"
7114 (abbreviate-file-name (buffer-file-name))))
7115 ;; Add a context string
7116 (when (org-xor org-context-in-file-links arg)
7117 (setq cpltxt
7118 (concat cpltxt "::"
7119 (org-make-org-heading-camel
7120 (if (org-region-active-p)
7121 (buffer-substring (region-beginning) (region-end))
7122 (buffer-substring (point-at-bol) (point-at-eol)))))))
7123 (setq link (org-make-link cpltxt)))
7124
7125 ((interactive-p)
7126 (error "Cannot link to a buffer which is not visiting a file"))
7127
7128 (t (setq link nil)))
7129
7130 (if (and (interactive-p) link)
7131 (progn
7132 (setq org-stored-links
7133 (cons (cons (or cpltxt link) link) org-stored-links))
7134 (message "Stored: %s" (or cpltxt link)))
7135 link)))
7136
7137 (defun org-make-org-heading-camel (&optional string)
7138 "Make a CamelCase string for S or the current headline."
7139 (interactive)
7140 (let ((s (or string (org-get-heading))))
7141 (unless string
7142 ;; We are using a headline, clean up garbage in there.
7143 (if (string-match org-todo-regexp s)
7144 (setq s (replace-match "" t t s)))
7145 (setq s (org-trim s))
7146 (if (string-match (concat "^\\(" org-quote-string "\\|"
7147 org-comment-string "\\)") s)
7148 (setq s (replace-match "" t t s)))
7149 (while (string-match org-ts-regexp s)
7150 (setq s (replace-match "" t t s))))
7151 (while (string-match "[^a-zA-Z_ \t]+" s)
7152 (setq s (replace-match " " t t s)))
7153 (or string (setq s (concat "*" s))) ; Add * for headlines
7154 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7155
7156 (defun org-make-link (&rest strings)
7157 "Concatenate STRINGS, format resulting string with `org-link-format'."
7158 (format org-link-format (apply 'concat strings)))
7159
7160 (defun org-xor (a b)
7161 "Exclusive or."
7162 (if a (not b) b))
7163
7164 (defun org-get-header (header)
7165 "Find a header field in the current buffer."
7166 (save-excursion
7167 (goto-char (point-min))
7168 (let ((case-fold-search t) s)
7169 (cond
7170 ((eq header 'from)
7171 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7172 (setq s (match-string 1)))
7173 (while (string-match "\"" s)
7174 (setq s (replace-match "" t t s)))
7175 (if (string-match "[<(].*" s)
7176 (setq s (replace-match "" t t s))))
7177 ((eq header 'message-id)
7178 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7179 (setq s (match-string 1))))
7180 ((eq header 'subject)
7181 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7182 (setq s (match-string 1)))))
7183 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7184 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7185 s)))
7186
7187
7188 (defun org-fixup-message-id-for-http (s)
7189 "Replace special characters in a message id, so it can be used in an http query."
7190 (while (string-match "<" s)
7191 (setq s (replace-match "%3C" t t s)))
7192 (while (string-match ">" s)
7193 (setq s (replace-match "%3E" t t s)))
7194 (while (string-match "@" s)
7195 (setq s (replace-match "%40" t t s)))
7196 s)
7197
7198 (defun org-insert-link (&optional complete-file)
7199 "Insert a link. At the prompt, enter the link.
7200
7201 Completion can be used to select a link previously stored with
7202 `org-store-link'. When the empty string is entered (i.e. if you just
7203 press RET at the prompt), the link defaults to the most recently
7204 stored link. As SPC triggers completion in the minibuffer, you need to
7205 use M-SPC or C-q SPC to force the insertion of a space character.
7206
7207 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7208 selected using completion. The path to the file will be relative to
7209 the current directory if the file is in the current directory or a
7210 subdirectory. Otherwise, the link will be the absolute path as
7211 completed in the minibuffer (i.e. normally ~/path/to/file).
7212
7213 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7214 is in the current directory or below."
7215 (interactive "P")
7216 (let ((link (if complete-file
7217 (read-file-name "File: ")
7218 (completing-read
7219 "Link: " org-stored-links nil nil nil
7220 org-insert-link-history
7221 (or (car (car org-stored-links))))))
7222 linktxt matched)
7223 (if (or (not link) (equal link ""))
7224 (error "No links available"))
7225 (if complete-file
7226 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7227 (cond
7228 ((equal complete-file '(16))
7229 (insert
7230 (org-make-link
7231 "file:" (abbreviate-file-name (expand-file-name link)))))
7232 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7233 (expand-file-name link))
7234 (insert
7235 (org-make-link
7236 "file:" (match-string 1 (expand-file-name link)))))
7237 (t (insert (org-make-link "file:" link)))))
7238 (setq linktxt (cdr (assoc link org-stored-links)))
7239 (if (not org-keep-stored-link-after-insertion)
7240 (setq org-stored-links (delq (assoc link org-stored-links)
7241 org-stored-links)))
7242 (if (not linktxt) (setq link (org-make-link link)))
7243 (setq link (or linktxt link))
7244 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7245 (let* ((path (match-string 1 link))
7246 (case-fold-search nil)
7247 (search (match-string 2 link)))
7248 (when (save-match-data
7249 (equal (file-truename (buffer-file-name))
7250 (file-truename path)))
7251 (if (save-match-data
7252 (string-match (concat "^" org-camel-regexp "$") search))
7253 (setq link (replace-match search t t link)
7254 matched t)
7255 (setq link (replace-match (concat "<file:::" search ">")
7256 t t link))))))
7257 (let ((lines (org-split-string link "\n")))
7258 (insert (car lines))
7259 (setq matched (or matched (string-match org-link-regexp (car lines))))
7260 (setq lines (cdr lines))
7261 (while lines
7262 (insert "\n")
7263 (if (save-excursion
7264 (beginning-of-line 0)
7265 (looking-at "[ \t]+\\S-"))
7266 (indent-relative))
7267 (setq matched (or matched
7268 (string-match org-link-regexp (car lines))))
7269 (insert (car lines))
7270 (setq lines (cdr lines))))
7271 (unless matched
7272 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7273
7274 ;;; Hooks for remember.el
7275 ;;;###autoload
7276 (defun org-remember-annotation ()
7277 "Return a link to the current location as an annotation for remember.el.
7278 If you are using Org-mode files as target for data storage with
7279 remember.el, then the annotations should include a link compatible with the
7280 conventions in Org-mode. This function returns such a link."
7281 (org-store-link nil))
7282
7283 (defconst org-remember-help
7284 "Select a destination location for the note.
7285 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7286 RET at beg-of-buf -> Append to file as level 2 headline
7287 RET on headline -> Store as sublevel entry to current headline
7288 <left>/<right> -> before/after current headline, same headings level")
7289
7290 ;;;###autoload
7291 (defun org-remember-handler ()
7292 "Store stuff from remember.el into an org file.
7293 First prompts for an org file. If the user just presses return, the value
7294 of `org-default-notes-file' is used.
7295 Then the command offers the headings tree of the selected file in order to
7296 file the text at a specific location.
7297 You can either immediately press RET to get the note appended to the
7298 file, or you can use vertical cursor motion and visibility cycling (TAB) to
7299 find a better place. Then press RET or <left> or <right> in insert the note.
7300
7301 Key Cursor position Note gets inserted
7302 -----------------------------------------------------------------------------
7303 RET buffer-start as level 2 heading at end of file
7304 RET on headline as sublevel of the heading at cursor
7305 RET no heading at cursor position, level taken from context.
7306 Or use prefix arg to specify level manually.
7307 <left> on headline as same level, before current heading
7308 <right> on headline as same level, after current heading
7309
7310 So the fastest way to store the note is to press RET RET to append it to
7311 the default file. This way your current train of thought is not
7312 interrupted, in accordance with the principles of remember.el. But with
7313 little extra effort, you can push it directly to the correct location.
7314
7315 Before being stored away, the function ensures that the text has a
7316 headline, i.e. a first line that starts with a \"*\". If not, a headline
7317 is constructed from the current date and some additional data.
7318
7319 If the variable `org-adapt-indentation' is non-nil, the entire text is
7320 also indented so that it starts in the same column as the headline
7321 \(i.e. after the stars).
7322
7323 See also the variable `org-reverse-note-order'."
7324 (catch 'quit
7325 (let* ((txt (buffer-substring (point-min) (point-max)))
7326 (fastp current-prefix-arg)
7327 (file (if fastp org-default-notes-file (org-get-org-file)))
7328 (visiting (find-buffer-visiting file))
7329 (org-startup-with-deadline-check nil)
7330 (org-startup-folded nil)
7331 spos level indent reversed)
7332 ;; Modify text so that it becomes a nice subtree which can be inserted
7333 ;; into an org tree.
7334 (let* ((lines (split-string txt "\n"))
7335 (first (car lines))
7336 (lines (cdr lines)))
7337 (if (string-match "^\\*+" first)
7338 ;; Is already a headline
7339 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7340 -1) ?\ ))
7341 ;; We need to add a headline: Use time and first buffer line
7342 (setq lines (cons first lines)
7343 first (concat "* " (current-time-string)
7344 " (" (remember-buffer-desc) ")")
7345 indent " "))
7346 (if org-adapt-indentation
7347 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7348 (setq txt (concat first "\n"
7349 (mapconcat 'identity lines "\n"))))
7350 ;; Find the file
7351 (if (not visiting)
7352 (find-file-noselect file))
7353 (with-current-buffer (get-file-buffer file)
7354 (setq reversed (org-notes-order-reversed-p))
7355 (save-excursion
7356 (save-restriction
7357 (widen)
7358 ;; Ask the User for a location
7359 (setq spos (if fastp 1 (org-get-location
7360 (current-buffer)
7361 org-remember-help)))
7362 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7363 ; not handle this note
7364 (goto-char spos)
7365 (cond ((bobp)
7366 ;; Put it at the start or end, as level 2
7367 (save-restriction
7368 (widen)
7369 (goto-char (if reversed (point-min) (point-max)))
7370 (if (not (bolp)) (newline))
7371 (org-paste-subtree (or current-prefix-arg 2) txt)))
7372 ((and (org-on-heading-p nil) (not current-prefix-arg))
7373 ;; Put it below this entry, at the beg/end of the subtree
7374 (org-back-to-heading)
7375 (setq level (outline-level))
7376 (if reversed
7377 (outline-end-of-heading)
7378 (outline-end-of-subtree))
7379 (if (not (bolp)) (newline))
7380 (beginning-of-line 1)
7381 (org-paste-subtree (1+ level) txt))
7382 (t
7383 ;; Put it right there, with automatic level determined by
7384 ;; org-paste-subtree or from prefix arg
7385 (org-paste-subtree current-prefix-arg txt)))
7386 (when remember-save-after-remembering
7387 (save-buffer)
7388 (if (not visiting) (kill-buffer (current-buffer)))))))))
7389 t) ;; return t to indicate that we took care of this note.
7390
7391 (defun org-get-org-file ()
7392 "Read a filename, with default directory `org-directory'."
7393 (let ((default (or org-default-notes-file remember-data-file)))
7394 (read-file-name (format "File name [%s]: " default)
7395 (file-name-as-directory org-directory)
7396 default)))
7397
7398 (defun org-notes-order-reversed-p ()
7399 "Check if the current file should receive notes in reversed order."
7400 (cond
7401 ((not org-reverse-note-order) nil)
7402 ((eq t org-reverse-note-order) t)
7403 ((not (listp org-reverse-note-order)) nil)
7404 (t (catch 'exit
7405 (let ((all org-reverse-note-order)
7406 entry)
7407 (while (setq entry (pop all))
7408 (if (string-match (car entry) (buffer-file-name))
7409 (throw 'exit (cdr entry))))
7410 nil)))))
7411
7412 ;;; Tables
7413
7414 ;; Watch out: Here we are talking about two different kind of tables.
7415 ;; Most of the code is for the tables created with the Org-mode table editor.
7416 ;; Sometimes, we talk about tables created and edited with the table.el
7417 ;; Emacs package. We call the former org-type tables, and the latter
7418 ;; table.el-type tables.
7419
7420
7421 (defun org-before-change-function (beg end)
7422 "Every change indicates that a table might need an update."
7423 (setq org-table-may-need-update t))
7424
7425 (defconst org-table-line-regexp "^[ \t]*|"
7426 "Detects an org-type table line.")
7427 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7428 "Detects an org-type table line.")
7429 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7430 "Detects a table line marked for automatic recalculation.")
7431 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7432 "Detects a table line marked for automatic recalculation.")
7433 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7434 "Detects a table line marked for automatic recalculation.")
7435 (defconst org-table-hline-regexp "^[ \t]*|-"
7436 "Detects an org-type table hline.")
7437 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7438 "Detects a table-type table hline.")
7439 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7440 "Detects an org-type or table-type table.")
7441 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7442 "Searching from within a table (any type) this finds the first line
7443 outside the table.")
7444 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7445 "Searching from within a table (any type) this finds the first line
7446 outside the table.")
7447
7448 (defun org-table-create-with-table.el ()
7449 "Use the table.el package to insert a new table.
7450 If there is already a table at point, convert between Org-mode tables
7451 and table.el tables."
7452 (interactive)
7453 (require 'table)
7454 (cond
7455 ((org-at-table.el-p)
7456 (if (y-or-n-p "Convert table to Org-mode table? ")
7457 (org-table-convert)))
7458 ((org-at-table-p)
7459 (if (y-or-n-p "Convert table to table.el table? ")
7460 (org-table-convert)))
7461 (t (call-interactively 'table-insert))))
7462
7463 (defun org-table-create (&optional size)
7464 "Query for a size and insert a table skeleton.
7465 SIZE is a string Columns x Rows like for example \"3x2\"."
7466 (interactive "P")
7467 (unless size
7468 (setq size (read-string
7469 (concat "Table size Columns x Rows [e.g. "
7470 org-table-default-size "]: ")
7471 "" nil org-table-default-size)))
7472
7473 (let* ((pos (point))
7474 (indent (make-string (current-column) ?\ ))
7475 (split (org-split-string size " *x *"))
7476 (rows (string-to-number (nth 1 split)))
7477 (columns (string-to-number (car split)))
7478 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7479 "\n")))
7480 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7481 (point-at-bol) (point)))
7482 (beginning-of-line 1)
7483 (newline))
7484 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7485 (dotimes (i rows) (insert line))
7486 (goto-char pos)
7487 (if (> rows 1)
7488 ;; Insert a hline after the first row.
7489 (progn
7490 (end-of-line 1)
7491 (insert "\n|-")
7492 (goto-char pos)))
7493 (org-table-align)))
7494
7495 (defun org-table-convert-region (beg0 end0 nspace)
7496 "Convert region to a table.
7497 The region goes from BEG0 to END0, but these borders will be moved
7498 slightly, to make sure a beginning of line in the first line is included.
7499 When NSPACE is non-nil, it indicates the minimum number of spaces that
7500 separate columns (default: just one space)."
7501 (let* ((beg (min beg0 end0))
7502 (end (max beg0 end0))
7503 (tabsep t)
7504 re)
7505 (goto-char beg)
7506 (beginning-of-line 1)
7507 (setq beg (move-marker (make-marker) (point)))
7508 (goto-char end)
7509 (if (bolp) (backward-char 1) (end-of-line 1))
7510 (setq end (move-marker (make-marker) (point)))
7511 ;; Lets see if this is tab-separated material. If every nonempty line
7512 ;; contains a tab, we will assume that it is tab-separated material
7513 (if nspace
7514 (setq tabsep nil)
7515 (goto-char beg)
7516 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7517 (if nspace (setq tabsep nil))
7518 (if tabsep
7519 (setq re "^\\|\t")
7520 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7521 (max 1 (prefix-numeric-value nspace)))))
7522 (goto-char beg)
7523 (while (re-search-forward re end t)
7524 (replace-match "|" t t))
7525 (goto-char beg)
7526 (insert " ")
7527 (org-table-align)))
7528
7529 (defun org-table-import (file arg)
7530 "Import FILE as a table.
7531 The file is assumed to be tab-separated. Such files can be produced by most
7532 spreadsheet and database applications. If no tabs (at least one per line)
7533 are found, lines will be split on whitespace into fields."
7534 (interactive "f\nP")
7535 (or (bolp) (newline))
7536 (let ((beg (point))
7537 (pm (point-max)))
7538 (insert-file-contents file)
7539 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7540
7541 (defun org-table-export ()
7542 "Export table as a tab-separated file.
7543 Such a file can be imported into a spreadsheet program like Excel."
7544 (interactive)
7545 (let* ((beg (org-table-begin))
7546 (end (org-table-end))
7547 (table (buffer-substring beg end))
7548 (file (read-file-name "Export table to: "))
7549 buf)
7550 (unless (or (not (file-exists-p file))
7551 (y-or-n-p (format "Overwrite file %s? " file)))
7552 (error "Abort"))
7553 (with-current-buffer (find-file-noselect file)
7554 (setq buf (current-buffer))
7555 (erase-buffer)
7556 (fundamental-mode)
7557 (insert table)
7558 (goto-char (point-min))
7559 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7560 (replace-match "" t t)
7561 (end-of-line 1))
7562 (goto-char (point-min))
7563 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7564 (replace-match "" t t)
7565 (goto-char (min (1+ (point)) (point-max))))
7566 (goto-char (point-min))
7567 (while (re-search-forward "^-[-+]*$" nil t)
7568 (replace-match "")
7569 (if (looking-at "\n")
7570 (delete-char 1)))
7571 (goto-char (point-min))
7572 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7573 (replace-match "\t" t t))
7574 (save-buffer))
7575 (kill-buffer buf)))
7576
7577 (defvar org-table-aligned-begin-marker (make-marker)
7578 "Marker at the beginning of the table last aligned.
7579 Used to check if cursor still is in that table, to minimize realignment.")
7580 (defvar org-table-aligned-end-marker (make-marker)
7581 "Marker at the end of the table last aligned.
7582 Used to check if cursor still is in that table, to minimize realignment.")
7583 (defvar org-table-last-alignment nil
7584 "List of flags for flushright alignment, from the last re-alignment.
7585 This is being used to correctly align a single field after TAB or RET.")
7586 ;; FIXME: The following is currently not used.
7587 (defvar org-table-last-column-widths nil
7588 "List of max width of fields in each column.
7589 This is being used to correctly align a single field after TAB or RET.")
7590
7591 (defvar org-last-recalc-line nil)
7592
7593 (defun org-table-align ()
7594 "Align the table at point by aligning all vertical bars."
7595 (interactive)
7596 ;; (message "align") (sit-for 2)
7597 (let* (
7598 ;; Limits of table
7599 (beg (org-table-begin))
7600 (end (org-table-end))
7601 ;; Current cursor position
7602 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7603 (colpos (org-table-current-column))
7604 (winstart (window-start))
7605 text lines (new "") lengths l typenums ty fields maxfields i
7606 column
7607 (indent "") cnt frac
7608 rfmt hfmt
7609 (spaces (if (org-in-invisibility-spec-p '(org-table))
7610 org-table-spaces-around-invisible-separators
7611 org-table-spaces-around-separators))
7612 (sp1 (car spaces))
7613 (sp2 (cdr spaces))
7614 (rfmt1 (concat
7615 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7616 (hfmt1 (concat
7617 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7618 emptystrings)
7619 (untabify beg end)
7620 ;; (message "Aligning table...")
7621 ;; Get the rows
7622 (setq lines (org-split-string
7623 (buffer-substring-no-properties beg end) "\n"))
7624 ;; Store the indentation of the first line
7625 (if (string-match "^ *" (car lines))
7626 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7627 ;; Mark the hlines
7628 (setq lines (mapcar (lambda (l)
7629 (if (string-match "^ *|-" l)
7630 nil
7631 (if (string-match "[ \t]+$" l)
7632 (substring l 0 (match-beginning 0))
7633 l)))
7634 lines))
7635 ;; Get the data fields
7636 (setq fields (mapcar
7637 (lambda (l)
7638 (org-split-string l " *| *"))
7639 (delq nil (copy-sequence lines))))
7640 ;; How many fields in the longest line?
7641 (condition-case nil
7642 (setq maxfields (apply 'max (mapcar 'length fields)))
7643 (error
7644 (kill-region beg end)
7645 (org-table-create org-table-default-size)
7646 (error "Empty table - created default table")))
7647 ;; A list of empty string to fill any short rows on output
7648 (setq emptystrings (make-list maxfields ""))
7649 ;; Get the maximum length of a field and the most common datatype
7650 ;; for each column
7651 (setq i -1)
7652 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7653 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7654 ;; maximum length
7655 (push (apply 'max 1 (mapcar 'string-width column)) lengths)
7656 ;; compute the fraction stepwise, ignoring empty fields
7657 (setq cnt 0 frac 0.0)
7658 (mapcar
7659 (lambda (x)
7660 (if (equal x "")
7661 nil
7662 (setq frac ( / (+ (* frac cnt)
7663 (if (string-match org-table-number-regexp x) 1 0))
7664 (setq cnt (1+ cnt))))))
7665 column)
7666 (push (>= frac org-table-number-fraction) typenums))
7667 (setq lengths (nreverse lengths)
7668 typenums (nreverse typenums))
7669 (setq org-table-last-alignment typenums
7670 org-table-last-column-widths lengths)
7671 ;; Compute the formats needed for output of the table
7672 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7673 (while (setq l (pop lengths))
7674 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7675 (setq rfmt (concat rfmt (format rfmt1 ty l))
7676 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7677 (setq rfmt (concat rfmt "\n")
7678 hfmt (concat (substring hfmt 0 -1) "|\n"))
7679 ;; Produce the new table
7680 ;;(while lines
7681 ;; (setq l (pop lines))
7682 ;; (if l
7683 ;; (setq new (concat new (apply 'format rfmt
7684 ;; (append (pop fields) emptystrings))))
7685 ;; (setq new (concat new hfmt))))
7686 (setq new (mapconcat
7687 (lambda (l)
7688 (if l (apply 'format rfmt
7689 (append (pop fields) emptystrings))
7690 hfmt))
7691 lines ""))
7692 ;; Replace the old one
7693 (delete-region beg end)
7694 (move-marker end nil)
7695 (move-marker org-table-aligned-begin-marker (point))
7696 (insert new)
7697 (move-marker org-table-aligned-end-marker (point))
7698 ;; Try to move to the old location (approximately)
7699 (goto-line linepos)
7700 (set-window-start (selected-window) winstart 'noforce)
7701 (org-table-goto-column colpos)
7702 (setq org-table-may-need-update nil)
7703 (if (org-in-invisibility-spec-p '(org-table))
7704 (org-table-add-invisible-to-vertical-lines))
7705 ))
7706
7707 (defun org-table-begin (&optional table-type)
7708 "Find the beginning of the table and return its position.
7709 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7710 (save-excursion
7711 (if (not (re-search-backward
7712 (if table-type org-table-any-border-regexp
7713 org-table-border-regexp)
7714 nil t))
7715 (error "Can't find beginning of table")
7716 (goto-char (match-beginning 0))
7717 (beginning-of-line 2)
7718 (point))))
7719
7720 (defun org-table-end (&optional table-type)
7721 "Find the end of the table and return its position.
7722 With argument TABLE-TYPE, go to the end of a table.el-type table."
7723 (save-excursion
7724 (if (not (re-search-forward
7725 (if table-type org-table-any-border-regexp
7726 org-table-border-regexp)
7727 nil t))
7728 (goto-char (point-max))
7729 (goto-char (match-beginning 0)))
7730 (point-marker)))
7731
7732 (defun org-table-justify-field-maybe (&optional new)
7733 "Justify the current field, text to left, number to right.
7734 Optional argument NEW may specify text to replace the current field content."
7735 (cond
7736 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7737 ((org-at-table-hline-p)
7738 ;; FIXME: I used to enforce realign here, but I think this is not needed.
7739 ;; (setq org-table-may-need-update t)
7740 )
7741 ((and (not new)
7742 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7743 (current-buffer)))
7744 (< (point) org-table-aligned-begin-marker)
7745 (>= (point) org-table-aligned-end-marker)))
7746 ;; This is not the same table, force a full re-align
7747 (setq org-table-may-need-update t))
7748 (t ;; realign the current field, based on previous full realign
7749 (let* ((pos (point)) s
7750 (col (org-table-current-column))
7751 (num (nth (1- col) org-table-last-alignment))
7752 l f n o e)
7753 (when (> col 0)
7754 (skip-chars-backward "^|\n")
7755 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7756 (progn
7757 (setq s (match-string 1)
7758 o (match-string 0)
7759 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7760 e (not (= (match-beginning 2) (match-end 2))))
7761 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7762 l (if e "|" (setq org-table-may-need-update t) ""))
7763 n (format f s t t))
7764 (if new
7765 (if (<= (length new) l)
7766 (setq n (format f new t t)) ;; FIXME: why t t?????
7767 (setq n (concat new "|") org-table-may-need-update t)))
7768 (or (equal n o)
7769 (let (org-table-may-need-update)
7770 (replace-match n))))
7771 (setq org-table-may-need-update t))
7772 (goto-char pos))))))
7773
7774 (defun org-table-next-field ()
7775 "Go to the next field in the current table, creating new lines as needed.
7776 Before doing so, re-align the table if necessary."
7777 (interactive)
7778 (org-table-maybe-eval-formula)
7779 (org-table-maybe-recalculate-line)
7780 (if (and org-table-automatic-realign
7781 org-table-may-need-update)
7782 (org-table-align))
7783 (let ((end (org-table-end)))
7784 (if (org-at-table-hline-p)
7785 (end-of-line 1))
7786 (condition-case nil
7787 (progn
7788 (re-search-forward "|" end)
7789 (if (looking-at "[ \t]*$")
7790 (re-search-forward "|" end))
7791 (if (and (looking-at "-")
7792 org-table-tab-jumps-over-hlines
7793 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7794 (goto-char (match-beginning 1)))
7795 (if (looking-at "-")
7796 (progn
7797 (beginning-of-line 0)
7798 (org-table-insert-row 'below))
7799 (if (looking-at " ") (forward-char 1))))
7800 (error
7801 (org-table-insert-row 'below)))))
7802
7803 (defun org-table-previous-field ()
7804 "Go to the previous field in the table.
7805 Before doing so, re-align the table if necessary."
7806 (interactive)
7807 (org-table-justify-field-maybe)
7808 (org-table-maybe-recalculate-line)
7809 (if (and org-table-automatic-realign
7810 org-table-may-need-update)
7811 (org-table-align))
7812 (if (org-at-table-hline-p)
7813 (end-of-line 1))
7814 (re-search-backward "|" (org-table-begin))
7815 (re-search-backward "|" (org-table-begin))
7816 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7817 (re-search-backward "|" (org-table-begin)))
7818 (if (looking-at "| ?")
7819 (goto-char (match-end 0))))
7820
7821 (defun org-table-next-row ()
7822 "Go to the next row (same column) in the current table.
7823 Before doing so, re-align the table if necessary."
7824 (interactive)
7825 (org-table-maybe-eval-formula)
7826 (org-table-maybe-recalculate-line)
7827 (if (or (looking-at "[ \t]*$")
7828 (save-excursion (skip-chars-backward " \t") (bolp)))
7829 (newline)
7830 (if (and org-table-automatic-realign
7831 org-table-may-need-update)
7832 (org-table-align))
7833 (let ((col (org-table-current-column)))
7834 (beginning-of-line 2)
7835 (if (or (not (org-at-table-p))
7836 (org-at-table-hline-p))
7837 (progn
7838 (beginning-of-line 0)
7839 (org-table-insert-row 'below)))
7840 (org-table-goto-column col)
7841 (skip-chars-backward "^|\n\r")
7842 (if (looking-at " ") (forward-char 1)))))
7843
7844 (defun org-table-copy-down (n)
7845 "Copy a field down in the current column.
7846 If the field at the cursor is empty, copy into it the content of the nearest
7847 non-empty field above. With argument N, use the Nth non-empty field.
7848 If the current field is not empty, it is copied down to the next row, and
7849 the cursor is moved with it. Therefore, repeating this command causes the
7850 column to be filled row-by-row.
7851 If the variable `org-table-copy-increment' is non-nil and the field is an
7852 integer, it will be incremented while copying."
7853 (interactive "p")
7854 (let* ((colpos (org-table-current-column))
7855 (field (org-table-get-field))
7856 (non-empty (string-match "[^ \t]" field))
7857 (beg (org-table-begin))
7858 txt)
7859 (org-table-check-inside-data-field)
7860 (if non-empty
7861 (progn
7862 (setq txt (org-trim field))
7863 (org-table-next-row)
7864 (org-table-blank-field))
7865 (save-excursion
7866 (setq txt
7867 (catch 'exit
7868 (while (progn (beginning-of-line 1)
7869 (re-search-backward org-table-dataline-regexp
7870 beg t))
7871 (org-table-goto-column colpos t)
7872 (if (and (looking-at
7873 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7874 (= (setq n (1- n)) 0))
7875 (throw 'exit (match-string 1))))))))
7876 (if txt
7877 (progn
7878 (if (and org-table-copy-increment
7879 (string-match "^[0-9]+$" txt))
7880 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7881 (insert txt)
7882 (org-table-maybe-recalculate-line)
7883 (org-table-align))
7884 (error "No non-empty field found"))))
7885
7886 (defun org-table-check-inside-data-field ()
7887 "Is point inside a table data field?
7888 I.e. not on a hline or before the first or after the last column?
7889 This actually throws an error, so it aborts the current command."
7890 (if (or (not (org-at-table-p))
7891 (= (org-table-current-column) 0)
7892 (org-at-table-hline-p)
7893 (looking-at "[ \t]*$"))
7894 (error "Not in table data field")))
7895
7896 (defvar org-table-clip nil
7897 "Clipboard for table regions.")
7898
7899 (defun org-table-blank-field ()
7900 "Blank the current table field or active region."
7901 (interactive)
7902 (org-table-check-inside-data-field)
7903 (if (and (interactive-p) (org-region-active-p))
7904 (let (org-table-clip)
7905 (org-table-cut-region (region-beginning) (region-end)))
7906 (skip-chars-backward "^|")
7907 (backward-char 1)
7908 (if (looking-at "|[^|\n]+")
7909 (let* ((pos (match-beginning 0))
7910 (match (match-string 0))
7911 (len (string-width match)))
7912 (replace-match (concat "|" (make-string (1- len) ?\ )))
7913 (goto-char (+ 2 pos))
7914 (substring match 1)))))
7915
7916 (defun org-table-get-field (&optional n replace)
7917 "Return the value of the field in column N of current row.
7918 N defaults to current field.
7919 If REPLACE is a string, replace field with this value. The return value
7920 is always the old value."
7921 (and n (org-table-goto-column n))
7922 (skip-chars-backward "^|\n")
7923 (backward-char 1)
7924 (if (looking-at "|[^|\r\n]*")
7925 (let* ((pos (match-beginning 0))
7926 (val (buffer-substring (1+ pos) (match-end 0))))
7927 (if replace
7928 (replace-match (concat "|" replace)))
7929 (goto-char (min (point-at-eol) (+ 2 pos)))
7930 val)
7931 (forward-char 1) ""))
7932
7933 (defun org-table-current-column ()
7934 "Find out which column we are in.
7935 When called interactively, column is also displayed in echo area."
7936 (interactive)
7937 (if (interactive-p) (org-table-check-inside-data-field))
7938 (save-excursion
7939 (let ((cnt 0) (pos (point)))
7940 (beginning-of-line 1)
7941 (while (search-forward "|" pos t)
7942 (setq cnt (1+ cnt)))
7943 (if (interactive-p) (message "This is table column %d" cnt))
7944 cnt)))
7945
7946 (defun org-table-goto-column (n &optional on-delim force)
7947 "Move the cursor to the Nth column in the current table line.
7948 With optional argument ON-DELIM, stop with point before the left delimiter
7949 of the field.
7950 If there are less than N fields, just go to after the last delimiter.
7951 However, when FORCE is non-nil, create new columns if necessary."
7952 (interactive "p")
7953 (let ((pos (point-at-eol)))
7954 (beginning-of-line 1)
7955 (when (> n 0)
7956 (while (and (> (setq n (1- n)) -1)
7957 (or (search-forward "|" pos t)
7958 (and force
7959 (progn (end-of-line 1)
7960 (skip-chars-backward "^|")
7961 (insert " | "))))))
7962 ; (backward-char 2) t)))))
7963 (when (and force (not (looking-at ".*|")))
7964 (save-excursion (end-of-line 1) (insert " | ")))
7965 (if on-delim
7966 (backward-char 1)
7967 (if (looking-at " ") (forward-char 1))))))
7968
7969 (defun org-at-table-p (&optional table-type)
7970 "Return t if the cursor is inside an org-type table.
7971 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7972 (if org-enable-table-editor
7973 (save-excursion
7974 (beginning-of-line 1)
7975 (looking-at (if table-type org-table-any-line-regexp
7976 org-table-line-regexp)))
7977 nil))
7978
7979 (defun org-at-table.el-p ()
7980 "Return t if and only if we are at a table.el table."
7981 (and (org-at-table-p 'any)
7982 (save-excursion
7983 (goto-char (org-table-begin 'any))
7984 (looking-at org-table1-hline-regexp))))
7985
7986 (defun org-table-recognize-table.el ()
7987 "If there is a table.el table nearby, recognize it and move into it."
7988 (if org-table-tab-recognizes-table.el
7989 (if (org-at-table.el-p)
7990 (progn
7991 (beginning-of-line 1)
7992 (if (looking-at org-table-dataline-regexp)
7993 nil
7994 (if (looking-at org-table1-hline-regexp)
7995 (progn
7996 (beginning-of-line 2)
7997 (if (looking-at org-table-any-border-regexp)
7998 (beginning-of-line -1)))))
7999 (if (re-search-forward "|" (org-table-end t) t)
8000 (progn
8001 (require 'table)
8002 (if (table--at-cell-p (point))
8003 t
8004 (message "recognizing table.el table...")
8005 (table-recognize-table)
8006 (message "recognizing table.el table...done")))
8007 (error "This should not happen..."))
8008 t)
8009 nil)
8010 nil))
8011
8012 (defun org-at-table-hline-p ()
8013 "Return t if the cursor is inside a hline in a table."
8014 (if org-enable-table-editor
8015 (save-excursion
8016 (beginning-of-line 1)
8017 (looking-at org-table-hline-regexp))
8018 nil))
8019
8020 (defun org-table-insert-column ()
8021 "Insert a new column into the table."
8022 (interactive)
8023 (if (not (org-at-table-p))
8024 (error "Not at a table"))
8025 (org-table-find-dataline)
8026 (let* ((col (max 1 (org-table-current-column)))
8027 (beg (org-table-begin))
8028 (end (org-table-end))
8029 ;; Current cursor position
8030 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8031 (colpos col))
8032 (goto-char beg)
8033 (while (< (point) end)
8034 (if (org-at-table-hline-p)
8035 nil
8036 (org-table-goto-column col t)
8037 (insert "| "))
8038 (beginning-of-line 2))
8039 (move-marker end nil)
8040 (goto-line linepos)
8041 (org-table-goto-column colpos)
8042 (org-table-align)
8043 (org-table-modify-formulas 'insert col)))
8044
8045 (defun org-table-find-dataline ()
8046 "Find a dataline in the current table, which is needed for column commands."
8047 (if (and (org-at-table-p)
8048 (not (org-at-table-hline-p)))
8049 t
8050 (let ((col (current-column))
8051 (end (org-table-end)))
8052 (move-to-column col)
8053 (while (and (< (point) end)
8054 (or (not (= (current-column) col))
8055 (org-at-table-hline-p)))
8056 (beginning-of-line 2)
8057 (move-to-column col))
8058 (if (and (org-at-table-p)
8059 (not (org-at-table-hline-p)))
8060 t
8061 (error
8062 "Please position cursor in a data line for column operations")))))
8063
8064 (defun org-table-delete-column ()
8065 "Delete a column into the table."
8066 (interactive)
8067 (if (not (org-at-table-p))
8068 (error "Not at a table"))
8069 (org-table-find-dataline)
8070 (org-table-check-inside-data-field)
8071 (let* ((col (org-table-current-column))
8072 (beg (org-table-begin))
8073 (end (org-table-end))
8074 ;; Current cursor position
8075 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8076 (colpos col))
8077 (goto-char beg)
8078 (while (< (point) end)
8079 (if (org-at-table-hline-p)
8080 nil
8081 (org-table-goto-column col t)
8082 (and (looking-at "|[^|\n]+|")
8083 (replace-match "|")))
8084 (beginning-of-line 2))
8085 (move-marker end nil)
8086 (goto-line linepos)
8087 (org-table-goto-column colpos)
8088 (org-table-align)
8089 (org-table-modify-formulas 'remove col)))
8090
8091 (defun org-table-move-column-right ()
8092 "Move column to the right."
8093 (interactive)
8094 (org-table-move-column nil))
8095 (defun org-table-move-column-left ()
8096 "Move column to the left."
8097 (interactive)
8098 (org-table-move-column 'left))
8099
8100 (defun org-table-move-column (&optional left)
8101 "Move the current column to the right. With arg LEFT, move to the left."
8102 (interactive "P")
8103 (if (not (org-at-table-p))
8104 (error "Not at a table"))
8105 (org-table-find-dataline)
8106 (org-table-check-inside-data-field)
8107 (let* ((col (org-table-current-column))
8108 (col1 (if left (1- col) col))
8109 (beg (org-table-begin))
8110 (end (org-table-end))
8111 ;; Current cursor position
8112 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8113 (colpos (if left (1- col) (1+ col))))
8114 (if (and left (= col 1))
8115 (error "Cannot move column further left"))
8116 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8117 (error "Cannot move column further right"))
8118 (goto-char beg)
8119 (while (< (point) end)
8120 (if (org-at-table-hline-p)
8121 nil
8122 (org-table-goto-column col1 t)
8123 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8124 (replace-match "|\\2|\\1|")))
8125 (beginning-of-line 2))
8126 (move-marker end nil)
8127 (goto-line linepos)
8128 (org-table-goto-column colpos)
8129 (org-table-align)
8130 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8131
8132 (defun org-table-move-row-down ()
8133 "Move table row down."
8134 (interactive)
8135 (org-table-move-row nil))
8136 (defun org-table-move-row-up ()
8137 "Move table row up."
8138 (interactive)
8139 (org-table-move-row 'up))
8140
8141 (defun org-table-move-row (&optional up)
8142 "Move the current table line down. With arg UP, move it up."
8143 (interactive "P")
8144 (let ((col (current-column))
8145 (pos (point))
8146 (tonew (if up 0 2))
8147 txt)
8148 (beginning-of-line tonew)
8149 (if (not (org-at-table-p))
8150 (progn
8151 (goto-char pos)
8152 (error "Cannot move row further")))
8153 (goto-char pos)
8154 (beginning-of-line 1)
8155 (setq pos (point))
8156 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8157 (delete-region (point) (1+ (point-at-eol)))
8158 (beginning-of-line tonew)
8159 (insert txt)
8160 (beginning-of-line 0)
8161 (move-to-column col)))
8162
8163 (defun org-table-insert-row (&optional arg)
8164 "Insert a new row above the current line into the table.
8165 With prefix ARG, insert below the current line."
8166 (interactive "P")
8167 (if (not (org-at-table-p))
8168 (error "Not at a table"))
8169 (let* ((line
8170 (org-expand-wide-chars
8171 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8172 new)
8173 (if (string-match "^[ \t]*|-" line)
8174 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8175 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8176 ;; Fix the first field if necessary
8177 (setq new (concat new))
8178 (if (string-match "^[ \t]*| *[#$] *|" line)
8179 (setq new (replace-match (match-string 0 line) t t new)))
8180 (beginning-of-line (if arg 2 1))
8181 (let (org-table-may-need-update)
8182 (insert-before-markers new)
8183 (insert-before-markers "\n"))
8184 (beginning-of-line 0)
8185 (re-search-forward "| ?" (point-at-eol) t)
8186 (and org-table-may-need-update (org-table-align))))
8187
8188 (defun org-table-insert-hline (&optional arg)
8189 "Insert a horizontal-line below the current line into the table.
8190 With prefix ARG, insert above the current line."
8191 (interactive "P")
8192 (if (not (org-at-table-p))
8193 (error "Not at a table"))
8194 (let ((line
8195 (org-expand-wide-chars
8196 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8197 (col (current-column))
8198 start)
8199 (if (string-match "^[ \t]*|-" line)
8200 (setq line
8201 (mapcar (lambda (x) (if (member x '(?| ?+))
8202 (prog1 (if start ?+ ?|) (setq start t))
8203 (if start ?- ?\ )))
8204 line))
8205 (setq line
8206 (mapcar (lambda (x) (if (equal x ?|)
8207 (prog1 (if start ?+ ?|) (setq start t))
8208 (if start ?- ?\ )))
8209 line)))
8210 (beginning-of-line (if arg 1 2))
8211 (apply 'insert line)
8212 (if (equal (char-before (point)) ?+)
8213 (progn (backward-delete-char 1) (insert "|")))
8214 (insert "\n")
8215 (beginning-of-line (if arg 1 -1))
8216 (move-to-column col)))
8217
8218 (defun org-expand-wide-chars (s)
8219 "Expand wide characters to spaces."
8220 (let (w a)
8221 (mapconcat
8222 (lambda (x)
8223 (if (> (setq w (string-width (setq a (char-to-string x)))) 1)
8224 (make-string w ?\ )
8225 a))
8226 s "")))
8227
8228 (defun org-table-kill-row ()
8229 "Delete the current row or horizontal line from the table."
8230 (interactive)
8231 (if (not (org-at-table-p))
8232 (error "Not at a table"))
8233 (let ((col (current-column)))
8234 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8235 (if (not (org-at-table-p)) (beginning-of-line 0))
8236 (move-to-column col)))
8237
8238 (defun org-table-sort-lines (beg end numericp)
8239 "Sort table lines in region.
8240 Point and mark define the first and last line to include. Both point and
8241 mark should be in the column that is used for sorting. For example, to
8242 sort according to column 3, put the mark in the first line to sort, in
8243 table column 3. Put point into the last line to be included in the sorting,
8244 also in table column 3. The command will prompt for the sorting method (n for
8245 numerical, a for alphanumeric)."
8246 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8247 (setq numericp (string-match "[nN]" numericp))
8248 (org-table-align) ;; Just to be safe
8249 (let* (bcol ecol cmp column lns)
8250 (goto-char beg)
8251 (org-table-check-inside-data-field)
8252 (setq column (org-table-current-column)
8253 beg (move-marker (make-marker) (point-at-bol)))
8254 (goto-char end)
8255 (org-table-check-inside-data-field)
8256 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8257 (untabify beg end)
8258 (goto-char beg)
8259 (org-table-goto-column column)
8260 (skip-chars-backward "^|")
8261 (setq bcol (current-column))
8262 (org-table-goto-column (1+ column))
8263 (skip-chars-backward "^|")
8264 (setq ecol (1- (current-column)))
8265 (setq cmp (if numericp
8266 (lambda (a b) (< (car a) (car b)))
8267 (lambda (a b) (string< (car a) (car b)))))
8268 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8269 (split-string (buffer-substring beg end) "\n")))
8270 (if numericp
8271 (setq lns (mapcar (lambda(x)
8272 (cons (string-to-number (car x)) (cdr x)))
8273 lns)))
8274 (delete-region beg end)
8275 (move-marker beg nil)
8276 (move-marker end nil)
8277 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8278 (message "%d lines sorted %s based on column %d"
8279 (length lns)
8280 (if numericp "numerically" "alphabetically") column)))
8281
8282 (defun org-table-cut-region (beg end)
8283 "Copy region in table to the clipboard and blank all relevant fields."
8284 (interactive "r")
8285 (org-table-copy-region beg end 'cut))
8286
8287 (defun org-table-copy-region (beg end &optional cut)
8288 "Copy rectangular region in table to clipboard.
8289 A special clipboard is used which can only be accessed
8290 with `org-table-paste-rectangle'."
8291 (interactive "rP")
8292 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8293 region cols
8294 (rpl (if cut " " nil)))
8295 (goto-char beg)
8296 (org-table-check-inside-data-field)
8297 (setq l01 (count-lines (point-min) (point))
8298 c01 (org-table-current-column))
8299 (goto-char end)
8300 (org-table-check-inside-data-field)
8301 (setq l02 (count-lines (point-min) (point))
8302 c02 (org-table-current-column))
8303 (setq l1 (min l01 l02) l2 (max l01 l02)
8304 c1 (min c01 c02) c2 (max c01 c02))
8305 (catch 'exit
8306 (while t
8307 (catch 'nextline
8308 (if (> l1 l2) (throw 'exit t))
8309 (goto-line l1)
8310 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8311 (setq cols nil ic1 c1 ic2 c2)
8312 (while (< ic1 (1+ ic2))
8313 (push (org-table-get-field ic1 rpl) cols)
8314 (setq ic1 (1+ ic1)))
8315 (push (nreverse cols) region)
8316 (setq l1 (1+ l1)))))
8317 (setq org-table-clip (nreverse region))
8318 (if cut (org-table-align))
8319 org-table-clip))
8320
8321 (defun org-table-paste-rectangle ()
8322 "Paste a rectangular region into a table.
8323 The upper right corner ends up in the current field. All involved fields
8324 will be overwritten. If the rectangle does not fit into the present table,
8325 the table is enlarged as needed. The process ignores horizontal separator
8326 lines."
8327 (interactive)
8328 (unless (and org-table-clip (listp org-table-clip))
8329 (error "First cut/copy a region to paste!"))
8330 (org-table-check-inside-data-field)
8331 (let* ((clip org-table-clip)
8332 (line (count-lines (point-min) (point)))
8333 (col (org-table-current-column))
8334 (org-enable-table-editor t)
8335 (org-table-automatic-realign nil)
8336 c cols field)
8337 (while (setq cols (pop clip))
8338 (while (org-at-table-hline-p) (beginning-of-line 2))
8339 (if (not (org-at-table-p))
8340 (progn (end-of-line 0) (org-table-next-field)))
8341 (setq c col)
8342 (while (setq field (pop cols))
8343 (org-table-goto-column c nil 'force)
8344 (org-table-get-field nil field)
8345 (setq c (1+ c)))
8346 (beginning-of-line 2))
8347 (goto-line line)
8348 (org-table-goto-column col)
8349 (org-table-align)))
8350
8351 (defun org-table-convert ()
8352 "Convert from `org-mode' table to table.el and back.
8353 Obviously, this only works within limits. When an Org-mode table is
8354 converted to table.el, all horizontal separator lines get lost, because
8355 table.el uses these as cell boundaries and has no notion of horizontal lines.
8356 A table.el table can be converted to an Org-mode table only if it does not
8357 do row or column spanning. Multiline cells will become multiple cells.
8358 Beware, Org-mode does not test if the table can be successfully converted - it
8359 blindly applies a recipe that works for simple tables."
8360 (interactive)
8361 (require 'table)
8362 (if (org-at-table.el-p)
8363 ;; convert to Org-mode table
8364 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8365 (end (move-marker (make-marker) (org-table-end t))))
8366 (table-unrecognize-region beg end)
8367 (goto-char beg)
8368 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8369 (replace-match ""))
8370 (goto-char beg))
8371 (if (org-at-table-p)
8372 ;; convert to table.el table
8373 (let ((beg (move-marker (make-marker) (org-table-begin)))
8374 (end (move-marker (make-marker) (org-table-end))))
8375 ;; first, get rid of all horizontal lines
8376 (goto-char beg)
8377 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8378 (replace-match ""))
8379 ;; insert a hline before first
8380 (goto-char beg)
8381 (org-table-insert-hline 'above)
8382 (beginning-of-line -1)
8383 ;; insert a hline after each line
8384 (while (progn (beginning-of-line 3) (< (point) end))
8385 (org-table-insert-hline))
8386 (goto-char beg)
8387 (setq end (move-marker end (org-table-end)))
8388 ;; replace "+" at beginning and ending of hlines
8389 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8390 (replace-match "\\1+-"))
8391 (goto-char beg)
8392 (while (re-search-forward "-|[ \t]*$" end t)
8393 (replace-match "-+"))
8394 (goto-char beg)))))
8395
8396 (defun org-table-wrap-region (arg)
8397 "Wrap several fields in a column like a paragraph.
8398 This is useful if you'd like to spread the contents of a field over several
8399 lines, in order to keep the table compact.
8400
8401 If there is an active region, and both point and mark are in the same column,
8402 the text in the column is wrapped to minimum width for the given number of
8403 lines. Generally, this makes the table more compact. A prefix ARG may be
8404 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8405 formats the selected text to two lines. If the region was longer than two
8406 lines, the remaining lines remain empty. A negative prefix argument reduces
8407 the current number of lines by that amount. The wrapped text is pasted back
8408 into the table. If you formatted it to more lines than it was before, fields
8409 further down in the table get overwritten - so you might need to make space in
8410 the table first.
8411
8412 If there is no region, the current field is split at the cursor position and
8413 the text fragment to the right of the cursor is prepended to the field one
8414 line down.
8415
8416 If there is no region, but you specify a prefix ARG, the current field gets
8417 blank, and the content is appended to the field above."
8418 (interactive "P")
8419 (org-table-check-inside-data-field)
8420 (if (org-region-active-p)
8421 ;; There is a region: fill as a paragraph
8422 (let ((beg (region-beginning))
8423 nlines)
8424 (org-table-cut-region (region-beginning) (region-end))
8425 (if (> (length (car org-table-clip)) 1)
8426 (error "Region must be limited to single column"))
8427 (setq nlines (if arg
8428 (if (< arg 1)
8429 (+ (length org-table-clip) arg)
8430 arg)
8431 (length org-table-clip)))
8432 (setq org-table-clip
8433 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8434 nil nlines)))
8435 (goto-char beg)
8436 (org-table-paste-rectangle))
8437 ;; No region, split the current field at point
8438 (if arg
8439 ;; combine with field above
8440 (let ((s (org-table-blank-field))
8441 (col (org-table-current-column)))
8442 (beginning-of-line 0)
8443 (while (org-at-table-hline-p) (beginning-of-line 0))
8444 (org-table-goto-column col)
8445 (skip-chars-forward "^|")
8446 (skip-chars-backward " ")
8447 (insert " " (org-trim s))
8448 (org-table-align))
8449 ;; split field
8450 (when (looking-at "\\([^|]+\\)+|")
8451 (let ((s (match-string 1)))
8452 (replace-match " |")
8453 (goto-char (match-beginning 0))
8454 (org-table-next-row)
8455 (insert (org-trim s) " ")
8456 (org-table-align))))))
8457
8458 (defun org-trim (s)
8459 "Remove whitespace at beginning and end of string."
8460 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8461 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8462 s)
8463
8464 (defun org-wrap (string &optional width lines)
8465 "Wrap string to either a number of lines, or a width in characters.
8466 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8467 that costs. If there is a word longer than WIDTH, the text is actually
8468 wrapped to the length of that word.
8469 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8470 many lines, whatever width that takes.
8471 The return value is a list of lines, without newlines at the end."
8472 (let* ((words (org-split-string string "[ \t\n]+"))
8473 (maxword (apply 'max (mapcar 'string-width words)))
8474 w ll)
8475 (cond (width
8476 (org-do-wrap words (max maxword width)))
8477 (lines
8478 (setq w maxword)
8479 (setq ll (org-do-wrap words maxword))
8480 (if (<= (length ll) lines)
8481 ll
8482 (setq ll words)
8483 (while (> (length ll) lines)
8484 (setq w (1+ w))
8485 (setq ll (org-do-wrap words w)))
8486 ll))
8487 (t (error "Cannot wrap this")))))
8488
8489
8490 (defun org-do-wrap (words width)
8491 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8492 (let (lines line)
8493 (while words
8494 (setq line (pop words))
8495 (while (and words (< (+ (length line) (length (car words))) width))
8496 (setq line (concat line " " (pop words))))
8497 (setq lines (push line lines)))
8498 (nreverse lines)))
8499
8500 ;; FIXME: I think I can make this more efficient
8501 (defun org-split-string (string &optional separators)
8502 "Splits STRING into substrings at SEPARATORS.
8503 No empty strings are returned if there are matches at the beginning
8504 and end of string."
8505 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8506 (start 0)
8507 notfirst
8508 (list nil))
8509 (while (and (string-match rexp string
8510 (if (and notfirst
8511 (= start (match-beginning 0))
8512 (< start (length string)))
8513 (1+ start) start))
8514 (< (match-beginning 0) (length string)))
8515 (setq notfirst t)
8516 (or (eq (match-beginning 0) 0)
8517 (and (eq (match-beginning 0) (match-end 0))
8518 (eq (match-beginning 0) start))
8519 (setq list
8520 (cons (substring string start (match-beginning 0))
8521 list)))
8522 (setq start (match-end 0)))
8523 (or (eq start (length string))
8524 (setq list
8525 (cons (substring string start)
8526 list)))
8527 (nreverse list)))
8528
8529 (defun org-table-add-invisible-to-vertical-lines ()
8530 "Add an `invisible' property to vertical lines of current table."
8531 (interactive)
8532 (let* ((beg (org-table-begin))
8533 (end (org-table-end))
8534 (end1))
8535 (save-excursion
8536 (goto-char beg)
8537 (while (< (point) end)
8538 (setq end1 (point-at-eol))
8539 (if (looking-at org-table-dataline-regexp)
8540 (while (re-search-forward "|" end1 t)
8541 (add-text-properties (1- (point)) (point)
8542 '(invisible org-table)))
8543 (while (re-search-forward "[+|]" end1 t)
8544 (add-text-properties (1- (point)) (point)
8545 '(invisible org-table))))
8546 (beginning-of-line 2)))))
8547
8548 (defun org-table-toggle-vline-visibility (&optional arg)
8549 "Toggle the visibility of table vertical lines.
8550 The effect is immediate and on all tables in the file.
8551 With prefix ARG, make lines invisible when ARG is positive, make lines
8552 visible when ARG is not positive."
8553 (interactive "P")
8554 (let ((action (cond
8555 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
8556 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
8557 (t (if (org-in-invisibility-spec-p '(org-table))
8558 'off
8559 'on)))))
8560 (if (eq action 'off)
8561 (progn
8562 (org-remove-from-invisibility-spec '(org-table))
8563 (org-table-map-tables 'org-table-align)
8564 (message "Vertical table lines visible")
8565 (if (org-at-table-p)
8566 (org-table-align)))
8567 (org-add-to-invisibility-spec '(org-table))
8568 (org-table-map-tables 'org-table-align)
8569 (message "Vertical table lines invisible"))
8570 (redraw-frame (selected-frame))))
8571
8572 (defun org-table-map-tables (function)
8573 "Apply FUNCTION to the start of all tables in the buffer."
8574 (save-excursion
8575 (save-restriction
8576 (widen)
8577 (goto-char (point-min))
8578 (while (re-search-forward org-table-any-line-regexp nil t)
8579 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8580 (beginning-of-line 1)
8581 (if (looking-at org-table-line-regexp)
8582 (save-excursion (funcall function)))
8583 (re-search-forward org-table-any-border-regexp nil 1)))))
8584
8585 (defun org-table-sum (&optional beg end nlast)
8586 "Sum numbers in region of current table column.
8587 The result will be displayed in the echo area, and will be available
8588 as kill to be inserted with \\[yank].
8589
8590 If there is an active region, it is interpreted as a rectangle and all
8591 numbers in that rectangle will be summed. If there is no active
8592 region and point is located in a table column, sum all numbers in that
8593 column.
8594
8595 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8596 numbers are assumed to be times as well (in decimal hours) and the
8597 numbers are added as such.
8598
8599 If NLAST is a number, only the NLAST fields will actually be summed."
8600 (interactive)
8601 (save-excursion
8602 (let (col (timecnt 0) diff h m s org-table-clip)
8603 (cond
8604 ((and beg end)) ; beg and end given explicitly
8605 ((org-region-active-p)
8606 (setq beg (region-beginning) end (region-end)))
8607 (t
8608 (setq col (org-table-current-column))
8609 (goto-char (org-table-begin))
8610 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8611 (error "No table data"))
8612 (org-table-goto-column col)
8613 ;not needed? (skip-chars-backward "^|")
8614 (setq beg (point))
8615 (goto-char (org-table-end))
8616 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8617 (error "No table data"))
8618 (org-table-goto-column col)
8619 ;not needed? (skip-chars-forward "^|")
8620 (setq end (point))))
8621 (let* ((items (apply 'append (org-table-copy-region beg end)))
8622 (items1 (cond ((not nlast) items)
8623 ((>= nlast (length items)) items)
8624 (t (setq items (reverse items))
8625 (setcdr (nthcdr (1- nlast) items) nil)
8626 (nreverse items))))
8627 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8628 items1)))
8629 (res (apply '+ numbers))
8630 (sres (if (= timecnt 0)
8631 (format "%g" res)
8632 (setq diff (* 3600 res)
8633 h (floor (/ diff 3600)) diff (mod diff 3600)
8634 m (floor (/ diff 60)) diff (mod diff 60)
8635 s diff)
8636 (format "%d:%02d:%02d" h m s))))
8637 (kill-new sres)
8638 (if (interactive-p)
8639 (message "%s"
8640 (substitute-command-keys
8641 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8642 (length numbers) sres))))
8643 sres))))
8644
8645 (defun org-table-get-number-for-summing (s)
8646 (let (n)
8647 (if (string-match "^ *|? *" s)
8648 (setq s (replace-match "" nil nil s)))
8649 (if (string-match " *|? *$" s)
8650 (setq s (replace-match "" nil nil s)))
8651 (setq n (string-to-number s))
8652 (cond
8653 ((and (string-match "0" s)
8654 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8655 ((string-match "\\`[ \t]+\\'" s) nil)
8656 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8657 (let ((h (string-to-number (or (match-string 1 s) "0")))
8658 (m (string-to-number (or (match-string 2 s) "0")))
8659 (s (string-to-number (or (match-string 4 s) "0"))))
8660 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
8661 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8662 ((equal n 0) nil)
8663 (t n))))
8664
8665 (defun org-table-get-vertical-vector (desc &optional tbeg col)
8666 "Get a calc vector from a column, accorting to descriptor DESC.
8667 Optional arguments TBEG and COL can give the beginning of the table and
8668 the current column, to avoid unnecessary parsing."
8669 (save-excursion
8670 (or tbeg (setq tbeg (org-table-begin)))
8671 (or col (setq col (org-table-current-column)))
8672 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
8673 (cond
8674 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
8675 (setq n1 (- (match-end 1) (match-beginning 1)))
8676 (if (match-beginning 3)
8677 (setq n2 (- (match-end 2) (match-beginning 3))))
8678 (setq n (if n2 (max n1 n2) n1))
8679 (setq n1 (if n2 (min n1 n2)))
8680 (setq nn n)
8681 (while (and (> nn 0)
8682 (re-search-backward org-table-hline-regexp tbeg t))
8683 (push (org-current-line) hline-list)
8684 (setq nn (1- nn)))
8685 (setq hline-list (nreverse hline-list))
8686 (goto-line (nth (1- n) hline-list))
8687 (when (re-search-forward org-table-dataline-regexp)
8688 (org-table-goto-column col)
8689 (setq beg (point)))
8690 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
8691 (when (re-search-backward org-table-dataline-regexp)
8692 (org-table-goto-column col)
8693 (setq end (point)))
8694 (setq l (apply 'append (org-table-copy-region beg end)))
8695 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
8696 (if (equal x "") "0" x))
8697 l ",") "]"))
8698 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
8699 (setq n1 (string-to-number (match-string 1 desc))
8700 n2 (string-to-number (match-string 2 desc)))
8701 (beginning-of-line 1)
8702 (save-excursion
8703 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
8704 (org-table-goto-column col)
8705 (setq beg (point))))
8706 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
8707 (org-table-goto-column col)
8708 (setq end (point)))
8709 (setq l (apply 'append (org-table-copy-region beg end)))
8710 (concat "[" (mapconcat
8711 (lambda (x) (setq x (org-trim x))
8712 (if (equal x "") "0" x))
8713 l ",") "]"))
8714 ((string-match "\\([0-9]+\\)" desc)
8715 (beginning-of-line 1)
8716 (when (re-search-backward org-table-dataline-regexp tbeg t
8717 (string-to-number (match-string 0 desc)))
8718 (org-table-goto-column col)
8719 (org-trim (org-table-get-field))))))))
8720
8721 (defvar org-table-formula-history nil)
8722
8723 (defvar org-table-column-names nil
8724 "Alist with column names, derived from the `!' line.")
8725 (defvar org-table-column-name-regexp nil
8726 "Regular expression matching the current column names.")
8727 (defvar org-table-local-parameters nil
8728 "Alist with parameter names, derived from the `$' line.")
8729 (defvar org-table-named-field-locations nil
8730 "Alist with locations of named fields.")
8731
8732 (defun org-table-get-formula (&optional equation named)
8733 "Read a formula from the minibuffer, offer stored formula as default."
8734 (let* ((name (car (rassoc (list (org-current-line)
8735 (org-table-current-column))
8736 org-table-named-field-locations)))
8737 (scol (if named
8738 (if name name
8739 (error "Not in a named field"))
8740 (int-to-string (org-table-current-column))))
8741 (dummy (and name (not named)
8742 (not (y-or-n-p "Replace named-field formula with column equation? " ))
8743 (error "Abort")))
8744 (org-table-may-need-update nil)
8745 (stored-list (org-table-get-stored-formulas))
8746 (stored (cdr (assoc scol stored-list)))
8747 (eq (cond
8748 ((and stored equation (string-match "^ *=? *$" equation))
8749 stored)
8750 ((stringp equation)
8751 equation)
8752 (t (read-string
8753 (format "%s formula $%s=" (if named "Field" "Column") scol)
8754 (or stored "") 'org-table-formula-history
8755 ;stored
8756 ))))
8757 mustsave)
8758 (when (not (string-match "\\S-" eq))
8759 ;; remove formula
8760 (setq stored-list (delq (assoc scol stored-list) stored-list))
8761 (org-table-store-formulas stored-list)
8762 (error "Formula removed"))
8763 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8764 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8765 (if (and name (not named))
8766 ;; We set the column equation, delete the named one.
8767 (setq stored-list (delq (assoc name stored-list) stored-list)
8768 mustsave t))
8769 (if stored
8770 (setcdr (assoc scol stored-list) eq)
8771 (setq stored-list (cons (cons scol eq) stored-list)))
8772 (if (or mustsave (not (equal stored eq)))
8773 (org-table-store-formulas stored-list))
8774 eq))
8775
8776 (defun org-table-store-formulas (alist)
8777 "Store the list of formulas below the current table."
8778 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
8779 (save-excursion
8780 (goto-char (org-table-end))
8781 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
8782 (delete-region (point) (match-end 0)))
8783 (insert "#+TBLFM: "
8784 (mapconcat (lambda (x)
8785 (concat "$" (car x) "=" (cdr x)))
8786 alist "::")
8787 "\n")))
8788
8789 (defun org-table-get-stored-formulas ()
8790 "Return an alist with the t=stored formulas directly after current table."
8791 (interactive)
8792 (let (scol eq eq-alist strings string seen)
8793 (save-excursion
8794 (goto-char (org-table-end))
8795 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8796 (setq strings (org-split-string (match-string 2) " *:: *"))
8797 (while (setq string (pop strings))
8798 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
8799 (setq scol (match-string 1 string)
8800 eq (match-string 2 string)
8801 eq-alist (cons (cons scol eq) eq-alist))
8802 (if (member scol seen)
8803 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8804 (push scol seen))))))
8805 (nreverse eq-alist)))
8806
8807 (defun org-table-modify-formulas (action &rest columns)
8808 "Modify the formulas stored below the current table.
8809 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
8810 expected, for the other actions only a single column number is needed."
8811 (let ((list (org-table-get-stored-formulas))
8812 (nmax (length (org-split-string
8813 (buffer-substring (point-at-bol) (point-at-eol))
8814 "|")))
8815 col col1 col2 scol si sc1 sc2)
8816 (cond
8817 ((null list)) ; No action needed if there are no stored formulas
8818 ((eq action 'remove)
8819 (setq col (car columns)
8820 scol (int-to-string col))
8821 (org-table-replace-in-formulas list scol "INVALID")
8822 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
8823 (loop for i from (1+ col) upto nmax by 1 do
8824 (setq si (int-to-string i))
8825 (org-table-replace-in-formulas list si (int-to-string (1- i)))
8826 (if (assoc si list) (setcar (assoc si list)
8827 (int-to-string (1- i))))))
8828 ((eq action 'insert)
8829 (setq col (car columns))
8830 (loop for i from nmax downto col by 1 do
8831 (setq si (int-to-string i))
8832 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
8833 (if (assoc si list) (setcar (assoc si list)
8834 (int-to-string (1+ i))))))
8835 ((eq action 'swap)
8836 (setq col1 (car columns) col2 (nth 1 columns)
8837 sc1 (int-to-string col1) sc2 (int-to-string col2))
8838 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
8839 (org-table-replace-in-formulas list sc1 "ZqZ")
8840 (org-table-replace-in-formulas list sc2 sc1)
8841 (org-table-replace-in-formulas list "ZqZ" sc2)
8842 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
8843 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
8844 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
8845 (t (error "Invalid action in `org-table-modify-formulas'")))
8846 (if list (org-table-store-formulas list))))
8847
8848 (defun org-table-replace-in-formulas (list s1 s2)
8849 (let (elt re s)
8850 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
8851 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
8852 re (concat (regexp-quote s1) "\\>"))
8853 (while (setq elt (pop list))
8854 (setq s (cdr elt))
8855 (while (string-match re s)
8856 (setq s (replace-match s2 t t s)))
8857 (setcdr elt s))))
8858
8859 (defun org-table-get-specials ()
8860 "Get the column names and local parameters for this table."
8861 (save-excursion
8862 (let ((beg (org-table-begin)) (end (org-table-end))
8863 names name fields fields1 field cnt c v line col)
8864 (setq org-table-column-names nil
8865 org-table-local-parameters nil
8866 org-table-named-field-locations nil)
8867 (goto-char beg)
8868 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8869 (setq names (org-split-string (match-string 1) " *| *")
8870 cnt 1)
8871 (while (setq name (pop names))
8872 (setq cnt (1+ cnt))
8873 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8874 (push (cons name (int-to-string cnt)) org-table-column-names))))
8875 (setq org-table-column-names (nreverse org-table-column-names))
8876 (setq org-table-column-name-regexp
8877 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8878 (goto-char beg)
8879 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8880 (setq fields (org-split-string (match-string 1) " *| *"))
8881 (while (setq field (pop fields))
8882 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8883 (push (cons (match-string 1 field) (match-string 2 field))
8884 org-table-local-parameters))))
8885 (goto-char beg)
8886 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8887 (setq c (match-string 1)
8888 fields (org-split-string (match-string 2) " *| *"))
8889 (save-excursion
8890 (beginning-of-line (if (equal c "_") 2 0))
8891 (setq line (org-current-line) col 1)
8892 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8893 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8894 (while (and fields1 (setq field (pop fields)))
8895 (setq v (pop fields1) col (1+ col))
8896 (when (and (stringp field) (stringp v)
8897 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8898 (push (cons field v) org-table-local-parameters)
8899 (push (list field line col) org-table-named-field-locations)))))))
8900
8901 (defun org-this-word ()
8902 ;; Get the current word
8903 (save-excursion
8904 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
8905 (end (progn (skip-chars-forward "^ \t\n") (point))))
8906 (buffer-substring-no-properties beg end))))
8907
8908 (defun org-table-maybe-eval-formula ()
8909 "Check if the current field starts with \"=\" or \":=\".
8910 If yes, store the formula and apply it."
8911 ;; We already know we are in a table. Get field will only return a formula
8912 ;; when appropriate. It might return a separator line, but no problem.
8913 (when org-table-formula-evaluate-inline
8914 (let* ((field (org-trim (or (org-table-get-field) "")))
8915 named eq)
8916 (when (string-match "^:?=\\(.*\\)" field)
8917 (setq named (equal (string-to-char field) ?:)
8918 eq (match-string 1 field))
8919 (if (fboundp 'calc-eval)
8920 (org-table-eval-formula (if named '(4) nil) eq))))))
8921
8922 (defvar org-recalc-commands nil
8923 "List of commands triggering the recalculation of a line.
8924 Will be filled automatically during use.")
8925
8926 (defvar org-recalc-marks
8927 '((" " . "Unmarked: no special line, no automatic recalculation")
8928 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8929 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8930 ("!" . "Column name definition line. Reference in formula as $name.")
8931 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8932 ("_" . "Names for values in row below this one.")
8933 ("^" . "Names for values in row above this one.")))
8934
8935 (defun org-table-rotate-recalc-marks (&optional newchar)
8936 "Rotate the recalculation mark in the first column.
8937 If in any row, the first field is not consistent with a mark,
8938 insert a new column for the markers.
8939 When there is an active region, change all the lines in the region,
8940 after prompting for the marking character.
8941 After each change, a message will be displayed indicating the meaning
8942 of the new mark."
8943 (interactive)
8944 (unless (org-at-table-p) (error "Not at a table"))
8945 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8946 (beg (org-table-begin))
8947 (end (org-table-end))
8948 (l (org-current-line))
8949 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8950 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8951 (have-col
8952 (save-excursion
8953 (goto-char beg)
8954 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8955 (col (org-table-current-column))
8956 (forcenew (car (assoc newchar org-recalc-marks)))
8957 epos new)
8958 (when l1
8959 (message "Change region to what mark? Type # * ! $ or SPC: ")
8960 (setq newchar (char-to-string (read-char-exclusive))
8961 forcenew (car (assoc newchar org-recalc-marks))))
8962 (if (and newchar (not forcenew))
8963 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8964 newchar))
8965 (if l1 (goto-line l1))
8966 (save-excursion
8967 (beginning-of-line 1)
8968 (unless (looking-at org-table-dataline-regexp)
8969 (error "Not at a table data line")))
8970 (unless have-col
8971 (org-table-goto-column 1)
8972 (org-table-insert-column)
8973 (org-table-goto-column (1+ col)))
8974 (setq epos (point-at-eol))
8975 (save-excursion
8976 (beginning-of-line 1)
8977 (org-table-get-field
8978 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8979 (concat " "
8980 (setq new (or forcenew
8981 (cadr (member (match-string 1) marks))))
8982 " ")
8983 " # ")))
8984 (if (and l1 l2)
8985 (progn
8986 (goto-line l1)
8987 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8988 (and (looking-at org-table-dataline-regexp)
8989 (org-table-get-field 1 (concat " " new " "))))
8990 (goto-line l1)))
8991 (if (not (= epos (point-at-eol))) (org-table-align))
8992 (goto-line l)
8993 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8994
8995 (defun org-table-maybe-recalculate-line ()
8996 "Recompute the current line if marked for it, and if we haven't just done it."
8997 (interactive)
8998 (and org-table-allow-automatic-line-recalculation
8999 (not (and (memq last-command org-recalc-commands)
9000 (equal org-last-recalc-line (org-current-line))))
9001 (save-excursion (beginning-of-line 1)
9002 (looking-at org-table-auto-recalculate-regexp))
9003 (fboundp 'calc-eval)
9004 (org-table-recalculate) t))
9005
9006 (defvar org-table-formula-debug nil
9007 "Non-nil means, debug table formulas.
9008 When nil, simply write \"#ERROR\" in corrupted fields.")
9009
9010 (defvar modes)
9011 (defsubst org-set-calc-mode (var &optional value)
9012 (if (stringp var)
9013 (setq var (assoc var '(("D" calc-angle-mode deg)
9014 ("R" calc-angle-mode rad)
9015 ("F" calc-prefer-frac t)
9016 ("S" calc-symbolic-mode t)))
9017 value (nth 2 var) var (nth 1 var)))
9018 (if (memq var modes)
9019 (setcar (cdr (memq var modes)) value)
9020 (cons var (cons value modes)))
9021 modes)
9022
9023 (defun org-table-eval-formula (&optional arg equation
9024 suppress-align suppress-const
9025 suppress-store)
9026 "Replace the table field value at the cursor by the result of a calculation.
9027
9028 This function makes use of Dave Gillespie's Calc package, in my view the
9029 most exciting program ever written for GNU Emacs. So you need to have Calc
9030 installed in order to use this function.
9031
9032 In a table, this command replaces the value in the current field with the
9033 result of a formula. It also installs the formula as the \"current\" column
9034 formula, by storing it in a special line below the table. When called
9035 with a `C-u' prefix, the current field must ba a named field, and the
9036 formula is installed as valid in only this specific field.
9037
9038 When called, the command first prompts for a formula, which is read in
9039 the minibuffer. Previously entered formulas are available through the
9040 history list, and the last used formula is offered as a default.
9041 These stored formulas are adapted correctly when moving, inserting, or
9042 deleting columns with the corresponding commands.
9043
9044 The formula can be any algebraic expression understood by the Calc package.
9045 For details, see the Org-mode manual.
9046
9047 This function can also be called from Lisp programs and offers
9048 additional arguments: EQUATION can be the formula to apply. If this
9049 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9050 used to speed-up recursive calls by by-passing unnecessary aligns.
9051 SUPPRESS-CONST suppresses the interpretation of constants in the
9052 formula, assuming that this has been done already outside the function.
9053 SUPPRESS-STORE means the formula should not be stored, either because
9054 it is already stored, or because it is a modified equation that should
9055 not overwrite the stored one."
9056 (interactive "P")
9057 (require 'calc)
9058 (org-table-check-inside-data-field)
9059 (org-table-get-specials)
9060 (let* (fields
9061 (ndown (if (integerp arg) arg 1))
9062 (org-table-automatic-realign nil)
9063 (case-fold-search nil)
9064 (down (> ndown 1))
9065 (formula (if (and equation suppress-store)
9066 equation
9067 (org-table-get-formula equation (equal arg '(4)))))
9068 (n0 (org-table-current-column))
9069 (modes (copy-sequence org-calc-default-modes))
9070 n form fmt x ev orig c)
9071 ;; Parse the format string. Since we have a lot of modes, this is
9072 ;; a lot of work. However, I think calc still uses most of the time.
9073 (if (string-match ";" formula)
9074 (let ((tmp (org-split-string formula ";")))
9075 (setq formula (car tmp)
9076 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9077 (nth 1 tmp)))
9078 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9079 (setq c (string-to-char (match-string 1 fmt))
9080 n (string-to-number (or (match-string 1 fmt) "")))
9081 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9082 (setq modes (org-set-calc-mode
9083 'calc-float-format
9084 (list (cdr (assoc c '((?n. float) (?f. fix)
9085 (?s. sci) (?e. eng))))
9086 n))))
9087 (setq fmt (replace-match "" t t fmt)))
9088 (while (string-match "[DRFS]" fmt)
9089 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9090 (setq fmt (replace-match "" t t fmt)))
9091 (unless (string-match "\\S-" fmt)
9092 (setq fmt nil))))
9093 (if (and (not suppress-const) org-table-formula-use-constants)
9094 (setq formula (org-table-formula-substitute-names formula)))
9095 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9096 (while (> ndown 0)
9097 (setq fields (org-split-string
9098 (buffer-substring
9099 (point-at-bol) (point-at-eol)) " *| *"))
9100 (if org-table-formula-numbers-only
9101 (setq fields (mapcar
9102 (lambda (x) (number-to-string (string-to-number x)))
9103 fields)))
9104 (setq ndown (1- ndown))
9105 (setq form (copy-sequence formula))
9106 ;; Insert the references to fields in same row
9107 (while (string-match "\\$\\([0-9]+\\)?" form)
9108 (setq n (if (match-beginning 1)
9109 (string-to-number (match-string 1 form))
9110 n0)
9111 x (nth (1- n) fields))
9112 (unless x (error "Invalid field specifier \"%s\""
9113 (match-string 0 form)))
9114 (if (equal x "") (setq x "0"))
9115 (setq form (replace-match (concat "(" x ")") t t form)))
9116 ;; Insert ranges in current column
9117 (while (string-match "\\&[-I0-9]+" form)
9118 (setq form (replace-match
9119 (save-match-data
9120 (org-table-get-vertical-vector (match-string 0 form)
9121 nil n0))
9122 t t form)))
9123 (setq ev (calc-eval (cons form modes)
9124 (if org-table-formula-numbers-only 'num)))
9125
9126 (when org-table-formula-debug
9127 (with-output-to-temp-buffer "*Help*"
9128 (princ (format "Substitution history of formula
9129 Orig: %s
9130 $xyz-> %s
9131 $1-> %s\n" orig formula form))
9132 (if (listp ev)
9133 (princ (format " %s^\nError: %s"
9134 (make-string (car ev) ?\-) (nth 1 ev)))
9135 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9136 ev (or fmt "NONE")
9137 (if fmt (format fmt (string-to-number ev)) ev)))))
9138 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9139 (unless (and (interactive-p) (not ndown))
9140 (unless (let (inhibit-redisplay)
9141 (y-or-n-p "Debugging Formula. Continue to next? "))
9142 (org-table-align)
9143 (error "Abort"))
9144 (delete-window (get-buffer-window "*Help*"))
9145 (message "")))
9146 (if (listp ev) (setq fmt nil ev "#ERROR"))
9147 (org-table-justify-field-maybe
9148 (if fmt (format fmt (string-to-number ev)) ev))
9149 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9150 (call-interactively 'org-return)
9151 (setq ndown 0)))
9152 (and down (org-table-maybe-recalculate-line))
9153 (or suppress-align (and org-table-may-need-update
9154 (org-table-align)))))
9155
9156 (defun org-table-recalculate (&optional all noalign)
9157 "Recalculate the current table line by applying all stored formulas."
9158 (interactive "P")
9159 (or (memq this-command org-recalc-commands)
9160 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9161 (unless (org-at-table-p) (error "Not at a table"))
9162 (org-table-get-specials)
9163 (let* ((eqlist (sort (org-table-get-stored-formulas)
9164 (lambda (a b) (string< (car a) (car b)))))
9165 (inhibit-redisplay t)
9166 (line-re org-table-dataline-regexp)
9167 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9168 (thiscol (org-table-current-column))
9169 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9170 ;; Insert constants in all formulas
9171 (setq eqlist
9172 (mapcar (lambda (x)
9173 (setcdr x (org-table-formula-substitute-names (cdr x)))
9174 x)
9175 eqlist))
9176 ;; Split the equation list
9177 (while (setq eq (pop eqlist))
9178 (if (<= (string-to-char (car eq)) ?9)
9179 (push eq eqlnum)
9180 (push eq eqlname)))
9181 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9182 (if all
9183 (progn
9184 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9185 (goto-char (setq beg (org-table-begin)))
9186 (if (re-search-forward org-table-calculate-mark-regexp end t)
9187 ;; This is a table with marked lines, only compute selected lines
9188 (setq line-re org-table-recalculate-regexp)
9189 ;; Move forward to the first non-header line
9190 (if (and (re-search-forward org-table-dataline-regexp end t)
9191 (re-search-forward org-table-hline-regexp end t)
9192 (re-search-forward org-table-dataline-regexp end t))
9193 (setq beg (match-beginning 0))
9194 nil))) ;; just leave beg where it is
9195 (setq beg (point-at-bol)
9196 end (move-marker (make-marker) (1+ (point-at-eol)))))
9197 (goto-char beg)
9198 (and all (message "Re-applying formulas to full table..."))
9199 (while (re-search-forward line-re end t)
9200 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9201 ;; Unprotected line, recalculate
9202 (and all (message "Re-applying formulas to full table...(line %d)"
9203 (setq cnt (1+ cnt))))
9204 (setq org-last-recalc-line (org-current-line))
9205 (setq eql eqlnum)
9206 (while (setq entry (pop eql))
9207 (goto-line org-last-recalc-line)
9208 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9209 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9210 (goto-line thisline)
9211 (org-table-goto-column thiscol)
9212 (or noalign (and org-table-may-need-update (org-table-align))
9213 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9214 ;; Now do the names fields
9215 (while (setq eq (pop eqlname))
9216 (setq name (car eq)
9217 a (assoc name org-table-named-field-locations))
9218 (when a
9219 (message "Re-applying formula to named field: %s" name)
9220 (goto-line (nth 1 a))
9221 (org-table-goto-column (nth 2 a))
9222 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9223 ;; back to initial position
9224 (goto-line thisline)
9225 (org-table-goto-column thiscol)
9226 (or noalign (and org-table-may-need-update (org-table-align))
9227 (and all (message "Re-applying formulas...done")))))
9228
9229 (defun org-table-formula-substitute-names (f)
9230 "Replace $const with values in string F."
9231 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9232 ;; First, check for column names
9233 (while (setq start (string-match org-table-column-name-regexp f start))
9234 (setq start (1+ start))
9235 (setq a (assoc (match-string 1 f) org-table-column-names))
9236 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9237 ;; Expand ranges to vectors
9238 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9239 (setq n1 (string-to-number (match-string 1 f))
9240 n2 (string-to-number (match-string 2 f))
9241 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9242 s (concat "[($" (number-to-string (1- nn1)) ")"))
9243 (loop for i from nn1 upto nn2 do
9244 (setq s (concat s ",($" (int-to-string i) ")")))
9245 (setq s (concat s "]"))
9246 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9247 (setq f (replace-match s t t f)))
9248 ;; Parameters and constants
9249 (setq start 0)
9250 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9251 (setq start (1+ start))
9252 (if (setq a (save-match-data
9253 (org-table-get-constant (match-string 1 f))))
9254 (setq f (replace-match (concat "(" a ")") t t f))))
9255 (if org-table-formula-debug
9256 (put-text-property 0 (length f) :orig-formula f1 f))
9257 f))
9258
9259 (defun org-table-get-constant (const)
9260 "Find the value for a parameter or constant in a formula.
9261 Parameters get priority."
9262 (or (cdr (assoc const org-table-local-parameters))
9263 (cdr (assoc const org-table-formula-constants))
9264 (and (fboundp 'constants-get) (constants-get const))
9265 "#UNDEFINED_NAME"))
9266
9267 (defvar org-edit-formulas-map (make-sparse-keymap))
9268 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9269 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9270 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9271
9272 (defvar org-pos)
9273 (defvar org-window-configuration)
9274
9275 (defun org-table-edit-formulas ()
9276 "Edit the formulas of the current table in a separate buffer."
9277 (interactive)
9278 (unless (org-at-table-p)
9279 (error "Not at a table"))
9280 (org-table-get-specials)
9281 (let ((eql (org-table-get-stored-formulas))
9282 (pos (move-marker (make-marker) (point)))
9283 (wc (current-window-configuration))
9284 entry loc s)
9285 (switch-to-buffer-other-window "*Edit Formulas*")
9286 (erase-buffer)
9287 (fundamental-mode)
9288 (set (make-local-variable 'org-pos) pos)
9289 (set (make-local-variable 'org-window-configuration) wc)
9290 (use-local-map org-edit-formulas-map)
9291 (setq s "# Edit formulas and finish with `C-c C-c'.
9292 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9293 # Use `C-c ?' to get information about $name at point.
9294 # To cancel editing, press `C-c C-q'.\n")
9295 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9296 (insert s)
9297 (while (setq entry (pop eql))
9298 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9299 (setq s (format "# Named formula, referring to column %d in line %d\n"
9300 (nth 2 loc) (nth 1 loc)))
9301 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9302 (insert s))
9303 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9304 (remove-text-properties 0 (length s) '(face nil) s)
9305 (insert s))
9306 (goto-char (point-min))
9307 (message "Edit formulas and finish with `C-c C-c'.")))
9308
9309 (defun org-show-variable ()
9310 "Show the location/value of the $ expression at point."
9311 (interactive)
9312 (let (var (pos org-pos) (win (selected-window)) e)
9313 (save-excursion
9314 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9315 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9316 (setq var (match-string 1))
9317 (error "No variable at point")))
9318 (cond
9319 ((setq e (assoc var org-table-named-field-locations))
9320 (switch-to-buffer-other-window (marker-buffer pos))
9321 (goto-line (nth 1 e))
9322 (org-table-goto-column (nth 2 e))
9323 (select-window win)
9324 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9325 ((setq e (assoc var org-table-column-names))
9326 (switch-to-buffer-other-window (marker-buffer pos))
9327 (goto-char pos)
9328 (goto-char (org-table-begin))
9329 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9330 (org-table-end) t)
9331 (progn
9332 (goto-char (match-beginning 1))
9333 (message "Named column (column %s)" (cdr e)))
9334 (error "Column name not found"))
9335 (select-window win))
9336 ((string-match "^[0-9]$" var)
9337 ;; column number
9338 (switch-to-buffer-other-window (marker-buffer pos))
9339 (goto-char pos)
9340 (goto-char (org-table-begin))
9341 (recenter 1)
9342 (if (re-search-forward org-table-dataline-regexp
9343 (org-table-end) t)
9344 (progn
9345 (goto-char (match-beginning 0))
9346 (org-table-goto-column (string-to-number var))
9347 (message "Column %s" var))
9348 (error "Column name not found"))
9349 (select-window win))
9350 ((setq e (assoc var org-table-local-parameters))
9351 (switch-to-buffer-other-window (marker-buffer pos))
9352 (goto-char pos)
9353 (goto-char (org-table-begin))
9354 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9355 (progn
9356 (goto-char (match-beginning 1))
9357 (message "Local parameter."))
9358 (error "Parameter not found"))
9359 (select-window win))
9360 (t
9361 (cond
9362 ((setq e (assoc var org-table-formula-constants))
9363 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9364 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9365 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9366 (t (error "Undefined name $%s" var)))))))
9367
9368 (defun org-finish-edit-formulas (&optional arg)
9369 "Parse the buffer for formula definitions and install them.
9370 With prefix ARG, apply the new formulas to the table."
9371 (interactive "P")
9372 (let ((pos org-pos) eql)
9373 (goto-char (point-min))
9374 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9375 (push (cons (match-string 1) (match-string 2)) eql))
9376 (set-window-configuration org-window-configuration)
9377 (select-window (get-buffer-window (marker-buffer pos)))
9378 (goto-char pos)
9379 (unless (org-at-table-p)
9380 (error "Lost table position - cannot install formulae"))
9381 (org-table-store-formulas eql)
9382 (move-marker pos nil)
9383 (kill-buffer "*Edit Formulas*")
9384 (if arg
9385 (org-table-recalculate 'all)
9386 (message "New formulas installed - press C-u C-c C-c to apply."))))
9387
9388 (defun org-abort-edit-formulas ()
9389 "Abort editing formulas, without installing the changes."
9390 (interactive)
9391 (let ((pos org-pos))
9392 (set-window-configuration org-window-configuration)
9393 (select-window (get-buffer-window (marker-buffer pos)))
9394 (goto-char pos)
9395 (message "Formula editing aborted without installing changes")))
9396
9397 ;;; The orgtbl minor mode
9398
9399 ;; Define a minor mode which can be used in other modes in order to
9400 ;; integrate the org-mode table editor.
9401
9402 ;; This is really a hack, because the org-mode table editor uses several
9403 ;; keys which normally belong to the major mode, for example the TAB and
9404 ;; RET keys. Here is how it works: The minor mode defines all the keys
9405 ;; necessary to operate the table editor, but wraps the commands into a
9406 ;; function which tests if the cursor is currently inside a table. If that
9407 ;; is the case, the table editor command is executed. However, when any of
9408 ;; those keys is used outside a table, the function uses `key-binding' to
9409 ;; look up if the key has an associated command in another currently active
9410 ;; keymap (minor modes, major mode, global), and executes that command.
9411 ;; There might be problems if any of the keys used by the table editor is
9412 ;; otherwise used as a prefix key.
9413
9414 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9415 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9416 ;; addresses this by checking explicitly for both bindings.
9417
9418 ;; The optimized version (see variable `orgtbl-optimized') takes over
9419 ;; all keys which are bound to `self-insert-command' in the *global map*.
9420 ;; Some modes bind other commands to simple characters, for example
9421 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9422 ;; active, this binding is ignored inside tables and replaced with a
9423 ;; modified self-insert.
9424
9425 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9426 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9427 In the optimized version, the table editor takes over all simple keys that
9428 normally just insert a character. In tables, the characters are inserted
9429 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9430 for empty fields). Outside tables, the correct binding of the keys is
9431 restored.
9432
9433 The default for this option is t if the optimized version is also used in
9434 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9435 this variable requires a restart of Emacs to become effective."
9436 :group 'org-table
9437 :type 'boolean)
9438
9439 (defvar orgtbl-mode nil
9440 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9441 table editor in arbitrary modes.")
9442 (make-variable-buffer-local 'orgtbl-mode)
9443
9444 (defvar orgtbl-mode-map (make-keymap)
9445 "Keymap for `orgtbl-mode'.")
9446
9447 ;;;###autoload
9448 (defun turn-on-orgtbl ()
9449 "Unconditionally turn on `orgtbl-mode'."
9450 (orgtbl-mode 1))
9451
9452 ;;;###autoload
9453 (defun orgtbl-mode (&optional arg)
9454 "The `org-mode' table editor as a minor mode for use in other modes."
9455 (interactive)
9456 (if (eq major-mode 'org-mode)
9457 ;; Exit without error, in case some hook functions calls this
9458 ;; by accident in org-mode.
9459 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9460 (setq orgtbl-mode
9461 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9462 (if orgtbl-mode
9463 (progn
9464 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9465 ;; Make sure we are first in minor-mode-map-alist
9466 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9467 (and c (setq minor-mode-map-alist
9468 (cons c (delq c minor-mode-map-alist)))))
9469 (set (make-local-variable (quote org-table-may-need-update)) t)
9470 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
9471 (add-hook 'before-change-functions 'org-before-change-function
9472 nil 'local)
9473 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
9474 auto-fill-inhibit-regexp)
9475 (set (make-local-variable 'auto-fill-inhibit-regexp)
9476 (if auto-fill-inhibit-regexp
9477 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
9478 "[ \t]*|"))
9479 (easy-menu-add orgtbl-mode-menu)
9480 (run-hooks 'orgtbl-mode-hook))
9481 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9482 (remove-hook 'before-change-functions 'org-before-change-function t)
9483 (easy-menu-remove orgtbl-mode-menu)
9484 (force-mode-line-update 'all))))
9485
9486 ;; Install it as a minor mode.
9487 (put 'orgtbl-mode :included t)
9488 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9489 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9490
9491 (defun orgtbl-make-binding (fun n &rest keys)
9492 "Create a function for binding in the table minor mode.
9493 FUN is the command to call inside a table. N is used to create a unique
9494 command name. KEYS are keys that should be checked in for a command
9495 to execute outside of tables."
9496 (eval
9497 (list 'defun
9498 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9499 '(arg)
9500 (concat "In tables, run `" (symbol-name fun) "'.\n"
9501 "Outside of tables, run the binding of `"
9502 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9503 "'.")
9504 '(interactive "p")
9505 (list 'if
9506 '(org-at-table-p)
9507 (list 'call-interactively (list 'quote fun))
9508 (list 'let '(orgtbl-mode)
9509 (list 'call-interactively
9510 (append '(or)
9511 (mapcar (lambda (k)
9512 (list 'key-binding k))
9513 keys)
9514 '('orgtbl-error))))))))
9515
9516 (defun orgtbl-error ()
9517 "Error when there is no default binding for a table key."
9518 (interactive)
9519 (error "This key is has no function outside tables"))
9520
9521 (defun orgtbl-setup ()
9522 "Setup orgtbl keymaps."
9523 (let ((nfunc 0)
9524 (bindings
9525 (list
9526 '([(meta shift left)] org-table-delete-column)
9527 '([(meta left)] org-table-move-column-left)
9528 '([(meta right)] org-table-move-column-right)
9529 '([(meta shift right)] org-table-insert-column)
9530 '([(meta shift up)] org-table-kill-row)
9531 '([(meta shift down)] org-table-insert-row)
9532 '([(meta up)] org-table-move-row-up)
9533 '([(meta down)] org-table-move-row-down)
9534 '("\C-c\C-w" org-table-cut-region)
9535 '("\C-c\M-w" org-table-copy-region)
9536 '("\C-c\C-y" org-table-paste-rectangle)
9537 '("\C-c-" org-table-insert-hline)
9538 ; '([(shift tab)] org-table-previous-field)
9539 '("\C-m" org-table-next-row)
9540 (list (org-key 'S-return) 'org-table-copy-down)
9541 '([(meta return)] org-table-wrap-region)
9542 '("\C-c\C-q" org-table-wrap-region)
9543 '("\C-c?" org-table-current-column)
9544 '("\C-c " org-table-blank-field)
9545 '("\C-c+" org-table-sum)
9546 '("\C-c|" org-table-toggle-vline-visibility)
9547 '("\C-c=" org-table-eval-formula)
9548 '("\C-c'" org-table-edit-formulas)
9549 '("\C-c*" org-table-recalculate)
9550 '("\C-c^" org-table-sort-lines)
9551 '([(control ?#)] org-table-rotate-recalc-marks)))
9552 elt key fun cmd)
9553 (while (setq elt (pop bindings))
9554 (setq nfunc (1+ nfunc))
9555 (setq key (car elt)
9556 fun (nth 1 elt)
9557 cmd (orgtbl-make-binding fun nfunc key))
9558 (define-key orgtbl-mode-map key cmd))
9559 ;; Special treatment needed for TAB and RET
9560 (define-key orgtbl-mode-map [(return)]
9561 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9562 (define-key orgtbl-mode-map "\C-m"
9563 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9564 (define-key orgtbl-mode-map [(tab)]
9565 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9566 (define-key orgtbl-mode-map "\C-i"
9567 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
9568 (define-key orgtbl-mode-map "\C-i"
9569 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
9570 (define-key orgtbl-mode-map "\C-c\C-c"
9571 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
9572 (when orgtbl-optimized
9573 ;; If the user wants maximum table support, we need to hijack
9574 ;; some standard editing functions
9575 (org-remap orgtbl-mode-map
9576 'self-insert-command 'orgtbl-self-insert-command
9577 'delete-char 'orgtbl-delete-char
9578 'delete-backward-char 'orgtbl-delete-backward-char)
9579 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
9580 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
9581 '("OrgTbl"
9582 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
9583 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
9584 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
9585 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
9586 "--"
9587 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
9588 ["Copy Field from Above"
9589 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
9590 "--"
9591 ("Column"
9592 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
9593 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
9594 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
9595 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
9596 ("Row"
9597 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
9598 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
9599 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
9600 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
9601 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
9602 "--"
9603 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
9604 ("Rectangle"
9605 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
9606 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
9607 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
9608 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
9609 "--"
9610 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
9611 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9612 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
9613 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
9614 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
9615 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
9616 ["Sum Column/Rectangle" org-table-sum
9617 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
9618 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
9619 ["Debug Formulas"
9620 (setq org-table-formula-debug (not org-table-formula-debug))
9621 :style toggle :selected org-table-formula-debug]
9622 ))
9623 t)
9624
9625 (defun orgtbl-tab ()
9626 "Justification and field motion for `orgtbl-mode'."
9627 (interactive)
9628 (org-table-justify-field-maybe)
9629 (org-table-next-field))
9630
9631 (defun orgtbl-ret ()
9632 "Justification and field motion for `orgtbl-mode'."
9633 (interactive)
9634 (org-table-justify-field-maybe)
9635 (org-table-next-row))
9636
9637 (defun orgtbl-self-insert-command (N)
9638 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9639 If the cursor is in a table looking at whitespace, the whitespace is
9640 overwritten, and the table is not marked as requiring realignment."
9641 (interactive "p")
9642 (if (and (org-at-table-p)
9643 (or
9644 (and org-table-auto-blank-field
9645 (member last-command
9646 '(orgtbl-hijacker-command-100
9647 orgtbl-hijacker-command-101
9648 orgtbl-hijacker-command-102
9649 orgtbl-hijacker-command-103
9650 orgtbl-hijacker-command-104
9651 orgtbl-hijacker-command-105))
9652 (org-table-blank-field))
9653 t)
9654 (eq N 1)
9655 (looking-at "[^|\n]* +|"))
9656 (let (org-table-may-need-update)
9657 (goto-char (1- (match-end 0)))
9658 (delete-backward-char 1)
9659 (goto-char (match-beginning 0))
9660 (self-insert-command N))
9661 (setq org-table-may-need-update t)
9662 (let (orgtbl-mode)
9663 (call-interactively (key-binding (vector last-input-event))))))
9664
9665 (defun org-force-self-insert (N)
9666 "Needed to enforce self-insert under remapping."
9667 (interactive "p")
9668 (self-insert-command N))
9669
9670 (defun orgtbl-delete-backward-char (N)
9671 "Like `delete-backward-char', insert whitespace at field end in tables.
9672 When deleting backwards, in tables this function will insert whitespace in
9673 front of the next \"|\" separator, to keep the table aligned. The table will
9674 still be marked for re-alignment, because a narrow field may lead to a
9675 reduced column width."
9676 (interactive "p")
9677 (if (and (org-at-table-p)
9678 (eq N 1)
9679 (string-match "|" (buffer-substring (point-at-bol) (point)))
9680 (looking-at ".*?|"))
9681 (let ((pos (point)))
9682 (backward-delete-char N)
9683 (skip-chars-forward "^|")
9684 (insert " ")
9685 (goto-char (1- pos)))
9686 (delete-backward-char N)))
9687
9688 (defun orgtbl-delete-char (N)
9689 "Like `delete-char', but insert whitespace at field end in tables.
9690 When deleting characters, in tables this function will insert whitespace in
9691 front of the next \"|\" separator, to keep the table aligned. The table
9692 will still be marked for re-alignment, because a narrow field may lead to
9693 a reduced column width."
9694 (interactive "p")
9695 (if (and (org-at-table-p)
9696 (not (bolp))
9697 (not (= (char-after) ?|))
9698 (eq N 1))
9699 (if (looking-at ".*?|")
9700 (let ((pos (point)))
9701 (replace-match (concat
9702 (substring (match-string 0) 1 -1)
9703 " |"))
9704 (goto-char pos)))
9705 (delete-char N)))
9706
9707 ;;; Exporting
9708
9709 (defconst org-level-max 20)
9710
9711 (defun org-export-find-first-heading-line (list)
9712 "Remove all lines from LIST which are before the first headline."
9713 (let ((orig-list list)
9714 (re (concat "^" outline-regexp)))
9715 (while (and list
9716 (not (string-match re (car list))))
9717 (pop list))
9718 (or list orig-list)))
9719
9720 (defun org-skip-comments (lines)
9721 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
9722 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
9723 (re2 "^\\(\\*+\\)[ \t\n\r]")
9724 rtn line level)
9725 (while (setq line (pop lines))
9726 (cond
9727 ((and (string-match re1 line)
9728 (setq level (- (match-end 1) (match-beginning 1))))
9729 ;; Beginning of a COMMENT subtree. Skip it.
9730 (while (and (setq line (pop lines))
9731 (or (not (string-match re2 line))
9732 (> (- (match-end 1) (match-beginning 1)) level))))
9733 (setq lines (cons line lines)))
9734 ((string-match "^#" line)
9735 ;; an ordinary comment line
9736 )
9737 (t (setq rtn (cons line rtn)))))
9738 (nreverse rtn)))
9739
9740 ;; ASCII
9741
9742 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
9743 "Characters for underlining headings in ASCII export.")
9744
9745 (defconst org-html-entities
9746 '(("nbsp")
9747 ("iexcl")
9748 ("cent")
9749 ("pound")
9750 ("curren")
9751 ("yen")
9752 ("brvbar")
9753 ("sect")
9754 ("uml")
9755 ("copy")
9756 ("ordf")
9757 ("laquo")
9758 ("not")
9759 ("shy")
9760 ("reg")
9761 ("macr")
9762 ("deg")
9763 ("plusmn")
9764 ("sup2")
9765 ("sup3")
9766 ("acute")
9767 ("micro")
9768 ("para")
9769 ("middot")
9770 ("odot"."o")
9771 ("star"."*")
9772 ("cedil")
9773 ("sup1")
9774 ("ordm")
9775 ("raquo")
9776 ("frac14")
9777 ("frac12")
9778 ("frac34")
9779 ("iquest")
9780 ("Agrave")
9781 ("Aacute")
9782 ("Acirc")
9783 ("Atilde")
9784 ("Auml")
9785 ("Aring") ("AA"."&Aring;")
9786 ("AElig")
9787 ("Ccedil")
9788 ("Egrave")
9789 ("Eacute")
9790 ("Ecirc")
9791 ("Euml")
9792 ("Igrave")
9793 ("Iacute")
9794 ("Icirc")
9795 ("Iuml")
9796 ("ETH")
9797 ("Ntilde")
9798 ("Ograve")
9799 ("Oacute")
9800 ("Ocirc")
9801 ("Otilde")
9802 ("Ouml")
9803 ("times")
9804 ("Oslash")
9805 ("Ugrave")
9806 ("Uacute")
9807 ("Ucirc")
9808 ("Uuml")
9809 ("Yacute")
9810 ("THORN")
9811 ("szlig")
9812 ("agrave")
9813 ("aacute")
9814 ("acirc")
9815 ("atilde")
9816 ("auml")
9817 ("aring")
9818 ("aelig")
9819 ("ccedil")
9820 ("egrave")
9821 ("eacute")
9822 ("ecirc")
9823 ("euml")
9824 ("igrave")
9825 ("iacute")
9826 ("icirc")
9827 ("iuml")
9828 ("eth")
9829 ("ntilde")
9830 ("ograve")
9831 ("oacute")
9832 ("ocirc")
9833 ("otilde")
9834 ("ouml")
9835 ("divide")
9836 ("oslash")
9837 ("ugrave")
9838 ("uacute")
9839 ("ucirc")
9840 ("uuml")
9841 ("yacute")
9842 ("thorn")
9843 ("yuml")
9844 ("fnof")
9845 ("Alpha")
9846 ("Beta")
9847 ("Gamma")
9848 ("Delta")
9849 ("Epsilon")
9850 ("Zeta")
9851 ("Eta")
9852 ("Theta")
9853 ("Iota")
9854 ("Kappa")
9855 ("Lambda")
9856 ("Mu")
9857 ("Nu")
9858 ("Xi")
9859 ("Omicron")
9860 ("Pi")
9861 ("Rho")
9862 ("Sigma")
9863 ("Tau")
9864 ("Upsilon")
9865 ("Phi")
9866 ("Chi")
9867 ("Psi")
9868 ("Omega")
9869 ("alpha")
9870 ("beta")
9871 ("gamma")
9872 ("delta")
9873 ("epsilon")
9874 ("varepsilon"."&epsilon;")
9875 ("zeta")
9876 ("eta")
9877 ("theta")
9878 ("iota")
9879 ("kappa")
9880 ("lambda")
9881 ("mu")
9882 ("nu")
9883 ("xi")
9884 ("omicron")
9885 ("pi")
9886 ("rho")
9887 ("sigmaf") ("varsigma"."&sigmaf;")
9888 ("sigma")
9889 ("tau")
9890 ("upsilon")
9891 ("phi")
9892 ("chi")
9893 ("psi")
9894 ("omega")
9895 ("thetasym") ("vartheta"."&thetasym;")
9896 ("upsih")
9897 ("piv")
9898 ("bull") ("bullet"."&bull;")
9899 ("hellip") ("dots"."&hellip;")
9900 ("prime")
9901 ("Prime")
9902 ("oline")
9903 ("frasl")
9904 ("weierp")
9905 ("image")
9906 ("real")
9907 ("trade")
9908 ("alefsym")
9909 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
9910 ("uarr") ("uparrow"."&uarr;")
9911 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
9912 ("darr")("downarrow"."&darr;")
9913 ("harr") ("leftrightarrow"."&harr;")
9914 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
9915 ("lArr") ("Leftarrow"."&lArr;")
9916 ("uArr") ("Uparrow"."&uArr;")
9917 ("rArr") ("Rightarrow"."&rArr;")
9918 ("dArr") ("Downarrow"."&dArr;")
9919 ("hArr") ("Leftrightarrow"."&hArr;")
9920 ("forall")
9921 ("part") ("partial"."&part;")
9922 ("exist") ("exists"."&exist;")
9923 ("empty") ("emptyset"."&empty;")
9924 ("nabla")
9925 ("isin") ("in"."&isin;")
9926 ("notin")
9927 ("ni")
9928 ("prod")
9929 ("sum")
9930 ("minus")
9931 ("lowast") ("ast"."&lowast;")
9932 ("radic")
9933 ("prop") ("proptp"."&prop;")
9934 ("infin") ("infty"."&infin;")
9935 ("ang") ("angle"."&ang;")
9936 ("and") ("vee"."&and;")
9937 ("or") ("wedge"."&or;")
9938 ("cap")
9939 ("cup")
9940 ("int")
9941 ("there4")
9942 ("sim")
9943 ("cong") ("simeq"."&cong;")
9944 ("asymp")("approx"."&asymp;")
9945 ("ne") ("neq"."&ne;")
9946 ("equiv")
9947 ("le")
9948 ("ge")
9949 ("sub") ("subset"."&sub;")
9950 ("sup") ("supset"."&sup;")
9951 ("nsub")
9952 ("sube")
9953 ("supe")
9954 ("oplus")
9955 ("otimes")
9956 ("perp")
9957 ("sdot") ("cdot"."&sdot;")
9958 ("lceil")
9959 ("rceil")
9960 ("lfloor")
9961 ("rfloor")
9962 ("lang")
9963 ("rang")
9964 ("loz") ("Diamond"."&loz;")
9965 ("spades") ("spadesuit"."&spades;")
9966 ("clubs") ("clubsuit"."&clubs;")
9967 ("hearts") ("diamondsuit"."&hearts;")
9968 ("diams") ("diamondsuit"."&diams;")
9969 ("quot")
9970 ("amp")
9971 ("lt")
9972 ("gt")
9973 ("OElig")
9974 ("oelig")
9975 ("Scaron")
9976 ("scaron")
9977 ("Yuml")
9978 ("circ")
9979 ("tilde")
9980 ("ensp")
9981 ("emsp")
9982 ("thinsp")
9983 ("zwnj")
9984 ("zwj")
9985 ("lrm")
9986 ("rlm")
9987 ("ndash")
9988 ("mdash")
9989 ("lsquo")
9990 ("rsquo")
9991 ("sbquo")
9992 ("ldquo")
9993 ("rdquo")
9994 ("bdquo")
9995 ("dagger")
9996 ("Dagger")
9997 ("permil")
9998 ("lsaquo")
9999 ("rsaquo")
10000 ("euro")
10001
10002 ("arccos"."arccos")
10003 ("arcsin"."arcsin")
10004 ("arctan"."arctan")
10005 ("arg"."arg")
10006 ("cos"."cos")
10007 ("cosh"."cosh")
10008 ("cot"."cot")
10009 ("coth"."coth")
10010 ("csc"."csc")
10011 ("deg"."deg")
10012 ("det"."det")
10013 ("dim"."dim")
10014 ("exp"."exp")
10015 ("gcd"."gcd")
10016 ("hom"."hom")
10017 ("inf"."inf")
10018 ("ker"."ker")
10019 ("lg"."lg")
10020 ("lim"."lim")
10021 ("liminf"."liminf")
10022 ("limsup"."limsup")
10023 ("ln"."ln")
10024 ("log"."log")
10025 ("max"."max")
10026 ("min"."min")
10027 ("Pr"."Pr")
10028 ("sec"."sec")
10029 ("sin"."sin")
10030 ("sinh"."sinh")
10031 ("sup"."sup")
10032 ("tan"."tan")
10033 ("tanh"."tanh")
10034 )
10035 "Entities for TeX->HTML translation.
10036 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
10037 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
10038 In that case, \"\\ent\" will be translated to \"&other;\".
10039 The list contains HTML entities for Latin-1, Greek and other symbols.
10040 It is supplemented by a number of commonly used TeX macros with appropriate
10041 translations. There is currently no way for users to extend this.")
10042
10043 (defvar org-last-level nil) ; dynamically scoped variable
10044
10045 (defun org-export-as-ascii (arg)
10046 "Export the outline as a pretty ASCII file.
10047 If there is an active region, export only the region.
10048 The prefix ARG specifies how many levels of the outline should become
10049 underlined headlines. The default is 3."
10050 (interactive "P")
10051 (setq-default org-todo-line-regexp org-todo-line-regexp)
10052 (let* ((region
10053 (buffer-substring
10054 (if (org-region-active-p) (region-beginning) (point-min))
10055 (if (org-region-active-p) (region-end) (point-max))))
10056 (lines (org-export-find-first-heading-line
10057 (org-skip-comments (org-split-string region "[\r\n]"))))
10058 (org-startup-with-deadline-check nil)
10059 (level 0) line txt
10060 (umax nil)
10061 (case-fold-search nil)
10062 (filename (concat (file-name-sans-extension (buffer-file-name))
10063 ".txt"))
10064 (buffer (find-file-noselect filename))
10065 (levels-open (make-vector org-level-max nil))
10066 (date (format-time-string "%Y/%m/%d" (current-time)))
10067 (time (format-time-string "%X" (current-time)))
10068 (author user-full-name)
10069 (title (buffer-name))
10070 (options nil)
10071 (email user-mail-address)
10072 (language org-export-default-language)
10073 (text nil)
10074 (todo nil)
10075 (lang-words nil))
10076
10077 (setq org-last-level 1)
10078 (org-init-section-numbers)
10079
10080 (find-file-noselect filename)
10081
10082 ;; Search for the export key lines
10083 (org-parse-key-lines)
10084
10085 (setq lang-words (or (assoc language org-export-language-setup)
10086 (assoc "en" org-export-language-setup)))
10087 (if org-export-ascii-show-new-buffer
10088 (switch-to-buffer-other-window buffer)
10089 (set-buffer buffer))
10090 (erase-buffer)
10091 (fundamental-mode)
10092 (if options (org-parse-export-options options))
10093 (setq umax (if arg (prefix-numeric-value arg)
10094 org-export-headline-levels))
10095
10096 ;; File header
10097 (if title (org-insert-centered title ?=))
10098 (insert "\n")
10099 (if (or author email)
10100 (insert (concat (nth 1 lang-words) ": " (or author "")
10101 (if email (concat " <" email ">") "")
10102 "\n")))
10103 (if (and date time)
10104 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10105 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10106
10107 (insert "\n\n")
10108
10109 (if org-export-with-toc
10110 (progn
10111 (insert (nth 3 lang-words) "\n"
10112 (make-string (length (nth 3 lang-words)) ?=) "\n")
10113 (mapcar '(lambda (line)
10114 (if (string-match org-todo-line-regexp
10115 line)
10116 ;; This is a headline
10117 (progn
10118 (setq level (- (match-end 1) (match-beginning 1))
10119 txt (match-string 3 line)
10120 todo
10121 (or (and (match-beginning 2)
10122 (not (equal (match-string 2 line)
10123 org-done-string)))
10124 ; TODO, not DONE
10125 (and (= level umax)
10126 (org-search-todo-below
10127 line lines level))))
10128 (setq txt (org-html-expand-for-ascii txt))
10129
10130 (if org-export-with-section-numbers
10131 (setq txt (concat (org-section-number level)
10132 " " txt)))
10133 (if (<= level umax)
10134 (progn
10135 (insert
10136 (make-string (* (1- level) 4) ?\ )
10137 (format (if todo "%s (*)\n" "%s\n") txt))
10138 (setq org-last-level level))
10139 ))))
10140 lines)))
10141
10142 (org-init-section-numbers)
10143 (while (setq line (pop lines))
10144 ;; Remove the quoted HTML tags.
10145 (setq line (org-html-expand-for-ascii line))
10146 (cond
10147 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10148 ;; a Headline
10149 (setq level (- (match-end 1) (match-beginning 1))
10150 txt (match-string 2 line))
10151 (org-ascii-level-start level txt umax))
10152 (t (insert line "\n"))))
10153 (normal-mode)
10154 (save-buffer)
10155 (goto-char (point-min))))
10156
10157 (defun org-search-todo-below (line lines level)
10158 "Search the subtree below LINE for any TODO entries."
10159 (let ((rest (cdr (memq line lines)))
10160 (re org-todo-line-regexp)
10161 line lv todo)
10162 (catch 'exit
10163 (while (setq line (pop rest))
10164 (if (string-match re line)
10165 (progn
10166 (setq lv (- (match-end 1) (match-beginning 1))
10167 todo (and (match-beginning 2)
10168 (not (equal (match-string 2 line)
10169 org-done-string))))
10170 ; TODO, not DONE
10171 (if (<= lv level) (throw 'exit nil))
10172 (if todo (throw 'exit t))))))))
10173
10174 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10175 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10176 (defun org-html-expand-for-ascii (line)
10177 "Handle quoted HTML for ASCII export."
10178 (if org-export-html-expand
10179 (while (string-match "@<[^<>\n]*>" line)
10180 ;; We just remove the tags for now.
10181 (setq line (replace-match "" nil nil line))))
10182 line)
10183
10184 (defun org-insert-centered (s &optional underline)
10185 "Insert the string S centered and underline it with character UNDERLINE."
10186 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
10187 (insert (make-string ind ?\ ) s "\n")
10188 (if underline
10189 (insert (make-string ind ?\ )
10190 (make-string (length s) underline)
10191 "\n"))))
10192
10193 (defun org-ascii-level-start (level title umax)
10194 "Insert a new level in ASCII export."
10195 (let (char)
10196 (if (> level umax)
10197 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10198 (if (or (not (equal (char-before) ?\n))
10199 (not (equal (char-before (1- (point))) ?\n)))
10200 (insert "\n"))
10201 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10202 (if org-export-with-section-numbers
10203 (setq title (concat (org-section-number level) " " title)))
10204 (insert title "\n" (make-string (string-width title) char) "\n"))))
10205
10206 (defun org-export-copy-visible ()
10207 "Copy the visible part of the buffer to another buffer, for printing.
10208 Also removes the first line of the buffer if it specifies a mode,
10209 and all options lines."
10210 (interactive)
10211 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
10212 ".txt"))
10213 (buffer (find-file-noselect filename))
10214 (ore (concat
10215 (org-make-options-regexp
10216 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10217 "STARTUP" "ARCHIVE"
10218 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10219 (if org-noutline-p "\\(\n\\|$\\)" "")))
10220 s e)
10221 (with-current-buffer buffer
10222 (erase-buffer)
10223 (text-mode))
10224 (save-excursion
10225 (setq s (goto-char (point-min)))
10226 (while (not (= (point) (point-max)))
10227 (goto-char (org-find-invisible))
10228 (append-to-buffer buffer s (point))
10229 (setq s (goto-char (org-find-visible)))))
10230 (switch-to-buffer-other-window buffer)
10231 (newline)
10232 (goto-char (point-min))
10233 (if (looking-at ".*-\\*- mode:.*\n")
10234 (replace-match ""))
10235 (while (re-search-forward ore nil t)
10236 (replace-match ""))
10237 (goto-char (point-min))))
10238
10239 (defun org-find-visible ()
10240 (if (featurep 'noutline)
10241 (let ((s (point)))
10242 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10243 (get-char-property s 'invisible)))
10244 s)
10245 (skip-chars-forward "^\n")
10246 (point)))
10247 (defun org-find-invisible ()
10248 (if (featurep 'noutline)
10249 (let ((s (point)))
10250 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10251 (not (get-char-property s 'invisible))))
10252 s)
10253 (skip-chars-forward "^\r")
10254 (point)))
10255
10256 ;; HTML
10257
10258 (defun org-get-current-options ()
10259 "Return a string with current options as keyword options.
10260 Does include HTML export options as well as TODO and CATEGORY stuff."
10261 (format
10262 "#+TITLE: %s
10263 #+AUTHOR: %s
10264 #+EMAIL: %s
10265 #+LANGUAGE: %s
10266 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10267 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10268 #+CATEGORY: %s
10269 #+SEQ_TODO: %s
10270 #+TYP_TODO: %s
10271 #+STARTUP: %s %s
10272 #+ARCHIVE: %s
10273 "
10274 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10275 org-export-headline-levels
10276 org-export-with-section-numbers
10277 org-export-with-toc
10278 org-export-preserve-breaks
10279 org-export-html-expand
10280 org-export-with-fixed-width
10281 org-export-with-tables
10282 org-export-with-sub-superscripts
10283 org-export-with-emphasize
10284 org-export-with-TeX-macros
10285 (file-name-nondirectory (buffer-file-name))
10286 (if (equal org-todo-interpretation 'sequence)
10287 (mapconcat 'identity org-todo-keywords " ")
10288 "TODO FEEDBACK VERIFY DONE")
10289 (if (equal org-todo-interpretation 'type)
10290 (mapconcat 'identity org-todo-keywords " ")
10291 "Me Jason Marie DONE")
10292 (cdr (assoc org-startup-folded
10293 '((nil . "nofold")(t . "fold")(content . "content"))))
10294 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10295 org-archive-location
10296 ))
10297
10298 (defun org-insert-export-options-template ()
10299 "Insert into the buffer a template with information for exporting."
10300 (interactive)
10301 (if (not (bolp)) (newline))
10302 (let ((s (org-get-current-options)))
10303 (and (string-match "#\\+CATEGORY" s)
10304 (setq s (substring s 0 (match-beginning 0))))
10305 (insert s)))
10306
10307 (defun org-toggle-fixed-width-section (arg)
10308 "Toggle the fixed-width export.
10309 If there is no active region, the QUOTE keyword at the current headline is
10310 inserted or removed. When present, it causes the text between this headline
10311 and the next to be exported as fixed-width text, and unmodified.
10312 If there is an active region, this command adds or removes a colon as the
10313 first character of this line. If the first character of a line is a colon,
10314 this line is also exported in fixed-width font."
10315 (interactive "P")
10316 (let* ((cc 0)
10317 (regionp (org-region-active-p))
10318 (beg (if regionp (region-beginning) (point)))
10319 (end (if regionp (region-end)))
10320 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10321 (re "[ \t]*\\(:\\)")
10322 off)
10323 (if regionp
10324 (save-excursion
10325 (goto-char beg)
10326 (setq cc (current-column))
10327 (beginning-of-line 1)
10328 (setq off (looking-at re))
10329 (while (> nlines 0)
10330 (setq nlines (1- nlines))
10331 (beginning-of-line 1)
10332 (cond
10333 (arg
10334 (move-to-column cc t)
10335 (insert ":\n")
10336 (forward-line -1))
10337 ((and off (looking-at re))
10338 (replace-match "" t t nil 1))
10339 ((not off) (move-to-column cc t) (insert ":")))
10340 (forward-line 1)))
10341 (save-excursion
10342 (org-back-to-heading)
10343 (if (looking-at (concat outline-regexp
10344 "\\( +\\<" org-quote-string "\\>\\)"))
10345 (replace-match "" t t nil 1)
10346 (if (looking-at outline-regexp)
10347 (progn
10348 (goto-char (match-end 0))
10349 (insert " " org-quote-string))))))))
10350
10351 (defun org-export-as-html-and-open (arg)
10352 "Export the outline as HTML and immediately open it with a browser.
10353 If there is an active region, export only the region.
10354 The prefix ARG specifies how many levels of the outline should become
10355 headlines. The default is 3. Lower levels will become bulleted lists."
10356 (interactive "P")
10357 (org-export-as-html arg 'hidden)
10358 (org-open-file (buffer-file-name)))
10359
10360 (defun org-export-as-html-batch ()
10361 "Call `org-export-as-html', may be used in batch processing as
10362 emacs --batch
10363 --load=$HOME/lib/emacs/org.el
10364 --eval \"(setq org-export-headline-levels 2)\"
10365 --visit=MyFile --funcall org-export-as-html-batch"
10366 (org-export-as-html org-export-headline-levels 'hidden))
10367
10368 (defun org-export-as-html (arg &optional hidden)
10369 "Export the outline as a pretty HTML file.
10370 If there is an active region, export only the region.
10371 The prefix ARG specifies how many levels of the outline should become
10372 headlines. The default is 3. Lower levels will become bulleted lists."
10373 (interactive "P")
10374 (setq-default org-todo-line-regexp org-todo-line-regexp)
10375 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
10376 (setq-default org-done-string org-done-string)
10377 (let* ((style org-export-html-style)
10378 (region-p (org-region-active-p))
10379 (region
10380 (buffer-substring
10381 (if region-p (region-beginning) (point-min))
10382 (if region-p (region-end) (point-max))))
10383 (all_lines
10384 (org-skip-comments (org-split-string region "[\r\n]")))
10385 (lines (org-export-find-first-heading-line all_lines))
10386 (level 0) (line "") (origline "") txt todo
10387 (umax nil)
10388 (filename (concat (file-name-sans-extension (buffer-file-name))
10389 ".html"))
10390 (buffer (find-file-noselect filename))
10391 (levels-open (make-vector org-level-max nil))
10392 (date (format-time-string "%Y/%m/%d" (current-time)))
10393 (time (format-time-string "%X" (current-time)))
10394 (author user-full-name)
10395 (title (buffer-name))
10396 (options nil)
10397 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
10398 (inquote nil)
10399 (infixed nil)
10400 (in-local-list nil)
10401 (local-list-num nil)
10402 (local-list-indent nil)
10403 (llt org-plain-list-ordered-item-terminator)
10404 (email user-mail-address)
10405 (language org-export-default-language)
10406 (text nil)
10407 (lang-words nil)
10408 (head-count 0) cnt
10409 (start 0)
10410 ;; FIXME: The following returns always nil under XEmacs
10411 (coding-system (and (fboundp 'coding-system-get)
10412 (boundp 'buffer-file-coding-system)
10413 buffer-file-coding-system))
10414 (coding-system-for-write (or coding-system coding-system-for-write))
10415 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
10416 (charset (and coding-system
10417 (coding-system-get coding-system 'mime-charset)))
10418 table-open type
10419 table-buffer table-orig-buffer
10420 ind start-is-num starter
10421 )
10422 (message "Exporting...")
10423
10424 (setq org-last-level 1)
10425 (org-init-section-numbers)
10426
10427 ;; Search for the export key lines
10428 (org-parse-key-lines)
10429 (setq lang-words (or (assoc language org-export-language-setup)
10430 (assoc "en" org-export-language-setup)))
10431
10432 ;; Switch to the output buffer
10433 (if (or hidden (not org-export-html-show-new-buffer))
10434 (set-buffer buffer)
10435 (switch-to-buffer-other-window buffer))
10436 (erase-buffer)
10437 (fundamental-mode)
10438 (let ((case-fold-search nil))
10439 (if options (org-parse-export-options options))
10440 (setq umax (if arg (prefix-numeric-value arg)
10441 org-export-headline-levels))
10442
10443 ;; File header
10444 (insert (format
10445 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
10446 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
10447 <html lang=\"%s\"><head>
10448 <title>%s</title>
10449 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
10450 <meta name=generator content=\"Org-mode\">
10451 <meta name=generated content=\"%s %s\">
10452 <meta name=author content=\"%s\">
10453 %s
10454 </head><body>
10455 "
10456 language (org-html-expand title) (or charset "iso-8859-1")
10457 date time author style))
10458 (if title (insert (concat "<H1 class=\"title\">"
10459 (org-html-expand title) "</H1>\n")))
10460 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
10461 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
10462 email "&gt;</a>\n")))
10463 (if (or author email) (insert "<br>\n"))
10464 (if (and date time) (insert (concat (nth 2 lang-words) ": "
10465 date " " time "<br>\n")))
10466 (if text (insert (concat "<p>\n" (org-html-expand text))))
10467 (if org-export-with-toc
10468 (progn
10469 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
10470 (insert "<ul>\n")
10471 (mapcar '(lambda (line)
10472 (if (string-match org-todo-line-regexp line)
10473 ;; This is a headline
10474 (progn
10475 (setq level (- (match-end 1) (match-beginning 1))
10476 txt (save-match-data
10477 (org-html-expand
10478 (match-string 3 line)))
10479 todo
10480 (or (and (match-beginning 2)
10481 (not (equal (match-string 2 line)
10482 org-done-string)))
10483 ; TODO, not DONE
10484 (and (= level umax)
10485 (org-search-todo-below
10486 line lines level))))
10487 (if org-export-with-section-numbers
10488 (setq txt (concat (org-section-number level)
10489 " " txt)))
10490 (if (<= level umax)
10491 (progn
10492 (setq head-count (+ head-count 1))
10493 (if (> level org-last-level)
10494 (progn
10495 (setq cnt (- level org-last-level))
10496 (while (>= (setq cnt (1- cnt)) 0)
10497 (insert "<ul>"))
10498 (insert "\n")))
10499 (if (< level org-last-level)
10500 (progn
10501 (setq cnt (- org-last-level level))
10502 (while (>= (setq cnt (1- cnt)) 0)
10503 (insert "</ul>"))
10504 (insert "\n")))
10505 (insert
10506 (format
10507 (if todo
10508 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
10509 "<li><a href=\"#sec-%d\">%s</a>\n")
10510 head-count txt))
10511 (setq org-last-level level))
10512 ))))
10513 lines)
10514 (while (> org-last-level 0)
10515 (setq org-last-level (1- org-last-level))
10516 (insert "</ul>\n"))
10517 ))
10518 (setq head-count 0)
10519 (org-init-section-numbers)
10520
10521 (while (setq line (pop lines) origline line)
10522 (catch 'nextline
10523
10524 ;; end of quote section?
10525 (when (and inquote (string-match "^\\*+" line))
10526 (insert "</pre>\n")
10527 (setq inquote nil))
10528 ;; inside a quote section?
10529 (when inquote
10530 (insert (org-html-protect line) "\n")
10531 (throw 'nextline nil))
10532
10533 ;; verbatim lines
10534 (when (and org-export-with-fixed-width
10535 (string-match "^[ \t]*:\\(.*\\)" line))
10536 (when (not infixed)
10537 (setq infixed t)
10538 (insert "<pre>\n"))
10539 (insert (org-html-protect (match-string 1 line)) "\n")
10540 (when (and lines
10541 (not (string-match "^[ \t]*\\(:.*\\)"
10542 (car lines))))
10543 (setq infixed nil)
10544 (insert "</pre>\n"))
10545 (throw 'nextline nil))
10546
10547 ;; Protect the links
10548 (setq start 0)
10549 (while (string-match org-link-maybe-angles-regexp line start)
10550 (setq start (match-end 0))
10551 (setq line (replace-match
10552 (concat "\000" (match-string 1 line) "\000")
10553 t t line)))
10554
10555 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
10556 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
10557 (setq line (org-html-expand line))
10558
10559 ;; Format the links
10560 (setq start 0)
10561 (while (string-match org-protected-link-regexp line start)
10562 (setq start (- (match-end 0) 2))
10563 (setq type (match-string 1 line))
10564 (cond
10565 ((member type '("http" "https" "ftp" "mailto" "news"))
10566 ;; standard URL
10567 (setq line (replace-match
10568 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
10569 "<a href=\"\\1:\\2\">\\1:\\2</a>"
10570 nil nil line)))
10571 ((string= type "file")
10572 ;; FILE link
10573 (let* ((filename (match-string 2 line))
10574 (abs-p (file-name-absolute-p filename))
10575 (thefile (if abs-p (expand-file-name filename) filename))
10576 (thefile (save-match-data
10577 (if (string-match ":[0-9]+$" thefile)
10578 (replace-match "" t t thefile)
10579 thefile)))
10580 (file-is-image-p
10581 (save-match-data
10582 (string-match (org-image-file-name-regexp) thefile))))
10583 (setq line (replace-match
10584 (if (and org-export-html-inline-images
10585 file-is-image-p)
10586 (concat "<img src=\"" thefile "\"/>")
10587 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
10588 nil nil line))))
10589
10590 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
10591 (setq line (replace-match
10592 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
10593
10594 ;; TODO items
10595 (if (and (string-match org-todo-line-regexp line)
10596 (match-beginning 2))
10597 (if (equal (match-string 2 line) org-done-string)
10598 (setq line (replace-match
10599 "<span class=\"done\">\\2</span>"
10600 nil nil line 2))
10601 (setq line (replace-match "<span class=\"todo\">\\2</span>"
10602 nil nil line 2))))
10603
10604 ;; DEADLINES
10605 (if (string-match org-deadline-line-regexp line)
10606 (progn
10607 (if (save-match-data
10608 (string-match "<a href"
10609 (substring line 0 (match-beginning 0))))
10610 nil ; Don't do the replacement - it is inside a link
10611 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
10612 nil nil line 1)))))
10613 (cond
10614 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10615 ;; This is a headline
10616 (setq level (- (match-end 1) (match-beginning 1))
10617 txt (match-string 2 line))
10618 (if (<= level umax) (setq head-count (+ head-count 1)))
10619 (when in-local-list
10620 ;; Close any local lists before inserting a new header line
10621 (while local-list-num
10622 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10623 (pop local-list-num))
10624 (setq local-list-indent nil
10625 in-local-list nil))
10626 (org-html-level-start level txt umax
10627 (and org-export-with-toc (<= level umax))
10628 head-count)
10629 ;; QUOTES
10630 (when (string-match quote-re line)
10631 (insert "<pre>")
10632 (setq inquote t)))
10633
10634 ((and org-export-with-tables
10635 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
10636 (if (not table-open)
10637 ;; New table starts
10638 (setq table-open t table-buffer nil table-orig-buffer nil))
10639 ;; Accumulate lines
10640 (setq table-buffer (cons line table-buffer)
10641 table-orig-buffer (cons origline table-orig-buffer))
10642 (when (or (not lines)
10643 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
10644 (car lines))))
10645 (setq table-open nil
10646 table-buffer (nreverse table-buffer)
10647 table-orig-buffer (nreverse table-orig-buffer))
10648 (insert (org-format-table-html table-buffer table-orig-buffer))))
10649 (t
10650 ;; Normal lines
10651 (when (and (> org-export-plain-list-max-depth 0)
10652 (string-match
10653 (cond
10654 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10655 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10656 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10657 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
10658 line))
10659 (setq ind (org-get-string-indentation line)
10660 start-is-num (match-beginning 4)
10661 starter (if (match-beginning 2) (match-string 2 line))
10662 line (substring line (match-beginning 5)))
10663 (unless (string-match "[^ \t]" line)
10664 ;; empty line. Pretend indentation is large.
10665 (setq ind (1+ (or (car local-list-indent) 1))))
10666 (while (and in-local-list
10667 (or (and (= ind (car local-list-indent))
10668 (not starter))
10669 (< ind (car local-list-indent))))
10670 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10671 (pop local-list-num) (pop local-list-indent)
10672 (setq in-local-list local-list-indent))
10673 (cond
10674 ((and starter
10675 (or (not in-local-list)
10676 (> ind (car local-list-indent)))
10677 (< (length local-list-indent)
10678 org-export-plain-list-max-depth))
10679 ;; Start new (level of ) list
10680 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
10681 (push start-is-num local-list-num)
10682 (push ind local-list-indent)
10683 (setq in-local-list t))
10684 (starter
10685 ;; continue current list
10686 (insert "<li>\n"))))
10687 ;; Empty lines start a new paragraph. If hand-formatted lists
10688 ;; are not fully interpreted, lines starting with "-", "+", "*"
10689 ;; also start a new paragraph.
10690 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
10691 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
10692 ))
10693 (if org-export-html-with-timestamp
10694 (insert org-export-html-html-helper-timestamp))
10695 (insert "</body>\n</html>\n")
10696 (normal-mode)
10697 (save-buffer)
10698 (goto-char (point-min)))))
10699
10700 (defun org-format-table-html (lines olines)
10701 "Find out which HTML converter to use and return the HTML code."
10702 (if (string-match "^[ \t]*|" (car lines))
10703 ;; A normal org table
10704 (org-format-org-table-html lines)
10705 ;; Table made by table.el - test for spanning
10706 (let* ((hlines (delq nil (mapcar
10707 (lambda (x)
10708 (if (string-match "^[ \t]*\\+-" x) x
10709 nil))
10710 lines)))
10711 (first (car hlines))
10712 (ll (and (string-match "\\S-+" first)
10713 (match-string 0 first)))
10714 (re (concat "^[ \t]*" (regexp-quote ll)))
10715 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
10716 hlines))))
10717 (if (and (not spanning)
10718 (not org-export-prefer-native-exporter-for-tables))
10719 ;; We can use my own converter with HTML conversions
10720 (org-format-table-table-html lines)
10721 ;; Need to use the code generator in table.el, with the original text.
10722 (org-format-table-table-html-using-table-generate-source olines)))))
10723
10724 (defun org-format-org-table-html (lines)
10725 "Format a table into html."
10726 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10727 (setq lines (nreverse lines))
10728 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10729 (setq lines (nreverse lines))
10730 (let ((head (and org-export-highlight-first-table-line
10731 (delq nil (mapcar
10732 (lambda (x) (string-match "^[ \t]*|-" x))
10733 (cdr lines)))))
10734 line fields html)
10735 (setq html (concat org-export-html-table-tag "\n"))
10736 (while (setq line (pop lines))
10737 (catch 'next-line
10738 (if (string-match "^[ \t]*|-" line)
10739 (progn
10740 (setq head nil) ;; head ends here, first time around
10741 ;; ignore this line
10742 (throw 'next-line t)))
10743 ;; Break the line into fields
10744 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10745 (setq html (concat
10746 html
10747 "<tr>"
10748 (mapconcat (lambda (x)
10749 (if head
10750 (concat "<th>" x "</th>")
10751 (concat "<td>" x "</td>")))
10752 fields "")
10753 "</tr>\n"))))
10754 (setq html (concat html "</table>\n"))
10755 html))
10756
10757 (defun org-fake-empty-table-line (line)
10758 "Replace everything except \"|\" with spaces."
10759 (let ((i (length line))
10760 (newstr (copy-sequence line)))
10761 (while (> i 0)
10762 (setq i (1- i))
10763 (if (not (eq (aref newstr i) ?|))
10764 (aset newstr i ?\ )))
10765 newstr))
10766
10767 (defun org-format-table-table-html (lines)
10768 "Format a table generated by table.el into html.
10769 This conversion does *not* use `table-generate-source' from table.el.
10770 This has the advantage that Org-mode's HTML conversions can be used.
10771 But it has the disadvantage, that no cell- or row-spanning is allowed."
10772 (let (line field-buffer
10773 (head org-export-highlight-first-table-line)
10774 fields html empty)
10775 (setq html (concat org-export-html-table-tag "\n"))
10776 (while (setq line (pop lines))
10777 (setq empty "&nbsp")
10778 (catch 'next-line
10779 (if (string-match "^[ \t]*\\+-" line)
10780 (progn
10781 (if field-buffer
10782 (progn
10783 (setq html (concat
10784 html
10785 "<tr>"
10786 (mapconcat
10787 (lambda (x)
10788 (if (equal x "") (setq x empty))
10789 (if head
10790 (concat "<th>" x "</th>\n")
10791 (concat "<td>" x "</td>\n")))
10792 field-buffer "\n")
10793 "</tr>\n"))
10794 (setq head nil)
10795 (setq field-buffer nil)))
10796 ;; Ignore this line
10797 (throw 'next-line t)))
10798 ;; Break the line into fields and store the fields
10799 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10800 (if field-buffer
10801 (setq field-buffer (mapcar
10802 (lambda (x)
10803 (concat x "<br>" (pop fields)))
10804 field-buffer))
10805 (setq field-buffer fields))))
10806 (setq html (concat html "</table>\n"))
10807 html))
10808
10809 (defun org-format-table-table-html-using-table-generate-source (lines)
10810 "Format a table into html, using `table-generate-source' from table.el.
10811 This has the advantage that cell- or row-spanning is allowed.
10812 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
10813 (require 'table)
10814 (with-current-buffer (get-buffer-create " org-tmp1 ")
10815 (erase-buffer)
10816 (insert (mapconcat 'identity lines "\n"))
10817 (goto-char (point-min))
10818 (if (not (re-search-forward "|[^+]" nil t))
10819 (error "Error processing table"))
10820 (table-recognize-table)
10821 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
10822 (table-generate-source 'html " org-tmp2 ")
10823 (set-buffer " org-tmp2 ")
10824 (buffer-substring (point-min) (point-max))))
10825
10826 (defun org-html-protect (s)
10827 ;; convert & to &amp;, < to &lt; and > to &gt;
10828 (let ((start 0))
10829 (while (string-match "&" s start)
10830 (setq s (replace-match "&amp;" t t s)
10831 start (1+ (match-beginning 0))))
10832 (while (string-match "<" s)
10833 (setq s (replace-match "&lt;" t t s)))
10834 (while (string-match ">" s)
10835 (setq s (replace-match "&gt;" t t s))))
10836 s)
10837
10838 (defun org-html-expand (string)
10839 "Prepare STRING for HTML export. Applies all active conversions."
10840 ;; First check if there is a link in the line - if yes, apply conversions
10841 ;; only before the start of the link.
10842 ;; FIXME: This is no longer correct, because links now have an end.
10843 (let* ((m (string-match org-link-regexp string))
10844 (s (if m (substring string 0 m) string))
10845 (r (if m (substring string m) "")))
10846 ;; convert & to &amp;, < to &lt; and > to &gt;
10847 (setq s (org-html-protect s))
10848 (if org-export-html-expand
10849 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
10850 (setq s (replace-match "<\\1>" nil nil s))))
10851 (if org-export-with-emphasize
10852 (setq s (org-export-html-convert-emphasize s)))
10853 (if org-export-with-sub-superscripts
10854 (setq s (org-export-html-convert-sub-super s)))
10855 (if org-export-with-TeX-macros
10856 (let ((start 0) wd ass)
10857 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
10858 (setq wd (match-string 1 s))
10859 (if (setq ass (assoc wd org-html-entities))
10860 (setq s (replace-match (or (cdr ass)
10861 (concat "&" (car ass) ";"))
10862 t t s))
10863 (setq start (+ start (length wd)))))))
10864 (concat s r)))
10865
10866 (defun org-create-multibrace-regexp (left right n)
10867 "Create a regular expression which will match a balanced sexp.
10868 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
10869 as single character strings.
10870 The regexp returned will match the entire expression including the
10871 delimiters. It will also define a single group which contains the
10872 match except for the outermost delimiters. The maximum depth of
10873 stacked delimiters is N. Escaping delimiters is not possible."
10874 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
10875 (or "\\|")
10876 (re nothing)
10877 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
10878 (while (> n 1)
10879 (setq n (1- n)
10880 re (concat re or next)
10881 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
10882 (concat left "\\(" re "\\)" right)))
10883
10884 (defvar org-match-substring-regexp
10885 (concat
10886 "\\([^\\]\\)\\([_^]\\)\\("
10887 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
10888 "\\|"
10889 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
10890 "\\|"
10891 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
10892 "The regular expression matching a sub- or superscript.")
10893
10894 (defun org-export-html-convert-sub-super (string)
10895 "Convert sub- and superscripts in STRING to HTML."
10896 (let (key c)
10897 (while (string-match org-match-substring-regexp string)
10898 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
10899 (setq c (or (match-string 8 string)
10900 (match-string 6 string)
10901 (match-string 5 string)))
10902 (setq string (replace-match
10903 (concat (match-string 1 string)
10904 "<" key ">" c "</" key ">")
10905 t t string)))
10906 (while (string-match "\\\\\\([_^]\\)" string)
10907 (setq string (replace-match (match-string 1 string) t t string))))
10908 string)
10909
10910 (defun org-export-html-convert-emphasize (string)
10911 (while (string-match
10912 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
10913 string)
10914 (setq string (replace-match
10915 (concat "<b>" (match-string 3 string) "</b>")
10916 t t string 2)))
10917 (while (string-match
10918 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
10919 string)
10920 (setq string (replace-match
10921 (concat "<i>" (match-string 3 string) "</i>")
10922 t t string 2)))
10923 (while (string-match
10924 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
10925 string)
10926 (setq string (replace-match
10927 (concat "<u>" (match-string 3 string) "</u>")
10928 t t string 2)))
10929 string)
10930
10931 (defun org-parse-key-lines ()
10932 "Find the special key lines with the information for exporters."
10933 (save-excursion
10934 (goto-char 0)
10935 (let ((re (org-make-options-regexp
10936 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
10937 key)
10938 (while (re-search-forward re nil t)
10939 (setq key (match-string 1))
10940 (cond ((string-equal key "TITLE")
10941 (setq title (match-string 2)))
10942 ((string-equal key "AUTHOR")
10943 (setq author (match-string 2)))
10944 ((string-equal key "EMAIL")
10945 (setq email (match-string 2)))
10946 ((string-equal key "LANGUAGE")
10947 (setq language (match-string 2)))
10948 ((string-equal key "TEXT")
10949 (setq text (concat text "\n" (match-string 2))))
10950 ((string-equal key "OPTIONS")
10951 (setq options (match-string 2))))))))
10952
10953 (defun org-parse-export-options (s)
10954 "Parse the export options line."
10955 (let ((op '(("H" . org-export-headline-levels)
10956 ("num" . org-export-with-section-numbers)
10957 ("toc" . org-export-with-toc)
10958 ("\\n" . org-export-preserve-breaks)
10959 ("@" . org-export-html-expand)
10960 (":" . org-export-with-fixed-width)
10961 ("|" . org-export-with-tables)
10962 ("^" . org-export-with-sub-superscripts)
10963 ("*" . org-export-with-emphasize)
10964 ("TeX" . org-export-with-TeX-macros)))
10965 o)
10966 (while (setq o (pop op))
10967 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
10968 s)
10969 (set (make-local-variable (cdr o))
10970 (car (read-from-string (match-string 1 s))))))))
10971
10972 (defun org-html-level-start (level title umax with-toc head-count)
10973 "Insert a new level in HTML export."
10974 (let ((l (1+ (max level umax))))
10975 (while (<= l org-level-max)
10976 (if (aref levels-open (1- l))
10977 (progn
10978 (org-html-level-close l)
10979 (aset levels-open (1- l) nil)))
10980 (setq l (1+ l)))
10981 (if (> level umax)
10982 (progn
10983 (if (aref levels-open (1- level))
10984 (insert "<li>" title "<p>\n")
10985 (aset levels-open (1- level) t)
10986 (insert "<ul><li>" title "<p>\n")))
10987 (if org-export-with-section-numbers
10988 (setq title (concat (org-section-number level) " " title)))
10989 (setq level (+ level 1))
10990 (if with-toc
10991 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
10992 level head-count title level))
10993 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
10994
10995 (defun org-html-level-close (&rest args)
10996 "Terminate one level in HTML export."
10997 (insert "</ul>"))
10998
10999 ;; Variable holding the vector with section numbers
11000 (defvar org-section-numbers (make-vector org-level-max 0))
11001
11002 (defun org-init-section-numbers ()
11003 "Initialize the vector for the section numbers."
11004 (let* ((level -1)
11005 (numbers (nreverse (org-split-string "" "\\.")))
11006 (depth (1- (length org-section-numbers)))
11007 (i depth) number-string)
11008 (while (>= i 0)
11009 (if (> i level)
11010 (aset org-section-numbers i 0)
11011 (setq number-string (or (car numbers) "0"))
11012 (if (string-match "\\`[A-Z]\\'" number-string)
11013 (aset org-section-numbers i
11014 (- (string-to-char number-string) ?A -1))
11015 (aset org-section-numbers i (string-to-number number-string)))
11016 (pop numbers))
11017 (setq i (1- i)))))
11018
11019 (defun org-section-number (&optional level)
11020 "Return a string with the current section number.
11021 When LEVEL is non-nil, increase section numbers on that level."
11022 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
11023 (when level
11024 (when (> level -1)
11025 (aset org-section-numbers
11026 level (1+ (aref org-section-numbers level))))
11027 (setq idx (1+ level))
11028 (while (<= idx depth)
11029 (if (not (= idx 1))
11030 (aset org-section-numbers idx 0))
11031 (setq idx (1+ idx))))
11032 (setq idx 0)
11033 (while (<= idx depth)
11034 (setq n (aref org-section-numbers idx))
11035 (setq string (concat string (if (not (string= string "")) "." "")
11036 (int-to-string n)))
11037 (setq idx (1+ idx)))
11038 (save-match-data
11039 (if (string-match "\\`\\([@0]\\.\\)+" string)
11040 (setq string (replace-match "" nil nil string)))
11041 (if (string-match "\\(\\.0\\)+\\'" string)
11042 (setq string (replace-match "" nil nil string))))
11043 string))
11044
11045
11046 (defun org-export-icalendar-this-file ()
11047 "Export current file as an iCalendar file.
11048 The iCalendar file will be located in the same directory as the Org-mode
11049 file, but with extension `.ics'."
11050 (interactive)
11051 (org-export-icalendar nil (buffer-file-name)))
11052
11053 ;;;###autoload
11054 (defun org-export-icalendar-all-agenda-files ()
11055 "Export all files in `org-agenda-files' to iCalendar .ics files.
11056 Each iCalendar file will be located in the same directory as the Org-mode
11057 file, but with extension `.ics'."
11058 (interactive)
11059 (apply 'org-export-icalendar nil org-agenda-files))
11060
11061 ;;;###autoload
11062 (defun org-export-icalendar-combine-agenda-files ()
11063 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11064 The file is stored under the name `org-combined-agenda-icalendar-file'."
11065 (interactive)
11066 (apply 'org-export-icalendar t org-agenda-files))
11067
11068 (defun org-export-icalendar (combine &rest files)
11069 "Create iCalendar files for all elements of FILES.
11070 If COMBINE is non-nil, combine all calendar entries into a single large
11071 file and store it under the name `org-combined-agenda-icalendar-file'."
11072 (save-excursion
11073 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11074 (when combine
11075 (setq ical-file org-combined-agenda-icalendar-file
11076 ical-buffer (org-get-agenda-file-buffer ical-file))
11077 (set-buffer ical-buffer) (erase-buffer))
11078 (while (setq file (pop files))
11079 (catch 'nextfile
11080 (org-check-agenda-file file)
11081 (unless combine
11082 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11083 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11084 (set-buffer ical-buffer) (erase-buffer))
11085 (set-buffer (org-get-agenda-file-buffer file))
11086 (setq category (or org-category
11087 (file-name-sans-extension
11088 (file-name-nondirectory (buffer-file-name)))))
11089 (if (symbolp category) (setq category (symbol-name category)))
11090 (let ((standard-output ical-buffer))
11091 (if combine
11092 (and (not started) (setq started t)
11093 (org-start-icalendar-file org-icalendar-combined-name))
11094 (org-start-icalendar-file category))
11095 (org-print-icalendar-entries combine category)
11096 (when (or (and combine (not files)) (not combine))
11097 (org-finish-icalendar-file)
11098 (set-buffer ical-buffer)
11099 (save-buffer)
11100 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11101 (org-release-buffers org-agenda-new-buffers))))
11102
11103 (defvar org-after-save-iCalendar-file-hook nil
11104 "Hook run after an iCalendar file has been saved.
11105 The iCalendar buffer is still current when this hook is run.
11106 A good way to use this is to tell a desktop calenndar application to re-read
11107 the iCalendar file.")
11108
11109 (defun org-print-icalendar-entries (&optional combine category)
11110 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11111 When COMBINE is non nil, add the category to each line."
11112 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11113 (dts (org-ical-ts-to-string
11114 (format-time-string (cdr org-time-stamp-formats) (current-time))
11115 "DTSTART"))
11116 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11117 (save-excursion
11118 (goto-char (point-min))
11119 (while (re-search-forward org-ts-regexp nil t)
11120 (setq pos (match-beginning 0)
11121 ts (match-string 0)
11122 inc t
11123 hd (org-get-heading))
11124 (if (looking-at re2)
11125 (progn
11126 (goto-char (match-end 0))
11127 (setq ts2 (match-string 1) inc nil))
11128 (setq ts2 ts
11129 tmp (buffer-substring (max (point-min)
11130 (- pos org-ds-keyword-length))
11131 pos)
11132 deadlinep (string-match org-deadline-regexp tmp)
11133 scheduledp (string-match org-scheduled-regexp tmp)
11134 ;; donep (org-entry-is-done-p)
11135 ))
11136 (if (or (string-match org-tr-regexp hd)
11137 (string-match org-ts-regexp hd))
11138 (setq hd (replace-match "" t t hd)))
11139 (if combine
11140 (setq hd (concat hd " (category " category ")")))
11141 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11142 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11143 (princ (format "BEGIN:VEVENT
11144 %s
11145 %s
11146 SUMMARY:%s
11147 END:VEVENT\n"
11148 (org-ical-ts-to-string ts "DTSTART")
11149 (org-ical-ts-to-string ts2 "DTEND" inc)
11150 hd)))
11151 (when org-icalendar-include-todo
11152 (goto-char (point-min))
11153 (while (re-search-forward org-todo-line-regexp nil t)
11154 (setq state (match-string 1))
11155 (unless (equal state org-done-string)
11156 (setq hd (match-string 3))
11157 (if (string-match org-priority-regexp hd)
11158 (setq pri (string-to-char (match-string 2 hd))
11159 hd (concat (substring hd 0 (match-beginning 1))
11160 (substring hd (- (match-end 1)))))
11161 (setq pri org-default-priority))
11162 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11163 (- org-lowest-priority ?A))))))
11164
11165 (princ (format "BEGIN:VTODO
11166 %s
11167 SUMMARY:%s
11168 SEQUENCE:1
11169 PRIORITY:%d
11170 END:VTODO\n"
11171 dts hd pri))))))))
11172
11173 (defun org-start-icalendar-file (name)
11174 "Start an iCalendar file by inserting the header."
11175 (let ((user user-full-name)
11176 (name (or name "unknown"))
11177 (timezone (cadr (current-time-zone))))
11178 (princ
11179 (format "BEGIN:VCALENDAR
11180 VERSION:2.0
11181 X-WR-CALNAME:%s
11182 PRODID:-//%s//Emacs with Org-mode//EN
11183 X-WR-TIMEZONE:%s
11184 CALSCALE:GREGORIAN\n" name user timezone))))
11185
11186 (defun org-finish-icalendar-file ()
11187 "Finish an iCalendar file by inserting the END statement."
11188 (princ "END:VCALENDAR\n"))
11189
11190 (defun org-ical-ts-to-string (s keyword &optional inc)
11191 "Take a time string S and convert it to iCalendar format.
11192 KEYWORD is added in front, to make a complete line like DTSTART....
11193 When INC is non-nil, increase the hour by two (if time string contains
11194 a time), or the day by one (if it does not contain a time)."
11195 (let ((t1 (org-parse-time-string s 'nodefault))
11196 t2 fmt have-time time)
11197 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11198 (setq t2 t1 have-time t)
11199 (setq t2 (org-parse-time-string s)))
11200 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11201 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11202 (when inc
11203 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11204 (setq time (encode-time s mi h d m y)))
11205 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11206 (concat keyword (format-time-string fmt time))))
11207
11208
11209 ;;; Key bindings
11210
11211 ;; - Bindings in Org-mode map are currently
11212 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11213 ;; abcd fgh j lmnopqrstuvwxyz!? #$ -+*/= [] ; |,.<>~ \t necessary bindings
11214 ;; e (?) useful from outline-mode
11215 ;; i k @ expendable from outline-mode
11216 ;; 0123456789 %^& ()_{} " `' free
11217
11218 ;; Make `C-c C-x' a prefix key
11219 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11220
11221 ;; TAB key with modifiers
11222 (define-key org-mode-map "\C-i" 'org-cycle)
11223 (define-key org-mode-map [(meta tab)] 'org-complete)
11224 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11225 ;; The following line is necessary under Suse GNU/Linux
11226 (unless org-xemacs-p
11227 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11228 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11229
11230 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11231 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11232 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11233 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11234 (define-key org-mode-map [(meta return)] 'org-meta-return)
11235 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11236 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11237
11238 ;; Cursor keys with modifiers
11239 (define-key org-mode-map [(meta left)] 'org-metaleft)
11240 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11241 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11242 (define-key org-mode-map [(meta right)] 'org-metaright)
11243 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11244 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11245 (define-key org-mode-map [(meta up)] 'org-metaup)
11246 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11247 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11248 (define-key org-mode-map [(meta down)] 'org-metadown)
11249 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11250 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11251
11252 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11253 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11254 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11255 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11256 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11257 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11258 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11259 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11260 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11261 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11262 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11263 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11264 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11265 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11266 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11267 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11268
11269 ;; All the other keys
11270 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11271 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11272 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11273 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11274 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11275 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11276 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11277 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11278 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11279 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11280 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11281 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11282 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11283 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11284 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11285 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11286 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11287 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11288 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11289 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11290 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11291 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11292 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
11293 (define-key org-mode-map "\C-c]" 'org-remove-file)
11294 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
11295 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
11296 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
11297 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11298 (define-key org-mode-map "\C-m" 'org-return)
11299 (define-key org-mode-map "\C-c?" 'org-table-current-column)
11300 (define-key org-mode-map "\C-c " 'org-table-blank-field)
11301 (define-key org-mode-map "\C-c+" 'org-table-sum)
11302 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
11303 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
11304 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
11305 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
11306 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11307 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
11308 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11309 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
11310 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
11311 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
11312 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
11313 ;; OPML support is only an option for the future
11314 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
11315 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
11316 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
11317 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
11318 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
11319 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11320 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
11321 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11322 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
11323 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
11324 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
11325
11326 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11327 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11328 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11329
11330 (defsubst org-table-p () (org-at-table-p))
11331
11332 (defun org-self-insert-command (N)
11333 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11334 If the cursor is in a table looking at whitespace, the whitespace is
11335 overwritten, and the table is not marked as requiring realignment."
11336 (interactive "p")
11337 (if (and (org-table-p)
11338 (or
11339 (and org-table-auto-blank-field
11340 (member last-command
11341 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11342 (org-table-blank-field))
11343 t)
11344 (eq N 1)
11345 (looking-at "[^|\n]* +|"))
11346 (let (org-table-may-need-update)
11347 (goto-char (1- (match-end 0)))
11348 (delete-backward-char 1)
11349 (goto-char (match-beginning 0))
11350 (self-insert-command N))
11351 (setq org-table-may-need-update t)
11352 (self-insert-command N)))
11353
11354 ;; FIXME:
11355 ;; The following two functions might still be optimized to trigger
11356 ;; re-alignment less frequently.
11357
11358 (defun org-delete-backward-char (N)
11359 "Like `delete-backward-char', insert whitespace at field end in tables.
11360 When deleting backwards, in tables this function will insert whitespace in
11361 front of the next \"|\" separator, to keep the table aligned. The table will
11362 still be marked for re-alignment, because a narrow field may lead to a
11363 reduced column width."
11364 (interactive "p")
11365 (if (and (org-table-p)
11366 (eq N 1)
11367 (string-match "|" (buffer-substring (point-at-bol) (point)))
11368 (looking-at ".*?|"))
11369 (let ((pos (point)))
11370 (backward-delete-char N)
11371 (skip-chars-forward "^|")
11372 (insert " ")
11373 (goto-char (1- pos)))
11374 (backward-delete-char N)))
11375
11376 (defun org-delete-char (N)
11377 "Like `delete-char', but insert whitespace at field end in tables.
11378 When deleting characters, in tables this function will insert whitespace in
11379 front of the next \"|\" separator, to keep the table aligned. The table
11380 will still be marked for re-alignment, because a narrow field may lead to
11381 a reduced column width."
11382 (interactive "p")
11383 (if (and (org-table-p)
11384 (not (bolp))
11385 (not (= (char-after) ?|))
11386 (eq N 1))
11387 (if (looking-at ".*?|")
11388 (let ((pos (point)))
11389 (replace-match (concat
11390 (substring (match-string 0) 1 -1)
11391 " |"))
11392 (goto-char pos)))
11393 (delete-char N)))
11394
11395 ;; How to do this: Measure non-white length of current string
11396 ;; If equal to column width, we should realign.
11397
11398 (defun org-remap (map &rest commands)
11399 "In MAP, remap the functions given in COMMANDS.
11400 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11401 (let (new old)
11402 (while commands
11403 (setq old (pop commands) new (pop commands))
11404 (if (fboundp 'command-remapping)
11405 (define-key map (vector 'remap old) new)
11406 (substitute-key-definition old new map global-map)))))
11407
11408 (when (eq org-enable-table-editor 'optimized)
11409 ;; If the user wants maximum table support, we need to hijack
11410 ;; some standard editing functions
11411 (org-remap org-mode-map
11412 'self-insert-command 'org-self-insert-command
11413 'delete-char 'org-delete-char
11414 'delete-backward-char 'org-delete-backward-char)
11415 (define-key org-mode-map "|" 'org-force-self-insert))
11416
11417 (defun org-shiftcursor-error ()
11418 "Throw an error because Shift-Cursor command was applied in wrong context."
11419 (error "This command is active in special context like tables, headlines or timestamps"))
11420
11421 (defun org-shifttab ()
11422 "Global visibility cycling or move to previous table field.
11423 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
11424 See the individual commands for more information."
11425 (interactive)
11426 (cond
11427 ((org-at-table-p) (org-table-previous-field))
11428 (t (org-cycle '(4)))))
11429
11430 (defun org-shiftmetaleft ()
11431 "Promote subtree or delete table column.
11432 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
11433 See the individual commands for more information."
11434 (interactive)
11435 (cond
11436 ((org-at-table-p) (org-table-delete-column))
11437 ((org-on-heading-p) (org-promote-subtree))
11438 ((org-at-item-p) (call-interactively 'org-outdent-item))
11439 (t (org-shiftcursor-error))))
11440
11441 (defun org-shiftmetaright ()
11442 "Demote subtree or insert table column.
11443 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
11444 See the individual commands for more information."
11445 (interactive)
11446 (cond
11447 ((org-at-table-p) (org-table-insert-column))
11448 ((org-on-heading-p) (org-demote-subtree))
11449 ((org-at-item-p) (call-interactively 'org-indent-item))
11450 (t (org-shiftcursor-error))))
11451
11452 (defun org-shiftmetaup (&optional arg)
11453 "Move subtree up or kill table row.
11454 Calls `org-move-subtree-up' or `org-table-kill-row' or
11455 `org-move-item-up' depending on context. See the individual commands
11456 for more information."
11457 (interactive "P")
11458 (cond
11459 ((org-at-table-p) (org-table-kill-row))
11460 ((org-on-heading-p) (org-move-subtree-up arg))
11461 ((org-at-item-p) (org-move-item-up arg))
11462 (t (org-shiftcursor-error))))
11463 (defun org-shiftmetadown (&optional arg)
11464 "Move subtree down or insert table row.
11465 Calls `org-move-subtree-down' or `org-table-insert-row' or
11466 `org-move-item-down', depending on context. See the individual
11467 commands for more information."
11468 (interactive "P")
11469 (cond
11470 ((org-at-table-p) (org-table-insert-row arg))
11471 ((org-on-heading-p) (org-move-subtree-down arg))
11472 ((org-at-item-p) (org-move-item-down arg))
11473 (t (org-shiftcursor-error))))
11474
11475 (defun org-metaleft (&optional arg)
11476 "Promote heading or move table column to left.
11477 Calls `org-do-promote' or `org-table-move-column', depending on context.
11478 With no specific context, calls the Emacs default `backward-word'.
11479 See the individual commands for more information."
11480 (interactive "P")
11481 (cond
11482 ((org-at-table-p) (org-table-move-column 'left))
11483 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
11484 (t (backward-word (prefix-numeric-value arg)))))
11485
11486 (defun org-metaright (&optional arg)
11487 "Demote subtree or move table column to right.
11488 Calls `org-do-demote' or `org-table-move-column', depending on context.
11489 With no specific context, calls the Emacs default `forward-word'.
11490 See the individual commands for more information."
11491 (interactive "P")
11492 (cond
11493 ((org-at-table-p) (org-table-move-column nil))
11494 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
11495 (t (forward-word (prefix-numeric-value arg)))))
11496
11497 (defun org-metaup (&optional arg)
11498 "Move subtree up or move table row up.
11499 Calls `org-move-subtree-up' or `org-table-move-row' or
11500 `org-move-item-up', depending on context. See the individual commands
11501 for more information."
11502 (interactive "P")
11503 (cond
11504 ((org-at-table-p) (org-table-move-row 'up))
11505 ((org-on-heading-p) (org-move-subtree-up arg))
11506 ((org-at-item-p) (org-move-item-up arg))
11507 (t (org-shiftcursor-error))))
11508
11509 (defun org-metadown (&optional arg)
11510 "Move subtree down or move table row down.
11511 Calls `org-move-subtree-down' or `org-table-move-row' or
11512 `org-move-item-down', depending on context. See the individual
11513 commands for more information."
11514 (interactive "P")
11515 (cond
11516 ((org-at-table-p) (org-table-move-row nil))
11517 ((org-on-heading-p) (org-move-subtree-down arg))
11518 ((org-at-item-p) (org-move-item-down arg))
11519 (t (org-shiftcursor-error))))
11520
11521 (defun org-shiftup (&optional arg)
11522 "Increase item in timestamp or increase priority of current item.
11523 Calls `org-timestamp-up' or `org-priority-up', depending on context.
11524 See the individual commands for more information."
11525 (interactive "P")
11526 (cond
11527 ((org-at-timestamp-p) (org-timestamp-up arg))
11528 (t (org-priority-up))))
11529
11530 (defun org-shiftdown (&optional arg)
11531 "Decrease item in timestamp or decrease priority of current item.
11532 Calls `org-timestamp-down' or `org-priority-down', depending on context.
11533 See the individual commands for more information."
11534 (interactive "P")
11535 (cond
11536 ((org-at-timestamp-p) (org-timestamp-down arg))
11537 (t (org-priority-down))))
11538
11539 (defun org-shiftright ()
11540 "Next TODO keyword or timestamp one day later, depending on context."
11541 (interactive)
11542 (cond
11543 ((org-at-timestamp-p) (org-timestamp-up-day))
11544 ((org-on-heading-p) (org-todo 'right))
11545 (t (org-shiftcursor-error))))
11546
11547 (defun org-shiftleft ()
11548 "Previous TODO keyword or timestamp one day earlier, depending on context."
11549 (interactive)
11550 (cond
11551 ((org-at-timestamp-p) (org-timestamp-down-day))
11552 ((org-on-heading-p) (org-todo 'left))
11553 (t (org-shiftcursor-error))))
11554
11555 (defun org-copy-special ()
11556 "Copy region in table or copy current subtree.
11557 Calls `org-table-copy' or `org-copy-subtree', depending on context.
11558 See the individual commands for more information."
11559 (interactive)
11560 (call-interactively
11561 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
11562
11563 (defun org-cut-special ()
11564 "Cut region in table or cut current subtree.
11565 Calls `org-table-copy' or `org-cut-subtree', depending on context.
11566 See the individual commands for more information."
11567 (interactive)
11568 (call-interactively
11569 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
11570
11571 (defun org-paste-special (arg)
11572 "Paste rectangular region into table, or past subtree relative to level.
11573 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
11574 See the individual commands for more information."
11575 (interactive "P")
11576 (if (org-at-table-p)
11577 (org-table-paste-rectangle)
11578 (org-paste-subtree arg)))
11579
11580 (defun org-ctrl-c-ctrl-c (&optional arg)
11581 "Call realign table, or recognize a table.el table, or update keywords.
11582 When the cursor is inside a table created by the table.el package,
11583 activate that table. Otherwise, if the cursor is at a normal table
11584 created with org.el, re-align that table. This command works even if
11585 the automatic table editor has been turned off.
11586
11587 If the cursor is in a headline, prompt for tags and insert them into
11588 the current line, aligned to `org-tags-column'. When in a headline and
11589 called with prefix arg, realign all tags in the current buffer.
11590
11591 If the cursor is in one of the special #+KEYWORD lines, this triggers
11592 scanning the buffer for these lines and updating the information.
11593 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
11594 (interactive "P")
11595 (let ((org-enable-table-editor t))
11596 (cond
11597 ((org-on-heading-p) (org-set-tags arg))
11598 ((org-at-table.el-p)
11599 (require 'table)
11600 (beginning-of-line 1)
11601 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
11602 (table-recognize-table))
11603 ((org-at-table-p)
11604 (org-table-maybe-eval-formula)
11605 (if arg
11606 (org-table-recalculate t)
11607 (org-table-maybe-recalculate-line))
11608 (org-table-align))
11609 ((org-at-item-p)
11610 (org-renumber-ordered-list (prefix-numeric-value arg)))
11611 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
11612 (cond
11613 ((equal (match-string 1) "TBLFM")
11614 ;; Recalculate the table before this line
11615 (save-excursion
11616 (beginning-of-line 1)
11617 (skip-chars-backward " \r\n\t")
11618 (if (org-at-table-p) (org-table-recalculate t))))
11619 (t
11620 (org-mode-restart))))
11621 ((org-region-active-p)
11622 (org-table-convert-region (region-beginning) (region-end) arg))
11623 ((condition-case nil
11624 (and (region-beginning) (region-end))
11625 (error nil))
11626 (if (y-or-n-p "Convert inactive region to table? ")
11627 (org-table-convert-region (region-beginning) (region-end) arg)
11628 (error "Abort")))
11629 (t (error "C-c C-c can do nothing useful at this location.")))))
11630
11631 (defun org-mode-restart ()
11632 "Restart Org-mode, to scan again for special lines.
11633 Also updates the keyword regular expressions."
11634 (interactive)
11635 (let ((org-inhibit-startup t)) (org-mode))
11636 (message "Org-mode restarted to refresh keyword and special line setup"))
11637
11638 (defun org-return ()
11639 "Goto next table row or insert a newline.
11640 Calls `org-table-next-row' or `newline', depending on context.
11641 See the individual commands for more information."
11642 (interactive)
11643 (cond
11644 ((org-at-table-p)
11645 (org-table-justify-field-maybe)
11646 (org-table-next-row))
11647 (t (newline))))
11648
11649 (defun org-meta-return (&optional arg)
11650 "Insert a new heading or wrap a region in a table.
11651 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
11652 See the individual commands for more information."
11653 (interactive "P")
11654 (cond
11655 ((org-at-table-p)
11656 (org-table-wrap-region arg))
11657 (t (org-insert-heading arg))))
11658
11659 ;;; Menu entries
11660
11661 ;; Define the Org-mode menus
11662 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
11663 '("Tbl"
11664 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
11665 ["Next Field" org-cycle (org-at-table-p)]
11666 ["Previous Field" org-shifttab (org-at-table-p)]
11667 ["Next Row" org-return (org-at-table-p)]
11668 "--"
11669 ["Blank Field" org-table-blank-field (org-at-table-p)]
11670 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
11671 "--"
11672 ("Column"
11673 ["Move Column Left" org-metaleft (org-at-table-p)]
11674 ["Move Column Right" org-metaright (org-at-table-p)]
11675 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
11676 ["Insert Column" org-shiftmetaright (org-at-table-p)])
11677 ("Row"
11678 ["Move Row Up" org-metaup (org-at-table-p)]
11679 ["Move Row Down" org-metadown (org-at-table-p)]
11680 ["Delete Row" org-shiftmetaup (org-at-table-p)]
11681 ["Insert Row" org-shiftmetadown (org-at-table-p)]
11682 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
11683 "--"
11684 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
11685 ("Rectangle"
11686 ["Copy Rectangle" org-copy-special (org-at-table-p)]
11687 ["Cut Rectangle" org-cut-special (org-at-table-p)]
11688 ["Paste Rectangle" org-paste-special (org-at-table-p)]
11689 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
11690 "--"
11691 ("Calculate"
11692 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
11693 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11694 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
11695 "--"
11696 ["Recalculate line" org-table-recalculate (org-at-table-p)]
11697 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
11698 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
11699 "--"
11700 ["Sum Column/Rectangle" org-table-sum
11701 (or (org-at-table-p) (org-region-active-p))]
11702 ["Which Column?" org-table-current-column (org-at-table-p)])
11703 ["Debug Formulas"
11704 (setq org-table-formula-debug (not org-table-formula-debug))
11705 :style toggle :selected org-table-formula-debug]
11706 "--"
11707 ["Invisible Vlines" org-table-toggle-vline-visibility
11708 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
11709 "--"
11710 ["Create" org-table-create (and (not (org-at-table-p))
11711 org-enable-table-editor)]
11712 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
11713 ["Import from File" org-table-import (not (org-at-table-p))]
11714 ["Export to File" org-table-export (org-at-table-p)]
11715 "--"
11716 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
11717
11718 (easy-menu-define org-org-menu org-mode-map "Org menu"
11719 '("Org"
11720 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
11721 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
11722 ["Sparse Tree" org-occur t]
11723 ["Show All" show-all t]
11724 "--"
11725 ["New Heading" org-insert-heading t]
11726 ("Navigate Headings"
11727 ["Up" outline-up-heading t]
11728 ["Next" outline-next-visible-heading t]
11729 ["Previous" outline-previous-visible-heading t]
11730 ["Next Same Level" outline-forward-same-level t]
11731 ["Previous Same Level" outline-backward-same-level t]
11732 "--"
11733 ["Jump" org-goto t])
11734 ("Edit Structure"
11735 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
11736 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
11737 "--"
11738 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
11739 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
11740 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
11741 "--"
11742 ["Promote Heading" org-metaleft (not (org-at-table-p))]
11743 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
11744 ["Demote Heading" org-metaright (not (org-at-table-p))]
11745 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
11746 "--"
11747 ["Archive Subtree" org-archive-subtree t])
11748 "--"
11749 ("TODO Lists"
11750 ["TODO/DONE/-" org-todo t]
11751 ["Show TODO Tree" org-show-todo-tree t]
11752 ["Global TODO list" org-todo-list t]
11753 "--"
11754 ["Set Priority" org-priority t]
11755 ["Priority Up" org-shiftup t]
11756 ["Priority Down" org-shiftdown t])
11757 ("Dates and Scheduling"
11758 ["Timestamp" org-time-stamp t]
11759 ["Timestamp (inactive)" org-time-stamp-inactive t]
11760 ("Change Date"
11761 ["1 Day Later" org-timestamp-up-day t]
11762 ["1 Day Earlier" org-timestamp-down-day t]
11763 ["1 ... Later" org-shiftup t]
11764 ["1 ... Earlier" org-shiftdown t])
11765 ["Compute Time Range" org-evaluate-time-range t]
11766 ["Schedule Item" org-schedule t]
11767 ["Deadline" org-deadline t]
11768 "--"
11769 ["Goto Calendar" org-goto-calendar t]
11770 ["Date from Calendar" org-date-from-calendar t])
11771 "--"
11772 ["Agenda Command" org-agenda t]
11773 ("File List for Agenda")
11774 ("Special views current file"
11775 ["TODO Tree" org-show-todo-tree t]
11776 ["Check Deadlines" org-check-deadlines t]
11777 ["Timeline" org-timeline t]
11778 ["Tags Tree" org-tags-sparse-tree t])
11779 "--"
11780 ("Hyperlinks"
11781 ["Store Link (Global)" org-store-link t]
11782 ["Insert Link" org-insert-link t]
11783 ["Follow Link" org-open-at-point t])
11784 "--"
11785 ("Export"
11786 ["ASCII" org-export-as-ascii t]
11787 ["Extract Visible Text" org-export-copy-visible t]
11788 ["HTML" org-export-as-html t]
11789 ["HTML and Open" org-export-as-html-and-open t]
11790 ; ["OPML" org-export-as-opml nil]
11791 "--"
11792 ["iCalendar this file" org-export-icalendar-this-file t]
11793 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
11794 :active t :keys "C-c C-x C-i"]
11795 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
11796 "--"
11797 ["Option Template" org-insert-export-options-template t]
11798 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
11799 "--"
11800 ("Documentation"
11801 ["Show Version" org-version t]
11802 ["Info Documentation" org-info t])
11803 ("Customize"
11804 ["Browse Org Group" org-customize t]
11805 "--"
11806 ["Build Full Customize Menu" org-create-customize-menu
11807 (fboundp 'customize-menu-create)])
11808 "--"
11809 ["Refresh setup" org-mode-restart t]
11810 ))
11811
11812 (defun org-info (&optional node)
11813 "Read documentation for Org-mode in the info system.
11814 With optional NODE, go directly to that node."
11815 (interactive)
11816 (require 'info)
11817 (Info-goto-node (format "(org)%s" (or node ""))))
11818
11819 (defun org-install-agenda-files-menu ()
11820 (easy-menu-change
11821 '("Org") "File List for Agenda"
11822 (append
11823 (list
11824 ["Edit File List" (customize-variable 'org-agenda-files) t]
11825 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
11826 ["Remove Current File from List" org-remove-file t]
11827 ["Cycle through agenda files" org-cycle-agenda-files t]
11828 "--")
11829 (mapcar 'org-file-menu-entry org-agenda-files))))
11830
11831 ;;; Documentation
11832
11833 (defun org-customize ()
11834 "Call the customize function with org as argument."
11835 (interactive)
11836 (customize-browse 'org))
11837
11838 (defun org-create-customize-menu ()
11839 "Create a full customization menu for Org-mode, insert it into the menu."
11840 (interactive)
11841 (if (fboundp 'customize-menu-create)
11842 (progn
11843 (easy-menu-change
11844 '("Org") "Customize"
11845 `(["Browse Org group" org-customize t]
11846 "--"
11847 ,(customize-menu-create 'org)
11848 ["Set" Custom-set t]
11849 ["Save" Custom-save t]
11850 ["Reset to Current" Custom-reset-current t]
11851 ["Reset to Saved" Custom-reset-saved t]
11852 ["Reset to Standard Settings" Custom-reset-standard t]))
11853 (message "\"Org\"-menu now contains full customization menu"))
11854 (error "Cannot expand menu (outdated version of cus-edit.el)")))
11855
11856 ;;; Miscellaneous stuff
11857
11858 (defun org-move-line-down (arg)
11859 "Move the current line down. With prefix argument, move it past ARG lines."
11860 (interactive "p")
11861 (let ((col (current-column))
11862 beg end pos)
11863 (beginning-of-line 1) (setq beg (point))
11864 (beginning-of-line 2) (setq end (point))
11865 (beginning-of-line (+ 1 arg))
11866 (setq pos (move-marker (make-marker) (point)))
11867 (insert (delete-and-extract-region beg end))
11868 (goto-char pos)
11869 (move-to-column col)))
11870
11871 (defun org-move-line-up (arg)
11872 "Move the current line up. With prefix argument, move it past ARG lines."
11873 (interactive "p")
11874 (let ((col (current-column))
11875 beg end pos)
11876 (beginning-of-line 1) (setq beg (point))
11877 (beginning-of-line 2) (setq end (point))
11878 (beginning-of-line (- arg))
11879 (setq pos (move-marker (make-marker) (point)))
11880 (insert (delete-and-extract-region beg end))
11881 (goto-char pos)
11882 (move-to-column col)))
11883
11884 ;; Paragraph filling stuff.
11885 ;; We want this to be just right, so use the full arsenal.
11886 ;; FIXME: This very likely does not work correctly for XEmacs, because the
11887 ;; filladapt package works slightly differently.
11888
11889 (defun org-set-autofill-regexps ()
11890 (interactive)
11891 ;; In the paragraph separator we include headlines, because filling
11892 ;; text in a line directly attached to a headline would otherwise
11893 ;; fill the headline as well.
11894 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
11895 ;; The paragraph starter includes hand-formatted lists.
11896 (set (make-local-variable 'paragraph-start)
11897 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
11898 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
11899 ;; But only if the user has not turned off tables or fixed-width regions
11900 (set (make-local-variable 'auto-fill-inhibit-regexp)
11901 (concat "\\*\\|#"
11902 (if (or org-enable-table-editor org-enable-fixed-width-editor)
11903 (concat
11904 "\\|[ \t]*["
11905 (if org-enable-table-editor "|" "")
11906 (if org-enable-fixed-width-editor ":" "")
11907 "]"))))
11908 ;; We use our own fill-paragraph function, to make sure that tables
11909 ;; and fixed-width regions are not wrapped. That function will pass
11910 ;; through to `fill-paragraph' when appropriate.
11911 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
11912 ;; Adaptive filling: To get full control, first make sure that
11913 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
11914 (setq adaptive-fill-regexp "\000")
11915 (setq adaptive-fill-function 'org-adaptive-fill-function))
11916
11917 (defun org-fill-paragraph (&optional justify)
11918 "Re-align a table, pass through to fill-paragraph if no table."
11919 (let ((table-p (org-at-table-p))
11920 (table.el-p (org-at-table.el-p)))
11921 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
11922 (table.el-p t) ; skip table.el tables
11923 (table-p (org-table-align) t) ; align org-mode tables
11924 (t nil)))) ; call paragraph-fill
11925
11926 ;; For reference, this is the default value of adaptive-fill-regexp
11927 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
11928
11929 (defun org-adaptive-fill-function ()
11930 "Return a fill prefix for org-mode files.
11931 In particular, this makes sure hanging paragraphs for hand-formatted lists
11932 work correctly."
11933 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
11934 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11935
11936 ;; Functions needed for Emacs/XEmacs region compatibility
11937
11938 (defun org-region-active-p ()
11939 "Is `transient-mark-mode' on and the region active?
11940 Works on both Emacs and XEmacs."
11941 (if org-ignore-region
11942 nil
11943 (if org-xemacs-p
11944 (and zmacs-regions (region-active-p))
11945 (and transient-mark-mode mark-active))))
11946
11947 (defun org-add-to-invisibility-spec (arg)
11948 "Add elements to `buffer-invisibility-spec'.
11949 See documentation for `buffer-invisibility-spec' for the kind of elements
11950 that can be added."
11951 (cond
11952 ((fboundp 'add-to-invisibility-spec)
11953 (add-to-invisibility-spec arg))
11954 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
11955 (setq buffer-invisibility-spec (list arg)))
11956 (t
11957 (setq buffer-invisibility-spec
11958 (cons arg buffer-invisibility-spec)))))
11959
11960 (defun org-remove-from-invisibility-spec (arg)
11961 "Remove elements from `buffer-invisibility-spec'."
11962 (if (fboundp 'remove-from-invisibility-spec)
11963 (remove-from-invisibility-spec arg)
11964 (if (consp buffer-invisibility-spec)
11965 (setq buffer-invisibility-spec
11966 (delete arg buffer-invisibility-spec)))))
11967
11968 (defun org-in-invisibility-spec-p (arg)
11969 "Is ARG a member of `buffer-invisibility-spec'?"
11970 (if (consp buffer-invisibility-spec)
11971 (member arg buffer-invisibility-spec)
11972 nil))
11973
11974 (defun org-image-file-name-regexp ()
11975 "Return regexp matching the file names of images."
11976 (if (fboundp 'image-file-name-regexp)
11977 (image-file-name-regexp)
11978 (let ((image-file-name-extensions
11979 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
11980 "xbm" "xpm" "pbm" "pgm" "ppm")))
11981 (concat "\\."
11982 (regexp-opt (nconc (mapcar 'upcase
11983 image-file-name-extensions)
11984 image-file-name-extensions)
11985 t)
11986 "\\'"))))
11987
11988 ;; Functions needed for compatibility with old outline.el.
11989
11990 ;; Programming for the old outline.el (that uses selective display
11991 ;; instead of `invisible' text properties) is a nightmare, mostly
11992 ;; because regular expressions can no longer be anchored at
11993 ;; beginning/end of line. Therefore a number of function need special
11994 ;; treatment when the old outline.el is being used.
11995
11996 ;; The following functions capture almost the entire compatibility code
11997 ;; between the different versions of outline-mode. The only other
11998 ;; places where this is important are the font-lock-keywords, and in
11999 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
12000
12001 ;; C-a should go to the beginning of a *visible* line, also in the
12002 ;; new outline.el. I guess this should be patched into Emacs?
12003 (defun org-beginning-of-line ()
12004 "Go to the beginning of the current line. If that is invisible, continue
12005 to a visible line beginning. This makes the function of C-a more intuitive."
12006 (interactive)
12007 (beginning-of-line 1)
12008 (if (bobp)
12009 nil
12010 (backward-char 1)
12011 (if (org-invisible-p)
12012 (while (and (not (bobp)) (org-invisible-p))
12013 (backward-char 1)
12014 (beginning-of-line 1))
12015 (forward-char 1))))
12016
12017 (when org-noutline-p
12018 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
12019 ;; FIXME: should I use substitute-key-definition to reach other bindings
12020 ;; of beginning-of-line?
12021
12022 (defun org-invisible-p ()
12023 "Check if point is at a character currently not visible."
12024 (if org-noutline-p
12025 ;; Early versions of noutline don't have `outline-invisible-p'.
12026 (if (fboundp 'outline-invisible-p)
12027 (outline-invisible-p)
12028 (get-char-property (point) 'invisible))
12029 (save-excursion
12030 (skip-chars-backward "^\r\n")
12031 (equal (char-before) ?\r))))
12032
12033 (defun org-back-to-heading (&optional invisible-ok)
12034 "Move to previous heading line, or beg of this line if it's a heading.
12035 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
12036 (if org-noutline-p
12037 (outline-back-to-heading invisible-ok)
12038 (if (and (memq (char-before) '(?\n ?\r))
12039 (looking-at outline-regexp))
12040 t
12041 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
12042 outline-regexp)
12043 nil t)
12044 (if invisible-ok
12045 (progn (goto-char (match-end 1))
12046 (looking-at outline-regexp)))
12047 (error "Before first heading")))))
12048
12049 (defun org-on-heading-p (&optional invisible-ok)
12050 "Return t if point is on a (visible) heading line.
12051 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12052 (if org-noutline-p
12053 (outline-on-heading-p 'invisible-ok)
12054 (save-excursion
12055 (skip-chars-backward "^\n\r")
12056 (and (looking-at outline-regexp)
12057 (or invisible-ok
12058 (bobp)
12059 (equal (char-before) ?\n))))))
12060
12061 (defun org-up-heading-all (arg)
12062 "Move to the heading line of which the present line is a subheading.
12063 This function considers both visible and invisible heading lines.
12064 With argument, move up ARG levels."
12065 (if org-noutline-p
12066 (if (fboundp 'outline-up-heading-all)
12067 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12068 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12069 (org-back-to-heading t)
12070 (looking-at outline-regexp)
12071 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12072 (error "Cannot move up %d levels" arg)
12073 (re-search-backward
12074 (concat "[\n\r]" (regexp-quote
12075 (make-string (- (match-end 0) (match-beginning 0) arg)
12076 ?*))
12077 "[^*]"))
12078 (forward-char 1))))
12079
12080 (defun org-show-hidden-entry ()
12081 "Show an entry where even the heading is hidden."
12082 (save-excursion
12083 (if (not org-noutline-p)
12084 (progn
12085 (org-back-to-heading t)
12086 (org-flag-heading nil)))
12087 (org-show-entry)))
12088
12089 (defun org-check-occur-regexp (regexp)
12090 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12091 Of course, only for the old outline mode."
12092 (if org-noutline-p
12093 regexp
12094 (if (string-match "^\\^" regexp)
12095 (concat "[\n\r]" (substring regexp 1))
12096 regexp)))
12097
12098 (defun org-flag-heading (flag &optional entry)
12099 "Flag the current heading. FLAG non-nil means make invisible.
12100 When ENTRY is non-nil, show the entire entry."
12101 (save-excursion
12102 (org-back-to-heading t)
12103 (if (not org-noutline-p)
12104 ;; Make the current headline visible
12105 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12106 ;; Check if we should show the entire entry
12107 (if entry
12108 (progn
12109 (org-show-entry)
12110 (save-excursion ;; FIXME: Is this the fix for points in the -|
12111 ;; middle of text? |
12112 (and (outline-next-heading) ;; |
12113 (org-flag-heading nil)))) ; show the next heading _|
12114 (outline-flag-region (max 1 (1- (point)))
12115 (save-excursion (outline-end-of-heading) (point))
12116 (if org-noutline-p
12117 flag
12118 (if flag ?\r ?\n))))))
12119
12120 (defun org-end-of-subtree (&optional invisible-OK)
12121 ;; This is an exact copy of the original function, but it uses
12122 ;; `org-back-to-heading', to make it work also in invisible
12123 ;; trees. And is uses an invisible-OK argument.
12124 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
12125 (org-back-to-heading invisible-OK)
12126 (let ((first t)
12127 (level (funcall outline-level)))
12128 (while (and (not (eobp))
12129 (or first (> (funcall outline-level) level)))
12130 (setq first nil)
12131 (outline-next-heading))
12132 (if (memq (preceding-char) '(?\n ?\^M))
12133 (progn
12134 ;; Go to end of line before heading
12135 (forward-char -1)
12136 (if (memq (preceding-char) '(?\n ?\^M))
12137 ;; leave blank line before heading
12138 (forward-char -1))))))
12139
12140 (defun org-show-subtree ()
12141 "Show everything after this heading at deeper levels."
12142 (outline-flag-region
12143 (point)
12144 (save-excursion
12145 (outline-end-of-subtree) (outline-next-heading) (point))
12146 (if org-noutline-p nil ?\n)))
12147
12148 (defun org-show-entry ()
12149 "Show the body directly following this heading.
12150 Show the heading too, if it is currently invisible."
12151 (interactive)
12152 (save-excursion
12153 (org-back-to-heading t)
12154 (outline-flag-region
12155 (1- (point))
12156 (save-excursion
12157 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12158 (or (match-beginning 1) (point-max)))
12159 (if org-noutline-p nil ?\n))))
12160
12161
12162 (defun org-make-options-regexp (kwds)
12163 "Make a regular expression for keyword lines."
12164 (concat
12165 (if org-noutline-p "^" "[\n\r]")
12166 "#?[ \t]*\\+\\("
12167 (mapconcat 'regexp-quote kwds "\\|")
12168 "\\):[ \t]*"
12169 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12170
12171 ;; Make `bookmark-jump' show the jump location if it was hidden.
12172 (eval-after-load "bookmark"
12173 '(if (boundp 'bookmark-after-jump-hook)
12174 ;; We can use the hook
12175 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12176 ;; Hook not available, use advice
12177 (defadvice bookmark-jump (after org-make-visible activate)
12178 "Make the position visible."
12179 (org-bookmark-jump-unhide))))
12180
12181 (defun org-bookmark-jump-unhide ()
12182 "Unhide the current position, to show the bookmark location."
12183 (and (eq major-mode 'org-mode)
12184 (or (org-invisible-p)
12185 (save-excursion (goto-char (max (point-min) (1- (point))))
12186 (org-invisible-p)))
12187 (org-show-hierarchy-above)))
12188
12189 ;;; Finish up
12190
12191 (provide 'org)
12192
12193 (run-hooks 'org-load-hook)
12194
12195 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12196 ;;; org.el ends here
12197
12198