]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-open-file): Use mailcap for selecting an
[gnu-emacs] / lisp / textmodes / org.el
1 ;;; org.el --- Outline-based notes management and organize
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (c) 2004, 2005, 2006 Free Software Foundation
4 ;;
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 4.03
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.03
85 ;; - Table alignment fixed for use with wide characters.
86 ;; - `C-c -' leaves cursor in current table line.
87 ;; - The current TAG can be incorporated into the agenda prefix.
88 ;; See option `org-agenda-prefix-format' for details.
89 ;;
90 ;; Version 4.02
91 ;; - Minor bug fixes and improvements around tag searches.
92 ;; - XEmacs compatibility fixes.
93 ;;
94 ;; Version 4.01
95 ;; - Tags can also be set remotely from agenda buffer.
96 ;; - Boolean logic for tag searches.
97 ;; - Additional agenda commands can be configured through the variable
98 ;; `org-agenda-custom-commands'.
99 ;; - Minor bug fixes.
100 ;;
101 ;;; Code:
102
103 (eval-when-compile (require 'cl) (require 'calendar))
104 (require 'outline)
105 (require 'time-date)
106 (require 'easymenu)
107
108 (defvar calc-embedded-close-formula)
109 (defvar calc-embedded-open-formula)
110 (defvar font-lock-unfontify-region-function)
111
112 ;;; Customization variables
113
114 (defvar org-version "4.03"
115 "The version number of the file org.el.")
116 (defun org-version ()
117 (interactive)
118 (message "Org-mode version %s" org-version))
119
120 ;; The following two constants are for compatibility with different Emacs
121 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
122 ;; The compatibility code in org.el is based on these two constants.
123 (defconst org-xemacs-p (featurep 'xemacs)
124 "Are we running xemacs?")
125 (defconst org-noutline-p (featurep 'noutline)
126 "Are we using the new outline mode?")
127
128 (defgroup org nil
129 "Outline-based notes management and organizer "
130 :tag "Org"
131 :group 'outlines
132 :group 'hypermedia
133 :group 'calendar)
134
135 (defgroup org-startup nil
136 "Options concerning startup of Org-mode."
137 :tag "Org Startup"
138 :group 'org)
139
140 (defcustom org-CUA-compatible nil
141 "Non-nil means use alternative key bindings for S-<cursor movement>.
142 Org-mode used S-<cursor movement> for changing timestamps and priorities.
143 S-<cursor movement> is also used for example by `CUA-mode' to select text.
144 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
145 alternative bindings. Setting this variable to t will replace the following
146 keys both in Org-mode and in the Org-agenda buffer.
147
148 S-RET -> C-S-RET
149 S-up -> M-p
150 S-down -> M-n
151 S-left -> M--
152 S-right -> M-+
153
154 If you do not like the alternative keys, take a look at the variable
155 `org-disputed-keys'.
156
157 This option is only relevant at load-time of Org-mode. Changing it requires
158 a restart of Emacs to become effective."
159 :group 'org-startup
160 :type 'boolean)
161
162 (defvar org-disputed-keys
163 '((S-up [(shift up)] [(meta ?p)])
164 (S-down [(shift down)] [(meta ?n)])
165 (S-left [(shift left)] [(meta ?-)])
166 (S-right [(shift right)] [(meta ?+)])
167 (S-return [(shift return)] [(control shift return)]))
168 "Keys for which Org-mode and other modes compete.
169 This is an alist, cars are symbols for lookup, 1st element is the default key,
170 second element will be used when `org-CUA-compatible' is t.")
171
172 (defun org-key (key)
173 "Select a key according to `org-CUA-compatible'."
174 (nth (if org-CUA-compatible 2 1)
175 (or (assq key org-disputed-keys)
176 (error "Invalid Key %s in `org-key'" key))))
177
178 (defcustom org-startup-folded t
179 "Non-nil means, entering Org-mode will switch to OVERVIEW.
180 This can also be configured on a per-file basis by adding one of
181 the following lines anywhere in the buffer:
182
183 #+STARTUP: fold
184 #+STARTUP: nofold
185 #+STARTUP: content"
186 :group 'org-startup
187 :type '(choice
188 (const :tag "nofold: show all" nil)
189 (const :tag "fold: overview" t)
190 (const :tag "content: all headlines" content)))
191
192 (defcustom org-startup-truncated t
193 "Non-nil means, entering Org-mode will set `truncate-lines'.
194 This is useful since some lines containing links can be very long and
195 uninteresting. Also tables look terrible when wrapped."
196 :group 'org-startup
197 :type 'boolean)
198
199 (defcustom org-startup-with-deadline-check nil
200 "Non-nil means, entering Org-mode will run the deadline check.
201 This means, if you start editing an org file, you will get an
202 immediate reminder of any due deadlines.
203 This can also be configured on a per-file basis by adding one of
204 the following lines anywhere in the buffer:
205
206 #+STARTUP: dlcheck
207 #+STARTUP: nodlcheck"
208 :group 'org-startup
209 :type 'boolean)
210
211 (defcustom org-insert-mode-line-in-empty-file nil
212 "Non-nil means insert the first line setting Org-mode in empty files.
213 When the function `org-mode' is called interactively in an empty file, this
214 normally means that the file name does not automatically trigger Org-mode.
215 To ensure that the file will always be in Org-mode in the future, a
216 line enforcing Org-mode will be inserted into the buffer, if this option
217 has been set."
218 :group 'org-startup
219 :type 'boolean)
220
221 (defgroup org-keywords nil
222 "Options concerning TODO items in Org-mode."
223 :tag "Org Keywords"
224 :group 'org)
225
226 (defcustom org-todo-keywords '("TODO" "DONE")
227 "List of TODO entry keywords.
228 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
229 considered to mean that the entry is \"done\". All the other mean that
230 action is required, and will make the entry show up in todo lists, diaries
231 etc.
232 The command \\[org-todo] cycles an entry through these states, and an
233 additional state where no keyword is present. For details about this
234 cycling, see also the variable `org-todo-interpretation'
235 Changes become only effective after restarting Emacs."
236 :group 'org-keywords
237 :type '(repeat (string :tag "Keyword")))
238
239 (defcustom org-todo-interpretation 'sequence
240 "Controls how TODO keywords are interpreted.
241 \\<org-mode-map>Possible values are `sequence' and `type'.
242 This variable is only relevant if `org-todo-keywords' contains more than two
243 states. There are two ways how these keywords can be used:
244
245 - As a sequence in the process of working on a TODO item, for example
246 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
247 org-todo-interpretation 'sequence)
248
249 - As different types of TODO items, for example
250 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
251 org-todo-interpretation 'type)
252
253 When the states are interpreted as a sequence, \\[org-todo] always cycles
254 to the next state, in order to walk through all different states. So with
255 \\[org-todo], you turn an empty entry into the state TODO. When you started
256 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
257 later to VERIFY and finally to DONE.
258
259 When the states are interpreted as types, \\[org-todo] still cycles through
260 when it is called several times in direct succession, in order to initially
261 select the type. However, if not called immediately after a previous
262 \\[org-todo], it switches from each type directly to DONE. So with the
263 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
264 RELAXED. If you later return to this entry and press \\[org-todo] again,
265 RELAXED will not be changed REMIND, but directly to DONE.
266
267 You can create a large number of types. To initially select a
268 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
269 type with completion. Of course, you can also type the keyword
270 directly into the buffer. M-TAB completes TODO keywords at the
271 beginning of a headline."
272 :group 'org-keywords
273 :type '(choice (const sequence)
274 (const type)))
275
276 (defcustom org-default-priority ?B
277 "The default priority of TODO items.
278 This is the priority an item get if no explicit priority is given."
279 :group 'org-keywords
280 :type 'character)
281
282 (defcustom org-lowest-priority ?C
283 "The lowest priority of TODO items. A character like ?A, ?B etc."
284 :group 'org-keywords
285 :type 'character)
286
287 (defcustom org-deadline-string "DEADLINE:"
288 "String to mark deadline entries.
289 A deadline is this string, followed by a time stamp. Should be a word,
290 terminated by a colon. You can insert a schedule keyword and
291 a timestamp with \\[org-deadline].
292 Changes become only effective after restarting Emacs."
293 :group 'org-keywords
294 :type 'string)
295
296 (defcustom org-scheduled-string "SCHEDULED:"
297 "String to mark scheduled TODO entries.
298 A schedule is this string, followed by a time stamp. Should be a word,
299 terminated by a colon. You can insert a schedule keyword and
300 a timestamp with \\[org-schedule].
301 Changes become only effective after restarting Emacs."
302 :group 'org-keywords
303 :type 'string)
304
305 (defcustom org-closed-string "CLOSED:"
306 "String ued as the prefix for timestamps logging closing a TODO entry."
307 :group 'org-keywords
308 :type 'string)
309
310 (defcustom org-comment-string "COMMENT"
311 "Entries starting with this keyword will never be exported.
312 An entry can be toggled between COMMENT and normal with
313 \\[org-toggle-comment].
314 Changes become only effective after restarting Emacs."
315 :group 'org-keywords
316 :type 'string)
317
318 (defcustom org-quote-string "QUOTE"
319 "Entries starting with this keyword will be exported in fixed-width font.
320 Quoting applies only to the text in the entry following the headline, and does
321 not extend beyond the next headline, even if that is lower level.
322 An entry can be toggled between QUOTE and normal with
323 \\[org-toggle-fixed-width-section]"
324 :group 'org-keywords
325 :type 'string)
326
327 (defcustom org-after-todo-state-change-hook nil
328 "Hook which is run after the state of a TODO item was changed.
329 The new state (a string with a todo keyword, or nil) is available in the
330 Lisp variable `state'."
331 :group 'org-keywords
332 :type 'hook)
333
334 ;; Variables for pre-computed regular expressions, all buffer local
335 (defvar org-todo-kwd-priority-p nil
336 "Do TODO items have priorities?")
337 (make-variable-buffer-local 'org-todo-kwd-priority-p)
338 (defvar org-todo-kwd-max-priority nil
339 "Maximum priority of TODO items.")
340 (make-variable-buffer-local 'org-todo-kwd-max-priority)
341 (defvar org-ds-keyword-length 12
342 "Maximum length of the Deadline and SCHEDULED keywords.")
343 (make-variable-buffer-local 'org-ds-keyword-length)
344 (defvar org-done-string nil
345 "The last string in `org-todo-keywords', indicating an item is DONE.")
346 (make-variable-buffer-local 'org-done-string)
347 (defvar org-todo-regexp nil
348 "Matches any of the TODO state keywords.")
349 (make-variable-buffer-local 'org-todo-regexp)
350 (defvar org-not-done-regexp nil
351 "Matches any of the TODO state keywords except the last one.")
352 (make-variable-buffer-local 'org-not-done-regexp)
353 (defvar org-todo-line-regexp nil
354 "Matches a headline and puts TODO state into group 2 if present.")
355 (make-variable-buffer-local 'org-todo-line-regexp)
356 (defvar org-nl-done-regexp nil
357 "Matches newline followed by a headline with the DONE keyword.")
358 (make-variable-buffer-local 'org-nl-done-regexp)
359 (defvar org-looking-at-done-regexp nil
360 "Matches the DONE keyword a point.")
361 (make-variable-buffer-local 'org-looking-at-done-regexp)
362 (defvar org-deadline-regexp nil
363 "Matches the DEADLINE keyword.")
364 (make-variable-buffer-local 'org-deadline-regexp)
365 (defvar org-deadline-time-regexp nil
366 "Matches the DEADLINE keyword together with a time stamp.")
367 (make-variable-buffer-local 'org-deadline-time-regexp)
368 (defvar org-deadline-line-regexp nil
369 "Matches the DEADLINE keyword and the rest of the line.")
370 (make-variable-buffer-local 'org-deadline-line-regexp)
371 (defvar org-scheduled-regexp nil
372 "Matches the SCHEDULED keyword.")
373 (make-variable-buffer-local 'org-scheduled-regexp)
374 (defvar org-scheduled-time-regexp nil
375 "Matches the SCHEDULED keyword together with a time stamp.")
376 (make-variable-buffer-local 'org-scheduled-time-regexp)
377
378 (defvar org-category nil
379 "Variable used by org files to set a category for agenda display.
380 Such files should use a file variable to set it, for example
381
382 -*- mode: org; org-category: \"ELisp\"
383
384 or contain a special line
385
386 #+CATEGORY: ELisp
387
388 If the file does not specify a category, then file's base name
389 is used instead.")
390 (make-variable-buffer-local 'org-category)
391
392 (defgroup org-time nil
393 "Options concerning time stamps and deadlines in Org-mode."
394 :tag "Org Time"
395 :group 'org)
396
397 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
398 "Formats for `format-time-string' which are used for time stamps.
399 It is not recommended to change this constant.")
400
401
402 (defcustom org-deadline-warning-days 30
403 "No. of days before expiration during which a deadline becomes active.
404 This variable governs the display in the org file."
405 :group 'org-time
406 :type 'number)
407
408 (defcustom org-popup-calendar-for-date-prompt t
409 "Non-nil means, pop up a calendar when prompting for a date.
410 In the calendar, the date can be selected with mouse-1. However, the
411 minibuffer will also be active, and you can simply enter the date as well.
412 When nil, only the minibuffer will be available."
413 :group 'org-time
414 :type 'number)
415
416 (defcustom org-calendar-follow-timestamp-change t
417 "Non-nil means, make the calendar window follow timestamp changes.
418 When a timestamp is modified and the calendar window is visible, it will be
419 moved to the new date."
420 :group 'org-time
421 :type 'boolean)
422
423 (defcustom org-log-done nil
424 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
425 When the state of an entry is changed from nothing to TODO, remove a previous
426 closing date."
427 :group 'org-time
428 :type 'boolean)
429
430 (defgroup org-agenda nil
431 "Options concerning agenda display Org-mode."
432 :tag "Org Agenda"
433 :group 'org)
434
435 (defcustom org-agenda-files nil
436 "A list of org files for agenda/diary display.
437 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
438 \\[org-remove-file]. You can also use customize to edit the list."
439 :group 'org-agenda
440 :type '(repeat file))
441
442 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
443 "Custom commands for the agenda.
444 These commands will be offered on the splash screen displayed by the
445 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
446
447 key The key (a single char as a string) to be associated with the command.
448 type The command type, any of the following symbols:
449 todo Entries with a specific TODO keyword, in all agenda files.
450 tags Tags match in all agenda files.
451 todo-tree Sparse tree of specific TODO keyword in *current* file.
452 tags-tree Sparse tree with all tags matches in *current* file.
453 occur-tree Occur sparse tree for current file.
454 match What to search for:
455 - a single keyword for TODO keyword searches
456 - a tags match expression for tags searches
457 - a regular expression for occur searches"
458 :group 'org-agenda
459 :type '(repeat
460 (list (string :tag "Key")
461 (choice :tag "Type"
462 (const :tag "Tags search in all agenda files" tags)
463 (const :tag "TODO keyword search in all agenda files" todo)
464 (const :tag "Tags sparse tree in current buffer" tags-tree)
465 (const :tag "TODO keyword tree in current buffer" todo-tree)
466 (const :tag "Occur tree in current buffer" occur-tree))
467 (string :tag "Match"))))
468
469 (defcustom org-select-timeline-window t
470 "Non-nil means, after creating a timeline, move cursor into Timeline window.
471 When nil, cursor will remain in the current window."
472 :group 'org-agenda
473 :type 'boolean)
474
475 (defcustom org-select-agenda-window t
476 "Non-nil means, after creating an agenda, move cursor into Agenda window.
477 When nil, cursor will remain in the current window."
478 :group 'org-agenda
479 :type 'boolean)
480
481 (defcustom org-fit-agenda-window t
482 "Non-nil means, change window size of agenda to fit content."
483 :group 'org-agenda
484 :type 'boolean)
485
486 (defcustom org-agenda-show-all-dates t
487 "Non-nil means, `org-agenda' shows every day in the selected range.
488 When nil, only the days which actually have entries are shown."
489 :group 'org-agenda
490 :type 'boolean)
491
492 ;; FIXME: First day of month works only for current month because it would
493 ;; require a variable ndays treatment.
494 (defcustom org-agenda-start-on-weekday 1
495 "Non-nil means, start the overview always on the specified weekday.
496 0 Denotes Sunday, 1 denotes Monday etc.
497 When nil, always start on the current day."
498 :group 'org-agenda
499 :type '(choice (const :tag "Today" nil)
500 (const :tag "First day of month" t)
501 (number :tag "Weekday No.")))
502
503 (defcustom org-agenda-ndays 7
504 "Number of days to include in overview display."
505 :group 'org-agenda
506 :type 'number)
507
508 (defcustom org-agenda-include-all-todo t
509 "Non-nil means, the agenda will always contain all TODO entries.
510 When nil, date-less entries will only be shown if `org-agenda' is called
511 with a prefix argument.
512 When non-nil, the TODO entries will be listed at the top of the agenda, before
513 the entries for specific days."
514 :group 'org-agenda
515 :type 'boolean)
516
517 (defcustom org-agenda-include-diary nil
518 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
519 :group 'org-agenda
520 :type 'boolean)
521
522 (defcustom org-calendar-to-agenda-key [?c]
523 "The key to be installed in `calendar-mode-map' for switching to the agenda.
524 The command `org-calendar-goto-agenda' will be bound to this key. The
525 default is the character `c' because then`c' can be used to switch back and
526 force between agenda and calendar."
527 :group 'org-agenda
528 :type 'sexp)
529
530 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
531 "Sorting structure for the agenda items of a single day.
532 This is a list of symbols which will be used in sequence to determine
533 if an entry should be listed before another entry. The following
534 symbols are recognized.
535
536 time-up Put entries with time-of-day indications first, early first
537 time-down Put entries with time-of-day indications first, late first
538 category-keep Keep the default order of categories, corresponding to the
539 sequence in `org-agenda-files'.
540 category-up Sort alphabetically by category, A-Z.
541 category-down Sort alphabetically by category, Z-A.
542 priority-up Sort numerically by priority, high priority last.
543 priority-down Sort numerically by priority, high priority first.
544
545 The different possibilities will be tried in sequence, and testing stops
546 if one comparison returns a \"not-equal\". For example, the default
547 '(time-up category-keep priority-down)
548 means: Pull out all entries having a specified time of day and sort them,
549 in order to make a time schedule for the current day the first thing in the
550 agenda listing for the day. Of the entries without a time indication, keep
551 the grouped in categories, don't sort the categories, but keep them in
552 the sequence given in `org-agenda-files'. Within each category sort by
553 priority.
554
555 Leaving out `category-keep' would mean that items will be sorted across
556 categories by priority."
557 :group 'org-agenda
558 :type '(repeat
559 (choice
560 (const time-up)
561 (const time-down)
562 (const category-keep)
563 (const category-up)
564 (const category-down)
565 (const priority-up)
566 (const priority-down))))
567
568 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
569 "Format specification for the prefix of items in the agenda buffer.
570 This format works similar to a printf format, with the following meaning:
571
572 %c the category of the item, \"Diary\" for entries from the diary, or
573 as given by the CATEGORY keyword or derived from the file name.
574 %T the first tag of the item.
575 %t the time-of-day specification if one applies to the entry, in the
576 format HH:MM
577 %s Scheduling/Deadline information, a short string
578
579 All specifiers work basically like the standard `%s' of printf, but may
580 contain two additional characters: A question mark just after the `%' and
581 a whitespace/punctuation character just before the final letter.
582
583 If the first character after `%' is a question mark, the entire field
584 will only be included if the corresponding value applies to the
585 current entry. This is useful for fields which should have fixed
586 width when present, but zero width when absent. For example,
587 \"%?-12t\" will result in a 12 character time field if a time of the
588 day is specified, but will completely disappear in entries which do
589 not contain a time.
590
591 If there is punctuation or whitespace character just before the final
592 format letter, this character will be appended to the field value if
593 the value is not empty. For example, the format \"%-12:c\" leads to
594 \"Diary: \" if the category is \"Diary\". If the category were be
595 empty, no additional colon would be interted.
596
597 The default value of this option is \" %-12:c%?-12t% s\", meaning:
598 - Indent the line with two space characters
599 - Give the category in a 12 chars wide field, padded with whitespace on
600 the right (because of `-'). Append a colon if there is a category
601 (because of `:').
602 - If there is a time-of-day, put it into a 12 chars wide field. If no
603 time, don't put in an empty field, just skip it (because of '?').
604 - Finally, put the scheduling information and append a whitespace.
605
606 As another example, if you don't want the time-of-day of entries in
607 the prefix, you could use:
608
609 (setq org-agenda-prefix-format \" %-11:c% s\")
610
611 See also the variable `org-agenda-remove-times-when-in-prefix'."
612 :type 'string
613 :group 'org-agenda)
614
615 (defcustom org-timeline-prefix-format " % s"
616 "Like `org-agenda-prefix-format', but for the timeline of a single file."
617 :type 'string
618 :group 'org-agenda)
619
620 (defvar org-prefix-format-compiled nil
621 "The compiled version of the most recently used prefix format.
622 Depending on which command was used last, this may be the compiled version
623 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
624
625 (defcustom org-agenda-use-time-grid t
626 "Non-nil means, show a time grid in the agenda schedule.
627 A time grid is a set of lines for specific times (like every two hours between
628 8:00 and 20:00. The items scheduled for a day at specific times are
629 sorted in between these lines.
630 For deails about when the grid will be shown, and what it will look like, see
631 the variable `org-agenda-time-grid'."
632 :group 'org-agenda
633 :type 'boolean)
634
635 (defcustom org-agenda-time-grid
636 '((daily today require-timed)
637 "----------------"
638 (800 1000 1200 1400 1600 1800 2000))
639
640 "The settings for time grid for agenda display.
641 This is a list of three items. The first item is again a list. It contains
642 symbols specifying conditions when the grid should be displayed:
643
644 daily if the agenda shows a single day
645 weekly if the agenda shows an entire week
646 today show grid on current date, independent of daily/weekly display
647 require-timed show grid only if at least on item has a time specification
648
649 The second item is a string which will be places behing the grid time.
650
651 The third item is a list of integers, indicating the times that should have
652 a grid line."
653 :group 'org-agenda
654 :type
655 '(list
656 (set :greedy t :tag "Grid Display Options"
657 (const :tag "Show grid in single day agenda display" daily)
658 (const :tag "Show grid in weekly agenda display" weekly)
659 (const :tag "Always show grid for today" today)
660 (const :tag "Show grid only if any timed entries are present"
661 require-timed)
662 (const :tag "Skip grid times already present in an entry"
663 remove-match))
664 (string :tag "Grid String")
665 (repeat :tag "Grid Times" (integer :tag "Time"))))
666
667 (defcustom org-agenda-remove-times-when-in-prefix t
668 "Non-nil means, remove duplicate time specifications in agenda items.
669 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
670 time-of-day specification in a headline or diary entry is extracted and
671 placed into the prefix. If this option is non-nil, the original specification
672 \(a timestamp or -range, or just a plain time(range) specification like
673 11:30-4pm) will be removed for agenda display. This makes the agenda less
674 cluttered.
675 The option can be t or nil. It may also be the symbol `beg', indicating
676 that the time should only be removed what it is located at the beginning of
677 the headline/diary entry."
678 :group 'org-agenda
679 :type '(choice
680 (const :tag "Always" t)
681 (const :tag "Never" nil)
682 (const :tag "When at beginning of entry" beg)))
683
684 (defcustom org-sort-agenda-notime-is-late t
685 "Non-nil means, items without time are considered late.
686 This is only relevant for sorting. When t, items which have no explicit
687 time like 15:30 will be considered as 24:01, i.e. later than any items which
688 do have a time. When nil, the default time is before 0:00. You can use this
689 option to decide if the schedule for today should come before or after timeless
690 agenda entries."
691 :group 'org-agenda
692 :type 'boolean)
693
694 (defgroup org-structure nil
695 "Options concerning structure editing in Org-mode."
696 :tag "Org Structure"
697 :group 'org)
698
699 (defcustom org-cycle-include-plain-lists nil
700 "Non-nil means, include plain lists into visibility cycling.
701 This means that during cycling, plain list items will *temporarily* be
702 interpreted as outline headlines with a level given by 1000+i where i is the
703 indentation of the bullet. In all other operations, plain list items are
704 not seen as headlines. For example, you cannot assign a TODO keyword to
705 such an item."
706 :group 'org-structure
707 :type 'boolean)
708
709 (defcustom org-cycle-emulate-tab t
710 "Where should `org-cycle' emulate TAB.
711 nil Never
712 white Only in completely white lines
713 t Everywhere except in headlines"
714 :group 'org-structure
715 :type '(choice (const :tag "Never" nil)
716 (const :tag "Only in completely white lines" white)
717 (const :tag "Everywhere except in headlines" t)
718 ))
719
720 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
721 "Hook that is run after `org-cycle' has changed the buffer visibility.
722 The function(s) in this hook must accept a single argument which indicates
723 the new state that was set by the most recent `org-cycle' command. The
724 argument is a symbol. After a global state change, it can have the values
725 `overview', `content', or `all'. After a local state change, it can have
726 the values `folded', `children', or `subtree'."
727 :group 'org-structure
728 :type 'hook)
729
730 (defcustom org-highlight-sparse-tree-matches t
731 "Non-nil means, highlight all matches that define a sparse tree.
732 The highlights will automatically disappear the next time the buffer is
733 changed by an edit command."
734 :group 'org-structure
735 :type 'boolean)
736
737 (defcustom org-show-hierarchy-above t
738 "Non-nil means, show full hierarchy when showing a spot in the tree.
739 Turning this off makes sparse trees more compact, but also less clear."
740 :group 'org-structure
741 :type 'boolean)
742
743 (defcustom org-show-following-heading t
744 "Non-nil means, show heading following match in `org-occur'.
745 When doing an `org-occur' it is useful to show the headline which
746 follows the match, even if they do not match the regexp. This makes it
747 easier to edit directly inside the sparse tree. However, if you use
748 org-occur mainly as an overview, the following headlines are
749 unnecessary clutter."
750 :group 'org-structure
751 :type 'boolean)
752
753 (defcustom org-occur-hook '(org-first-headline-recenter)
754 "Hook that is run after `org-occur' has constructed a sparse tree.
755 This can be used to recenter the window to show as much of the structure
756 as possible."
757 :group 'org-structure
758 :type 'hook)
759
760 (defcustom org-level-color-stars-only nil
761 "Non-nil means fontify only the stars in each headline.
762 When nil, the entire headline is fontified.
763 After changin this, requires restart of Emacs to become effective."
764 :group 'org-structure
765 :type 'boolean)
766
767 (defcustom org-adapt-indentation t
768 "Non-nil means, adapt indentation when promoting and demoting.
769 When this is set and the *entire* text in an entry is indented, the
770 indentation is increased by one space in a demotion command, and
771 decreased by one in a promotion command. If any line in the entry
772 body starts at column 0, indentation is not changed at all."
773 :group 'org-structure
774 :type 'boolean)
775
776 (defcustom org-plain-list-ordered-item-terminator t
777 "The character that makes a line with leading number an ordered list item.
778 Valid values are ?. and ?\). To get both terminators, use t. While
779 ?. may look nicer, it creates the danger that a line with leading
780 number may be incorrectly interpreted as an item. ?\) therefore is
781 the safe choice."
782 :group 'org-structure
783 :type '(choice (const :tag "dot like in \"2.\"" ?.)
784 (const :tag "paren like in \"2)\"" ?\))
785 (const :tab "both" t)))
786
787 (defcustom org-auto-renumber-ordered-lists t
788 "Non-nil means, automatically renumber ordered plain lists.
789 Renumbering happens when the sequence have been changed with
790 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
791 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
792 :group 'org-structure
793 :type 'boolean)
794
795 (defcustom org-enable-fixed-width-editor t
796 "Non-nil means, lines starting with \":\" are treated as fixed-width.
797 This currently only means, they are never auto-wrapped.
798 When nil, such lines will be treated like ordinary lines.
799 See also the QUOTE keyword."
800 :group 'org-structure
801 :type 'boolean)
802
803 (defcustom org-archive-location "%s_archive::"
804 "The location where subtrees should be archived.
805 This string consists of two parts, separated by a double-colon.
806
807 The first part is a file name - when omitted, archiving happens in the same
808 file. %s will be replaced by the current file name (without directory part).
809 Archiving to a different file is useful to keep archived entries from
810 contributing to the Org-mode Agenda.
811
812 The part after the double colon is a headline. The archived entries will be
813 filed under that headline. When omitted, the subtrees are simply filed away
814 at the end of the file, as top-level entries.
815
816 Here are a few examples:
817 \"%s_archive::\"
818 If the current file is Projects.org, archive in file
819 Projects.org_archive, as top-level trees. This is the default.
820
821 \"::* Archived Tasks\"
822 Archive in the current file, under the top-level headline
823 \"* Archived Tasks\".
824
825 \"~/org/archive.org::\"
826 Archive in file ~/org/archive.org (absolute path), as top-level trees.
827
828 \"basement::** Finished Tasks\"
829 Archive in file ./basement (relative path), as level 3 trees
830 below the level 2 heading \"** Finished Tasks\".
831
832 You may set this option on a per-file basis by adding to the buffer a
833 line like
834
835 #+ARCHIVE: basement::** Finished Tasks"
836 :group 'org-structure
837 :type 'string)
838
839 (defcustom org-archive-mark-done t
840 "Non-nil means, mark archived entries as DONE."
841 :group 'org-structure
842 :type 'boolean)
843
844 (defcustom org-archive-stamp-time t
845 "Non-nil means, add a time stamp to archived entries.
846 The time stamp will be added directly after the TODO state keyword in the
847 first line, so it is probably best to use this in combinations with
848 `org-archive-mark-done'."
849 :group 'org-structure
850 :type 'boolean)
851
852 (defgroup org-tags nil
853 "Options concerning startup of Org-mode."
854 :tag "Org Tags"
855 :group 'org)
856
857 (defcustom org-tags-column 48
858 "The column to which tags should be indented in a headline.
859 If this number is positive, it specified the column. If it is negative,
860 it means that the tags should be flushright to that column. For example,
861 -79 works well for a normal 80 character screen."
862 :group 'org-tags
863 :type 'integer)
864
865 (defcustom org-auto-align-tags t
866 "Non-nil means, realign tags after pro/demotion of TODO state change.
867 These operations change the length of a headline and therefore shift
868 the tags around. With this options turned on, after each such operation
869 the tags are again aligned to `org-tags-column'."
870 :group 'org-tags
871 :type 'boolean)
872
873 (defcustom org-use-tag-inheritance t
874 "Non-nil means, tags in levels apply also for sublevels.
875 When nil, only the tags directly give in a specific line apply there.
876 If you turn off this option, you very likely want to turn on the
877 companion option `org-tags-match-list-sublevels'."
878 :group 'org-tags
879 :type 'boolean)
880
881 (defcustom org-tags-match-list-sublevels nil
882 "Non-nil means list also sublevels of headlines matching tag search.
883 Because of tag inheritance (see variable `org-use-tag-inheritance'),
884 the sublevels of a headline matching a tag search often also match
885 the same search. Listing all of them can create very long lists.
886 Setting this variable to nil causes subtrees to be skipped.
887 This option is off by default, because inheritance in on. If you turn
888 inheritance off, you very likely want to turn this option on.
889
890 As a special case, if the tag search is restricted to TODO items, the
891 value of this variable is ignored and sublevels are always checked, to
892 make sure all corresponding TODO items find their way into the list."
893 :group 'org-tags
894 :type 'boolean)
895
896 (defvar org-tags-history nil
897 "History of minibuffer reads for tags.")
898 (defvar org-last-tags-completion-table nil
899 "The last used completion table for tags.")
900
901 (defgroup org-link nil
902 "Options concerning links in Org-mode."
903 :tag "Org Link"
904 :group 'org)
905
906 (defcustom org-tab-follows-link nil
907 "Non-nil means, on links TAB will follow the link.
908 Needs to be set before org.el is loaded."
909 :group 'org-link
910 :type 'boolean)
911
912 (defcustom org-return-follows-link nil
913 "Non-nil means, on links RET will follow the link.
914 Needs to be set before org.el is loaded."
915 :group 'org-link
916 :type 'boolean)
917
918 (defcustom org-link-format "<%s>"
919 "Default format for linkes in the buffer.
920 This is a format string for printf, %s will be replaced by the link text.
921 If you want to make sure that your link is always properly terminated,
922 include angle brackets into this format, like \"<%s>\". Some people also
923 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
924 :group 'org-link
925 :type '(choice
926 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
927 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
928 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
929 (string :tag "Other" :value "<%s>")))
930
931 (defcustom org-allow-space-in-links t
932 "Non-nil means, file names in links may contain space characters.
933 When nil, it becomes possible to put several links into a line.
934 Note that in tables, a link never extends accross fields, so in a table
935 it is always possible to put several links into a line.
936 Changing this varable requires a re-launch of Emacs of become effective."
937 :group 'org-link
938 :type 'boolean)
939
940 (defcustom org-context-in-file-links t
941 "Non-nil means, file links from `org-store-link' contain context.
942 The line number will be added to the file name with :: as separator and
943 used to find the context when the link is activated by the command
944 `org-open-at-point'.
945 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
946 negates this setting for the duration of the command."
947 :group 'org-link
948 :type 'boolean)
949
950 (defcustom org-keep-stored-link-after-insertion nil
951 "Non-nil means, keep link in list for entire session.
952
953 The command `org-store-link' adds a link pointing to the current
954 location to an internal list. These links accumulate during a session.
955 The command `org-insert-link' can be used to insert links into any
956 Org-mode file (offering completion for all stored links). When this
957 option is nil, every link which has been inserted once using \\[org-insert-link]
958 will be removed from the list, to make completing the unused links
959 more efficient."
960 :group 'org-link
961 :type 'boolean)
962
963 (defcustom org-link-frame-setup
964 '((vm . vm-visit-folder-other-frame)
965 (gnus . gnus-other-frame)
966 (file . find-file-other-window))
967 "Setup the frame configuration for following links.
968 When following a link with Emacs, it may often be useful to display
969 this link in another window or frame. This variable can be used to
970 set this up for the different types of links.
971 For VM, use any of
972 `vm-visit-folder'
973 `vm-visit-folder-other-frame'
974 For Gnus, use any of
975 `gnus'
976 `gnus-other-frame'
977 For FILE, use any of
978 `find-file'
979 `find-file-other-window'
980 `find-file-other-frame'
981 For the calendar, use the variable `calendar-setup'.
982 For BBDB, it is currently only possible to display the matches in
983 another window."
984 :group 'org-link
985 :type '(list
986 (cons (const vm)
987 (choice
988 (const vm-visit-folder)
989 (const vm-visit-folder-other-window)
990 (const vm-visit-folder-other-frame)))
991 (cons (const gnus)
992 (choice
993 (const gnus)
994 (const gnus-other-frame)))
995 (cons (const file)
996 (choice
997 (const find-file)
998 (const find-file-other-window)
999 (const find-file-other-frame)))))
1000
1001 (defcustom org-usenet-links-prefer-google nil
1002 "Non-nil means, `org-store-link' will create web links to google groups.
1003 When nil, Gnus will be used for such links.
1004 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1005 negates this setting for the duration of the command."
1006 :group 'org-link
1007 :type 'boolean)
1008
1009 (defcustom org-open-non-existing-files nil
1010 "Non-nil means, `org-open-file' will open non-existing file.
1011 When nil, an error will be generated."
1012 :group 'org-link
1013 :type 'boolean)
1014
1015 (defcustom org-confirm-shell-links t
1016 "Non-nil means, ask for confirmation before executing shell links.
1017 The default is true, to keep new users from shooting into their own foot."
1018 :group 'org-link
1019 :type 'boolean)
1020
1021 (defconst org-file-apps-defaults-gnu
1022 '((t . mailcap))
1023 "Default file applications on a UNIX/LINUX system.
1024 See `org-file-apps'.")
1025
1026 (defconst org-file-apps-defaults-macosx
1027 '((t . "open %s")
1028 ("ps" . "gv %s")
1029 ("ps.gz" . "gv %s")
1030 ("eps" . "gv %s")
1031 ("eps.gz" . "gv %s")
1032 ("dvi" . "xdvi %s")
1033 ("fig" . "xfig %s"))
1034 "Default file applications on a MacOS X system.
1035 The system \"open\" is known as a default, but we use X11 applications
1036 for some files for which the OS does not have a good default.
1037 See `org-file-apps'.")
1038
1039 (defconst org-file-apps-defaults-windowsnt
1040 '((t . (w32-shell-execute "open" file)))
1041 "Default file applications on a Windows NT system.
1042 The system \"open\" is used for most files.
1043 See `org-file-apps'.")
1044
1045 (defcustom org-file-apps
1046 '(
1047 ("txt" . emacs)
1048 ("tex" . emacs)
1049 ("ltx" . emacs)
1050 ("org" . emacs)
1051 ("el" . emacs)
1052 )
1053 "External applications for opening `file:path' items in a document.
1054 Org-mode uses system defaults for different file types, but
1055 you can use this variable to set the application for a given file
1056 extension. The entries in this list are cons cells with a file extension
1057 and the corresponding command. Possible values for the command are:
1058 `emacs' The file will be visited by the current Emacs process.
1059 `default' Use the default application for this file type.
1060 string A command to be executed by a shell; %s will be replaced
1061 by the path to the file.
1062 sexp A Lisp form which will be evaluated. The file path will
1063 be available in the Lisp variable `file'.
1064 For more examples, see the system specific constants
1065 `org-file-apps-defaults-macosx'
1066 `org-file-apps-defaults-windowsnt'
1067 `org-file-apps-defaults-gnu'."
1068 :group 'org-link
1069 :type '(repeat
1070 (cons (string :tag "Extension")
1071 (choice :value ""
1072 (const :tag "Visit with Emacs" 'emacs)
1073 (const :tag "Use system default" 'default)
1074 (string :tag "Command")
1075 (sexp :tag "Lisp form")))))
1076
1077
1078 (defgroup org-remember nil
1079 "Options concerning interaction with remember.el."
1080 :tag "Org Remember"
1081 :group 'org)
1082
1083 (defcustom org-directory "~/org"
1084 "Directory with org files.
1085 This directory will be used as default to prompt for org files.
1086 Used by the hooks for remember.el."
1087 :group 'org-remember
1088 :type 'directory)
1089
1090 (defcustom org-default-notes-file "~/.notes"
1091 "Default target for storing notes.
1092 Used by the hooks for remember.el. This can be a string, or nil to mean
1093 the value of `remember-data-file'."
1094 :group 'org-remember
1095 :type '(choice
1096 (const :tag "Default from remember-data-file" nil)
1097 file))
1098
1099 (defcustom org-reverse-note-order nil
1100 "Non-nil means, store new notes at the beginning of a file or entry.
1101 When nil, new notes will be filed to the end of a file or entry."
1102 :group 'org-remember
1103 :type '(choice
1104 (const :tag "Reverse always" t)
1105 (const :tag "Reverse never" nil)
1106 (repeat :tag "By file name regexp"
1107 (cons regexp boolean))))
1108
1109 (defgroup org-table nil
1110 "Options concerning tables in Org-mode."
1111 :tag "Org Table"
1112 :group 'org)
1113
1114 (defcustom org-enable-table-editor 'optimized
1115 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1116 When nil, such lines will be treated like ordinary lines.
1117
1118 When equal to the symbol `optimized', the table editor will be optimized to
1119 do the following
1120 - Use automatic overwrite mode in front of whitespace in table fields.
1121 This make the structure of the table stay in tact as long as the edited
1122 field does not exceed the column width.
1123 - Minimize the number of realigns. Normally, the table is aligned each time
1124 TAB or RET are pressed to move to another field. With optimization this
1125 happens only if changes to a field might have changed the column width.
1126 Optimization requires replacing the functions `self-insert-command',
1127 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1128 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1129 very good at guessing when a re-align will be necessary, but you can always
1130 force one with \\[org-ctrl-c-ctrl-c].
1131
1132 If you would like to use the optimized version in Org-mode, but the
1133 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1134
1135 This variable can be used to turn on and off the table editor during a session,
1136 but in order to toggle optimization, a restart is required.
1137
1138 See also the variable `org-table-auto-blank-field'."
1139 :group 'org-table
1140 :type '(choice
1141 (const :tag "off" nil)
1142 (const :tag "on" t)
1143 (const :tag "on, optimized" optimized)))
1144
1145 ;; FIXME: We could have a third option which makes it jump only over the first
1146 ;; hline in a table.
1147 (defcustom org-table-tab-jumps-over-hlines t
1148 "Non-nil means, tab in the last column of a table with jump over a hline.
1149 If a horizontal separator line is following the current line,
1150 `org-table-next-field' can either create a new row before that line, or jump
1151 over the line. When this option is nil, a new line will be created before
1152 this line."
1153 :group 'org-table
1154 :type 'boolean)
1155
1156 (defcustom org-table-auto-blank-field t
1157 "Non-nil means, automatically blank table field when starting to type into it.
1158 This only happens when typing immediately after a field motion
1159 command (TAB, S-TAB or RET).
1160 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1161 :group 'org-table
1162 :type 'boolean)
1163
1164 (defcustom org-table-default-size "5x2"
1165 "The default size for newly created tables, Columns x Rows."
1166 :group 'org-table
1167 :type 'string)
1168
1169 (defcustom org-table-automatic-realign t
1170 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1171 When nil, aligning is only done with \\[org-table-align], or after column
1172 removal/insertion."
1173 :group 'org-table
1174 :type 'boolean)
1175
1176 (defcustom org-table-spaces-around-separators '(1 . 1)
1177 "The number of spaces to be placed before and after separators."
1178 :group 'org-table
1179 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1180
1181 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1182 "The number of spaces to be placed before and after separators.
1183 This option applies when the column separators have been made invisible."
1184 :group 'org-table
1185 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1186
1187 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1188 "Regular expression for recognizing numbers in table columns.
1189 If a table column contains mostly numbers, it will be aligned to the
1190 right. If not, it will be aligned to the left.
1191
1192 The default value of this option is a regular expression which allows
1193 anything which looks remotely like a number as used in scientific
1194 context. For example, all of the following will be considered a
1195 number:
1196 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1197
1198 Other options offered by the customize interface are more restrictive."
1199 :group 'org-table
1200 :type '(choice
1201 (const :tag "Positive Integers"
1202 "^[0-9]+$")
1203 (const :tag "Integers"
1204 "^[-+]?[0-9]+$")
1205 (const :tag "Floating Point Numbers"
1206 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1207 (const :tag "Floating Point Number or Integer"
1208 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1209 (const :tag "Exponential, Floating point, Integer"
1210 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1211 (const :tag "Very General Number-Like"
1212 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1213 (string :tag "Regexp:")))
1214
1215 (defcustom org-table-number-fraction 0.5
1216 "Fraction of numbers in a column required to make the column align right.
1217 In a column all non-white fields are considered. If at least this
1218 fraction of fields is matched by `org-table-number-fraction',
1219 alignment to the right border applies."
1220 :group 'org-table
1221 :type 'number)
1222
1223 (defcustom org-export-highlight-first-table-line t
1224 "Non-nil means, highlight the first table line.
1225 In HTML export, this means use <th> instead of <td>.
1226 In tables created with table.el, this applies to the first table line.
1227 In Org-mode tables, all lines before the first horizontal separator
1228 line will be formatted with <th> tags."
1229 :group 'org-table
1230 :type 'boolean)
1231
1232 (defcustom org-table-tab-recognizes-table.el t
1233 "Non-nil means, TAB will automatically notice a table.el table.
1234 When it sees such a table, it moves point into it and - if necessary -
1235 calls `table-recognize-table'."
1236 :group 'org-table
1237 :type 'boolean)
1238
1239 (defgroup org-table-calculation nil
1240 "Options concerning tables in Org-mode."
1241 :tag "Org Table Calculation"
1242 :group 'org)
1243
1244 (defcustom org-table-copy-increment t
1245 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1246 :group 'org-table-calculation
1247 :type 'boolean)
1248
1249 (defcustom org-calc-default-modes
1250 '(calc-internal-prec 12
1251 calc-float-format (float 5)
1252 calc-angle-mode deg
1253 calc-prefer-frac nil
1254 calc-symbolic-mode nil
1255 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1256 calc-display-working-message t
1257 )
1258 "List with Calc mode settings for use in calc-eval for table formulas.
1259 The list must contain alternating symbols (calc modes variables and values.
1260 Don't remove any of the default settings, just change the values. Org-mode
1261 relies on the variables to be present in the list."
1262 :group 'org-table-calculation
1263 :type 'plist)
1264
1265 (defcustom org-table-formula-evaluate-inline t
1266 "Non-nil means, TAB and RET evaluate a formula in current table field.
1267 If the current field starts with an equal sign, it is assumed to be a formula
1268 which should be evaluated as described in the manual and in the documentation
1269 string of the command `org-table-eval-formula'. This feature requires the
1270 Emacs calc package.
1271 When this variable is nil, formula calculation is only available through
1272 the command \\[org-table-eval-formula]."
1273 :group 'org-table-calculation
1274 :type 'boolean)
1275
1276
1277 (defcustom org-table-formula-use-constants t
1278 "Non-nil means, interpret constants in formulas in tables.
1279 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1280 by the value given in `org-table-formula-constants', or by a value obtained
1281 from the `constants.el' package."
1282 :group 'org-table-calculation
1283 :type 'boolean)
1284
1285 (defcustom org-table-formula-constants nil
1286 "Alist with constant names and values, for use in table formulas.
1287 The car of each element is a name of a constant, without the `$' before it.
1288 The cdr is the value as a string. For example, if you'd like to use the
1289 speed of light in a formula, you would configure
1290
1291 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1292
1293 and then use it in an equation like `$1*$c'."
1294 :group 'org-table-calculation
1295 :type '(repeat
1296 (cons (string :tag "name")
1297 (string :tag "value"))))
1298
1299 (defcustom org-table-formula-numbers-only nil
1300 "Non-nil means, calculate only with numbers in table formulas.
1301 Then all input fields will be converted to a number, and the result
1302 must also be a number. When nil, calc's full potential is available
1303 in table calculations, including symbolics etc."
1304 :group 'org-table-calculation
1305 :type 'boolean)
1306
1307 (defcustom org-table-allow-automatic-line-recalculation t
1308 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1309 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1310 :group 'org-table-calculation
1311 :type 'boolean)
1312
1313 (defgroup org-export nil
1314 "Options for exporting org-listings."
1315 :tag "Org Export"
1316 :group 'org)
1317
1318 (defcustom org-export-language-setup
1319 '(("en" "Author" "Date" "Table of Contents")
1320 ("da" "Ophavsmand" "Dato" "Indhold")
1321 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1322 ("es" "Autor" "Fecha" "\xccndice")
1323 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1324 ("it" "Autore" "Data" "Indice")
1325 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1326 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1327 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1328 "Terms used in export text, translated to different languages.
1329 Use the variable `org-export-default-language' to set the language,
1330 or use the +OPTION lines for a per-file setting."
1331 :group 'org-export
1332 :type '(repeat
1333 (list
1334 (string :tag "HTML language tag")
1335 (string :tag "Author")
1336 (string :tag "Date")
1337 (string :tag "Table of Contents"))))
1338
1339 (defcustom org-export-default-language "en"
1340 "The default language of HTML export, as a string.
1341 This should have an association in `org-export-language-setup'."
1342 :group 'org-export
1343 :type 'string)
1344
1345 (defcustom org-export-html-style
1346 "<style type=\"text/css\">
1347 html {
1348 font-family: Times, serif;
1349 font-size: 12pt;
1350 }
1351 .title { text-align: center; }
1352 .todo, .deadline { color: red; }
1353 .done { color: green; }
1354 pre {
1355 border: 1pt solid #AEBDCC;
1356 background-color: #F3F5F7;
1357 padding: 5pt;
1358 font-family: courier, monospace;
1359 }
1360 table { border-collapse: collapse; }
1361 td, th {
1362 vertical-align: top;
1363 border: 1pt solid #ADB9CC;
1364 }
1365 </style>"
1366 "The default style specification for exported HTML files.
1367 Since there are different ways of setting style information, this variable
1368 needs to contain the full HTML structure to provide a style, including the
1369 surrounding HTML tags. The style specifications should include definiitons
1370 for new classes todo, done, title, and deadline. For example, legal values
1371 would be.
1372
1373 <style type=\"text/css\">
1374 p {font-weight: normal; color: gray; }
1375 h1 {color: black; }
1376 .title { text-align: center; }
1377 .todo, .deadline { color: red; }
1378 .done { color: green; }
1379 </style>
1380
1381 or, if you want to keep the style in a file,
1382
1383 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1384
1385 As the value of this option simply gets inserted into the HTML <head> header,
1386 you can \"misuse\" it to add arbitrary text to the header."
1387 :group 'org-export
1388 :type 'string)
1389
1390 (defcustom org-export-headline-levels 3
1391 "The last level which is still exported as a headline.
1392 Inferior levels will produce itemize lists when exported.
1393 Note that a numeric prefix argument to an exporter function overrides
1394 this setting.
1395
1396 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1397 :group 'org-export
1398 :type 'number)
1399
1400 (defcustom org-export-with-section-numbers t
1401 "Non-nil means, add section numbers to headlines when exporting.
1402
1403 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1404 :group 'org-export
1405 :type 'boolean)
1406
1407 (defcustom org-export-with-toc t
1408 "Non-nil means, create a table of contents in exported files.
1409 The TOC contains headlines with levels up to`org-export-headline-levels'.
1410
1411 Headlines which contain any TODO items will be marked with \"(*)\" in
1412 ASCII export, and with red color in HTML output.
1413
1414 In HTML output, the TOC will be clickable.
1415
1416 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1417 :group 'org-export
1418 :type 'boolean)
1419
1420 (defcustom org-export-plain-list-max-depth 20
1421 "Maximum depth of hand-formatted lists in HTML export.
1422
1423 Org-mode parses hand-formatted enumeration and bullet lists and
1424 transforms them to HTML open export. Different indentation of the
1425 bullet or number indicates different list nesting levels. To avoid
1426 confusion, only a single level is allowed by default. When this is
1427 larger than 1, deeper indentation leads to deeper list nesting. For
1428 example, the default value of 3 allows the following list to be
1429 formatted correctly in HTML:
1430
1431 * Fruit
1432 - Apple
1433 - Banana
1434 1. from Africa
1435 2. from South America
1436 - Pineapple
1437 * Bread
1438 * Dairy products"
1439 :group 'org-export
1440 :type 'integer)
1441
1442 (defcustom org-export-preserve-breaks nil
1443 "Non-nil means, preserve all line breaks when exporting.
1444 Normally, in HTML output paragraphs will be reformatted. In ASCII
1445 export, line breaks will always be preserved, regardless of this variable.
1446
1447 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1448 :group 'org-export
1449 :type 'boolean)
1450
1451 (defcustom org-export-html-inline-images t
1452 "Non-nil means, inline images into exported HTML pages.
1453 The link will still be to the original location of the image file.
1454 So if you are moving the page, lets say to your public HTML site,
1455 you will have to move the image and maybe change the link."
1456 :group 'org-export
1457 :type 'boolean)
1458
1459 (defcustom org-export-html-expand t
1460 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1461 When nil, these tags will be exported as plain text and therefore
1462 not be interpreted by a browser.
1463
1464 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1465 :group 'org-export
1466 :type 'boolean)
1467
1468 (defcustom org-export-with-fixed-width t
1469 "Non-nil means, lines starting with \":\" will be in fixed width font.
1470 This can be used to have pre-formatted text, fragments of code etc. For
1471 example
1472 : ;; Some Lisp examples
1473 : (while (defc cnt)
1474 : (ding))
1475 will be looking just like this in also HTML. In ASCII export, this option
1476 has no effect.
1477
1478 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1479 :group 'org-export
1480 :type 'boolean)
1481
1482 (defcustom org-export-with-tables t
1483 "If non-nil, lines starting with \"|\" define a table.
1484 For example:
1485
1486 | Name | Address | Birthday |
1487 |-------------+----------+-----------|
1488 | Arthur Dent | England | 29.2.2100 |
1489
1490 In ASCII export, this option has no effect.
1491
1492 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1493 :group 'org-export
1494 :type 'boolean)
1495
1496 (defcustom org-export-prefer-native-exporter-for-tables nil
1497 "Non-nil means, always export tables created with table.el natively.
1498 Natively means, use the HTML code generator in table.el.
1499 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1500 the table does not use row- or column-spanning). This has the
1501 advantage, that the automatic HTML conversions for math symbols and
1502 sub/superscripts can be applied. Org-mode's HTML generator is also
1503 much faster."
1504 :group 'org-export
1505 :type 'boolean)
1506
1507 (defcustom org-export-html-table-tag
1508 "<table border=1 cellspacing=0 cellpadding=6>"
1509 "The HTML tag used to start a table.
1510 This must be a <table> tag, but you may change the options like
1511 borders and spacing."
1512 :group 'org-export
1513 :type 'string)
1514
1515 (defcustom org-export-with-emphasize t
1516 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1517 If the export target supports emphasizing text, the word will be
1518 typeset in bold, italic, or underlined, respectively. Works only for
1519 single words, but you can say: I *really* *mean* *this*.
1520 In ASCII export, this option has no effect.
1521
1522 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1523 :group 'org-export
1524 :type 'boolean)
1525
1526 (defcustom org-match-sexp-depth 3
1527 "Number of stacked braces for sub/superscript matching.
1528 This has to be set before loading org.el to be effective."
1529 :group 'org-export
1530 :type 'integer)
1531
1532 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1533 (defcustom org-export-with-sub-superscripts t
1534 "Non-nil means, interpret \"_\" and \"^\" for export.
1535 When this option is turned on, you can use TeX-like syntax for sub- and
1536 superscripts. Several characters after \"_\" or \"^\" will be
1537 considered as a single item - so grouping with {} is normally not
1538 needed. For example, the following things will be parsed as single
1539 sub- or superscripts.
1540
1541 10^24 or 10^tau several digits will be considered 1 item
1542 10^-12 or 10^-tau a leading sign with digits or a word
1543 x^2-y^3 will be read as x^2 - y^3, because items are
1544 terminated by almost any nonword/nondigit char.
1545 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1546
1547 Still, ambiguity is possible - so when in doubt use {} to enclose the
1548 sub/superscript.
1549 In ASCII export, this option has no effect.
1550
1551 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1552 :group 'org-export
1553 :type 'boolean)
1554
1555 (defcustom org-export-with-TeX-macros t
1556 "Non-nil means, interpret simple TeX-like macros when exporting.
1557 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1558 No only real TeX macros will work here, but the standard HTML entities
1559 for math can be used as macro names as well. For a list of supported
1560 names in HTML export, see the constant `org-html-entities'.
1561 In ASCII export, this option has no effect.
1562
1563 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1564 :group 'org-export
1565 :type 'boolean)
1566
1567 (defcustom org-export-html-with-timestamp nil
1568 "If non-nil, write `org-export-html-html-helper-timestamp'
1569 into the exported html text. Otherwise, the buffer will just be saved
1570 to a file."
1571 :group 'org-export
1572 :type 'boolean)
1573
1574 (defcustom org-export-html-html-helper-timestamp
1575 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1576 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1577 :group 'org-export
1578 :type 'string)
1579
1580 (defcustom org-export-ascii-show-new-buffer t
1581 "Non-nil means, popup buffer containing the exported ASCII text.
1582 Otherwise the buffer will just be saved to a file and stay hidden."
1583 :group 'org-export
1584 :type 'boolean)
1585
1586 (defcustom org-export-html-show-new-buffer nil
1587 "Non-nil means, popup buffer containing the exported html text.
1588 Otherwise, the buffer will just be saved to a file and stay hidden."
1589 :group 'org-export
1590 :type 'boolean)
1591
1592 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1593 "The file name for the iCalendar file covering all agenda files.
1594 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1595 :group 'org-export
1596 :type 'file)
1597
1598 (defcustom org-icalendar-include-todo nil
1599 "Non-nil means, export to iCalendar files should also cover TODO items."
1600 :group 'org-export
1601 :type 'boolean)
1602
1603 (defcustom org-icalendar-combined-name "OrgMode"
1604 "Calendar name for the combined iCalendar representing all agenda files."
1605 :group 'org-export
1606 :type 'string)
1607
1608 (defgroup org-faces nil
1609 "Faces for highlighting in Org-mode."
1610 :tag "Org Faces"
1611 :group 'org)
1612
1613 (defface org-level-1 ;; font-lock-function-name-face
1614 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1615 (((class color) (background light)) (:foreground "Blue"))
1616 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1617 (t (:inverse-video t :bold t)))
1618 "Face used for level 1 headlines."
1619 :group 'org-faces)
1620
1621 (defface org-level-2 ;; font-lock-variable-name-face
1622 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1623 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1624 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1625 (t (:bold t :italic t)))
1626 "Face used for level 2 headlines."
1627 :group 'org-faces)
1628
1629 (defface org-level-3 ;; font-lock-keyword-face
1630 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1631 (((class color) (background light)) (:foreground "Purple"))
1632 (((class color) (background dark)) (:foreground "Cyan"))
1633 (t (:bold t)))
1634 "Face used for level 3 headlines."
1635 :group 'org-faces)
1636
1637 (defface org-level-4 ;; font-lock-comment-face
1638 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1639 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1640 (((class color) (background light)) (:foreground "Firebrick"))
1641 (((class color) (background dark)) (:foreground "chocolate1"))
1642 (t (:bold t :italic t)))
1643 "Face used for level 4 headlines."
1644 :group 'org-faces)
1645
1646 (defface org-level-5 ;; font-lock-type-face
1647 '((((type tty) (class color)) (:foreground "green"))
1648 (((class color) (background light)) (:foreground "ForestGreen"))
1649 (((class color) (background dark)) (:foreground "PaleGreen"))
1650 (t (:bold t :underline t)))
1651 "Face used for level 5 headlines."
1652 :group 'org-faces)
1653
1654 (defface org-level-6 ;; font-lock-constant-face
1655 '((((type tty) (class color)) (:foreground "magenta"))
1656 (((class color) (background light)) (:foreground "CadetBlue"))
1657 (((class color) (background dark)) (:foreground "Aquamarine"))
1658 (t (:bold t :underline t)))
1659 "Face used for level 6 headlines."
1660 :group 'org-faces)
1661
1662 (defface org-level-7 ;; font-lock-builtin-face
1663 '((((type tty) (class color)) (:foreground "blue" :weight light))
1664 (((class color) (background light)) (:foreground "Orchid"))
1665 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1666 (t (:bold t)))
1667 "Face used for level 7 headlines."
1668 :group 'org-faces)
1669
1670 (defface org-level-8 ;; font-lock-string-face
1671 '((((type tty) (class color)) (:foreground "green"))
1672 (((class color) (background light)) (:foreground "RosyBrown"))
1673 (((class color) (background dark)) (:foreground "LightSalmon"))
1674 (t (:italic t)))
1675 "Face used for level 8 headlines."
1676 :group 'org-faces)
1677
1678 (defface org-special-keyword ;; font-lock-string-face
1679 '((((type tty) (class color)) (:foreground "green"))
1680 (((class color) (background light)) (:foreground "RosyBrown"))
1681 (((class color) (background dark)) (:foreground "LightSalmon"))
1682 (t (:italic t)))
1683 "Face used for level 8 headlines."
1684 :group 'org-faces)
1685
1686 (defface org-warning ;; font-lock-warning-face
1687 '((((type tty) (class color)) (:foreground "red"))
1688 (((class color) (background light)) (:foreground "Red" :bold t))
1689 (((class color) (background dark)) (:foreground "Red1" :bold t))
1690 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1691 (t (:inverse-video t :bold t)))
1692 "Face for deadlines and TODO keywords."
1693 :group 'org-faces)
1694
1695 (defcustom org-fontify-done-headline nil
1696 "Non-nil means, change the face of a headline if it is marked DONE.
1697 Normally, only the TODO/DONE keyword indicates the state of a headline.
1698 When this is non-nil, the headline after the keyword is set to the
1699 `org-headline-done' as an additional indication."
1700 :group 'org-faces
1701 :type 'boolean)
1702
1703 (defface org-headline-done ;; font-lock-string-face
1704 '((((type tty) (class color)) (:foreground "green"))
1705 (((class color) (background light)) (:foreground "RosyBrown"))
1706 (((class color) (background dark)) (:foreground "LightSalmon"))
1707 (t (:italic t)))
1708 "Face used to indicate that a headline is DONE. See also the variable
1709 `org-fontify-done-headline'."
1710 :group 'org-faces)
1711
1712 ;; Inheritance does not yet work for xemacs. So we just copy...
1713
1714 (defface org-deadline-announce
1715 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1716 (((class color) (background light)) (:foreground "Blue"))
1717 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1718 (t (:inverse-video t :bold t)))
1719 "Face for upcoming deadlines."
1720 :group 'org-faces)
1721
1722 (defface org-scheduled-today
1723 '((((type tty) (class color)) (:foreground "green"))
1724 (((class color) (background light)) (:foreground "DarkGreen"))
1725 (((class color) (background dark)) (:foreground "PaleGreen"))
1726 (t (:bold t :underline t)))
1727 "Face for items scheduled for a certain day."
1728 :group 'org-faces)
1729
1730 (defface org-scheduled-previously
1731 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1732 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1733 (((class color) (background light)) (:foreground "Firebrick"))
1734 (((class color) (background dark)) (:foreground "chocolate1"))
1735 (t (:bold t :italic t)))
1736 "Face for items scheduled previously, and not yet done."
1737 :group 'org-faces)
1738
1739 (defface org-formula
1740 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1741 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1742 (((class color) (background light)) (:foreground "Firebrick"))
1743 (((class color) (background dark)) (:foreground "chocolate1"))
1744 (t (:bold t :italic t)))
1745 "Face for items scheduled previously, and not yet done."
1746 :group 'org-faces)
1747
1748 (defface org-link
1749 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1750 (((class color) (background light)) (:foreground "Purple"))
1751 (((class color) (background dark)) (:foreground "Cyan"))
1752 (t (:bold t)))
1753 "Face for links."
1754 :group 'org-faces)
1755
1756 (defface org-done ;; font-lock-type-face
1757 '((((type tty) (class color)) (:foreground "green"))
1758 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1759 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1760 (t (:bold t :underline t)))
1761 "Face used for DONE."
1762 :group 'org-faces)
1763
1764 (defface org-table ;; font-lock-function-name-face
1765 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1766 (((class color) (background light)) (:foreground "Blue"))
1767 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1768 (t (:inverse-video t :bold t)))
1769 "Face used for tables."
1770 :group 'org-faces)
1771
1772 (defface org-time-grid ;; font-lock-variable-name-face
1773 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1774 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1775 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1776 (t (:bold t :italic t)))
1777 "Face used for level 2 headlines."
1778 :group 'org-faces)
1779
1780 (defvar org-level-faces
1781 '(
1782 org-level-1
1783 org-level-2
1784 org-level-3
1785 org-level-4
1786 org-level-5
1787 org-level-6
1788 org-level-7
1789 org-level-8
1790 ))
1791 (defvar org-n-levels (length org-level-faces))
1792
1793 (defun org-set-regexps-and-options ()
1794 "Precompute regular expressions for current buffer."
1795 (when (eq major-mode 'org-mode)
1796 (let ((re (org-make-options-regexp
1797 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1798 "STARTUP" "ARCHIVE")))
1799 (splitre "[ \t]+")
1800 kwds int key value cat arch)
1801 (save-excursion
1802 (save-restriction
1803 (widen)
1804 (goto-char (point-min))
1805 (while (re-search-forward re nil t)
1806 (setq key (match-string 1) value (match-string 2))
1807 (cond
1808 ((equal key "CATEGORY")
1809 (if (string-match "[ \t]+$" value)
1810 (setq value (replace-match "" t t value)))
1811 (setq cat (intern value)))
1812 ((equal key "SEQ_TODO")
1813 (setq int 'sequence
1814 kwds (append kwds (org-split-string value splitre))))
1815 ((equal key "PRI_TODO")
1816 (setq int 'priority
1817 kwds (append kwds (org-split-string value splitre))))
1818 ((equal key "TYP_TODO")
1819 (setq int 'type
1820 kwds (append kwds (org-split-string value splitre))))
1821 ((equal key "STARTUP")
1822 (let ((opts (org-split-string value splitre))
1823 (set '(("fold" org-startup-folded t)
1824 ("nofold" org-startup-folded nil)
1825 ("content" org-startup-folded content)
1826 ("dlcheck" org-startup-with-deadline-check t)
1827 ("nodlcheck" org-startup-with-deadline-check nil)))
1828 l var val)
1829 (while (setq l (assoc (pop opts) set))
1830 (setq var (nth 1 l) val (nth 2 l))
1831 (set (make-local-variable var) val))))
1832 ((equal key "ARCHIVE")
1833 (string-match " *$" value)
1834 (setq arch (replace-match "" t t value))
1835 (remove-text-properties 0 (length arch)
1836 '(face t fontified t) arch)))
1837 )))
1838 (and cat (set (make-local-variable 'org-category) cat))
1839 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1840 (and arch (set (make-local-variable 'org-archive-location) arch))
1841 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1842 ;; Compute the regular expressions and other local variables
1843 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1844 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1845 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1846 (length org-scheduled-string)))
1847 org-done-string
1848 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1849 org-todo-regexp
1850 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1851 "\\|") "\\)\\>")
1852 org-not-done-regexp
1853 (concat "\\<\\("
1854 (mapconcat 'regexp-quote
1855 (nreverse (cdr (reverse org-todo-keywords)))
1856 "\\|")
1857 "\\)\\>")
1858 org-todo-line-regexp
1859 (concat "^\\(\\*+\\)[ \t]*\\("
1860 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1861 "\\)? *\\(.*\\)")
1862 org-nl-done-regexp
1863 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1864 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1865 org-deadline-regexp (concat "\\<" org-deadline-string)
1866 org-deadline-time-regexp
1867 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1868 org-deadline-line-regexp
1869 (concat "\\<\\(" org-deadline-string "\\).*")
1870 org-scheduled-regexp
1871 (concat "\\<" org-scheduled-string)
1872 org-scheduled-time-regexp
1873 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1874 (org-set-font-lock-defaults)))
1875
1876 ;; Tell the compiler about dynamically scoped variables,
1877 ;; and variables from other packages
1878 (eval-when-compile
1879 (defvar zmacs-regions)
1880 (defvar original-date)
1881 (defvar org-transient-mark-mode)
1882 (defvar org-old-auto-fill-inhibit-regexp)
1883 (defvar orgtbl-mode-menu)
1884 (defvar org-html-entities)
1885 (defvar org-goto-start-pos)
1886 (defvar org-cursor-color)
1887 (defvar org-time-was-given)
1888 (defvar org-ts-what)
1889 (defvar mark-active)
1890 (defvar timecnt)
1891 (defvar levels-open)
1892 (defvar title)
1893 (defvar author)
1894 (defvar email)
1895 (defvar text)
1896 (defvar entry)
1897 (defvar date)
1898 (defvar language)
1899 (defvar options)
1900 (defvar ans1)
1901 (defvar ans2)
1902 (defvar starting-day)
1903 (defvar include-all-loc)
1904 (defvar vm-message-pointer)
1905 (defvar vm-folder-directory)
1906 (defvar wl-summary-buffer-elmo-folder)
1907 (defvar wl-summary-buffer-folder-name)
1908 (defvar gnus-group-name)
1909 (defvar gnus-article-current)
1910 (defvar w3m-current-url)
1911 (defvar org-selected-point)
1912 (defvar calendar-mode-map)
1913 (defvar remember-save-after-remembering)
1914 (defvar remember-data-file))
1915
1916
1917 ;;; Define the mode
1918
1919 (defvar org-mode-map (copy-keymap outline-mode-map)
1920 "Keymap for Org-mode.")
1921
1922 (defvar org-struct-menu)
1923 (defvar org-org-menu)
1924 (defvar org-tbl-menu)
1925
1926 ;; We use a before-change function to check if a table might need
1927 ;; an update.
1928 (defvar org-table-may-need-update t
1929 "Indicates of a table might need an update.
1930 This variable is set by `org-before-change-function'. `org-table-align'
1931 sets it back to nil.")
1932 (defvar org-mode-hook nil)
1933 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1934 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
1935
1936
1937 ;;;###autoload
1938 (define-derived-mode org-mode outline-mode "Org"
1939 "Outline-based notes management and organizer, alias
1940 \"Carstens outline-mode for keeping track of everything.\"
1941
1942 Org-mode develops organizational tasks around a NOTES file which
1943 contains information about projects as plain text. Org-mode is
1944 implemented on top of outline-mode, which is ideal to keep the content
1945 of large files well structured. It supports ToDo items, deadlines and
1946 time stamps, which magically appear in the diary listing of the Emacs
1947 calendar. Tables are easily created with a built-in table editor.
1948 Plain text URL-like links connect to websites, emails (VM), Usenet
1949 messages (Gnus), BBDB entries, and any files related to the project.
1950 For printing and sharing of notes, an Org-mode file (or a part of it)
1951 can be exported as a structured ASCII or HTML file.
1952
1953 The following commands are available:
1954
1955 \\{org-mode-map}"
1956 (easy-menu-add org-org-menu)
1957 (easy-menu-add org-tbl-menu)
1958 (org-install-agenda-files-menu)
1959 (setq outline-regexp "\\*+")
1960 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
1961 (setq outline-level 'org-outline-level)
1962 (if org-startup-truncated (setq truncate-lines t))
1963 (org-set-regexps-and-options)
1964 (set (make-local-variable 'font-lock-unfontify-region-function)
1965 'org-unfontify-region)
1966 ;; Activate before-change-function
1967 (set (make-local-variable 'org-table-may-need-update) t)
1968 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1969 (add-hook 'before-change-functions 'org-before-change-function nil
1970 'local)
1971 ;; FIXME: The following does not work because isearch-mode-end-hook
1972 ;; is called *before* the visibility overlays as removed.
1973 ;; There should be another hook then for me to be used.
1974 ;; (make-local-hook 'isearch-mode-end-hook) ;; needed for XEmacs
1975 ;; (add-hook 'isearch-mode-end-hook 'org-show-hierarchy-above nil
1976 ;; 'local)
1977 ;; Paragraphs and auto-filling
1978 (org-set-autofill-regexps)
1979 ;; Settings for Calc embedded mode
1980 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
1981 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
1982 (if (and org-insert-mode-line-in-empty-file
1983 (interactive-p)
1984 (= (point-min) (point-max)))
1985 (insert " -*- mode: org -*-\n\n"))
1986
1987 ;; Get rid of Outline menus, they are not needed
1988 ;; Need to do this here because define-derived-mode sets up
1989 ;; the keymap so late.
1990 (if org-xemacs-p
1991 (progn
1992 (delete-menu-item '("Headings"))
1993 (delete-menu-item '("Show"))
1994 (delete-menu-item '("Hide"))
1995 (set-menubar-dirty-flag))
1996 (define-key org-mode-map [menu-bar headings] 'undefined)
1997 (define-key org-mode-map [menu-bar hide] 'undefined)
1998 (define-key org-mode-map [menu-bar show] 'undefined))
1999
2000 (unless org-inhibit-startup
2001 (if org-startup-with-deadline-check
2002 (call-interactively 'org-check-deadlines)
2003 (cond
2004 ((eq org-startup-folded t)
2005 (org-cycle '(4)))
2006 ((eq org-startup-folded 'content)
2007 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2008 (org-cycle '(4)) (org-cycle '(4))))))))
2009
2010 (defsubst org-current-line (&optional pos)
2011 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2012
2013
2014 ;; FIXME: Do we need to copy?
2015 (defun org-string-props (string &rest properties)
2016 "Add PROPERTIES to string."
2017 (add-text-properties 0 (length string) properties string)
2018 string)
2019
2020 ;;; Font-Lock stuff
2021
2022 (defvar org-mouse-map (make-sparse-keymap))
2023 (define-key org-mouse-map
2024 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2025 (define-key org-mouse-map
2026 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2027 (when org-tab-follows-link
2028 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2029 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2030 (when org-return-follows-link
2031 (define-key org-mouse-map [(return)] 'org-open-at-point)
2032 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2033
2034 (require 'font-lock)
2035
2036 (defconst org-non-link-chars "\t\n\r|<>\000")
2037 (defconst org-link-regexp
2038 (if org-allow-space-in-links
2039 (concat
2040 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2041 (concat
2042 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2043 )
2044 "Regular expression for matching links.")
2045 (defconst org-link-maybe-angles-regexp
2046 (concat "<?\\(" org-link-regexp "\\)>?")
2047 "Matches a link and optionally surrounding angle brackets.")
2048 (defconst org-protected-link-regexp
2049 (concat "\000" org-link-regexp "\000")
2050 "Matches a link and optionally surrounding angle brackets.")
2051
2052 (defconst org-ts-lengths
2053 (cons (length (format-time-string (car org-time-stamp-formats)))
2054 (length (format-time-string (cdr org-time-stamp-formats))))
2055 "This holds the lengths of the two different time formats.")
2056 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2057 "Regular expression for fast time stamp matching.")
2058 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2059 "Regular expression for fast time stamp matching.")
2060 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2061 "Regular expression matching time strings for analysis.")
2062 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2063 "Regular expression matching time stamps, with groups.")
2064 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2065 "Regular expression matching a time stamp range.")
2066 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2067 org-ts-regexp "\\)?")
2068 "Regular expression matching a time stamp or time stamp range.")
2069
2070 (defun org-activate-links (limit)
2071 "Run through the buffer and add overlays to links."
2072 (if (re-search-forward org-link-regexp limit t)
2073 (progn
2074 (add-text-properties (match-beginning 0) (match-end 0)
2075 (list 'mouse-face 'highlight
2076 'keymap org-mouse-map))
2077 t)))
2078
2079 (defun org-activate-dates (limit)
2080 "Run through the buffer and add overlays to dates."
2081 (if (re-search-forward org-tsr-regexp limit t)
2082 (progn
2083 (add-text-properties (match-beginning 0) (match-end 0)
2084 (list 'mouse-face 'highlight
2085 'keymap org-mouse-map))
2086 t)))
2087
2088 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2089 "Matches CamelCase words, possibly with a star before it.")
2090 (defun org-activate-camels (limit)
2091 "Run through the buffer and add overlays to dates."
2092 (if (re-search-forward org-camel-regexp limit t)
2093 (progn
2094 (add-text-properties (match-beginning 0) (match-end 0)
2095 (list 'mouse-face 'highlight
2096 'keymap org-mouse-map))
2097 t)))
2098
2099 (defun org-activate-tags (limit)
2100 (if (re-search-forward "[ \t]\\(:[A-Za-z_:]+:\\)[ \r\n]" limit t)
2101 (progn
2102 (add-text-properties (match-beginning 1) (match-end 1)
2103 (list 'mouse-face 'highlight
2104 'keymap org-mouse-map))
2105 t)))
2106
2107 (defun org-font-lock-level ()
2108 (save-excursion
2109 (org-back-to-heading t)
2110 (- (match-end 0) (match-beginning 0))))
2111
2112 (defun org-outline-level ()
2113 (save-excursion
2114 (looking-at outline-regexp)
2115 (if (match-beginning 1)
2116 (+ (org-get-string-indentation (match-string 1)) 1000)
2117 (- (match-end 0) (match-beginning 0)))))
2118
2119 (defvar org-font-lock-keywords nil)
2120
2121 (defun org-set-font-lock-defaults ()
2122 (let ((org-font-lock-extra-keywords
2123 (list
2124 '(org-activate-links (0 'org-link t))
2125 '(org-activate-dates (0 'org-link t))
2126 '(org-activate-camels (0 'org-link t))
2127 '(org-activate-tags (1 'org-link t))
2128 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2129 '(1 'org-warning t))
2130 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2131 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2132 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2133 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2134 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2135 ;; (3 'bold))
2136 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2137 ;; (3 'italic))
2138 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2139 ;; (3 'underline))
2140 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2141 ; '(1 'org-warning t))
2142 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2143 "\\|" org-quote-string "\\)\\>")
2144 '(1 'org-special-keyword t))
2145 '("^#.*" (0 'font-lock-comment-face t))
2146 (if org-fontify-done-headline
2147 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2148 '(1 'org-done t) '(2 'org-headline-done t))
2149 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2150 '(1 'org-done t)))
2151 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2152 (1 'org-table t))
2153 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2154 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2155 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2156 )))
2157 (set (make-local-variable 'org-font-lock-keywords)
2158 (append
2159 (if org-noutline-p ; FIXME: I am not sure if eval will work
2160 ; on XEmacs if noutline is ever ported
2161 `((eval . (list "^\\(\\*+\\).*"
2162 ,(if org-level-color-stars-only 1 0)
2163 '(nth
2164 (% (- (match-end 1) (match-beginning 1) 1)
2165 org-n-levels)
2166 org-level-faces)
2167 nil t)))
2168 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2169 (,(if org-level-color-stars-only 2 0)
2170 (nth (% (- (match-end 2) (match-beginning 2) 1)
2171 org-n-levels)
2172 org-level-faces)
2173 nil t))))
2174 org-font-lock-extra-keywords))
2175 (set (make-local-variable 'font-lock-defaults)
2176 '(org-font-lock-keywords t nil nil backward-paragraph))
2177 (kill-local-variable 'font-lock-keywords) nil))
2178
2179 (defun org-unfontify-region (beg end &optional maybe_loudly)
2180 "Remove fontification and activation overlays from links."
2181 (font-lock-default-unfontify-region beg end)
2182 (let* ((buffer-undo-list t)
2183 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2184 (inhibit-modification-hooks t)
2185 deactivate-mark buffer-file-name buffer-file-truename)
2186 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2187
2188 ;;; Visibility cycling
2189
2190 (defvar org-cycle-global-status nil)
2191 (defvar org-cycle-subtree-status nil)
2192 (defun org-cycle (&optional arg)
2193 "Visibility cycling for Org-mode.
2194
2195 - When this function is called with a prefix argument, rotate the entire
2196 buffer through 3 states (global cycling)
2197 1. OVERVIEW: Show only top-level headlines.
2198 2. CONTENTS: Show all headlines of all levels, but no body text.
2199 3. SHOW ALL: Show everything.
2200
2201 - When point is at the beginning of a headline, rotate the subtree started
2202 by this line through 3 different states (local cycling)
2203 1. FOLDED: Only the main headline is shown.
2204 2. CHILDREN: The main headline and the direct children are shown. From
2205 this state, you can move to one of the children and
2206 zoom in further.
2207 3. SUBTREE: Show the entire subtree, including body text.
2208
2209 - When there is a numeric prefix, go up to a heading with level ARG, do
2210 a `show-subtree' and return to the previous cursor position. If ARG
2211 is negative, go up that many levels.
2212
2213 - When point is not at the beginning of a headline, execute
2214 `indent-relative', like TAB normally does. See the option
2215 `org-cycle-emulate-tab' for details.
2216
2217 - Special case: if point is the the beginning of the buffer and there is
2218 no headline in line 1, this function will act as if called with prefix arg."
2219 (interactive "P")
2220
2221 (if (or (and (bobp) (not (looking-at outline-regexp)))
2222 (equal arg '(4)))
2223 ;; special case: use global cycling
2224 (setq arg t))
2225
2226 (let ((outline-regexp
2227 (if org-cycle-include-plain-lists
2228 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2229 outline-regexp)))
2230
2231 (cond
2232
2233 ((org-at-table-p 'any)
2234 ;; Enter the table or move to the next field in the table
2235 (or (org-table-recognize-table.el)
2236 (progn
2237 (org-table-justify-field-maybe)
2238 (org-table-next-field))))
2239
2240 ((eq arg t) ;; Global cycling
2241
2242 (cond
2243 ((and (eq last-command this-command)
2244 (eq org-cycle-global-status 'overview))
2245 ;; We just created the overview - now do table of contents
2246 ;; This can be slow in very large buffers, so indicate action
2247 (message "CONTENTS...")
2248 (save-excursion
2249 ;; Visit all headings and show their offspring
2250 (goto-char (point-max))
2251 (catch 'exit
2252 (while (and (progn (condition-case nil
2253 (outline-previous-visible-heading 1)
2254 (error (goto-char (point-min))))
2255 t)
2256 (looking-at outline-regexp))
2257 (show-branches)
2258 (if (bobp) (throw 'exit nil))))
2259 (message "CONTENTS...done"))
2260 (setq org-cycle-global-status 'contents)
2261 (run-hook-with-args 'org-cycle-hook 'contents))
2262
2263 ((and (eq last-command this-command)
2264 (eq org-cycle-global-status 'contents))
2265 ;; We just showed the table of contents - now show everything
2266 (show-all)
2267 (message "SHOW ALL")
2268 (setq org-cycle-global-status 'all)
2269 (run-hook-with-args 'org-cycle-hook 'all))
2270
2271 (t
2272 ;; Default action: go to overview
2273 (hide-sublevels 1)
2274 (message "OVERVIEW")
2275 (setq org-cycle-global-status 'overview)
2276 (run-hook-with-args 'org-cycle-hook 'overview))))
2277
2278 ((integerp arg)
2279 ;; Show-subtree, ARG levels up from here.
2280 (save-excursion
2281 (org-back-to-heading)
2282 (outline-up-heading (if (< arg 0) (- arg)
2283 (- (outline-level) arg)))
2284 (org-show-subtree)))
2285
2286 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2287 ;; At a heading: rotate between three different views
2288 (org-back-to-heading)
2289 (let ((goal-column 0) eoh eol eos)
2290 ;; First, some boundaries
2291 (save-excursion
2292 (org-back-to-heading)
2293 (save-excursion
2294 (beginning-of-line 2)
2295 (while (and (not (eobp)) ;; this is like `next-line'
2296 (get-char-property (1- (point)) 'invisible))
2297 (beginning-of-line 2)) (setq eol (point)))
2298 (outline-end-of-heading) (setq eoh (point))
2299 (org-end-of-subtree t) (setq eos (point))
2300 (outline-next-heading))
2301 ;; Find out what to do next and set `this-command'
2302 (cond
2303 ((= eos eoh)
2304 ;; Nothing is hidden behind this heading
2305 (message "EMPTY ENTRY")
2306 (setq org-cycle-subtree-status nil))
2307 ((>= eol eos)
2308 ;; Entire subtree is hidden in one line: open it
2309 (org-show-entry)
2310 (show-children)
2311 (message "CHILDREN")
2312 (setq org-cycle-subtree-status 'children)
2313 (run-hook-with-args 'org-cycle-hook 'children))
2314 ((and (eq last-command this-command)
2315 (eq org-cycle-subtree-status 'children))
2316 ;; We just showed the children, now show everything.
2317 (org-show-subtree)
2318 (message "SUBTREE")
2319 (setq org-cycle-subtree-status 'subtree)
2320 (run-hook-with-args 'org-cycle-hook 'subtree))
2321 (t
2322 ;; Default action: hide the subtree.
2323 (hide-subtree)
2324 (message "FOLDED")
2325 (setq org-cycle-subtree-status 'folded)
2326 (run-hook-with-args 'org-cycle-hook 'folded)))))
2327
2328 ;; TAB emulation
2329 (buffer-read-only (org-back-to-heading))
2330 ((if (and (eq org-cycle-emulate-tab 'white)
2331 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2332 t
2333 (eq org-cycle-emulate-tab t))
2334 (if (and (looking-at "[ \n\r\t]")
2335 (string-match "^[ \t]*$" (buffer-substring
2336 (point-at-bol) (point))))
2337 (progn
2338 (beginning-of-line 1)
2339 (and (looking-at "[ \t]+") (replace-match ""))))
2340 (indent-relative))
2341
2342 (t (save-excursion
2343 (org-back-to-heading)
2344 (org-cycle))))))
2345
2346 (defun org-optimize-window-after-visibility-change (state)
2347 "Adjust the window after a change in outline visibility.
2348 This function is the default value of the hook `org-cycle-hook'."
2349 (cond
2350 ((eq state 'overview) (org-first-headline-recenter 1))
2351 ((eq state 'content) nil)
2352 ((eq state 'all) nil)
2353 ((eq state 'folded) nil)
2354 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2355 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2356
2357 (defun org-subtree-end-visible-p ()
2358 "Is the end of the current subtree visible?"
2359 (pos-visible-in-window-p
2360 (save-excursion (org-end-of-subtree t) (point))))
2361
2362 (defun org-first-headline-recenter (&optional N)
2363 "Move cursor to the first headline and recenter the headline.
2364 Optional argument N means, put the headline into the Nth line of the window."
2365 (goto-char (point-min))
2366 (when (re-search-forward (concat "^" outline-regexp) nil t)
2367 (beginning-of-line)
2368 (recenter (prefix-numeric-value N))))
2369
2370 (defvar org-goto-window-configuration nil)
2371 (defvar org-goto-marker nil)
2372 (defvar org-goto-map (make-sparse-keymap))
2373 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2374 (while (setq cmd (pop cmds))
2375 (substitute-key-definition cmd cmd org-goto-map global-map)))
2376 (define-key org-goto-map "\C-m" 'org-goto-ret)
2377 (define-key org-goto-map [(left)] 'org-goto-left)
2378 (define-key org-goto-map [(right)] 'org-goto-right)
2379 (define-key org-goto-map [(?q)] 'org-goto-quit)
2380 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2381 (define-key org-goto-map "\C-i" 'org-cycle)
2382 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2383 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2384 (define-key org-goto-map "n" 'outline-next-visible-heading)
2385 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2386 (define-key org-goto-map "f" 'outline-forward-same-level)
2387 (define-key org-goto-map "b" 'outline-backward-same-level)
2388 (define-key org-goto-map "u" 'outline-up-heading)
2389 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2390 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2391 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2392 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2393 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2394 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2395 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2396
2397 (defconst org-goto-help
2398 "Select a location to jump to, press RET
2399 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2400
2401 (defun org-goto ()
2402 "Go to a different location of the document, keeping current visibility.
2403
2404 When you want to go to a different location in a document, the fastest way
2405 is often to fold the entire buffer and then dive into the tree. This
2406 method has the disadvantage, that the previous location will be folded,
2407 which may not be what you want.
2408
2409 This command works around this by showing a copy of the current buffer in
2410 overview mode. You can dive into the tree in that copy, to find the
2411 location you want to reach. When pressing RET, the command returns to the
2412 original buffer in which the visibility is still unchanged. It then jumps
2413 to the new location, making it and the headline hierarchy above it visible."
2414 (interactive)
2415 (let* ((org-goto-start-pos (point))
2416 (selected-point
2417 (org-get-location (current-buffer) org-goto-help)))
2418 (if selected-point
2419 (progn
2420 (goto-char selected-point)
2421 (if (org-invisible-p) (org-show-hierarchy-above)))
2422 (error "Quit"))))
2423
2424 (defun org-get-location (buf help)
2425 "Let the user select a location in the Org-mode buffer BUF.
2426 This function uses a recursive edit. It returns the selected position
2427 or nil."
2428 (let (org-selected-point)
2429 (save-excursion
2430 (save-window-excursion
2431 (delete-other-windows)
2432 (switch-to-buffer (get-buffer-create "*org-goto*"))
2433 (with-output-to-temp-buffer "*Help*"
2434 (princ help))
2435 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2436 (setq buffer-read-only nil)
2437 (erase-buffer)
2438 (insert-buffer-substring buf)
2439 (let ((org-startup-truncated t)
2440 (org-startup-folded t)
2441 (org-startup-with-deadline-check nil))
2442 (org-mode))
2443 (setq buffer-read-only t)
2444 (if (boundp 'org-goto-start-pos)
2445 (goto-char org-goto-start-pos)
2446 (goto-char (point-min)))
2447 (org-beginning-of-line)
2448 (message "Select location and press RET")
2449 ;; now we make sure that during selection, ony very few keys work
2450 ;; and that it is impossible to switch to another window.
2451 (let ((gm (current-global-map))
2452 (overriding-local-map org-goto-map))
2453 (unwind-protect
2454 (progn
2455 (use-global-map org-goto-map)
2456 (recursive-edit))
2457 (use-global-map gm)))))
2458 (kill-buffer "*org-goto*")
2459 org-selected-point))
2460
2461 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2462 (defun org-goto-ret (&optional arg)
2463 "Finish org-goto by going to the new location."
2464 (interactive "P")
2465 (setq org-selected-point (point)
2466 current-prefix-arg arg)
2467 (throw 'exit nil))
2468
2469 (defun org-goto-left ()
2470 "Finish org-goto by going to the new location."
2471 (interactive)
2472 (if (org-on-heading-p)
2473 (progn
2474 (beginning-of-line 1)
2475 (setq org-selected-point (point)
2476 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2477 (throw 'exit nil))
2478 (error "Not on a heading")))
2479
2480 (defun org-goto-right ()
2481 "Finish org-goto by going to the new location."
2482 (interactive)
2483 (if (org-on-heading-p)
2484 (progn
2485 (outline-end-of-subtree)
2486 (or (eobp) (forward-char 1))
2487 (setq org-selected-point (point)
2488 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2489 (throw 'exit nil))
2490 (error "Not on a heading")))
2491
2492 (defun org-goto-quit ()
2493 "Finish org-goto without cursor motion."
2494 (interactive)
2495 (setq org-selected-point nil)
2496 (throw 'exit nil))
2497
2498 ;;; Promotion, Demotion, Inserting new headlines
2499
2500 (defvar org-ignore-region nil
2501 "To temporarily disable the active region.")
2502
2503 (defun org-insert-heading (&optional force-heading)
2504 "Insert a new heading or item with same depth at point.
2505 If ARG is non-nil"
2506 (interactive "P")
2507 (when (or force-heading (not (org-insert-item)))
2508 (let* ((head (save-excursion
2509 (condition-case nil
2510 (org-back-to-heading)
2511 (error (outline-next-heading)))
2512 (prog1 (match-string 0)
2513 (funcall outline-level)))))
2514 (unless (bolp) (newline))
2515 (insert head)
2516 (unless (eolp)
2517 (save-excursion (newline-and-indent)))
2518 (unless (equal (char-before) ?\ )
2519 (insert " "))
2520 (run-hooks 'org-insert-heading-hook))))
2521
2522 (defun org-insert-item ()
2523 "Insert a new item at the current level.
2524 Return t when tings worked, nil when we are not in an item."
2525 (when (save-excursion
2526 (condition-case nil
2527 (progn
2528 (org-beginning-of-item)
2529 (org-at-item-p)
2530 t)
2531 (error nil)))
2532 (unless (bolp) (newline))
2533 (insert (match-string 0))
2534 (org-maybe-renumber-ordered-list)
2535 t))
2536
2537 (defun org-insert-todo-heading (arg)
2538 "Insert a new heading with the same level and TODO state as current heading.
2539 If the heading has no TODO state, or if the state is DONE, use the first
2540 state (TODO by default). Also with prefix arg, force first state."
2541 (interactive "P")
2542 (org-insert-heading)
2543 (save-excursion
2544 (org-back-to-heading)
2545 (outline-previous-heading)
2546 (looking-at org-todo-line-regexp))
2547 (if (or arg
2548 (not (match-beginning 2))
2549 (equal (match-string 2) org-done-string))
2550 (insert (car org-todo-keywords) " ")
2551 (insert (match-string 2) " ")))
2552
2553 (defun org-promote-subtree ()
2554 "Promote the entire subtree.
2555 See also `org-promote'."
2556 (interactive)
2557 (save-excursion
2558 (org-map-tree 'org-promote)))
2559
2560 (defun org-demote-subtree ()
2561 "Demote the entire subtree. See `org-demote'.
2562 See also `org-promote'."
2563 (interactive)
2564 (save-excursion
2565 (org-map-tree 'org-demote)))
2566
2567 (defun org-do-promote ()
2568 "Promote the current heading higher up the tree.
2569 If the region is active in `transient-mark-mode', promote all headings
2570 in the region."
2571 (interactive)
2572 (save-excursion
2573 (if (org-region-active-p)
2574 (org-map-region 'org-promote (region-beginning) (region-end))
2575 (org-promote)))
2576 (org-fix-position-after-promote))
2577
2578 (defun org-do-demote ()
2579 "Demote the current heading lower down the tree.
2580 If the region is active in `transient-mark-mode', demote all headings
2581 in the region."
2582 (interactive)
2583 (save-excursion
2584 (if (org-region-active-p)
2585 (org-map-region 'org-demote (region-beginning) (region-end))
2586 (org-demote)))
2587 (org-fix-position-after-promote))
2588
2589 (defun org-fix-position-after-promote ()
2590 "Make sure that after pro/demotion cursor position is right."
2591 (and (equal (char-after) ?\ )
2592 (equal (char-before) ?*)
2593 (forward-char 1)))
2594
2595 (defun org-promote ()
2596 "Promote the current heading higher up the tree.
2597 If the region is active in `transient-mark-mode', promote all headings
2598 in the region."
2599 (org-back-to-heading t)
2600 (let* ((level (save-match-data (funcall outline-level)))
2601 (up-head (make-string (1- level) ?*)))
2602 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2603 (replace-match up-head nil t)
2604 ;; Fixup tag positioning
2605 (and org-auto-align-tags (org-set-tags nil t))
2606 (if org-adapt-indentation
2607 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2608
2609 (defun org-demote ()
2610 "Demote the current heading lower down the tree.
2611 If the region is active in `transient-mark-mode', demote all headings
2612 in the region."
2613 (org-back-to-heading t)
2614 (let* ((level (save-match-data (funcall outline-level)))
2615 (down-head (make-string (1+ level) ?*)))
2616 (replace-match down-head nil t)
2617 ;; Fixup tag positioning
2618 (and org-auto-align-tags (org-set-tags nil t))
2619 (if org-adapt-indentation
2620 (org-fixup-indentation "^ " " " "^\\S-"))))
2621
2622 (defun org-map-tree (fun)
2623 "Call FUN for every heading underneath the current one."
2624 (org-back-to-heading)
2625 (let ((level (outline-level)))
2626 (save-excursion
2627 (funcall fun)
2628 (while (and (progn
2629 (outline-next-heading)
2630 (> (funcall outline-level) level))
2631 (not (eobp)))
2632 (funcall fun)))))
2633
2634 (defun org-map-region (fun beg end)
2635 "Call FUN for every heading between BEG and END."
2636 (let ((org-ignore-region t))
2637 (save-excursion
2638 (setq end (copy-marker end))
2639 (goto-char beg)
2640 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2641 (< (point) end))
2642 (funcall fun))
2643 (while (and (progn
2644 (outline-next-heading)
2645 (< (point) end))
2646 (not (eobp)))
2647 (funcall fun)))))
2648
2649 (defun org-fixup-indentation (from to prohibit)
2650 "Change the indentation in the current entry by re-replacing FROM with TO.
2651 However, if the regexp PROHIBIT matches at all, don't do anything.
2652 This is being used to change indentation along with the length of the
2653 heading marker. But if there are any lines which are not indented, nothing
2654 is changed at all."
2655 (save-excursion
2656 (let ((end (save-excursion (outline-next-heading)
2657 (point-marker))))
2658 (unless (save-excursion (re-search-forward prohibit end t))
2659 (while (re-search-forward from end t)
2660 (replace-match to)
2661 (beginning-of-line 2)))
2662 (move-marker end nil))))
2663
2664 ;;; Vertical tree motion, cutting and pasting of subtrees
2665
2666 (defun org-move-subtree-up (&optional arg)
2667 "Move the current subtree up past ARG headlines of the same level."
2668 (interactive "p")
2669 (org-move-subtree-down (- (prefix-numeric-value arg))))
2670
2671 (defun org-move-subtree-down (&optional arg)
2672 "Move the current subtree down past ARG headlines of the same level."
2673 (interactive "p")
2674 (setq arg (prefix-numeric-value arg))
2675 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2676 'outline-get-last-sibling))
2677 (ins-point (make-marker))
2678 (cnt (abs arg))
2679 beg end txt folded)
2680 ;; Select the tree
2681 (org-back-to-heading)
2682 (setq beg (point))
2683 (save-match-data
2684 (save-excursion (outline-end-of-heading)
2685 (setq folded (org-invisible-p)))
2686 (outline-end-of-subtree))
2687 (outline-next-heading)
2688 (setq end (point))
2689 ;; Find insertion point, with error handling
2690 (goto-char beg)
2691 (while (> cnt 0)
2692 (or (and (funcall movfunc) (looking-at outline-regexp))
2693 (progn (goto-char beg)
2694 (error "Cannot move past superior level or buffer limit")))
2695 (setq cnt (1- cnt)))
2696 (if (> arg 0)
2697 ;; Moving forward - still need to move over subtree
2698 (progn (outline-end-of-subtree)
2699 (outline-next-heading)
2700 (if (not (or (looking-at (concat "^" outline-regexp))
2701 (bolp)))
2702 (newline))))
2703 (move-marker ins-point (point))
2704 (setq txt (buffer-substring beg end))
2705 (delete-region beg end)
2706 (insert txt)
2707 (goto-char ins-point)
2708 (if folded (hide-subtree))
2709 (move-marker ins-point nil)))
2710
2711 (defvar org-subtree-clip ""
2712 "Clipboard for cut and paste of subtrees.
2713 This is actually only a copy of the kill, because we use the normal kill
2714 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2715
2716 (defvar org-subtree-clip-folded nil
2717 "Was the last copied subtree folded?
2718 This is used to fold the tree back after pasting.")
2719
2720 (defun org-cut-subtree ()
2721 "Cut the current subtree into the clipboard.
2722 This is a short-hand for marking the subtree and then cutting it."
2723 (interactive)
2724 (org-copy-subtree 'cut))
2725
2726 (defun org-copy-subtree (&optional cut)
2727 "Cut the current subtree into the clipboard.
2728 This is a short-hand for marking the subtree and then copying it.
2729 If CUT is non nil, actually cut the subtree."
2730 (interactive)
2731 (let (beg end folded)
2732 (org-back-to-heading)
2733 (setq beg (point))
2734 (save-match-data
2735 (save-excursion (outline-end-of-heading)
2736 (setq folded (org-invisible-p)))
2737 (outline-end-of-subtree))
2738 (if (equal (char-after) ?\n) (forward-char 1))
2739 (setq end (point))
2740 (goto-char beg)
2741 (when (> end beg)
2742 (setq org-subtree-clip-folded folded)
2743 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2744 (setq org-subtree-clip (current-kill 0))
2745 (message "%s: Subtree with %d characters"
2746 (if cut "Cut" "Copied")
2747 (length org-subtree-clip)))))
2748
2749 (defun org-paste-subtree (&optional level tree)
2750 "Paste the clipboard as a subtree, with modification of headline level.
2751 The entire subtree is promoted or demoted in order to match a new headline
2752 level. By default, the new level is derived from the visible headings
2753 before and after the insertion point, and taken to be the inferior headline
2754 level of the two. So if the previous visible heading is level 3 and the
2755 next is level 4 (or vice versa), level 4 will be used for insertion.
2756 This makes sure that the subtree remains an independent subtree and does
2757 not swallow low level entries.
2758
2759 You can also force a different level, either by using a numeric prefix
2760 argument, or by inserting the heading marker by hand. For example, if the
2761 cursor is after \"*****\", then the tree will be shifted to level 5.
2762
2763 If you want to insert the tree as is, just use \\[yank].
2764
2765 If optional TREE is given, use this text instead of the kill ring."
2766 (interactive "P")
2767 (unless (org-kill-is-subtree-p tree)
2768 (error
2769 (substitute-command-keys
2770 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2771 (let* ((txt (or tree (current-kill 0)))
2772 (^re (concat "^\\(" outline-regexp "\\)"))
2773 (re (concat "\\(" outline-regexp "\\)"))
2774 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2775
2776 (old-level (if (string-match ^re txt)
2777 (- (match-end 0) (match-beginning 0))
2778 -1))
2779 (force-level (cond (level (prefix-numeric-value level))
2780 ((string-match
2781 ^re_ (buffer-substring (point-at-bol) (point)))
2782 (- (match-end 0) (match-beginning 0)))
2783 (t nil)))
2784 (previous-level (save-excursion
2785 (condition-case nil
2786 (progn
2787 (outline-previous-visible-heading 1)
2788 (if (looking-at re)
2789 (- (match-end 0) (match-beginning 0))
2790 1))
2791 (error 1))))
2792 (next-level (save-excursion
2793 (condition-case nil
2794 (progn
2795 (outline-next-visible-heading 1)
2796 (if (looking-at re)
2797 (- (match-end 0) (match-beginning 0))
2798 1))
2799 (error 1))))
2800 (new-level (or force-level (max previous-level next-level)))
2801 (shift (if (or (= old-level -1)
2802 (= new-level -1)
2803 (= old-level new-level))
2804 0
2805 (- new-level old-level)))
2806 (shift1 shift)
2807 (delta (if (> shift 0) -1 1))
2808 (func (if (> shift 0) 'org-demote 'org-promote))
2809 beg end)
2810 ;; Remove the forces level indicator
2811 (if force-level
2812 (delete-region (point-at-bol) (point)))
2813 ;; Make sure we start at the beginning of an empty line
2814 (if (not (bolp)) (insert "\n"))
2815 (if (not (looking-at "[ \t]*$"))
2816 (progn (insert "\n") (backward-char 1)))
2817 ;; Paste
2818 (setq beg (point))
2819 (insert txt)
2820 (setq end (point))
2821 (goto-char beg)
2822 ;; Shift if necessary
2823 (if (= shift 0)
2824 (message "Pasted at level %d, without shift" new-level)
2825 (save-restriction
2826 (narrow-to-region beg end)
2827 (while (not (= shift 0))
2828 (org-map-region func (point-min) (point-max))
2829 (setq shift (+ delta shift)))
2830 (goto-char (point-min))
2831 (message "Pasted at level %d, with shift by %d levels"
2832 new-level shift1)))
2833 (if (and (eq org-subtree-clip (current-kill 0))
2834 org-subtree-clip-folded)
2835 ;; The tree was folded before it was killed/copied
2836 (hide-subtree))))
2837
2838 (defun org-kill-is-subtree-p (&optional txt)
2839 "Check if the current kill is an outline subtree, or a set of trees.
2840 Returns nil if kill does not start with a headline, or if the first
2841 headline level is not the largest headline level in the tree.
2842 So this will actually accept several entries of equal levels as well,
2843 which is OK for `org-paste-subtree'.
2844 If optional TXT is given, check this string instead of the current kill."
2845 (let* ((kill (or txt (current-kill 0) ""))
2846 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2847 (- (match-end 0) (match-beginning 0))))
2848 (re (concat "^" outline-regexp))
2849 (start 1))
2850 (if (not start-level)
2851 nil ;; does not even start with a heading
2852 (catch 'exit
2853 (while (setq start (string-match re kill (1+ start)))
2854 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2855 (throw 'exit nil)))
2856 t))))
2857
2858 ;;; Plain list items
2859
2860 (defun org-at-item-p ()
2861 "Is point in a line starting a hand-formatted item?"
2862 (let ((llt org-plain-list-ordered-item-terminator))
2863 (save-excursion
2864 (goto-char (point-at-bol))
2865 (looking-at
2866 (cond
2867 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2868 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2869 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2870 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
2871
2872 (defun org-get-indentation ()
2873 "Get the indentation of the current line, ionterpreting tabs."
2874 (save-excursion
2875 (beginning-of-line 1)
2876 (skip-chars-forward " \t")
2877 (current-column)))
2878
2879 (defun org-beginning-of-item ()
2880 "Go to the beginning of the current hand-formatted item.
2881 If the cursor is not in an item, throw an error."
2882 (let ((pos (point))
2883 (limit (save-excursion (org-back-to-heading)
2884 (beginning-of-line 2) (point)))
2885 ind ind1)
2886 (if (org-at-item-p)
2887 (beginning-of-line 1)
2888 (beginning-of-line 1)
2889 (skip-chars-forward " \t")
2890 (setq ind (current-column))
2891 (if (catch 'exit
2892 (while t
2893 (beginning-of-line 0)
2894 (if (< (point) limit) (throw 'exit nil))
2895 (unless (looking-at " \t]*$")
2896 (skip-chars-forward " \t")
2897 (setq ind1 (current-column))
2898 (if (< ind1 ind)
2899 (throw 'exit (org-at-item-p))))))
2900 nil
2901 (goto-char pos)
2902 (error "Not in an item")))))
2903
2904 (defun org-end-of-item ()
2905 "Go to the beginning of the current hand-formatted item.
2906 If the cursor is not in an item, throw an error."
2907 (let ((pos (point))
2908 (limit (save-excursion (outline-next-heading) (point)))
2909 (ind (save-excursion
2910 (org-beginning-of-item)
2911 (skip-chars-forward " \t")
2912 (current-column)))
2913 ind1)
2914 (if (catch 'exit
2915 (while t
2916 (beginning-of-line 2)
2917 (if (>= (point) limit) (throw 'exit t))
2918 (unless (looking-at "[ \t]*$")
2919 (skip-chars-forward " \t")
2920 (setq ind1 (current-column))
2921 (if (<= ind1 ind) (throw 'exit t)))))
2922 (beginning-of-line 1)
2923 (goto-char pos)
2924 (error "Not in an item"))))
2925
2926 (defun org-move-item-down (arg)
2927 "Move the plain list item at point down, i.e. swap with following item.
2928 Subitems (items with larger indentation are considered part of the item,
2929 so this really moves item trees."
2930 (interactive "p")
2931 (let (beg end ind ind1 (pos (point)) txt)
2932 (org-beginning-of-item)
2933 (setq beg (point))
2934 (setq ind (org-get-indentation))
2935 (org-end-of-item)
2936 (setq end (point))
2937 (setq ind1 (org-get-indentation))
2938 (if (and (org-at-item-p) (= ind ind1))
2939 (progn
2940 (org-end-of-item)
2941 (setq txt (buffer-substring beg end))
2942 (save-excursion
2943 (delete-region beg end))
2944 (setq pos (point))
2945 (insert txt)
2946 (goto-char pos)
2947 (org-maybe-renumber-ordered-list))
2948 (goto-char pos)
2949 (error "Cannot move this item further down"))))
2950
2951 (defun org-move-item-up (arg)
2952 "Move the plain list item at point up, i.e. swap with previous item.
2953 Subitems (items with larger indentation are considered part of the item,
2954 so this really moves item trees."
2955 (interactive "p")
2956 (let (beg end ind ind1 (pos (point)) txt)
2957 (org-beginning-of-item)
2958 (setq beg (point))
2959 (setq ind (org-get-indentation))
2960 (org-end-of-item)
2961 (setq end (point))
2962 (goto-char beg)
2963 (catch 'exit
2964 (while t
2965 (beginning-of-line 0)
2966 (if (looking-at "[ \t]*$")
2967 nil
2968 (if (<= (setq ind1 (org-get-indentation)) ind)
2969 (throw 'exit t)))))
2970 (condition-case nil
2971 (org-beginning-of-item)
2972 (error (goto-char beg)
2973 (error "Cannot move this item further up")))
2974 (setq ind1 (org-get-indentation))
2975 (if (and (org-at-item-p) (= ind ind1))
2976 (progn
2977 (setq txt (buffer-substring beg end))
2978 (save-excursion
2979 (delete-region beg end))
2980 (setq pos (point))
2981 (insert txt)
2982 (goto-char pos)
2983 (org-maybe-renumber-ordered-list))
2984 (goto-char pos)
2985 (error "Cannot move this item further up"))))
2986
2987 (defun org-maybe-renumber-ordered-list ()
2988 "Renumber the ordered list at point if setup allows it.
2989 This tests the user option `org-auto-renumber-ordered-lists' before
2990 doing the renumbering."
2991 (and org-auto-renumber-ordered-lists
2992 (org-at-item-p)
2993 (match-beginning 3)
2994 (org-renumber-ordered-list 1)))
2995
2996 (defun org-get-string-indentation (s)
2997 "What indentation has S due to SPACE and TAB at the beginning of the string?"
2998 (let ((n -1) (i 0) (w tab-width) c)
2999 (catch 'exit
3000 (while (< (setq n (1+ n)) (length s))
3001 (setq c (aref s n))
3002 (cond ((= c ?\ ) (setq i (1+ i)))
3003 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3004 (t (throw 'exit t)))))
3005 i))
3006
3007 (defun org-renumber-ordered-list (arg)
3008 "Renumber an ordered plain list.
3009 Cursor neext to be in the first line of an item, the line that starts
3010 with something like \"1.\" or \"2)\"."
3011 (interactive "p")
3012 (unless (and (org-at-item-p)
3013 (match-beginning 3))
3014 (error "This is not an ordered list"))
3015 (let ((line (org-current-line))
3016 (col (current-column))
3017 (ind (org-get-string-indentation
3018 (buffer-substring (point-at-bol) (match-beginning 3))))
3019 ;; (term (substring (match-string 3) -1))
3020 ind1 (n (1- arg)))
3021 ;; find where this list begins
3022 (catch 'exit
3023 (while t
3024 (catch 'next
3025 (beginning-of-line 0)
3026 (if (looking-at "[ \t]*$") (throw 'next t))
3027 (skip-chars-forward " \t") (setq ind1 (current-column))
3028 (if (or (< ind1 ind)
3029 (and (= ind1 ind)
3030 (not (org-at-item-p))))
3031 (throw 'exit t)))))
3032 ;; Walk forward and replace these numbers
3033 (catch 'exit
3034 (while t
3035 (catch 'next
3036 (beginning-of-line 2)
3037 (if (eobp) (throw 'exit nil))
3038 (if (looking-at "[ \t]*$") (throw 'next nil))
3039 (skip-chars-forward " \t") (setq ind1 (current-column))
3040 (if (> ind1 ind) (throw 'next t))
3041 (if (< ind1 ind) (throw 'exit t))
3042 (if (not (org-at-item-p)) (throw 'exit nil))
3043 (if (not (match-beginning 3))
3044 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3045 (delete-region (match-beginning 3) (1- (match-end 3)))
3046 (goto-char (match-beginning 3))
3047 (insert (format "%d" (setq n (1+ n)))))))
3048 (goto-line line)
3049 (move-to-column col)))
3050
3051 (defvar org-last-indent-begin-marker (make-marker))
3052 (defvar org-last-indent-end-marker (make-marker))
3053
3054
3055 (defun org-outdent-item (arg)
3056 "Outdent a local list item."
3057 (interactive "p")
3058 (org-indent-item (- arg)))
3059
3060 (defun org-indent-item (arg)
3061 "Indent a local list item."
3062 (interactive "p")
3063 (unless (org-at-item-p)
3064 (error "Not on an item"))
3065 (let (beg end ind ind1)
3066 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3067 (setq beg org-last-indent-begin-marker
3068 end org-last-indent-end-marker)
3069 (org-beginning-of-item)
3070 (setq beg (move-marker org-last-indent-begin-marker (point)))
3071 (org-end-of-item)
3072 (setq end (move-marker org-last-indent-end-marker (point))))
3073 (goto-char beg)
3074 (skip-chars-forward " \t") (setq ind (current-column))
3075 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3076 (while (< (point) end)
3077 (beginning-of-line 1)
3078 (skip-chars-forward " \t") (setq ind1 (current-column))
3079 (delete-region (point-at-bol) (point))
3080 (indent-to-column (+ ind1 arg))
3081 (beginning-of-line 2))
3082 (goto-char beg)))
3083
3084 ;;; Archiving
3085
3086 (defun org-archive-subtree ()
3087 "Move the current subtree to the archive.
3088 The archive can be a certain top-level heading in the current file, or in
3089 a different file. The tree will be moved to that location, the subtree
3090 heading be marked DONE, and the current time will be added."
3091 (interactive)
3092 ;; Save all relevant TODO keyword-relatex variables
3093 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3094 (tr-org-todo-keywords org-todo-keywords)
3095 (tr-org-todo-interpretation org-todo-interpretation)
3096 (tr-org-done-string org-done-string)
3097 (tr-org-todo-regexp org-todo-regexp)
3098 (tr-org-todo-line-regexp org-todo-line-regexp)
3099 (this-buffer (current-buffer))
3100 file heading buffer level newfile-p)
3101 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3102 (progn
3103 (setq file (format (match-string 1 org-archive-location)
3104 (file-name-nondirectory (buffer-file-name)))
3105 heading (match-string 2 org-archive-location)))
3106 (error "Invalid `org-archive-location'"))
3107 (if (> (length file) 0)
3108 (setq newfile-p (not (file-exists-p file))
3109 buffer (find-file-noselect file))
3110 (setq buffer (current-buffer)))
3111 (unless buffer
3112 (error "Cannot access file \"%s\"" file))
3113 (if (and (> (length heading) 0)
3114 (string-match "^\\*+" heading))
3115 (setq level (match-end 0))
3116 (setq heading nil level 0))
3117 (save-excursion
3118 ;; We first only copy, in case something goes wrong
3119 ;; we need to protect this-command, to avoid kill-region sets it,
3120 ;; which would lead to duplication of subtrees
3121 (let (this-command) (org-copy-subtree))
3122 (set-buffer buffer)
3123 ;; Enforce org-mode for the archive buffer
3124 (if (not (eq major-mode 'org-mode))
3125 ;; Force the mode for future visits.
3126 (let ((org-insert-mode-line-in-empty-file t))
3127 (call-interactively 'org-mode)))
3128 (when newfile-p
3129 (goto-char (point-max))
3130 (insert (format "\nArchived entries from file %s\n\n"
3131 (buffer-file-name this-buffer))))
3132 ;; Force the TODO keywords of the original buffer
3133 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3134 (org-todo-keywords tr-org-todo-keywords)
3135 (org-todo-interpretation tr-org-todo-interpretation)
3136 (org-done-string tr-org-done-string)
3137 (org-todo-regexp tr-org-todo-regexp)
3138 (org-todo-line-regexp tr-org-todo-line-regexp))
3139 (goto-char (point-min))
3140 (if heading
3141 (progn
3142 (if (re-search-forward
3143 (concat "\\(^\\|\r\\)"
3144 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3145 nil t)
3146 (goto-char (match-end 0))
3147 ;; Heading not found, just insert it at the end
3148 (goto-char (point-max))
3149 (or (bolp) (insert "\n"))
3150 (insert "\n" heading "\n")
3151 (end-of-line 0))
3152 ;; Make the heading visible, and the following as well
3153 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3154 (if (re-search-forward
3155 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3156 nil t)
3157 (progn (goto-char (match-beginning 0)) (insert "\n")
3158 (beginning-of-line 0))
3159 (goto-char (point-max)) (insert "\n")))
3160 (goto-char (point-max)) (insert "\n"))
3161 ;; Paste
3162 (org-paste-subtree (1+ level))
3163 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3164 (if org-archive-mark-done
3165 (org-todo (length org-todo-keywords)))
3166 ;; Move cursor to right after the TODO keyword
3167 (when org-archive-stamp-time
3168 (beginning-of-line 1)
3169 (looking-at org-todo-line-regexp)
3170 (goto-char (or (match-end 2) (match-beginning 3)))
3171 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3172 (current-time))
3173 ")"))
3174 ;; Save the buffer, if it is not the same buffer.
3175 (if (not (eq this-buffer buffer)) (save-buffer))))
3176 ;; Here we are back in the original buffer. Everything seems to have
3177 ;; worked. So now cut the tree and finish up.
3178 (let (this-command) (org-cut-subtree))
3179 (if (looking-at "[ \t]*$") (kill-line))
3180 (message "Subtree archived %s"
3181 (if (eq this-buffer buffer)
3182 (concat "under heading: " heading)
3183 (concat "in file: " (abbreviate-file-name file))))))
3184
3185 ;;; Completion
3186
3187 (defun org-complete (&optional arg)
3188 "Perform completion on word at point.
3189 At the beginning of a headline, this completes TODO keywords as given in
3190 `org-todo-keywords'.
3191 If the current word is preceded by a backslash, completes the TeX symbols
3192 that are supported for HTML support.
3193 If the current word is preceded by \"#+\", completes special words for
3194 setting file options.
3195 At all other locations, this simply calls `ispell-complete-word'."
3196 (interactive "P")
3197 (catch 'exit
3198 (let* ((end (point))
3199 (beg1 (save-excursion
3200 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3201 (skip-chars-backward "a-zA-Z_")
3202 (point)))
3203 (beg (save-excursion
3204 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3205 (skip-chars-backward "a-zA-Z0-9_:$")
3206 (point)))
3207 (camel (equal (char-before beg) ?*))
3208 (tag (equal (char-before beg1) ?:))
3209 (texp (equal (char-before beg) ?\\))
3210 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3211 beg)
3212 "#+"))
3213 (completion-ignore-case opt)
3214 (type nil)
3215 (tbl nil)
3216 (table (cond
3217 (opt
3218 (setq type :opt)
3219 (mapcar (lambda (x)
3220 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3221 (cons (match-string 2 x) (match-string 1 x)))
3222 (org-split-string (org-get-current-options) "\n")))
3223 (texp
3224 (setq type :tex)
3225 org-html-entities)
3226 ((string-match "\\`\\*+[ \t]*\\'"
3227 (buffer-substring (point-at-bol) beg))
3228 (setq type :todo)
3229 (mapcar 'list org-todo-keywords))
3230 (camel
3231 (setq type :camel)
3232 (save-excursion
3233 (goto-char (point-min))
3234 (while (re-search-forward org-todo-line-regexp nil t)
3235 (push (list (org-make-org-heading-camel (match-string 3)))
3236 tbl)))
3237 tbl)
3238 (tag (setq type :tag beg beg1)
3239 (org-get-buffer-tags))
3240 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3241 (pattern (buffer-substring-no-properties beg end))
3242 (completion (try-completion pattern table)))
3243 (cond ((eq completion t)
3244 (if (equal type :opt)
3245 (insert (substring (cdr (assoc (upcase pattern) table))
3246 (length pattern)))))
3247 ((null completion)
3248 (message "Can't find completion for \"%s\"" pattern)
3249 (ding))
3250 ((not (string= pattern completion))
3251 (delete-region beg end)
3252 (if (string-match " +$" completion)
3253 (setq completion (replace-match "" t t completion)))
3254 (insert completion)
3255 (if (get-buffer-window "*Completions*")
3256 (delete-window (get-buffer-window "*Completions*")))
3257 (if (assoc completion table)
3258 (if (eq type :todo) (insert " ")
3259 (if (eq type :tag) (insert ":"))))
3260 (if (and (equal type :opt) (assoc completion table))
3261 (message "%s" (substitute-command-keys
3262 "Press \\[org-complete] again to insert example settings"))))
3263 (t
3264 (message "Making completion list...")
3265 (let ((list (sort (all-completions pattern table) 'string<)))
3266 (with-output-to-temp-buffer "*Completions*"
3267 (display-completion-list list)))
3268 (message "Making completion list...%s" "done"))))))
3269
3270 ;;; Comments, TODO and DEADLINE
3271
3272 (defun org-toggle-comment ()
3273 "Change the COMMENT state of an entry."
3274 (interactive)
3275 (save-excursion
3276 (org-back-to-heading)
3277 (if (looking-at (concat outline-regexp
3278 "\\( +\\<" org-comment-string "\\>\\)"))
3279 (replace-match "" t t nil 1)
3280 (if (looking-at outline-regexp)
3281 (progn
3282 (goto-char (match-end 0))
3283 (insert " " org-comment-string))))))
3284
3285 (defvar org-last-todo-state-is-todo nil
3286 "This is non-nil when the last TODO state change led to a TODO state.
3287 If the last change removed the TODO tag or switched to DONE, then
3288 this is nil.")
3289
3290 (defun org-todo (&optional arg)
3291 "Change the TODO state of an item.
3292 The state of an item is given by a keyword at the start of the heading,
3293 like
3294 *** TODO Write paper
3295 *** DONE Call mom
3296
3297 The different keywords are specified in the variable `org-todo-keywords'. By
3298 default the available states are \"TODO\" and \"DONE\".
3299 So for this example: when the item starts with TODO, it is changed to DONE.
3300 When it starts with DONE, the DONE is removed. And when neither TODO nor
3301 DONE are present, add TODO at the beginning of the heading.
3302
3303 With prefix arg, use completion to determined the new state. With numeric
3304 prefix arg, switch to that state."
3305 (interactive "P")
3306 (save-excursion
3307 (org-back-to-heading)
3308 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3309 (or (looking-at (concat " +" org-todo-regexp " *"))
3310 (looking-at " *"))
3311 (let* ((this (match-string 1))
3312 (completion-ignore-case t)
3313 (member (member this org-todo-keywords))
3314 (tail (cdr member))
3315 (state (cond
3316 ((equal arg '(4))
3317 ;; Read a state with completion
3318 (completing-read "State: " (mapcar (lambda(x) (list x))
3319 org-todo-keywords)
3320 nil t))
3321 ((eq arg 'right)
3322 (if this
3323 (if tail (car tail) nil)
3324 (car org-todo-keywords)))
3325 ((eq arg 'left)
3326 (if (equal member org-todo-keywords)
3327 nil
3328 (if this
3329 (nth (- (length org-todo-keywords) (length tail) 2)
3330 org-todo-keywords)
3331 org-done-string)))
3332 (arg
3333 ;; user requests a specific state
3334 (nth (1- (prefix-numeric-value arg))
3335 org-todo-keywords))
3336 ((null member) (car org-todo-keywords))
3337 ((null tail) nil) ;; -> first entry
3338 ((eq org-todo-interpretation 'sequence)
3339 (car tail))
3340 ((memq org-todo-interpretation '(type priority))
3341 (if (eq this-command last-command)
3342 (car tail)
3343 (if (> (length tail) 0) org-done-string nil)))
3344 (t nil)))
3345 (next (if state (concat " " state " ") " ")))
3346 (replace-match next t t)
3347 (setq org-last-todo-state-is-todo
3348 (not (equal state org-done-string)))
3349 (when org-log-done
3350 (if (equal state org-done-string)
3351 (org-log-done)
3352 (if (not this)
3353 (org-log-done t))))
3354 ;; Fixup tag positioning
3355 (and org-auto-align-tags (org-set-tags nil t))
3356 (run-hooks 'org-after-todo-state-change-hook)))
3357 ;; Fixup cursor location if close to the keyword
3358 (if (and (outline-on-heading-p)
3359 (not (bolp))
3360 (save-excursion (beginning-of-line 1)
3361 (looking-at org-todo-line-regexp))
3362 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3363 (progn
3364 (goto-char (or (match-end 2) (match-end 1)))
3365 (just-one-space))))
3366
3367 (defun org-log-done (&optional undone)
3368 "Add a time stamp logging that a TODO entry has been closed.
3369 When UNDONE is non-nil, remove such a time stamg again."
3370 (interactive)
3371 (let (beg end col)
3372 (save-excursion
3373 (org-back-to-heading t)
3374 (setq beg (point))
3375 (looking-at (concat outline-regexp " *"))
3376 (goto-char (match-end 0))
3377 (setq col (current-column))
3378 (outline-next-heading)
3379 (setq end (point))
3380 (goto-char beg)
3381 (when (re-search-forward (concat
3382 "[\r\n]\\([ \t]*"
3383 (regexp-quote org-closed-string)
3384 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3385 (delete-region (match-beginning 1) (match-end 1)))
3386 (unless undone
3387 (org-back-to-heading t)
3388 (skip-chars-forward "^\n\r")
3389 (goto-char (min (1+ (point)) (point-max)))
3390 (when (not (member (char-before) '(?\r ?\n)))
3391 (insert "\n"))
3392 (indent-to col)
3393 (insert org-closed-string " "
3394 (format-time-string
3395 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3396 (current-time))
3397 "\n")))))
3398
3399 (defun org-show-todo-tree (arg)
3400 "Make a compact tree which shows all headlines marked with TODO.
3401 The tree will show the lines where the regexp matches, and all higher
3402 headlines above the match.
3403 With \\[universal-argument] prefix, also show the DONE entries.
3404 With a numeric prefix N, construct a sparse tree for the Nth element
3405 of `org-todo-keywords'."
3406 (interactive "P")
3407 (let ((case-fold-search nil)
3408 (kwd-re
3409 (cond ((null arg) org-not-done-regexp)
3410 ((equal arg '(4)) org-todo-regexp)
3411 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3412 (regexp-quote (nth (1- (prefix-numeric-value arg))
3413 org-todo-keywords)))
3414 (t (error "Invalid prefix argument: %s" arg)))))
3415 (message "%d TODO entries found"
3416 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3417
3418 (defun org-deadline ()
3419 "Insert the DEADLINE: string to make a deadline.
3420 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3421 to modify it to the correct date."
3422 (interactive)
3423 (insert
3424 org-deadline-string " "
3425 (format-time-string (car org-time-stamp-formats)
3426 (org-read-date nil 'to-time)))
3427 (message "%s" (substitute-command-keys
3428 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3429
3430 (defun org-schedule ()
3431 "Insert the SCHEDULED: string to schedule a TODO item.
3432 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3433 to modify it to the correct date."
3434 (interactive)
3435 (insert
3436 org-scheduled-string " "
3437 (format-time-string (car org-time-stamp-formats)
3438 (org-read-date nil 'to-time)))
3439 (message "%s" (substitute-command-keys
3440 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3441
3442
3443 (defun org-occur (regexp &optional callback)
3444 "Make a compact tree which shows all matches of REGEXP.
3445 The tree will show the lines where the regexp matches, and all higher
3446 headlines above the match. It will also show the heading after the match,
3447 to make sure editing the matching entry is easy.
3448 if CALLBACK is non-nil, it is a function which is called to confirm
3449 that the match should indeed be shown."
3450 (interactive "sRegexp: ")
3451 (org-remove-occur-highlights nil nil t)
3452 (setq regexp (org-check-occur-regexp regexp))
3453 (let ((cnt 0))
3454 (save-excursion
3455 (goto-char (point-min))
3456 (hide-sublevels 1)
3457 (while (re-search-forward regexp nil t)
3458 (when (or (not callback)
3459 (save-match-data (funcall callback)))
3460 (setq cnt (1+ cnt))
3461 (org-highlight-new-match (match-beginning 0) (match-end 0))
3462 (org-show-hierarchy-above))))
3463 (make-local-hook 'before-change-functions) ; needed for XEmacs
3464 (add-hook 'before-change-functions 'org-remove-occur-highlights
3465 nil 'local)
3466 (run-hooks 'org-occur-hook)
3467 (if (interactive-p)
3468 (message "%d match(es) for regexp %s" cnt regexp))
3469 cnt))
3470
3471 (defun org-show-hierarchy-above ()
3472 "Make sure point and the headings hierarchy above is visible."
3473 (catch 'exit
3474 (if (org-on-heading-p t)
3475 (org-flag-heading nil) ; only show the heading
3476 (and (org-invisible-p) (org-show-hidden-entry))) ; show entire entry
3477 (save-excursion
3478 (and org-show-following-heading
3479 (outline-next-heading)
3480 (org-flag-heading nil))) ; show the next heading
3481 (when org-show-hierarchy-above
3482 (save-excursion ; show all higher headings
3483 (while (and (condition-case nil
3484 (progn (org-up-heading-all 1) t)
3485 (error nil))
3486 (not (bobp)))
3487 (org-flag-heading nil))))))
3488
3489 ;; Overlay compatibility functions
3490 (defun org-make-overlay (beg end &optional buffer)
3491 (if org-xemacs-p (make-extent beg end buffer) (make-overlay beg end buffer)))
3492 (defun org-delete-overlay (ovl)
3493 (if org-xemacs-p (delete-extent ovl) (delete-overlay ovl)))
3494 (defun org-detatch-overlay (ovl)
3495 (if org-xemacs-p (detach-extent ovl) (delete-overlay ovl)))
3496 (defun org-move-overlay (ovl beg end &optional buffer)
3497 (if org-xemacs-p
3498 (set-extent-endpoints ovl beg end buffer)
3499 (move-overlay ovl beg end buffer)))
3500 (defun org-overlay-put (ovl prop value)
3501 (if org-xemacs-p
3502 (set-extent-property ovl prop value)
3503 (overlay-put ovl prop value)))
3504
3505 (defvar org-occur-highlights nil)
3506 (defun org-highlight-new-match (beg end)
3507 "Highlight from BEG to END and mark the highlight is an occur headline."
3508 (let ((ov (org-make-overlay beg end)))
3509 (org-overlay-put ov 'face 'secondary-selection)
3510 (push ov org-occur-highlights)))
3511
3512 (defun org-remove-occur-highlights (&optional beg end noremove)
3513 "Remove the occur highlights from the buffer.
3514 BEG and END are ignored. If NOREMOVE is nil, remove this function
3515 from the before-change-functions in the current buffer."
3516 (interactive)
3517 (mapc 'org-delete-overlay org-occur-highlights)
3518 (setq org-occur-highlights nil)
3519 (unless noremove
3520 (remove-hook 'before-change-functions
3521 'org-remove-occur-highlights 'local)))
3522
3523 ;;; Priorities
3524
3525 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3526 "Regular expression matching the priority indicator.")
3527
3528 (defvar org-remove-priority-next-time nil)
3529
3530 (defun org-priority-up ()
3531 "Increase the priority of the current item."
3532 (interactive)
3533 (org-priority 'up))
3534
3535 (defun org-priority-down ()
3536 "Decrease the priority of the current item."
3537 (interactive)
3538 (org-priority 'down))
3539
3540 (defun org-priority (&optional action)
3541 "Change the priority of an item by ARG.
3542 ACTION can be set, up, or down."
3543 (interactive)
3544 (setq action (or action 'set))
3545 (let (current new news have remove)
3546 (save-excursion
3547 (org-back-to-heading)
3548 (if (looking-at org-priority-regexp)
3549 (setq current (string-to-char (match-string 2))
3550 have t)
3551 (setq current org-default-priority))
3552 (cond
3553 ((eq action 'set)
3554 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3555 (setq new (read-char-exclusive))
3556 (cond ((equal new ?\ ) (setq remove t))
3557 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3558 (error "Priority must be between `%c' and `%c'"
3559 ?A org-lowest-priority))))
3560 ((eq action 'up)
3561 (setq new (1- current)))
3562 ((eq action 'down)
3563 (setq new (1+ current)))
3564 (t (error "Invalid action")))
3565 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3566 (setq news (format "%c" new))
3567 (if have
3568 (if remove
3569 (replace-match "" t t nil 1)
3570 (replace-match news t t nil 2))
3571 (if remove
3572 (error "No priority cookie found in line")
3573 (looking-at org-todo-line-regexp)
3574 (if (match-end 2)
3575 (progn
3576 (goto-char (match-end 2))
3577 (insert " [#" news "]"))
3578 (goto-char (match-beginning 3))
3579 (insert "[#" news "] ")))))
3580 (if remove
3581 (message "Priority removed")
3582 (message "Priority of current item set to %s" news))))
3583
3584
3585 (defun org-get-priority (s)
3586 "Find priority cookie and return priority."
3587 (save-match-data
3588 (if (not (string-match org-priority-regexp s))
3589 (* 1000 (- org-lowest-priority org-default-priority))
3590 (* 1000 (- org-lowest-priority
3591 (string-to-char (match-string 2 s)))))))
3592
3593 ;;; Timestamps
3594
3595 (defvar org-last-changed-timestamp nil)
3596
3597 (defun org-time-stamp (arg)
3598 "Prompt for a date/time and insert a time stamp.
3599 If the user specifies a time like HH:MM, or if this command is called
3600 with a prefix argument, the time stamp will contain date and time.
3601 Otherwise, only the date will be included. All parts of a date not
3602 specified by the user will be filled in from the current date/time.
3603 So if you press just return without typing anything, the time stamp
3604 will represent the current date/time. If there is already a timestamp
3605 at the cursor, it will be modified."
3606 (interactive "P")
3607 (let ((fmt (if arg (cdr org-time-stamp-formats)
3608 (car org-time-stamp-formats)))
3609 (org-time-was-given nil)
3610 time)
3611 (cond
3612 ((and (org-at-timestamp-p)
3613 (eq last-command 'org-time-stamp)
3614 (eq this-command 'org-time-stamp))
3615 (insert "--")
3616 (setq time (let ((this-command this-command))
3617 (org-read-date arg 'totime)))
3618 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3619 (insert (format-time-string fmt time)))
3620 ((org-at-timestamp-p)
3621 (setq time (let ((this-command this-command))
3622 (org-read-date arg 'totime)))
3623 (and (org-at-timestamp-p) (replace-match
3624 (setq org-last-changed-timestamp
3625 (format-time-string fmt time))
3626 t t))
3627 (message "Timestamp updated"))
3628 (t
3629 (setq time (let ((this-command this-command))
3630 (org-read-date arg 'totime)))
3631 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3632 (insert (format-time-string fmt time))))))
3633
3634 (defun org-time-stamp-inactive (&optional arg)
3635 "Insert an inactive time stamp.
3636 An inactive time stamp is enclosed in square brackets instead of angle
3637 brackets. It is inactive in the sense that it does not trigger agenda entries,
3638 does not link to the calendar and cannot be changed with the S-cursor keys.
3639 So these are more for recording a certain time/date."
3640 ;; FIXME: Would it be better not to ask for a date/time here?
3641 (interactive "P")
3642 (let ((fmt (if arg (cdr org-time-stamp-formats)
3643 (car org-time-stamp-formats)))
3644 (org-time-was-given nil)
3645 time)
3646 (setq time (org-read-date arg 'totime))
3647 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3648 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3649 (insert (format-time-string fmt time))))
3650
3651 (defvar org-date-ovl (org-make-overlay 1 1))
3652 (org-overlay-put org-date-ovl 'face 'org-warning)
3653 (org-detatch-overlay org-date-ovl)
3654
3655 ;;; FIXME: Make the function take "Fri" as "next friday"
3656 ;;; because these are mostly being used to record the current time.
3657 (defun org-read-date (&optional with-time to-time)
3658 "Read a date and make things smooth for the user.
3659 The prompt will suggest to enter an ISO date, but you can also enter anything
3660 which will at least partially be understood by `parse-time-string'.
3661 Unrecognized parts of the date will default to the current day, month ,year,
3662 hour and minute. For example,
3663 3-2-5 --> 2003-02-05
3664 feb 15 --> currentyear-02-15
3665 sep 12 9 --> 2009-09-12
3666 12:45 --> today 12:45
3667 22 sept 0:34 --> currentyear-09-22 0:34
3668 12 --> currentyear-currentmonth-12
3669 etc.
3670 The function understands only English month and weekday abbreviations,
3671 but this can be configured with the variables `parse-time-months' and
3672 `parse-time-weekdays'.
3673
3674 While prompting, a calendar is popped up - you can also select the
3675 date with the mouse (button 1). The calendar shows a period of three
3676 month. To scroll it to other months, use the keys `>' and `<'.
3677 If you don't like the calendar, turn it off with
3678 \(setq org-popup-calendar-for-date-prompt nil).
3679
3680 With optional argument TO-TIME, the date will immediately be converted
3681 to an internal time.
3682 With an optional argument WITH-TIME, the prompt will suggest to also
3683 insert a time. Note that when WITH-TIME is not set, you can still
3684 enter a time, and this function will inform the calling routine about
3685 this change. The calling routine may then choose to change the format
3686 used to insert the time stamp into the buffer to include the time."
3687 (let* ((default-time
3688 ;; Default time is either today, or, when entering a range,
3689 ;; the range start.
3690 (if (save-excursion
3691 (re-search-backward
3692 (concat org-ts-regexp "--\\=")
3693 (- (point) 20) t))
3694 (apply
3695 'encode-time
3696 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3697 (parse-time-string (match-string 1))))
3698 (current-time)))
3699 (calendar-move-hook nil)
3700 (view-diary-entries-initially nil)
3701 (timestr (format-time-string
3702 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3703 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3704 ans ans1 ans2
3705 second minute hour day month year tl)
3706
3707 (if org-popup-calendar-for-date-prompt
3708 ;; Also show a calendar for date selection
3709 ;; Copied (with modifications) from planner.el by John Wiegley
3710 (save-excursion
3711 (save-window-excursion
3712 (calendar)
3713 (calendar-forward-day (- (time-to-days default-time)
3714 (calendar-absolute-from-gregorian
3715 (calendar-current-date))))
3716 (org-eval-in-calendar nil)
3717 (let* ((old-map (current-local-map))
3718 (map (copy-keymap calendar-mode-map))
3719 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3720 (define-key map (kbd "RET") 'org-calendar-select)
3721 (define-key map (if org-xemacs-p [button1] [mouse-1])
3722 'org-calendar-select-mouse)
3723 (define-key map (if org-xemacs-p [button2] [mouse-2])
3724 'org-calendar-select-mouse)
3725 (define-key minibuffer-local-map [(meta shift left)]
3726 (lambda () (interactive)
3727 (org-eval-in-calendar '(calendar-backward-month 1))))
3728 (define-key minibuffer-local-map [(meta shift right)]
3729 (lambda () (interactive)
3730 (org-eval-in-calendar '(calendar-forward-month 1))))
3731 (define-key minibuffer-local-map [(shift up)]
3732 (lambda () (interactive)
3733 (org-eval-in-calendar '(calendar-backward-week 1))))
3734 (define-key minibuffer-local-map [(shift down)]
3735 (lambda () (interactive)
3736 (org-eval-in-calendar '(calendar-forward-week 1))))
3737 (define-key minibuffer-local-map [(shift left)]
3738 (lambda () (interactive)
3739 (org-eval-in-calendar '(calendar-backward-day 1))))
3740 (define-key minibuffer-local-map [(shift right)]
3741 (lambda () (interactive)
3742 (org-eval-in-calendar '(calendar-forward-day 1))))
3743 (define-key minibuffer-local-map ">"
3744 (lambda () (interactive)
3745 (org-eval-in-calendar '(scroll-calendar-left 1))))
3746 (define-key minibuffer-local-map "<"
3747 (lambda () (interactive)
3748 (org-eval-in-calendar '(scroll-calendar-right 1))))
3749 (unwind-protect
3750 (progn
3751 (use-local-map map)
3752 (setq ans (read-string prompt "" nil nil))
3753 (setq ans (or ans1 ans2 ans)))
3754 (use-local-map old-map)))))
3755 ;; Naked prompt only
3756 (setq ans (read-string prompt "" nil timestr)))
3757 (org-detatch-overlay org-date-ovl)
3758
3759 (if (string-match
3760 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3761 (progn
3762 (setq year (if (match-end 2)
3763 (string-to-number (match-string 2 ans))
3764 (string-to-number (format-time-string "%Y")))
3765 month (string-to-number (match-string 3 ans))
3766 day (string-to-number (match-string 4 ans)))
3767 (if (< year 100) (setq year (+ 2000 year)))
3768 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3769 t t ans))))
3770 (setq tl (parse-time-string ans)
3771 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3772 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3773 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3774 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3775 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3776 second (or (nth 0 tl) 0))
3777 (if (and (boundp 'org-time-was-given)
3778 (nth 2 tl))
3779 (setq org-time-was-given t))
3780 (if (< year 100) (setq year (+ 2000 year)))
3781 (if to-time
3782 (encode-time second minute hour day month year)
3783 (if (or (nth 1 tl) (nth 2 tl))
3784 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3785 (format "%04d-%02d-%02d" year month day)))))
3786
3787 (defun org-eval-in-calendar (form)
3788 "Eval FORM in the calendar window and return to current window.
3789 Also, store the cursor date in variable ans2."
3790 (let ((sw (selected-window)))
3791 (select-window (get-buffer-window "*Calendar*"))
3792 (eval form)
3793 (when (calendar-cursor-to-date)
3794 (let* ((date (calendar-cursor-to-date))
3795 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3796 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3797 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
3798 (select-window sw)))
3799
3800 (defun org-calendar-select ()
3801 "Return to `org-read-date' with the date currently selected.
3802 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3803 (interactive)
3804 (when (calendar-cursor-to-date)
3805 (let* ((date (calendar-cursor-to-date))
3806 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3807 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3808 (if (active-minibuffer-window) (exit-minibuffer))))
3809
3810 (defun org-calendar-select-mouse (ev)
3811 "Return to `org-read-date' with the date currently selected.
3812 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3813 (interactive "e")
3814 (mouse-set-point ev)
3815 (when (calendar-cursor-to-date)
3816 (let* ((date (calendar-cursor-to-date))
3817 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3818 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3819 (if (active-minibuffer-window) (exit-minibuffer))))
3820
3821 (defun org-check-deadlines (ndays)
3822 "Check if there are any deadlines due or past due.
3823 A deadline is considered due if it happens within `org-deadline-warning-days'
3824 days from today's date. If the deadline appears in an entry marked DONE,
3825 it is not shown. The prefix arg NDAYS can be used to test that many
3826 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3827 (interactive "P")
3828 (let* ((org-warn-days
3829 (cond
3830 ((equal ndays '(4)) 100000)
3831 (ndays (prefix-numeric-value ndays))
3832 (t org-deadline-warning-days)))
3833 (case-fold-search nil)
3834 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3835 (callback
3836 (lambda ()
3837 (and (let ((d1 (time-to-days (current-time)))
3838 (d2 (time-to-days
3839 (org-time-string-to-time (match-string 1)))))
3840 (< (- d2 d1) org-warn-days))
3841 (not (org-entry-is-done-p))))))
3842 (message "%d deadlines past-due or due within %d days"
3843 (org-occur regexp callback)
3844 org-warn-days)))
3845
3846 (defun org-evaluate-time-range (&optional to-buffer)
3847 "Evaluate a time range by computing the difference between start and end.
3848 Normally the result is just printed in the echo area, but with prefix arg
3849 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3850 If the time range is actually in a table, the result is inserted into the
3851 next column.
3852 For time difference computation, a year is assumed to be exactly 365
3853 days in order to avoid rounding problems."
3854 (interactive "P")
3855 (save-excursion
3856 (unless (org-at-date-range-p)
3857 (goto-char (point-at-bol))
3858 (re-search-forward org-tr-regexp (point-at-eol) t))
3859 (if (not (org-at-date-range-p))
3860 (error "Not at a time-stamp range, and none found in current line")))
3861 (let* ((ts1 (match-string 1))
3862 (ts2 (match-string 2))
3863 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3864 (match-end (match-end 0))
3865 (time1 (org-time-string-to-time ts1))
3866 (time2 (org-time-string-to-time ts2))
3867 (t1 (time-to-seconds time1))
3868 (t2 (time-to-seconds time2))
3869 (diff (abs (- t2 t1)))
3870 (negative (< (- t2 t1) 0))
3871 ;; (ys (floor (* 365 24 60 60)))
3872 (ds (* 24 60 60))
3873 (hs (* 60 60))
3874 (fy "%dy %dd %02d:%02d")
3875 (fy1 "%dy %dd")
3876 (fd "%dd %02d:%02d")
3877 (fd1 "%dd")
3878 (fh "%02d:%02d")
3879 y d h m align)
3880 ;; FIXME: Should I re-introduce years, make year refer to same date?
3881 ;; This would be the only useful way to have years, actually.
3882 (if havetime
3883 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3884 y 0
3885 d (floor (/ diff ds)) diff (mod diff ds)
3886 h (floor (/ diff hs)) diff (mod diff hs)
3887 m (floor (/ diff 60)))
3888 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3889 y 0
3890 d (floor (+ (/ diff ds) 0.5))
3891 h 0 m 0))
3892 (if (not to-buffer)
3893 (message (org-make-tdiff-string y d h m))
3894 (when (org-at-table-p)
3895 (goto-char match-end)
3896 (setq align t)
3897 (and (looking-at " *|") (goto-char (match-end 0))))
3898 (if (looking-at
3899 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3900 (replace-match ""))
3901 (if negative (insert " -"))
3902 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3903 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3904 (insert " " (format fh h m))))
3905 (if align (org-table-align))
3906 (message "Time difference inserted"))))
3907
3908 (defun org-make-tdiff-string (y d h m)
3909 (let ((fmt "")
3910 (l nil))
3911 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3912 l (push y l)))
3913 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3914 l (push d l)))
3915 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3916 l (push h l)))
3917 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3918 l (push m l)))
3919 (apply 'format fmt (nreverse l))))
3920
3921 (defun org-time-string-to-time (s)
3922 (apply 'encode-time (org-parse-time-string s)))
3923
3924 (defun org-parse-time-string (s &optional nodefault)
3925 "Parse the standard Org-mode time string.
3926 This should be a lot faster than the normal `parse-time-string'.
3927 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3928 hour and minute fields will be nil if not given."
3929 (if (string-match org-ts-regexp1 s)
3930 (list 0
3931 (if (or (match-beginning 8) (not nodefault))
3932 (string-to-number (or (match-string 8 s) "0")))
3933 (if (or (match-beginning 7) (not nodefault))
3934 (string-to-number (or (match-string 7 s) "0")))
3935 (string-to-number (match-string 4 s))
3936 (string-to-number (match-string 3 s))
3937 (string-to-number (match-string 2 s))
3938 nil nil nil)
3939 (make-list 9 0)))
3940
3941 (defun org-timestamp-up (&optional arg)
3942 "Increase the date item at the cursor by one.
3943 If the cursor is on the year, change the year. If it is on the month or
3944 the day, change that.
3945 With prefix ARG, change by that many units."
3946 (interactive "p")
3947 (org-timestamp-change (prefix-numeric-value arg)))
3948
3949 (defun org-timestamp-down (&optional arg)
3950 "Decrease the date item at the cursor by one.
3951 If the cursor is on the year, change the year. If it is on the month or
3952 the day, change that.
3953 With prefix ARG, change by that many units."
3954 (interactive "p")
3955 (org-timestamp-change (- (prefix-numeric-value arg))))
3956
3957 (defun org-timestamp-up-day (&optional arg)
3958 "Increase the date in the time stamp by one day.
3959 With prefix ARG, change that many days."
3960 (interactive "p")
3961 (if (and (not (org-at-timestamp-p))
3962 (org-on-heading-p))
3963 (org-todo 'up)
3964 (org-timestamp-change (prefix-numeric-value arg) 'day)))
3965
3966 (defun org-timestamp-down-day (&optional arg)
3967 "Decrease the date in the time stamp by one day.
3968 With prefix ARG, change that many days."
3969 (interactive "p")
3970 (if (and (not (org-at-timestamp-p))
3971 (org-on-heading-p))
3972 (org-todo 'down)
3973 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
3974
3975 (defsubst org-pos-in-match-range (pos n)
3976 (and (match-beginning n)
3977 (<= (match-beginning n) pos)
3978 (>= (match-end n) pos)))
3979
3980 (defun org-at-timestamp-p ()
3981 "Determine if the cursor is in or at a timestamp."
3982 (interactive)
3983 (let* ((tsr org-ts-regexp2)
3984 (pos (point))
3985 (ans (or (looking-at tsr)
3986 (save-excursion
3987 (skip-chars-backward "^<\n\r\t")
3988 (if (> (point) 1) (backward-char 1))
3989 (and (looking-at tsr)
3990 (> (- (match-end 0) pos) -1))))))
3991 (and (boundp 'org-ts-what)
3992 (setq org-ts-what
3993 (cond
3994 ((org-pos-in-match-range pos 2) 'year)
3995 ((org-pos-in-match-range pos 3) 'month)
3996 ((org-pos-in-match-range pos 7) 'hour)
3997 ((org-pos-in-match-range pos 8) 'minute)
3998 ((or (org-pos-in-match-range pos 4)
3999 (org-pos-in-match-range pos 5)) 'day)
4000 (t 'day))))
4001 ans))
4002
4003 (defun org-timestamp-change (n &optional what)
4004 "Change the date in the time stamp at point.
4005 The date will be changed by N times WHAT. WHAT can be `day', `month',
4006 `year', `minute', `second'. If WHAT is not given, the cursor position
4007 in the timestamp determines what will be changed."
4008 (let ((fmt (car org-time-stamp-formats))
4009 org-ts-what
4010 (pos (point))
4011 ts time time0)
4012 (if (not (org-at-timestamp-p))
4013 (error "Not at a timestamp"))
4014 (setq org-ts-what (or what org-ts-what))
4015 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4016 (- (match-end 0) (match-beginning 0))))
4017 1)
4018 (cdr org-time-stamp-formats)
4019 (car org-time-stamp-formats)))
4020 (setq ts (match-string 0))
4021 (replace-match "")
4022 (setq time0 (org-parse-time-string ts))
4023 (setq time
4024 (apply 'encode-time
4025 (append
4026 (list (or (car time0) 0))
4027 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4028 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4029 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4030 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4031 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4032 (nthcdr 6 time0))))
4033 (if (eq what 'calendar)
4034 (let ((cal-date
4035 (save-excursion
4036 (save-match-data
4037 (set-buffer "*Calendar*")
4038 (calendar-cursor-to-date)))))
4039 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4040 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4041 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4042 (setcar time0 (or (car time0) 0))
4043 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4044 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4045 (setq time (apply 'encode-time time0))))
4046 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4047 (goto-char pos)
4048 ;; Try to recenter the calendar window, if any
4049 (if (and org-calendar-follow-timestamp-change
4050 (get-buffer-window "*Calendar*" t)
4051 (memq org-ts-what '(day month year)))
4052 (org-recenter-calendar (time-to-days time)))))
4053
4054 (defun org-recenter-calendar (date)
4055 "If the calendar is visible, recenter it to DATE."
4056 (let* ((win (selected-window))
4057 (cwin (get-buffer-window "*Calendar*" t))
4058 (calendar-move-hook nil))
4059 (when cwin
4060 (select-window cwin)
4061 (calendar-goto-date (if (listp date) date
4062 (calendar-gregorian-from-absolute date)))
4063 (select-window win))))
4064
4065 (defun org-goto-calendar (&optional arg)
4066 "Go to the Emacs calendar at the current date.
4067 If there is a time stamp in the current line, go to that date.
4068 A prefix ARG can be used force the current date."
4069 (interactive "P")
4070 (let ((tsr org-ts-regexp) diff
4071 (calendar-move-hook nil)
4072 (view-diary-entries-initially nil))
4073 (if (or (org-at-timestamp-p)
4074 (save-excursion
4075 (beginning-of-line 1)
4076 (looking-at (concat ".*" tsr))))
4077 (let ((d1 (time-to-days (current-time)))
4078 (d2 (time-to-days
4079 (org-time-string-to-time (match-string 1)))))
4080 (setq diff (- d2 d1))))
4081 (calendar)
4082 (calendar-goto-today)
4083 (if (and diff (not arg)) (calendar-forward-day diff))))
4084
4085 (defun org-date-from-calendar ()
4086 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4087 If there is already a time stamp at the cursor position, update it."
4088 (interactive)
4089 (org-timestamp-change 0 'calendar))
4090
4091 ;;; Agenda, and Diary Integration
4092
4093 ;;; Define the mode
4094
4095 (defvar org-agenda-mode-map (make-sparse-keymap)
4096 "Keymap for `org-agenda-mode'.")
4097
4098 (defvar org-agenda-menu)
4099 (defvar org-agenda-follow-mode nil)
4100 (defvar org-agenda-show-log nil)
4101 (defvar org-agenda-buffer-name "*Org Agenda*")
4102 (defvar org-agenda-redo-command nil)
4103 (defvar org-agenda-mode-hook nil)
4104 (defvar org-agenda-type nil)
4105 (defvar org-agenda-force-single-file nil)
4106
4107 ;;;###autoload
4108 (defun org-agenda-mode ()
4109 "Mode for time-sorted view on action items in Org-mode files.
4110
4111 The following commands are available:
4112
4113 \\{org-agenda-mode-map}"
4114 (interactive)
4115 (kill-all-local-variables)
4116 (setq major-mode 'org-agenda-mode)
4117 (setq mode-name "Org-Agenda")
4118 (use-local-map org-agenda-mode-map)
4119 (easy-menu-add org-agenda-menu)
4120 (if org-startup-truncated (setq truncate-lines t))
4121 (make-local-hook 'post-command-hook) ; Needed for XEmacs
4122 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4123 (make-local-hook 'pre-command-hook) ; Needed for XEmacs
4124 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4125 (unless org-agenda-keep-modes
4126 (setq org-agenda-follow-mode nil
4127 org-agenda-show-log nil))
4128 (easy-menu-change
4129 '("Agenda") "Agenda Files"
4130 (append
4131 (list
4132 (vector
4133 (if (get 'org-agenda-files 'org-restrict)
4134 "Restricted to single file"
4135 "Edit File List")
4136 '(customize-variable 'org-agenda-files)
4137 (not (get 'org-agenda-files 'org-restrict)))
4138 "--")
4139 (mapcar 'org-file-menu-entry (org-agenda-files))))
4140 (org-agenda-set-mode-name)
4141 (apply
4142 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4143 (list 'org-agenda-mode-hook)))
4144
4145 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4146 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4147 (define-key org-agenda-mode-map " " 'org-agenda-show)
4148 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4149 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4150 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4151 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4152 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4153 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4154 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4155 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4156 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4157 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4158 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4159 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4160
4161 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4162 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4163 (while l (define-key org-agenda-mode-map
4164 (int-to-string (pop l)) 'digit-argument)))
4165
4166 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4167 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4168 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4169 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4170 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4171 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4172 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4173 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4174 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4175 (define-key org-agenda-mode-map "n" 'next-line)
4176 (define-key org-agenda-mode-map "p" 'previous-line)
4177 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4178 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4179 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4180 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4181 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4182 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4183 (eval-after-load "calendar"
4184 '(define-key calendar-mode-map org-calendar-to-agenda-key
4185 'org-calendar-goto-agenda))
4186 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4187 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4188 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4189 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4190 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4191 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4192 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4193 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4194 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4195 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4196 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4197 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4198 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4199 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4200 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4201 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4202 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4203 "Local keymap for agenda entries from Org-mode.")
4204
4205 (define-key org-agenda-keymap
4206 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4207 (define-key org-agenda-keymap
4208 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4209
4210 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4211 '("Agenda"
4212 ("Agenda Files")
4213 "--"
4214 ["Show" org-agenda-show t]
4215 ["Go To (other window)" org-agenda-goto t]
4216 ["Go To (one window)" org-agenda-switch-to t]
4217 ["Follow Mode" org-agenda-follow-mode
4218 :style toggle :selected org-agenda-follow-mode :active t]
4219 "--"
4220 ["Cycle TODO" org-agenda-todo t]
4221 ("Tags"
4222 ["Show all Tags" org-agenda-show-tags t]
4223 ["Set Tags" org-agenda-set-tags t])
4224 ("Reschedule"
4225 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4226 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4227 "--"
4228 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4229 ("Priority"
4230 ["Set Priority" org-agenda-priority t]
4231 ["Increase Priority" org-agenda-priority-up t]
4232 ["Decrease Priority" org-agenda-priority-down t]
4233 ["Show Priority" org-agenda-show-priority t])
4234 "--"
4235 ;; ["New agenda command" org-agenda t]
4236 ["Rebuild buffer" org-agenda-redo t]
4237 "--"
4238 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4239 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4240 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4241 "--"
4242 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4243 :style radio :selected (equal org-agenda-ndays 1)]
4244 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4245 :style radio :selected (equal org-agenda-ndays 7)]
4246 "--"
4247 ["Show Logbook entries" org-agenda-log-mode
4248 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4249 ["Include Diary" org-agenda-toggle-diary
4250 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4251 ["Use Time Grid" org-agenda-toggle-time-grid
4252 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4253 "--"
4254 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4255 ("Calendar Commands"
4256 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4257 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4258 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4259 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4260 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4261 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4262 "--"
4263 ["Quit" org-agenda-quit t]
4264 ["Exit and Release Buffers" org-agenda-exit t]
4265 ))
4266
4267 ;;;###autoload
4268 (defun org-agenda (arg)
4269 "Dispatch agenda commands to collect entries to the agenda buffer.
4270 Prompts for a character to select a command. Any prefix arg will be passed
4271 on to the selected command. The default selections are:
4272
4273 a Call `org-agenda' to display the agenda for the current day or week.
4274 t Call `org-todo-list' to display the global todo list.
4275 T Call `org-todo-list' to display the global todo list, select only
4276 entries with a specific TODO keyword (the user get a prompt).
4277 m Call `org-tags-view' to display headlines with tags matching
4278 a condition (the user is prompted for the condition).
4279 M like `m', but select only TODO entries, no ordinary headlines.
4280
4281 More commands can be added by configuring the variable
4282 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4283 searches can be pre-defined in this way.
4284
4285 If the current buffer is in Org-mode and visiting a file, you can also
4286 first press `1' to indicate that the agenda should be temporarily (until the
4287 next use of \\[org-agenda]) restricted to the current file."
4288 (interactive "P")
4289 (catch 'exit
4290 (let ((restrict-ok (and (buffer-file-name) (eq major-mode 'org-mode)))
4291 (custom org-agenda-custom-commands)
4292 c entry key type string)
4293 (put 'org-agenda-files 'org-restrict nil)
4294 (save-window-excursion
4295 (delete-other-windows)
4296 (switch-to-buffer-other-window " *Agenda Commands*")
4297 (erase-buffer)
4298 (insert
4299 "Press key for an agenda command:
4300 --------------------------------
4301 a Agenda for current week or day
4302 t List of all TODO entries T Entries with special TODO kwd
4303 m Match a TAGS query M Like m, but only TODO entries.
4304 C Configure your own agenda commands")
4305 (while (setq entry (pop custom))
4306 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4307 (insert (format "\n%-4s%-14s: %s"
4308 key
4309 (cond
4310 ((eq type 'tags) "Tags query")
4311 ((eq type 'todo) "TODO keyword")
4312 ((eq type 'tags-tree) "Tags tree")
4313 ((eq type 'todo-tree) "TODO kwd tree")
4314 ((eq type 'occur-tree) "Occur tree")
4315 (t "???"))
4316 (org-string-props string 'face 'org-link))))
4317 (goto-char (point-min))
4318 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4319 (message "Press key for agenda command%s"
4320 (if restrict-ok ", or [1] to restrict to current file" ""))
4321 (setq c (read-char-exclusive))
4322 (message "")
4323 (when (equal c ?1)
4324 (if restrict-ok
4325 (put 'org-agenda-files 'org-restrict (list (buffer-file-name)))
4326 (error "Cannot restrict agenda to current buffer"))
4327 (message "Press key for agenda command%s"
4328 (if restrict-ok " (restricted to current file)" ""))
4329 (setq c (read-char-exclusive))
4330 (message "")))
4331 (require 'calendar) ; FIXME: can we avoid this for some commands?
4332 ;; For example the todo list should not need it (but does...)
4333 (cond
4334 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4335 ((equal c ?a) (call-interactively 'org-agenda-list))
4336 ((equal c ?t) (call-interactively 'org-todo-list))
4337 ((equal c ?T)
4338 (setq current-prefix-arg (or arg '(4)))
4339 (call-interactively 'org-todo-list))
4340 ((equal c ?m) (call-interactively 'org-tags-view))
4341 ((equal c ?M)
4342 (setq current-prefix-arg (or arg '(4)))
4343 (call-interactively 'org-tags-view))
4344 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4345 (setq type (nth 1 entry) string (nth 2 entry))
4346 (cond
4347 ((eq type 'tags)
4348 (org-tags-view current-prefix-arg string))
4349 ((eq type 'todo)
4350 (org-todo-list string))
4351 ((eq type 'tags-tree)
4352 (org-check-for-org-mode)
4353 (org-tags-sparse-tree current-prefix-arg string))
4354 ((eq type 'todo-tree)
4355 (org-check-for-org-mode)
4356 (org-occur (concat "^" outline-regexp "[ \t]*"
4357 (regexp-quote string) "\\>")))
4358 ((eq type 'occur-tree)
4359 (org-check-for-org-mode)
4360 (org-occur string))
4361 (t (error "Invalid custom agenda command type %s" type))))
4362 (t (error "Invalid key"))))))
4363
4364 (defun org-check-for-org-mode ()
4365 "Make sure current buffer is in org-mode. Error if not."
4366 (or (eq major-mode 'org-mode)
4367 (error "Cannot execute org-mode agenda command on buffer in %s."
4368 major-mode)))
4369
4370 (defun org-fit-agenda-window ()
4371 "Fit the window to the buffer size."
4372 (and org-fit-agenda-window
4373 (fboundp 'fit-window-to-buffer)
4374 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4375 (/ (frame-height) 2))))
4376
4377 (defun org-agenda-files ()
4378 "Get the list of agenda files."
4379 (or (get 'org-agenda-files 'org-restrict)
4380 org-agenda-files))
4381
4382 (defvar org-agenda-markers nil
4383 "List of all currently active markers created by `org-agenda'.")
4384 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4385 "Creation time of the last agenda marker.")
4386
4387 (defun org-agenda-new-marker (&optional pos)
4388 "Return a new agenda marker.
4389 Org-mode keeps a list of these markers and resets them when they are
4390 no longer in use."
4391 (let ((m (copy-marker (or pos (point)))))
4392 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4393 (push m org-agenda-markers)
4394 m))
4395
4396 (defun org-agenda-maybe-reset-markers (&optional force)
4397 "Reset markers created by `org-agenda'. But only if they are old enough."
4398 (if (or force
4399 (> (- (time-to-seconds (current-time))
4400 org-agenda-last-marker-time)
4401 5))
4402 (while org-agenda-markers
4403 (move-marker (pop org-agenda-markers) nil))))
4404
4405 (defvar org-agenda-new-buffers nil
4406 "Buffers created to visit agenda files.")
4407
4408 (defun org-get-agenda-file-buffer (file)
4409 "Get a buffer visiting FILE. If the buffer needs to be created, add
4410 it to the list of buffers which might be released later."
4411 (let ((buf (find-buffer-visiting file)))
4412 (if buf
4413 buf ; just return it
4414 ;; Make a new buffer and remember it
4415 (setq buf (find-file-noselect file))
4416 (if buf (push buf org-agenda-new-buffers))
4417 buf)))
4418
4419 (defun org-release-buffers (blist)
4420 "Release all buffers in list, asking the user for confirmation when needed.
4421 When a buffer is unmodified, it is just killed. When modified, it is saved
4422 \(if the user agrees) and then killed."
4423 (let (buf file)
4424 (while (setq buf (pop blist))
4425 (setq file (buffer-file-name buf))
4426 (when (and (buffer-modified-p buf)
4427 file
4428 (y-or-n-p (format "Save file %s? " file)))
4429 (with-current-buffer buf (save-buffer)))
4430 (kill-buffer buf))))
4431
4432 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4433
4434 (defun org-timeline (&optional include-all keep-modes)
4435 "Show a time-sorted view of the entries in the current org file.
4436 Only entries with a time stamp of today or later will be listed. With
4437 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4438 under the current date.
4439 If the buffer contains an active region, only check the region for
4440 dates."
4441 (interactive "P")
4442 (require 'calendar)
4443 (org-agenda-maybe-reset-markers 'force)
4444 (org-compile-prefix-format org-timeline-prefix-format)
4445 (let* ((dopast t)
4446 (dotodo include-all)
4447 (doclosed org-agenda-show-log)
4448 (org-agenda-keep-modes keep-modes)
4449 (entry (buffer-file-name))
4450 (org-agenda-files (list (buffer-file-name)))
4451 (date (calendar-current-date))
4452 (win (selected-window))
4453 (pos1 (point))
4454 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4455 (end (if (org-region-active-p) (region-end) (point-max)))
4456 (day-numbers (org-get-all-dates beg end 'no-ranges
4457 t doclosed)) ; always include today
4458 (today (time-to-days (current-time)))
4459 (org-respect-restriction t)
4460 (past t)
4461 args
4462 s e rtn d)
4463 (setq org-agenda-redo-command
4464 (list 'progn
4465 (list 'switch-to-buffer-other-window (current-buffer))
4466 (list 'org-timeline (list 'quote include-all) t)))
4467 (if (not dopast)
4468 ;; Remove past dates from the list of dates.
4469 (setq day-numbers (delq nil (mapcar (lambda(x)
4470 (if (>= x today) x nil))
4471 day-numbers))))
4472 (switch-to-buffer-other-window
4473 (get-buffer-create org-agenda-buffer-name))
4474 (setq buffer-read-only nil)
4475 (erase-buffer)
4476 (org-agenda-mode) (setq buffer-read-only nil)
4477 (set (make-local-variable 'org-agenda-type) 'timeline)
4478 (if doclosed (push :closed args))
4479 (push :timestamp args)
4480 (if dotodo (push :todo args))
4481 (while (setq d (pop day-numbers))
4482 (if (and (>= d today)
4483 dopast
4484 past)
4485 (progn
4486 (setq past nil)
4487 (insert (make-string 79 ?-) "\n")))
4488 (setq date (calendar-gregorian-from-absolute d))
4489 (setq s (point))
4490 (setq rtn (apply 'org-agenda-get-day-entries
4491 entry date args))
4492 (if (or rtn (equal d today))
4493 (progn
4494 (insert (calendar-day-name date) " "
4495 (number-to-string (extract-calendar-day date)) " "
4496 (calendar-month-name (extract-calendar-month date)) " "
4497 (number-to-string (extract-calendar-year date)) "\n")
4498 (put-text-property s (1- (point)) 'face
4499 'org-link)
4500 (if (equal d today)
4501 (put-text-property s (1- (point)) 'org-today t))
4502 (insert (org-finalize-agenda-entries rtn) "\n")
4503 (put-text-property s (1- (point)) 'day d))))
4504 (goto-char (point-min))
4505 (setq buffer-read-only t)
4506 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4507 (point-min)))
4508 (when (not org-select-timeline-window)
4509 (select-window win)
4510 (goto-char pos1))))
4511
4512 ;;;###autoload
4513 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4514 "Produce a weekly view from all files in variable `org-agenda-files'.
4515 The view will be for the current week, but from the overview buffer you
4516 will be able to go to other weeks.
4517 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4518 also be shown, under the current date.
4519 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4520 on the days are also shown. See the variable `org-log-done' for how
4521 to turn on logging.
4522 START-DAY defaults to TODAY, or to the most recent match for the weekday
4523 given in `org-agenda-start-on-weekday'.
4524 NDAYS defaults to `org-agenda-ndays'."
4525 (interactive "P")
4526 (org-agenda-maybe-reset-markers 'force)
4527 (org-compile-prefix-format org-agenda-prefix-format)
4528 (require 'calendar)
4529 (let* ((org-agenda-start-on-weekday
4530 (if (or (equal ndays 1)
4531 (and (null ndays) (equal 1 org-agenda-ndays)))
4532 nil org-agenda-start-on-weekday))
4533 (org-agenda-keep-modes keep-modes)
4534 (files (copy-sequence (org-agenda-files)))
4535 (win (selected-window))
4536 (today (time-to-days (current-time)))
4537 (sd (or start-day today))
4538 (start (if (or (null org-agenda-start-on-weekday)
4539 (< org-agenda-ndays 7))
4540 sd
4541 (let* ((nt (calendar-day-of-week
4542 (calendar-gregorian-from-absolute sd)))
4543 (n1 org-agenda-start-on-weekday)
4544 (d (- nt n1)))
4545 (- sd (+ (if (< d 0) 7 0) d)))))
4546 (day-numbers (list start))
4547 (inhibit-redisplay t)
4548 s e rtn rtnall file date d start-pos end-pos todayp nd)
4549 (setq org-agenda-redo-command
4550 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4551 ;; Make the list of days
4552 (setq ndays (or ndays org-agenda-ndays)
4553 nd ndays)
4554 (while (> ndays 1)
4555 (push (1+ (car day-numbers)) day-numbers)
4556 (setq ndays (1- ndays)))
4557 (setq day-numbers (nreverse day-numbers))
4558 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4559 (progn
4560 (delete-other-windows)
4561 (switch-to-buffer-other-window
4562 (get-buffer-create org-agenda-buffer-name))))
4563 (setq buffer-read-only nil)
4564 (erase-buffer)
4565 (org-agenda-mode) (setq buffer-read-only nil)
4566 (set (make-local-variable 'org-agenda-type) 'agenda)
4567 (set (make-local-variable 'starting-day) (car day-numbers))
4568 (set (make-local-variable 'include-all-loc) include-all)
4569 (when (and (or include-all org-agenda-include-all-todo)
4570 (member today day-numbers))
4571 (setq files (org-agenda-files)
4572 rtnall nil)
4573 (while (setq file (pop files))
4574 (catch 'nextfile
4575 (org-check-agenda-file file)
4576 (setq date (calendar-gregorian-from-absolute today)
4577 rtn (org-agenda-get-day-entries
4578 file date :todo))
4579 (setq rtnall (append rtnall rtn))))
4580 (when rtnall
4581 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4582 (add-text-properties (point-min) (1- (point))
4583 (list 'face 'org-link))
4584 (insert (org-finalize-agenda-entries rtnall) "\n")))
4585 (while (setq d (pop day-numbers))
4586 (setq date (calendar-gregorian-from-absolute d)
4587 s (point))
4588 (if (or (setq todayp (= d today))
4589 (and (not start-pos) (= d sd)))
4590 (setq start-pos (point))
4591 (if (and start-pos (not end-pos))
4592 (setq end-pos (point))))
4593 (setq files (org-agenda-files)
4594 rtnall nil)
4595 (while (setq file (pop files))
4596 (catch 'nextfile
4597 (org-check-agenda-file file)
4598 (if org-agenda-show-log
4599 (setq rtn (org-agenda-get-day-entries
4600 file date
4601 :deadline :scheduled :timestamp :closed))
4602 (setq rtn (org-agenda-get-day-entries
4603 file date
4604 :deadline :scheduled :timestamp)))
4605 (setq rtnall (append rtnall rtn))))
4606 (if org-agenda-include-diary
4607 (progn
4608 (require 'diary-lib)
4609 (setq rtn (org-get-entries-from-diary date))
4610 (setq rtnall (append rtnall rtn))))
4611 (if (or rtnall org-agenda-show-all-dates)
4612 (progn
4613 (insert (format "%-9s %2d %s %4d\n"
4614 (calendar-day-name date)
4615 (extract-calendar-day date)
4616 (calendar-month-name (extract-calendar-month date))
4617 (extract-calendar-year date)))
4618 (put-text-property s (1- (point)) 'face
4619 'org-link)
4620 (if rtnall (insert
4621 (org-finalize-agenda-entries
4622 (org-agenda-add-time-grid-maybe
4623 rtnall nd todayp))
4624 "\n"))
4625 (put-text-property s (1- (point)) 'day d))))
4626 (goto-char (point-min))
4627 (setq buffer-read-only t)
4628 (org-fit-agenda-window)
4629 (unless (and (pos-visible-in-window-p (point-min))
4630 (pos-visible-in-window-p (point-max)))
4631 (goto-char (1- (point-max)))
4632 (recenter -1)
4633 (if (not (pos-visible-in-window-p (or start-pos 1)))
4634 (progn
4635 (goto-char (or start-pos 1))
4636 (recenter 1))))
4637 (goto-char (or start-pos 1))
4638 (if (not org-select-agenda-window) (select-window win))
4639 (message "")))
4640
4641 (defvar org-select-this-todo-keyword nil)
4642
4643 ;;;###autoload
4644 (defun org-todo-list (arg &optional keep-modes)
4645 "Show all TODO entries from all agenda file in a single list.
4646 The prefix arg can be used to select a specific TODO keyword and limit
4647 the list to these. When using \\[universal-argument], you will be prompted
4648 for a keyword. A numeric prefix directly selects the Nth keyword in
4649 `org-todo-keywords'."
4650 (interactive "P")
4651 (org-agenda-maybe-reset-markers 'force)
4652 (org-compile-prefix-format org-agenda-prefix-format)
4653 (let* ((org-agenda-keep-modes keep-modes)
4654 (today (time-to-days (current-time)))
4655 (date (calendar-gregorian-from-absolute today))
4656 (win (selected-window))
4657 (kwds org-todo-keywords)
4658 (completion-ignore-case t)
4659 (org-select-this-todo-keyword
4660 (if (stringp arg) arg
4661 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4662 rtn rtnall files file pos)
4663 (when (equal arg '(4))
4664 (setq org-select-this-todo-keyword
4665 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4666 nil t)))
4667 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4668 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4669 (progn
4670 (delete-other-windows)
4671 (switch-to-buffer-other-window
4672 (get-buffer-create org-agenda-buffer-name))))
4673 (setq buffer-read-only nil)
4674 (erase-buffer)
4675 (org-agenda-mode) (setq buffer-read-only nil)
4676 (set (make-local-variable 'org-agenda-type) 'todo)
4677 (set (make-local-variable 'last-arg) arg)
4678 (set (make-local-variable 'org-todo-keywords) kwds)
4679 (set (make-local-variable 'org-agenda-redo-command)
4680 '(org-todo-list (or current-prefix-arg last-arg) t))
4681 (setq files (org-agenda-files)
4682 rtnall nil)
4683 (while (setq file (pop files))
4684 (catch 'nextfile
4685 (org-check-agenda-file file)
4686 (setq rtn (org-agenda-get-day-entries file date :todo))
4687 (setq rtnall (append rtnall rtn))))
4688 (insert "Global list of TODO items of type: ")
4689 (add-text-properties (point-min) (1- (point))
4690 (list 'face 'org-link))
4691 (setq pos (point))
4692 (insert (or org-select-this-todo-keyword "ALL") "\n")
4693 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4694 (setq pos (point))
4695 (insert
4696 "Available with `N r': (0)ALL "
4697 (let ((n 0))
4698 (mapconcat (lambda (x)
4699 (format "(%d)%s" (setq n (1+ n)) x))
4700 org-todo-keywords " "))
4701 "\n")
4702 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4703 (when rtnall
4704 (insert (org-finalize-agenda-entries rtnall) "\n"))
4705 (goto-char (point-min))
4706 (setq buffer-read-only t)
4707 (org-fit-agenda-window)
4708 (if (not org-select-agenda-window) (select-window win))))
4709
4710 (defun org-check-agenda-file (file)
4711 "Make sure FILE exists. If not, ask user what to do."
4712 ;; FIXME: this does not correctly change the menus
4713 ;; Could probably be fixed by explicitly going to the buffer where
4714 ;; the call originated.
4715 (when (not (file-exists-p file))
4716 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4717 file)
4718 (let ((r (downcase (read-char-exclusive))))
4719 (cond
4720 ((equal r ?r)
4721 (org-remove-file file)
4722 (throw 'nextfile t))
4723 (t (error "Abort"))))))
4724
4725 (defun org-agenda-check-type (error &rest types)
4726 "Check if agenda buffer is of allowed type.
4727 If ERROR is non-nil, throw an error, otherwise just return nil."
4728 (if (memq org-agenda-type types)
4729 t
4730 (if error
4731 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
4732 nil)))
4733
4734 (defun org-agenda-quit ()
4735 "Exit agenda by removing the window or the buffer."
4736 (interactive)
4737 (let ((buf (current-buffer)))
4738 (if (not (one-window-p)) (delete-window))
4739 (kill-buffer buf)
4740 (org-agenda-maybe-reset-markers 'force)))
4741
4742 (defun org-agenda-exit ()
4743 "Exit agenda by removing the window or the buffer.
4744 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4745 Org-mode buffers visited directly by the user will not be touched."
4746 (interactive)
4747 (org-release-buffers org-agenda-new-buffers)
4748 (setq org-agenda-new-buffers nil)
4749 (org-agenda-quit))
4750
4751 (defun org-agenda-redo ()
4752 "Rebuild Agenda.
4753 When this is the global TODO list, a prefix argument will be interpreted."
4754 (interactive)
4755 (message "Rebuilding agenda buffer...")
4756 (eval org-agenda-redo-command)
4757 (message "Rebuilding agenda buffer...done"))
4758
4759 (defun org-agenda-goto-today ()
4760 "Go to today."
4761 (interactive)
4762 (org-agenda-check-type t 'timeline 'agenda)
4763 (if (boundp 'starting-day)
4764 (let ((cmd (car org-agenda-redo-command))
4765 (iall (nth 1 org-agenda-redo-command))
4766 (nday (nth 3 org-agenda-redo-command))
4767 (keep (nth 4 org-agenda-redo-command)))
4768 (eval (list cmd iall nil nday keep)))
4769 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4770 (point-min)))))
4771
4772 (defun org-agenda-later (arg)
4773 "Go forward in time by `org-agenda-ndays' days.
4774 With prefix ARG, go forward that many times `org-agenda-ndays'."
4775 (interactive "p")
4776 (org-agenda-check-type t 'agenda)
4777 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4778 (+ starting-day (* arg org-agenda-ndays)) nil t))
4779
4780 (defun org-agenda-earlier (arg)
4781 "Go back in time by `org-agenda-ndays' days.
4782 With prefix ARG, go back that many times `org-agenda-ndays'."
4783 (interactive "p")
4784 (org-agenda-check-type t 'agenda)
4785 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4786 (- starting-day (* arg org-agenda-ndays)) nil t))
4787
4788 (defun org-agenda-week-view ()
4789 "Switch to weekly view for agenda."
4790 (interactive)
4791 (org-agenda-check-type t 'agenda)
4792 (setq org-agenda-ndays 7)
4793 (org-agenda-list include-all-loc
4794 (or (get-text-property (point) 'day)
4795 starting-day)
4796 nil t)
4797 (org-agenda-set-mode-name)
4798 (message "Switched to week view"))
4799
4800 (defun org-agenda-day-view ()
4801 "Switch to weekly view for agenda."
4802 (interactive)
4803 (org-agenda-check-type t 'agenda)
4804 (setq org-agenda-ndays 1)
4805 (org-agenda-list include-all-loc
4806 (or (get-text-property (point) 'day)
4807 starting-day)
4808 nil t)
4809 (org-agenda-set-mode-name)
4810 (message "Switched to day view"))
4811
4812 (defun org-agenda-next-date-line (&optional arg)
4813 "Jump to the next line indicating a date in agenda buffer."
4814 (interactive "p")
4815 (org-agenda-check-type t 'agenda 'timeline)
4816 (beginning-of-line 1)
4817 (if (looking-at "^\\S-") (forward-char 1))
4818 (if (not (re-search-forward "^\\S-" nil t arg))
4819 (progn
4820 (backward-char 1)
4821 (error "No next date after this line in this buffer")))
4822 (goto-char (match-beginning 0)))
4823
4824 (defun org-agenda-previous-date-line (&optional arg)
4825 "Jump to the next line indicating a date in agenda buffer."
4826 (interactive "p")
4827 (org-agenda-check-type t 'agenda 'timeline)
4828 (beginning-of-line 1)
4829 (if (not (re-search-backward "^\\S-" nil t arg))
4830 (error "No previous date before this line in this buffer")))
4831
4832 ;; Initialize the highlight
4833 (defvar org-hl (org-make-overlay 1 1))
4834 (org-overlay-put org-hl 'face 'highlight)
4835
4836 (defun org-highlight (begin end &optional buffer)
4837 "Highlight a region with overlay."
4838 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4839 org-hl begin end (or buffer (current-buffer))))
4840
4841 (defun org-unhighlight ()
4842 "Detach overlay INDEX."
4843 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4844
4845
4846 (defun org-agenda-follow-mode ()
4847 "Toggle follow mode in an agenda buffer."
4848 (interactive)
4849 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4850 (org-agenda-set-mode-name)
4851 (message "Follow mode is %s"
4852 (if org-agenda-follow-mode "on" "off")))
4853
4854 (defun org-agenda-log-mode ()
4855 "Toggle follow mode in an agenda buffer."
4856 (interactive)
4857 (org-agenda-check-type t 'agenda 'timeline)
4858 (setq org-agenda-show-log (not org-agenda-show-log))
4859 (org-agenda-set-mode-name)
4860 (org-agenda-redo)
4861 (message "Log mode is %s"
4862 (if org-agenda-show-log "on" "off")))
4863
4864 (defun org-agenda-toggle-diary ()
4865 "Toggle follow mode in an agenda buffer."
4866 (interactive)
4867 (org-agenda-check-type t 'agenda)
4868 (setq org-agenda-include-diary (not org-agenda-include-diary))
4869 (org-agenda-redo)
4870 (org-agenda-set-mode-name)
4871 (message "Diary inclusion turned %s"
4872 (if org-agenda-include-diary "on" "off")))
4873
4874 (defun org-agenda-toggle-time-grid ()
4875 "Toggle follow mode in an agenda buffer."
4876 (interactive)
4877 (org-agenda-check-type t 'agenda)
4878 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4879 (org-agenda-redo)
4880 (org-agenda-set-mode-name)
4881 (message "Time-grid turned %s"
4882 (if org-agenda-use-time-grid "on" "off")))
4883
4884 (defun org-agenda-set-mode-name ()
4885 "Set the mode name to indicate all the small mode settings."
4886 (setq mode-name
4887 (concat "Org-Agenda"
4888 (if (equal org-agenda-ndays 1) " Day" "")
4889 (if (equal org-agenda-ndays 7) " Week" "")
4890 (if org-agenda-follow-mode " Follow" "")
4891 (if org-agenda-include-diary " Diary" "")
4892 (if org-agenda-use-time-grid " Grid" "")
4893 (if org-agenda-show-log " Log" "")))
4894 (force-mode-line-update))
4895
4896 (defun org-agenda-post-command-hook ()
4897 (and (eolp) (not (bolp)) (backward-char 1))
4898 (if (and org-agenda-follow-mode
4899 (get-text-property (point) 'org-marker))
4900 (org-agenda-show)))
4901
4902 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4903
4904 (defun org-get-entries-from-diary (date)
4905 "Get the (Emacs Calendar) diary entries for DATE."
4906 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4907 (diary-display-hook '(fancy-diary-display))
4908 (list-diary-entries-hook
4909 (cons 'org-diary-default-entry list-diary-entries-hook))
4910 (diary-file-name-prefix-function nil) ; turn this feature off
4911 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4912 entries
4913 (org-disable-agenda-to-diary t))
4914 (save-excursion
4915 (save-window-excursion
4916 (list-diary-entries date 1)))
4917 (if (not (get-buffer fancy-diary-buffer))
4918 (setq entries nil)
4919 (with-current-buffer fancy-diary-buffer
4920 (setq buffer-read-only nil)
4921 (if (= (point-max) 1)
4922 ;; No entries
4923 (setq entries nil)
4924 ;; Omit the date and other unnecessary stuff
4925 (org-agenda-cleanup-fancy-diary)
4926 ;; Add prefix to each line and extend the text properties
4927 (if (= (point-max) 1)
4928 (setq entries nil)
4929 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4930 (set-buffer-modified-p nil)
4931 (kill-buffer fancy-diary-buffer)))
4932 (when entries
4933 (setq entries (org-split-string entries "\n"))
4934 (setq entries
4935 (mapcar
4936 (lambda (x)
4937 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
4938 ;; Extend the text properties to the beginning of the line
4939 (add-text-properties
4940 0 (length x)
4941 (text-properties-at (1- (length x)) x)
4942 x)
4943 x)
4944 entries)))))
4945
4946 (defun org-agenda-cleanup-fancy-diary ()
4947 "Remove unwanted stuff in buffer created by fancy-diary-display.
4948 This gets rid of the date, the underline under the date, and
4949 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4950 date. Itt also removes lines that contain only whitespace."
4951 (goto-char (point-min))
4952 (if (looking-at ".*?:[ \t]*")
4953 (progn
4954 (replace-match "")
4955 (re-search-forward "\n=+$" nil t)
4956 (replace-match "")
4957 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4958 (re-search-forward "\n=+$" nil t)
4959 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4960 (goto-char (point-min))
4961 (while (re-search-forward "^ +\n" nil t)
4962 (replace-match ""))
4963 (goto-char (point-min))
4964 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4965 (replace-match "")))
4966
4967 ;; Make sure entries from the diary have the right text properties.
4968 (eval-after-load "diary-lib"
4969 '(if (boundp 'diary-modify-entry-list-string-function)
4970 ;; We can rely on the hook, nothing to do
4971 nil
4972 ;; Hook not avaiable, must use advice to make this work
4973 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4974 "Make the position visible."
4975 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4976 (stringp string)
4977 (buffer-file-name))
4978 (setq string (org-modify-diary-entry-string string))))))
4979
4980 (defun org-modify-diary-entry-string (string)
4981 "Add text properties to string, allowing org-mode to act on it."
4982 (add-text-properties
4983 0 (length string)
4984 (list 'mouse-face 'highlight
4985 'keymap org-agenda-keymap
4986 'help-echo
4987 (format
4988 "mouse-2 or RET jump to diary file %s"
4989 (abbreviate-file-name (buffer-file-name)))
4990 'org-agenda-diary-link t
4991 'org-marker (org-agenda-new-marker (point-at-bol)))
4992 string)
4993 string)
4994
4995 (defun org-diary-default-entry ()
4996 "Add a dummy entry to the diary.
4997 Needed to avoid empty dates which mess up holiday display."
4998 ;; Catch the error if dealing with the new add-to-diary-alist
4999 (when org-disable-agenda-to-diary
5000 (condition-case nil
5001 (add-to-diary-list original-date "Org-mode dummy" "")
5002 (error
5003 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5004
5005 (defun org-cycle-agenda-files ()
5006 "Cycle through the files in `org-agenda-files'.
5007 If the current buffer visits an agenda file, find the next one in the list.
5008 If the current buffer does not, find the first agenda file."
5009 (interactive)
5010 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5011 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
5012 file)
5013 (unless files (error "No agenda files"))
5014 (catch 'exit
5015 (while (setq file (pop files))
5016 (if (equal (file-truename file) tcf)
5017 (when (car files)
5018 (find-file (car files))
5019 (throw 'exit t))))
5020 (find-file (car org-agenda-files)))))
5021
5022 (defun org-agenda-file-to-end (&optional file)
5023 "Move/add the current file to the end of the agenda fiole list.
5024 I the file is not present in the list, it is appended ot the list. If it is
5025 present, it is moved there."
5026 (interactive)
5027 (org-agenda-file-to-front 'to-end file))
5028
5029 (defun org-agenda-file-to-front (&optional to-end file)
5030 "Move/add the current file to the top of the agenda file list.
5031 If the file is not present in the list, it is added to the front. If it is
5032 present, it is moved there. With optional argument TO-END, add/move to the
5033 end of the list."
5034 (interactive "P")
5035 (let ((file-alist (mapcar (lambda (x)
5036 (cons (file-truename x) x))
5037 org-agenda-files))
5038 (ctf (file-truename (buffer-file-name)))
5039 x had)
5040 (setq x (assoc ctf file-alist) had x)
5041
5042 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
5043 (if to-end
5044 (setq file-alist (append (delq x file-alist) (list x)))
5045 (setq file-alist (cons x (delq x file-alist))))
5046 (setq org-agenda-files (mapcar 'cdr file-alist))
5047 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5048 (customize-save-variable 'org-agenda-files org-agenda-files))
5049 (org-install-agenda-files-menu)
5050 (message "File %s to %s of agenda file list"
5051 (if had "moved" "added") (if to-end "end" "front"))))
5052
5053 (defun org-remove-file (&optional file)
5054 "Remove current file from the list of files in variable `org-agenda-files'.
5055 These are the files which are being checked for agenda entries.
5056 Optional argument FILE means, use this file instead of the current."
5057 (interactive)
5058 (let* ((file (or file (buffer-file-name)))
5059 (true-file (file-truename file))
5060 (afile (abbreviate-file-name file))
5061 (files (delq nil (mapcar
5062 (lambda (x)
5063 (if (equal true-file
5064 (file-truename x))
5065 nil x))
5066 org-agenda-files))))
5067 (if (not (= (length files) (length org-agenda-files)))
5068 (progn
5069 (setq org-agenda-files files)
5070 (customize-save-variable 'org-agenda-files org-agenda-files)
5071 (org-install-agenda-files-menu)
5072 (message "Removed file: %s" afile))
5073 (message "File was not in list: %s" afile))))
5074
5075 (defun org-file-menu-entry (file)
5076 (vector file (list 'find-file file) t))
5077 ;; FIXME: Maybe we removed a buffer visited through the menu from
5078 ;; org-agenda-new-buffers, so that the buffer will not be removed
5079 ;; when exiting the agenda????
5080
5081 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5082 "Return a list of all relevant day numbers from BEG to END buffer positions.
5083 If NO-RANGES is non-nil, include only the start and end dates of a range,
5084 not every single day in the range. If FORCE-TODAY is non-nil, make
5085 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5086 inactive time stamps (those in square brackets) are included."
5087 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5088 dates date day day1 day2 ts1 ts2)
5089 (if force-today
5090 (setq dates (list (time-to-days (current-time)))))
5091 (save-excursion
5092 (goto-char beg)
5093 (while (re-search-forward re end t)
5094 (setq day (time-to-days (org-time-string-to-time
5095 (substring (match-string 1) 0 10))))
5096 (or (memq day dates) (push day dates)))
5097 (unless no-ranges
5098 (goto-char beg)
5099 (while (re-search-forward org-tr-regexp end t)
5100 (setq ts1 (substring (match-string 1) 0 10)
5101 ts2 (substring (match-string 2) 0 10)
5102 day1 (time-to-days (org-time-string-to-time ts1))
5103 day2 (time-to-days (org-time-string-to-time ts2)))
5104 (while (< (setq day1 (1+ day1)) day2)
5105 (or (memq day1 dates) (push day1 dates)))))
5106 (sort dates '<))))
5107
5108 ;;;###autoload
5109 (defun org-diary (&rest args)
5110 "Return diary information from org-files.
5111 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5112 It accesses org files and extracts information from those files to be
5113 listed in the diary. The function accepts arguments specifying what
5114 items should be listed. The following arguments are allowed:
5115
5116 :timestamp List the headlines of items containing a date stamp or
5117 date range matching the selected date. Deadlines will
5118 also be listed, on the expiration day.
5119
5120 :deadline List any deadlines past due, or due within
5121 `org-deadline-warning-days'. The listing occurs only
5122 in the diary for *today*, not at any other date. If
5123 an entry is marked DONE, it is no longer listed.
5124
5125 :scheduled List all items which are scheduled for the given date.
5126 The diary for *today* also contains items which were
5127 scheduled earlier and are not yet marked DONE.
5128
5129 :todo List all TODO items from the org-file. This may be a
5130 long list - so this is not turned on by default.
5131 Like deadlines, these entries only show up in the
5132 diary for *today*, not at any other date.
5133
5134 The call in the diary file should look like this:
5135
5136 &%%(org-diary) ~/path/to/some/orgfile.org
5137
5138 Use a separate line for each org file to check. Or, if you omit the file name,
5139 all files listed in `org-agenda-files' will be checked automatically:
5140
5141 &%%(org-diary)
5142
5143 If you don't give any arguments (as in the example above), the default
5144 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5145 also be written as
5146
5147 &%%(org-diary :deadline :timestamp :scheduled)
5148
5149 The function expects the lisp variables `entry' and `date' to be provided
5150 by the caller, because this is how the calendar works. Don't use this
5151 function from a program - use `org-agenda-get-day-entries' instead."
5152 (org-agenda-maybe-reset-markers)
5153 (org-compile-prefix-format org-agenda-prefix-format)
5154 (setq args (or args '(:deadline :scheduled :timestamp)))
5155 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5156 (list entry)
5157 org-agenda-files))
5158 file rtn results)
5159 ;; If this is called during org-agenda, don't return any entries to
5160 ;; the calendar. Org Agenda will list these entries itself.
5161 (if org-disable-agenda-to-diary (setq files nil))
5162 (while (setq file (pop files))
5163 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5164 (setq results (append results rtn)))
5165 (if results
5166 (concat (org-finalize-agenda-entries results) "\n"))))
5167 (defvar org-category-table nil)
5168 (defun org-get-category-table ()
5169 "Get the table of categories and positions in current buffer."
5170 (let (tbl)
5171 (save-excursion
5172 (goto-char (point-min))
5173 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5174 (push (cons (point) (org-trim (match-string 2))) tbl)))
5175 tbl))
5176 (defun org-get-category (&optional pos)
5177 "Get the category applying to position POS."
5178 (if (not org-category-table)
5179 (cond
5180 ((null org-category)
5181 (setq org-category
5182 (if (buffer-file-name)
5183 (file-name-sans-extension
5184 (file-name-nondirectory (buffer-file-name)))
5185 "???")))
5186 ((symbolp org-category) (symbol-name org-category))
5187 (t org-category))
5188 (let ((tbl org-category-table)
5189 (pos (or pos (point))))
5190 (while (and tbl (> (caar tbl) pos))
5191 (pop tbl))
5192 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5193 org-category-table))))))
5194
5195 (defun org-agenda-get-day-entries (file date &rest args)
5196 "Does the work for `org-diary' and `org-agenda'.
5197 FILE is the path to a file to be checked for entries. DATE is date like
5198 the one returned by `calendar-current-date'. ARGS are symbols indicating
5199 which kind of entries should be extracted. For details about these, see
5200 the documentation of `org-diary'."
5201 (setq args (or args '(:deadline :scheduled :timestamp)))
5202 (let* ((org-startup-with-deadline-check nil)
5203 (org-startup-folded nil)
5204 (buffer (if (file-exists-p file)
5205 (org-get-agenda-file-buffer file)
5206 (error "No such file %s" file)))
5207 arg results rtn)
5208 (if (not buffer)
5209 ;; If file does not exist, make sure an error message ends up in diary
5210 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5211 (with-current-buffer buffer
5212 (unless (eq major-mode 'org-mode)
5213 (error "Agenda file %s is not in `org-mode'" file))
5214 (setq org-category-table (org-get-category-table))
5215 (let ((case-fold-search nil))
5216 (save-excursion
5217 (save-restriction
5218 (if org-respect-restriction
5219 (if (org-region-active-p)
5220 ;; Respect a region to restrict search
5221 (narrow-to-region (region-beginning) (region-end)))
5222 ;; If we work for the calendar or many files,
5223 ;; get rid of any restriction
5224 (widen))
5225 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5226 (while (setq arg (pop args))
5227 (cond
5228 ((and (eq arg :todo)
5229 (equal date (calendar-current-date)))
5230 (setq rtn (org-agenda-get-todos))
5231 (setq results (append results rtn)))
5232 ((eq arg :timestamp)
5233 (setq rtn (org-agenda-get-blocks))
5234 (setq results (append results rtn))
5235 (setq rtn (org-agenda-get-timestamps))
5236 (setq results (append results rtn)))
5237 ((eq arg :scheduled)
5238 (setq rtn (org-agenda-get-scheduled))
5239 (setq results (append results rtn)))
5240 ((eq arg :closed)
5241 (setq rtn (org-agenda-get-closed))
5242 (setq results (append results rtn)))
5243 ((and (eq arg :deadline)
5244 (equal date (calendar-current-date)))
5245 (setq rtn (org-agenda-get-deadlines))
5246 (setq results (append results rtn))))))))
5247 results))))
5248
5249 (defun org-entry-is-done-p ()
5250 "Is the current entry marked DONE?"
5251 (save-excursion
5252 (and (re-search-backward "[\r\n]\\*" nil t)
5253 (looking-at org-nl-done-regexp))))
5254
5255 (defun org-at-date-range-p ()
5256 "Is the cursor inside a date range?"
5257 (interactive)
5258 (save-excursion
5259 (catch 'exit
5260 (let ((pos (point)))
5261 (skip-chars-backward "^<\r\n")
5262 (skip-chars-backward "<")
5263 (and (looking-at org-tr-regexp)
5264 (>= (match-end 0) pos)
5265 (throw 'exit t))
5266 (skip-chars-backward "^<\r\n")
5267 (skip-chars-backward "<")
5268 (and (looking-at org-tr-regexp)
5269 (>= (match-end 0) pos)
5270 (throw 'exit t)))
5271 nil)))
5272
5273 (defun org-agenda-get-todos ()
5274 "Return the TODO information for agenda display."
5275 (let* ((props (list 'face nil
5276 'done-face 'org-done
5277 'mouse-face 'highlight
5278 'keymap org-agenda-keymap
5279 'help-echo
5280 (format "mouse-2 or RET jump to org file %s"
5281 (abbreviate-file-name (buffer-file-name)))))
5282 (regexp (concat "[\n\r]\\*+ *\\("
5283 (if org-select-this-todo-keyword
5284 (concat "\\<\\(" org-select-this-todo-keyword
5285 "\\)\\>")
5286 org-not-done-regexp)
5287 "[^\n\r]*\\)"))
5288 marker priority category tags
5289 ee txt)
5290 (goto-char (point-min))
5291 (while (re-search-forward regexp nil t)
5292 (goto-char (match-beginning 1))
5293 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5294 category (org-get-category)
5295 tags (org-get-tags-at (point))
5296 txt (org-format-agenda-item "" (match-string 1) category tags)
5297 priority
5298 (+ (org-get-priority txt)
5299 (if org-todo-kwd-priority-p
5300 (- org-todo-kwd-max-priority -2
5301 (length
5302 (member (match-string 2) org-todo-keywords)))
5303 1)))
5304 (add-text-properties
5305 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5306 'priority priority 'category category)
5307 props)
5308 txt)
5309 (push txt ee)
5310 (goto-char (match-end 1)))
5311 (nreverse ee)))
5312
5313 (defconst org-agenda-no-heading-message
5314 "No heading for this item in buffer or region")
5315
5316 (defun org-agenda-get-timestamps ()
5317 "Return the date stamp information for agenda display."
5318 (let* ((props (list 'face nil
5319 'mouse-face 'highlight
5320 'keymap org-agenda-keymap
5321 'help-echo
5322 (format "mouse-2 or RET jump to org file %s"
5323 (abbreviate-file-name (buffer-file-name)))))
5324 (regexp (regexp-quote
5325 (substring
5326 (format-time-string
5327 (car org-time-stamp-formats)
5328 (apply 'encode-time ; DATE bound by calendar
5329 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5330 0 11)))
5331 marker hdmarker deadlinep scheduledp donep tmp priority category
5332 ee txt timestr tags)
5333 (goto-char (point-min))
5334 (while (re-search-forward regexp nil t)
5335 (if (not (save-match-data (org-at-date-range-p)))
5336 (progn
5337 (setq marker (org-agenda-new-marker (match-beginning 0))
5338 category (org-get-category (match-beginning 0))
5339 tmp (buffer-substring (max (point-min)
5340 (- (match-beginning 0)
5341 org-ds-keyword-length))
5342 (match-beginning 0))
5343 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5344 deadlinep (string-match org-deadline-regexp tmp)
5345 scheduledp (string-match org-scheduled-regexp tmp)
5346 donep (org-entry-is-done-p))
5347 (if (string-match ">" timestr)
5348 ;; substring should only run to end of time stamp
5349 (setq timestr (substring timestr 0 (match-end 0))))
5350 (save-excursion
5351 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5352 (progn
5353 (goto-char (match-end 1))
5354 (setq hdmarker (org-agenda-new-marker)
5355 tags (org-get-tags-at))
5356 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5357 (setq txt (org-format-agenda-item
5358 (format "%s%s"
5359 (if deadlinep "Deadline: " "")
5360 (if scheduledp "Scheduled: " ""))
5361 (match-string 1) category tags timestr)))
5362 (setq txt org-agenda-no-heading-message))
5363 (setq priority (org-get-priority txt))
5364 (add-text-properties
5365 0 (length txt) (append (list 'org-marker marker
5366 'org-hd-marker hdmarker) props)
5367 txt)
5368 (if deadlinep
5369 (add-text-properties
5370 0 (length txt)
5371 (list 'face
5372 (if donep 'org-done 'org-warning)
5373 'undone-face 'org-warning
5374 'done-face 'org-done
5375 'category category
5376 'priority (+ 100 priority))
5377 txt)
5378 (if scheduledp
5379 (add-text-properties
5380 0 (length txt)
5381 (list 'face 'org-scheduled-today
5382 'undone-face 'org-scheduled-today
5383 'done-face 'org-done
5384 'category category
5385 priority (+ 99 priority))
5386 txt)
5387 (add-text-properties
5388 0 (length txt)
5389 (list 'priority priority 'category category) txt)))
5390 (push txt ee))
5391 (outline-next-heading))))
5392 (nreverse ee)))
5393
5394 (defun org-agenda-get-closed ()
5395 "Return the loggedd TODO entries for agenda display."
5396 (let* ((props (list 'mouse-face 'highlight
5397 'keymap org-agenda-keymap
5398 'help-echo
5399 (format "mouse-2 or RET jump to org file %s"
5400 (abbreviate-file-name (buffer-file-name)))))
5401 (regexp (concat
5402 "\\<" org-closed-string " *\\["
5403 (regexp-quote
5404 (substring
5405 (format-time-string
5406 (car org-time-stamp-formats)
5407 (apply 'encode-time ; DATE bound by calendar
5408 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5409 1 11))))
5410 marker hdmarker priority category tags
5411 ee txt timestr)
5412 (goto-char (point-min))
5413 (while (re-search-forward regexp nil t)
5414 (if (not (save-match-data (org-at-date-range-p)))
5415 (progn
5416 (setq marker (org-agenda-new-marker (match-beginning 0))
5417 category (org-get-category (match-beginning 0))
5418 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5419 ;; donep (org-entry-is-done-p)
5420 )
5421 (if (string-match "\\]" timestr)
5422 ;; substring should only run to end of time stamp
5423 (setq timestr (substring timestr 0 (match-end 0))))
5424 (save-excursion
5425 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5426 (progn
5427 (goto-char (match-end 1))
5428 (setq hdmarker (org-agenda-new-marker)
5429 tags (org-get-tags-at))
5430 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5431 (setq txt (org-format-agenda-item
5432 "Closed: "
5433 (match-string 1) category tags timestr)))
5434 (setq txt org-agenda-no-heading-message))
5435 (setq priority 100000)
5436 (add-text-properties
5437 0 (length txt) (append (list 'org-marker marker
5438 'org-hd-marker hdmarker
5439 'face 'org-done
5440 'priority priority
5441 'category category
5442 'undone-face 'org-warning
5443 'done-face 'org-done) props)
5444 txt)
5445 (push txt ee))
5446 (outline-next-heading))))
5447 (nreverse ee)))
5448
5449 (defun org-agenda-get-deadlines ()
5450 "Return the deadline information for agenda display."
5451 (let* ((wdays org-deadline-warning-days)
5452 (props (list 'mouse-face 'highlight
5453 'keymap org-agenda-keymap
5454 'help-echo
5455 (format "mouse-2 or RET jump to org file %s"
5456 (abbreviate-file-name (buffer-file-name)))))
5457 (regexp org-deadline-time-regexp)
5458 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5459 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5460 d2 diff pos pos1 category tags
5461 ee txt head)
5462 (goto-char (point-min))
5463 (while (re-search-forward regexp nil t)
5464 (setq pos (1- (match-beginning 1))
5465 d2 (time-to-days
5466 (org-time-string-to-time (match-string 1)))
5467 diff (- d2 d1))
5468 ;; When to show a deadline in the calendar:
5469 ;; If the expiration is within wdays warning time.
5470 ;; Past-due deadlines are only shown on the current date
5471 (if (and (< diff wdays) todayp (not (= diff 0)))
5472 (save-excursion
5473 (setq category (org-get-category))
5474 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5475 (progn
5476 (goto-char (match-end 0))
5477 (setq pos1 (match-end 1))
5478 (setq tags (org-get-tags-at pos1))
5479 (setq head (buffer-substring-no-properties
5480 (point)
5481 (progn (skip-chars-forward "^\r\n")
5482 (point))))
5483 (if (string-match org-looking-at-done-regexp head)
5484 (setq txt nil)
5485 (setq txt (org-format-agenda-item
5486 (format "In %3d d.: " diff) head category tags))))
5487 (setq txt org-agenda-no-heading-message))
5488 (when txt
5489 (add-text-properties
5490 0 (length txt)
5491 (append
5492 (list 'org-marker (org-agenda-new-marker pos)
5493 'org-hd-marker (org-agenda-new-marker pos1)
5494 'priority (+ (- 10 diff) (org-get-priority txt))
5495 'category category
5496 'face (cond ((<= diff 0) 'org-warning)
5497 ((<= diff 5) 'org-scheduled-previously)
5498 (t nil))
5499 'undone-face (cond
5500 ((<= diff 0) 'org-warning)
5501 ((<= diff 5) 'org-scheduled-previously)
5502 (t nil))
5503 'done-face 'org-done)
5504 props)
5505 txt)
5506 (push txt ee)))))
5507 ee))
5508
5509 (defun org-agenda-get-scheduled ()
5510 "Return the scheduled information for agenda display."
5511 (let* ((props (list 'face 'org-scheduled-previously
5512 'undone-face 'org-scheduled-previously
5513 'done-face 'org-done
5514 'mouse-face 'highlight
5515 'keymap org-agenda-keymap
5516 'help-echo
5517 (format "mouse-2 or RET jump to org file %s"
5518 (abbreviate-file-name (buffer-file-name)))))
5519 (regexp org-scheduled-time-regexp)
5520 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5521 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5522 d2 diff pos pos1 category tags
5523 ee txt head)
5524 (goto-char (point-min))
5525 (while (re-search-forward regexp nil t)
5526 (setq pos (1- (match-beginning 1))
5527 d2 (time-to-days
5528 (org-time-string-to-time (match-string 1)))
5529 diff (- d2 d1))
5530 ;; When to show a scheduled item in the calendar:
5531 ;; If it is on or past the date.
5532 (if (and (< diff 0) todayp)
5533 (save-excursion
5534 (setq category (org-get-category))
5535 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5536 (progn
5537 (goto-char (match-end 0))
5538 (setq pos1 (match-end 1))
5539 (setq tags (org-get-tags-at))
5540 (setq head (buffer-substring-no-properties
5541 (point)
5542 (progn (skip-chars-forward "^\r\n") (point))))
5543 (if (string-match org-looking-at-done-regexp head)
5544 (setq txt nil)
5545 (setq txt (org-format-agenda-item
5546 (format "Sched.%2dx: " (- 1 diff)) head
5547 category tags))))
5548 (setq txt org-agenda-no-heading-message))
5549 (when txt
5550 (add-text-properties
5551 0 (length txt)
5552 (append (list 'org-marker (org-agenda-new-marker pos)
5553 'org-hd-marker (org-agenda-new-marker pos1)
5554 'priority (+ (- 5 diff) (org-get-priority txt))
5555 'category category)
5556 props) txt)
5557 (push txt ee)))))
5558 ee))
5559
5560 (defun org-agenda-get-blocks ()
5561 "Return the date-range information for agenda display."
5562 (let* ((props (list 'face nil
5563 'mouse-face 'highlight
5564 'keymap org-agenda-keymap
5565 'help-echo
5566 (format "mouse-2 or RET jump to org file %s"
5567 (abbreviate-file-name (buffer-file-name)))))
5568 (regexp org-tr-regexp)
5569 (d0 (calendar-absolute-from-gregorian date))
5570 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
5571 (goto-char (point-min))
5572 (while (re-search-forward regexp nil t)
5573 (setq timestr (match-string 0)
5574 s1 (match-string 1)
5575 s2 (match-string 2)
5576 d1 (time-to-days (org-time-string-to-time s1))
5577 d2 (time-to-days (org-time-string-to-time s2)))
5578 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5579 ;; Only allow days between the limits, because the normal
5580 ;; date stamps will catch the limits.
5581 (save-excursion
5582 (setq marker (org-agenda-new-marker (point)))
5583 (setq category (org-get-category))
5584 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5585 (progn
5586 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5587 (goto-char (match-end 1))
5588 (setq tags (org-get-tags-at))
5589 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5590 (setq txt (org-format-agenda-item
5591 (format (if (= d1 d2) "" "(%d/%d): ")
5592 (1+ (- d0 d1)) (1+ (- d2 d1)))
5593 (match-string 1) category tags
5594 (if (= d0 d1) timestr))))
5595 (setq txt org-agenda-no-heading-message))
5596 (add-text-properties
5597 0 (length txt) (append (list 'org-marker marker
5598 'org-hd-marker hdmarker
5599 'priority (org-get-priority txt)
5600 'category category)
5601 props)
5602 txt)
5603 (push txt ee)))
5604 (outline-next-heading))
5605 ;; Sort the entries by expiration date.
5606 (nreverse ee)))
5607
5608 (defconst org-plain-time-of-day-regexp
5609 (concat
5610 "\\(\\<[012]?[0-9]"
5611 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5612 "\\(--?"
5613 "\\(\\<[012]?[0-9]"
5614 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5615 "\\)?")
5616 "Regular expression to match a plain time or time range.
5617 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5618 groups carry important information:
5619 0 the full match
5620 1 the first time, range or not
5621 8 the second time, if it is a range.")
5622
5623 (defconst org-stamp-time-of-day-regexp
5624 (concat
5625 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5626 "\\([012][0-9]:[0-5][0-9]\\)>"
5627 "\\(--?"
5628 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5629 "Regular expression to match a timestamp time or time range.
5630 After a match, the following groups carry important information:
5631 0 the full match
5632 1 date plus weekday, for backreferencing to make sure both times on same day
5633 2 the first time, range or not
5634 4 the second time, if it is a range.")
5635
5636 (defvar org-prefix-has-time nil
5637 "A flag, set by `org-compile-prefix-format'.
5638 The flag is set if the currently compiled format contains a `%t'.")
5639
5640 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
5641 "Format TXT to be inserted into the agenda buffer.
5642 In particular, it adds the prefix and corresponding text properties. EXTRA
5643 must be a string and replaces the `%s' specifier in the prefix format.
5644 CATEGORY (string, symbol or nil) may be used to overule the default
5645 category taken from local variable or file name. It will replace the `%c'
5646 specifier in the format. DOTIME, when non-nil, indicates that a
5647 time-of-day should be extracted from TXT for sorting of this entry, and for
5648 the `%t' specifier in the format. When DOTIME is a string, this string is
5649 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5650 only the correctly processes TXT should be returned - this is used by
5651 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
5652 (save-match-data
5653 ;; Diary entries sometimes have extra whitespace at the beginning
5654 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5655 (let* ((category (or category
5656 org-category
5657 (if (buffer-file-name)
5658 (file-name-sans-extension
5659 (file-name-nondirectory (buffer-file-name)))
5660 "")))
5661 (tag (or (nth (1- (length tags)) tags) ""))
5662 time ;; needed for the eval of the prefix format
5663 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5664 (time-of-day (and dotime (org-get-time-of-day ts)))
5665 stamp plain s0 s1 s2 rtn)
5666 (when (and dotime time-of-day org-prefix-has-time)
5667 ;; Extract starting and ending time and move them to prefix
5668 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5669 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5670 (setq s0 (match-string 0 ts)
5671 s1 (match-string (if plain 1 2) ts)
5672 s2 (match-string (if plain 8 4) ts))
5673
5674 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5675 ;; them, we might want to remove them there to avoid duplication.
5676 ;; The user can turn this off with a variable.
5677 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5678 (string-match (concat (regexp-quote s0) " *") txt)
5679 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5680 (= (match-beginning 0) 0)
5681 t))
5682 (setq txt (replace-match "" nil nil txt))))
5683 ;; Normalize the time(s) to 24 hour
5684 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5685 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5686
5687 ;; Create the final string
5688 (if noprefix
5689 (setq rtn txt)
5690 ;; Prepare the variables needed in the eval of the compiled format
5691 (setq time (cond (s2 (concat s1 "-" s2))
5692 (s1 (concat s1 "......"))
5693 (t ""))
5694 extra (or extra "")
5695 category (if (symbolp category) (symbol-name category) category))
5696 ;; Evaluate the compiled format
5697 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5698
5699 ;; And finally add the text properties
5700 (add-text-properties
5701 0 (length rtn) (list 'category (downcase category)
5702 'tags tags
5703 'prefix-length (- (length rtn) (length txt))
5704 'time-of-day time-of-day
5705 'dotime dotime)
5706 rtn)
5707 rtn)))
5708
5709 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5710 (catch 'exit
5711 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5712 ((and todayp (member 'today (car org-agenda-time-grid))))
5713 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5714 ((member 'weekly (car org-agenda-time-grid)))
5715 (t (throw 'exit list)))
5716 (let* ((have (delq nil (mapcar
5717 (lambda (x) (get-text-property 1 'time-of-day x))
5718 list)))
5719 (string (nth 1 org-agenda-time-grid))
5720 (gridtimes (nth 2 org-agenda-time-grid))
5721 (req (car org-agenda-time-grid))
5722 (remove (member 'remove-match req))
5723 new time)
5724 (if (and (member 'require-timed req) (not have))
5725 ;; don't show empty grid
5726 (throw 'exit list))
5727 (while (setq time (pop gridtimes))
5728 (unless (and remove (member time have))
5729 (setq time (int-to-string time))
5730 (push (org-format-agenda-item
5731 nil string "" nil ;; FIXME: put a category for the grid?
5732 (concat (substring time 0 -2) ":" (substring time -2)))
5733 new)
5734 (put-text-property
5735 1 (length (car new)) 'face 'org-time-grid (car new))))
5736 (if (member 'time-up org-agenda-sorting-strategy)
5737 (append new list)
5738 (append list new)))))
5739
5740 (defun org-compile-prefix-format (format)
5741 "Compile the prefix format into a Lisp form that can be evaluated.
5742 The resulting form is returned and stored in the variable
5743 `org-prefix-format-compiled'."
5744 (setq org-prefix-has-time nil)
5745 (let ((start 0) varform vars var (s format)e c f opt)
5746 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5747 s start)
5748 (setq var (cdr (assoc (match-string 4 s)
5749 '(("c" . category) ("t" . time) ("s" . extra)
5750 ("T" . tag))))
5751 c (or (match-string 3 s) "")
5752 opt (match-beginning 1)
5753 start (1+ (match-beginning 0)))
5754 (if (equal var 'time) (setq org-prefix-has-time t))
5755 (setq f (concat "%" (match-string 2 s) "s"))
5756 (if opt
5757 (setq varform
5758 `(if (equal "" ,var)
5759 ""
5760 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5761 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5762 (setq s (replace-match "%s" t nil s))
5763 (push varform vars))
5764 (setq vars (nreverse vars))
5765 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5766
5767 (defun org-get-time-of-day (s &optional string)
5768 "Check string S for a time of day.
5769 If found, return it as a military time number between 0 and 2400.
5770 If not found, return nil.
5771 The optional STRING argument forces conversion into a 5 character wide string
5772 HH:MM."
5773 (save-match-data
5774 (when
5775 (or
5776 (string-match
5777 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5778 (string-match
5779 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5780 (let* ((t0 (+ (* 100
5781 (+ (string-to-number (match-string 1 s))
5782 (if (and (match-beginning 4)
5783 (equal (downcase (match-string 4 s)) "pm"))
5784 12 0)))
5785 (if (match-beginning 3)
5786 (string-to-number (match-string 3 s))
5787 0)))
5788 (t1 (concat " "
5789 (if (< t0 100) "0" "")
5790 (int-to-string t0))))
5791 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
5792
5793 (defun org-finalize-agenda-entries (list)
5794 "Sort and concatenate the agenda items."
5795 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
5796
5797 (defsubst org-cmp-priority (a b)
5798 "Compare the priorities of string a and b."
5799 (let ((pa (or (get-text-property 1 'priority a) 0))
5800 (pb (or (get-text-property 1 'priority b) 0)))
5801 (cond ((> pa pb) +1)
5802 ((< pa pb) -1)
5803 (t nil))))
5804
5805 (defsubst org-cmp-category (a b)
5806 "Compare the string values of categories of strings a and b."
5807 (let ((ca (or (get-text-property 1 'category a) ""))
5808 (cb (or (get-text-property 1 'category b) "")))
5809 (cond ((string-lessp ca cb) -1)
5810 ((string-lessp cb ca) +1)
5811 (t nil))))
5812
5813 (defsubst org-cmp-time (a b)
5814 "Compare the time-of-day values of strings a and b."
5815 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
5816 (ta (or (get-text-property 1 'time-of-day a) def))
5817 (tb (or (get-text-property 1 'time-of-day b) def)))
5818 (cond ((< ta tb) -1)
5819 ((< tb ta) +1)
5820 (t nil))))
5821
5822 (defun org-entries-lessp (a b)
5823 "Predicate for sorting agenda entries."
5824 ;; The following variables will be used when the form is evaluated.
5825 (let* ((time-up (org-cmp-time a b))
5826 (time-down (if time-up (- time-up) nil))
5827 (priority-up (org-cmp-priority a b))
5828 (priority-down (if priority-up (- priority-up) nil))
5829 (category-up (org-cmp-category a b))
5830 (category-down (if category-up (- category-up) nil))
5831 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
5832 (cdr (assoc
5833 (eval (cons 'or org-agenda-sorting-strategy))
5834 '((-1 . t) (1 . nil) (nil . nil))))))
5835
5836 (defun org-agenda-show-priority ()
5837 "Show the priority of the current item.
5838 This priority is composed of the main priority given with the [#A] cookies,
5839 and by additional input from the age of a schedules or deadline entry."
5840 (interactive)
5841 (let* ((pri (get-text-property (point-at-bol) 'priority)))
5842 (message "Priority is %d" (if pri pri -1000))))
5843
5844 (defun org-agenda-show-tags ()
5845 "Show the tags applicable to the current item."
5846 (interactive)
5847 (let* ((tags (get-text-property (point-at-bol) 'tags)))
5848 (if tags
5849 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
5850 (message "No tags associated with this line"))))
5851
5852 (defun org-agenda-goto (&optional highlight)
5853 "Go to the Org-mode file which contains the item at point."
5854 (interactive)
5855 (let* ((marker (or (get-text-property (point) 'org-marker)
5856 (org-agenda-error)))
5857 (buffer (marker-buffer marker))
5858 (pos (marker-position marker)))
5859 (switch-to-buffer-other-window buffer)
5860 (widen)
5861 (goto-char pos)
5862 (when (eq major-mode 'org-mode)
5863 (org-show-hidden-entry)
5864 (save-excursion
5865 (and (outline-next-heading)
5866 (org-flag-heading nil)))) ; show the next heading
5867 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
5868
5869 (defun org-agenda-switch-to ()
5870 "Go to the Org-mode file which contains the item at point."
5871 (interactive)
5872 (let* ((marker (or (get-text-property (point) 'org-marker)
5873 (org-agenda-error)))
5874 (buffer (marker-buffer marker))
5875 (pos (marker-position marker)))
5876 (switch-to-buffer buffer)
5877 (delete-other-windows)
5878 (widen)
5879 (goto-char pos)
5880 (when (eq major-mode 'org-mode)
5881 (org-show-hidden-entry)
5882 (save-excursion
5883 (and (outline-next-heading)
5884 (org-flag-heading nil)))))) ; show the next heading
5885
5886 (defun org-agenda-goto-mouse (ev)
5887 "Go to the Org-mode file which contains the item at the mouse click."
5888 (interactive "e")
5889 (mouse-set-point ev)
5890 (org-agenda-goto))
5891
5892 (defun org-agenda-show ()
5893 "Display the Org-mode file which contains the item at point."
5894 (interactive)
5895 (let ((win (selected-window)))
5896 (org-agenda-goto t)
5897 (select-window win)))
5898
5899 (defun org-agenda-recenter (arg)
5900 "Display the Org-mode file which contains the item at point and recenter."
5901 (interactive "P")
5902 (let ((win (selected-window)))
5903 (org-agenda-goto t)
5904 (recenter arg)
5905 (select-window win)))
5906
5907 (defun org-agenda-show-mouse (ev)
5908 "Display the Org-mode file which contains the item at the mouse click."
5909 (interactive "e")
5910 (mouse-set-point ev)
5911 (org-agenda-show))
5912
5913 (defun org-agenda-check-no-diary ()
5914 "Check if the entry is a diary link and abort if yes."
5915 (if (get-text-property (point) 'org-agenda-diary-link)
5916 (org-agenda-error)))
5917
5918 (defun org-agenda-error ()
5919 (error "Command not allowed in this line"))
5920
5921 (defvar org-last-heading-marker (make-marker)
5922 "Marker pointing to the headline that last changed its TODO state
5923 by a remote command from the agenda.")
5924
5925 (defun org-agenda-todo (&optional arg)
5926 "Cycle TODO state of line at point, also in Org-mode file.
5927 This changes the line at point, all other lines in the agenda referring to
5928 the same tree node, and the headline of the tree node in the Org-mode file."
5929 (interactive "P")
5930 (org-agenda-check-no-diary)
5931 (let* ((col (current-column))
5932 (marker (or (get-text-property (point) 'org-marker)
5933 (org-agenda-error)))
5934 (buffer (marker-buffer marker))
5935 (pos (marker-position marker))
5936 (hdmarker (get-text-property (point) 'org-hd-marker))
5937 (buffer-read-only nil)
5938 newhead)
5939 (with-current-buffer buffer
5940 (widen)
5941 (goto-char pos)
5942 (org-show-hidden-entry)
5943 (save-excursion
5944 (and (outline-next-heading)
5945 (org-flag-heading nil))) ; show the next heading
5946 (org-todo arg)
5947 (forward-char 1)
5948 (setq newhead (org-get-heading))
5949 (save-excursion
5950 (org-back-to-heading)
5951 (move-marker org-last-heading-marker (point))))
5952 (beginning-of-line 1)
5953 (save-excursion
5954 (org-agenda-change-all-lines newhead hdmarker 'fixface))
5955 (move-to-column col)))
5956
5957 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
5958 "Change all lines in the agenda buffer which match hdmarker.
5959 The new content of the line will be NEWHEAD (as modified by
5960 `org-format-agenda-item'). HDMARKER is checked with
5961 `equal' against all `org-hd-marker' text properties in the file.
5962 If FIXFACE is non-nil, the face of each item is modified acording to
5963 the new TODO state."
5964 (let* (props m pl undone-face done-face finish new dotime cat tags)
5965 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
5966 (save-excursion
5967 (goto-char (point-max))
5968 (beginning-of-line 1)
5969 (while (not finish)
5970 (setq finish (bobp))
5971 (when (and (setq m (get-text-property (point) 'org-hd-marker))
5972 (equal m hdmarker))
5973 (setq props (text-properties-at (point))
5974 dotime (get-text-property (point) 'dotime)
5975 cat (get-text-property (point) 'category)
5976 tags (get-text-property (point) 'tags)
5977 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
5978 pl (get-text-property (point) 'prefix-length)
5979 undone-face (get-text-property (point) 'undone-face)
5980 done-face (get-text-property (point) 'done-face))
5981 (move-to-column pl)
5982 (if (looking-at ".*")
5983 (progn
5984 (replace-match new t t)
5985 (beginning-of-line 1)
5986 (add-text-properties (point-at-bol) (point-at-eol) props)
5987 (if fixface
5988 (add-text-properties
5989 (point-at-bol) (point-at-eol)
5990 (list 'face
5991 (if org-last-todo-state-is-todo
5992 undone-face done-face))))
5993 (beginning-of-line 1))
5994 (error "Line update did not work")))
5995 (beginning-of-line 0)))))
5996
5997 (defun org-agenda-priority-up ()
5998 "Increase the priority of line at point, also in Org-mode file."
5999 (interactive)
6000 (org-agenda-priority 'up))
6001
6002 (defun org-agenda-priority-down ()
6003 "Decrease the priority of line at point, also in Org-mode file."
6004 (interactive)
6005 (org-agenda-priority 'down))
6006
6007 (defun org-agenda-priority (&optional force-direction)
6008 "Set the priority of line at point, also in Org-mode file.
6009 This changes the line at point, all other lines in the agenda referring to
6010 the same tree node, and the headline of the tree node in the Org-mode file."
6011 (interactive)
6012 (org-agenda-check-no-diary)
6013 (let* ((marker (or (get-text-property (point) 'org-marker)
6014 (org-agenda-error)))
6015 (buffer (marker-buffer marker))
6016 (pos (marker-position marker))
6017 (hdmarker (get-text-property (point) 'org-hd-marker))
6018 (buffer-read-only nil)
6019 newhead)
6020 (with-current-buffer buffer
6021 (widen)
6022 (goto-char pos)
6023 (org-show-hidden-entry)
6024 (save-excursion
6025 (and (outline-next-heading)
6026 (org-flag-heading nil))) ; show the next heading
6027 (funcall 'org-priority force-direction)
6028 (end-of-line 1)
6029 (setq newhead (org-get-heading)))
6030 (org-agenda-change-all-lines newhead hdmarker)
6031 (beginning-of-line 1)))
6032
6033 (defun org-agenda-set-tags ()
6034 "Set tags for the current headline."
6035 (interactive)
6036 (org-agenda-check-no-diary)
6037 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6038 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6039 (org-agenda-error)))
6040 (buffer (marker-buffer hdmarker))
6041 (pos (marker-position hdmarker))
6042 (buffer-read-only nil)
6043 newhead)
6044 (with-current-buffer buffer
6045 (widen)
6046 (goto-char pos)
6047 (org-show-hidden-entry)
6048 (save-excursion
6049 (and (outline-next-heading)
6050 (org-flag-heading nil))) ; show the next heading
6051 (call-interactively 'org-set-tags)
6052 (end-of-line 1)
6053 (setq newhead (org-get-heading)))
6054 (org-agenda-change-all-lines newhead hdmarker)
6055 (beginning-of-line 1)))
6056
6057 (defun org-agenda-date-later (arg &optional what)
6058 "Change the date of this item to one day later."
6059 (interactive "p")
6060 (org-agenda-check-type t 'agenda 'timeline)
6061 (org-agenda-check-no-diary)
6062 (let* ((marker (or (get-text-property (point) 'org-marker)
6063 (org-agenda-error)))
6064 (buffer (marker-buffer marker))
6065 (pos (marker-position marker)))
6066 (with-current-buffer buffer
6067 (widen)
6068 (goto-char pos)
6069 (if (not (org-at-timestamp-p))
6070 (error "Cannot find time stamp"))
6071 (org-timestamp-change arg (or what 'day))
6072 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6073
6074 (defun org-agenda-date-earlier (arg &optional what)
6075 "Change the date of this item to one day earlier."
6076 (interactive "p")
6077 (org-agenda-date-later (- arg) what))
6078
6079 (defun org-agenda-date-prompt (arg)
6080 "Change the date of this item. Date is prompted for, with default today.
6081 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6082 be used to request time specification in the time stamp."
6083 (interactive "P")
6084 (org-agenda-check-type t 'agenda 'timeline)
6085 (org-agenda-check-no-diary)
6086 (let* ((marker (or (get-text-property (point) 'org-marker)
6087 (org-agenda-error)))
6088 (buffer (marker-buffer marker))
6089 (pos (marker-position marker)))
6090 (with-current-buffer buffer
6091 (widen)
6092 (goto-char pos)
6093 (if (not (org-at-timestamp-p))
6094 (error "Cannot find time stamp"))
6095 (org-time-stamp arg)
6096 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6097
6098 (defun org-get-heading ()
6099 "Return the heading of the current entry, without the stars."
6100 (save-excursion
6101 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6102 ;;FIXME???????? (and (bolp) (end-of-line 1))
6103 (if (and (re-search-backward "[\r\n]\\*" nil t)
6104 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6105 (match-string 1)
6106 "")))
6107
6108 (defun org-agenda-diary-entry ()
6109 "Make a diary entry, like the `i' command from the calendar.
6110 All the standard commands work: block, weekly etc"
6111 (interactive)
6112 (org-agenda-check-type t 'agenda 'timeline)
6113 (require 'diary-lib)
6114 (let* ((char (progn
6115 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6116 (read-char-exclusive)))
6117 (cmd (cdr (assoc char
6118 '((?d . insert-diary-entry)
6119 (?w . insert-weekly-diary-entry)
6120 (?m . insert-monthly-diary-entry)
6121 (?y . insert-yearly-diary-entry)
6122 (?a . insert-anniversary-diary-entry)
6123 (?b . insert-block-diary-entry)
6124 (?c . insert-cyclic-diary-entry)))))
6125 (oldf (symbol-function 'calendar-cursor-to-date))
6126 (point (point))
6127 (mark (or (mark t) (point))))
6128 (unless cmd
6129 (error "No command associated with <%c>" char))
6130 (unless (and (get-text-property point 'day)
6131 (or (not (equal ?b char))
6132 (get-text-property mark 'day)))
6133 (error "Don't know which date to use for diary entry"))
6134 ;; We implement this by hacking the `calendar-cursor-to-date' function
6135 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6136 (let ((calendar-mark-ring
6137 (list (calendar-gregorian-from-absolute
6138 (or (get-text-property mark 'day)
6139 (get-text-property point 'day))))))
6140 (unwind-protect
6141 (progn
6142 (fset 'calendar-cursor-to-date
6143 (lambda (&optional error)
6144 (calendar-gregorian-from-absolute
6145 (get-text-property point 'day))))
6146 (call-interactively cmd))
6147 (fset 'calendar-cursor-to-date oldf)))))
6148
6149
6150 (defun org-agenda-execute-calendar-command (cmd)
6151 "Execute a calendar command from the agenda, with the date associated to
6152 the cursor position."
6153 (org-agenda-check-type t 'agenda 'timeline)
6154 (require 'diary-lib)
6155 (unless (get-text-property (point) 'day)
6156 (error "Don't know which date to use for calendar command"))
6157 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6158 (point (point))
6159 (date (calendar-gregorian-from-absolute
6160 (get-text-property point 'day)))
6161 (displayed-day (extract-calendar-day date))
6162 (displayed-month (extract-calendar-month date))
6163 (displayed-year (extract-calendar-year date)))
6164 (unwind-protect
6165 (progn
6166 (fset 'calendar-cursor-to-date
6167 (lambda (&optional error)
6168 (calendar-gregorian-from-absolute
6169 (get-text-property point 'day))))
6170 (call-interactively cmd))
6171 (fset 'calendar-cursor-to-date oldf))))
6172
6173 (defun org-agenda-phases-of-moon ()
6174 "Display the phases of the moon for the 3 months around the cursor date."
6175 (interactive)
6176 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6177
6178 (defun org-agenda-holidays ()
6179 "Display the holidays for the 3 months around the cursor date."
6180 (interactive)
6181 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6182
6183 (defun org-agenda-sunrise-sunset (arg)
6184 "Display sunrise and sunset for the cursor date.
6185 Latitude and longitude can be specified with the variables
6186 `calendar-latitude' and `calendar-longitude'. When called with prefix
6187 argument, latitude and longitude will be prompted for."
6188 (interactive "P")
6189 (let ((calendar-longitude (if arg nil calendar-longitude))
6190 (calendar-latitude (if arg nil calendar-latitude))
6191 (calendar-location-name
6192 (if arg "the given coordinates" calendar-location-name)))
6193 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6194
6195 (defun org-agenda-goto-calendar ()
6196 "Open the Emacs calendar with the date at the cursor."
6197 (interactive)
6198 (org-agenda-check-type t 'agenda 'timeline)
6199 (let* ((day (or (get-text-property (point) 'day)
6200 (error "Don't know which date to open in calendar")))
6201 (date (calendar-gregorian-from-absolute day))
6202 (calendar-move-hook nil)
6203 (view-diary-entries-initially nil))
6204 (calendar)
6205 (calendar-goto-date date)))
6206
6207 (defun org-calendar-goto-agenda ()
6208 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6209 This is a command that has to be installed in `calendar-mode-map'."
6210 (interactive)
6211 (org-agenda-list nil (calendar-absolute-from-gregorian
6212 (calendar-cursor-to-date))
6213 nil t))
6214
6215 (defun org-agenda-convert-date ()
6216 (interactive)
6217 (org-agenda-check-type t 'agenda 'timeline)
6218 (let ((day (get-text-property (point) 'day))
6219 date s)
6220 (unless day
6221 (error "Don't know which date to convert"))
6222 (setq date (calendar-gregorian-from-absolute day))
6223 (setq s (concat
6224 "Gregorian: " (calendar-date-string date) "\n"
6225 "ISO: " (calendar-iso-date-string date) "\n"
6226 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6227 "Julian: " (calendar-julian-date-string date) "\n"
6228 "Astron. JD: " (calendar-astro-date-string date)
6229 " (Julian date number at noon UTC)\n"
6230 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6231 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6232 "French: " (calendar-french-date-string date) "\n"
6233 "Mayan: " (calendar-mayan-date-string date) "\n"
6234 "Coptic: " (calendar-coptic-date-string date) "\n"
6235 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6236 "Persian: " (calendar-persian-date-string date) "\n"
6237 "Chinese: " (calendar-chinese-date-string date) "\n"))
6238 (with-output-to-temp-buffer "*Dates*"
6239 (princ s))
6240 (if (fboundp 'fit-window-to-buffer)
6241 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6242
6243 ;;; Tags
6244
6245 (defun org-scan-tags (action matcher &optional todo-only)
6246 "Scan headline tags with inheritance and produce output ACTION.
6247 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6248 evaluated, testing if a given set of tags qualifies a headline for
6249 inclusion. When TODO-ONLY is non-nil, only lines with a TDOD keyword
6250 d are included in the output."
6251 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6252 (mapconcat 'regexp-quote
6253 (nreverse (cdr (reverse org-todo-keywords)))
6254 "\\|")
6255 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_:]+:\\)?[ \t]*[\n\r]"))
6256 (props (list 'face nil
6257 'done-face 'org-done
6258 'undone-face nil
6259 'mouse-face 'highlight
6260 'keymap org-agenda-keymap
6261 'help-echo
6262 (format "mouse-2 or RET jump to org file %s"
6263 (abbreviate-file-name (buffer-file-name)))))
6264 lspos
6265 tags tags-list tags-alist (llast 0) rtn level category i txt
6266 todo marker)
6267
6268 (save-excursion
6269 (goto-char (point-min))
6270 (when (eq action 'sparse-tree) (hide-sublevels 1))
6271 (while (re-search-forward re nil t)
6272 (setq todo (if (match-end 1) (match-string 2))
6273 tags (if (match-end 4) (match-string 4)))
6274 (goto-char (setq lspos (1+ (match-beginning 0))))
6275 (setq level (outline-level)
6276 category (org-get-category))
6277 (setq i llast llast level)
6278 ;; remove tag lists from same and sublevels
6279 (while (>= i level)
6280 (when (setq entry (assoc i tags-alist))
6281 (setq tags-alist (delete entry tags-alist)))
6282 (setq i (1- i)))
6283 ;; add the nex tags
6284 (when tags
6285 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6286 tags-alist
6287 (cons (cons level tags) tags-alist)))
6288 ;; compile tags for current headline
6289 (setq tags-list
6290 (if org-use-tag-inheritance
6291 (apply 'append (mapcar 'cdr tags-alist))
6292 tags))
6293 (when (and (or (not todo-only) todo)
6294 (eval matcher))
6295 ;; list this headline
6296 (if (eq action 'sparse-tree)
6297 (progn
6298 (org-show-hierarchy-above))
6299 (setq txt (org-format-agenda-item
6300 ""
6301 (concat
6302 (if org-tags-match-list-sublevels
6303 (make-string (1- level) ?.) "")
6304 (org-get-heading))
6305 category tags-list))
6306 (goto-char lspos)
6307 (setq marker (org-agenda-new-marker))
6308 (add-text-properties
6309 0 (length txt)
6310 (append (list 'org-marker marker 'org-hd-marker marker
6311 'category category)
6312 props)
6313 txt)
6314 (push txt rtn))
6315 ;; if we are to skip sublevels, jump to end of subtree
6316 (point)
6317 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6318 (nreverse rtn)))
6319
6320 (defun org-tags-sparse-tree (&optional arg match)
6321 "Create a sparse tree according to tags search string MATCH.
6322 MATCH can contain positive and negative selection of tags, like
6323 \"+WORK+URGENT-WITHBOSS\"."
6324 (interactive "P")
6325 (let ((org-show-following-heading nil)
6326 (org-show-hierarchy-above nil))
6327 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6328
6329 (defun org-make-tags-matcher (match)
6330 "Create the TAGS matcher form for the tags-selecting string MATCH."
6331 (unless match
6332 ;; Get a new match request, with completion
6333 (setq org-last-tags-completion-table
6334 (or (org-get-buffer-tags)
6335 org-last-tags-completion-table))
6336 (setq match (completing-read
6337 "Tags: " 'org-tags-completion-function nil nil nil
6338 'org-tags-history)))
6339 ;; parse the string and create a lisp form
6340 (let ((match0 match) minus tag mm matcher orterms term orlist)
6341 (setq orterms (org-split-string match "|"))
6342 (while (setq term (pop orterms))
6343 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_]+\\)" term)
6344 (setq minus (and (match-end 1)
6345 (equal (match-string 1 term) "-"))
6346 tag (match-string 2 term)
6347 term (substring term (match-end 0))
6348 mm (list 'member (downcase tag) 'tags-list)
6349 mm (if minus (list 'not mm) mm))
6350 (push mm matcher))
6351 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6352 orlist)
6353 (setq matcher nil))
6354 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6355 ;; Return the string and lisp forms of the matcher
6356 (cons match0 matcher)))
6357
6358 ;;;###autoload
6359 (defun org-tags-view (&optional todo-only match keep-modes)
6360 "Show all headlines for all `org-agenda-files' matching a TAGS criterions.
6361 The prefix arg TODO-ONLY limits the search to TODO entries."
6362 (interactive "P")
6363 (org-agenda-maybe-reset-markers 'force)
6364 (org-compile-prefix-format org-agenda-prefix-format)
6365 (let* ((org-agenda-keep-modes keep-modes)
6366 (org-tags-match-list-sublevels
6367 (if todo-only t org-tags-match-list-sublevels))
6368 (win (selected-window))
6369 (completion-ignore-case t)
6370 rtn rtnall files file pos matcher
6371 buffer)
6372 (setq matcher (org-make-tags-matcher match)
6373 match (car matcher) matcher (cdr matcher))
6374 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6375 (progn
6376 (delete-other-windows)
6377 (switch-to-buffer-other-window
6378 (get-buffer-create org-agenda-buffer-name))))
6379 (setq buffer-read-only nil)
6380 (erase-buffer)
6381 (org-agenda-mode) (setq buffer-read-only nil)
6382 (set (make-local-variable 'org-agenda-type) 'tags)
6383 (set (make-local-variable 'org-agenda-redo-command)
6384 (list 'org-tags-view (list 'quote todo-only)
6385 (list 'if 'current-prefix-arg nil match) t))
6386 (setq files (org-agenda-files)
6387 rtnall nil)
6388 (while (setq file (pop files))
6389 (catch 'nextfile
6390 (org-check-agenda-file file)
6391 (setq buffer (if (file-exists-p file)
6392 (org-get-agenda-file-buffer file)
6393 (error "No such file %s" file)))
6394 (if (not buffer)
6395 ;; If file does not exist, merror message to agenda
6396 (setq rtn (list
6397 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6398 rtnall (append rtnall rtn))
6399 (with-current-buffer buffer
6400 (unless (eq major-mode 'org-mode)
6401 (error "Agenda file %s is not in `org-mode'" file))
6402 (save-excursion
6403 (save-restriction
6404 (if org-respect-restriction
6405 (if (org-region-active-p)
6406 ;; Respect a region to restrict search
6407 (narrow-to-region (region-beginning) (region-end)))
6408 ;; If we work for the calendar or many files,
6409 ;; get rid of any restriction
6410 (widen))
6411 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6412 (setq rtnall (append rtnall rtn))))))))
6413 (insert "Headlines with TAGS match: ")
6414 (add-text-properties (point-min) (1- (point))
6415 (list 'face 'org-link))
6416 (setq pos (point))
6417 (insert match "\n")
6418 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6419 (setq pos (point))
6420 (insert "Press `C-u r' to search again with new search string\n")
6421 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6422 (when rtnall
6423 (insert (mapconcat 'identity rtnall "\n")))
6424 (goto-char (point-min))
6425 (setq buffer-read-only t)
6426 (org-fit-agenda-window)
6427 (if (not org-select-agenda-window) (select-window win))))
6428
6429 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6430 (defun org-set-tags (&optional arg just-align)
6431 "Set the tags for the current headline.
6432 With prefix ARG, realign all tags in headings in the current buffer."
6433 (interactive)
6434 (let* (;(inherit (org-get-inherited-tags))
6435 (re (concat "^" outline-regexp))
6436 (col (current-column))
6437 (current (org-get-tags))
6438 tags hd empty)
6439 (if arg
6440 (save-excursion
6441 (goto-char (point-min))
6442 (while (re-search-forward re nil t)
6443 (org-set-tags nil t))
6444 (message "All tags realigned to column %d" org-tags-column))
6445 (if just-align
6446 (setq tags current)
6447 (setq org-last-tags-completion-table
6448 (or (org-get-buffer-tags)
6449 org-last-tags-completion-table))
6450 (setq tags
6451 (let ((org-add-colon-after-tag-completion t))
6452 (completing-read "Tags: " 'org-tags-completion-function
6453 nil nil current 'org-tags-history)))
6454 (while (string-match "[-+&]+" tags)
6455 (setq tags (replace-match ":" t t tags)))
6456 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6457 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6458 (unless (string-match "^:" tags) (setq tags (concat ":" tags)))))
6459 (if (equal current "")
6460 (progn
6461 (end-of-line 1)
6462 (or empty (insert " ")))
6463 (beginning-of-line 1)
6464 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6465 (setq hd (match-string 1))
6466 (delete-region (match-beginning 0) (match-end 0))
6467 (insert (org-trim hd) (if empty "" " ")))
6468 (unless (equal tags "")
6469 (move-to-column (max (current-column)
6470 (if (> org-tags-column 0)
6471 org-tags-column
6472 (- (- org-tags-column) (length tags))))
6473 t)
6474 (insert tags))
6475 (move-to-column col))))
6476
6477 (defun org-tags-completion-function (string predicate &optional flag)
6478 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6479 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6480 (setq s1 (match-string 1 string)
6481 s2 (match-string 2 string))
6482 (setq s1 "" s2 string))
6483 (cond
6484 ((eq flag nil)
6485 ;; try completion
6486 (setq rtn (try-completion s2 ctable))
6487 (if (stringp rtn)
6488 (concat s1 s2 (substring rtn (length s2))
6489 (if (and org-add-colon-after-tag-completion
6490 (assoc rtn ctable))
6491 ":" "")))
6492 )
6493 ((eq flag t)
6494 ;; all-completions
6495 (all-completions s2 ctable)
6496 )
6497 ((eq flag 'lambda)
6498 ;; exact match?
6499 (assoc s2 ctable)))
6500 ))
6501
6502 (defun org-get-tags ()
6503 "Get the TAGS string in the current headline."
6504 (unless (org-on-heading-p)
6505 (error "Not on a heading"))
6506 (save-excursion
6507 (beginning-of-line 1)
6508 (if (looking-at ".*[ \t]\\(:[A-Za-z_:]+:\\)[ \t]*\\(\r\\|$\\)")
6509 (match-string 1)
6510 "")))
6511
6512 (defun org-get-buffer-tags ()
6513 "Get a table of all tags used in the buffer, for completion."
6514 (let (tags)
6515 (save-excursion
6516 (goto-char (point-min))
6517 (while (re-search-forward "[ \t]:\\([A-Za-z_:]+\\):[ \t\r\n]" nil t)
6518 (mapc (lambda (x) (add-to-list 'tags x))
6519 (org-split-string (match-string 1) ":"))))
6520 (mapcar 'list tags)))
6521
6522 ;;; Link Stuff
6523
6524 (defun org-find-file-at-mouse (ev)
6525 "Open file link or URL at mouse."
6526 (interactive "e")
6527 (mouse-set-point ev)
6528 (org-open-at-point 'in-emacs))
6529
6530 (defun org-open-at-mouse (ev)
6531 "Open file link or URL at mouse."
6532 (interactive "e")
6533 (mouse-set-point ev)
6534 (org-open-at-point))
6535
6536 (defun org-open-at-point (&optional in-emacs)
6537 "Open link at or after point.
6538 If there is no link at point, this function will search forward up to
6539 the end of the current subtree.
6540 Normally, files will be opened by an appropriate application. If the
6541 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6542 (interactive "P")
6543 (org-remove-occur-highlights nil nil t)
6544 (if (org-at-timestamp-p)
6545 (org-agenda-list nil (time-to-days (org-time-string-to-time
6546 (substring (match-string 1) 0 10)))
6547 1)
6548 (let (type path line search (pos (point)))
6549 (catch 'match
6550 (save-excursion
6551 (skip-chars-backward
6552 (concat (if org-allow-space-in-links "^" "^ ")
6553 org-non-link-chars))
6554 (when (looking-at org-link-regexp)
6555 (setq type (match-string 1)
6556 path (match-string 2))
6557 (throw 'match t)))
6558 (save-excursion
6559 (skip-chars-backward "^ \t\n\r")
6560 (when (looking-at "\\(:[A-Za-z_:]+\\):[ \t\r\n]")
6561 (setq type "tags"
6562 path (match-string 1))
6563 (while (string-match ":" path)
6564 (setq path (replace-match "+" t t path)))
6565 (throw 'match t)))
6566 (save-excursion
6567 (skip-chars-backward "a-zA-Z_")
6568 (when (looking-at org-camel-regexp)
6569 (setq type "camel" path (match-string 0))
6570 (if (equal (char-before) ?*)
6571 (setq path (concat "*" path))))
6572 (throw 'match t))
6573 (save-excursion
6574 (when (re-search-forward
6575 org-link-regexp
6576 (save-excursion
6577 (condition-case nil
6578 (progn (outline-end-of-subtree) (max pos (point)))
6579 (error (end-of-line 1) (point))))
6580 t)
6581 (setq type (match-string 1)
6582 path (match-string 2)))))
6583 (unless path
6584 (error "No link found"))
6585 ;; Remove any trailing spaces in path
6586 (if (string-match " +\\'" path)
6587 (setq path (replace-match "" t t path)))
6588
6589 (cond
6590
6591 ((string= type "tags")
6592 (org-tags-view path in-emacs))
6593 ((string= type "camel")
6594 (org-link-search
6595 path
6596 (cond ((equal in-emacs '(4)) 'occur)
6597 ((equal in-emacs '(16)) 'org-occur)
6598 (t nil))))
6599
6600 ((string= type "file")
6601 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6602 (setq line (string-to-number (match-string 1 path))
6603 path (substring path 0 (match-beginning 0)))
6604 (if (string-match "::\\(.+\\)\\'" path)
6605 (setq search (match-string 1 path)
6606 path (substring path 0 (match-beginning 0)))))
6607 (org-open-file path in-emacs line search))
6608
6609 ((string= type "news")
6610 (org-follow-gnus-link path))
6611
6612 ((string= type "bbdb")
6613 (org-follow-bbdb-link path))
6614
6615 ((string= type "gnus")
6616 (let (group article)
6617 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6618 (error "Error in Gnus link"))
6619 (setq group (match-string 1 path)
6620 article (match-string 3 path))
6621 (org-follow-gnus-link group article)))
6622
6623 ((string= type "vm")
6624 (let (folder article)
6625 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6626 (error "Error in VM link"))
6627 (setq folder (match-string 1 path)
6628 article (match-string 3 path))
6629 ;; in-emacs is the prefix arg, will be interpreted as read-only
6630 (org-follow-vm-link folder article in-emacs)))
6631
6632 ((string= type "wl")
6633 (let (folder article)
6634 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6635 (error "Error in Wanderlust link"))
6636 (setq folder (match-string 1 path)
6637 article (match-string 3 path))
6638 (org-follow-wl-link folder article)))
6639
6640 ((string= type "rmail")
6641 (let (folder article)
6642 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6643 (error "Error in RMAIL link"))
6644 (setq folder (match-string 1 path)
6645 article (match-string 3 path))
6646 (org-follow-rmail-link folder article)))
6647
6648 ((string= type "shell")
6649 (let ((cmd path))
6650 (while (string-match "@{" cmd)
6651 (setq cmd (replace-match "<" t t cmd)))
6652 (while (string-match "@}" cmd)
6653 (setq cmd (replace-match ">" t t cmd)))
6654 (if (or (not org-confirm-shell-links)
6655 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6656 (shell-command cmd)
6657 (error "Abort"))))
6658
6659 (t
6660 (browse-url-at-point))))))
6661
6662 (defun org-link-search (s &optional type)
6663 "Search for a link search option.
6664 When S is a CamelCaseWord, search for a target, or for a sentence containing
6665 the words. If S is surrounded by forward slashes, it is interpreted as a
6666 regular expression. In org-mode files, this will create an `org-occur'
6667 sparse tree. In ordinary files, `occur' will be used to list matched.
6668 If the current buffer is in `dired-mode', grep will be used to search
6669 in all files."
6670 (let ((case-fold-search t)
6671 (s0 s)
6672 (pos (point))
6673 (pre "") (post "")
6674 words re0 re1 re2 re3 re4 re5 reall)
6675 (cond ((string-match "^/\\(.*\\)/$" s)
6676 ;; A regular expression
6677 (cond
6678 ((eq major-mode 'org-mode)
6679 (org-occur (match-string 1 s)))
6680 ;;((eq major-mode 'dired-mode)
6681 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6682 (t (org-do-occur (match-string 1 s)))))
6683 ((string-match (concat "^" org-camel-regexp) s)
6684 ;; A camel
6685 (if (equal (string-to-char s) ?*)
6686 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6687 post "[ \t]*$"
6688 s (substring s 1)))
6689 (remove-text-properties
6690 0 (length s)
6691 '(face nil mouse-face nil keymap nil fontified nil) s)
6692 ;; Make a series of regular expressions to find a match
6693 (setq words (org-camel-to-words s)
6694 re0 (concat "<<" (regexp-quote s0) ">>")
6695 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6696 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6697 re1 (concat pre re2 post)
6698 re3 (concat pre re4 post)
6699 re5 (concat pre ".*" re4)
6700 re2 (concat pre re2)
6701 re4 (concat pre re4)
6702 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6703 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6704 re5 "\\)"
6705 ))
6706 (cond
6707 ((eq type 'org-occur) (org-occur reall))
6708 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6709 (t (goto-char (point-min))
6710 (if (or (re-search-forward re0 nil t)
6711 (re-search-forward re1 nil t)
6712 (re-search-forward re2 nil t)
6713 (re-search-forward re3 nil t)
6714 (re-search-forward re4 nil t)
6715 (re-search-forward re5 nil t))
6716 (goto-char (match-beginning 0))
6717 (goto-char pos)
6718 (error "No match")))))
6719 (t
6720 ;; Normal string-search
6721 (goto-char (point-min))
6722 (if (search-forward s nil t)
6723 (goto-char (match-beginning 0))
6724 (error "No match"))))))
6725
6726 (defun org-do-occur (regexp &optional cleanup)
6727 "Call the Emacs command `occur'.
6728 If CLEANUP is non-nil, remove the printout of the regular expression
6729 in the *Occur* buffer. This is useful if the regex is long and not useful
6730 to read."
6731 (occur regexp)
6732 (when cleanup
6733 (let ((cwin (selected-window)) win beg end)
6734 (when (setq win (get-buffer-window "*Occur*"))
6735 (select-window win))
6736 (goto-char (point-min))
6737 (when (re-search-forward "match[a-z]+" nil t)
6738 (setq beg (match-end 0))
6739 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6740 (setq end (1- (match-beginning 0)))))
6741 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
6742 (goto-char (point-min))
6743 (select-window cwin))))
6744
6745 (defun org-camel-to-words (s)
6746 "Split \"CamelCaseWords\" to (\"Camel \" \"Case\" \"Words\")."
6747 (let ((case-fold-search nil)
6748 words)
6749 (while (string-match "[a-z][A-Z]" s)
6750 (push (substring s 0 (1+ (match-beginning 0))) words)
6751 (setq s (substring s (1+ (match-beginning 0)))))
6752 (nreverse (cons s words))))
6753
6754 (defun org-follow-bbdb-link (name)
6755 "Follow a BBDB link to NAME."
6756 (require 'bbdb)
6757 (let ((inhibit-redisplay t))
6758 (catch 'exit
6759 ;; Exact match on name
6760 (bbdb-name (concat "\\`" name "\\'") nil)
6761 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6762 ;; Exact match on name
6763 (bbdb-company (concat "\\`" name "\\'") nil)
6764 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6765 ;; Partial match on name
6766 (bbdb-name name nil)
6767 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6768 ;; Partial match on company
6769 (bbdb-company name nil)
6770 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6771 ;; General match including network address and notes
6772 (bbdb name nil)
6773 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
6774 (delete-window (get-buffer-window "*BBDB*"))
6775 (error "No matching BBDB record")))))
6776
6777 (defun org-follow-gnus-link (&optional group article)
6778 "Follow a Gnus link to GROUP and ARTICLE."
6779 (require 'gnus)
6780 (funcall (cdr (assq 'gnus org-link-frame-setup)))
6781 (if group (gnus-fetch-group group))
6782 (if article
6783 (or (gnus-summary-goto-article article nil 'force)
6784 (if (fboundp 'gnus-summary-insert-cached-articles)
6785 (progn
6786 (gnus-summary-insert-cached-articles)
6787 (gnus-summary-goto-article article nil 'force))
6788 (message "Message could not be found.")))))
6789
6790 (defun org-follow-vm-link (&optional folder article readonly)
6791 "Follow a VM link to FOLDER and ARTICLE."
6792 (require 'vm)
6793 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
6794 ;; ange-ftp or efs or tramp access
6795 (let ((user (or (match-string 1 folder) (user-login-name)))
6796 (host (match-string 2 folder))
6797 (file (match-string 3 folder)))
6798 (cond
6799 ((featurep 'tramp)
6800 ;; use tramp to access the file
6801 (if org-xemacs-p
6802 (setq folder (format "[%s@%s]%s" user host file))
6803 (setq folder (format "/%s@%s:%s" user host file))))
6804 (t
6805 ;; use ange-ftp or efs
6806 (require (if org-xemacs-p 'efs 'ange-ftp))
6807 (setq folder (format "/%s@%s:%s" user host file))))))
6808 (when folder
6809 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
6810 (sit-for 0.1)
6811 (when article
6812 (vm-select-folder-buffer)
6813 (widen)
6814 (let ((case-fold-search t))
6815 (goto-char (point-min))
6816 (if (not (re-search-forward
6817 (concat "^" "message-id: *" (regexp-quote article))))
6818 (error "Could not find the specified message in this folder"))
6819 (vm-isearch-update)
6820 (vm-isearch-narrow)
6821 (vm-beginning-of-message)
6822 (vm-summarize)))))
6823
6824 (defun org-follow-wl-link (folder article)
6825 "Follow a Wanderlust link to FOLDER and ARTICLE."
6826 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
6827 (if article (wl-summary-jump-to-msg-by-message-id article))
6828 (wl-summary-redisplay))
6829
6830 (defun org-follow-rmail-link (folder article)
6831 "Follow an RMAIL link to FOLDER and ARTICLE."
6832 (let (message-number)
6833 (save-excursion
6834 (save-window-excursion
6835 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6836 (setq message-number
6837 (save-restriction
6838 (widen)
6839 (goto-char (point-max))
6840 (if (re-search-backward
6841 (concat "^Message-ID:\\s-+" (regexp-quote
6842 (or article "")))
6843 nil t)
6844 (rmail-what-message))))))
6845 (if message-number
6846 (progn
6847 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6848 (rmail-show-message message-number)
6849 message-number)
6850 (error "Message not found"))))
6851
6852 (defun org-open-file (path &optional in-emacs line search)
6853 "Open the file at PATH.
6854 First, this expands any special file name abbreviations. Then the
6855 configuration variable `org-file-apps' is checked if it contains an
6856 entry for this file type, and if yes, the corresponding command is launched.
6857 If no application is found, Emacs simply visits the file.
6858 With optional argument IN-EMACS, Emacs will visit the file.
6859 Optional LINE specifies a line to go to, optional SEARCH a string to
6860 search for. If LINE or SEARCH is given, the file will always be
6861 openen in emacs.
6862 If the file does not exist, an error is thrown."
6863 (setq in-emacs (or in-emacs line search))
6864 (let* ((file (if (equal path "")
6865 (buffer-file-name)
6866 (convert-standard-filename (org-expand-file-name path))))
6867 (dfile (downcase file))
6868 ext cmd apps)
6869 (if (and (not (file-exists-p file))
6870 (not org-open-non-existing-files))
6871 (error "No such file: %s" file))
6872 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
6873 (setq ext (match-string 1 dfile))
6874 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
6875 (setq ext (match-string 1 dfile))))
6876 (setq apps (append org-file-apps (org-default-apps)))
6877 (if in-emacs
6878 (setq cmd 'emacs)
6879 (setq cmd (or (cdr (assoc ext apps))
6880 (cdr (assoc t apps)))))
6881 (when (eq cmd 'mailcap)
6882 (require 'mailcap)
6883 (mailcap-parse-mailcaps)
6884 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
6885 (command (mailcap-mime-info mime-type)))
6886 (if (stringp command)
6887 (setq cmd command)
6888 (setq cmd 'emacs))))
6889 (cond
6890 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
6891 (setq cmd (format cmd (concat "\"" file "\"")))
6892 (save-window-excursion
6893 (shell-command (concat cmd " &"))))
6894 ((or (stringp cmd)
6895 (eq cmd 'emacs))
6896 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
6897 (funcall (cdr (assq 'file org-link-frame-setup)) file))
6898 (if line (goto-line line)
6899 (if search (org-link-search search))))
6900 ((consp cmd)
6901 (eval cmd))
6902 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
6903
6904 (defun org-default-apps ()
6905 "Return the default applications for this operating system."
6906 (cond
6907 ((eq system-type 'darwin)
6908 org-file-apps-defaults-macosx)
6909 ((eq system-type 'windows-nt)
6910 org-file-apps-defaults-windowsnt)
6911 (t org-file-apps-defaults-gnu)))
6912
6913 (defun org-expand-file-name (path)
6914 "Replace special path abbreviations and expand the file name."
6915 (expand-file-name path))
6916
6917
6918 (defvar org-insert-link-history nil
6919 "Minibuffer history for links inserted with `org-insert-link'.")
6920
6921 (defvar org-stored-links nil
6922 "Contains the links stored with `org-store-link'.")
6923
6924 ;;;###autoload
6925 (defun org-store-link (arg)
6926 "\\<org-mode-map>Store an org-link to the current location.
6927 This link can later be inserted into an org-buffer with
6928 \\[org-insert-link].
6929 For some link types, a prefix arg is interpreted:
6930 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6931 For file links, arg negates `org-context-in-file-links'."
6932 (interactive "P")
6933 (let (link cpltxt)
6934 (cond
6935
6936 ((eq major-mode 'bbdb-mode)
6937 (setq cpltxt (concat
6938 "bbdb:"
6939 (or (bbdb-record-name (bbdb-current-record))
6940 (bbdb-record-company (bbdb-current-record))))
6941 link (org-make-link cpltxt)))
6942
6943 ((eq major-mode 'calendar-mode)
6944 (let ((cd (calendar-cursor-to-date)))
6945 (setq link
6946 (format-time-string
6947 (car org-time-stamp-formats)
6948 (apply 'encode-time
6949 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6950 nil nil nil))))))
6951
6952 ((or (eq major-mode 'vm-summary-mode)
6953 (eq major-mode 'vm-presentation-mode))
6954 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
6955 (vm-follow-summary-cursor)
6956 (save-excursion
6957 (vm-select-folder-buffer)
6958 (let* ((message (car vm-message-pointer))
6959 (folder (buffer-file-name))
6960 (subject (vm-su-subject message))
6961 (author (vm-su-full-name message))
6962 (message-id (vm-su-message-id message)))
6963 (setq folder (abbreviate-file-name folder))
6964 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
6965 folder)
6966 (setq folder (replace-match "" t t folder)))
6967 (setq cpltxt (concat author " on: " subject))
6968 (setq link (concat cpltxt "\n "
6969 (org-make-link
6970 "vm:" folder "#" message-id))))))
6971
6972 ((eq major-mode 'wl-summary-mode)
6973 (let* ((msgnum (wl-summary-message-number))
6974 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
6975 msgnum 'message-id))
6976 (wl-message-entity (elmo-msgdb-overview-get-entity
6977 msgnum (wl-summary-buffer-msgdb)))
6978 (author (wl-summary-line-from)) ; FIXME: how to get author name?
6979 (subject "???")) ; FIXME: How to get subject of email?
6980 (setq cpltxt (concat author " on: " subject))
6981 (setq link (concat cpltxt "\n "
6982 (org-make-link
6983 "wl:" wl-summary-buffer-folder-name
6984 "#" message-id)))))
6985
6986 ((eq major-mode 'rmail-mode)
6987 (save-excursion
6988 (save-restriction
6989 (rmail-narrow-to-non-pruned-header)
6990 (let ((folder (buffer-file-name))
6991 (message-id (mail-fetch-field "message-id"))
6992 (author (mail-fetch-field "from"))
6993 (subject (mail-fetch-field "subject")))
6994 (setq cpltxt (concat author " on: " subject))
6995 (setq link (concat cpltxt "\n "
6996 (org-make-link
6997 "rmail:" folder "#" message-id)))))))
6998
6999 ((eq major-mode 'gnus-group-mode)
7000 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7001 (gnus-group-group-name)) ; version
7002 ((fboundp 'gnus-group-name)
7003 (gnus-group-name))
7004 (t "???"))))
7005 (setq cpltxt (concat
7006 (if (org-xor arg org-usenet-links-prefer-google)
7007 "http://groups.google.com/groups?group="
7008 "gnus:")
7009 group)
7010 link (org-make-link cpltxt))))
7011
7012 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7013 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7014 (gnus-summary-beginning-of-article)
7015 (let* ((group (car gnus-article-current))
7016 (article (cdr gnus-article-current))
7017 (header (gnus-summary-article-header article))
7018 (author (mail-header-from header))
7019 (message-id (mail-header-id header))
7020 (date (mail-header-date header))
7021 (subject (gnus-summary-subject-string)))
7022 (setq cpltxt (concat author " on: " subject))
7023 (if (org-xor arg org-usenet-links-prefer-google)
7024 (setq link
7025 (concat
7026 cpltxt "\n "
7027 (format "http://groups.google.com/groups?as_umsgid=%s"
7028 (org-fixup-message-id-for-http message-id))))
7029 (setq link (concat cpltxt "\n"
7030 (org-make-link
7031 "gnus:" group
7032 "#" (number-to-string article)))))))
7033
7034 ((eq major-mode 'w3-mode)
7035 (setq cpltxt (url-view-url t)
7036 link (org-make-link cpltxt)))
7037 ((eq major-mode 'w3m-mode)
7038 (setq cpltxt w3m-current-url
7039 link (org-make-link cpltxt)))
7040
7041 ((eq major-mode 'org-mode)
7042 ;; Just link to current headline
7043 (setq cpltxt (concat "file:"
7044 (abbreviate-file-name (buffer-file-name))))
7045 ;; Add a context search string
7046 (when (org-xor org-context-in-file-links arg)
7047 (if (save-excursion
7048 (skip-chars-backward "a-zA-Z<")
7049 (looking-at (concat "<<\\(" org-camel-regexp "\\)>>")))
7050 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7051 (setq cpltxt
7052 (concat cpltxt "::"
7053 (org-make-org-heading-camel
7054 (cond
7055 ((org-on-heading-p) nil)
7056 ((org-region-active-p)
7057 (buffer-substring (region-beginning) (region-end)))
7058 (t (buffer-substring (point-at-bol) (point-at-eol))))
7059 )))))
7060 (setq link (org-make-link cpltxt)))
7061
7062 ((buffer-file-name)
7063 ;; Just link to this file here.
7064 (setq cpltxt (concat "file:"
7065 (abbreviate-file-name (buffer-file-name))))
7066 ;; Add a context string
7067 (when (org-xor org-context-in-file-links arg)
7068 (setq cpltxt
7069 (concat cpltxt "::"
7070 (org-make-org-heading-camel
7071 (if (org-region-active-p)
7072 (buffer-substring (region-beginning) (region-end))
7073 (buffer-substring (point-at-bol) (point-at-eol)))))))
7074 (setq link (org-make-link cpltxt)))
7075
7076 ((interactive-p)
7077 (error "Cannot link to a buffer which is not visiting a file"))
7078
7079 (t (setq link nil)))
7080
7081 (if (and (interactive-p) link)
7082 (progn
7083 (setq org-stored-links
7084 (cons (cons (or cpltxt link) link) org-stored-links))
7085 (message "Stored: %s" (or cpltxt link)))
7086 link)))
7087
7088 (defun org-make-org-heading-camel (&optional string)
7089 "Make a CamelCase string for S or the current headline."
7090 (interactive)
7091 (let ((s (or string (org-get-heading))))
7092 (unless string
7093 ;; We are using a headline, clean up garbage in there.
7094 (if (string-match org-todo-regexp s)
7095 (setq s (replace-match "" t t s)))
7096 (setq s (org-trim s))
7097 (if (string-match (concat "^\\(" org-quote-string "\\|"
7098 org-comment-string "\\)") s)
7099 (setq s (replace-match "" t t s)))
7100 (while (string-match org-ts-regexp s)
7101 (setq s (replace-match "" t t s))))
7102 (while (string-match "[^a-zA-Z_ \t]+" s)
7103 (setq s (replace-match " " t t s)))
7104 (or string (setq s (concat "*" s))) ; Add * for headlines
7105 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7106
7107 (defun org-make-link (&rest strings)
7108 "Concatenate STRINGS, format resulting string with `org-link-format'."
7109 (format org-link-format (apply 'concat strings)))
7110
7111 (defun org-xor (a b)
7112 "Exclusive or."
7113 (if a (not b) b))
7114
7115 (defun org-get-header (header)
7116 "Find a header field in the current buffer."
7117 (save-excursion
7118 (goto-char (point-min))
7119 (let ((case-fold-search t) s)
7120 (cond
7121 ((eq header 'from)
7122 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7123 (setq s (match-string 1)))
7124 (while (string-match "\"" s)
7125 (setq s (replace-match "" t t s)))
7126 (if (string-match "[<(].*" s)
7127 (setq s (replace-match "" t t s))))
7128 ((eq header 'message-id)
7129 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7130 (setq s (match-string 1))))
7131 ((eq header 'subject)
7132 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7133 (setq s (match-string 1)))))
7134 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7135 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7136 s)))
7137
7138
7139 (defun org-fixup-message-id-for-http (s)
7140 "Replace special characters in a message id, so it can be used in an http query."
7141 (while (string-match "<" s)
7142 (setq s (replace-match "%3C" t t s)))
7143 (while (string-match ">" s)
7144 (setq s (replace-match "%3E" t t s)))
7145 (while (string-match "@" s)
7146 (setq s (replace-match "%40" t t s)))
7147 s)
7148
7149 (defun org-insert-link (&optional complete-file)
7150 "Insert a link. At the prompt, enter the link.
7151
7152 Completion can be used to select a link previously stored with
7153 `org-store-link'. When the empty string is entered (i.e. if you just
7154 press RET at the prompt), the link defaults to the most recently
7155 stored link. As SPC triggers completion in the minibuffer, you need to
7156 use M-SPC or C-q SPC to force the insertion of a space character.
7157
7158 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7159 selected using completion. The path to the file will be relative to
7160 the current directory if the file is in the current directory or a
7161 subdirectory. Otherwise, the link will be the absolute path as
7162 completed in the minibuffer (i.e. normally ~/path/to/file).
7163
7164 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7165 is in the current directory or below."
7166 (interactive "P")
7167 (let ((link (if complete-file
7168 (read-file-name "File: ")
7169 (completing-read
7170 "Link: " org-stored-links nil nil nil
7171 org-insert-link-history
7172 (or (car (car org-stored-links))))))
7173 linktxt matched)
7174 (if (or (not link) (equal link ""))
7175 (error "No links available"))
7176 (if complete-file
7177 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7178 (cond
7179 ((equal complete-file '(16))
7180 (insert
7181 (org-make-link
7182 "file:" (abbreviate-file-name (expand-file-name link)))))
7183 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7184 (expand-file-name link))
7185 (insert
7186 (org-make-link
7187 "file:" (match-string 1 (expand-file-name link)))))
7188 (t (insert (org-make-link "file:" link)))))
7189 (setq linktxt (cdr (assoc link org-stored-links)))
7190 (if (not org-keep-stored-link-after-insertion)
7191 (setq org-stored-links (delq (assoc link org-stored-links)
7192 org-stored-links)))
7193 (if (not linktxt) (setq link (org-make-link link)))
7194 (setq link (or linktxt link))
7195 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7196 (let* ((path (match-string 1 link))
7197 (case-fold-search nil)
7198 (search (match-string 2 link)))
7199 (when (save-match-data
7200 (equal (file-truename (buffer-file-name))
7201 (file-truename path)))
7202 (if (save-match-data
7203 (string-match (concat "^" org-camel-regexp "$") search))
7204 (setq link (replace-match search t t link)
7205 matched t)
7206 (setq link (replace-match (concat "<file:::" search ">")
7207 t t link))))))
7208 (let ((lines (org-split-string link "\n")))
7209 (insert (car lines))
7210 (setq matched (or matched (string-match org-link-regexp (car lines))))
7211 (setq lines (cdr lines))
7212 (while lines
7213 (insert "\n")
7214 (if (save-excursion
7215 (beginning-of-line 0)
7216 (looking-at "[ \t]+\\S-"))
7217 (indent-relative))
7218 (setq matched (or matched
7219 (string-match org-link-regexp (car lines))))
7220 (insert (car lines))
7221 (setq lines (cdr lines))))
7222 (unless matched
7223 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7224
7225 ;;; Hooks for remember.el
7226 ;;;###autoload
7227 (defun org-remember-annotation ()
7228 "Return a link to the current location as an annotation for remember.el.
7229 If you are using Org-mode files as target for data storage with
7230 remember.el, then the annotations should include a link compatible with the
7231 conventions in Org-mode. This function returns such a link."
7232 (org-store-link nil))
7233
7234 (defconst org-remember-help
7235 "Select a destination location for the note.
7236 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7237 RET at beg-of-buf -> Append to file as level 2 headline
7238 RET on headline -> Store as sublevel entry to current headline
7239 <left>/<right> -> before/after current headline, same headings level")
7240
7241 ;;;###autoload
7242 (defun org-remember-handler ()
7243 "Store stuff from remember.el into an org file.
7244 First prompts for an org file. If the user just presses return, the value
7245 of `org-default-notes-file' is used.
7246 Then the command offers the headings tree of the selected file in order to
7247 file the text at a specific location.
7248 You can either immediately press RET to get the note appended to the
7249 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
7250 find a better place. Then press RET or <left> or <right> in insert the note.
7251
7252 Key Cursor position Note gets inserted
7253 -----------------------------------------------------------------------------
7254 RET buffer-start as level 2 heading at end of file
7255 RET on headline as sublevel of the heading at cursor
7256 RET no heading at cursor position, level taken from context.
7257 Or use prefix arg to specify level manually.
7258 <left> on headline as same level, before current heading
7259 <right> on headline as same level, after current heading
7260
7261 So the fastest way to store the note is to press RET RET to append it to
7262 the default file. This way your current train of thought is not
7263 interrupted, in accordance with the principles of remember.el. But with
7264 little extra effort, you can push it directly to the correct location.
7265
7266 Before being stored away, the function ensures that the text has a
7267 headline, i.e. a first line that starts with a \"*\". If not, a headline
7268 is constructed from the current date and some additional data.
7269
7270 If the variable `org-adapt-indentation' is non-nil, the entire text is
7271 also indented so that it starts in the same column as the headline
7272 \(i.e. after the stars).
7273
7274 See also the variable `org-reverse-note-order'."
7275 (catch 'quit
7276 (let* ((txt (buffer-substring (point-min) (point-max)))
7277 (fastp current-prefix-arg)
7278 (file (if fastp org-default-notes-file (org-get-org-file)))
7279 (visiting (find-buffer-visiting file))
7280 (org-startup-with-deadline-check nil)
7281 (org-startup-folded nil)
7282 spos level indent reversed)
7283 ;; Modify text so that it becomes a nice subtree which can be inserted
7284 ;; into an org tree.
7285 (let* ((lines (split-string txt "\n"))
7286 (first (car lines))
7287 (lines (cdr lines)))
7288 (if (string-match "^\\*+" first)
7289 ;; Is already a headline
7290 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7291 -1) ?\ ))
7292 ;; We need to add a headline: Use time and first buffer line
7293 (setq lines (cons first lines)
7294 first (concat "* " (current-time-string)
7295 " (" (remember-buffer-desc) ")")
7296 indent " "))
7297 (if org-adapt-indentation
7298 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7299 (setq txt (concat first "\n"
7300 (mapconcat 'identity lines "\n"))))
7301 ;; Find the file
7302 (if (not visiting)
7303 (find-file-noselect file))
7304 (with-current-buffer (get-file-buffer file)
7305 (setq reversed (org-notes-order-reversed-p))
7306 (save-excursion
7307 (save-restriction
7308 (widen)
7309 ;; Ask the User for a location
7310 (setq spos (if fastp 1 (org-get-location
7311 (current-buffer)
7312 org-remember-help)))
7313 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7314 ; not handle this note
7315 (goto-char spos)
7316 (cond ((bobp)
7317 ;; Put it at the start or end, as level 2
7318 (save-restriction
7319 (widen)
7320 (goto-char (if reversed (point-min) (point-max)))
7321 (if (not (bolp)) (newline))
7322 (org-paste-subtree (or current-prefix-arg 2) txt)))
7323 ((and (org-on-heading-p nil) (not current-prefix-arg))
7324 ;; Put it below this entry, at the beg/end of the subtree
7325 (org-back-to-heading)
7326 (setq level (outline-level))
7327 (if reversed
7328 (outline-end-of-heading)
7329 (outline-end-of-subtree))
7330 (if (not (bolp)) (newline))
7331 (beginning-of-line 1)
7332 (org-paste-subtree (1+ level) txt))
7333 (t
7334 ;; Put it right there, with automatic level determined by
7335 ;; org-paste-subtree or from prefix arg
7336 (org-paste-subtree current-prefix-arg txt)))
7337 (when remember-save-after-remembering
7338 (save-buffer)
7339 (if (not visiting) (kill-buffer (current-buffer)))))))))
7340 t) ;; return t to indicate that we took care of this note.
7341
7342 (defun org-get-org-file ()
7343 "Read a filename, with default directory `org-directory'."
7344 (let ((default (or org-default-notes-file remember-data-file)))
7345 (read-file-name (format "File name [%s]: " default)
7346 (file-name-as-directory org-directory)
7347 default)))
7348
7349 (defun org-notes-order-reversed-p ()
7350 "Check if the current file should receive notes in reversed order."
7351 (cond
7352 ((not org-reverse-note-order) nil)
7353 ((eq t org-reverse-note-order) t)
7354 ((not (listp org-reverse-note-order)) nil)
7355 (t (catch 'exit
7356 (let ((all org-reverse-note-order)
7357 entry)
7358 (while (setq entry (pop all))
7359 (if (string-match (car entry) (buffer-file-name))
7360 (throw 'exit (cdr entry))))
7361 nil)))))
7362
7363 ;;; Tables
7364
7365 ;; Watch out: Here we are talking about two different kind of tables.
7366 ;; Most of the code is for the tables created with the Org-mode table editor.
7367 ;; Sometimes, we talk about tables created and edited with the table.el
7368 ;; Emacs package. We call the former org-type tables, and the latter
7369 ;; table.el-type tables.
7370
7371
7372 (defun org-before-change-function (beg end)
7373 "Every change indicates that a table might need an update."
7374 (setq org-table-may-need-update t))
7375
7376 (defconst org-table-line-regexp "^[ \t]*|"
7377 "Detects an org-type table line.")
7378 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7379 "Detects an org-type table line.")
7380 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7381 "Detects a table line marked for automatic recalculation.")
7382 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7383 "Detects a table line marked for automatic recalculation.")
7384 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7385 "Detects a table line marked for automatic recalculation.")
7386 (defconst org-table-hline-regexp "^[ \t]*|-"
7387 "Detects an org-type table hline.")
7388 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7389 "Detects a table-type table hline.")
7390 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7391 "Detects an org-type or table-type table.")
7392 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7393 "Searching from within a table (any type) this finds the first line
7394 outside the table.")
7395 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7396 "Searching from within a table (any type) this finds the first line
7397 outside the table.")
7398
7399 (defun org-table-create-with-table.el ()
7400 "Use the table.el package to insert a new table.
7401 If there is already a table at point, convert between Org-mode tables
7402 and table.el tables."
7403 (interactive)
7404 (require 'table)
7405 (cond
7406 ((org-at-table.el-p)
7407 (if (y-or-n-p "Convert table to Org-mode table? ")
7408 (org-table-convert)))
7409 ((org-at-table-p)
7410 (if (y-or-n-p "Convert table to table.el table? ")
7411 (org-table-convert)))
7412 (t (call-interactively 'table-insert))))
7413
7414 (defun org-table-create (&optional size)
7415 "Query for a size and insert a table skeleton.
7416 SIZE is a string Columns x Rows like for example \"3x2\"."
7417 (interactive "P")
7418 (unless size
7419 (setq size (read-string
7420 (concat "Table size Columns x Rows [e.g. "
7421 org-table-default-size "]: ")
7422 "" nil org-table-default-size)))
7423
7424 (let* ((pos (point))
7425 (indent (make-string (current-column) ?\ ))
7426 (split (org-split-string size " *x *"))
7427 (rows (string-to-number (nth 1 split)))
7428 (columns (string-to-number (car split)))
7429 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7430 "\n")))
7431 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7432 (point-at-bol) (point)))
7433 (beginning-of-line 1)
7434 (newline))
7435 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7436 (dotimes (i rows) (insert line))
7437 (goto-char pos)
7438 (if (> rows 1)
7439 ;; Insert a hline after the first row.
7440 (progn
7441 (end-of-line 1)
7442 (insert "\n|-")
7443 (goto-char pos)))
7444 (org-table-align)))
7445
7446 (defun org-table-convert-region (beg0 end0 nspace)
7447 "Convert region to a table.
7448 The region goes from BEG0 to END0, but these borders will be moved
7449 slightly, to make sure a beginning of line in the first line is included.
7450 When NSPACE is non-nil, it indicates the minimum number of spaces that
7451 separate columns (default: just one space)"
7452 (let* ((beg (min beg0 end0))
7453 (end (max beg0 end0))
7454 (tabsep t)
7455 re)
7456 (goto-char beg)
7457 (beginning-of-line 1)
7458 (setq beg (move-marker (make-marker) (point)))
7459 (goto-char end)
7460 (if (bolp) (backward-char 1) (end-of-line 1))
7461 (setq end (move-marker (make-marker) (point)))
7462 ;; Lets see if this is tab-separated material. If every nonempty line
7463 ;; contains a tab, we will assume that it is tab-separated material
7464 (if nspace
7465 (setq tabsep nil)
7466 (goto-char beg)
7467 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7468 (if nspace (setq tabsep nil))
7469 (if tabsep
7470 (setq re "^\\|\t")
7471 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7472 (max 1 (prefix-numeric-value nspace)))))
7473 (goto-char beg)
7474 (while (re-search-forward re end t)
7475 (replace-match "|" t t))
7476 (goto-char beg)
7477 (insert " ")
7478 (org-table-align)))
7479
7480 (defun org-table-import (file arg)
7481 "Import FILE as a table.
7482 The file is assumed to be tab-separated. Such files can be produced by most
7483 spreadsheet and database applications. If no tabs (at least one per line)
7484 are found, lines will be split on whitespace into fields."
7485 (interactive "f\nP")
7486 (or (bolp) (newline))
7487 (let ((beg (point))
7488 (pm (point-max)))
7489 (insert-file-contents file)
7490 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7491
7492 (defun org-table-export ()
7493 "Export table as a tab-separated file.
7494 Such a file can be imported into a spreadsheet program like Excel."
7495 (interactive)
7496 (let* ((beg (org-table-begin))
7497 (end (org-table-end))
7498 (table (buffer-substring beg end))
7499 (file (read-file-name "Export table to: "))
7500 buf)
7501 (unless (or (not (file-exists-p file))
7502 (y-or-n-p (format "Overwrite file %s? " file)))
7503 (error "Abort"))
7504 (with-current-buffer (find-file-noselect file)
7505 (setq buf (current-buffer))
7506 (erase-buffer)
7507 (fundamental-mode)
7508 (insert table)
7509 (goto-char (point-min))
7510 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7511 (replace-match "" t t)
7512 (end-of-line 1))
7513 (goto-char (point-min))
7514 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7515 (replace-match "" t t)
7516 (goto-char (min (1+ (point)) (point-max))))
7517 (goto-char (point-min))
7518 (while (re-search-forward "^-[-+]*$" nil t)
7519 (replace-match "")
7520 (if (looking-at "\n")
7521 (delete-char 1)))
7522 (goto-char (point-min))
7523 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7524 (replace-match "\t" t t))
7525 (save-buffer))
7526 (kill-buffer buf)))
7527
7528 (defvar org-table-aligned-begin-marker (make-marker)
7529 "Marker at the beginning of the table last aligned.
7530 Used to check if cursor still is in that table, to minimize realignment.")
7531 (defvar org-table-aligned-end-marker (make-marker)
7532 "Marker at the end of the table last aligned.
7533 Used to check if cursor still is in that table, to minimize realignment.")
7534 (defvar org-table-last-alignment nil
7535 "List of flags for flushright alignment, from the last re-alignment.
7536 This is being used to correctly align a single field after TAB or RET.")
7537 ;; FIXME: The following is currently not used.
7538 (defvar org-table-last-column-widths nil
7539 "List of max width of fields in each column.
7540 This is being used to correctly align a single field after TAB or RET.")
7541
7542 (defvar org-last-recalc-line nil)
7543
7544 (defun org-table-align ()
7545 "Align the table at point by aligning all vertical bars."
7546 (interactive)
7547 ;; (message "align") (sit-for 2)
7548 (let* (
7549 ;; Limits of table
7550 (beg (org-table-begin))
7551 (end (org-table-end))
7552 ;; Current cursor position
7553 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7554 (colpos (org-table-current-column))
7555 (winstart (window-start))
7556 text lines (new "") lengths l typenums ty fields maxfields i
7557 column
7558 (indent "") cnt frac
7559 rfmt hfmt
7560 (spaces (if (org-in-invisibility-spec-p '(org-table))
7561 org-table-spaces-around-invisible-separators
7562 org-table-spaces-around-separators))
7563 (sp1 (car spaces))
7564 (sp2 (cdr spaces))
7565 (rfmt1 (concat
7566 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7567 (hfmt1 (concat
7568 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7569 emptystrings)
7570 (untabify beg end)
7571 ;; (message "Aligning table...")
7572 ;; Get the rows
7573 (setq lines (org-split-string
7574 (buffer-substring-no-properties beg end) "\n"))
7575 ;; Store the indentation of the first line
7576 (if (string-match "^ *" (car lines))
7577 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7578 ;; Mark the hlines
7579 (setq lines (mapcar (lambda (l)
7580 (if (string-match "^ *|-" l)
7581 nil
7582 (if (string-match "[ \t]+$" l)
7583 (substring l 0 (match-beginning 0))
7584 l)))
7585 lines))
7586 ;; Get the data fields
7587 (setq fields (mapcar
7588 (lambda (l)
7589 (org-split-string l " *| *"))
7590 (delq nil (copy-sequence lines))))
7591 ;; How many fields in the longest line?
7592 (condition-case nil
7593 (setq maxfields (apply 'max (mapcar 'length fields)))
7594 (error
7595 (kill-region beg end)
7596 (org-table-create org-table-default-size)
7597 (error "Empty table - created default table")))
7598 ;; A list of empty string to fill any short rows on output
7599 (setq emptystrings (make-list maxfields ""))
7600 ;; Get the maximum length of a field and the most common datatype
7601 ;; for each column
7602 (setq i -1)
7603 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7604 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7605 ;; maximum length
7606 (push (apply 'max 1 (mapcar 'string-width column)) lengths)
7607 ;; compute the fraction stepwise, ignoring empty fields
7608 (setq cnt 0 frac 0.0)
7609 (mapcar
7610 (lambda (x)
7611 (if (equal x "")
7612 nil
7613 (setq frac ( / (+ (* frac cnt)
7614 (if (string-match org-table-number-regexp x) 1 0))
7615 (setq cnt (1+ cnt))))))
7616 column)
7617 (push (>= frac org-table-number-fraction) typenums))
7618 (setq lengths (nreverse lengths)
7619 typenums (nreverse typenums))
7620 (setq org-table-last-alignment typenums
7621 org-table-last-column-widths lengths)
7622 ;; Compute the formats needed for output of the table
7623 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7624 (while (setq l (pop lengths))
7625 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7626 (setq rfmt (concat rfmt (format rfmt1 ty l))
7627 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7628 (setq rfmt (concat rfmt "\n")
7629 hfmt (concat (substring hfmt 0 -1) "|\n"))
7630 ;; Produce the new table
7631 ;;(while lines
7632 ;; (setq l (pop lines))
7633 ;; (if l
7634 ;; (setq new (concat new (apply 'format rfmt
7635 ;; (append (pop fields) emptystrings))))
7636 ;; (setq new (concat new hfmt))))
7637 (setq new (mapconcat
7638 (lambda (l)
7639 (if l (apply 'format rfmt
7640 (append (pop fields) emptystrings))
7641 hfmt))
7642 lines ""))
7643 ;; Replace the old one
7644 (delete-region beg end)
7645 (move-marker end nil)
7646 (move-marker org-table-aligned-begin-marker (point))
7647 (insert new)
7648 (move-marker org-table-aligned-end-marker (point))
7649 ;; Try to move to the old location (approximately)
7650 (goto-line linepos)
7651 (set-window-start (selected-window) winstart 'noforce)
7652 (org-table-goto-column colpos)
7653 (setq org-table-may-need-update nil)
7654 (if (org-in-invisibility-spec-p '(org-table))
7655 (org-table-add-invisible-to-vertical-lines))
7656 ))
7657
7658 (defun org-table-begin (&optional table-type)
7659 "Find the beginning of the table and return its position.
7660 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7661 (save-excursion
7662 (if (not (re-search-backward
7663 (if table-type org-table-any-border-regexp
7664 org-table-border-regexp)
7665 nil t))
7666 (error "Can't find beginning of table")
7667 (goto-char (match-beginning 0))
7668 (beginning-of-line 2)
7669 (point))))
7670
7671 (defun org-table-end (&optional table-type)
7672 "Find the end of the table and return its position.
7673 With argument TABLE-TYPE, go to the end of a table.el-type table."
7674 (save-excursion
7675 (if (not (re-search-forward
7676 (if table-type org-table-any-border-regexp
7677 org-table-border-regexp)
7678 nil t))
7679 (goto-char (point-max))
7680 (goto-char (match-beginning 0)))
7681 (point-marker)))
7682
7683 (defun org-table-justify-field-maybe (&optional new)
7684 "Justify the current field, text to left, number to right.
7685 Optional argument NEW may specify text to replace the current field content."
7686 (cond
7687 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7688 ((org-at-table-hline-p)
7689 ;; FIXME: I used to enforce realign here, but I think this is not needed.
7690 ;; (setq org-table-may-need-update t)
7691 )
7692 ((and (not new)
7693 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7694 (current-buffer)))
7695 (< (point) org-table-aligned-begin-marker)
7696 (>= (point) org-table-aligned-end-marker)))
7697 ;; This is not the same table, force a full re-align
7698 (setq org-table-may-need-update t))
7699 (t ;; realign the current field, based on previous full realign
7700 (let* ((pos (point)) s
7701 (col (org-table-current-column))
7702 (num (nth (1- col) org-table-last-alignment))
7703 l f n o e)
7704 (when (> col 0)
7705 (skip-chars-backward "^|\n")
7706 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7707 (progn
7708 (setq s (match-string 1)
7709 o (match-string 0)
7710 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7711 e (not (= (match-beginning 2) (match-end 2))))
7712 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7713 l (if e "|" (setq org-table-may-need-update t) ""))
7714 n (format f s t t))
7715 (if new
7716 (if (<= (length new) l)
7717 (setq n (format f new t t)) ;; FIXME: why t t?????
7718 (setq n (concat new "|") org-table-may-need-update t)))
7719 (or (equal n o)
7720 (let (org-table-may-need-update)
7721 (replace-match n))))
7722 (setq org-table-may-need-update t))
7723 (goto-char pos))))))
7724
7725 (defun org-table-next-field ()
7726 "Go to the next field in the current table, creating new lines as needed.
7727 Before doing so, re-align the table if necessary."
7728 (interactive)
7729 (org-table-maybe-eval-formula)
7730 (org-table-maybe-recalculate-line)
7731 (if (and org-table-automatic-realign
7732 org-table-may-need-update)
7733 (org-table-align))
7734 (let ((end (org-table-end)))
7735 (if (org-at-table-hline-p)
7736 (end-of-line 1))
7737 (condition-case nil
7738 (progn
7739 (re-search-forward "|" end)
7740 (if (looking-at "[ \t]*$")
7741 (re-search-forward "|" end))
7742 (if (and (looking-at "-")
7743 org-table-tab-jumps-over-hlines
7744 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7745 (goto-char (match-beginning 1)))
7746 (if (looking-at "-")
7747 (progn
7748 (beginning-of-line 0)
7749 (org-table-insert-row 'below))
7750 (if (looking-at " ") (forward-char 1))))
7751 (error
7752 (org-table-insert-row 'below)))))
7753
7754 (defun org-table-previous-field ()
7755 "Go to the previous field in the table.
7756 Before doing so, re-align the table if necessary."
7757 (interactive)
7758 (org-table-justify-field-maybe)
7759 (org-table-maybe-recalculate-line)
7760 (if (and org-table-automatic-realign
7761 org-table-may-need-update)
7762 (org-table-align))
7763 (if (org-at-table-hline-p)
7764 (end-of-line 1))
7765 (re-search-backward "|" (org-table-begin))
7766 (re-search-backward "|" (org-table-begin))
7767 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7768 (re-search-backward "|" (org-table-begin)))
7769 (if (looking-at "| ?")
7770 (goto-char (match-end 0))))
7771
7772 (defun org-table-next-row ()
7773 "Go to the next row (same column) in the current table.
7774 Before doing so, re-align the table if necessary."
7775 (interactive)
7776 (org-table-maybe-eval-formula)
7777 (org-table-maybe-recalculate-line)
7778 (if (or (looking-at "[ \t]*$")
7779 (save-excursion (skip-chars-backward " \t") (bolp)))
7780 (newline)
7781 (if (and org-table-automatic-realign
7782 org-table-may-need-update)
7783 (org-table-align))
7784 (let ((col (org-table-current-column)))
7785 (beginning-of-line 2)
7786 (if (or (not (org-at-table-p))
7787 (org-at-table-hline-p))
7788 (progn
7789 (beginning-of-line 0)
7790 (org-table-insert-row 'below)))
7791 (org-table-goto-column col)
7792 (skip-chars-backward "^|\n\r")
7793 (if (looking-at " ") (forward-char 1)))))
7794
7795 (defun org-table-copy-down (n)
7796 "Copy a field down in the current column.
7797 If the field at the cursor is empty, copy into it the content of the nearest
7798 non-empty field above. With argument N, use the Nth non-empty field.
7799 If the current field is not empty, it is copied down to the next row, and
7800 the cursor is moved with it. Therefore, repeating this command causes the
7801 column to be filled row-by-row.
7802 If the variable `org-table-copy-increment' is non-nil and the field is an
7803 integer, it will be incremented while copying."
7804 (interactive "p")
7805 (let* ((colpos (org-table-current-column))
7806 (field (org-table-get-field))
7807 (non-empty (string-match "[^ \t]" field))
7808 (beg (org-table-begin))
7809 txt)
7810 (org-table-check-inside-data-field)
7811 (if non-empty
7812 (progn
7813 (setq txt (org-trim field))
7814 (org-table-next-row)
7815 (org-table-blank-field))
7816 (save-excursion
7817 (setq txt
7818 (catch 'exit
7819 (while (progn (beginning-of-line 1)
7820 (re-search-backward org-table-dataline-regexp
7821 beg t))
7822 (org-table-goto-column colpos t)
7823 (if (and (looking-at
7824 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7825 (= (setq n (1- n)) 0))
7826 (throw 'exit (match-string 1))))))))
7827 (if txt
7828 (progn
7829 (if (and org-table-copy-increment
7830 (string-match "^[0-9]+$" txt))
7831 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7832 (insert txt)
7833 (org-table-maybe-recalculate-line)
7834 (org-table-align))
7835 (error "No non-empty field found"))))
7836
7837 (defun org-table-check-inside-data-field ()
7838 "Is point inside a table data field?
7839 I.e. not on a hline or before the first or after the last column?
7840 This actually throws an error, so it aborts the current command."
7841 (if (or (not (org-at-table-p))
7842 (= (org-table-current-column) 0)
7843 (org-at-table-hline-p)
7844 (looking-at "[ \t]*$"))
7845 (error "Not in table data field")))
7846
7847 (defvar org-table-clip nil
7848 "Clipboard for table regions.")
7849
7850 (defun org-table-blank-field ()
7851 "Blank the current table field or active region."
7852 (interactive)
7853 (org-table-check-inside-data-field)
7854 (if (and (interactive-p) (org-region-active-p))
7855 (let (org-table-clip)
7856 (org-table-cut-region (region-beginning) (region-end)))
7857 (skip-chars-backward "^|")
7858 (backward-char 1)
7859 (if (looking-at "|[^|\n]+")
7860 (let* ((pos (match-beginning 0))
7861 (match (match-string 0))
7862 (len (string-width match)))
7863 (replace-match (concat "|" (make-string (1- len) ?\ )))
7864 (goto-char (+ 2 pos))
7865 (substring match 1)))))
7866
7867 (defun org-table-get-field (&optional n replace)
7868 "Return the value of the field in column N of current row.
7869 N defaults to current field.
7870 If REPLACE is a string, replace field with this value. The return value
7871 is always the old value."
7872 (and n (org-table-goto-column n))
7873 (skip-chars-backward "^|\n")
7874 (backward-char 1)
7875 (if (looking-at "|[^|\r\n]*")
7876 (let* ((pos (match-beginning 0))
7877 (val (buffer-substring (1+ pos) (match-end 0))))
7878 (if replace
7879 (replace-match (concat "|" replace)))
7880 (goto-char (min (point-at-eol) (+ 2 pos)))
7881 val)
7882 (forward-char 1) ""))
7883
7884 (defun org-table-current-column ()
7885 "Find out which column we are in.
7886 When called interactively, column is also displayed in echo area."
7887 (interactive)
7888 (if (interactive-p) (org-table-check-inside-data-field))
7889 (save-excursion
7890 (let ((cnt 0) (pos (point)))
7891 (beginning-of-line 1)
7892 (while (search-forward "|" pos t)
7893 (setq cnt (1+ cnt)))
7894 (if (interactive-p) (message "This is table column %d" cnt))
7895 cnt)))
7896
7897 (defun org-table-goto-column (n &optional on-delim force)
7898 "Move the cursor to the Nth column in the current table line.
7899 With optional argument ON-DELIM, stop with point before the left delimiter
7900 of the field.
7901 If there are less than N fields, just go to after the last delimiter.
7902 However, when FORCE is non-nil, create new columns if necessary."
7903 (interactive "p")
7904 (let ((pos (point-at-eol)))
7905 (beginning-of-line 1)
7906 (when (> n 0)
7907 (while (and (> (setq n (1- n)) -1)
7908 (or (search-forward "|" pos t)
7909 (and force
7910 (progn (end-of-line 1)
7911 (skip-chars-backward "^|")
7912 (insert " | "))))))
7913 ; (backward-char 2) t)))))
7914 (when (and force (not (looking-at ".*|")))
7915 (save-excursion (end-of-line 1) (insert " | ")))
7916 (if on-delim
7917 (backward-char 1)
7918 (if (looking-at " ") (forward-char 1))))))
7919
7920 (defun org-at-table-p (&optional table-type)
7921 "Return t if the cursor is inside an org-type table.
7922 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7923 (if org-enable-table-editor
7924 (save-excursion
7925 (beginning-of-line 1)
7926 (looking-at (if table-type org-table-any-line-regexp
7927 org-table-line-regexp)))
7928 nil))
7929
7930 (defun org-at-table.el-p ()
7931 "Return t if and only if we are at a table.el table."
7932 (and (org-at-table-p 'any)
7933 (save-excursion
7934 (goto-char (org-table-begin 'any))
7935 (looking-at org-table1-hline-regexp))))
7936
7937 (defun org-table-recognize-table.el ()
7938 "If there is a table.el table nearby, recognize it and move into it."
7939 (if org-table-tab-recognizes-table.el
7940 (if (org-at-table.el-p)
7941 (progn
7942 (beginning-of-line 1)
7943 (if (looking-at org-table-dataline-regexp)
7944 nil
7945 (if (looking-at org-table1-hline-regexp)
7946 (progn
7947 (beginning-of-line 2)
7948 (if (looking-at org-table-any-border-regexp)
7949 (beginning-of-line -1)))))
7950 (if (re-search-forward "|" (org-table-end t) t)
7951 (progn
7952 (require 'table)
7953 (if (table--at-cell-p (point))
7954 t
7955 (message "recognizing table.el table...")
7956 (table-recognize-table)
7957 (message "recognizing table.el table...done")))
7958 (error "This should not happen..."))
7959 t)
7960 nil)
7961 nil))
7962
7963 (defun org-at-table-hline-p ()
7964 "Return t if the cursor is inside a hline in a table."
7965 (if org-enable-table-editor
7966 (save-excursion
7967 (beginning-of-line 1)
7968 (looking-at org-table-hline-regexp))
7969 nil))
7970
7971 (defun org-table-insert-column ()
7972 "Insert a new column into the table."
7973 (interactive)
7974 (if (not (org-at-table-p))
7975 (error "Not at a table"))
7976 (org-table-find-dataline)
7977 (let* ((col (max 1 (org-table-current-column)))
7978 (beg (org-table-begin))
7979 (end (org-table-end))
7980 ;; Current cursor position
7981 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7982 (colpos col))
7983 (goto-char beg)
7984 (while (< (point) end)
7985 (if (org-at-table-hline-p)
7986 nil
7987 (org-table-goto-column col t)
7988 (insert "| "))
7989 (beginning-of-line 2))
7990 (move-marker end nil)
7991 (goto-line linepos)
7992 (org-table-goto-column colpos)
7993 (org-table-align)
7994 (org-table-modify-formulas 'insert col)))
7995
7996 (defun org-table-find-dataline ()
7997 "Find a dataline in the current table, which is needed for column commands."
7998 (if (and (org-at-table-p)
7999 (not (org-at-table-hline-p)))
8000 t
8001 (let ((col (current-column))
8002 (end (org-table-end)))
8003 (move-to-column col)
8004 (while (and (< (point) end)
8005 (or (not (= (current-column) col))
8006 (org-at-table-hline-p)))
8007 (beginning-of-line 2)
8008 (move-to-column col))
8009 (if (and (org-at-table-p)
8010 (not (org-at-table-hline-p)))
8011 t
8012 (error
8013 "Please position cursor in a data line for column operations")))))
8014
8015 (defun org-table-delete-column ()
8016 "Delete a column into the table."
8017 (interactive)
8018 (if (not (org-at-table-p))
8019 (error "Not at a table"))
8020 (org-table-find-dataline)
8021 (org-table-check-inside-data-field)
8022 (let* ((col (org-table-current-column))
8023 (beg (org-table-begin))
8024 (end (org-table-end))
8025 ;; Current cursor position
8026 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8027 (colpos col))
8028 (goto-char beg)
8029 (while (< (point) end)
8030 (if (org-at-table-hline-p)
8031 nil
8032 (org-table-goto-column col t)
8033 (and (looking-at "|[^|\n]+|")
8034 (replace-match "|")))
8035 (beginning-of-line 2))
8036 (move-marker end nil)
8037 (goto-line linepos)
8038 (org-table-goto-column colpos)
8039 (org-table-align)
8040 (org-table-modify-formulas 'remove col)))
8041
8042 (defun org-table-move-column-right ()
8043 "Move column to the right."
8044 (interactive)
8045 (org-table-move-column nil))
8046 (defun org-table-move-column-left ()
8047 "Move column to the left."
8048 (interactive)
8049 (org-table-move-column 'left))
8050
8051 (defun org-table-move-column (&optional left)
8052 "Move the current column to the right. With arg LEFT, move to the left."
8053 (interactive "P")
8054 (if (not (org-at-table-p))
8055 (error "Not at a table"))
8056 (org-table-find-dataline)
8057 (org-table-check-inside-data-field)
8058 (let* ((col (org-table-current-column))
8059 (col1 (if left (1- col) col))
8060 (beg (org-table-begin))
8061 (end (org-table-end))
8062 ;; Current cursor position
8063 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8064 (colpos (if left (1- col) (1+ col))))
8065 (if (and left (= col 1))
8066 (error "Cannot move column further left"))
8067 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8068 (error "Cannot move column further right"))
8069 (goto-char beg)
8070 (while (< (point) end)
8071 (if (org-at-table-hline-p)
8072 nil
8073 (org-table-goto-column col1 t)
8074 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8075 (replace-match "|\\2|\\1|")))
8076 (beginning-of-line 2))
8077 (move-marker end nil)
8078 (goto-line linepos)
8079 (org-table-goto-column colpos)
8080 (org-table-align)
8081 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8082
8083 (defun org-table-move-row-down ()
8084 "move table row down."
8085 (interactive)
8086 (org-table-move-row nil))
8087 (defun org-table-move-row-up ()
8088 "move table row up."
8089 (interactive)
8090 (org-table-move-row 'up))
8091
8092 (defun org-table-move-row (&optional up)
8093 "Move the current table line down. With arg UP, move it up."
8094 (interactive "P")
8095 (let ((col (current-column))
8096 (pos (point))
8097 (tonew (if up 0 2))
8098 txt)
8099 (beginning-of-line tonew)
8100 (if (not (org-at-table-p))
8101 (progn
8102 (goto-char pos)
8103 (error "Cannot move row further")))
8104 (goto-char pos)
8105 (beginning-of-line 1)
8106 (setq pos (point))
8107 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8108 (delete-region (point) (1+ (point-at-eol)))
8109 (beginning-of-line tonew)
8110 (insert txt)
8111 (beginning-of-line 0)
8112 (move-to-column col)))
8113
8114 (defun org-table-insert-row (&optional arg)
8115 "Insert a new row above the current line into the table.
8116 With prefix ARG, insert below the current line."
8117 (interactive "P")
8118 (if (not (org-at-table-p))
8119 (error "Not at a table"))
8120 (let* ((line
8121 (org-expand-wide-chars
8122 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8123 new)
8124 (if (string-match "^[ \t]*|-" line)
8125 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8126 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8127 ;; Fix the first field if necessary
8128 (setq new (concat new))
8129 (if (string-match "^[ \t]*| *[#$] *|" line)
8130 (setq new (replace-match (match-string 0 line) t t new)))
8131 (beginning-of-line (if arg 2 1))
8132 (let (org-table-may-need-update)
8133 (insert-before-markers new)
8134 (insert-before-markers "\n"))
8135 (beginning-of-line 0)
8136 (re-search-forward "| ?" (point-at-eol) t)
8137 (and org-table-may-need-update (org-table-align))))
8138
8139 (defun org-table-insert-hline (&optional arg)
8140 "Insert a horizontal-line below the current line into the table.
8141 With prefix ARG, insert above the current line."
8142 (interactive "P")
8143 (if (not (org-at-table-p))
8144 (error "Not at a table"))
8145 (let ((line
8146 (org-expand-wide-chars
8147 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8148 (col (current-column))
8149 start)
8150 (if (string-match "^[ \t]*|-" line)
8151 (setq line
8152 (mapcar (lambda (x) (if (member x '(?| ?+))
8153 (prog1 (if start ?+ ?|) (setq start t))
8154 (if start ?- ?\ )))
8155 line))
8156 (setq line
8157 (mapcar (lambda (x) (if (equal x ?|)
8158 (prog1 (if start ?+ ?|) (setq start t))
8159 (if start ?- ?\ )))
8160 line)))
8161 (beginning-of-line (if arg 1 2))
8162 (apply 'insert line)
8163 (if (equal (char-before (point)) ?+)
8164 (progn (backward-delete-char 1) (insert "|")))
8165 (insert "\n")
8166 (beginning-of-line (if arg 1 -1))
8167 (move-to-column col)))
8168
8169 (defun org-expand-wide-chars (s)
8170 "Expand wide characters to spaces."
8171 (let (w a)
8172 (mapconcat
8173 (lambda (x)
8174 (if (> (setq w (string-width (setq a (char-to-string x)))) 1)
8175 (make-string w ?\ )
8176 a))
8177 s "")))
8178
8179 (defun org-table-kill-row ()
8180 "Delete the current row or horizontal line from the table."
8181 (interactive)
8182 (if (not (org-at-table-p))
8183 (error "Not at a table"))
8184 (let ((col (current-column)))
8185 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8186 (if (not (org-at-table-p)) (beginning-of-line 0))
8187 (move-to-column col)))
8188
8189 (defun org-table-sort-lines (beg end numericp)
8190 "Sort table lines in region.
8191 Point and mark define the first and last line to include. Both point and
8192 mark should be in the column that is used for sorting. For example, to
8193 sort according to column 3, put the mark in the first line to sort, in
8194 table column 3. Put point into the last line to be included in the sorting,
8195 also in table column 3. The command will prompt for the sorting method (n for
8196 numerical, a for alphanumeric)."
8197 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8198 (setq numericp (string-match "[nN]" numericp))
8199 (org-table-align) ;; Just to be safe
8200 (let* (bcol ecol cmp column lns)
8201 (goto-char beg)
8202 (org-table-check-inside-data-field)
8203 (setq column (org-table-current-column)
8204 beg (move-marker (make-marker) (point-at-bol)))
8205 (goto-char end)
8206 (org-table-check-inside-data-field)
8207 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8208 (untabify beg end)
8209 (goto-char beg)
8210 (org-table-goto-column column)
8211 (skip-chars-backward "^|")
8212 (setq bcol (current-column))
8213 (org-table-goto-column (1+ column))
8214 (skip-chars-backward "^|")
8215 (setq ecol (1- (current-column)))
8216 (setq cmp (if numericp
8217 (lambda (a b) (< (car a) (car b)))
8218 (lambda (a b) (string< (car a) (car b)))))
8219 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8220 (split-string (buffer-substring beg end) "\n")))
8221 (if numericp
8222 (setq lns (mapcar (lambda(x)
8223 (cons (string-to-number (car x)) (cdr x)))
8224 lns)))
8225 (delete-region beg end)
8226 (move-marker beg nil)
8227 (move-marker end nil)
8228 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8229 (message "%d lines sorted %s based on column %d"
8230 (length lns)
8231 (if numericp "numerically" "alphabetically") column)))
8232
8233 (defun org-table-cut-region (beg end)
8234 "Copy region in table to the clipboard and blank all relevant fields."
8235 (interactive "r")
8236 (org-table-copy-region beg end 'cut))
8237
8238 (defun org-table-copy-region (beg end &optional cut)
8239 "Copy rectangular region in table to clipboard.
8240 A special clipboard is used which can only be accessed
8241 with `org-table-paste-rectangle'"
8242 (interactive "rP")
8243 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8244 region cols
8245 (rpl (if cut " " nil)))
8246 (goto-char beg)
8247 (org-table-check-inside-data-field)
8248 (setq l01 (count-lines (point-min) (point))
8249 c01 (org-table-current-column))
8250 (goto-char end)
8251 (org-table-check-inside-data-field)
8252 (setq l02 (count-lines (point-min) (point))
8253 c02 (org-table-current-column))
8254 (setq l1 (min l01 l02) l2 (max l01 l02)
8255 c1 (min c01 c02) c2 (max c01 c02))
8256 (catch 'exit
8257 (while t
8258 (catch 'nextline
8259 (if (> l1 l2) (throw 'exit t))
8260 (goto-line l1)
8261 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8262 (setq cols nil ic1 c1 ic2 c2)
8263 (while (< ic1 (1+ ic2))
8264 (push (org-table-get-field ic1 rpl) cols)
8265 (setq ic1 (1+ ic1)))
8266 (push (nreverse cols) region)
8267 (setq l1 (1+ l1)))))
8268 (setq org-table-clip (nreverse region))
8269 (if cut (org-table-align))
8270 org-table-clip))
8271
8272 (defun org-table-paste-rectangle ()
8273 "Paste a rectangular region into a table.
8274 The upper right corner ends up in the current field. All involved fields
8275 will be overwritten. If the rectangle does not fit into the present table,
8276 the table is enlarged as needed. The process ignores horizontal separator
8277 lines."
8278 (interactive)
8279 (unless (and org-table-clip (listp org-table-clip))
8280 (error "First cut/copy a region to paste!"))
8281 (org-table-check-inside-data-field)
8282 (let* ((clip org-table-clip)
8283 (line (count-lines (point-min) (point)))
8284 (col (org-table-current-column))
8285 (org-enable-table-editor t)
8286 (org-table-automatic-realign nil)
8287 c cols field)
8288 (while (setq cols (pop clip))
8289 (while (org-at-table-hline-p) (beginning-of-line 2))
8290 (if (not (org-at-table-p))
8291 (progn (end-of-line 0) (org-table-next-field)))
8292 (setq c col)
8293 (while (setq field (pop cols))
8294 (org-table-goto-column c nil 'force)
8295 (org-table-get-field nil field)
8296 (setq c (1+ c)))
8297 (beginning-of-line 2))
8298 (goto-line line)
8299 (org-table-goto-column col)
8300 (org-table-align)))
8301
8302 (defun org-table-convert ()
8303 "Convert from `org-mode' table to table.el and back.
8304 Obviously, this only works within limits. When an Org-mode table is
8305 converted to table.el, all horizontal separator lines get lost, because
8306 table.el uses these as cell boundaries and has no notion of horizontal lines.
8307 A table.el table can be converted to an Org-mode table only if it does not
8308 do row or column spanning. Multiline cells will become multiple cells.
8309 Beware, Org-mode does not test if the table can be successfully converted - it
8310 blindly applies a recipe that works for simple tables."
8311 (interactive)
8312 (require 'table)
8313 (if (org-at-table.el-p)
8314 ;; convert to Org-mode table
8315 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8316 (end (move-marker (make-marker) (org-table-end t))))
8317 (table-unrecognize-region beg end)
8318 (goto-char beg)
8319 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8320 (replace-match ""))
8321 (goto-char beg))
8322 (if (org-at-table-p)
8323 ;; convert to table.el table
8324 (let ((beg (move-marker (make-marker) (org-table-begin)))
8325 (end (move-marker (make-marker) (org-table-end))))
8326 ;; first, get rid of all horizontal lines
8327 (goto-char beg)
8328 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8329 (replace-match ""))
8330 ;; insert a hline before first
8331 (goto-char beg)
8332 (org-table-insert-hline 'above)
8333 (beginning-of-line -1)
8334 ;; insert a hline after each line
8335 (while (progn (beginning-of-line 3) (< (point) end))
8336 (org-table-insert-hline))
8337 (goto-char beg)
8338 (setq end (move-marker end (org-table-end)))
8339 ;; replace "+" at beginning and ending of hlines
8340 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8341 (replace-match "\\1+-"))
8342 (goto-char beg)
8343 (while (re-search-forward "-|[ \t]*$" end t)
8344 (replace-match "-+"))
8345 (goto-char beg)))))
8346
8347 (defun org-table-wrap-region (arg)
8348 "Wrap several fields in a column like a paragraph.
8349 This is useful if you'd like to spread the contents of a field over several
8350 lines, in order to keep the table compact.
8351
8352 If there is an active region, and both point and mark are in the same column,
8353 the text in the column is wrapped to minimum width for the given number of
8354 lines. Generally, this makes the table more compact. A prefix ARG may be
8355 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8356 formats the selected text to two lines. If the region was longer than 2
8357 lines, the remaining lines remain empty. A negative prefix argument reduces
8358 the current number of lines by that amount. The wrapped text is pasted back
8359 into the table. If you formatted it to more lines than it was before, fields
8360 further down in the table get overwritten - so you might need to make space in
8361 the table first.
8362
8363 If there is no region, the current field is split at the cursor position and
8364 the text fragment to the right of the cursor is prepended to the field one
8365 line down.
8366
8367 If there is no region, but you specify a prefix ARG, the current field gets
8368 blank, and the content is appended to the field above."
8369 (interactive "P")
8370 (org-table-check-inside-data-field)
8371 (if (org-region-active-p)
8372 ;; There is a region: fill as a paragraph
8373 (let ((beg (region-beginning))
8374 nlines)
8375 (org-table-cut-region (region-beginning) (region-end))
8376 (if (> (length (car org-table-clip)) 1)
8377 (error "Region must be limited to single column"))
8378 (setq nlines (if arg
8379 (if (< arg 1)
8380 (+ (length org-table-clip) arg)
8381 arg)
8382 (length org-table-clip)))
8383 (setq org-table-clip
8384 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8385 nil nlines)))
8386 (goto-char beg)
8387 (org-table-paste-rectangle))
8388 ;; No region, split the current field at point
8389 (if arg
8390 ;; combine with field above
8391 (let ((s (org-table-blank-field))
8392 (col (org-table-current-column)))
8393 (beginning-of-line 0)
8394 (while (org-at-table-hline-p) (beginning-of-line 0))
8395 (org-table-goto-column col)
8396 (skip-chars-forward "^|")
8397 (skip-chars-backward " ")
8398 (insert " " (org-trim s))
8399 (org-table-align))
8400 ;; split field
8401 (when (looking-at "\\([^|]+\\)+|")
8402 (let ((s (match-string 1)))
8403 (replace-match " |")
8404 (goto-char (match-beginning 0))
8405 (org-table-next-row)
8406 (insert (org-trim s) " ")
8407 (org-table-align))))))
8408
8409 (defun org-trim (s)
8410 "Remove whitespace at beginning and end of string."
8411 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8412 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8413 s)
8414
8415 (defun org-wrap (string &optional width lines)
8416 "Wrap string to either a number of lines, or a width in characters.
8417 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8418 that costs. If there is a word longer than WIDTH, the text is actually
8419 wrapped to the length of that word.
8420 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8421 many lines, whatever width that takes.
8422 The return value is a list of lines, without newlines at the end."
8423 (let* ((words (org-split-string string "[ \t\n]+"))
8424 (maxword (apply 'max (mapcar 'string-width words)))
8425 w ll)
8426 (cond (width
8427 (org-do-wrap words (max maxword width)))
8428 (lines
8429 (setq w maxword)
8430 (setq ll (org-do-wrap words maxword))
8431 (if (<= (length ll) lines)
8432 ll
8433 (setq ll words)
8434 (while (> (length ll) lines)
8435 (setq w (1+ w))
8436 (setq ll (org-do-wrap words w)))
8437 ll))
8438 (t (error "Cannot wrap this")))))
8439
8440
8441 (defun org-do-wrap (words width)
8442 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8443 (let (lines line)
8444 (while words
8445 (setq line (pop words))
8446 (while (and words (< (+ (length line) (length (car words))) width))
8447 (setq line (concat line " " (pop words))))
8448 (setq lines (push line lines)))
8449 (nreverse lines)))
8450
8451 ;; FIXME: I think I can make this more efficient
8452 (defun org-split-string (string &optional separators)
8453 "Splits STRING into substrings at SEPARATORS.
8454 No empty strings are returned if there are matches at the beginning
8455 and end of string."
8456 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8457 (start 0)
8458 notfirst
8459 (list nil))
8460 (while (and (string-match rexp string
8461 (if (and notfirst
8462 (= start (match-beginning 0))
8463 (< start (length string)))
8464 (1+ start) start))
8465 (< (match-beginning 0) (length string)))
8466 (setq notfirst t)
8467 (or (eq (match-beginning 0) 0)
8468 (and (eq (match-beginning 0) (match-end 0))
8469 (eq (match-beginning 0) start))
8470 (setq list
8471 (cons (substring string start (match-beginning 0))
8472 list)))
8473 (setq start (match-end 0)))
8474 (or (eq start (length string))
8475 (setq list
8476 (cons (substring string start)
8477 list)))
8478 (nreverse list)))
8479
8480 (defun org-table-add-invisible-to-vertical-lines ()
8481 "Add an `invisible' property to vertical lines of current table."
8482 (interactive)
8483 (let* ((beg (org-table-begin))
8484 (end (org-table-end))
8485 (end1))
8486 (save-excursion
8487 (goto-char beg)
8488 (while (< (point) end)
8489 (setq end1 (point-at-eol))
8490 (if (looking-at org-table-dataline-regexp)
8491 (while (re-search-forward "|" end1 t)
8492 (add-text-properties (1- (point)) (point)
8493 '(invisible org-table)))
8494 (while (re-search-forward "[+|]" end1 t)
8495 (add-text-properties (1- (point)) (point)
8496 '(invisible org-table))))
8497 (beginning-of-line 2)))))
8498
8499 (defun org-table-toggle-vline-visibility (&optional arg)
8500 "Toggle the visibility of table vertical lines.
8501 The effect is immediate and on all tables in the file.
8502 With prefix ARG, make lines invisible when ARG is positive, make lines
8503 visible when ARG is not positive"
8504 (interactive "P")
8505 (let ((action (cond
8506 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
8507 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
8508 (t (if (org-in-invisibility-spec-p '(org-table))
8509 'off
8510 'on)))))
8511 (if (eq action 'off)
8512 (progn
8513 (org-remove-from-invisibility-spec '(org-table))
8514 (org-table-map-tables 'org-table-align)
8515 (message "Vertical table lines visible")
8516 (if (org-at-table-p)
8517 (org-table-align)))
8518 (org-add-to-invisibility-spec '(org-table))
8519 (org-table-map-tables 'org-table-align)
8520 (message "Vertical table lines invisible"))
8521 (redraw-frame (selected-frame))))
8522
8523 (defun org-table-map-tables (function)
8524 "Apply FUNCTION to the start of all tables in the buffer."
8525 (save-excursion
8526 (save-restriction
8527 (widen)
8528 (goto-char (point-min))
8529 (while (re-search-forward org-table-any-line-regexp nil t)
8530 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8531 (beginning-of-line 1)
8532 (if (looking-at org-table-line-regexp)
8533 (save-excursion (funcall function)))
8534 (re-search-forward org-table-any-border-regexp nil 1)))))
8535
8536 (defun org-table-sum (&optional beg end nlast)
8537 "Sum numbers in region of current table column.
8538 The result will be displayed in the echo area, and will be available
8539 as kill to be inserted with \\[yank].
8540
8541 If there is an active region, it is interpreted as a rectangle and all
8542 numbers in that rectangle will be summed. If there is no active
8543 region and point is located in a table column, sum all numbers in that
8544 column.
8545
8546 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8547 numbers are assumed to be times as well (in decimal hours) and the
8548 numbers are added as such.
8549
8550 If NLAST is a number, only the NLAST fields will actually be summed."
8551 (interactive)
8552 (save-excursion
8553 (let (col (timecnt 0) diff h m s org-table-clip)
8554 (cond
8555 ((and beg end)) ; beg and end given explicitly
8556 ((org-region-active-p)
8557 (setq beg (region-beginning) end (region-end)))
8558 (t
8559 (setq col (org-table-current-column))
8560 (goto-char (org-table-begin))
8561 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8562 (error "No table data"))
8563 (org-table-goto-column col)
8564 ;not needed? (skip-chars-backward "^|")
8565 (setq beg (point))
8566 (goto-char (org-table-end))
8567 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8568 (error "No table data"))
8569 (org-table-goto-column col)
8570 ;not needed? (skip-chars-forward "^|")
8571 (setq end (point))))
8572 (let* ((items (apply 'append (org-table-copy-region beg end)))
8573 (items1 (cond ((not nlast) items)
8574 ((>= nlast (length items)) items)
8575 (t (setq items (reverse items))
8576 (setcdr (nthcdr (1- nlast) items) nil)
8577 (nreverse items))))
8578 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8579 items1)))
8580 (res (apply '+ numbers))
8581 (sres (if (= timecnt 0)
8582 (format "%g" res)
8583 (setq diff (* 3600 res)
8584 h (floor (/ diff 3600)) diff (mod diff 3600)
8585 m (floor (/ diff 60)) diff (mod diff 60)
8586 s diff)
8587 (format "%d:%02d:%02d" h m s))))
8588 (kill-new sres)
8589 (if (interactive-p)
8590 (message "%s"
8591 (substitute-command-keys
8592 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8593 (length numbers) sres))))
8594 sres))))
8595
8596 (defun org-table-get-number-for-summing (s)
8597 (let (n)
8598 (if (string-match "^ *|? *" s)
8599 (setq s (replace-match "" nil nil s)))
8600 (if (string-match " *|? *$" s)
8601 (setq s (replace-match "" nil nil s)))
8602 (setq n (string-to-number s))
8603 (cond
8604 ((and (string-match "0" s)
8605 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8606 ((string-match "\\`[ \t]+\\'" s) nil)
8607 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8608 (let ((h (string-to-number (or (match-string 1 s) "0")))
8609 (m (string-to-number (or (match-string 2 s) "0")))
8610 (s (string-to-number (or (match-string 4 s) "0"))))
8611 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
8612 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8613 ((equal n 0) nil)
8614 (t n))))
8615
8616 (defun org-table-get-vertical-vector (desc &optional tbeg col)
8617 "Get a calc vector from a column, accorting to desctiptor DESC.
8618 Optional arguments TBEG and COL can give the beginning of the table and
8619 the current column, to avoid unnecessary parsing."
8620 (save-excursion
8621 (or tbeg (setq tbeg (org-table-begin)))
8622 (or col (setq col (org-table-current-column)))
8623 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
8624 (cond
8625 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
8626 (setq n1 (- (match-end 1) (match-beginning 1)))
8627 (if (match-beginning 3)
8628 (setq n2 (- (match-end 2) (match-beginning 3))))
8629 (setq n (if n2 (max n1 n2) n1))
8630 (setq n1 (if n2 (min n1 n2)))
8631 (setq nn n)
8632 (while (and (> nn 0)
8633 (re-search-backward org-table-hline-regexp tbeg t))
8634 (push (org-current-line) hline-list)
8635 (setq nn (1- nn)))
8636 (setq hline-list (nreverse hline-list))
8637 (goto-line (nth (1- n) hline-list))
8638 (when (re-search-forward org-table-dataline-regexp)
8639 (org-table-goto-column col)
8640 (setq beg (point)))
8641 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
8642 (when (re-search-backward org-table-dataline-regexp)
8643 (org-table-goto-column col)
8644 (setq end (point)))
8645 (setq l (apply 'append (org-table-copy-region beg end)))
8646 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
8647 (if (equal x "") "0" x))
8648 l ",") "]"))
8649 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
8650 (setq n1 (string-to-number (match-string 1 desc))
8651 n2 (string-to-number (match-string 2 desc)))
8652 (beginning-of-line 1)
8653 (save-excursion
8654 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
8655 (org-table-goto-column col)
8656 (setq beg (point))))
8657 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
8658 (org-table-goto-column col)
8659 (setq end (point)))
8660 (setq l (apply 'append (org-table-copy-region beg end)))
8661 (concat "[" (mapconcat
8662 (lambda (x) (setq x (org-trim x))
8663 (if (equal x "") "0" x))
8664 l ",") "]"))
8665 ((string-match "\\([0-9]+\\)" desc)
8666 (beginning-of-line 1)
8667 (when (re-search-backward org-table-dataline-regexp tbeg t
8668 (string-to-number (match-string 0 desc)))
8669 (org-table-goto-column col)
8670 (org-trim (org-table-get-field))))))))
8671
8672 (defvar org-table-formula-history nil)
8673
8674 (defvar org-table-column-names nil
8675 "Alist with column names, derived from the `!' line.")
8676 (defvar org-table-column-name-regexp nil
8677 "Regular expression matching the current column names.")
8678 (defvar org-table-local-parameters nil
8679 "Alist with parameter names, derived from the `$' line.")
8680 (defvar org-table-named-field-locations nil
8681 "Alist with locations of named fields.")
8682
8683 (defun org-table-get-formula (&optional equation named)
8684 "Read a formula from the minibuffer, offer stored formula as default."
8685 (let* ((name (car (rassoc (list (org-current-line)
8686 (org-table-current-column))
8687 org-table-named-field-locations)))
8688 (scol (if named
8689 (if name name
8690 (error "Not in a named field"))
8691 (int-to-string (org-table-current-column))))
8692 (dummy (and name (not named)
8693 (not (y-or-n-p "Replace named-field formula with column equation? " ))
8694 (error "Abort")))
8695 (org-table-may-need-update nil)
8696 (stored-list (org-table-get-stored-formulas))
8697 (stored (cdr (assoc scol stored-list)))
8698 (eq (cond
8699 ((and stored equation (string-match "^ *=? *$" equation))
8700 stored)
8701 ((stringp equation)
8702 equation)
8703 (t (read-string
8704 (format "%s formula $%s=" (if named "Field" "Column") scol)
8705 (or stored "") 'org-table-formula-history
8706 ;stored
8707 ))))
8708 mustsave)
8709 (when (not (string-match "\\S-" eq))
8710 ;; remove formula
8711 (setq stored-list (delq (assoc scol stored-list) stored-list))
8712 (org-table-store-formulas stored-list)
8713 (error "Formula removed"))
8714 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8715 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8716 (if (and name (not named))
8717 ;; We set the column equation, delete the named one.
8718 (setq stored-list (delq (assoc name stored-list) stored-list)
8719 mustsave t))
8720 (if stored
8721 (setcdr (assoc scol stored-list) eq)
8722 (setq stored-list (cons (cons scol eq) stored-list)))
8723 (if (or mustsave (not (equal stored eq)))
8724 (org-table-store-formulas stored-list))
8725 eq))
8726
8727 (defun org-table-store-formulas (alist)
8728 "Store the list of formulas below the current table."
8729 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
8730 (save-excursion
8731 (goto-char (org-table-end))
8732 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
8733 (delete-region (point) (match-end 0)))
8734 (insert "#+TBLFM: "
8735 (mapconcat (lambda (x)
8736 (concat "$" (car x) "=" (cdr x)))
8737 alist "::")
8738 "\n")))
8739
8740 (defun org-table-get-stored-formulas ()
8741 "Return an alist with the t=stored formulas directly after current table."
8742 (interactive)
8743 (let (scol eq eq-alist strings string seen)
8744 (save-excursion
8745 (goto-char (org-table-end))
8746 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8747 (setq strings (org-split-string (match-string 2) " *:: *"))
8748 (while (setq string (pop strings))
8749 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
8750 (setq scol (match-string 1 string)
8751 eq (match-string 2 string)
8752 eq-alist (cons (cons scol eq) eq-alist))
8753 (if (member scol seen)
8754 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8755 (push scol seen))))))
8756 (nreverse eq-alist)))
8757
8758 (defun org-table-modify-formulas (action &rest columns)
8759 "Modify the formulas stored below the current table.
8760 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
8761 expected, for the other action only a single column number is needed."
8762 (let ((list (org-table-get-stored-formulas))
8763 (nmax (length (org-split-string
8764 (buffer-substring (point-at-bol) (point-at-eol))
8765 "|")))
8766 col col1 col2 scol si sc1 sc2)
8767 (cond
8768 ((null list)) ; No action needed if there are no stored formulas
8769 ((eq action 'remove)
8770 (setq col (car columns)
8771 scol (int-to-string col))
8772 (org-table-replace-in-formulas list scol "INVALID")
8773 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
8774 (loop for i from (1+ col) upto nmax by 1 do
8775 (setq si (int-to-string i))
8776 (org-table-replace-in-formulas list si (int-to-string (1- i)))
8777 (if (assoc si list) (setcar (assoc si list)
8778 (int-to-string (1- i))))))
8779 ((eq action 'insert)
8780 (setq col (car columns))
8781 (loop for i from nmax downto col by 1 do
8782 (setq si (int-to-string i))
8783 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
8784 (if (assoc si list) (setcar (assoc si list)
8785 (int-to-string (1+ i))))))
8786 ((eq action 'swap)
8787 (setq col1 (car columns) col2 (nth 1 columns)
8788 sc1 (int-to-string col1) sc2 (int-to-string col2))
8789 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
8790 (org-table-replace-in-formulas list sc1 "ZqZ")
8791 (org-table-replace-in-formulas list sc2 sc1)
8792 (org-table-replace-in-formulas list "ZqZ" sc2)
8793 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
8794 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
8795 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
8796 (t (error "Invalid action in `org-table-modify-formulas'")))
8797 (if list (org-table-store-formulas list))))
8798
8799 (defun org-table-replace-in-formulas (list s1 s2)
8800 (let (elt re s)
8801 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
8802 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
8803 re (concat (regexp-quote s1) "\\>"))
8804 (while (setq elt (pop list))
8805 (setq s (cdr elt))
8806 (while (string-match re s)
8807 (setq s (replace-match s2 t t s)))
8808 (setcdr elt s))))
8809
8810 (defun org-table-get-specials ()
8811 "Get the column nmaes and local parameters for this table."
8812 (save-excursion
8813 (let ((beg (org-table-begin)) (end (org-table-end))
8814 names name fields fields1 field cnt c v line col)
8815 (setq org-table-column-names nil
8816 org-table-local-parameters nil
8817 org-table-named-field-locations nil)
8818 (goto-char beg)
8819 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8820 (setq names (org-split-string (match-string 1) " *| *")
8821 cnt 1)
8822 (while (setq name (pop names))
8823 (setq cnt (1+ cnt))
8824 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8825 (push (cons name (int-to-string cnt)) org-table-column-names))))
8826 (setq org-table-column-names (nreverse org-table-column-names))
8827 (setq org-table-column-name-regexp
8828 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8829 (goto-char beg)
8830 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8831 (setq fields (org-split-string (match-string 1) " *| *"))
8832 (while (setq field (pop fields))
8833 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8834 (push (cons (match-string 1 field) (match-string 2 field))
8835 org-table-local-parameters))))
8836 (goto-char beg)
8837 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8838 (setq c (match-string 1)
8839 fields (org-split-string (match-string 2) " *| *"))
8840 (save-excursion
8841 (beginning-of-line (if (equal c "_") 2 0))
8842 (setq line (org-current-line) col 1)
8843 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8844 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8845 (while (and fields1 (setq field (pop fields)))
8846 (setq v (pop fields1) col (1+ col))
8847 (when (and (stringp field) (stringp v)
8848 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8849 (push (cons field v) org-table-local-parameters)
8850 (push (list field line col) org-table-named-field-locations)))))))
8851
8852 (defun org-this-word ()
8853 ;; Get the current word
8854 (save-excursion
8855 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
8856 (end (progn (skip-chars-forward "^ \t\n") (point))))
8857 (buffer-substring-no-properties beg end))))
8858
8859 (defun org-table-maybe-eval-formula ()
8860 "Check if the current field starts with \"=\" or \":=\".
8861 If yes, store the formula and apply it."
8862 ;; We already know we are in a table. Get field will only return a formula
8863 ;; when appropriate. It might return a separator line, but no problem.
8864 (when org-table-formula-evaluate-inline
8865 (let* ((field (org-trim (or (org-table-get-field) "")))
8866 named eq)
8867 (when (string-match "^:?=\\(.*\\)" field)
8868 (setq named (equal (string-to-char field) ?:)
8869 eq (match-string 1 field))
8870 (if (fboundp 'calc-eval)
8871 (org-table-eval-formula (if named '(4) nil) eq))))))
8872
8873 (defvar org-recalc-commands nil
8874 "List of commands triggering the reccalculation of a line.
8875 Will be filled automatically during use.")
8876
8877 (defvar org-recalc-marks
8878 '((" " . "Unmarked: no special line, no automatic recalculation")
8879 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8880 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8881 ("!" . "Column name definition line. Reference in formula as $name.")
8882 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8883 ("_" . "Names for values in row below this one.")
8884 ("^" . "Names for values in row above this one.")))
8885
8886 (defun org-table-rotate-recalc-marks (&optional newchar)
8887 "Rotate the recalculation mark in the first column.
8888 If in any row, the first field is not consistent with a mark,
8889 insert a new column for the makers.
8890 When there is an active region, change all the lines in the region,
8891 after prompting for the marking character.
8892 After each change, a message will be displayed indication the meaning
8893 of the new mark."
8894 (interactive)
8895 (unless (org-at-table-p) (error "Not at a table"))
8896 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8897 (beg (org-table-begin))
8898 (end (org-table-end))
8899 (l (org-current-line))
8900 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8901 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8902 (have-col
8903 (save-excursion
8904 (goto-char beg)
8905 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8906 (col (org-table-current-column))
8907 (forcenew (car (assoc newchar org-recalc-marks)))
8908 epos new)
8909 (when l1
8910 (message "Change region to what mark? Type # * ! $ or SPC: ")
8911 (setq newchar (char-to-string (read-char-exclusive))
8912 forcenew (car (assoc newchar org-recalc-marks))))
8913 (if (and newchar (not forcenew))
8914 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8915 newchar))
8916 (if l1 (goto-line l1))
8917 (save-excursion
8918 (beginning-of-line 1)
8919 (unless (looking-at org-table-dataline-regexp)
8920 (error "Not at a table data line")))
8921 (unless have-col
8922 (org-table-goto-column 1)
8923 (org-table-insert-column)
8924 (org-table-goto-column (1+ col)))
8925 (setq epos (point-at-eol))
8926 (save-excursion
8927 (beginning-of-line 1)
8928 (org-table-get-field
8929 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8930 (concat " "
8931 (setq new (or forcenew
8932 (cadr (member (match-string 1) marks))))
8933 " ")
8934 " # ")))
8935 (if (and l1 l2)
8936 (progn
8937 (goto-line l1)
8938 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8939 (and (looking-at org-table-dataline-regexp)
8940 (org-table-get-field 1 (concat " " new " "))))
8941 (goto-line l1)))
8942 (if (not (= epos (point-at-eol))) (org-table-align))
8943 (goto-line l)
8944 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8945
8946 (defun org-table-maybe-recalculate-line ()
8947 "Recompute the current line if marked for it, and if we haven't just done it."
8948 (interactive)
8949 (and org-table-allow-automatic-line-recalculation
8950 (not (and (memq last-command org-recalc-commands)
8951 (equal org-last-recalc-line (org-current-line))))
8952 (save-excursion (beginning-of-line 1)
8953 (looking-at org-table-auto-recalculate-regexp))
8954 (fboundp 'calc-eval)
8955 (org-table-recalculate) t))
8956
8957 (defvar org-table-formula-debug nil
8958 "Non-nil means, debug table formulas.
8959 When nil, simply write \"#ERROR\" in corrupted fields.")
8960
8961 (defvar modes)
8962 (defsubst org-set-calc-mode (var &optional value)
8963 (if (stringp var)
8964 (setq var (assoc var '(("D" calc-angle-mode deg)
8965 ("R" calc-angle-mode rad)
8966 ("F" calc-prefer-frac t)
8967 ("S" calc-symbolic-mode t)))
8968 value (nth 2 var) var (nth 1 var)))
8969 (if (memq var modes)
8970 (setcar (cdr (memq var modes)) value)
8971 (cons var (cons value modes)))
8972 modes)
8973
8974 (defun org-table-eval-formula (&optional arg equation
8975 suppress-align suppress-const
8976 suppress-store)
8977 "Replace the table field value at the cursor by the result of a calculation.
8978
8979 This function makes use of Dave Gillespie's calc package, in my view the
8980 most exciting program ever written for GNU Emacs. So you need to have calc
8981 installed in order to use this function.
8982
8983 In a table, this command replaces the value in the current field with the
8984 result of a formula. It also installes the formula as the \"current\" column
8985 formula, by storing it in a special line below the table. When called
8986 with a `C-u' prefix, the current field must ba a named field, and the
8987 formula is installed as valid in only this specific field.
8988
8989 When called, the command first prompts for a formula, which is read in
8990 the minibuffer. Previously entered formulas are available through the
8991 history list, and the last used formula is offered as a default.
8992 These stored formulas are adapted correctly when moving, inserting, or
8993 deleting columns with the corresponding commands.
8994
8995 The formula can be any algebraic expression understood by the calc package.
8996 For details, see the Org-mode manual.
8997
8998 This function can also be called from Lisp programs and offers
8999 additional Arguments: EQUATION can be the formula to apply. If this
9000 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9001 used to speed-up recursive calls by by-passing unnecessary aligns.
9002 SUPPRESS-CONST suppresses the interpretation of constants in the
9003 formula, assuming that this has been done already outside the fuction.
9004 SUPPRESS-STORE means the formula should not be stored, either because
9005 it is already stored, or because it is a modified equation that should
9006 not overwrite the stored one."
9007 (interactive "P")
9008 (require 'calc)
9009 (org-table-check-inside-data-field)
9010 (org-table-get-specials)
9011 (let* (fields
9012 (ndown (if (integerp arg) arg 1))
9013 (org-table-automatic-realign nil)
9014 (case-fold-search nil)
9015 (down (> ndown 1))
9016 (formula (if (and equation suppress-store)
9017 equation
9018 (org-table-get-formula equation (equal arg '(4)))))
9019 (n0 (org-table-current-column))
9020 (modes (copy-sequence org-calc-default-modes))
9021 n form fmt x ev orig c)
9022 ;; Parse the format string. Since we have a lot of modes, this is
9023 ;; a lot of work. However, I think calc still uses most of the time.
9024 (if (string-match ";" formula)
9025 (let ((tmp (org-split-string formula ";")))
9026 (setq formula (car tmp)
9027 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9028 (nth 1 tmp)))
9029 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9030 (setq c (string-to-char (match-string 1 fmt))
9031 n (string-to-number (or (match-string 1 fmt) "")))
9032 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9033 (setq modes (org-set-calc-mode
9034 'calc-float-format
9035 (list (cdr (assoc c '((?n. float) (?f. fix)
9036 (?s. sci) (?e. eng))))
9037 n))))
9038 (setq fmt (replace-match "" t t fmt)))
9039 (while (string-match "[DRFS]" fmt)
9040 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9041 (setq fmt (replace-match "" t t fmt)))
9042 (unless (string-match "\\S-" fmt)
9043 (setq fmt nil))))
9044 (if (and (not suppress-const) org-table-formula-use-constants)
9045 (setq formula (org-table-formula-substitute-names formula)))
9046 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9047 (while (> ndown 0)
9048 (setq fields (org-split-string
9049 (buffer-substring
9050 (point-at-bol) (point-at-eol)) " *| *"))
9051 (if org-table-formula-numbers-only
9052 (setq fields (mapcar
9053 (lambda (x) (number-to-string (string-to-number x)))
9054 fields)))
9055 (setq ndown (1- ndown))
9056 (setq form (copy-sequence formula))
9057 ;; Insert the references to fields in same row
9058 (while (string-match "\\$\\([0-9]+\\)?" form)
9059 (setq n (if (match-beginning 1)
9060 (string-to-number (match-string 1 form))
9061 n0)
9062 x (nth (1- n) fields))
9063 (unless x (error "Invalid field specifier \"%s\""
9064 (match-string 0 form)))
9065 (if (equal x "") (setq x "0"))
9066 (setq form (replace-match (concat "(" x ")") t t form)))
9067 ;; Insert ranges in current column
9068 (while (string-match "\\&[-I0-9]+" form)
9069 (setq form (replace-match
9070 (save-match-data
9071 (org-table-get-vertical-vector (match-string 0 form)
9072 nil n0))
9073 t t form)))
9074 (setq ev (calc-eval (cons form modes)
9075 (if org-table-formula-numbers-only 'num)))
9076
9077 (when org-table-formula-debug
9078 (with-output-to-temp-buffer "*Help*"
9079 (princ (format "Substitution history of formula
9080 Orig: %s
9081 $xyz-> %s
9082 $1-> %s\n" orig formula form))
9083 (if (listp ev)
9084 (princ (format " %s^\nError: %s"
9085 (make-string (car ev) ?\-) (nth 1 ev)))
9086 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9087 ev (or fmt "NONE")
9088 (if fmt (format fmt (string-to-number ev)) ev)))))
9089 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9090 (unless (and (interactive-p) (not ndown))
9091 (unless (let (inhibit-redisplay)
9092 (y-or-n-p "Debugging Formula. Continue to next? "))
9093 (org-table-align)
9094 (error "Abort"))
9095 (delete-window (get-buffer-window "*Help*"))
9096 (message "")))
9097 (if (listp ev) (setq fmt nil ev "#ERROR"))
9098 (org-table-justify-field-maybe
9099 (if fmt (format fmt (string-to-number ev)) ev))
9100 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9101 (call-interactively 'org-return)
9102 (setq ndown 0)))
9103 (and down (org-table-maybe-recalculate-line))
9104 (or suppress-align (and org-table-may-need-update
9105 (org-table-align)))))
9106
9107 (defun org-table-recalculate (&optional all noalign)
9108 "Recalculate the current table line by applying all stored formulas."
9109 (interactive "P")
9110 (or (memq this-command org-recalc-commands)
9111 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9112 (unless (org-at-table-p) (error "Not at a table"))
9113 (org-table-get-specials)
9114 (let* ((eqlist (sort (org-table-get-stored-formulas)
9115 (lambda (a b) (string< (car a) (car b)))))
9116 (inhibit-redisplay t)
9117 (line-re org-table-dataline-regexp)
9118 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9119 (thiscol (org-table-current-column))
9120 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9121 ;; Insert constants in all formulas
9122 (setq eqlist
9123 (mapcar (lambda (x)
9124 (setcdr x (org-table-formula-substitute-names (cdr x)))
9125 x)
9126 eqlist))
9127 ;; Split the equation list
9128 (while (setq eq (pop eqlist))
9129 (if (<= (string-to-char (car eq)) ?9)
9130 (push eq eqlnum)
9131 (push eq eqlname)))
9132 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9133 (if all
9134 (progn
9135 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9136 (goto-char (setq beg (org-table-begin)))
9137 (if (re-search-forward org-table-calculate-mark-regexp end t)
9138 ;; This is a table with marked lines, only compute selected lines
9139 (setq line-re org-table-recalculate-regexp)
9140 ;; Move forward to the first non-header line
9141 (if (and (re-search-forward org-table-dataline-regexp end t)
9142 (re-search-forward org-table-hline-regexp end t)
9143 (re-search-forward org-table-dataline-regexp end t))
9144 (setq beg (match-beginning 0))
9145 nil))) ;; just leave beg where it is
9146 (setq beg (point-at-bol)
9147 end (move-marker (make-marker) (1+ (point-at-eol)))))
9148 (goto-char beg)
9149 (and all (message "Re-applying formulas to full table..."))
9150 (while (re-search-forward line-re end t)
9151 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9152 ;; Unprotected line, recalculate
9153 (and all (message "Re-applying formulas to full table...(line %d)"
9154 (setq cnt (1+ cnt))))
9155 (setq org-last-recalc-line (org-current-line))
9156 (setq eql eqlnum)
9157 (while (setq entry (pop eql))
9158 (goto-line org-last-recalc-line)
9159 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9160 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9161 (goto-line thisline)
9162 (org-table-goto-column thiscol)
9163 (or noalign (and org-table-may-need-update (org-table-align))
9164 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9165 ;; Now do the names fields
9166 (while (setq eq (pop eqlname))
9167 (setq name (car eq)
9168 a (assoc name org-table-named-field-locations))
9169 (when a
9170 (message "Re-applying formula to named field: %s" name)
9171 (goto-line (nth 1 a))
9172 (org-table-goto-column (nth 2 a))
9173 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9174 ;; back to initial position
9175 (goto-line thisline)
9176 (org-table-goto-column thiscol)
9177 (or noalign (and org-table-may-need-update (org-table-align))
9178 (and all (message "Re-applying formulas...done")))))
9179
9180 (defun org-table-formula-substitute-names (f)
9181 "Replace $const with values in string F."
9182 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9183 ;; First, check for column names
9184 (while (setq start (string-match org-table-column-name-regexp f start))
9185 (setq start (1+ start))
9186 (setq a (assoc (match-string 1 f) org-table-column-names))
9187 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9188 ;; Expand ranges to vectors
9189 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9190 (setq n1 (string-to-number (match-string 1 f))
9191 n2 (string-to-number (match-string 2 f))
9192 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9193 s (concat "[($" (number-to-string (1- nn1)) ")"))
9194 (loop for i from nn1 upto nn2 do
9195 (setq s (concat s ",($" (int-to-string i) ")")))
9196 (setq s (concat s "]"))
9197 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9198 (setq f (replace-match s t t f)))
9199 ;; Parameters and constants
9200 (setq start 0)
9201 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9202 (setq start (1+ start))
9203 (if (setq a (save-match-data
9204 (org-table-get-constant (match-string 1 f))))
9205 (setq f (replace-match (concat "(" a ")") t t f))))
9206 (if org-table-formula-debug
9207 (put-text-property 0 (length f) :orig-formula f1 f))
9208 f))
9209
9210 (defun org-table-get-constant (const)
9211 "Find the value for a parameter or constant in a formula.
9212 Parameters get priority."
9213 (or (cdr (assoc const org-table-local-parameters))
9214 (cdr (assoc const org-table-formula-constants))
9215 (and (fboundp 'constants-get) (constants-get const))
9216 "#UNDEFINED_NAME"))
9217
9218 (defvar org-edit-formulas-map (make-sparse-keymap))
9219 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9220 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9221 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9222
9223 (defvar org-pos)
9224 (defvar org-window-configuration)
9225
9226 (defun org-table-edit-formulas ()
9227 "Edit the formulas of the current table in a separate buffer."
9228 (interactive)
9229 (unless (org-at-table-p)
9230 (error "Not at a table"))
9231 (org-table-get-specials)
9232 (let ((eql (org-table-get-stored-formulas))
9233 (pos (move-marker (make-marker) (point)))
9234 (wc (current-window-configuration))
9235 entry loc s)
9236 (switch-to-buffer-other-window "*Edit Formulas*")
9237 (erase-buffer)
9238 (fundamental-mode)
9239 (set (make-local-variable 'org-pos) pos)
9240 (set (make-local-variable 'org-window-configuration) wc)
9241 (use-local-map org-edit-formulas-map)
9242 (setq s "# Edit formulas and finish with `C-c C-c'.
9243 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9244 # Use `C-c ?' to get information about $name at point.
9245 # To cancel editing, press `C-c C-q'.\n")
9246 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9247 (insert s)
9248 (while (setq entry (pop eql))
9249 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9250 (setq s (format "# Named formula, referring to column %d in line %d\n"
9251 (nth 2 loc) (nth 1 loc)))
9252 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9253 (insert s))
9254 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9255 (remove-text-properties 0 (length s) '(face nil) s)
9256 (insert s))
9257 (goto-char (point-min))
9258 (message "Edit formulas and finish with `C-c C-c'.")))
9259
9260 (defun org-show-variable ()
9261 "Show the location/value of the $ expression at point."
9262 (interactive)
9263 (let (var (pos org-pos) (win (selected-window)) e)
9264 (save-excursion
9265 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9266 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9267 (setq var (match-string 1))
9268 (error "No variable at point")))
9269 (cond
9270 ((setq e (assoc var org-table-named-field-locations))
9271 (switch-to-buffer-other-window (marker-buffer pos))
9272 (goto-line (nth 1 e))
9273 (org-table-goto-column (nth 2 e))
9274 (select-window win)
9275 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9276 ((setq e (assoc var org-table-column-names))
9277 (switch-to-buffer-other-window (marker-buffer pos))
9278 (goto-char pos)
9279 (goto-char (org-table-begin))
9280 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9281 (org-table-end) t)
9282 (progn
9283 (goto-char (match-beginning 1))
9284 (message "Named column (column %s)" (cdr e)))
9285 (error "Column name not found"))
9286 (select-window win))
9287 ((string-match "^[0-9]$" var)
9288 ;; column number
9289 (switch-to-buffer-other-window (marker-buffer pos))
9290 (goto-char pos)
9291 (goto-char (org-table-begin))
9292 (recenter 1)
9293 (if (re-search-forward org-table-dataline-regexp
9294 (org-table-end) t)
9295 (progn
9296 (goto-char (match-beginning 0))
9297 (org-table-goto-column (string-to-number var))
9298 (message "Column %s" var))
9299 (error "Column name not found"))
9300 (select-window win))
9301 ((setq e (assoc var org-table-local-parameters))
9302 (switch-to-buffer-other-window (marker-buffer pos))
9303 (goto-char pos)
9304 (goto-char (org-table-begin))
9305 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9306 (progn
9307 (goto-char (match-beginning 1))
9308 (message "Local parameter."))
9309 (error "Parameter not found"))
9310 (select-window win))
9311 (t
9312 (cond
9313 ((setq e (assoc var org-table-formula-constants))
9314 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9315 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9316 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9317 (t (error "Undefined name $%s" var)))))))
9318
9319 (defun org-finish-edit-formulas (&optional arg)
9320 "Parse the buffer for formula definitions and install them.
9321 With prefix ARG, apply the new formulas to the table."
9322 (interactive "P")
9323 (let ((pos org-pos) eql)
9324 (goto-char (point-min))
9325 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9326 (push (cons (match-string 1) (match-string 2)) eql))
9327 (set-window-configuration org-window-configuration)
9328 (select-window (get-buffer-window (marker-buffer pos)))
9329 (goto-char pos)
9330 (unless (org-at-table-p)
9331 (error "Lost table position - cannot install formulae"))
9332 (org-table-store-formulas eql)
9333 (move-marker pos nil)
9334 (kill-buffer "*Edit Formulas*")
9335 (if arg
9336 (org-table-recalculate 'all)
9337 (message "New formulas installed - press C-u C-c C-c to apply."))))
9338
9339 (defun org-abort-edit-formulas ()
9340 "Abort editing formulas, without installing the changes."
9341 (interactive)
9342 (let ((pos org-pos))
9343 (set-window-configuration org-window-configuration)
9344 (select-window (get-buffer-window (marker-buffer pos)))
9345 (goto-char pos)
9346 (message "Formula editing aborted without installing changes")))
9347
9348 ;;; The orgtbl minor mode
9349
9350 ;; Define a minor mode which can be used in other modes in order to
9351 ;; integrate the org-mode table editor.
9352
9353 ;; This is really a hack, because the org-mode table editor uses several
9354 ;; keys which normally belong to the major mode, for example the TAB and
9355 ;; RET keys. Here is how it works: The minor mode defines all the keys
9356 ;; necessary to operate the table editor, but wraps the commands into a
9357 ;; function which tests if the cursor is currently inside a table. If that
9358 ;; is the case, the table editor command is executed. However, when any of
9359 ;; those keys is used outside a table, the function uses `key-binding' to
9360 ;; look up if the key has an associated command in another currently active
9361 ;; keymap (minor modes, major mode, global), and executes that command.
9362 ;; There might be problems if any of the keys used by the table editor is
9363 ;; otherwise used as a prefix key.
9364
9365 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9366 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9367 ;; addresses this by checking explicitly for both bindings.
9368
9369 ;; The optimized version (see variable `orgtbl-optimized') takes over
9370 ;; all keys which are bound to `self-insert-command' in the *global map*.
9371 ;; Some modes bind other commands to simple characters, for example
9372 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9373 ;; active, this binding is ignored inside tables and replaced with a
9374 ;; modified self-insert.
9375
9376 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9377 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9378 In the optimized version, the table editor takes over all simple keys that
9379 normally just insert a character. In tables, the characters are inserted
9380 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9381 for empty fields). Outside tables, the correct binding of the keys is
9382 restored.
9383
9384 The default for this option is t if the optimized version is also used in
9385 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9386 this variable requires a restart of Emacs to become effective."
9387 :group 'org-table
9388 :type 'boolean)
9389
9390 (defvar orgtbl-mode nil
9391 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9392 table editor in arbitrary modes.")
9393 (make-variable-buffer-local 'orgtbl-mode)
9394
9395 (defvar orgtbl-mode-map (make-keymap)
9396 "Keymap for `orgtbl-mode'.")
9397
9398 ;;;###autoload
9399 (defun turn-on-orgtbl ()
9400 "Unconditionally turn on `orgtbl-mode'."
9401 (orgtbl-mode 1))
9402
9403 ;;;###autoload
9404 (defun orgtbl-mode (&optional arg)
9405 "The `org-mode' table editor as a minor mode for use in other modes."
9406 (interactive)
9407 (if (eq major-mode 'org-mode)
9408 ;; Exit without error, in case some hook functions calls this
9409 ;; by accident in org-mode.
9410 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9411 (setq orgtbl-mode
9412 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9413 (if orgtbl-mode
9414 (progn
9415 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9416 ;; Make sure we are first in minor-mode-map-alist
9417 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9418 (and c (setq minor-mode-map-alist
9419 (cons c (delq c minor-mode-map-alist)))))
9420 (set (make-local-variable (quote org-table-may-need-update)) t)
9421 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
9422 (add-hook 'before-change-functions 'org-before-change-function
9423 nil 'local)
9424 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
9425 auto-fill-inhibit-regexp)
9426 (set (make-local-variable 'auto-fill-inhibit-regexp)
9427 (if auto-fill-inhibit-regexp
9428 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
9429 "[ \t]*|"))
9430 (easy-menu-add orgtbl-mode-menu)
9431 (run-hooks 'orgtbl-mode-hook))
9432 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9433 (remove-hook 'before-change-functions 'org-before-change-function t)
9434 (easy-menu-remove orgtbl-mode-menu)
9435 (force-mode-line-update 'all))))
9436
9437 ;; Install it as a minor mode.
9438 (put 'orgtbl-mode :included t)
9439 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9440 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9441
9442 (defun orgtbl-make-binding (fun n &rest keys)
9443 "Create a function for binding in the table minor mode.
9444 FUN is the command to call inside a table. N is used to create a unique
9445 command name. KEYS are keys that should be checked in for a command
9446 to execute outside of tables."
9447 (eval
9448 (list 'defun
9449 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9450 '(arg)
9451 (concat "In tables, run `" (symbol-name fun) "'.\n"
9452 "Outside of tables, run the binding of `"
9453 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9454 "'.")
9455 '(interactive "p")
9456 (list 'if
9457 '(org-at-table-p)
9458 (list 'call-interactively (list 'quote fun))
9459 (list 'let '(orgtbl-mode)
9460 (list 'call-interactively
9461 (append '(or)
9462 (mapcar (lambda (k)
9463 (list 'key-binding k))
9464 keys)
9465 '('orgtbl-error))))))))
9466
9467 (defun orgtbl-error ()
9468 "Error when there is no default binding for a table key."
9469 (interactive)
9470 (error "This key is has no function outside tables"))
9471
9472 (defun orgtbl-setup ()
9473 "Setup orgtbl keymaps."
9474 (let ((nfunc 0)
9475 (bindings
9476 (list
9477 '([(meta shift left)] org-table-delete-column)
9478 '([(meta left)] org-table-move-column-left)
9479 '([(meta right)] org-table-move-column-right)
9480 '([(meta shift right)] org-table-insert-column)
9481 '([(meta shift up)] org-table-kill-row)
9482 '([(meta shift down)] org-table-insert-row)
9483 '([(meta up)] org-table-move-row-up)
9484 '([(meta down)] org-table-move-row-down)
9485 '("\C-c\C-w" org-table-cut-region)
9486 '("\C-c\M-w" org-table-copy-region)
9487 '("\C-c\C-y" org-table-paste-rectangle)
9488 '("\C-c-" org-table-insert-hline)
9489 ; '([(shift tab)] org-table-previous-field)
9490 '("\C-m" org-table-next-row)
9491 (list (org-key 'S-return) 'org-table-copy-down)
9492 '([(meta return)] org-table-wrap-region)
9493 '("\C-c\C-q" org-table-wrap-region)
9494 '("\C-c?" org-table-current-column)
9495 '("\C-c " org-table-blank-field)
9496 '("\C-c+" org-table-sum)
9497 '("\C-c|" org-table-toggle-vline-visibility)
9498 '("\C-c=" org-table-eval-formula)
9499 '("\C-c'" org-table-edit-formulas)
9500 '("\C-c*" org-table-recalculate)
9501 '("\C-c^" org-table-sort-lines)
9502 '([(control ?#)] org-table-rotate-recalc-marks)))
9503 elt key fun cmd)
9504 (while (setq elt (pop bindings))
9505 (setq nfunc (1+ nfunc))
9506 (setq key (car elt)
9507 fun (nth 1 elt)
9508 cmd (orgtbl-make-binding fun nfunc key))
9509 (define-key orgtbl-mode-map key cmd))
9510 ;; Special treatment needed for TAB and RET
9511 (define-key orgtbl-mode-map [(return)]
9512 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9513 (define-key orgtbl-mode-map "\C-m"
9514 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9515 (define-key orgtbl-mode-map [(tab)]
9516 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9517 (define-key orgtbl-mode-map "\C-i"
9518 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
9519 (define-key orgtbl-mode-map "\C-i"
9520 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
9521 (define-key orgtbl-mode-map "\C-c\C-c"
9522 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
9523 (when orgtbl-optimized
9524 ;; If the user wants maximum table support, we need to hijack
9525 ;; some standard editing functions
9526 (org-remap orgtbl-mode-map
9527 'self-insert-command 'orgtbl-self-insert-command
9528 'delete-char 'orgtbl-delete-char
9529 'delete-backward-char 'orgtbl-delete-backward-char)
9530 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
9531 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
9532 '("OrgTbl"
9533 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
9534 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
9535 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
9536 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
9537 "--"
9538 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
9539 ["Copy Field from Above"
9540 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
9541 "--"
9542 ("Column"
9543 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
9544 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
9545 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
9546 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
9547 ("Row"
9548 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
9549 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
9550 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
9551 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
9552 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
9553 "--"
9554 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
9555 ("Rectangle"
9556 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
9557 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
9558 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
9559 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
9560 "--"
9561 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
9562 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9563 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
9564 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
9565 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
9566 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
9567 ["Sum Column/Rectangle" org-table-sum
9568 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
9569 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
9570 ["Debug Formulas"
9571 (setq org-table-formula-debug (not org-table-formula-debug))
9572 :style toggle :selected org-table-formula-debug]
9573 ))
9574 t)
9575
9576 (defun orgtbl-tab ()
9577 "Justification and field motion for `orgtbl-mode'."
9578 (interactive)
9579 (org-table-justify-field-maybe)
9580 (org-table-next-field))
9581
9582 (defun orgtbl-ret ()
9583 "Justification and field motion for `orgtbl-mode'."
9584 (interactive)
9585 (org-table-justify-field-maybe)
9586 (org-table-next-row))
9587
9588 (defun orgtbl-self-insert-command (N)
9589 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9590 If the cursor is in a table looking at whitespace, the whitespace is
9591 overwritten, and the table is not marked as requiring realignment."
9592 (interactive "p")
9593 (if (and (org-at-table-p)
9594 (or
9595 (and org-table-auto-blank-field
9596 (member last-command
9597 '(orgtbl-hijacker-command-100
9598 orgtbl-hijacker-command-101
9599 orgtbl-hijacker-command-102
9600 orgtbl-hijacker-command-103
9601 orgtbl-hijacker-command-104
9602 orgtbl-hijacker-command-105))
9603 (org-table-blank-field))
9604 t)
9605 (eq N 1)
9606 (looking-at "[^|\n]* +|"))
9607 (let (org-table-may-need-update)
9608 (goto-char (1- (match-end 0)))
9609 (delete-backward-char 1)
9610 (goto-char (match-beginning 0))
9611 (self-insert-command N))
9612 (setq org-table-may-need-update t)
9613 (let (orgtbl-mode)
9614 (call-interactively (key-binding (vector last-input-event))))))
9615
9616 (defun org-force-self-insert (N)
9617 "Needed to enforce self-insert under remapping."
9618 (interactive "p")
9619 (self-insert-command N))
9620
9621 (defun orgtbl-delete-backward-char (N)
9622 "Like `delete-backward-char', insert whitespace at field end in tables.
9623 When deleting backwards, in tables this function will insert whitespace in
9624 front of the next \"|\" separator, to keep the table aligned. The table will
9625 still be marked for re-alignment, because a narrow field may lead to a
9626 reduced column width."
9627 (interactive "p")
9628 (if (and (org-at-table-p)
9629 (eq N 1)
9630 (string-match "|" (buffer-substring (point-at-bol) (point)))
9631 (looking-at ".*?|"))
9632 (let ((pos (point)))
9633 (backward-delete-char N)
9634 (skip-chars-forward "^|")
9635 (insert " ")
9636 (goto-char (1- pos)))
9637 (delete-backward-char N)))
9638
9639 (defun orgtbl-delete-char (N)
9640 "Like `delete-char', but insert whitespace at field end in tables.
9641 When deleting characters, in tables this function will insert whitespace in
9642 front of the next \"|\" separator, to keep the table aligned. The table
9643 will still be marked for re-alignment, because a narrow field may lead to
9644 a reduced column width."
9645 (interactive "p")
9646 (if (and (org-at-table-p)
9647 (not (bolp))
9648 (not (= (char-after) ?|))
9649 (eq N 1))
9650 (if (looking-at ".*?|")
9651 (let ((pos (point)))
9652 (replace-match (concat
9653 (substring (match-string 0) 1 -1)
9654 " |"))
9655 (goto-char pos)))
9656 (delete-char N)))
9657
9658 ;;; Exporting
9659
9660 (defconst org-level-max 20)
9661
9662 (defun org-export-find-first-heading-line (list)
9663 "Remove all lines from LIST which are before the first headline."
9664 (let ((orig-list list)
9665 (re (concat "^" outline-regexp)))
9666 (while (and list
9667 (not (string-match re (car list))))
9668 (pop list))
9669 (or list orig-list)))
9670
9671 (defun org-skip-comments (lines)
9672 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
9673 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
9674 (re2 "^\\(\\*+\\)[ \t\n\r]")
9675 rtn line level)
9676 (while (setq line (pop lines))
9677 (cond
9678 ((and (string-match re1 line)
9679 (setq level (- (match-end 1) (match-beginning 1))))
9680 ;; Beginning of a COMMENT subtree. Skip it.
9681 (while (and (setq line (pop lines))
9682 (or (not (string-match re2 line))
9683 (> (- (match-end 1) (match-beginning 1)) level))))
9684 (setq lines (cons line lines)))
9685 ((string-match "^#" line)
9686 ;; an ordinary comment line
9687 )
9688 (t (setq rtn (cons line rtn)))))
9689 (nreverse rtn)))
9690
9691 ;; ASCII
9692
9693 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
9694 "Characters for underlining headings in ASCII export.")
9695
9696 (defconst org-html-entities
9697 '(("nbsp")
9698 ("iexcl")
9699 ("cent")
9700 ("pound")
9701 ("curren")
9702 ("yen")
9703 ("brvbar")
9704 ("sect")
9705 ("uml")
9706 ("copy")
9707 ("ordf")
9708 ("laquo")
9709 ("not")
9710 ("shy")
9711 ("reg")
9712 ("macr")
9713 ("deg")
9714 ("plusmn")
9715 ("sup2")
9716 ("sup3")
9717 ("acute")
9718 ("micro")
9719 ("para")
9720 ("middot")
9721 ("odot"."o")
9722 ("star"."*")
9723 ("cedil")
9724 ("sup1")
9725 ("ordm")
9726 ("raquo")
9727 ("frac14")
9728 ("frac12")
9729 ("frac34")
9730 ("iquest")
9731 ("Agrave")
9732 ("Aacute")
9733 ("Acirc")
9734 ("Atilde")
9735 ("Auml")
9736 ("Aring") ("AA"."&Aring;")
9737 ("AElig")
9738 ("Ccedil")
9739 ("Egrave")
9740 ("Eacute")
9741 ("Ecirc")
9742 ("Euml")
9743 ("Igrave")
9744 ("Iacute")
9745 ("Icirc")
9746 ("Iuml")
9747 ("ETH")
9748 ("Ntilde")
9749 ("Ograve")
9750 ("Oacute")
9751 ("Ocirc")
9752 ("Otilde")
9753 ("Ouml")
9754 ("times")
9755 ("Oslash")
9756 ("Ugrave")
9757 ("Uacute")
9758 ("Ucirc")
9759 ("Uuml")
9760 ("Yacute")
9761 ("THORN")
9762 ("szlig")
9763 ("agrave")
9764 ("aacute")
9765 ("acirc")
9766 ("atilde")
9767 ("auml")
9768 ("aring")
9769 ("aelig")
9770 ("ccedil")
9771 ("egrave")
9772 ("eacute")
9773 ("ecirc")
9774 ("euml")
9775 ("igrave")
9776 ("iacute")
9777 ("icirc")
9778 ("iuml")
9779 ("eth")
9780 ("ntilde")
9781 ("ograve")
9782 ("oacute")
9783 ("ocirc")
9784 ("otilde")
9785 ("ouml")
9786 ("divide")
9787 ("oslash")
9788 ("ugrave")
9789 ("uacute")
9790 ("ucirc")
9791 ("uuml")
9792 ("yacute")
9793 ("thorn")
9794 ("yuml")
9795 ("fnof")
9796 ("Alpha")
9797 ("Beta")
9798 ("Gamma")
9799 ("Delta")
9800 ("Epsilon")
9801 ("Zeta")
9802 ("Eta")
9803 ("Theta")
9804 ("Iota")
9805 ("Kappa")
9806 ("Lambda")
9807 ("Mu")
9808 ("Nu")
9809 ("Xi")
9810 ("Omicron")
9811 ("Pi")
9812 ("Rho")
9813 ("Sigma")
9814 ("Tau")
9815 ("Upsilon")
9816 ("Phi")
9817 ("Chi")
9818 ("Psi")
9819 ("Omega")
9820 ("alpha")
9821 ("beta")
9822 ("gamma")
9823 ("delta")
9824 ("epsilon")
9825 ("varepsilon"."&epsilon;")
9826 ("zeta")
9827 ("eta")
9828 ("theta")
9829 ("iota")
9830 ("kappa")
9831 ("lambda")
9832 ("mu")
9833 ("nu")
9834 ("xi")
9835 ("omicron")
9836 ("pi")
9837 ("rho")
9838 ("sigmaf") ("varsigma"."&sigmaf;")
9839 ("sigma")
9840 ("tau")
9841 ("upsilon")
9842 ("phi")
9843 ("chi")
9844 ("psi")
9845 ("omega")
9846 ("thetasym") ("vartheta"."&thetasym;")
9847 ("upsih")
9848 ("piv")
9849 ("bull") ("bullet"."&bull;")
9850 ("hellip") ("dots"."&hellip;")
9851 ("prime")
9852 ("Prime")
9853 ("oline")
9854 ("frasl")
9855 ("weierp")
9856 ("image")
9857 ("real")
9858 ("trade")
9859 ("alefsym")
9860 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
9861 ("uarr") ("uparrow"."&uarr;")
9862 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
9863 ("darr")("downarrow"."&darr;")
9864 ("harr") ("leftrightarrow"."&harr;")
9865 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
9866 ("lArr") ("Leftarrow"."&lArr;")
9867 ("uArr") ("Uparrow"."&uArr;")
9868 ("rArr") ("Rightarrow"."&rArr;")
9869 ("dArr") ("Downarrow"."&dArr;")
9870 ("hArr") ("Leftrightarrow"."&hArr;")
9871 ("forall")
9872 ("part") ("partial"."&part;")
9873 ("exist") ("exists"."&exist;")
9874 ("empty") ("emptyset"."&empty;")
9875 ("nabla")
9876 ("isin") ("in"."&isin;")
9877 ("notin")
9878 ("ni")
9879 ("prod")
9880 ("sum")
9881 ("minus")
9882 ("lowast") ("ast"."&lowast;")
9883 ("radic")
9884 ("prop") ("proptp"."&prop;")
9885 ("infin") ("infty"."&infin;")
9886 ("ang") ("angle"."&ang;")
9887 ("and") ("vee"."&and;")
9888 ("or") ("wedge"."&or;")
9889 ("cap")
9890 ("cup")
9891 ("int")
9892 ("there4")
9893 ("sim")
9894 ("cong") ("simeq"."&cong;")
9895 ("asymp")("approx"."&asymp;")
9896 ("ne") ("neq"."&ne;")
9897 ("equiv")
9898 ("le")
9899 ("ge")
9900 ("sub") ("subset"."&sub;")
9901 ("sup") ("supset"."&sup;")
9902 ("nsub")
9903 ("sube")
9904 ("supe")
9905 ("oplus")
9906 ("otimes")
9907 ("perp")
9908 ("sdot") ("cdot"."&sdot;")
9909 ("lceil")
9910 ("rceil")
9911 ("lfloor")
9912 ("rfloor")
9913 ("lang")
9914 ("rang")
9915 ("loz") ("Diamond"."&loz;")
9916 ("spades") ("spadesuit"."&spades;")
9917 ("clubs") ("clubsuit"."&clubs;")
9918 ("hearts") ("diamondsuit"."&hearts;")
9919 ("diams") ("diamondsuit"."&diams;")
9920 ("quot")
9921 ("amp")
9922 ("lt")
9923 ("gt")
9924 ("OElig")
9925 ("oelig")
9926 ("Scaron")
9927 ("scaron")
9928 ("Yuml")
9929 ("circ")
9930 ("tilde")
9931 ("ensp")
9932 ("emsp")
9933 ("thinsp")
9934 ("zwnj")
9935 ("zwj")
9936 ("lrm")
9937 ("rlm")
9938 ("ndash")
9939 ("mdash")
9940 ("lsquo")
9941 ("rsquo")
9942 ("sbquo")
9943 ("ldquo")
9944 ("rdquo")
9945 ("bdquo")
9946 ("dagger")
9947 ("Dagger")
9948 ("permil")
9949 ("lsaquo")
9950 ("rsaquo")
9951 ("euro")
9952
9953 ("arccos"."arccos")
9954 ("arcsin"."arcsin")
9955 ("arctan"."arctan")
9956 ("arg"."arg")
9957 ("cos"."cos")
9958 ("cosh"."cosh")
9959 ("cot"."cot")
9960 ("coth"."coth")
9961 ("csc"."csc")
9962 ("deg"."deg")
9963 ("det"."det")
9964 ("dim"."dim")
9965 ("exp"."exp")
9966 ("gcd"."gcd")
9967 ("hom"."hom")
9968 ("inf"."inf")
9969 ("ker"."ker")
9970 ("lg"."lg")
9971 ("lim"."lim")
9972 ("liminf"."liminf")
9973 ("limsup"."limsup")
9974 ("ln"."ln")
9975 ("log"."log")
9976 ("max"."max")
9977 ("min"."min")
9978 ("Pr"."Pr")
9979 ("sec"."sec")
9980 ("sin"."sin")
9981 ("sinh"."sinh")
9982 ("sup"."sup")
9983 ("tan"."tan")
9984 ("tanh"."tanh")
9985 )
9986 "Entities for TeX->HTML translation.
9987 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
9988 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
9989 In that case, \"\\ent\" will be translated to \"&other;\".
9990 The list contains HTML entities for Latin-1, Greek and other symbols.
9991 It is supplemented by a number of commonly used TeX macros with appropriate
9992 translations. There is currently no way for users to extend this.")
9993
9994 (defvar org-last-level nil) ; dynamically scoped variable
9995
9996 (defun org-export-as-ascii (arg)
9997 "Export the outline as a pretty ASCII file.
9998 If there is an active region, export only the region.
9999 The prefix ARG specifies how many levels of the outline should become
10000 underlined headlines. The default is 3."
10001 (interactive "P")
10002 (setq-default org-todo-line-regexp org-todo-line-regexp)
10003 (let* ((region
10004 (buffer-substring
10005 (if (org-region-active-p) (region-beginning) (point-min))
10006 (if (org-region-active-p) (region-end) (point-max))))
10007 (lines (org-export-find-first-heading-line
10008 (org-skip-comments (org-split-string region "[\r\n]"))))
10009 (org-startup-with-deadline-check nil)
10010 (level 0) line txt
10011 (umax nil)
10012 (case-fold-search nil)
10013 (filename (concat (file-name-sans-extension (buffer-file-name))
10014 ".txt"))
10015 (buffer (find-file-noselect filename))
10016 (levels-open (make-vector org-level-max nil))
10017 (date (format-time-string "%Y/%m/%d" (current-time)))
10018 (time (format-time-string "%X" (current-time)))
10019 (author user-full-name)
10020 (title (buffer-name))
10021 (options nil)
10022 (email user-mail-address)
10023 (language org-export-default-language)
10024 (text nil)
10025 (todo nil)
10026 (lang-words nil))
10027
10028 (setq org-last-level 1)
10029 (org-init-section-numbers)
10030
10031 (find-file-noselect filename)
10032
10033 ;; Search for the export key lines
10034 (org-parse-key-lines)
10035
10036 (setq lang-words (or (assoc language org-export-language-setup)
10037 (assoc "en" org-export-language-setup)))
10038 (if org-export-ascii-show-new-buffer
10039 (switch-to-buffer-other-window buffer)
10040 (set-buffer buffer))
10041 (erase-buffer)
10042 (fundamental-mode)
10043 (if options (org-parse-export-options options))
10044 (setq umax (if arg (prefix-numeric-value arg)
10045 org-export-headline-levels))
10046
10047 ;; File header
10048 (if title (org-insert-centered title ?=))
10049 (insert "\n")
10050 (if (or author email)
10051 (insert (concat (nth 1 lang-words) ": " (or author "")
10052 (if email (concat " <" email ">") "")
10053 "\n")))
10054 (if (and date time)
10055 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10056 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10057
10058 (insert "\n\n")
10059
10060 (if org-export-with-toc
10061 (progn
10062 (insert (nth 3 lang-words) "\n"
10063 (make-string (length (nth 3 lang-words)) ?=) "\n")
10064 (mapcar '(lambda (line)
10065 (if (string-match org-todo-line-regexp
10066 line)
10067 ;; This is a headline
10068 (progn
10069 (setq level (- (match-end 1) (match-beginning 1))
10070 txt (match-string 3 line)
10071 todo
10072 (or (and (match-beginning 2)
10073 (not (equal (match-string 2 line)
10074 org-done-string)))
10075 ; TODO, not DONE
10076 (and (= level umax)
10077 (org-search-todo-below
10078 line lines level))))
10079 (setq txt (org-html-expand-for-ascii txt))
10080
10081 (if org-export-with-section-numbers
10082 (setq txt (concat (org-section-number level)
10083 " " txt)))
10084 (if (<= level umax)
10085 (progn
10086 (insert
10087 (make-string (* (1- level) 4) ?\ )
10088 (format (if todo "%s (*)\n" "%s\n") txt))
10089 (setq org-last-level level))
10090 ))))
10091 lines)))
10092
10093 (org-init-section-numbers)
10094 (while (setq line (pop lines))
10095 ;; Remove the quoted HTML tags.
10096 (setq line (org-html-expand-for-ascii line))
10097 (cond
10098 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10099 ;; a Headline
10100 (setq level (- (match-end 1) (match-beginning 1))
10101 txt (match-string 2 line))
10102 (org-ascii-level-start level txt umax))
10103 (t (insert line "\n"))))
10104 (normal-mode)
10105 (save-buffer)
10106 (goto-char (point-min))))
10107
10108 (defun org-search-todo-below (line lines level)
10109 "Search the subtree below LINE for any TODO entries."
10110 (let ((rest (cdr (memq line lines)))
10111 (re org-todo-line-regexp)
10112 line lv todo)
10113 (catch 'exit
10114 (while (setq line (pop rest))
10115 (if (string-match re line)
10116 (progn
10117 (setq lv (- (match-end 1) (match-beginning 1))
10118 todo (and (match-beginning 2)
10119 (not (equal (match-string 2 line)
10120 org-done-string))))
10121 ; TODO, not DONE
10122 (if (<= lv level) (throw 'exit nil))
10123 (if todo (throw 'exit t))))))))
10124
10125 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10126 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10127 (defun org-html-expand-for-ascii (line)
10128 "Handle quoted HTML for ASCII export."
10129 (if org-export-html-expand
10130 (while (string-match "@<[^<>\n]*>" line)
10131 ;; We just remove the tags for now.
10132 (setq line (replace-match "" nil nil line))))
10133 line)
10134
10135 (defun org-insert-centered (s &optional underline)
10136 "Insert the string S centered and underline it with character UNDERLINE."
10137 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
10138 (insert (make-string ind ?\ ) s "\n")
10139 (if underline
10140 (insert (make-string ind ?\ )
10141 (make-string (length s) underline)
10142 "\n"))))
10143
10144 (defun org-ascii-level-start (level title umax)
10145 "Insert a new level in ASCII export."
10146 (let (char)
10147 (if (> level umax)
10148 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10149 (if (or (not (equal (char-before) ?\n))
10150 (not (equal (char-before (1- (point))) ?\n)))
10151 (insert "\n"))
10152 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10153 (if org-export-with-section-numbers
10154 (setq title (concat (org-section-number level) " " title)))
10155 (insert title "\n" (make-string (string-width title) char) "\n"))))
10156
10157 (defun org-export-copy-visible ()
10158 "Copy the visible part of the buffer to another buffer, for printing.
10159 Also removes the first line of the buffer if it specifies a mode,
10160 and all options lines."
10161 (interactive)
10162 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
10163 ".txt"))
10164 (buffer (find-file-noselect filename))
10165 (ore (concat
10166 (org-make-options-regexp
10167 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10168 "STARTUP" "ARCHIVE"
10169 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10170 (if org-noutline-p "\\(\n\\|$\\)" "")))
10171 s e)
10172 (with-current-buffer buffer
10173 (erase-buffer)
10174 (text-mode))
10175 (save-excursion
10176 (setq s (goto-char (point-min)))
10177 (while (not (= (point) (point-max)))
10178 (goto-char (org-find-invisible))
10179 (append-to-buffer buffer s (point))
10180 (setq s (goto-char (org-find-visible)))))
10181 (switch-to-buffer-other-window buffer)
10182 (newline)
10183 (goto-char (point-min))
10184 (if (looking-at ".*-\\*- mode:.*\n")
10185 (replace-match ""))
10186 (while (re-search-forward ore nil t)
10187 (replace-match ""))
10188 (goto-char (point-min))))
10189
10190 (defun org-find-visible ()
10191 (if (featurep 'noutline)
10192 (let ((s (point)))
10193 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10194 (get-char-property s 'invisible)))
10195 s)
10196 (skip-chars-forward "^\n")
10197 (point)))
10198 (defun org-find-invisible ()
10199 (if (featurep 'noutline)
10200 (let ((s (point)))
10201 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10202 (not (get-char-property s 'invisible))))
10203 s)
10204 (skip-chars-forward "^\r")
10205 (point)))
10206
10207 ;; HTML
10208
10209 (defun org-get-current-options ()
10210 "Return a string with current options as keyword options.
10211 Does include HTML export options as well as TODO and CATEGORY stuff."
10212 (format
10213 "#+TITLE: %s
10214 #+AUTHOR: %s
10215 #+EMAIL: %s
10216 #+LANGUAGE: %s
10217 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10218 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10219 #+CATEGORY: %s
10220 #+SEQ_TODO: %s
10221 #+TYP_TODO: %s
10222 #+STARTUP: %s %s
10223 #+ARCHIVE: %s
10224 "
10225 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10226 org-export-headline-levels
10227 org-export-with-section-numbers
10228 org-export-with-toc
10229 org-export-preserve-breaks
10230 org-export-html-expand
10231 org-export-with-fixed-width
10232 org-export-with-tables
10233 org-export-with-sub-superscripts
10234 org-export-with-emphasize
10235 org-export-with-TeX-macros
10236 (file-name-nondirectory (buffer-file-name))
10237 (if (equal org-todo-interpretation 'sequence)
10238 (mapconcat 'identity org-todo-keywords " ")
10239 "TODO FEEDBACK VERIFY DONE")
10240 (if (equal org-todo-interpretation 'type)
10241 (mapconcat 'identity org-todo-keywords " ")
10242 "Me Jason Marie DONE")
10243 (cdr (assoc org-startup-folded
10244 '((nil . "nofold")(t . "fold")(content . "content"))))
10245 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10246 org-archive-location
10247 ))
10248
10249 (defun org-insert-export-options-template ()
10250 "Insert into the buffer a template with information for exporting."
10251 (interactive)
10252 (if (not (bolp)) (newline))
10253 (let ((s (org-get-current-options)))
10254 (and (string-match "#\\+CATEGORY" s)
10255 (setq s (substring s 0 (match-beginning 0))))
10256 (insert s)))
10257
10258 (defun org-toggle-fixed-width-section (arg)
10259 "Toggle the fixed-width export.
10260 If there is no active region, the QUOTE keyword at the current headline is
10261 inserted or removed. When present, it causes the text between this headline
10262 and the next to be exported as fixed-width text, and unmodified.
10263 If there is an active region, this command adds or removes a colon as the
10264 first character of this line. If the first character of a line is a colon,
10265 this line is also exported in fixed-width font."
10266 (interactive "P")
10267 (let* ((cc 0)
10268 (regionp (org-region-active-p))
10269 (beg (if regionp (region-beginning) (point)))
10270 (end (if regionp (region-end)))
10271 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10272 (re "[ \t]*\\(:\\)")
10273 off)
10274 (if regionp
10275 (save-excursion
10276 (goto-char beg)
10277 (setq cc (current-column))
10278 (beginning-of-line 1)
10279 (setq off (looking-at re))
10280 (while (> nlines 0)
10281 (setq nlines (1- nlines))
10282 (beginning-of-line 1)
10283 (cond
10284 (arg
10285 (move-to-column cc t)
10286 (insert ":\n")
10287 (forward-line -1))
10288 ((and off (looking-at re))
10289 (replace-match "" t t nil 1))
10290 ((not off) (move-to-column cc t) (insert ":")))
10291 (forward-line 1)))
10292 (save-excursion
10293 (org-back-to-heading)
10294 (if (looking-at (concat outline-regexp
10295 "\\( +\\<" org-quote-string "\\>\\)"))
10296 (replace-match "" t t nil 1)
10297 (if (looking-at outline-regexp)
10298 (progn
10299 (goto-char (match-end 0))
10300 (insert " " org-quote-string))))))))
10301
10302 (defun org-export-as-html-and-open (arg)
10303 "Export the outline as HTML and immediately open it with a browser.
10304 If there is an active region, export only the region.
10305 The prefix ARG specifies how many levels of the outline should become
10306 headlines. The default is 3. Lower levels will become bulleted lists."
10307 (interactive "P")
10308 (org-export-as-html arg 'hidden)
10309 (org-open-file (buffer-file-name)))
10310
10311 (defun org-export-as-html-batch ()
10312 "Call `org-export-as-html', may be used in batch processing as
10313 emacs --batch
10314 --load=$HOME/lib/emacs/org.el
10315 --eval \"(setq org-export-headline-levels 2)\"
10316 --visit=MyFile --funcall org-export-as-html-batch"
10317 (org-export-as-html org-export-headline-levels 'hidden))
10318
10319 (defun org-export-as-html (arg &optional hidden)
10320 "Export the outline as a pretty HTML file.
10321 If there is an active region, export only the region.
10322 The prefix ARG specifies how many levels of the outline should become
10323 headlines. The default is 3. Lower levels will become bulleted lists."
10324 (interactive "P")
10325 (setq-default org-todo-line-regexp org-todo-line-regexp)
10326 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
10327 (setq-default org-done-string org-done-string)
10328 (let* ((style org-export-html-style)
10329 (region-p (org-region-active-p))
10330 (region
10331 (buffer-substring
10332 (if region-p (region-beginning) (point-min))
10333 (if region-p (region-end) (point-max))))
10334 (all_lines
10335 (org-skip-comments (org-split-string region "[\r\n]")))
10336 (lines (org-export-find-first-heading-line all_lines))
10337 (level 0) (line "") (origline "") txt todo
10338 (umax nil)
10339 (filename (concat (file-name-sans-extension (buffer-file-name))
10340 ".html"))
10341 (buffer (find-file-noselect filename))
10342 (levels-open (make-vector org-level-max nil))
10343 (date (format-time-string "%Y/%m/%d" (current-time)))
10344 (time (format-time-string "%X" (current-time)))
10345 (author user-full-name)
10346 (title (buffer-name))
10347 (options nil)
10348 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
10349 (inquote nil)
10350 (infixed nil)
10351 (in-local-list nil)
10352 (local-list-num nil)
10353 (local-list-indent nil)
10354 (llt org-plain-list-ordered-item-terminator)
10355 (email user-mail-address)
10356 (language org-export-default-language)
10357 (text nil)
10358 (lang-words nil)
10359 (head-count 0) cnt
10360 (start 0)
10361 ;; FIXME: The following returns always nil under XEmacs
10362 (coding-system (and (fboundp 'coding-system-get)
10363 (boundp 'buffer-file-coding-system)
10364 buffer-file-coding-system))
10365 (coding-system-for-write (or coding-system coding-system-for-write))
10366 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
10367 (charset (and coding-system
10368 (coding-system-get coding-system 'mime-charset)))
10369 table-open type
10370 table-buffer table-orig-buffer
10371 ind start-is-num starter
10372 )
10373 (message "Exporting...")
10374
10375 (setq org-last-level 1)
10376 (org-init-section-numbers)
10377
10378 ;; Search for the export key lines
10379 (org-parse-key-lines)
10380 (setq lang-words (or (assoc language org-export-language-setup)
10381 (assoc "en" org-export-language-setup)))
10382
10383 ;; Switch to the output buffer
10384 (if (or hidden (not org-export-html-show-new-buffer))
10385 (set-buffer buffer)
10386 (switch-to-buffer-other-window buffer))
10387 (erase-buffer)
10388 (fundamental-mode)
10389 (let ((case-fold-search nil))
10390 (if options (org-parse-export-options options))
10391 (setq umax (if arg (prefix-numeric-value arg)
10392 org-export-headline-levels))
10393
10394 ;; File header
10395 (insert (format
10396 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
10397 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
10398 <html lang=\"%s\"><head>
10399 <title>%s</title>
10400 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
10401 <meta name=generator content=\"Org-mode\">
10402 <meta name=generated content=\"%s %s\">
10403 <meta name=author content=\"%s\">
10404 %s
10405 </head><body>
10406 "
10407 language (org-html-expand title) (or charset "iso-8859-1")
10408 date time author style))
10409 (if title (insert (concat "<H1 class=\"title\">"
10410 (org-html-expand title) "</H1>\n")))
10411 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
10412 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
10413 email "&gt;</a>\n")))
10414 (if (or author email) (insert "<br>\n"))
10415 (if (and date time) (insert (concat (nth 2 lang-words) ": "
10416 date " " time "<br>\n")))
10417 (if text (insert (concat "<p>\n" (org-html-expand text))))
10418 (if org-export-with-toc
10419 (progn
10420 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
10421 (insert "<ul>\n")
10422 (mapcar '(lambda (line)
10423 (if (string-match org-todo-line-regexp line)
10424 ;; This is a headline
10425 (progn
10426 (setq level (- (match-end 1) (match-beginning 1))
10427 txt (save-match-data
10428 (org-html-expand
10429 (match-string 3 line)))
10430 todo
10431 (or (and (match-beginning 2)
10432 (not (equal (match-string 2 line)
10433 org-done-string)))
10434 ; TODO, not DONE
10435 (and (= level umax)
10436 (org-search-todo-below
10437 line lines level))))
10438 (if org-export-with-section-numbers
10439 (setq txt (concat (org-section-number level)
10440 " " txt)))
10441 (if (<= level umax)
10442 (progn
10443 (setq head-count (+ head-count 1))
10444 (if (> level org-last-level)
10445 (progn
10446 (setq cnt (- level org-last-level))
10447 (while (>= (setq cnt (1- cnt)) 0)
10448 (insert "<ul>"))
10449 (insert "\n")))
10450 (if (< level org-last-level)
10451 (progn
10452 (setq cnt (- org-last-level level))
10453 (while (>= (setq cnt (1- cnt)) 0)
10454 (insert "</ul>"))
10455 (insert "\n")))
10456 (insert
10457 (format
10458 (if todo
10459 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
10460 "<li><a href=\"#sec-%d\">%s</a>\n")
10461 head-count txt))
10462 (setq org-last-level level))
10463 ))))
10464 lines)
10465 (while (> org-last-level 0)
10466 (setq org-last-level (1- org-last-level))
10467 (insert "</ul>\n"))
10468 ))
10469 (setq head-count 0)
10470 (org-init-section-numbers)
10471
10472 (while (setq line (pop lines) origline line)
10473 (catch 'nextline
10474
10475 ;; end of quote section?
10476 (when (and inquote (string-match "^\\*+" line))
10477 (insert "</pre>\n")
10478 (setq inquote nil))
10479 ;; inside a quote section?
10480 (when inquote
10481 (insert (org-html-protect line) "\n")
10482 (throw 'nextline nil))
10483
10484 ;; verbatim lines
10485 (when (and org-export-with-fixed-width
10486 (string-match "^[ \t]*:\\(.*\\)" line))
10487 (when (not infixed)
10488 (setq infixed t)
10489 (insert "<pre>\n"))
10490 (insert (org-html-protect (match-string 1 line)) "\n")
10491 (when (and lines
10492 (not (string-match "^[ \t]*\\(:.*\\)"
10493 (car lines))))
10494 (setq infixed nil)
10495 (insert "</pre>\n"))
10496 (throw 'nextline nil))
10497
10498 ;; Protect the links
10499 (setq start 0)
10500 (while (string-match org-link-maybe-angles-regexp line start)
10501 (setq start (match-end 0))
10502 (setq line (replace-match
10503 (concat "\000" (match-string 1 line) "\000")
10504 t t line)))
10505
10506 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
10507 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
10508 (setq line (org-html-expand line))
10509
10510 ;; Format the links
10511 (setq start 0)
10512 (while (string-match org-protected-link-regexp line start)
10513 (setq start (- (match-end 0) 2))
10514 (setq type (match-string 1 line))
10515 (cond
10516 ((member type '("http" "https" "ftp" "mailto" "news"))
10517 ;; standard URL
10518 (setq line (replace-match
10519 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
10520 "<a href=\"\\1:\\2\">\\1:\\2</a>"
10521 nil nil line)))
10522 ((string= type "file")
10523 ;; FILE link
10524 (let* ((filename (match-string 2 line))
10525 (abs-p (file-name-absolute-p filename))
10526 (thefile (if abs-p (expand-file-name filename) filename))
10527 (thefile (save-match-data
10528 (if (string-match ":[0-9]+$" thefile)
10529 (replace-match "" t t thefile)
10530 thefile)))
10531 (file-is-image-p
10532 (save-match-data
10533 (string-match (org-image-file-name-regexp) thefile))))
10534 (setq line (replace-match
10535 (if (and org-export-html-inline-images
10536 file-is-image-p)
10537 (concat "<img src=\"" thefile "\"/>")
10538 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
10539 nil nil line))))
10540
10541 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
10542 (setq line (replace-match
10543 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
10544
10545 ;; TODO items
10546 (if (and (string-match org-todo-line-regexp line)
10547 (match-beginning 2))
10548 (if (equal (match-string 2 line) org-done-string)
10549 (setq line (replace-match
10550 "<span class=\"done\">\\2</span>"
10551 nil nil line 2))
10552 (setq line (replace-match "<span class=\"todo\">\\2</span>"
10553 nil nil line 2))))
10554
10555 ;; DEADLINES
10556 (if (string-match org-deadline-line-regexp line)
10557 (progn
10558 (if (save-match-data
10559 (string-match "<a href"
10560 (substring line 0 (match-beginning 0))))
10561 nil ; Don't do the replacement - it is inside a link
10562 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
10563 nil nil line 1)))))
10564 (cond
10565 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10566 ;; This is a headline
10567 (setq level (- (match-end 1) (match-beginning 1))
10568 txt (match-string 2 line))
10569 (if (<= level umax) (setq head-count (+ head-count 1)))
10570 (when in-local-list
10571 ;; Close any local lists before inserting a new header line
10572 (while local-list-num
10573 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10574 (pop local-list-num))
10575 (setq local-list-indent nil
10576 in-local-list nil))
10577 (org-html-level-start level txt umax
10578 (and org-export-with-toc (<= level umax))
10579 head-count)
10580 ;; QUOTES
10581 (when (string-match quote-re line)
10582 (insert "<pre>")
10583 (setq inquote t)))
10584
10585 ((and org-export-with-tables
10586 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
10587 (if (not table-open)
10588 ;; New table starts
10589 (setq table-open t table-buffer nil table-orig-buffer nil))
10590 ;; Accumulate lines
10591 (setq table-buffer (cons line table-buffer)
10592 table-orig-buffer (cons origline table-orig-buffer))
10593 (when (or (not lines)
10594 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
10595 (car lines))))
10596 (setq table-open nil
10597 table-buffer (nreverse table-buffer)
10598 table-orig-buffer (nreverse table-orig-buffer))
10599 (insert (org-format-table-html table-buffer table-orig-buffer))))
10600 (t
10601 ;; Normal lines
10602 (when (and (> org-export-plain-list-max-depth 0)
10603 (string-match
10604 (cond
10605 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10606 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10607 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10608 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
10609 line))
10610 (setq ind (org-get-string-indentation line)
10611 start-is-num (match-beginning 4)
10612 starter (if (match-beginning 2) (match-string 2 line))
10613 line (substring line (match-beginning 5)))
10614 (unless (string-match "[^ \t]" line)
10615 ;; empty line. Pretend indentation is large.
10616 (setq ind (1+ (or (car local-list-indent) 1))))
10617 (while (and in-local-list
10618 (or (and (= ind (car local-list-indent))
10619 (not starter))
10620 (< ind (car local-list-indent))))
10621 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10622 (pop local-list-num) (pop local-list-indent)
10623 (setq in-local-list local-list-indent))
10624 (cond
10625 ((and starter
10626 (or (not in-local-list)
10627 (> ind (car local-list-indent)))
10628 (< (length local-list-indent)
10629 org-export-plain-list-max-depth))
10630 ;; Start new (level of ) list
10631 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
10632 (push start-is-num local-list-num)
10633 (push ind local-list-indent)
10634 (setq in-local-list t))
10635 (starter
10636 ;; continue current list
10637 (insert "<li>\n"))))
10638 ;; Empty lines start a new paragraph. If hand-formatted lists
10639 ;; are not fully interpreted, lines starting with "-", "+", "*"
10640 ;; also start a new paragraph.
10641 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
10642 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
10643 ))
10644 (if org-export-html-with-timestamp
10645 (insert org-export-html-html-helper-timestamp))
10646 (insert "</body>\n</html>\n")
10647 (normal-mode)
10648 (save-buffer)
10649 (goto-char (point-min)))))
10650
10651 (defun org-format-table-html (lines olines)
10652 "Find out which HTML converter to use and return the HTML code."
10653 (if (string-match "^[ \t]*|" (car lines))
10654 ;; A normal org table
10655 (org-format-org-table-html lines)
10656 ;; Table made by table.el - test for spanning
10657 (let* ((hlines (delq nil (mapcar
10658 (lambda (x)
10659 (if (string-match "^[ \t]*\\+-" x) x
10660 nil))
10661 lines)))
10662 (first (car hlines))
10663 (ll (and (string-match "\\S-+" first)
10664 (match-string 0 first)))
10665 (re (concat "^[ \t]*" (regexp-quote ll)))
10666 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
10667 hlines))))
10668 (if (and (not spanning)
10669 (not org-export-prefer-native-exporter-for-tables))
10670 ;; We can use my own converter with HTML conversions
10671 (org-format-table-table-html lines)
10672 ;; Need to use the code generator in table.el, with the original text.
10673 (org-format-table-table-html-using-table-generate-source olines)))))
10674
10675 (defun org-format-org-table-html (lines)
10676 "Format a table into html."
10677 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10678 (setq lines (nreverse lines))
10679 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10680 (setq lines (nreverse lines))
10681 (let ((head (and org-export-highlight-first-table-line
10682 (delq nil (mapcar
10683 (lambda (x) (string-match "^[ \t]*|-" x))
10684 (cdr lines)))))
10685 line fields html)
10686 (setq html (concat org-export-html-table-tag "\n"))
10687 (while (setq line (pop lines))
10688 (catch 'next-line
10689 (if (string-match "^[ \t]*|-" line)
10690 (progn
10691 (setq head nil) ;; head ends here, first time around
10692 ;; ignore this line
10693 (throw 'next-line t)))
10694 ;; Break the line into fields
10695 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10696 (setq html (concat
10697 html
10698 "<tr>"
10699 (mapconcat (lambda (x)
10700 (if head
10701 (concat "<th>" x "</th>")
10702 (concat "<td>" x "</td>")))
10703 fields "")
10704 "</tr>\n"))))
10705 (setq html (concat html "</table>\n"))
10706 html))
10707
10708 (defun org-fake-empty-table-line (line)
10709 "Replace everything except \"|\" with spaces."
10710 (let ((i (length line))
10711 (newstr (copy-sequence line)))
10712 (while (> i 0)
10713 (setq i (1- i))
10714 (if (not (eq (aref newstr i) ?|))
10715 (aset newstr i ?\ )))
10716 newstr))
10717
10718 (defun org-format-table-table-html (lines)
10719 "Format a table generated by table.el into html.
10720 This conversion does *not* use `table-generate-source' from table.el.
10721 This has the advantage that Org-mode's HTML conversions can be used.
10722 But it has the disadvantage, that no cell- or row-spanning is allowed."
10723 (let (line field-buffer
10724 (head org-export-highlight-first-table-line)
10725 fields html empty)
10726 (setq html (concat org-export-html-table-tag "\n"))
10727 (while (setq line (pop lines))
10728 (setq empty "&nbsp")
10729 (catch 'next-line
10730 (if (string-match "^[ \t]*\\+-" line)
10731 (progn
10732 (if field-buffer
10733 (progn
10734 (setq html (concat
10735 html
10736 "<tr>"
10737 (mapconcat
10738 (lambda (x)
10739 (if (equal x "") (setq x empty))
10740 (if head
10741 (concat "<th>" x "</th>\n")
10742 (concat "<td>" x "</td>\n")))
10743 field-buffer "\n")
10744 "</tr>\n"))
10745 (setq head nil)
10746 (setq field-buffer nil)))
10747 ;; Ignore this line
10748 (throw 'next-line t)))
10749 ;; Break the line into fields and store the fields
10750 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10751 (if field-buffer
10752 (setq field-buffer (mapcar
10753 (lambda (x)
10754 (concat x "<br>" (pop fields)))
10755 field-buffer))
10756 (setq field-buffer fields))))
10757 (setq html (concat html "</table>\n"))
10758 html))
10759
10760 (defun org-format-table-table-html-using-table-generate-source (lines)
10761 "Format a table into html, using `table-generate-source' from table.el.
10762 This has the advantage that cell- or row-spanning is allowed.
10763 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
10764 (require 'table)
10765 (with-current-buffer (get-buffer-create " org-tmp1 ")
10766 (erase-buffer)
10767 (insert (mapconcat 'identity lines "\n"))
10768 (goto-char (point-min))
10769 (if (not (re-search-forward "|[^+]" nil t))
10770 (error "Error processing table"))
10771 (table-recognize-table)
10772 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
10773 (table-generate-source 'html " org-tmp2 ")
10774 (set-buffer " org-tmp2 ")
10775 (buffer-substring (point-min) (point-max))))
10776
10777 (defun org-html-protect (s)
10778 ;; convert & to &amp;, < to &lt; and > to &gt;
10779 (let ((start 0))
10780 (while (string-match "&" s start)
10781 (setq s (replace-match "&amp;" t t s)
10782 start (1+ (match-beginning 0))))
10783 (while (string-match "<" s)
10784 (setq s (replace-match "&lt;" t t s)))
10785 (while (string-match ">" s)
10786 (setq s (replace-match "&gt;" t t s))))
10787 s)
10788
10789 (defun org-html-expand (string)
10790 "Prepare STRING for HTML export. Applies all active conversions."
10791 ;; First check if there is a link in the line - if yes, apply conversions
10792 ;; only before the start of the link.
10793 ;; FIXME: This is no longer correct, because links now have an end.
10794 (let* ((m (string-match org-link-regexp string))
10795 (s (if m (substring string 0 m) string))
10796 (r (if m (substring string m) "")))
10797 ;; convert & to &amp;, < to &lt; and > to &gt;
10798 (setq s (org-html-protect s))
10799 (if org-export-html-expand
10800 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
10801 (setq s (replace-match "<\\1>" nil nil s))))
10802 (if org-export-with-emphasize
10803 (setq s (org-export-html-convert-emphasize s)))
10804 (if org-export-with-sub-superscripts
10805 (setq s (org-export-html-convert-sub-super s)))
10806 (if org-export-with-TeX-macros
10807 (let ((start 0) wd ass)
10808 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
10809 (setq wd (match-string 1 s))
10810 (if (setq ass (assoc wd org-html-entities))
10811 (setq s (replace-match (or (cdr ass)
10812 (concat "&" (car ass) ";"))
10813 t t s))
10814 (setq start (+ start (length wd)))))))
10815 (concat s r)))
10816
10817 (defun org-create-multibrace-regexp (left right n)
10818 "Create a regular expression which will match a balanced sexp.
10819 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
10820 as single character strings.
10821 The regexp returned will match the entire expression including the
10822 delimiters. It will also define a single group which contains the
10823 match except for the outermost delimiters. The maximum depth of
10824 stacked delimiters is N. Escaping delimiters is not possible."
10825 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
10826 (or "\\|")
10827 (re nothing)
10828 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
10829 (while (> n 1)
10830 (setq n (1- n)
10831 re (concat re or next)
10832 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
10833 (concat left "\\(" re "\\)" right)))
10834
10835 (defvar org-match-substring-regexp
10836 (concat
10837 "\\([^\\]\\)\\([_^]\\)\\("
10838 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
10839 "\\|"
10840 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
10841 "\\|"
10842 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
10843 "The regular expression matching a sub- or superscript.")
10844
10845 (defun org-export-html-convert-sub-super (string)
10846 "Convert sub- and superscripts in STRING to HTML."
10847 (let (key c)
10848 (while (string-match org-match-substring-regexp string)
10849 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
10850 (setq c (or (match-string 8 string)
10851 (match-string 6 string)
10852 (match-string 5 string)))
10853 (setq string (replace-match
10854 (concat (match-string 1 string)
10855 "<" key ">" c "</" key ">")
10856 t t string)))
10857 (while (string-match "\\\\\\([_^]\\)" string)
10858 (setq string (replace-match (match-string 1 string) t t string))))
10859 string)
10860
10861 (defun org-export-html-convert-emphasize (string)
10862 (while (string-match
10863 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
10864 string)
10865 (setq string (replace-match
10866 (concat "<b>" (match-string 3 string) "</b>")
10867 t t string 2)))
10868 (while (string-match
10869 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
10870 string)
10871 (setq string (replace-match
10872 (concat "<i>" (match-string 3 string) "</i>")
10873 t t string 2)))
10874 (while (string-match
10875 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
10876 string)
10877 (setq string (replace-match
10878 (concat "<u>" (match-string 3 string) "</u>")
10879 t t string 2)))
10880 string)
10881
10882 (defun org-parse-key-lines ()
10883 "Find the special key lines with the information for exporters."
10884 (save-excursion
10885 (goto-char 0)
10886 (let ((re (org-make-options-regexp
10887 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
10888 key)
10889 (while (re-search-forward re nil t)
10890 (setq key (match-string 1))
10891 (cond ((string-equal key "TITLE")
10892 (setq title (match-string 2)))
10893 ((string-equal key "AUTHOR")
10894 (setq author (match-string 2)))
10895 ((string-equal key "EMAIL")
10896 (setq email (match-string 2)))
10897 ((string-equal key "LANGUAGE")
10898 (setq language (match-string 2)))
10899 ((string-equal key "TEXT")
10900 (setq text (concat text "\n" (match-string 2))))
10901 ((string-equal key "OPTIONS")
10902 (setq options (match-string 2))))))))
10903
10904 (defun org-parse-export-options (s)
10905 "Parse the export options line."
10906 (let ((op '(("H" . org-export-headline-levels)
10907 ("num" . org-export-with-section-numbers)
10908 ("toc" . org-export-with-toc)
10909 ("\\n" . org-export-preserve-breaks)
10910 ("@" . org-export-html-expand)
10911 (":" . org-export-with-fixed-width)
10912 ("|" . org-export-with-tables)
10913 ("^" . org-export-with-sub-superscripts)
10914 ("*" . org-export-with-emphasize)
10915 ("TeX" . org-export-with-TeX-macros)))
10916 o)
10917 (while (setq o (pop op))
10918 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
10919 s)
10920 (set (make-local-variable (cdr o))
10921 (car (read-from-string (match-string 1 s))))))))
10922
10923 (defun org-html-level-start (level title umax with-toc head-count)
10924 "Insert a new level in HTML export."
10925 (let ((l (1+ (max level umax))))
10926 (while (<= l org-level-max)
10927 (if (aref levels-open (1- l))
10928 (progn
10929 (org-html-level-close l)
10930 (aset levels-open (1- l) nil)))
10931 (setq l (1+ l)))
10932 (if (> level umax)
10933 (progn
10934 (if (aref levels-open (1- level))
10935 (insert "<li>" title "<p>\n")
10936 (aset levels-open (1- level) t)
10937 (insert "<ul><li>" title "<p>\n")))
10938 (if org-export-with-section-numbers
10939 (setq title (concat (org-section-number level) " " title)))
10940 (setq level (+ level 1))
10941 (if with-toc
10942 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
10943 level head-count title level))
10944 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
10945
10946 (defun org-html-level-close (&rest args)
10947 "Terminate one level in HTML export."
10948 (insert "</ul>"))
10949
10950 ;; Variable holding the vector with section numbers
10951 (defvar org-section-numbers (make-vector org-level-max 0))
10952
10953 (defun org-init-section-numbers ()
10954 "Initialize the vector for the section numbers."
10955 (let* ((level -1)
10956 (numbers (nreverse (org-split-string "" "\\.")))
10957 (depth (1- (length org-section-numbers)))
10958 (i depth) number-string)
10959 (while (>= i 0)
10960 (if (> i level)
10961 (aset org-section-numbers i 0)
10962 (setq number-string (or (car numbers) "0"))
10963 (if (string-match "\\`[A-Z]\\'" number-string)
10964 (aset org-section-numbers i
10965 (- (string-to-char number-string) ?A -1))
10966 (aset org-section-numbers i (string-to-number number-string)))
10967 (pop numbers))
10968 (setq i (1- i)))))
10969
10970 (defun org-section-number (&optional level)
10971 "Return a string with the current section number.
10972 When LEVEL is non-nil, increase section numbers on that level."
10973 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
10974 (when level
10975 (when (> level -1)
10976 (aset org-section-numbers
10977 level (1+ (aref org-section-numbers level))))
10978 (setq idx (1+ level))
10979 (while (<= idx depth)
10980 (if (not (= idx 1))
10981 (aset org-section-numbers idx 0))
10982 (setq idx (1+ idx))))
10983 (setq idx 0)
10984 (while (<= idx depth)
10985 (setq n (aref org-section-numbers idx))
10986 (setq string (concat string (if (not (string= string "")) "." "")
10987 (int-to-string n)))
10988 (setq idx (1+ idx)))
10989 (save-match-data
10990 (if (string-match "\\`\\([@0]\\.\\)+" string)
10991 (setq string (replace-match "" nil nil string)))
10992 (if (string-match "\\(\\.0\\)+\\'" string)
10993 (setq string (replace-match "" nil nil string))))
10994 string))
10995
10996
10997 (defun org-export-icalendar-this-file ()
10998 "Export current file as an iCalendar file.
10999 The iCalendar file will be located in the same directory as the Org-mode
11000 file, but with extension `.ics'."
11001 (interactive)
11002 (org-export-icalendar nil (buffer-file-name)))
11003
11004 ;;;###autoload
11005 (defun org-export-icalendar-all-agenda-files ()
11006 "Export all files in `org-agenda-files' to iCalendar .ics files.
11007 Each iCalendar file will be located in the same directory as the Org-mode
11008 file, but with extension `.ics'."
11009 (interactive)
11010 (apply 'org-export-icalendar nil org-agenda-files))
11011
11012 ;;;###autoload
11013 (defun org-export-icalendar-combine-agenda-files ()
11014 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11015 The file is stored under the name `org-combined-agenda-icalendar-file'."
11016 (interactive)
11017 (apply 'org-export-icalendar t org-agenda-files))
11018
11019 (defun org-export-icalendar (combine &rest files)
11020 "Create iCalendar files for all elements of FILES.
11021 If COMBINE is non-nil, combine all calendar entries into a single large
11022 file and store it under the name `org-combined-agenda-icalendar-file'."
11023 (save-excursion
11024 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11025 (when combine
11026 (setq ical-file org-combined-agenda-icalendar-file
11027 ical-buffer (org-get-agenda-file-buffer ical-file))
11028 (set-buffer ical-buffer) (erase-buffer))
11029 (while (setq file (pop files))
11030 (catch 'nextfile
11031 (org-check-agenda-file file)
11032 (unless combine
11033 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11034 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11035 (set-buffer ical-buffer) (erase-buffer))
11036 (set-buffer (org-get-agenda-file-buffer file))
11037 (setq category (or org-category
11038 (file-name-sans-extension
11039 (file-name-nondirectory (buffer-file-name)))))
11040 (if (symbolp category) (setq category (symbol-name category)))
11041 (let ((standard-output ical-buffer))
11042 (if combine
11043 (and (not started) (setq started t)
11044 (org-start-icalendar-file org-icalendar-combined-name))
11045 (org-start-icalendar-file category))
11046 (org-print-icalendar-entries combine category)
11047 (when (or (and combine (not files)) (not combine))
11048 (org-finish-icalendar-file)
11049 (set-buffer ical-buffer)
11050 (save-buffer)
11051 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11052 (org-release-buffers org-agenda-new-buffers))))
11053
11054 (defvar org-after-save-iCalendar-file-hook nil
11055 "Hook run after an iCalendar file has been saved.
11056 The iCalendar buffer is still current when this hook is run.
11057 A good way to use this is to tell a desktop calenndar application to re-read
11058 the iCalendar file.")
11059
11060 (defun org-print-icalendar-entries (&optional combine category)
11061 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11062 When COMBINE is non nil, add the category to each line."
11063 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11064 (dts (org-ical-ts-to-string
11065 (format-time-string (cdr org-time-stamp-formats) (current-time))
11066 "DTSTART"))
11067 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11068 (save-excursion
11069 (goto-char (point-min))
11070 (while (re-search-forward org-ts-regexp nil t)
11071 (setq pos (match-beginning 0)
11072 ts (match-string 0)
11073 inc t
11074 hd (org-get-heading))
11075 (if (looking-at re2)
11076 (progn
11077 (goto-char (match-end 0))
11078 (setq ts2 (match-string 1) inc nil))
11079 (setq ts2 ts
11080 tmp (buffer-substring (max (point-min)
11081 (- pos org-ds-keyword-length))
11082 pos)
11083 deadlinep (string-match org-deadline-regexp tmp)
11084 scheduledp (string-match org-scheduled-regexp tmp)
11085 ;; donep (org-entry-is-done-p)
11086 ))
11087 (if (or (string-match org-tr-regexp hd)
11088 (string-match org-ts-regexp hd))
11089 (setq hd (replace-match "" t t hd)))
11090 (if combine
11091 (setq hd (concat hd " (category " category ")")))
11092 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11093 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11094 (princ (format "BEGIN:VEVENT
11095 %s
11096 %s
11097 SUMMARY:%s
11098 END:VEVENT\n"
11099 (org-ical-ts-to-string ts "DTSTART")
11100 (org-ical-ts-to-string ts2 "DTEND" inc)
11101 hd)))
11102 (when org-icalendar-include-todo
11103 (goto-char (point-min))
11104 (while (re-search-forward org-todo-line-regexp nil t)
11105 (setq state (match-string 1))
11106 (unless (equal state org-done-string)
11107 (setq hd (match-string 3))
11108 (if (string-match org-priority-regexp hd)
11109 (setq pri (string-to-char (match-string 2 hd))
11110 hd (concat (substring hd 0 (match-beginning 1))
11111 (substring hd (- (match-end 1)))))
11112 (setq pri org-default-priority))
11113 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11114 (- org-lowest-priority ?A))))))
11115
11116 (princ (format "BEGIN:VTODO
11117 %s
11118 SUMMARY:%s
11119 SEQUENCE:1
11120 PRIORITY:%d
11121 END:VTODO\n"
11122 dts hd pri))))))))
11123
11124 (defun org-start-icalendar-file (name)
11125 "Start an iCalendar file by inserting the header."
11126 (let ((user user-full-name)
11127 (name (or name "unknown"))
11128 (timezone (cadr (current-time-zone))))
11129 (princ
11130 (format "BEGIN:VCALENDAR
11131 VERSION:2.0
11132 X-WR-CALNAME:%s
11133 PRODID:-//%s//Emacs with Org-mode//EN
11134 X-WR-TIMEZONE:%s
11135 CALSCALE:GREGORIAN\n" name user timezone))))
11136
11137 (defun org-finish-icalendar-file ()
11138 "Finish an iCalendar file by inserting the END statement."
11139 (princ "END:VCALENDAR\n"))
11140
11141 (defun org-ical-ts-to-string (s keyword &optional inc)
11142 "Take a time string S and convert it to iCalendar format.
11143 KEYWORD is added in front, to make a complete line like DTSTART....
11144 When INC is non-nil, increase the hour by two (if time string contains
11145 a time), or the day by one (if it does not contain a time)."
11146 (let ((t1 (org-parse-time-string s 'nodefault))
11147 t2 fmt have-time time)
11148 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11149 (setq t2 t1 have-time t)
11150 (setq t2 (org-parse-time-string s)))
11151 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11152 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11153 (when inc
11154 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11155 (setq time (encode-time s mi h d m y)))
11156 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11157 (concat keyword (format-time-string fmt time))))
11158
11159
11160 ;;; Key bindings
11161
11162 ;; - Bindings in Org-mode map are currently
11163 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11164 ;; abcd fgh j lmnopqrstuvwxyz!? #$ -+*/= [] ; |,.<>~ \t necessary bindings
11165 ;; e (?) useful from outline-mode
11166 ;; i k @ expendable from outline-mode
11167 ;; 0123456789 %^& ()_{} " `' free
11168
11169 ;; Make `C-c C-x' a prefix key
11170 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11171
11172 ;; TAB key with modifiers
11173 (define-key org-mode-map "\C-i" 'org-cycle)
11174 (define-key org-mode-map [(meta tab)] 'org-complete)
11175 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11176 ;; The following line is necessary under Suse GNU/Linux
11177 (unless org-xemacs-p
11178 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11179 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11180
11181 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11182 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11183 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11184 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11185 (define-key org-mode-map [(meta return)] 'org-meta-return)
11186 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11187 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11188
11189 ;; Cursor keys with modifiers
11190 (define-key org-mode-map [(meta left)] 'org-metaleft)
11191 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11192 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11193 (define-key org-mode-map [(meta right)] 'org-metaright)
11194 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11195 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11196 (define-key org-mode-map [(meta up)] 'org-metaup)
11197 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11198 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11199 (define-key org-mode-map [(meta down)] 'org-metadown)
11200 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11201 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11202
11203 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11204 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11205 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11206 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11207 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11208 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11209 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11210 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11211 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11212 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11213 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11214 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11215 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11216 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11217 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11218 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11219
11220 ;; All the other keys
11221 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11222 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11223 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11224 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11225 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11226 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11227 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11228 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11229 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11230 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11231 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11232 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11233 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11234 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11235 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11236 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11237 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11238 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11239 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11240 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11241 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11242 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11243 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
11244 (define-key org-mode-map "\C-c]" 'org-remove-file)
11245 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
11246 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
11247 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
11248 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11249 (define-key org-mode-map "\C-m" 'org-return)
11250 (define-key org-mode-map "\C-c?" 'org-table-current-column)
11251 (define-key org-mode-map "\C-c " 'org-table-blank-field)
11252 (define-key org-mode-map "\C-c+" 'org-table-sum)
11253 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
11254 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
11255 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
11256 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
11257 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11258 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
11259 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11260 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
11261 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
11262 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
11263 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
11264 ;; OPML support is only an option for the future
11265 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
11266 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
11267 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
11268 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
11269 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
11270 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11271 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
11272 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11273 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
11274 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
11275 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
11276
11277 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11278 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11279 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11280
11281 (defsubst org-table-p () (org-at-table-p))
11282
11283 (defun org-self-insert-command (N)
11284 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11285 If the cursor is in a table looking at whitespace, the whitespace is
11286 overwritten, and the table is not marked as requiring realignment."
11287 (interactive "p")
11288 (if (and (org-table-p)
11289 (or
11290 (and org-table-auto-blank-field
11291 (member last-command
11292 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11293 (org-table-blank-field))
11294 t)
11295 (eq N 1)
11296 (looking-at "[^|\n]* +|"))
11297 (let (org-table-may-need-update)
11298 (goto-char (1- (match-end 0)))
11299 (delete-backward-char 1)
11300 (goto-char (match-beginning 0))
11301 (self-insert-command N))
11302 (setq org-table-may-need-update t)
11303 (self-insert-command N)))
11304
11305 ;; FIXME:
11306 ;; The following two functions might still be optimized to trigger
11307 ;; re-alignment less frequently.
11308
11309 (defun org-delete-backward-char (N)
11310 "Like `delete-backward-char', insert whitespace at field end in tables.
11311 When deleting backwards, in tables this function will insert whitespace in
11312 front of the next \"|\" separator, to keep the table aligned. The table will
11313 still be marked for re-alignment, because a narrow field may lead to a
11314 reduced column width."
11315 (interactive "p")
11316 (if (and (org-table-p)
11317 (eq N 1)
11318 (string-match "|" (buffer-substring (point-at-bol) (point)))
11319 (looking-at ".*?|"))
11320 (let ((pos (point)))
11321 (backward-delete-char N)
11322 (skip-chars-forward "^|")
11323 (insert " ")
11324 (goto-char (1- pos)))
11325 (backward-delete-char N)))
11326
11327 (defun org-delete-char (N)
11328 "Like `delete-char', but insert whitespace at field end in tables.
11329 When deleting characters, in tables this function will insert whitespace in
11330 front of the next \"|\" separator, to keep the table aligned. The table
11331 will still be marked for re-alignment, because a narrow field may lead to
11332 a reduced column width."
11333 (interactive "p")
11334 (if (and (org-table-p)
11335 (not (bolp))
11336 (not (= (char-after) ?|))
11337 (eq N 1))
11338 (if (looking-at ".*?|")
11339 (let ((pos (point)))
11340 (replace-match (concat
11341 (substring (match-string 0) 1 -1)
11342 " |"))
11343 (goto-char pos)))
11344 (delete-char N)))
11345
11346 ;; How to do this: Measure non-white length of current string
11347 ;; If equal to column width, we should realign.
11348
11349 (defun org-remap (map &rest commands)
11350 "In MAP, remap the functions given in COMMANDS.
11351 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11352 (let (new old)
11353 (while commands
11354 (setq old (pop commands) new (pop commands))
11355 (if (fboundp 'command-remapping)
11356 (define-key map (vector 'remap old) new)
11357 (substitute-key-definition old new map global-map)))))
11358
11359 (when (eq org-enable-table-editor 'optimized)
11360 ;; If the user wants maximum table support, we need to hijack
11361 ;; some standard editing functions
11362 (org-remap org-mode-map
11363 'self-insert-command 'org-self-insert-command
11364 'delete-char 'org-delete-char
11365 'delete-backward-char 'org-delete-backward-char)
11366 (define-key org-mode-map "|" 'org-force-self-insert))
11367
11368 (defun org-shiftcursor-error ()
11369 "Throw an error because Shift-Cursor command was applied in wrong context."
11370 (error "This command is active in special context like tables, headlines or timestamps"))
11371
11372 (defun org-shifttab ()
11373 "Global visibility cycling or move to previous table field.
11374 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
11375 See the individual commands for more information."
11376 (interactive)
11377 (cond
11378 ((org-at-table-p) (org-table-previous-field))
11379 (t (org-cycle '(4)))))
11380
11381 (defun org-shiftmetaleft ()
11382 "Promote subtree or delete table column.
11383 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
11384 See the individual commands for more information."
11385 (interactive)
11386 (cond
11387 ((org-at-table-p) (org-table-delete-column))
11388 ((org-on-heading-p) (org-promote-subtree))
11389 ((org-at-item-p) (call-interactively 'org-outdent-item))
11390 (t (org-shiftcursor-error))))
11391
11392 (defun org-shiftmetaright ()
11393 "Demote subtree or insert table column.
11394 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
11395 See the individual commands for more information."
11396 (interactive)
11397 (cond
11398 ((org-at-table-p) (org-table-insert-column))
11399 ((org-on-heading-p) (org-demote-subtree))
11400 ((org-at-item-p) (call-interactively 'org-indent-item))
11401 (t (org-shiftcursor-error))))
11402
11403 (defun org-shiftmetaup (&optional arg)
11404 "Move subtree up or kill table row.
11405 Calls `org-move-subtree-up' or `org-table-kill-row' or
11406 `org-move-item-up' depending on context. See the individual commands
11407 for more information."
11408 (interactive "P")
11409 (cond
11410 ((org-at-table-p) (org-table-kill-row))
11411 ((org-on-heading-p) (org-move-subtree-up arg))
11412 ((org-at-item-p) (org-move-item-up arg))
11413 (t (org-shiftcursor-error))))
11414 (defun org-shiftmetadown (&optional arg)
11415 "Move subtree down or insert table row.
11416 Calls `org-move-subtree-down' or `org-table-insert-row' or
11417 `org-move-item-down', depending on context. See the individual
11418 commands for more information."
11419 (interactive "P")
11420 (cond
11421 ((org-at-table-p) (org-table-insert-row arg))
11422 ((org-on-heading-p) (org-move-subtree-down arg))
11423 ((org-at-item-p) (org-move-item-down arg))
11424 (t (org-shiftcursor-error))))
11425
11426 (defun org-metaleft (&optional arg)
11427 "Promote heading or move table column to left.
11428 Calls `org-do-promote' or `org-table-move-column', depending on context.
11429 With no specific context, calls the Emacs default `backward-word'.
11430 See the individual commands for more information."
11431 (interactive "P")
11432 (cond
11433 ((org-at-table-p) (org-table-move-column 'left))
11434 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
11435 (t (backward-word (prefix-numeric-value arg)))))
11436
11437 (defun org-metaright (&optional arg)
11438 "Demote subtree or move table column to right.
11439 Calls `org-do-demote' or `org-table-move-column', depending on context.
11440 With no specific context, calls the Emacs default `forward-word'.
11441 See the individual commands for more information."
11442 (interactive "P")
11443 (cond
11444 ((org-at-table-p) (org-table-move-column nil))
11445 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
11446 (t (forward-word (prefix-numeric-value arg)))))
11447
11448 (defun org-metaup (&optional arg)
11449 "Move subtree up or move table row up.
11450 Calls `org-move-subtree-up' or `org-table-move-row' or
11451 `org-move-item-up', depending on context. See the individual commands
11452 for more information."
11453 (interactive "P")
11454 (cond
11455 ((org-at-table-p) (org-table-move-row 'up))
11456 ((org-on-heading-p) (org-move-subtree-up arg))
11457 ((org-at-item-p) (org-move-item-up arg))
11458 (t (org-shiftcursor-error))))
11459
11460 (defun org-metadown (&optional arg)
11461 "Move subtree down or move table row down.
11462 Calls `org-move-subtree-down' or `org-table-move-row' or
11463 `org-move-item-down', depending on context. See the individual
11464 commands for more information."
11465 (interactive "P")
11466 (cond
11467 ((org-at-table-p) (org-table-move-row nil))
11468 ((org-on-heading-p) (org-move-subtree-down arg))
11469 ((org-at-item-p) (org-move-item-down arg))
11470 (t (org-shiftcursor-error))))
11471
11472 (defun org-shiftup (&optional arg)
11473 "Increase item in timestamp or increase priority of current item.
11474 Calls `org-timestamp-up' or `org-priority-up', depending on context.
11475 See the individual commands for more information."
11476 (interactive "P")
11477 (cond
11478 ((org-at-timestamp-p) (org-timestamp-up arg))
11479 (t (org-priority-up))))
11480
11481 (defun org-shiftdown (&optional arg)
11482 "Decrease item in timestamp or decrease priority of current item.
11483 Calls `org-timestamp-down' or `org-priority-down', depending on context.
11484 See the individual commands for more information."
11485 (interactive "P")
11486 (cond
11487 ((org-at-timestamp-p) (org-timestamp-down arg))
11488 (t (org-priority-down))))
11489
11490 (defun org-shiftright ()
11491 "Next TODO keyword or timestamp one day later, depending on context."
11492 (interactive)
11493 (cond
11494 ((org-at-timestamp-p) (org-timestamp-up-day))
11495 ((org-on-heading-p) (org-todo 'right))
11496 (t (org-shiftcursor-error))))
11497
11498 (defun org-shiftleft ()
11499 "Previous TODO keyword or timestamp one day earlier, depending on context."
11500 (interactive)
11501 (cond
11502 ((org-at-timestamp-p) (org-timestamp-down-day))
11503 ((org-on-heading-p) (org-todo 'left))
11504 (t (org-shiftcursor-error))))
11505
11506 (defun org-copy-special ()
11507 "Copy region in table or copy current subtree.
11508 Calls `org-table-copy' or `org-copy-subtree', depending on context.
11509 See the individual commands for more information."
11510 (interactive)
11511 (call-interactively
11512 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
11513
11514 (defun org-cut-special ()
11515 "Cut region in table or cut current subtree.
11516 Calls `org-table-copy' or `org-cut-subtree', depending on context.
11517 See the individual commands for more information."
11518 (interactive)
11519 (call-interactively
11520 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
11521
11522 (defun org-paste-special (arg)
11523 "Paste rectangular region into table, or past subtree relative to level.
11524 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
11525 See the individual commands for more information."
11526 (interactive "P")
11527 (if (org-at-table-p)
11528 (org-table-paste-rectangle)
11529 (org-paste-subtree arg)))
11530
11531 (defun org-ctrl-c-ctrl-c (&optional arg)
11532 "Call realign table, or recognize a table.el table, or update keywords.
11533 When the cursor is inside a table created by the table.el package,
11534 activate that table. Otherwise, if the cursor is at a normal table
11535 created with org.el, re-align that table. This command works even if
11536 the automatic table editor has been turned off.
11537
11538 If the cursor is in a headline, prompt for tags and insert them into
11539 the current line, aligned to `org-tags-column'. When in a headline and
11540 called with prefix arg, realign all tags in the current buffer.
11541
11542 If the cursor is in one of the special #+KEYWORD lines, this triggers
11543 scanning the buffer for these lines and updating the information.
11544 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
11545 (interactive "P")
11546 (let ((org-enable-table-editor t))
11547 (cond
11548 ((org-on-heading-p) (org-set-tags arg))
11549 ((org-at-table.el-p)
11550 (require 'table)
11551 (beginning-of-line 1)
11552 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
11553 (table-recognize-table))
11554 ((org-at-table-p)
11555 (org-table-maybe-eval-formula)
11556 (if arg
11557 (org-table-recalculate t)
11558 (org-table-maybe-recalculate-line))
11559 (org-table-align))
11560 ((org-at-item-p)
11561 (org-renumber-ordered-list (prefix-numeric-value arg)))
11562 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
11563 (cond
11564 ((equal (match-string 1) "TBLFM")
11565 ;; Recalculate the table before this line
11566 (save-excursion
11567 (beginning-of-line 1)
11568 (skip-chars-backward " \r\n\t")
11569 (if (org-at-table-p) (org-table-recalculate t))))
11570 (t
11571 (org-mode-restart))))
11572 ((org-region-active-p)
11573 (org-table-convert-region (region-beginning) (region-end) arg))
11574 ((condition-case nil
11575 (and (region-beginning) (region-end))
11576 (error nil))
11577 (if (y-or-n-p "Convert inactive region to table? ")
11578 (org-table-convert-region (region-beginning) (region-end) arg)
11579 (error "Abort")))
11580 (t (error "C-c C-c can do nothing useful at this location.")))))
11581
11582 (defun org-mode-restart ()
11583 "Restart Org-mode, to scan again for special lines.
11584 Also updates the keyword regular expressions."
11585 (interactive)
11586 (let ((org-inhibit-startup t)) (org-mode))
11587 (message "Org-mode restarted to refresh keyword and special line setup"))
11588
11589 (defun org-return ()
11590 "Goto next table row or insert a newline.
11591 Calls `org-table-next-row' or `newline', depending on context.
11592 See the individual commands for more information."
11593 (interactive)
11594 (cond
11595 ((org-at-table-p)
11596 (org-table-justify-field-maybe)
11597 (org-table-next-row))
11598 (t (newline))))
11599
11600 (defun org-meta-return (&optional arg)
11601 "Insert a new heading or wrap a region in a table.
11602 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
11603 See the individual commands for more information."
11604 (interactive "P")
11605 (cond
11606 ((org-at-table-p)
11607 (org-table-wrap-region arg))
11608 (t (org-insert-heading arg))))
11609
11610 ;;; Menu entries
11611
11612 ;; Define the Org-mode menus
11613 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
11614 '("Tbl"
11615 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
11616 ["Next Field" org-cycle (org-at-table-p)]
11617 ["Previous Field" org-shifttab (org-at-table-p)]
11618 ["Next Row" org-return (org-at-table-p)]
11619 "--"
11620 ["Blank Field" org-table-blank-field (org-at-table-p)]
11621 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
11622 "--"
11623 ("Column"
11624 ["Move Column Left" org-metaleft (org-at-table-p)]
11625 ["Move Column Right" org-metaright (org-at-table-p)]
11626 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
11627 ["Insert Column" org-shiftmetaright (org-at-table-p)])
11628 ("Row"
11629 ["Move Row Up" org-metaup (org-at-table-p)]
11630 ["Move Row Down" org-metadown (org-at-table-p)]
11631 ["Delete Row" org-shiftmetaup (org-at-table-p)]
11632 ["Insert Row" org-shiftmetadown (org-at-table-p)]
11633 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
11634 "--"
11635 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
11636 ("Rectangle"
11637 ["Copy Rectangle" org-copy-special (org-at-table-p)]
11638 ["Cut Rectangle" org-cut-special (org-at-table-p)]
11639 ["Paste Rectangle" org-paste-special (org-at-table-p)]
11640 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
11641 "--"
11642 ("Calculate"
11643 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
11644 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11645 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
11646 "--"
11647 ["Recalculate line" org-table-recalculate (org-at-table-p)]
11648 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
11649 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
11650 "--"
11651 ["Sum Column/Rectangle" org-table-sum
11652 (or (org-at-table-p) (org-region-active-p))]
11653 ["Which Column?" org-table-current-column (org-at-table-p)])
11654 ["Debug Formulas"
11655 (setq org-table-formula-debug (not org-table-formula-debug))
11656 :style toggle :selected org-table-formula-debug]
11657 "--"
11658 ["Invisible Vlines" org-table-toggle-vline-visibility
11659 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
11660 "--"
11661 ["Create" org-table-create (and (not (org-at-table-p))
11662 org-enable-table-editor)]
11663 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
11664 ["Import from File" org-table-import (not (org-at-table-p))]
11665 ["Export to File" org-table-export (org-at-table-p)]
11666 "--"
11667 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
11668
11669 (easy-menu-define org-org-menu org-mode-map "Org menu"
11670 '("Org"
11671 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
11672 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
11673 ["Sparse Tree" org-occur t]
11674 ["Show All" show-all t]
11675 "--"
11676 ["New Heading" org-insert-heading t]
11677 ("Navigate Headings"
11678 ["Up" outline-up-heading t]
11679 ["Next" outline-next-visible-heading t]
11680 ["Previous" outline-previous-visible-heading t]
11681 ["Next Same Level" outline-forward-same-level t]
11682 ["Previous Same Level" outline-backward-same-level t]
11683 "--"
11684 ["Jump" org-goto t])
11685 ("Edit Structure"
11686 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
11687 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
11688 "--"
11689 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
11690 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
11691 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
11692 "--"
11693 ["Promote Heading" org-metaleft (not (org-at-table-p))]
11694 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
11695 ["Demote Heading" org-metaright (not (org-at-table-p))]
11696 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
11697 "--"
11698 ["Archive Subtree" org-archive-subtree t])
11699 "--"
11700 ("TODO Lists"
11701 ["TODO/DONE/-" org-todo t]
11702 ["Show TODO Tree" org-show-todo-tree t]
11703 ["Global TODO list" org-todo-list t]
11704 "--"
11705 ["Set Priority" org-priority t]
11706 ["Priority Up" org-shiftup t]
11707 ["Priority Down" org-shiftdown t])
11708 ("Dates and Scheduling"
11709 ["Timestamp" org-time-stamp t]
11710 ["Timestamp (inactive)" org-time-stamp-inactive t]
11711 ("Change Date"
11712 ["1 Day Later" org-timestamp-up-day t]
11713 ["1 Day Earlier" org-timestamp-down-day t]
11714 ["1 ... Later" org-shiftup t]
11715 ["1 ... Earlier" org-shiftdown t])
11716 ["Compute Time Range" org-evaluate-time-range t]
11717 ["Schedule Item" org-schedule t]
11718 ["Deadline" org-deadline t]
11719 "--"
11720 ["Goto Calendar" org-goto-calendar t]
11721 ["Date from Calendar" org-date-from-calendar t])
11722 "--"
11723 ["Agenda Command" org-agenda t]
11724 ("File List for Agenda")
11725 ("Special views current file"
11726 ["TODO Tree" org-show-todo-tree t]
11727 ["Check Deadlines" org-check-deadlines t]
11728 ["Timeline" org-timeline t]
11729 ["Tags Tree" org-tags-sparse-tree t])
11730 "--"
11731 ("Hyperlinks"
11732 ["Store Link (Global)" org-store-link t]
11733 ["Insert Link" org-insert-link t]
11734 ["Follow Link" org-open-at-point t])
11735 "--"
11736 ("Export"
11737 ["ASCII" org-export-as-ascii t]
11738 ["Extract Visible Text" org-export-copy-visible t]
11739 ["HTML" org-export-as-html t]
11740 ["HTML and Open" org-export-as-html-and-open t]
11741 ; ["OPML" org-export-as-opml nil]
11742 "--"
11743 ["iCalendar this file" org-export-icalendar-this-file t]
11744 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
11745 :active t :keys "C-c C-x C-i"]
11746 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
11747 "--"
11748 ["Option Template" org-insert-export-options-template t]
11749 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
11750 "--"
11751 ("Documentation"
11752 ["Show Version" org-version t]
11753 ["Info Documentation" org-info t])
11754 ("Customize"
11755 ["Browse Org Group" org-customize t]
11756 "--"
11757 ["Build Full Customize Menu" org-create-customize-menu
11758 (fboundp 'customize-menu-create)])
11759 "--"
11760 ["Refresh setup" org-mode-restart t]
11761 ))
11762
11763 (defun org-info (&optional node)
11764 "Read documentation for Org-mode in the info system.
11765 With optional NODE, go directly to that node."
11766 (interactive)
11767 (require 'info)
11768 (Info-goto-node (format "(org)%s" (or node ""))))
11769
11770 (defun org-install-agenda-files-menu ()
11771 (easy-menu-change
11772 '("Org") "File List for Agenda"
11773 (append
11774 (list
11775 ["Edit File List" (customize-variable 'org-agenda-files) t]
11776 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
11777 ["Remove Current File from List" org-remove-file t]
11778 ["Cycle through agenda files" org-cycle-agenda-files t]
11779 "--")
11780 (mapcar 'org-file-menu-entry org-agenda-files))))
11781
11782 ;;; Documentation
11783
11784 (defun org-customize ()
11785 "Call the customize function with org as argument."
11786 (interactive)
11787 (customize-browse 'org))
11788
11789 (defun org-create-customize-menu ()
11790 "Create a full customization menu for Org-mode, insert it into the menu."
11791 (interactive)
11792 (if (fboundp 'customize-menu-create)
11793 (progn
11794 (easy-menu-change
11795 '("Org") "Customize"
11796 `(["Browse Org group" org-customize t]
11797 "--"
11798 ,(customize-menu-create 'org)
11799 ["Set" Custom-set t]
11800 ["Save" Custom-save t]
11801 ["Reset to Current" Custom-reset-current t]
11802 ["Reset to Saved" Custom-reset-saved t]
11803 ["Reset to Standard Settings" Custom-reset-standard t]))
11804 (message "\"Org\"-menu now contains full customization menu"))
11805 (error "Cannot expand menu (outdated version of cus-edit.el)")))
11806
11807 ;;; Miscellaneous stuff
11808
11809 (defun org-move-line-down (arg)
11810 "Move the current line down. With prefix argument, move it past ARG lines."
11811 (interactive "p")
11812 (let ((col (current-column))
11813 beg end pos)
11814 (beginning-of-line 1) (setq beg (point))
11815 (beginning-of-line 2) (setq end (point))
11816 (beginning-of-line (+ 1 arg))
11817 (setq pos (move-marker (make-marker) (point)))
11818 (insert (delete-and-extract-region beg end))
11819 (goto-char pos)
11820 (move-to-column col)))
11821
11822 (defun org-move-line-up (arg)
11823 "Move the current line up. With prefix argument, move it past ARG lines."
11824 (interactive "p")
11825 (let ((col (current-column))
11826 beg end pos)
11827 (beginning-of-line 1) (setq beg (point))
11828 (beginning-of-line 2) (setq end (point))
11829 (beginning-of-line (- arg))
11830 (setq pos (move-marker (make-marker) (point)))
11831 (insert (delete-and-extract-region beg end))
11832 (goto-char pos)
11833 (move-to-column col)))
11834
11835 ;; Paragraph filling stuff.
11836 ;; We want this to be just right, so use the full arsenal.
11837 ;; FIXME: This very likely does not work correctly for XEmacs, because the
11838 ;; filladapt package works slightly differently.
11839
11840 (defun org-set-autofill-regexps ()
11841 (interactive)
11842 ;; In the paragraph separator we include headlines, because filling
11843 ;; text in a line directly attached to a headline would otherwise
11844 ;; fill the headline as well.
11845 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
11846 ;; The paragraph starter includes hand-formatted lists.
11847 (set (make-local-variable 'paragraph-start)
11848 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
11849 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
11850 ;; But only if the user has not turned off tables or fixed-width regions
11851 (set (make-local-variable 'auto-fill-inhibit-regexp)
11852 (concat "\\*\\|#"
11853 (if (or org-enable-table-editor org-enable-fixed-width-editor)
11854 (concat
11855 "\\|[ \t]*["
11856 (if org-enable-table-editor "|" "")
11857 (if org-enable-fixed-width-editor ":" "")
11858 "]"))))
11859 ;; We use our own fill-paragraph function, to make sure that tables
11860 ;; and fixed-width regions are not wrapped. That function will pass
11861 ;; through to `fill-paragraph' when appropriate.
11862 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
11863 ;; Adaptive filling: To get full control, first make sure that
11864 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
11865 (setq adaptive-fill-regexp "\000")
11866 (setq adaptive-fill-function 'org-adaptive-fill-function))
11867
11868 (defun org-fill-paragraph (&optional justify)
11869 "Re-align a table, pass through to fill-paragraph if no table."
11870 (let ((table-p (org-at-table-p))
11871 (table.el-p (org-at-table.el-p)))
11872 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
11873 (table.el-p t) ; skip table.el tables
11874 (table-p (org-table-align) t) ; align org-mode tables
11875 (t nil)))) ; call paragraph-fill
11876
11877 ;; For reference, this is the default value of adaptive-fill-regexp
11878 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
11879
11880 (defun org-adaptive-fill-function ()
11881 "Return a fill prefix for org-mode files.
11882 In particular, this makes sure hanging paragraphs for hand-formatted lists
11883 work correctly."
11884 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
11885 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11886
11887 ;; Functions needed for Emacs/XEmacs region compatibility
11888
11889 (defun org-region-active-p ()
11890 "Is `transient-mark-mode' on and the region active?
11891 Works on both Emacs and XEmacs."
11892 (if org-ignore-region
11893 nil
11894 (if org-xemacs-p
11895 (and zmacs-regions (region-active-p))
11896 (and transient-mark-mode mark-active))))
11897
11898 (defun org-add-to-invisibility-spec (arg)
11899 "Add elements to `buffer-invisibility-spec'.
11900 See documentation for `buffer-invisibility-spec' for the kind of elements
11901 that can be added."
11902 (cond
11903 ((fboundp 'add-to-invisibility-spec)
11904 (add-to-invisibility-spec arg))
11905 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
11906 (setq buffer-invisibility-spec (list arg)))
11907 (t
11908 (setq buffer-invisibility-spec
11909 (cons arg buffer-invisibility-spec)))))
11910
11911 (defun org-remove-from-invisibility-spec (arg)
11912 "Remove elements from `buffer-invisibility-spec'."
11913 (if (fboundp 'remove-from-invisibility-spec)
11914 (remove-from-invisibility-spec arg)
11915 (if (consp buffer-invisibility-spec)
11916 (setq buffer-invisibility-spec
11917 (delete arg buffer-invisibility-spec)))))
11918
11919 (defun org-in-invisibility-spec-p (arg)
11920 "Is ARG a member of `buffer-invisibility-spec'?."
11921 (if (consp buffer-invisibility-spec)
11922 (member arg buffer-invisibility-spec)
11923 nil))
11924
11925 (defun org-image-file-name-regexp ()
11926 "Return regexp matching the file names of images."
11927 (if (fboundp 'image-file-name-regexp)
11928 (image-file-name-regexp)
11929 (let ((image-file-name-extensions
11930 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
11931 "xbm" "xpm" "pbm" "pgm" "ppm")))
11932 (concat "\\."
11933 (regexp-opt (nconc (mapcar 'upcase
11934 image-file-name-extensions)
11935 image-file-name-extensions)
11936 t)
11937 "\\'"))))
11938
11939 ;; Functions needed for compatibility with old outline.el.
11940
11941 ;; Programming for the old outline.el (that uses selective display
11942 ;; instead of `invisible' text properties) is a nightmare, mostly
11943 ;; because regular expressions can no longer be anchored at
11944 ;; beginning/end of line. Therefore a number of function need special
11945 ;; treatment when the old outline.el is being used.
11946
11947 ;; The following functions capture almost the entire compatibility code
11948 ;; between the different versions of outline-mode. The only other
11949 ;; places where this is important are the font-lock-keywords, and in
11950 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
11951
11952 ;; C-a should go to the beginning of a *visible* line, also in the
11953 ;; new outline.el. I guess this should be patched into Emacs?
11954 (defun org-beginning-of-line ()
11955 "Go to the beginning of the current line. If that is invisible, continue
11956 to a visible line beginning. This makes the function of C-a more intuitive."
11957 (interactive)
11958 (beginning-of-line 1)
11959 (if (bobp)
11960 nil
11961 (backward-char 1)
11962 (if (org-invisible-p)
11963 (while (and (not (bobp)) (org-invisible-p))
11964 (backward-char 1)
11965 (beginning-of-line 1))
11966 (forward-char 1))))
11967
11968 (when org-noutline-p
11969 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
11970 ;; FIXME: should I use substitute-key-definition to reach other bindings
11971 ;; of beginning-of-line?
11972
11973 (defun org-invisible-p ()
11974 "Check if point is at a character currently not visible."
11975 (if org-noutline-p
11976 ;; Early versions of noutline don't have `outline-invisible-p'.
11977 (if (fboundp 'outline-invisible-p)
11978 (outline-invisible-p)
11979 (get-char-property (point) 'invisible))
11980 (save-excursion
11981 (skip-chars-backward "^\r\n")
11982 (equal (char-before) ?\r))))
11983
11984 (defun org-back-to-heading (&optional invisible-ok)
11985 "Move to previous heading line, or beg of this line if it's a heading.
11986 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
11987 (if org-noutline-p
11988 (outline-back-to-heading invisible-ok)
11989 (if (and (memq (char-before) '(?\n ?\r))
11990 (looking-at outline-regexp))
11991 t
11992 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
11993 outline-regexp)
11994 nil t)
11995 (if invisible-ok
11996 (progn (goto-char (match-end 1))
11997 (looking-at outline-regexp)))
11998 (error "Before first heading")))))
11999
12000 (defun org-on-heading-p (&optional invisible-ok)
12001 "Return t if point is on a (visible) heading line.
12002 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12003 (if org-noutline-p
12004 (outline-on-heading-p 'invisible-ok)
12005 (save-excursion
12006 (skip-chars-backward "^\n\r")
12007 (and (looking-at outline-regexp)
12008 (or invisible-ok
12009 (bobp)
12010 (equal (char-before) ?\n))))))
12011
12012 (defun org-up-heading-all (arg)
12013 "Move to the heading line of which the present line is a subheading.
12014 This function considers both visible and invisible heading lines.
12015 With argument, move up ARG levels."
12016 (if org-noutline-p
12017 (if (fboundp 'outline-up-heading-all)
12018 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12019 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12020 (org-back-to-heading t)
12021 (looking-at outline-regexp)
12022 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12023 (error "Cannot move up %d levels" arg)
12024 (re-search-backward
12025 (concat "[\n\r]" (regexp-quote
12026 (make-string (- (match-end 0) (match-beginning 0) arg)
12027 ?*))
12028 "[^*]"))
12029 (forward-char 1))))
12030
12031 (defun org-show-hidden-entry ()
12032 "Show an entry where even the heading is hidden."
12033 (save-excursion
12034 (if (not org-noutline-p)
12035 (progn
12036 (org-back-to-heading t)
12037 (org-flag-heading nil)))
12038 (org-show-entry)))
12039
12040 (defun org-check-occur-regexp (regexp)
12041 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12042 Of course, only for the old outline mode."
12043 (if org-noutline-p
12044 regexp
12045 (if (string-match "^\\^" regexp)
12046 (concat "[\n\r]" (substring regexp 1))
12047 regexp)))
12048
12049 (defun org-flag-heading (flag &optional entry)
12050 "Flag the current heading. FLAG non-nil means make invisible.
12051 When ENTRY is non-nil, show the entire entry."
12052 (save-excursion
12053 (org-back-to-heading t)
12054 (if (not org-noutline-p)
12055 ;; Make the current headline visible
12056 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12057 ;; Check if we should show the entire entry
12058 (if entry
12059 (progn
12060 (org-show-entry)
12061 (save-excursion ;; FIXME: Is this the fix for points in the -|
12062 ;; middle of text? |
12063 (and (outline-next-heading) ;; |
12064 (org-flag-heading nil)))) ; show the next heading _|
12065 (outline-flag-region (max 1 (1- (point)))
12066 (save-excursion (outline-end-of-heading) (point))
12067 (if org-noutline-p
12068 flag
12069 (if flag ?\r ?\n))))))
12070
12071 (defun org-end-of-subtree (&optional invisible-OK)
12072 ;; This is an exact copy of the original function, but it uses
12073 ;; `org-back-to-heading', to make it work also in invisible
12074 ;; trees. And is uses an invisible-OK argument.
12075 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
12076 (org-back-to-heading invisible-OK)
12077 (let ((opoint (point))
12078 (first t)
12079 (level (funcall outline-level)))
12080 (while (and (not (eobp))
12081 (or first (> (funcall outline-level) level)))
12082 (setq first nil)
12083 (outline-next-heading))
12084 (if (memq (preceding-char) '(?\n ?\^M))
12085 (progn
12086 ;; Go to end of line before heading
12087 (forward-char -1)
12088 (if (memq (preceding-char) '(?\n ?\^M))
12089 ;; leave blank line before heading
12090 (forward-char -1))))))
12091
12092 (defun org-show-subtree ()
12093 "Show everything after this heading at deeper levels."
12094 (outline-flag-region
12095 (point)
12096 (save-excursion
12097 (outline-end-of-subtree) (outline-next-heading) (point))
12098 (if org-noutline-p nil ?\n)))
12099
12100 (defun org-show-entry ()
12101 "Show the body directly following this heading.
12102 Show the heading too, if it is currently invisible."
12103 (interactive)
12104 (save-excursion
12105 (org-back-to-heading t)
12106 (outline-flag-region
12107 (1- (point))
12108 (save-excursion
12109 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12110 (or (match-beginning 1) (point-max)))
12111 (if org-noutline-p nil ?\n))))
12112
12113
12114 (defun org-make-options-regexp (kwds)
12115 "Make a regular expression for keyword lines."
12116 (concat
12117 (if org-noutline-p "^" "[\n\r]")
12118 "#?[ \t]*\\+\\("
12119 (mapconcat 'regexp-quote kwds "\\|")
12120 "\\):[ \t]*"
12121 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12122
12123 ;; Make `bookmark-jump' show the jump location if it was hidden.
12124 (eval-after-load "bookmark"
12125 '(if (boundp 'bookmark-after-jump-hook)
12126 ;; We can use the hook
12127 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12128 ;; Hook not available, use advice
12129 (defadvice bookmark-jump (after org-make-visible activate)
12130 "Make the position visible."
12131 (org-bookmark-jump-unhide))))
12132
12133 (defun org-bookmark-jump-unhide ()
12134 "Unhide the current position, to show the bookmark location."
12135 (and (eq major-mode 'org-mode)
12136 (or (org-invisible-p)
12137 (save-excursion (goto-char (max (point-min) (1- (point))))
12138 (org-invisible-p)))
12139 (org-show-hierarchy-above)))
12140
12141 ;;; Finish up
12142
12143 (provide 'org)
12144
12145 (run-hooks 'org-load-hook)
12146
12147 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12148 ;;; org.el ends here
12149
12150
12151 (defun org-get-tags-at (&optional pos)
12152 "Get a list of all headline targs applicable at POS.
12153 POS defaults to point. If tags are inherited, the list contains
12154 the targets in the same sequence as the headlines appear, i.e.
12155 the tags of the current headline come last."
12156 (interactive)
12157 (let (tags)
12158 (save-excursion
12159 (goto-char (or pos (point)))
12160 (save-match-data
12161 (org-back-to-heading t)
12162 (condition-case nil
12163 (while t
12164 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
12165 (setq tags (append (org-split-string (match-string 1) ":") tags)))
12166 (or org-use-tag-inheritance (error ""))
12167 (org-up-heading-all 1))
12168 (error nil))))
12169 (message "%s" tags)
12170 tags))
12171