]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
Move defvars out of eval-when-compile. Move code
[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 (defvar zmacs-regions)
1879 (defvar original-date)
1880 (defvar org-transient-mark-mode)
1881 (defvar org-old-auto-fill-inhibit-regexp)
1882 (defvar orgtbl-mode-menu)
1883 (defvar org-html-entities)
1884 (defvar org-goto-start-pos)
1885 (defvar org-cursor-color)
1886 (defvar org-time-was-given)
1887 (defvar org-ts-what)
1888 (defvar mark-active)
1889 (defvar timecnt)
1890 (defvar levels-open)
1891 (defvar title)
1892 (defvar author)
1893 (defvar email)
1894 (defvar text)
1895 (defvar entry)
1896 (defvar date)
1897 (defvar language)
1898 (defvar options)
1899 (defvar ans1)
1900 (defvar ans2)
1901 (defvar starting-day)
1902 (defvar include-all-loc)
1903 (defvar vm-message-pointer)
1904 (defvar vm-folder-directory)
1905 (defvar wl-summary-buffer-elmo-folder)
1906 (defvar wl-summary-buffer-folder-name)
1907 (defvar gnus-group-name)
1908 (defvar gnus-article-current)
1909 (defvar w3m-current-url)
1910 (defvar org-selected-point)
1911 (defvar calendar-mode-map)
1912 (defvar remember-save-after-remembering)
1913 (defvar remember-data-file)
1914
1915
1916 ;;; Define the mode
1917
1918 (defvar org-mode-map (copy-keymap outline-mode-map)
1919 "Keymap for Org-mode.")
1920
1921 (defvar org-struct-menu)
1922 (defvar org-org-menu)
1923 (defvar org-tbl-menu)
1924
1925 ;; We use a before-change function to check if a table might need
1926 ;; an update.
1927 (defvar org-table-may-need-update t
1928 "Indicates of a table might need an update.
1929 This variable is set by `org-before-change-function'. `org-table-align'
1930 sets it back to nil.")
1931 (defvar org-mode-hook nil)
1932 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1933 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
1934
1935
1936 ;;;###autoload
1937 (define-derived-mode org-mode outline-mode "Org"
1938 "Outline-based notes management and organizer, alias
1939 \"Carstens outline-mode for keeping track of everything.\"
1940
1941 Org-mode develops organizational tasks around a NOTES file which
1942 contains information about projects as plain text. Org-mode is
1943 implemented on top of outline-mode, which is ideal to keep the content
1944 of large files well structured. It supports ToDo items, deadlines and
1945 time stamps, which magically appear in the diary listing of the Emacs
1946 calendar. Tables are easily created with a built-in table editor.
1947 Plain text URL-like links connect to websites, emails (VM), Usenet
1948 messages (Gnus), BBDB entries, and any files related to the project.
1949 For printing and sharing of notes, an Org-mode file (or a part of it)
1950 can be exported as a structured ASCII or HTML file.
1951
1952 The following commands are available:
1953
1954 \\{org-mode-map}"
1955 (easy-menu-add org-org-menu)
1956 (easy-menu-add org-tbl-menu)
1957 (org-install-agenda-files-menu)
1958 (setq outline-regexp "\\*+")
1959 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
1960 (setq outline-level 'org-outline-level)
1961 (if org-startup-truncated (setq truncate-lines t))
1962 (org-set-regexps-and-options)
1963 (set (make-local-variable 'font-lock-unfontify-region-function)
1964 'org-unfontify-region)
1965 ;; Activate before-change-function
1966 (set (make-local-variable 'org-table-may-need-update) t)
1967 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1968 (add-hook 'before-change-functions 'org-before-change-function nil
1969 'local)
1970 ;; FIXME: The following does not work because isearch-mode-end-hook
1971 ;; is called *before* the visibility overlays as removed.
1972 ;; There should be another hook then for me to be used.
1973 ;; (make-local-hook 'isearch-mode-end-hook) ;; needed for XEmacs
1974 ;; (add-hook 'isearch-mode-end-hook 'org-show-hierarchy-above nil
1975 ;; 'local)
1976 ;; Paragraphs and auto-filling
1977 (org-set-autofill-regexps)
1978 ;; Settings for Calc embedded mode
1979 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
1980 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
1981 (if (and org-insert-mode-line-in-empty-file
1982 (interactive-p)
1983 (= (point-min) (point-max)))
1984 (insert " -*- mode: org -*-\n\n"))
1985
1986 ;; Get rid of Outline menus, they are not needed
1987 ;; Need to do this here because define-derived-mode sets up
1988 ;; the keymap so late.
1989 (if org-xemacs-p
1990 (progn
1991 (delete-menu-item '("Headings"))
1992 (delete-menu-item '("Show"))
1993 (delete-menu-item '("Hide"))
1994 (set-menubar-dirty-flag))
1995 (define-key org-mode-map [menu-bar headings] 'undefined)
1996 (define-key org-mode-map [menu-bar hide] 'undefined)
1997 (define-key org-mode-map [menu-bar show] 'undefined))
1998
1999 (unless org-inhibit-startup
2000 (if org-startup-with-deadline-check
2001 (call-interactively 'org-check-deadlines)
2002 (cond
2003 ((eq org-startup-folded t)
2004 (org-cycle '(4)))
2005 ((eq org-startup-folded 'content)
2006 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2007 (org-cycle '(4)) (org-cycle '(4))))))))
2008
2009 (defsubst org-current-line (&optional pos)
2010 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2011
2012
2013 ;; FIXME: Do we need to copy?
2014 (defun org-string-props (string &rest properties)
2015 "Add PROPERTIES to string."
2016 (add-text-properties 0 (length string) properties string)
2017 string)
2018
2019 ;;; Font-Lock stuff
2020
2021 (defvar org-mouse-map (make-sparse-keymap))
2022 (define-key org-mouse-map
2023 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2024 (define-key org-mouse-map
2025 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2026 (when org-tab-follows-link
2027 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2028 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2029 (when org-return-follows-link
2030 (define-key org-mouse-map [(return)] 'org-open-at-point)
2031 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2032
2033 (require 'font-lock)
2034
2035 (defconst org-non-link-chars "\t\n\r|<>\000")
2036 (defconst org-link-regexp
2037 (if org-allow-space-in-links
2038 (concat
2039 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2040 (concat
2041 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2042 )
2043 "Regular expression for matching links.")
2044 (defconst org-link-maybe-angles-regexp
2045 (concat "<?\\(" org-link-regexp "\\)>?")
2046 "Matches a link and optionally surrounding angle brackets.")
2047 (defconst org-protected-link-regexp
2048 (concat "\000" org-link-regexp "\000")
2049 "Matches a link and optionally surrounding angle brackets.")
2050
2051 (defconst org-ts-lengths
2052 (cons (length (format-time-string (car org-time-stamp-formats)))
2053 (length (format-time-string (cdr org-time-stamp-formats))))
2054 "This holds the lengths of the two different time formats.")
2055 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2056 "Regular expression for fast time stamp matching.")
2057 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2058 "Regular expression for fast time stamp matching.")
2059 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2060 "Regular expression matching time strings for analysis.")
2061 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2062 "Regular expression matching time stamps, with groups.")
2063 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2064 "Regular expression matching a time stamp range.")
2065 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2066 org-ts-regexp "\\)?")
2067 "Regular expression matching a time stamp or time stamp range.")
2068
2069 (defun org-activate-links (limit)
2070 "Run through the buffer and add overlays to links."
2071 (if (re-search-forward org-link-regexp limit t)
2072 (progn
2073 (add-text-properties (match-beginning 0) (match-end 0)
2074 (list 'mouse-face 'highlight
2075 'keymap org-mouse-map))
2076 t)))
2077
2078 (defun org-activate-dates (limit)
2079 "Run through the buffer and add overlays to dates."
2080 (if (re-search-forward org-tsr-regexp limit t)
2081 (progn
2082 (add-text-properties (match-beginning 0) (match-end 0)
2083 (list 'mouse-face 'highlight
2084 'keymap org-mouse-map))
2085 t)))
2086
2087 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2088 "Matches CamelCase words, possibly with a star before it.")
2089 (defun org-activate-camels (limit)
2090 "Run through the buffer and add overlays to dates."
2091 (if (re-search-forward org-camel-regexp limit t)
2092 (progn
2093 (add-text-properties (match-beginning 0) (match-end 0)
2094 (list 'mouse-face 'highlight
2095 'keymap org-mouse-map))
2096 t)))
2097
2098 (defun org-activate-tags (limit)
2099 (if (re-search-forward "[ \t]\\(:[A-Za-z_:]+:\\)[ \r\n]" limit t)
2100 (progn
2101 (add-text-properties (match-beginning 1) (match-end 1)
2102 (list 'mouse-face 'highlight
2103 'keymap org-mouse-map))
2104 t)))
2105
2106 (defun org-font-lock-level ()
2107 (save-excursion
2108 (org-back-to-heading t)
2109 (- (match-end 0) (match-beginning 0))))
2110
2111 (defun org-outline-level ()
2112 (save-excursion
2113 (looking-at outline-regexp)
2114 (if (match-beginning 1)
2115 (+ (org-get-string-indentation (match-string 1)) 1000)
2116 (- (match-end 0) (match-beginning 0)))))
2117
2118 (defvar org-font-lock-keywords nil)
2119
2120 (defun org-set-font-lock-defaults ()
2121 (let ((org-font-lock-extra-keywords
2122 (list
2123 '(org-activate-links (0 'org-link t))
2124 '(org-activate-dates (0 'org-link t))
2125 '(org-activate-camels (0 'org-link t))
2126 '(org-activate-tags (1 'org-link t))
2127 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2128 '(1 'org-warning t))
2129 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2130 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2131 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2132 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2133 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2134 ;; (3 'bold))
2135 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2136 ;; (3 'italic))
2137 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2138 ;; (3 'underline))
2139 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2140 ; '(1 'org-warning t))
2141 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2142 "\\|" org-quote-string "\\)\\>")
2143 '(1 'org-special-keyword t))
2144 '("^#.*" (0 'font-lock-comment-face t))
2145 (if org-fontify-done-headline
2146 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2147 '(1 'org-done t) '(2 'org-headline-done t))
2148 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2149 '(1 'org-done t)))
2150 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2151 (1 'org-table t))
2152 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2153 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2154 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2155 )))
2156 (set (make-local-variable 'org-font-lock-keywords)
2157 (append
2158 (if org-noutline-p ; FIXME: I am not sure if eval will work
2159 ; on XEmacs if noutline is ever ported
2160 `((eval . (list "^\\(\\*+\\).*"
2161 ,(if org-level-color-stars-only 1 0)
2162 '(nth
2163 (% (- (match-end 1) (match-beginning 1) 1)
2164 org-n-levels)
2165 org-level-faces)
2166 nil t)))
2167 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2168 (,(if org-level-color-stars-only 2 0)
2169 (nth (% (- (match-end 2) (match-beginning 2) 1)
2170 org-n-levels)
2171 org-level-faces)
2172 nil t))))
2173 org-font-lock-extra-keywords))
2174 (set (make-local-variable 'font-lock-defaults)
2175 '(org-font-lock-keywords t nil nil backward-paragraph))
2176 (kill-local-variable 'font-lock-keywords) nil))
2177
2178 (defun org-unfontify-region (beg end &optional maybe_loudly)
2179 "Remove fontification and activation overlays from links."
2180 (font-lock-default-unfontify-region beg end)
2181 (let* ((buffer-undo-list t)
2182 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2183 (inhibit-modification-hooks t)
2184 deactivate-mark buffer-file-name buffer-file-truename)
2185 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2186
2187 ;;; Visibility cycling
2188
2189 (defvar org-cycle-global-status nil)
2190 (defvar org-cycle-subtree-status nil)
2191 (defun org-cycle (&optional arg)
2192 "Visibility cycling for Org-mode.
2193
2194 - When this function is called with a prefix argument, rotate the entire
2195 buffer through 3 states (global cycling)
2196 1. OVERVIEW: Show only top-level headlines.
2197 2. CONTENTS: Show all headlines of all levels, but no body text.
2198 3. SHOW ALL: Show everything.
2199
2200 - When point is at the beginning of a headline, rotate the subtree started
2201 by this line through 3 different states (local cycling)
2202 1. FOLDED: Only the main headline is shown.
2203 2. CHILDREN: The main headline and the direct children are shown. From
2204 this state, you can move to one of the children and
2205 zoom in further.
2206 3. SUBTREE: Show the entire subtree, including body text.
2207
2208 - When there is a numeric prefix, go up to a heading with level ARG, do
2209 a `show-subtree' and return to the previous cursor position. If ARG
2210 is negative, go up that many levels.
2211
2212 - When point is not at the beginning of a headline, execute
2213 `indent-relative', like TAB normally does. See the option
2214 `org-cycle-emulate-tab' for details.
2215
2216 - Special case: if point is the the beginning of the buffer and there is
2217 no headline in line 1, this function will act as if called with prefix arg."
2218 (interactive "P")
2219
2220 (if (or (and (bobp) (not (looking-at outline-regexp)))
2221 (equal arg '(4)))
2222 ;; special case: use global cycling
2223 (setq arg t))
2224
2225 (let ((outline-regexp
2226 (if org-cycle-include-plain-lists
2227 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2228 outline-regexp)))
2229
2230 (cond
2231
2232 ((org-at-table-p 'any)
2233 ;; Enter the table or move to the next field in the table
2234 (or (org-table-recognize-table.el)
2235 (progn
2236 (org-table-justify-field-maybe)
2237 (org-table-next-field))))
2238
2239 ((eq arg t) ;; Global cycling
2240
2241 (cond
2242 ((and (eq last-command this-command)
2243 (eq org-cycle-global-status 'overview))
2244 ;; We just created the overview - now do table of contents
2245 ;; This can be slow in very large buffers, so indicate action
2246 (message "CONTENTS...")
2247 (save-excursion
2248 ;; Visit all headings and show their offspring
2249 (goto-char (point-max))
2250 (catch 'exit
2251 (while (and (progn (condition-case nil
2252 (outline-previous-visible-heading 1)
2253 (error (goto-char (point-min))))
2254 t)
2255 (looking-at outline-regexp))
2256 (show-branches)
2257 (if (bobp) (throw 'exit nil))))
2258 (message "CONTENTS...done"))
2259 (setq org-cycle-global-status 'contents)
2260 (run-hook-with-args 'org-cycle-hook 'contents))
2261
2262 ((and (eq last-command this-command)
2263 (eq org-cycle-global-status 'contents))
2264 ;; We just showed the table of contents - now show everything
2265 (show-all)
2266 (message "SHOW ALL")
2267 (setq org-cycle-global-status 'all)
2268 (run-hook-with-args 'org-cycle-hook 'all))
2269
2270 (t
2271 ;; Default action: go to overview
2272 (hide-sublevels 1)
2273 (message "OVERVIEW")
2274 (setq org-cycle-global-status 'overview)
2275 (run-hook-with-args 'org-cycle-hook 'overview))))
2276
2277 ((integerp arg)
2278 ;; Show-subtree, ARG levels up from here.
2279 (save-excursion
2280 (org-back-to-heading)
2281 (outline-up-heading (if (< arg 0) (- arg)
2282 (- (outline-level) arg)))
2283 (org-show-subtree)))
2284
2285 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2286 ;; At a heading: rotate between three different views
2287 (org-back-to-heading)
2288 (let ((goal-column 0) eoh eol eos)
2289 ;; First, some boundaries
2290 (save-excursion
2291 (org-back-to-heading)
2292 (save-excursion
2293 (beginning-of-line 2)
2294 (while (and (not (eobp)) ;; this is like `next-line'
2295 (get-char-property (1- (point)) 'invisible))
2296 (beginning-of-line 2)) (setq eol (point)))
2297 (outline-end-of-heading) (setq eoh (point))
2298 (org-end-of-subtree t) (setq eos (point))
2299 (outline-next-heading))
2300 ;; Find out what to do next and set `this-command'
2301 (cond
2302 ((= eos eoh)
2303 ;; Nothing is hidden behind this heading
2304 (message "EMPTY ENTRY")
2305 (setq org-cycle-subtree-status nil))
2306 ((>= eol eos)
2307 ;; Entire subtree is hidden in one line: open it
2308 (org-show-entry)
2309 (show-children)
2310 (message "CHILDREN")
2311 (setq org-cycle-subtree-status 'children)
2312 (run-hook-with-args 'org-cycle-hook 'children))
2313 ((and (eq last-command this-command)
2314 (eq org-cycle-subtree-status 'children))
2315 ;; We just showed the children, now show everything.
2316 (org-show-subtree)
2317 (message "SUBTREE")
2318 (setq org-cycle-subtree-status 'subtree)
2319 (run-hook-with-args 'org-cycle-hook 'subtree))
2320 (t
2321 ;; Default action: hide the subtree.
2322 (hide-subtree)
2323 (message "FOLDED")
2324 (setq org-cycle-subtree-status 'folded)
2325 (run-hook-with-args 'org-cycle-hook 'folded)))))
2326
2327 ;; TAB emulation
2328 (buffer-read-only (org-back-to-heading))
2329 ((if (and (eq org-cycle-emulate-tab 'white)
2330 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2331 t
2332 (eq org-cycle-emulate-tab t))
2333 (if (and (looking-at "[ \n\r\t]")
2334 (string-match "^[ \t]*$" (buffer-substring
2335 (point-at-bol) (point))))
2336 (progn
2337 (beginning-of-line 1)
2338 (and (looking-at "[ \t]+") (replace-match ""))))
2339 (indent-relative))
2340
2341 (t (save-excursion
2342 (org-back-to-heading)
2343 (org-cycle))))))
2344
2345 (defun org-optimize-window-after-visibility-change (state)
2346 "Adjust the window after a change in outline visibility.
2347 This function is the default value of the hook `org-cycle-hook'."
2348 (cond
2349 ((eq state 'overview) (org-first-headline-recenter 1))
2350 ((eq state 'content) nil)
2351 ((eq state 'all) nil)
2352 ((eq state 'folded) nil)
2353 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2354 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2355
2356 (defun org-subtree-end-visible-p ()
2357 "Is the end of the current subtree visible?"
2358 (pos-visible-in-window-p
2359 (save-excursion (org-end-of-subtree t) (point))))
2360
2361 (defun org-first-headline-recenter (&optional N)
2362 "Move cursor to the first headline and recenter the headline.
2363 Optional argument N means, put the headline into the Nth line of the window."
2364 (goto-char (point-min))
2365 (when (re-search-forward (concat "^" outline-regexp) nil t)
2366 (beginning-of-line)
2367 (recenter (prefix-numeric-value N))))
2368
2369 (defvar org-goto-window-configuration nil)
2370 (defvar org-goto-marker nil)
2371 (defvar org-goto-map (make-sparse-keymap))
2372 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2373 (while (setq cmd (pop cmds))
2374 (substitute-key-definition cmd cmd org-goto-map global-map)))
2375 (define-key org-goto-map "\C-m" 'org-goto-ret)
2376 (define-key org-goto-map [(left)] 'org-goto-left)
2377 (define-key org-goto-map [(right)] 'org-goto-right)
2378 (define-key org-goto-map [(?q)] 'org-goto-quit)
2379 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2380 (define-key org-goto-map "\C-i" 'org-cycle)
2381 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2382 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2383 (define-key org-goto-map "n" 'outline-next-visible-heading)
2384 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2385 (define-key org-goto-map "f" 'outline-forward-same-level)
2386 (define-key org-goto-map "b" 'outline-backward-same-level)
2387 (define-key org-goto-map "u" 'outline-up-heading)
2388 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2389 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2390 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2391 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2392 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2393 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2394 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2395
2396 (defconst org-goto-help
2397 "Select a location to jump to, press RET
2398 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2399
2400 (defun org-goto ()
2401 "Go to a different location of the document, keeping current visibility.
2402
2403 When you want to go to a different location in a document, the fastest way
2404 is often to fold the entire buffer and then dive into the tree. This
2405 method has the disadvantage, that the previous location will be folded,
2406 which may not be what you want.
2407
2408 This command works around this by showing a copy of the current buffer in
2409 overview mode. You can dive into the tree in that copy, to find the
2410 location you want to reach. When pressing RET, the command returns to the
2411 original buffer in which the visibility is still unchanged. It then jumps
2412 to the new location, making it and the headline hierarchy above it visible."
2413 (interactive)
2414 (let* ((org-goto-start-pos (point))
2415 (selected-point
2416 (org-get-location (current-buffer) org-goto-help)))
2417 (if selected-point
2418 (progn
2419 (goto-char selected-point)
2420 (if (org-invisible-p) (org-show-hierarchy-above)))
2421 (error "Quit"))))
2422
2423 (defun org-get-location (buf help)
2424 "Let the user select a location in the Org-mode buffer BUF.
2425 This function uses a recursive edit. It returns the selected position
2426 or nil."
2427 (let (org-selected-point)
2428 (save-excursion
2429 (save-window-excursion
2430 (delete-other-windows)
2431 (switch-to-buffer (get-buffer-create "*org-goto*"))
2432 (with-output-to-temp-buffer "*Help*"
2433 (princ help))
2434 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2435 (setq buffer-read-only nil)
2436 (erase-buffer)
2437 (insert-buffer-substring buf)
2438 (let ((org-startup-truncated t)
2439 (org-startup-folded t)
2440 (org-startup-with-deadline-check nil))
2441 (org-mode))
2442 (setq buffer-read-only t)
2443 (if (boundp 'org-goto-start-pos)
2444 (goto-char org-goto-start-pos)
2445 (goto-char (point-min)))
2446 (org-beginning-of-line)
2447 (message "Select location and press RET")
2448 ;; now we make sure that during selection, ony very few keys work
2449 ;; and that it is impossible to switch to another window.
2450 (let ((gm (current-global-map))
2451 (overriding-local-map org-goto-map))
2452 (unwind-protect
2453 (progn
2454 (use-global-map org-goto-map)
2455 (recursive-edit))
2456 (use-global-map gm)))))
2457 (kill-buffer "*org-goto*")
2458 org-selected-point))
2459
2460 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2461 (defun org-goto-ret (&optional arg)
2462 "Finish org-goto by going to the new location."
2463 (interactive "P")
2464 (setq org-selected-point (point)
2465 current-prefix-arg arg)
2466 (throw 'exit nil))
2467
2468 (defun org-goto-left ()
2469 "Finish org-goto by going to the new location."
2470 (interactive)
2471 (if (org-on-heading-p)
2472 (progn
2473 (beginning-of-line 1)
2474 (setq org-selected-point (point)
2475 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2476 (throw 'exit nil))
2477 (error "Not on a heading")))
2478
2479 (defun org-goto-right ()
2480 "Finish org-goto by going to the new location."
2481 (interactive)
2482 (if (org-on-heading-p)
2483 (progn
2484 (outline-end-of-subtree)
2485 (or (eobp) (forward-char 1))
2486 (setq org-selected-point (point)
2487 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2488 (throw 'exit nil))
2489 (error "Not on a heading")))
2490
2491 (defun org-goto-quit ()
2492 "Finish org-goto without cursor motion."
2493 (interactive)
2494 (setq org-selected-point nil)
2495 (throw 'exit nil))
2496
2497 ;;; Promotion, Demotion, Inserting new headlines
2498
2499 (defvar org-ignore-region nil
2500 "To temporarily disable the active region.")
2501
2502 (defun org-insert-heading (&optional force-heading)
2503 "Insert a new heading or item with same depth at point.
2504 If ARG is non-nil"
2505 (interactive "P")
2506 (when (or force-heading (not (org-insert-item)))
2507 (let* ((head (save-excursion
2508 (condition-case nil
2509 (org-back-to-heading)
2510 (error (outline-next-heading)))
2511 (prog1 (match-string 0)
2512 (funcall outline-level)))))
2513 (unless (bolp) (newline))
2514 (insert head)
2515 (unless (eolp)
2516 (save-excursion (newline-and-indent)))
2517 (unless (equal (char-before) ?\ )
2518 (insert " "))
2519 (run-hooks 'org-insert-heading-hook))))
2520
2521 (defun org-insert-item ()
2522 "Insert a new item at the current level.
2523 Return t when tings worked, nil when we are not in an item."
2524 (when (save-excursion
2525 (condition-case nil
2526 (progn
2527 (org-beginning-of-item)
2528 (org-at-item-p)
2529 t)
2530 (error nil)))
2531 (unless (bolp) (newline))
2532 (insert (match-string 0))
2533 (org-maybe-renumber-ordered-list)
2534 t))
2535
2536 (defun org-insert-todo-heading (arg)
2537 "Insert a new heading with the same level and TODO state as current heading.
2538 If the heading has no TODO state, or if the state is DONE, use the first
2539 state (TODO by default). Also with prefix arg, force first state."
2540 (interactive "P")
2541 (org-insert-heading)
2542 (save-excursion
2543 (org-back-to-heading)
2544 (outline-previous-heading)
2545 (looking-at org-todo-line-regexp))
2546 (if (or arg
2547 (not (match-beginning 2))
2548 (equal (match-string 2) org-done-string))
2549 (insert (car org-todo-keywords) " ")
2550 (insert (match-string 2) " ")))
2551
2552 (defun org-promote-subtree ()
2553 "Promote the entire subtree.
2554 See also `org-promote'."
2555 (interactive)
2556 (save-excursion
2557 (org-map-tree 'org-promote)))
2558
2559 (defun org-demote-subtree ()
2560 "Demote the entire subtree. See `org-demote'.
2561 See also `org-promote'."
2562 (interactive)
2563 (save-excursion
2564 (org-map-tree 'org-demote)))
2565
2566 (defun org-do-promote ()
2567 "Promote the current heading higher up the tree.
2568 If the region is active in `transient-mark-mode', promote all headings
2569 in the region."
2570 (interactive)
2571 (save-excursion
2572 (if (org-region-active-p)
2573 (org-map-region 'org-promote (region-beginning) (region-end))
2574 (org-promote)))
2575 (org-fix-position-after-promote))
2576
2577 (defun org-do-demote ()
2578 "Demote the current heading lower down the tree.
2579 If the region is active in `transient-mark-mode', demote all headings
2580 in the region."
2581 (interactive)
2582 (save-excursion
2583 (if (org-region-active-p)
2584 (org-map-region 'org-demote (region-beginning) (region-end))
2585 (org-demote)))
2586 (org-fix-position-after-promote))
2587
2588 (defun org-fix-position-after-promote ()
2589 "Make sure that after pro/demotion cursor position is right."
2590 (and (equal (char-after) ?\ )
2591 (equal (char-before) ?*)
2592 (forward-char 1)))
2593
2594 (defun org-promote ()
2595 "Promote the current heading higher up the tree.
2596 If the region is active in `transient-mark-mode', promote all headings
2597 in the region."
2598 (org-back-to-heading t)
2599 (let* ((level (save-match-data (funcall outline-level)))
2600 (up-head (make-string (1- level) ?*)))
2601 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2602 (replace-match up-head nil t)
2603 ;; Fixup tag positioning
2604 (and org-auto-align-tags (org-set-tags nil t))
2605 (if org-adapt-indentation
2606 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2607
2608 (defun org-demote ()
2609 "Demote the current heading lower down the tree.
2610 If the region is active in `transient-mark-mode', demote all headings
2611 in the region."
2612 (org-back-to-heading t)
2613 (let* ((level (save-match-data (funcall outline-level)))
2614 (down-head (make-string (1+ level) ?*)))
2615 (replace-match down-head nil t)
2616 ;; Fixup tag positioning
2617 (and org-auto-align-tags (org-set-tags nil t))
2618 (if org-adapt-indentation
2619 (org-fixup-indentation "^ " " " "^\\S-"))))
2620
2621 (defun org-map-tree (fun)
2622 "Call FUN for every heading underneath the current one."
2623 (org-back-to-heading)
2624 (let ((level (outline-level)))
2625 (save-excursion
2626 (funcall fun)
2627 (while (and (progn
2628 (outline-next-heading)
2629 (> (funcall outline-level) level))
2630 (not (eobp)))
2631 (funcall fun)))))
2632
2633 (defun org-map-region (fun beg end)
2634 "Call FUN for every heading between BEG and END."
2635 (let ((org-ignore-region t))
2636 (save-excursion
2637 (setq end (copy-marker end))
2638 (goto-char beg)
2639 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2640 (< (point) end))
2641 (funcall fun))
2642 (while (and (progn
2643 (outline-next-heading)
2644 (< (point) end))
2645 (not (eobp)))
2646 (funcall fun)))))
2647
2648 (defun org-fixup-indentation (from to prohibit)
2649 "Change the indentation in the current entry by re-replacing FROM with TO.
2650 However, if the regexp PROHIBIT matches at all, don't do anything.
2651 This is being used to change indentation along with the length of the
2652 heading marker. But if there are any lines which are not indented, nothing
2653 is changed at all."
2654 (save-excursion
2655 (let ((end (save-excursion (outline-next-heading)
2656 (point-marker))))
2657 (unless (save-excursion (re-search-forward prohibit end t))
2658 (while (re-search-forward from end t)
2659 (replace-match to)
2660 (beginning-of-line 2)))
2661 (move-marker end nil))))
2662
2663 ;;; Vertical tree motion, cutting and pasting of subtrees
2664
2665 (defun org-move-subtree-up (&optional arg)
2666 "Move the current subtree up past ARG headlines of the same level."
2667 (interactive "p")
2668 (org-move-subtree-down (- (prefix-numeric-value arg))))
2669
2670 (defun org-move-subtree-down (&optional arg)
2671 "Move the current subtree down past ARG headlines of the same level."
2672 (interactive "p")
2673 (setq arg (prefix-numeric-value arg))
2674 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2675 'outline-get-last-sibling))
2676 (ins-point (make-marker))
2677 (cnt (abs arg))
2678 beg end txt folded)
2679 ;; Select the tree
2680 (org-back-to-heading)
2681 (setq beg (point))
2682 (save-match-data
2683 (save-excursion (outline-end-of-heading)
2684 (setq folded (org-invisible-p)))
2685 (outline-end-of-subtree))
2686 (outline-next-heading)
2687 (setq end (point))
2688 ;; Find insertion point, with error handling
2689 (goto-char beg)
2690 (while (> cnt 0)
2691 (or (and (funcall movfunc) (looking-at outline-regexp))
2692 (progn (goto-char beg)
2693 (error "Cannot move past superior level or buffer limit")))
2694 (setq cnt (1- cnt)))
2695 (if (> arg 0)
2696 ;; Moving forward - still need to move over subtree
2697 (progn (outline-end-of-subtree)
2698 (outline-next-heading)
2699 (if (not (or (looking-at (concat "^" outline-regexp))
2700 (bolp)))
2701 (newline))))
2702 (move-marker ins-point (point))
2703 (setq txt (buffer-substring beg end))
2704 (delete-region beg end)
2705 (insert txt)
2706 (goto-char ins-point)
2707 (if folded (hide-subtree))
2708 (move-marker ins-point nil)))
2709
2710 (defvar org-subtree-clip ""
2711 "Clipboard for cut and paste of subtrees.
2712 This is actually only a copy of the kill, because we use the normal kill
2713 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2714
2715 (defvar org-subtree-clip-folded nil
2716 "Was the last copied subtree folded?
2717 This is used to fold the tree back after pasting.")
2718
2719 (defun org-cut-subtree ()
2720 "Cut the current subtree into the clipboard.
2721 This is a short-hand for marking the subtree and then cutting it."
2722 (interactive)
2723 (org-copy-subtree 'cut))
2724
2725 (defun org-copy-subtree (&optional cut)
2726 "Cut the current subtree into the clipboard.
2727 This is a short-hand for marking the subtree and then copying it.
2728 If CUT is non nil, actually cut the subtree."
2729 (interactive)
2730 (let (beg end folded)
2731 (org-back-to-heading)
2732 (setq beg (point))
2733 (save-match-data
2734 (save-excursion (outline-end-of-heading)
2735 (setq folded (org-invisible-p)))
2736 (outline-end-of-subtree))
2737 (if (equal (char-after) ?\n) (forward-char 1))
2738 (setq end (point))
2739 (goto-char beg)
2740 (when (> end beg)
2741 (setq org-subtree-clip-folded folded)
2742 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2743 (setq org-subtree-clip (current-kill 0))
2744 (message "%s: Subtree with %d characters"
2745 (if cut "Cut" "Copied")
2746 (length org-subtree-clip)))))
2747
2748 (defun org-paste-subtree (&optional level tree)
2749 "Paste the clipboard as a subtree, with modification of headline level.
2750 The entire subtree is promoted or demoted in order to match a new headline
2751 level. By default, the new level is derived from the visible headings
2752 before and after the insertion point, and taken to be the inferior headline
2753 level of the two. So if the previous visible heading is level 3 and the
2754 next is level 4 (or vice versa), level 4 will be used for insertion.
2755 This makes sure that the subtree remains an independent subtree and does
2756 not swallow low level entries.
2757
2758 You can also force a different level, either by using a numeric prefix
2759 argument, or by inserting the heading marker by hand. For example, if the
2760 cursor is after \"*****\", then the tree will be shifted to level 5.
2761
2762 If you want to insert the tree as is, just use \\[yank].
2763
2764 If optional TREE is given, use this text instead of the kill ring."
2765 (interactive "P")
2766 (unless (org-kill-is-subtree-p tree)
2767 (error
2768 (substitute-command-keys
2769 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2770 (let* ((txt (or tree (current-kill 0)))
2771 (^re (concat "^\\(" outline-regexp "\\)"))
2772 (re (concat "\\(" outline-regexp "\\)"))
2773 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2774
2775 (old-level (if (string-match ^re txt)
2776 (- (match-end 0) (match-beginning 0))
2777 -1))
2778 (force-level (cond (level (prefix-numeric-value level))
2779 ((string-match
2780 ^re_ (buffer-substring (point-at-bol) (point)))
2781 (- (match-end 0) (match-beginning 0)))
2782 (t nil)))
2783 (previous-level (save-excursion
2784 (condition-case nil
2785 (progn
2786 (outline-previous-visible-heading 1)
2787 (if (looking-at re)
2788 (- (match-end 0) (match-beginning 0))
2789 1))
2790 (error 1))))
2791 (next-level (save-excursion
2792 (condition-case nil
2793 (progn
2794 (outline-next-visible-heading 1)
2795 (if (looking-at re)
2796 (- (match-end 0) (match-beginning 0))
2797 1))
2798 (error 1))))
2799 (new-level (or force-level (max previous-level next-level)))
2800 (shift (if (or (= old-level -1)
2801 (= new-level -1)
2802 (= old-level new-level))
2803 0
2804 (- new-level old-level)))
2805 (shift1 shift)
2806 (delta (if (> shift 0) -1 1))
2807 (func (if (> shift 0) 'org-demote 'org-promote))
2808 beg end)
2809 ;; Remove the forces level indicator
2810 (if force-level
2811 (delete-region (point-at-bol) (point)))
2812 ;; Make sure we start at the beginning of an empty line
2813 (if (not (bolp)) (insert "\n"))
2814 (if (not (looking-at "[ \t]*$"))
2815 (progn (insert "\n") (backward-char 1)))
2816 ;; Paste
2817 (setq beg (point))
2818 (insert txt)
2819 (setq end (point))
2820 (goto-char beg)
2821 ;; Shift if necessary
2822 (if (= shift 0)
2823 (message "Pasted at level %d, without shift" new-level)
2824 (save-restriction
2825 (narrow-to-region beg end)
2826 (while (not (= shift 0))
2827 (org-map-region func (point-min) (point-max))
2828 (setq shift (+ delta shift)))
2829 (goto-char (point-min))
2830 (message "Pasted at level %d, with shift by %d levels"
2831 new-level shift1)))
2832 (if (and (eq org-subtree-clip (current-kill 0))
2833 org-subtree-clip-folded)
2834 ;; The tree was folded before it was killed/copied
2835 (hide-subtree))))
2836
2837 (defun org-kill-is-subtree-p (&optional txt)
2838 "Check if the current kill is an outline subtree, or a set of trees.
2839 Returns nil if kill does not start with a headline, or if the first
2840 headline level is not the largest headline level in the tree.
2841 So this will actually accept several entries of equal levels as well,
2842 which is OK for `org-paste-subtree'.
2843 If optional TXT is given, check this string instead of the current kill."
2844 (let* ((kill (or txt (current-kill 0) ""))
2845 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2846 (- (match-end 0) (match-beginning 0))))
2847 (re (concat "^" outline-regexp))
2848 (start 1))
2849 (if (not start-level)
2850 nil ;; does not even start with a heading
2851 (catch 'exit
2852 (while (setq start (string-match re kill (1+ start)))
2853 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2854 (throw 'exit nil)))
2855 t))))
2856
2857 ;;; Plain list items
2858
2859 (defun org-at-item-p ()
2860 "Is point in a line starting a hand-formatted item?"
2861 (let ((llt org-plain-list-ordered-item-terminator))
2862 (save-excursion
2863 (goto-char (point-at-bol))
2864 (looking-at
2865 (cond
2866 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2867 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2868 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2869 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
2870
2871 (defun org-get-indentation ()
2872 "Get the indentation of the current line, ionterpreting tabs."
2873 (save-excursion
2874 (beginning-of-line 1)
2875 (skip-chars-forward " \t")
2876 (current-column)))
2877
2878 (defun org-beginning-of-item ()
2879 "Go to the beginning of the current hand-formatted item.
2880 If the cursor is not in an item, throw an error."
2881 (let ((pos (point))
2882 (limit (save-excursion (org-back-to-heading)
2883 (beginning-of-line 2) (point)))
2884 ind ind1)
2885 (if (org-at-item-p)
2886 (beginning-of-line 1)
2887 (beginning-of-line 1)
2888 (skip-chars-forward " \t")
2889 (setq ind (current-column))
2890 (if (catch 'exit
2891 (while t
2892 (beginning-of-line 0)
2893 (if (< (point) limit) (throw 'exit nil))
2894 (unless (looking-at " \t]*$")
2895 (skip-chars-forward " \t")
2896 (setq ind1 (current-column))
2897 (if (< ind1 ind)
2898 (throw 'exit (org-at-item-p))))))
2899 nil
2900 (goto-char pos)
2901 (error "Not in an item")))))
2902
2903 (defun org-end-of-item ()
2904 "Go to the beginning of the current hand-formatted item.
2905 If the cursor is not in an item, throw an error."
2906 (let ((pos (point))
2907 (limit (save-excursion (outline-next-heading) (point)))
2908 (ind (save-excursion
2909 (org-beginning-of-item)
2910 (skip-chars-forward " \t")
2911 (current-column)))
2912 ind1)
2913 (if (catch 'exit
2914 (while t
2915 (beginning-of-line 2)
2916 (if (>= (point) limit) (throw 'exit t))
2917 (unless (looking-at "[ \t]*$")
2918 (skip-chars-forward " \t")
2919 (setq ind1 (current-column))
2920 (if (<= ind1 ind) (throw 'exit t)))))
2921 (beginning-of-line 1)
2922 (goto-char pos)
2923 (error "Not in an item"))))
2924
2925 (defun org-move-item-down (arg)
2926 "Move the plain list item at point down, i.e. swap with following item.
2927 Subitems (items with larger indentation are considered part of the item,
2928 so this really moves item trees."
2929 (interactive "p")
2930 (let (beg end ind ind1 (pos (point)) txt)
2931 (org-beginning-of-item)
2932 (setq beg (point))
2933 (setq ind (org-get-indentation))
2934 (org-end-of-item)
2935 (setq end (point))
2936 (setq ind1 (org-get-indentation))
2937 (if (and (org-at-item-p) (= ind ind1))
2938 (progn
2939 (org-end-of-item)
2940 (setq txt (buffer-substring beg end))
2941 (save-excursion
2942 (delete-region beg end))
2943 (setq pos (point))
2944 (insert txt)
2945 (goto-char pos)
2946 (org-maybe-renumber-ordered-list))
2947 (goto-char pos)
2948 (error "Cannot move this item further down"))))
2949
2950 (defun org-move-item-up (arg)
2951 "Move the plain list item at point up, i.e. swap with previous item.
2952 Subitems (items with larger indentation are considered part of the item,
2953 so this really moves item trees."
2954 (interactive "p")
2955 (let (beg end ind ind1 (pos (point)) txt)
2956 (org-beginning-of-item)
2957 (setq beg (point))
2958 (setq ind (org-get-indentation))
2959 (org-end-of-item)
2960 (setq end (point))
2961 (goto-char beg)
2962 (catch 'exit
2963 (while t
2964 (beginning-of-line 0)
2965 (if (looking-at "[ \t]*$")
2966 nil
2967 (if (<= (setq ind1 (org-get-indentation)) ind)
2968 (throw 'exit t)))))
2969 (condition-case nil
2970 (org-beginning-of-item)
2971 (error (goto-char beg)
2972 (error "Cannot move this item further up")))
2973 (setq ind1 (org-get-indentation))
2974 (if (and (org-at-item-p) (= ind ind1))
2975 (progn
2976 (setq txt (buffer-substring beg end))
2977 (save-excursion
2978 (delete-region beg end))
2979 (setq pos (point))
2980 (insert txt)
2981 (goto-char pos)
2982 (org-maybe-renumber-ordered-list))
2983 (goto-char pos)
2984 (error "Cannot move this item further up"))))
2985
2986 (defun org-maybe-renumber-ordered-list ()
2987 "Renumber the ordered list at point if setup allows it.
2988 This tests the user option `org-auto-renumber-ordered-lists' before
2989 doing the renumbering."
2990 (and org-auto-renumber-ordered-lists
2991 (org-at-item-p)
2992 (match-beginning 3)
2993 (org-renumber-ordered-list 1)))
2994
2995 (defun org-get-string-indentation (s)
2996 "What indentation has S due to SPACE and TAB at the beginning of the string?"
2997 (let ((n -1) (i 0) (w tab-width) c)
2998 (catch 'exit
2999 (while (< (setq n (1+ n)) (length s))
3000 (setq c (aref s n))
3001 (cond ((= c ?\ ) (setq i (1+ i)))
3002 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3003 (t (throw 'exit t)))))
3004 i))
3005
3006 (defun org-renumber-ordered-list (arg)
3007 "Renumber an ordered plain list.
3008 Cursor neext to be in the first line of an item, the line that starts
3009 with something like \"1.\" or \"2)\"."
3010 (interactive "p")
3011 (unless (and (org-at-item-p)
3012 (match-beginning 3))
3013 (error "This is not an ordered list"))
3014 (let ((line (org-current-line))
3015 (col (current-column))
3016 (ind (org-get-string-indentation
3017 (buffer-substring (point-at-bol) (match-beginning 3))))
3018 ;; (term (substring (match-string 3) -1))
3019 ind1 (n (1- arg)))
3020 ;; find where this list begins
3021 (catch 'exit
3022 (while t
3023 (catch 'next
3024 (beginning-of-line 0)
3025 (if (looking-at "[ \t]*$") (throw 'next t))
3026 (skip-chars-forward " \t") (setq ind1 (current-column))
3027 (if (or (< ind1 ind)
3028 (and (= ind1 ind)
3029 (not (org-at-item-p))))
3030 (throw 'exit t)))))
3031 ;; Walk forward and replace these numbers
3032 (catch 'exit
3033 (while t
3034 (catch 'next
3035 (beginning-of-line 2)
3036 (if (eobp) (throw 'exit nil))
3037 (if (looking-at "[ \t]*$") (throw 'next nil))
3038 (skip-chars-forward " \t") (setq ind1 (current-column))
3039 (if (> ind1 ind) (throw 'next t))
3040 (if (< ind1 ind) (throw 'exit t))
3041 (if (not (org-at-item-p)) (throw 'exit nil))
3042 (if (not (match-beginning 3))
3043 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3044 (delete-region (match-beginning 3) (1- (match-end 3)))
3045 (goto-char (match-beginning 3))
3046 (insert (format "%d" (setq n (1+ n)))))))
3047 (goto-line line)
3048 (move-to-column col)))
3049
3050 (defvar org-last-indent-begin-marker (make-marker))
3051 (defvar org-last-indent-end-marker (make-marker))
3052
3053
3054 (defun org-outdent-item (arg)
3055 "Outdent a local list item."
3056 (interactive "p")
3057 (org-indent-item (- arg)))
3058
3059 (defun org-indent-item (arg)
3060 "Indent a local list item."
3061 (interactive "p")
3062 (unless (org-at-item-p)
3063 (error "Not on an item"))
3064 (let (beg end ind ind1)
3065 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3066 (setq beg org-last-indent-begin-marker
3067 end org-last-indent-end-marker)
3068 (org-beginning-of-item)
3069 (setq beg (move-marker org-last-indent-begin-marker (point)))
3070 (org-end-of-item)
3071 (setq end (move-marker org-last-indent-end-marker (point))))
3072 (goto-char beg)
3073 (skip-chars-forward " \t") (setq ind (current-column))
3074 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3075 (while (< (point) end)
3076 (beginning-of-line 1)
3077 (skip-chars-forward " \t") (setq ind1 (current-column))
3078 (delete-region (point-at-bol) (point))
3079 (indent-to-column (+ ind1 arg))
3080 (beginning-of-line 2))
3081 (goto-char beg)))
3082
3083 ;;; Archiving
3084
3085 (defun org-archive-subtree ()
3086 "Move the current subtree to the archive.
3087 The archive can be a certain top-level heading in the current file, or in
3088 a different file. The tree will be moved to that location, the subtree
3089 heading be marked DONE, and the current time will be added."
3090 (interactive)
3091 ;; Save all relevant TODO keyword-relatex variables
3092 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3093 (tr-org-todo-keywords org-todo-keywords)
3094 (tr-org-todo-interpretation org-todo-interpretation)
3095 (tr-org-done-string org-done-string)
3096 (tr-org-todo-regexp org-todo-regexp)
3097 (tr-org-todo-line-regexp org-todo-line-regexp)
3098 (this-buffer (current-buffer))
3099 file heading buffer level newfile-p)
3100 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3101 (progn
3102 (setq file (format (match-string 1 org-archive-location)
3103 (file-name-nondirectory buffer-file-name))
3104 heading (match-string 2 org-archive-location)))
3105 (error "Invalid `org-archive-location'"))
3106 (if (> (length file) 0)
3107 (setq newfile-p (not (file-exists-p file))
3108 buffer (find-file-noselect file))
3109 (setq buffer (current-buffer)))
3110 (unless buffer
3111 (error "Cannot access file \"%s\"" file))
3112 (if (and (> (length heading) 0)
3113 (string-match "^\\*+" heading))
3114 (setq level (match-end 0))
3115 (setq heading nil level 0))
3116 (save-excursion
3117 ;; We first only copy, in case something goes wrong
3118 ;; we need to protect this-command, to avoid kill-region sets it,
3119 ;; which would lead to duplication of subtrees
3120 (let (this-command) (org-copy-subtree))
3121 (set-buffer buffer)
3122 ;; Enforce org-mode for the archive buffer
3123 (if (not (eq major-mode 'org-mode))
3124 ;; Force the mode for future visits.
3125 (let ((org-insert-mode-line-in-empty-file t))
3126 (call-interactively 'org-mode)))
3127 (when newfile-p
3128 (goto-char (point-max))
3129 (insert (format "\nArchived entries from file %s\n\n"
3130 (buffer-file-name this-buffer))))
3131 ;; Force the TODO keywords of the original buffer
3132 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3133 (org-todo-keywords tr-org-todo-keywords)
3134 (org-todo-interpretation tr-org-todo-interpretation)
3135 (org-done-string tr-org-done-string)
3136 (org-todo-regexp tr-org-todo-regexp)
3137 (org-todo-line-regexp tr-org-todo-line-regexp))
3138 (goto-char (point-min))
3139 (if heading
3140 (progn
3141 (if (re-search-forward
3142 (concat "\\(^\\|\r\\)"
3143 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3144 nil t)
3145 (goto-char (match-end 0))
3146 ;; Heading not found, just insert it at the end
3147 (goto-char (point-max))
3148 (or (bolp) (insert "\n"))
3149 (insert "\n" heading "\n")
3150 (end-of-line 0))
3151 ;; Make the heading visible, and the following as well
3152 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3153 (if (re-search-forward
3154 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3155 nil t)
3156 (progn (goto-char (match-beginning 0)) (insert "\n")
3157 (beginning-of-line 0))
3158 (goto-char (point-max)) (insert "\n")))
3159 (goto-char (point-max)) (insert "\n"))
3160 ;; Paste
3161 (org-paste-subtree (1+ level))
3162 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3163 (if org-archive-mark-done
3164 (org-todo (length org-todo-keywords)))
3165 ;; Move cursor to right after the TODO keyword
3166 (when org-archive-stamp-time
3167 (beginning-of-line 1)
3168 (looking-at org-todo-line-regexp)
3169 (goto-char (or (match-end 2) (match-beginning 3)))
3170 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3171 (current-time))
3172 ")"))
3173 ;; Save the buffer, if it is not the same buffer.
3174 (if (not (eq this-buffer buffer)) (save-buffer))))
3175 ;; Here we are back in the original buffer. Everything seems to have
3176 ;; worked. So now cut the tree and finish up.
3177 (let (this-command) (org-cut-subtree))
3178 (if (looking-at "[ \t]*$") (kill-line))
3179 (message "Subtree archived %s"
3180 (if (eq this-buffer buffer)
3181 (concat "under heading: " heading)
3182 (concat "in file: " (abbreviate-file-name file))))))
3183
3184 ;;; Completion
3185
3186 (defun org-complete (&optional arg)
3187 "Perform completion on word at point.
3188 At the beginning of a headline, this completes TODO keywords as given in
3189 `org-todo-keywords'.
3190 If the current word is preceded by a backslash, completes the TeX symbols
3191 that are supported for HTML support.
3192 If the current word is preceded by \"#+\", completes special words for
3193 setting file options.
3194 At all other locations, this simply calls `ispell-complete-word'."
3195 (interactive "P")
3196 (catch 'exit
3197 (let* ((end (point))
3198 (beg1 (save-excursion
3199 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3200 (skip-chars-backward "a-zA-Z_")
3201 (point)))
3202 (beg (save-excursion
3203 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3204 (skip-chars-backward "a-zA-Z0-9_:$")
3205 (point)))
3206 (camel (equal (char-before beg) ?*))
3207 (tag (equal (char-before beg1) ?:))
3208 (texp (equal (char-before beg) ?\\))
3209 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3210 beg)
3211 "#+"))
3212 (completion-ignore-case opt)
3213 (type nil)
3214 (tbl nil)
3215 (table (cond
3216 (opt
3217 (setq type :opt)
3218 (mapcar (lambda (x)
3219 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3220 (cons (match-string 2 x) (match-string 1 x)))
3221 (org-split-string (org-get-current-options) "\n")))
3222 (texp
3223 (setq type :tex)
3224 org-html-entities)
3225 ((string-match "\\`\\*+[ \t]*\\'"
3226 (buffer-substring (point-at-bol) beg))
3227 (setq type :todo)
3228 (mapcar 'list org-todo-keywords))
3229 (camel
3230 (setq type :camel)
3231 (save-excursion
3232 (goto-char (point-min))
3233 (while (re-search-forward org-todo-line-regexp nil t)
3234 (push (list (org-make-org-heading-camel (match-string 3)))
3235 tbl)))
3236 tbl)
3237 (tag (setq type :tag beg beg1)
3238 (org-get-buffer-tags))
3239 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3240 (pattern (buffer-substring-no-properties beg end))
3241 (completion (try-completion pattern table)))
3242 (cond ((eq completion t)
3243 (if (equal type :opt)
3244 (insert (substring (cdr (assoc (upcase pattern) table))
3245 (length pattern)))))
3246 ((null completion)
3247 (message "Can't find completion for \"%s\"" pattern)
3248 (ding))
3249 ((not (string= pattern completion))
3250 (delete-region beg end)
3251 (if (string-match " +$" completion)
3252 (setq completion (replace-match "" t t completion)))
3253 (insert completion)
3254 (if (get-buffer-window "*Completions*")
3255 (delete-window (get-buffer-window "*Completions*")))
3256 (if (assoc completion table)
3257 (if (eq type :todo) (insert " ")
3258 (if (eq type :tag) (insert ":"))))
3259 (if (and (equal type :opt) (assoc completion table))
3260 (message "%s" (substitute-command-keys
3261 "Press \\[org-complete] again to insert example settings"))))
3262 (t
3263 (message "Making completion list...")
3264 (let ((list (sort (all-completions pattern table) 'string<)))
3265 (with-output-to-temp-buffer "*Completions*"
3266 (display-completion-list list)))
3267 (message "Making completion list...%s" "done"))))))
3268
3269 ;;; Comments, TODO and DEADLINE
3270
3271 (defun org-toggle-comment ()
3272 "Change the COMMENT state of an entry."
3273 (interactive)
3274 (save-excursion
3275 (org-back-to-heading)
3276 (if (looking-at (concat outline-regexp
3277 "\\( +\\<" org-comment-string "\\>\\)"))
3278 (replace-match "" t t nil 1)
3279 (if (looking-at outline-regexp)
3280 (progn
3281 (goto-char (match-end 0))
3282 (insert " " org-comment-string))))))
3283
3284 (defvar org-last-todo-state-is-todo nil
3285 "This is non-nil when the last TODO state change led to a TODO state.
3286 If the last change removed the TODO tag or switched to DONE, then
3287 this is nil.")
3288
3289 (defun org-todo (&optional arg)
3290 "Change the TODO state of an item.
3291 The state of an item is given by a keyword at the start of the heading,
3292 like
3293 *** TODO Write paper
3294 *** DONE Call mom
3295
3296 The different keywords are specified in the variable `org-todo-keywords'. By
3297 default the available states are \"TODO\" and \"DONE\".
3298 So for this example: when the item starts with TODO, it is changed to DONE.
3299 When it starts with DONE, the DONE is removed. And when neither TODO nor
3300 DONE are present, add TODO at the beginning of the heading.
3301
3302 With prefix arg, use completion to determined the new state. With numeric
3303 prefix arg, switch to that state."
3304 (interactive "P")
3305 (save-excursion
3306 (org-back-to-heading)
3307 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3308 (or (looking-at (concat " +" org-todo-regexp " *"))
3309 (looking-at " *"))
3310 (let* ((this (match-string 1))
3311 (completion-ignore-case t)
3312 (member (member this org-todo-keywords))
3313 (tail (cdr member))
3314 (state (cond
3315 ((equal arg '(4))
3316 ;; Read a state with completion
3317 (completing-read "State: " (mapcar (lambda(x) (list x))
3318 org-todo-keywords)
3319 nil t))
3320 ((eq arg 'right)
3321 (if this
3322 (if tail (car tail) nil)
3323 (car org-todo-keywords)))
3324 ((eq arg 'left)
3325 (if (equal member org-todo-keywords)
3326 nil
3327 (if this
3328 (nth (- (length org-todo-keywords) (length tail) 2)
3329 org-todo-keywords)
3330 org-done-string)))
3331 (arg
3332 ;; user requests a specific state
3333 (nth (1- (prefix-numeric-value arg))
3334 org-todo-keywords))
3335 ((null member) (car org-todo-keywords))
3336 ((null tail) nil) ;; -> first entry
3337 ((eq org-todo-interpretation 'sequence)
3338 (car tail))
3339 ((memq org-todo-interpretation '(type priority))
3340 (if (eq this-command last-command)
3341 (car tail)
3342 (if (> (length tail) 0) org-done-string nil)))
3343 (t nil)))
3344 (next (if state (concat " " state " ") " ")))
3345 (replace-match next t t)
3346 (setq org-last-todo-state-is-todo
3347 (not (equal state org-done-string)))
3348 (when org-log-done
3349 (if (equal state org-done-string)
3350 (org-log-done)
3351 (if (not this)
3352 (org-log-done t))))
3353 ;; Fixup tag positioning
3354 (and org-auto-align-tags (org-set-tags nil t))
3355 (run-hooks 'org-after-todo-state-change-hook)))
3356 ;; Fixup cursor location if close to the keyword
3357 (if (and (outline-on-heading-p)
3358 (not (bolp))
3359 (save-excursion (beginning-of-line 1)
3360 (looking-at org-todo-line-regexp))
3361 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3362 (progn
3363 (goto-char (or (match-end 2) (match-end 1)))
3364 (just-one-space))))
3365
3366 (defun org-log-done (&optional undone)
3367 "Add a time stamp logging that a TODO entry has been closed.
3368 When UNDONE is non-nil, remove such a time stamg again."
3369 (interactive)
3370 (let (beg end col)
3371 (save-excursion
3372 (org-back-to-heading t)
3373 (setq beg (point))
3374 (looking-at (concat outline-regexp " *"))
3375 (goto-char (match-end 0))
3376 (setq col (current-column))
3377 (outline-next-heading)
3378 (setq end (point))
3379 (goto-char beg)
3380 (when (re-search-forward (concat
3381 "[\r\n]\\([ \t]*"
3382 (regexp-quote org-closed-string)
3383 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3384 (delete-region (match-beginning 1) (match-end 1)))
3385 (unless undone
3386 (org-back-to-heading t)
3387 (skip-chars-forward "^\n\r")
3388 (goto-char (min (1+ (point)) (point-max)))
3389 (when (not (member (char-before) '(?\r ?\n)))
3390 (insert "\n"))
3391 (indent-to col)
3392 (insert org-closed-string " "
3393 (format-time-string
3394 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3395 (current-time))
3396 "\n")))))
3397
3398 (defun org-show-todo-tree (arg)
3399 "Make a compact tree which shows all headlines marked with TODO.
3400 The tree will show the lines where the regexp matches, and all higher
3401 headlines above the match.
3402 With \\[universal-argument] prefix, also show the DONE entries.
3403 With a numeric prefix N, construct a sparse tree for the Nth element
3404 of `org-todo-keywords'."
3405 (interactive "P")
3406 (let ((case-fold-search nil)
3407 (kwd-re
3408 (cond ((null arg) org-not-done-regexp)
3409 ((equal arg '(4)) org-todo-regexp)
3410 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3411 (regexp-quote (nth (1- (prefix-numeric-value arg))
3412 org-todo-keywords)))
3413 (t (error "Invalid prefix argument: %s" arg)))))
3414 (message "%d TODO entries found"
3415 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3416
3417 (defun org-deadline ()
3418 "Insert the DEADLINE: string to make a deadline.
3419 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3420 to modify it to the correct date."
3421 (interactive)
3422 (insert
3423 org-deadline-string " "
3424 (format-time-string (car org-time-stamp-formats)
3425 (org-read-date nil 'to-time)))
3426 (message "%s" (substitute-command-keys
3427 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3428
3429 (defun org-schedule ()
3430 "Insert the SCHEDULED: string to schedule a TODO item.
3431 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3432 to modify it to the correct date."
3433 (interactive)
3434 (insert
3435 org-scheduled-string " "
3436 (format-time-string (car org-time-stamp-formats)
3437 (org-read-date nil 'to-time)))
3438 (message "%s" (substitute-command-keys
3439 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3440
3441
3442 (defun org-occur (regexp &optional callback)
3443 "Make a compact tree which shows all matches of REGEXP.
3444 The tree will show the lines where the regexp matches, and all higher
3445 headlines above the match. It will also show the heading after the match,
3446 to make sure editing the matching entry is easy.
3447 if CALLBACK is non-nil, it is a function which is called to confirm
3448 that the match should indeed be shown."
3449 (interactive "sRegexp: ")
3450 (org-remove-occur-highlights nil nil t)
3451 (setq regexp (org-check-occur-regexp regexp))
3452 (let ((cnt 0))
3453 (save-excursion
3454 (goto-char (point-min))
3455 (hide-sublevels 1)
3456 (while (re-search-forward regexp nil t)
3457 (when (or (not callback)
3458 (save-match-data (funcall callback)))
3459 (setq cnt (1+ cnt))
3460 (org-highlight-new-match (match-beginning 0) (match-end 0))
3461 (org-show-hierarchy-above))))
3462 (make-local-hook 'before-change-functions) ; needed for XEmacs
3463 (add-hook 'before-change-functions 'org-remove-occur-highlights
3464 nil 'local)
3465 (run-hooks 'org-occur-hook)
3466 (if (interactive-p)
3467 (message "%d match(es) for regexp %s" cnt regexp))
3468 cnt))
3469
3470 (defun org-show-hierarchy-above ()
3471 "Make sure point and the headings hierarchy above is visible."
3472 (catch 'exit
3473 (if (org-on-heading-p t)
3474 (org-flag-heading nil) ; only show the heading
3475 (and (org-invisible-p) (org-show-hidden-entry))) ; show entire entry
3476 (save-excursion
3477 (and org-show-following-heading
3478 (outline-next-heading)
3479 (org-flag-heading nil))) ; show the next heading
3480 (when org-show-hierarchy-above
3481 (save-excursion ; show all higher headings
3482 (while (and (condition-case nil
3483 (progn (org-up-heading-all 1) t)
3484 (error nil))
3485 (not (bobp)))
3486 (org-flag-heading nil))))))
3487
3488 ;; Overlay compatibility functions
3489 (defun org-make-overlay (beg end &optional buffer)
3490 (if org-xemacs-p (make-extent beg end buffer) (make-overlay beg end buffer)))
3491 (defun org-delete-overlay (ovl)
3492 (if org-xemacs-p (delete-extent ovl) (delete-overlay ovl)))
3493 (defun org-detatch-overlay (ovl)
3494 (if org-xemacs-p (detach-extent ovl) (delete-overlay ovl)))
3495 (defun org-move-overlay (ovl beg end &optional buffer)
3496 (if org-xemacs-p
3497 (set-extent-endpoints ovl beg end buffer)
3498 (move-overlay ovl beg end buffer)))
3499 (defun org-overlay-put (ovl prop value)
3500 (if org-xemacs-p
3501 (set-extent-property ovl prop value)
3502 (overlay-put ovl prop value)))
3503
3504 (defvar org-occur-highlights nil)
3505 (defun org-highlight-new-match (beg end)
3506 "Highlight from BEG to END and mark the highlight is an occur headline."
3507 (let ((ov (org-make-overlay beg end)))
3508 (org-overlay-put ov 'face 'secondary-selection)
3509 (push ov org-occur-highlights)))
3510
3511 (defun org-remove-occur-highlights (&optional beg end noremove)
3512 "Remove the occur highlights from the buffer.
3513 BEG and END are ignored. If NOREMOVE is nil, remove this function
3514 from the before-change-functions in the current buffer."
3515 (interactive)
3516 (mapc 'org-delete-overlay org-occur-highlights)
3517 (setq org-occur-highlights nil)
3518 (unless noremove
3519 (remove-hook 'before-change-functions
3520 'org-remove-occur-highlights 'local)))
3521
3522 ;;; Priorities
3523
3524 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3525 "Regular expression matching the priority indicator.")
3526
3527 (defvar org-remove-priority-next-time nil)
3528
3529 (defun org-priority-up ()
3530 "Increase the priority of the current item."
3531 (interactive)
3532 (org-priority 'up))
3533
3534 (defun org-priority-down ()
3535 "Decrease the priority of the current item."
3536 (interactive)
3537 (org-priority 'down))
3538
3539 (defun org-priority (&optional action)
3540 "Change the priority of an item by ARG.
3541 ACTION can be set, up, or down."
3542 (interactive)
3543 (setq action (or action 'set))
3544 (let (current new news have remove)
3545 (save-excursion
3546 (org-back-to-heading)
3547 (if (looking-at org-priority-regexp)
3548 (setq current (string-to-char (match-string 2))
3549 have t)
3550 (setq current org-default-priority))
3551 (cond
3552 ((eq action 'set)
3553 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3554 (setq new (read-char-exclusive))
3555 (cond ((equal new ?\ ) (setq remove t))
3556 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3557 (error "Priority must be between `%c' and `%c'"
3558 ?A org-lowest-priority))))
3559 ((eq action 'up)
3560 (setq new (1- current)))
3561 ((eq action 'down)
3562 (setq new (1+ current)))
3563 (t (error "Invalid action")))
3564 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3565 (setq news (format "%c" new))
3566 (if have
3567 (if remove
3568 (replace-match "" t t nil 1)
3569 (replace-match news t t nil 2))
3570 (if remove
3571 (error "No priority cookie found in line")
3572 (looking-at org-todo-line-regexp)
3573 (if (match-end 2)
3574 (progn
3575 (goto-char (match-end 2))
3576 (insert " [#" news "]"))
3577 (goto-char (match-beginning 3))
3578 (insert "[#" news "] ")))))
3579 (if remove
3580 (message "Priority removed")
3581 (message "Priority of current item set to %s" news))))
3582
3583
3584 (defun org-get-priority (s)
3585 "Find priority cookie and return priority."
3586 (save-match-data
3587 (if (not (string-match org-priority-regexp s))
3588 (* 1000 (- org-lowest-priority org-default-priority))
3589 (* 1000 (- org-lowest-priority
3590 (string-to-char (match-string 2 s)))))))
3591
3592 ;;; Timestamps
3593
3594 (defvar org-last-changed-timestamp nil)
3595
3596 (defun org-time-stamp (arg)
3597 "Prompt for a date/time and insert a time stamp.
3598 If the user specifies a time like HH:MM, or if this command is called
3599 with a prefix argument, the time stamp will contain date and time.
3600 Otherwise, only the date will be included. All parts of a date not
3601 specified by the user will be filled in from the current date/time.
3602 So if you press just return without typing anything, the time stamp
3603 will represent the current date/time. If there is already a timestamp
3604 at the cursor, it will be modified."
3605 (interactive "P")
3606 (let ((fmt (if arg (cdr org-time-stamp-formats)
3607 (car org-time-stamp-formats)))
3608 (org-time-was-given nil)
3609 time)
3610 (cond
3611 ((and (org-at-timestamp-p)
3612 (eq last-command 'org-time-stamp)
3613 (eq this-command 'org-time-stamp))
3614 (insert "--")
3615 (setq time (let ((this-command this-command))
3616 (org-read-date arg 'totime)))
3617 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3618 (insert (format-time-string fmt time)))
3619 ((org-at-timestamp-p)
3620 (setq time (let ((this-command this-command))
3621 (org-read-date arg 'totime)))
3622 (and (org-at-timestamp-p) (replace-match
3623 (setq org-last-changed-timestamp
3624 (format-time-string fmt time))
3625 t t))
3626 (message "Timestamp updated"))
3627 (t
3628 (setq time (let ((this-command this-command))
3629 (org-read-date arg 'totime)))
3630 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3631 (insert (format-time-string fmt time))))))
3632
3633 (defun org-time-stamp-inactive (&optional arg)
3634 "Insert an inactive time stamp.
3635 An inactive time stamp is enclosed in square brackets instead of angle
3636 brackets. It is inactive in the sense that it does not trigger agenda entries,
3637 does not link to the calendar and cannot be changed with the S-cursor keys.
3638 So these are more for recording a certain time/date."
3639 ;; FIXME: Would it be better not to ask for a date/time here?
3640 (interactive "P")
3641 (let ((fmt (if arg (cdr org-time-stamp-formats)
3642 (car org-time-stamp-formats)))
3643 (org-time-was-given nil)
3644 time)
3645 (setq time (org-read-date arg 'totime))
3646 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3647 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3648 (insert (format-time-string fmt time))))
3649
3650 (defvar org-date-ovl (org-make-overlay 1 1))
3651 (org-overlay-put org-date-ovl 'face 'org-warning)
3652 (org-detatch-overlay org-date-ovl)
3653
3654 ;;; FIXME: Make the function take "Fri" as "next friday"
3655 ;;; because these are mostly being used to record the current time.
3656 (defun org-read-date (&optional with-time to-time)
3657 "Read a date and make things smooth for the user.
3658 The prompt will suggest to enter an ISO date, but you can also enter anything
3659 which will at least partially be understood by `parse-time-string'.
3660 Unrecognized parts of the date will default to the current day, month ,year,
3661 hour and minute. For example,
3662 3-2-5 --> 2003-02-05
3663 feb 15 --> currentyear-02-15
3664 sep 12 9 --> 2009-09-12
3665 12:45 --> today 12:45
3666 22 sept 0:34 --> currentyear-09-22 0:34
3667 12 --> currentyear-currentmonth-12
3668 etc.
3669 The function understands only English month and weekday abbreviations,
3670 but this can be configured with the variables `parse-time-months' and
3671 `parse-time-weekdays'.
3672
3673 While prompting, a calendar is popped up - you can also select the
3674 date with the mouse (button 1). The calendar shows a period of three
3675 month. To scroll it to other months, use the keys `>' and `<'.
3676 If you don't like the calendar, turn it off with
3677 \(setq org-popup-calendar-for-date-prompt nil).
3678
3679 With optional argument TO-TIME, the date will immediately be converted
3680 to an internal time.
3681 With an optional argument WITH-TIME, the prompt will suggest to also
3682 insert a time. Note that when WITH-TIME is not set, you can still
3683 enter a time, and this function will inform the calling routine about
3684 this change. The calling routine may then choose to change the format
3685 used to insert the time stamp into the buffer to include the time."
3686 (let* ((default-time
3687 ;; Default time is either today, or, when entering a range,
3688 ;; the range start.
3689 (if (save-excursion
3690 (re-search-backward
3691 (concat org-ts-regexp "--\\=")
3692 (- (point) 20) t))
3693 (apply
3694 'encode-time
3695 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3696 (parse-time-string (match-string 1))))
3697 (current-time)))
3698 (calendar-move-hook nil)
3699 (view-diary-entries-initially nil)
3700 (timestr (format-time-string
3701 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3702 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3703 ans ans1 ans2
3704 second minute hour day month year tl)
3705
3706 (if org-popup-calendar-for-date-prompt
3707 ;; Also show a calendar for date selection
3708 ;; Copied (with modifications) from planner.el by John Wiegley
3709 (save-excursion
3710 (save-window-excursion
3711 (calendar)
3712 (calendar-forward-day (- (time-to-days default-time)
3713 (calendar-absolute-from-gregorian
3714 (calendar-current-date))))
3715 (org-eval-in-calendar nil)
3716 (let* ((old-map (current-local-map))
3717 (map (copy-keymap calendar-mode-map))
3718 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3719 (define-key map (kbd "RET") 'org-calendar-select)
3720 (define-key map (if org-xemacs-p [button1] [mouse-1])
3721 'org-calendar-select-mouse)
3722 (define-key map (if org-xemacs-p [button2] [mouse-2])
3723 'org-calendar-select-mouse)
3724 (define-key minibuffer-local-map [(meta shift left)]
3725 (lambda () (interactive)
3726 (org-eval-in-calendar '(calendar-backward-month 1))))
3727 (define-key minibuffer-local-map [(meta shift right)]
3728 (lambda () (interactive)
3729 (org-eval-in-calendar '(calendar-forward-month 1))))
3730 (define-key minibuffer-local-map [(shift up)]
3731 (lambda () (interactive)
3732 (org-eval-in-calendar '(calendar-backward-week 1))))
3733 (define-key minibuffer-local-map [(shift down)]
3734 (lambda () (interactive)
3735 (org-eval-in-calendar '(calendar-forward-week 1))))
3736 (define-key minibuffer-local-map [(shift left)]
3737 (lambda () (interactive)
3738 (org-eval-in-calendar '(calendar-backward-day 1))))
3739 (define-key minibuffer-local-map [(shift right)]
3740 (lambda () (interactive)
3741 (org-eval-in-calendar '(calendar-forward-day 1))))
3742 (define-key minibuffer-local-map ">"
3743 (lambda () (interactive)
3744 (org-eval-in-calendar '(scroll-calendar-left 1))))
3745 (define-key minibuffer-local-map "<"
3746 (lambda () (interactive)
3747 (org-eval-in-calendar '(scroll-calendar-right 1))))
3748 (unwind-protect
3749 (progn
3750 (use-local-map map)
3751 (setq ans (read-string prompt "" nil nil))
3752 (setq ans (or ans1 ans2 ans)))
3753 (use-local-map old-map)))))
3754 ;; Naked prompt only
3755 (setq ans (read-string prompt "" nil timestr)))
3756 (org-detatch-overlay org-date-ovl)
3757
3758 (if (string-match
3759 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3760 (progn
3761 (setq year (if (match-end 2)
3762 (string-to-number (match-string 2 ans))
3763 (string-to-number (format-time-string "%Y")))
3764 month (string-to-number (match-string 3 ans))
3765 day (string-to-number (match-string 4 ans)))
3766 (if (< year 100) (setq year (+ 2000 year)))
3767 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3768 t t ans))))
3769 (setq tl (parse-time-string ans)
3770 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3771 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3772 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3773 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3774 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3775 second (or (nth 0 tl) 0))
3776 (if (and (boundp 'org-time-was-given)
3777 (nth 2 tl))
3778 (setq org-time-was-given t))
3779 (if (< year 100) (setq year (+ 2000 year)))
3780 (if to-time
3781 (encode-time second minute hour day month year)
3782 (if (or (nth 1 tl) (nth 2 tl))
3783 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3784 (format "%04d-%02d-%02d" year month day)))))
3785
3786 (defun org-eval-in-calendar (form)
3787 "Eval FORM in the calendar window and return to current window.
3788 Also, store the cursor date in variable ans2."
3789 (let ((sw (selected-window)))
3790 (select-window (get-buffer-window "*Calendar*"))
3791 (eval form)
3792 (when (calendar-cursor-to-date)
3793 (let* ((date (calendar-cursor-to-date))
3794 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3795 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3796 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
3797 (select-window sw)))
3798
3799 (defun org-calendar-select ()
3800 "Return to `org-read-date' with the date currently selected.
3801 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3802 (interactive)
3803 (when (calendar-cursor-to-date)
3804 (let* ((date (calendar-cursor-to-date))
3805 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3806 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3807 (if (active-minibuffer-window) (exit-minibuffer))))
3808
3809 (defun org-calendar-select-mouse (ev)
3810 "Return to `org-read-date' with the date currently selected.
3811 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3812 (interactive "e")
3813 (mouse-set-point ev)
3814 (when (calendar-cursor-to-date)
3815 (let* ((date (calendar-cursor-to-date))
3816 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3817 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3818 (if (active-minibuffer-window) (exit-minibuffer))))
3819
3820 (defun org-check-deadlines (ndays)
3821 "Check if there are any deadlines due or past due.
3822 A deadline is considered due if it happens within `org-deadline-warning-days'
3823 days from today's date. If the deadline appears in an entry marked DONE,
3824 it is not shown. The prefix arg NDAYS can be used to test that many
3825 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3826 (interactive "P")
3827 (let* ((org-warn-days
3828 (cond
3829 ((equal ndays '(4)) 100000)
3830 (ndays (prefix-numeric-value ndays))
3831 (t org-deadline-warning-days)))
3832 (case-fold-search nil)
3833 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3834 (callback
3835 (lambda ()
3836 (and (let ((d1 (time-to-days (current-time)))
3837 (d2 (time-to-days
3838 (org-time-string-to-time (match-string 1)))))
3839 (< (- d2 d1) org-warn-days))
3840 (not (org-entry-is-done-p))))))
3841 (message "%d deadlines past-due or due within %d days"
3842 (org-occur regexp callback)
3843 org-warn-days)))
3844
3845 (defun org-evaluate-time-range (&optional to-buffer)
3846 "Evaluate a time range by computing the difference between start and end.
3847 Normally the result is just printed in the echo area, but with prefix arg
3848 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3849 If the time range is actually in a table, the result is inserted into the
3850 next column.
3851 For time difference computation, a year is assumed to be exactly 365
3852 days in order to avoid rounding problems."
3853 (interactive "P")
3854 (save-excursion
3855 (unless (org-at-date-range-p)
3856 (goto-char (point-at-bol))
3857 (re-search-forward org-tr-regexp (point-at-eol) t))
3858 (if (not (org-at-date-range-p))
3859 (error "Not at a time-stamp range, and none found in current line")))
3860 (let* ((ts1 (match-string 1))
3861 (ts2 (match-string 2))
3862 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3863 (match-end (match-end 0))
3864 (time1 (org-time-string-to-time ts1))
3865 (time2 (org-time-string-to-time ts2))
3866 (t1 (time-to-seconds time1))
3867 (t2 (time-to-seconds time2))
3868 (diff (abs (- t2 t1)))
3869 (negative (< (- t2 t1) 0))
3870 ;; (ys (floor (* 365 24 60 60)))
3871 (ds (* 24 60 60))
3872 (hs (* 60 60))
3873 (fy "%dy %dd %02d:%02d")
3874 (fy1 "%dy %dd")
3875 (fd "%dd %02d:%02d")
3876 (fd1 "%dd")
3877 (fh "%02d:%02d")
3878 y d h m align)
3879 ;; FIXME: Should I re-introduce years, make year refer to same date?
3880 ;; This would be the only useful way to have years, actually.
3881 (if havetime
3882 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3883 y 0
3884 d (floor (/ diff ds)) diff (mod diff ds)
3885 h (floor (/ diff hs)) diff (mod diff hs)
3886 m (floor (/ diff 60)))
3887 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3888 y 0
3889 d (floor (+ (/ diff ds) 0.5))
3890 h 0 m 0))
3891 (if (not to-buffer)
3892 (message (org-make-tdiff-string y d h m))
3893 (when (org-at-table-p)
3894 (goto-char match-end)
3895 (setq align t)
3896 (and (looking-at " *|") (goto-char (match-end 0))))
3897 (if (looking-at
3898 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3899 (replace-match ""))
3900 (if negative (insert " -"))
3901 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3902 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3903 (insert " " (format fh h m))))
3904 (if align (org-table-align))
3905 (message "Time difference inserted"))))
3906
3907 (defun org-make-tdiff-string (y d h m)
3908 (let ((fmt "")
3909 (l nil))
3910 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3911 l (push y l)))
3912 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3913 l (push d l)))
3914 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3915 l (push h l)))
3916 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3917 l (push m l)))
3918 (apply 'format fmt (nreverse l))))
3919
3920 (defun org-time-string-to-time (s)
3921 (apply 'encode-time (org-parse-time-string s)))
3922
3923 (defun org-parse-time-string (s &optional nodefault)
3924 "Parse the standard Org-mode time string.
3925 This should be a lot faster than the normal `parse-time-string'.
3926 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3927 hour and minute fields will be nil if not given."
3928 (if (string-match org-ts-regexp1 s)
3929 (list 0
3930 (if (or (match-beginning 8) (not nodefault))
3931 (string-to-number (or (match-string 8 s) "0")))
3932 (if (or (match-beginning 7) (not nodefault))
3933 (string-to-number (or (match-string 7 s) "0")))
3934 (string-to-number (match-string 4 s))
3935 (string-to-number (match-string 3 s))
3936 (string-to-number (match-string 2 s))
3937 nil nil nil)
3938 (make-list 9 0)))
3939
3940 (defun org-timestamp-up (&optional arg)
3941 "Increase the date item at the cursor by one.
3942 If the cursor is on the year, change the year. If it is on the month or
3943 the day, change that.
3944 With prefix ARG, change by that many units."
3945 (interactive "p")
3946 (org-timestamp-change (prefix-numeric-value arg)))
3947
3948 (defun org-timestamp-down (&optional arg)
3949 "Decrease the date item at the cursor by one.
3950 If the cursor is on the year, change the year. If it is on the month or
3951 the day, change that.
3952 With prefix ARG, change by that many units."
3953 (interactive "p")
3954 (org-timestamp-change (- (prefix-numeric-value arg))))
3955
3956 (defun org-timestamp-up-day (&optional arg)
3957 "Increase the date in the time stamp by one day.
3958 With prefix ARG, change that many days."
3959 (interactive "p")
3960 (if (and (not (org-at-timestamp-p))
3961 (org-on-heading-p))
3962 (org-todo 'up)
3963 (org-timestamp-change (prefix-numeric-value arg) 'day)))
3964
3965 (defun org-timestamp-down-day (&optional arg)
3966 "Decrease the date in the time stamp by one day.
3967 With prefix ARG, change that many days."
3968 (interactive "p")
3969 (if (and (not (org-at-timestamp-p))
3970 (org-on-heading-p))
3971 (org-todo 'down)
3972 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
3973
3974 (defsubst org-pos-in-match-range (pos n)
3975 (and (match-beginning n)
3976 (<= (match-beginning n) pos)
3977 (>= (match-end n) pos)))
3978
3979 (defun org-at-timestamp-p ()
3980 "Determine if the cursor is in or at a timestamp."
3981 (interactive)
3982 (let* ((tsr org-ts-regexp2)
3983 (pos (point))
3984 (ans (or (looking-at tsr)
3985 (save-excursion
3986 (skip-chars-backward "^<\n\r\t")
3987 (if (> (point) 1) (backward-char 1))
3988 (and (looking-at tsr)
3989 (> (- (match-end 0) pos) -1))))))
3990 (and (boundp 'org-ts-what)
3991 (setq org-ts-what
3992 (cond
3993 ((org-pos-in-match-range pos 2) 'year)
3994 ((org-pos-in-match-range pos 3) 'month)
3995 ((org-pos-in-match-range pos 7) 'hour)
3996 ((org-pos-in-match-range pos 8) 'minute)
3997 ((or (org-pos-in-match-range pos 4)
3998 (org-pos-in-match-range pos 5)) 'day)
3999 (t 'day))))
4000 ans))
4001
4002 (defun org-timestamp-change (n &optional what)
4003 "Change the date in the time stamp at point.
4004 The date will be changed by N times WHAT. WHAT can be `day', `month',
4005 `year', `minute', `second'. If WHAT is not given, the cursor position
4006 in the timestamp determines what will be changed."
4007 (let ((fmt (car org-time-stamp-formats))
4008 org-ts-what
4009 (pos (point))
4010 ts time time0)
4011 (if (not (org-at-timestamp-p))
4012 (error "Not at a timestamp"))
4013 (setq org-ts-what (or what org-ts-what))
4014 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4015 (- (match-end 0) (match-beginning 0))))
4016 1)
4017 (cdr org-time-stamp-formats)
4018 (car org-time-stamp-formats)))
4019 (setq ts (match-string 0))
4020 (replace-match "")
4021 (setq time0 (org-parse-time-string ts))
4022 (setq time
4023 (apply 'encode-time
4024 (append
4025 (list (or (car time0) 0))
4026 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4027 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4028 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4029 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4030 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4031 (nthcdr 6 time0))))
4032 (if (eq what 'calendar)
4033 (let ((cal-date
4034 (save-match-data
4035 (with-current-buffer "*Calendar*"
4036 (calendar-cursor-to-date)))))
4037 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4038 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4039 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4040 (setcar time0 (or (car time0) 0))
4041 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4042 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4043 (setq time (apply 'encode-time time0))))
4044 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4045 (goto-char pos)
4046 ;; Try to recenter the calendar window, if any
4047 (if (and org-calendar-follow-timestamp-change
4048 (get-buffer-window "*Calendar*" t)
4049 (memq org-ts-what '(day month year)))
4050 (org-recenter-calendar (time-to-days time)))))
4051
4052 (defun org-recenter-calendar (date)
4053 "If the calendar is visible, recenter it to DATE."
4054 (let* ((win (selected-window))
4055 (cwin (get-buffer-window "*Calendar*" t))
4056 (calendar-move-hook nil))
4057 (when cwin
4058 (select-window cwin)
4059 (calendar-goto-date (if (listp date) date
4060 (calendar-gregorian-from-absolute date)))
4061 (select-window win))))
4062
4063 (defun org-goto-calendar (&optional arg)
4064 "Go to the Emacs calendar at the current date.
4065 If there is a time stamp in the current line, go to that date.
4066 A prefix ARG can be used force the current date."
4067 (interactive "P")
4068 (let ((tsr org-ts-regexp) diff
4069 (calendar-move-hook nil)
4070 (view-diary-entries-initially nil))
4071 (if (or (org-at-timestamp-p)
4072 (save-excursion
4073 (beginning-of-line 1)
4074 (looking-at (concat ".*" tsr))))
4075 (let ((d1 (time-to-days (current-time)))
4076 (d2 (time-to-days
4077 (org-time-string-to-time (match-string 1)))))
4078 (setq diff (- d2 d1))))
4079 (calendar)
4080 (calendar-goto-today)
4081 (if (and diff (not arg)) (calendar-forward-day diff))))
4082
4083 (defun org-date-from-calendar ()
4084 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4085 If there is already a time stamp at the cursor position, update it."
4086 (interactive)
4087 (org-timestamp-change 0 'calendar))
4088
4089 ;;; Agenda, and Diary Integration
4090
4091 ;;; Define the mode
4092
4093 (defvar org-agenda-mode-map (make-sparse-keymap)
4094 "Keymap for `org-agenda-mode'.")
4095
4096 (defvar org-agenda-menu)
4097 (defvar org-agenda-follow-mode nil)
4098 (defvar org-agenda-show-log nil)
4099 (defvar org-agenda-buffer-name "*Org Agenda*")
4100 (defvar org-agenda-redo-command nil)
4101 (defvar org-agenda-mode-hook nil)
4102 (defvar org-agenda-type nil)
4103 (defvar org-agenda-force-single-file nil)
4104
4105 ;;;###autoload
4106 (defun org-agenda-mode ()
4107 "Mode for time-sorted view on action items in Org-mode files.
4108
4109 The following commands are available:
4110
4111 \\{org-agenda-mode-map}"
4112 (interactive)
4113 (kill-all-local-variables)
4114 (setq major-mode 'org-agenda-mode)
4115 (setq mode-name "Org-Agenda")
4116 (use-local-map org-agenda-mode-map)
4117 (easy-menu-add org-agenda-menu)
4118 (if org-startup-truncated (setq truncate-lines t))
4119 (make-local-hook 'post-command-hook) ; Needed for XEmacs
4120 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4121 (make-local-hook 'pre-command-hook) ; Needed for XEmacs
4122 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4123 (unless org-agenda-keep-modes
4124 (setq org-agenda-follow-mode nil
4125 org-agenda-show-log nil))
4126 (easy-menu-change
4127 '("Agenda") "Agenda Files"
4128 (append
4129 (list
4130 (vector
4131 (if (get 'org-agenda-files 'org-restrict)
4132 "Restricted to single file"
4133 "Edit File List")
4134 '(customize-variable 'org-agenda-files)
4135 (not (get 'org-agenda-files 'org-restrict)))
4136 "--")
4137 (mapcar 'org-file-menu-entry (org-agenda-files))))
4138 (org-agenda-set-mode-name)
4139 (apply
4140 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4141 (list 'org-agenda-mode-hook)))
4142
4143 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4144 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4145 (define-key org-agenda-mode-map " " 'org-agenda-show)
4146 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4147 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4148 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4149 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4150 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4151 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4152 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4153 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4154 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4155 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4156 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4157 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4158
4159 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4160 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4161 (while l (define-key org-agenda-mode-map
4162 (int-to-string (pop l)) 'digit-argument)))
4163
4164 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4165 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4166 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4167 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4168 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4169 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4170 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4171 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4172 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4173 (define-key org-agenda-mode-map "n" 'next-line)
4174 (define-key org-agenda-mode-map "p" 'previous-line)
4175 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4176 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4177 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4178 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4179 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4180 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4181 (eval-after-load "calendar"
4182 '(define-key calendar-mode-map org-calendar-to-agenda-key
4183 'org-calendar-goto-agenda))
4184 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4185 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4186 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4187 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4188 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4189 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4190 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4191 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4192 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4193 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4194 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4195 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4196 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4197 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4198 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4199 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4200 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4201 "Local keymap for agenda entries from Org-mode.")
4202
4203 (define-key org-agenda-keymap
4204 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4205 (define-key org-agenda-keymap
4206 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4207
4208 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4209 '("Agenda"
4210 ("Agenda Files")
4211 "--"
4212 ["Show" org-agenda-show t]
4213 ["Go To (other window)" org-agenda-goto t]
4214 ["Go To (one window)" org-agenda-switch-to t]
4215 ["Follow Mode" org-agenda-follow-mode
4216 :style toggle :selected org-agenda-follow-mode :active t]
4217 "--"
4218 ["Cycle TODO" org-agenda-todo t]
4219 ("Tags"
4220 ["Show all Tags" org-agenda-show-tags t]
4221 ["Set Tags" org-agenda-set-tags t])
4222 ("Reschedule"
4223 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4224 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4225 "--"
4226 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4227 ("Priority"
4228 ["Set Priority" org-agenda-priority t]
4229 ["Increase Priority" org-agenda-priority-up t]
4230 ["Decrease Priority" org-agenda-priority-down t]
4231 ["Show Priority" org-agenda-show-priority t])
4232 "--"
4233 ;; ["New agenda command" org-agenda t]
4234 ["Rebuild buffer" org-agenda-redo t]
4235 "--"
4236 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4237 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4238 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4239 "--"
4240 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4241 :style radio :selected (equal org-agenda-ndays 1)]
4242 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4243 :style radio :selected (equal org-agenda-ndays 7)]
4244 "--"
4245 ["Show Logbook entries" org-agenda-log-mode
4246 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4247 ["Include Diary" org-agenda-toggle-diary
4248 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4249 ["Use Time Grid" org-agenda-toggle-time-grid
4250 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4251 "--"
4252 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4253 ("Calendar Commands"
4254 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4255 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4256 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4257 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4258 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4259 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4260 "--"
4261 ["Quit" org-agenda-quit t]
4262 ["Exit and Release Buffers" org-agenda-exit t]
4263 ))
4264
4265 ;;;###autoload
4266 (defun org-agenda (arg)
4267 "Dispatch agenda commands to collect entries to the agenda buffer.
4268 Prompts for a character to select a command. Any prefix arg will be passed
4269 on to the selected command. The default selections are:
4270
4271 a Call `org-agenda' to display the agenda for the current day or week.
4272 t Call `org-todo-list' to display the global todo list.
4273 T Call `org-todo-list' to display the global todo list, select only
4274 entries with a specific TODO keyword (the user get a prompt).
4275 m Call `org-tags-view' to display headlines with tags matching
4276 a condition (the user is prompted for the condition).
4277 M like `m', but select only TODO entries, no ordinary headlines.
4278
4279 More commands can be added by configuring the variable
4280 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4281 searches can be pre-defined in this way.
4282
4283 If the current buffer is in Org-mode and visiting a file, you can also
4284 first press `1' to indicate that the agenda should be temporarily (until the
4285 next use of \\[org-agenda]) restricted to the current file."
4286 (interactive "P")
4287 (catch 'exit
4288 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4289 (custom org-agenda-custom-commands)
4290 c entry key type string)
4291 (put 'org-agenda-files 'org-restrict nil)
4292 (save-window-excursion
4293 (delete-other-windows)
4294 (switch-to-buffer-other-window " *Agenda Commands*")
4295 (erase-buffer)
4296 (insert
4297 "Press key for an agenda command:
4298 --------------------------------
4299 a Agenda for current week or day
4300 t List of all TODO entries T Entries with special TODO kwd
4301 m Match a TAGS query M Like m, but only TODO entries.
4302 C Configure your own agenda commands")
4303 (while (setq entry (pop custom))
4304 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4305 (insert (format "\n%-4s%-14s: %s"
4306 key
4307 (cond
4308 ((eq type 'tags) "Tags query")
4309 ((eq type 'todo) "TODO keyword")
4310 ((eq type 'tags-tree) "Tags tree")
4311 ((eq type 'todo-tree) "TODO kwd tree")
4312 ((eq type 'occur-tree) "Occur tree")
4313 (t "???"))
4314 (org-string-props string 'face 'org-link))))
4315 (goto-char (point-min))
4316 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4317 (message "Press key for agenda command%s"
4318 (if restrict-ok ", or [1] to restrict to current file" ""))
4319 (setq c (read-char-exclusive))
4320 (message "")
4321 (when (equal c ?1)
4322 (if restrict-ok
4323 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
4324 (error "Cannot restrict agenda to current buffer"))
4325 (message "Press key for agenda command%s"
4326 (if restrict-ok " (restricted to current file)" ""))
4327 (setq c (read-char-exclusive))
4328 (message "")))
4329 (require 'calendar) ; FIXME: can we avoid this for some commands?
4330 ;; For example the todo list should not need it (but does...)
4331 (cond
4332 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4333 ((equal c ?a) (call-interactively 'org-agenda-list))
4334 ((equal c ?t) (call-interactively 'org-todo-list))
4335 ((equal c ?T)
4336 (setq current-prefix-arg (or arg '(4)))
4337 (call-interactively 'org-todo-list))
4338 ((equal c ?m) (call-interactively 'org-tags-view))
4339 ((equal c ?M)
4340 (setq current-prefix-arg (or arg '(4)))
4341 (call-interactively 'org-tags-view))
4342 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4343 (setq type (nth 1 entry) string (nth 2 entry))
4344 (cond
4345 ((eq type 'tags)
4346 (org-tags-view current-prefix-arg string))
4347 ((eq type 'todo)
4348 (org-todo-list string))
4349 ((eq type 'tags-tree)
4350 (org-check-for-org-mode)
4351 (org-tags-sparse-tree current-prefix-arg string))
4352 ((eq type 'todo-tree)
4353 (org-check-for-org-mode)
4354 (org-occur (concat "^" outline-regexp "[ \t]*"
4355 (regexp-quote string) "\\>")))
4356 ((eq type 'occur-tree)
4357 (org-check-for-org-mode)
4358 (org-occur string))
4359 (t (error "Invalid custom agenda command type %s" type))))
4360 (t (error "Invalid key"))))))
4361
4362 (defun org-check-for-org-mode ()
4363 "Make sure current buffer is in org-mode. Error if not."
4364 (or (eq major-mode 'org-mode)
4365 (error "Cannot execute org-mode agenda command on buffer in %s."
4366 major-mode)))
4367
4368 (defun org-fit-agenda-window ()
4369 "Fit the window to the buffer size."
4370 (and org-fit-agenda-window
4371 (fboundp 'fit-window-to-buffer)
4372 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4373 (/ (frame-height) 2))))
4374
4375 (defun org-agenda-files ()
4376 "Get the list of agenda files."
4377 (or (get 'org-agenda-files 'org-restrict)
4378 org-agenda-files))
4379
4380 (defvar org-agenda-markers nil
4381 "List of all currently active markers created by `org-agenda'.")
4382 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4383 "Creation time of the last agenda marker.")
4384
4385 (defun org-agenda-new-marker (&optional pos)
4386 "Return a new agenda marker.
4387 Org-mode keeps a list of these markers and resets them when they are
4388 no longer in use."
4389 (let ((m (copy-marker (or pos (point)))))
4390 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4391 (push m org-agenda-markers)
4392 m))
4393
4394 (defun org-agenda-maybe-reset-markers (&optional force)
4395 "Reset markers created by `org-agenda'. But only if they are old enough."
4396 (if (or force
4397 (> (- (time-to-seconds (current-time))
4398 org-agenda-last-marker-time)
4399 5))
4400 (while org-agenda-markers
4401 (move-marker (pop org-agenda-markers) nil))))
4402
4403 (defvar org-agenda-new-buffers nil
4404 "Buffers created to visit agenda files.")
4405
4406 (defun org-get-agenda-file-buffer (file)
4407 "Get a buffer visiting FILE. If the buffer needs to be created, add
4408 it to the list of buffers which might be released later."
4409 (let ((buf (find-buffer-visiting file)))
4410 (if buf
4411 buf ; just return it
4412 ;; Make a new buffer and remember it
4413 (setq buf (find-file-noselect file))
4414 (if buf (push buf org-agenda-new-buffers))
4415 buf)))
4416
4417 (defun org-release-buffers (blist)
4418 "Release all buffers in list, asking the user for confirmation when needed.
4419 When a buffer is unmodified, it is just killed. When modified, it is saved
4420 \(if the user agrees) and then killed."
4421 (let (buf file)
4422 (while (setq buf (pop blist))
4423 (setq file (buffer-file-name buf))
4424 (when (and (buffer-modified-p buf)
4425 file
4426 (y-or-n-p (format "Save file %s? " file)))
4427 (with-current-buffer buf (save-buffer)))
4428 (kill-buffer buf))))
4429
4430 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4431
4432 (defun org-timeline (&optional include-all keep-modes)
4433 "Show a time-sorted view of the entries in the current org file.
4434 Only entries with a time stamp of today or later will be listed. With
4435 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4436 under the current date.
4437 If the buffer contains an active region, only check the region for
4438 dates."
4439 (interactive "P")
4440 (require 'calendar)
4441 (org-agenda-maybe-reset-markers 'force)
4442 (org-compile-prefix-format org-timeline-prefix-format)
4443 (let* ((dopast t)
4444 (dotodo include-all)
4445 (doclosed org-agenda-show-log)
4446 (org-agenda-keep-modes keep-modes)
4447 (entry buffer-file-name)
4448 (org-agenda-files (list buffer-file-name))
4449 (date (calendar-current-date))
4450 (win (selected-window))
4451 (pos1 (point))
4452 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4453 (end (if (org-region-active-p) (region-end) (point-max)))
4454 (day-numbers (org-get-all-dates beg end 'no-ranges
4455 t doclosed)) ; always include today
4456 (today (time-to-days (current-time)))
4457 (org-respect-restriction t)
4458 (past t)
4459 args
4460 s e rtn d)
4461 (setq org-agenda-redo-command
4462 (list 'progn
4463 (list 'switch-to-buffer-other-window (current-buffer))
4464 (list 'org-timeline (list 'quote include-all) t)))
4465 (if (not dopast)
4466 ;; Remove past dates from the list of dates.
4467 (setq day-numbers (delq nil (mapcar (lambda(x)
4468 (if (>= x today) x nil))
4469 day-numbers))))
4470 (switch-to-buffer-other-window
4471 (get-buffer-create org-agenda-buffer-name))
4472 (setq buffer-read-only nil)
4473 (erase-buffer)
4474 (org-agenda-mode) (setq buffer-read-only nil)
4475 (set (make-local-variable 'org-agenda-type) 'timeline)
4476 (if doclosed (push :closed args))
4477 (push :timestamp args)
4478 (if dotodo (push :todo args))
4479 (while (setq d (pop day-numbers))
4480 (if (and (>= d today)
4481 dopast
4482 past)
4483 (progn
4484 (setq past nil)
4485 (insert (make-string 79 ?-) "\n")))
4486 (setq date (calendar-gregorian-from-absolute d))
4487 (setq s (point))
4488 (setq rtn (apply 'org-agenda-get-day-entries
4489 entry date args))
4490 (if (or rtn (equal d today))
4491 (progn
4492 (insert (calendar-day-name date) " "
4493 (number-to-string (extract-calendar-day date)) " "
4494 (calendar-month-name (extract-calendar-month date)) " "
4495 (number-to-string (extract-calendar-year date)) "\n")
4496 (put-text-property s (1- (point)) 'face
4497 'org-link)
4498 (if (equal d today)
4499 (put-text-property s (1- (point)) 'org-today t))
4500 (insert (org-finalize-agenda-entries rtn) "\n")
4501 (put-text-property s (1- (point)) 'day d))))
4502 (goto-char (point-min))
4503 (setq buffer-read-only t)
4504 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4505 (point-min)))
4506 (when (not org-select-timeline-window)
4507 (select-window win)
4508 (goto-char pos1))))
4509
4510 ;;;###autoload
4511 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4512 "Produce a weekly view from all files in variable `org-agenda-files'.
4513 The view will be for the current week, but from the overview buffer you
4514 will be able to go to other weeks.
4515 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4516 also be shown, under the current date.
4517 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4518 on the days are also shown. See the variable `org-log-done' for how
4519 to turn on logging.
4520 START-DAY defaults to TODAY, or to the most recent match for the weekday
4521 given in `org-agenda-start-on-weekday'.
4522 NDAYS defaults to `org-agenda-ndays'."
4523 (interactive "P")
4524 (org-agenda-maybe-reset-markers 'force)
4525 (org-compile-prefix-format org-agenda-prefix-format)
4526 (require 'calendar)
4527 (let* ((org-agenda-start-on-weekday
4528 (if (or (equal ndays 1)
4529 (and (null ndays) (equal 1 org-agenda-ndays)))
4530 nil org-agenda-start-on-weekday))
4531 (org-agenda-keep-modes keep-modes)
4532 (files (copy-sequence (org-agenda-files)))
4533 (win (selected-window))
4534 (today (time-to-days (current-time)))
4535 (sd (or start-day today))
4536 (start (if (or (null org-agenda-start-on-weekday)
4537 (< org-agenda-ndays 7))
4538 sd
4539 (let* ((nt (calendar-day-of-week
4540 (calendar-gregorian-from-absolute sd)))
4541 (n1 org-agenda-start-on-weekday)
4542 (d (- nt n1)))
4543 (- sd (+ (if (< d 0) 7 0) d)))))
4544 (day-numbers (list start))
4545 (inhibit-redisplay t)
4546 s e rtn rtnall file date d start-pos end-pos todayp nd)
4547 (setq org-agenda-redo-command
4548 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4549 ;; Make the list of days
4550 (setq ndays (or ndays org-agenda-ndays)
4551 nd ndays)
4552 (while (> ndays 1)
4553 (push (1+ (car day-numbers)) day-numbers)
4554 (setq ndays (1- ndays)))
4555 (setq day-numbers (nreverse day-numbers))
4556 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4557 (progn
4558 (delete-other-windows)
4559 (switch-to-buffer-other-window
4560 (get-buffer-create org-agenda-buffer-name))))
4561 (setq buffer-read-only nil)
4562 (erase-buffer)
4563 (org-agenda-mode) (setq buffer-read-only nil)
4564 (set (make-local-variable 'org-agenda-type) 'agenda)
4565 (set (make-local-variable 'starting-day) (car day-numbers))
4566 (set (make-local-variable 'include-all-loc) include-all)
4567 (when (and (or include-all org-agenda-include-all-todo)
4568 (member today day-numbers))
4569 (setq files (org-agenda-files)
4570 rtnall nil)
4571 (while (setq file (pop files))
4572 (catch 'nextfile
4573 (org-check-agenda-file file)
4574 (setq date (calendar-gregorian-from-absolute today)
4575 rtn (org-agenda-get-day-entries
4576 file date :todo))
4577 (setq rtnall (append rtnall rtn))))
4578 (when rtnall
4579 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4580 (add-text-properties (point-min) (1- (point))
4581 (list 'face 'org-link))
4582 (insert (org-finalize-agenda-entries rtnall) "\n")))
4583 (while (setq d (pop day-numbers))
4584 (setq date (calendar-gregorian-from-absolute d)
4585 s (point))
4586 (if (or (setq todayp (= d today))
4587 (and (not start-pos) (= d sd)))
4588 (setq start-pos (point))
4589 (if (and start-pos (not end-pos))
4590 (setq end-pos (point))))
4591 (setq files (org-agenda-files)
4592 rtnall nil)
4593 (while (setq file (pop files))
4594 (catch 'nextfile
4595 (org-check-agenda-file file)
4596 (if org-agenda-show-log
4597 (setq rtn (org-agenda-get-day-entries
4598 file date
4599 :deadline :scheduled :timestamp :closed))
4600 (setq rtn (org-agenda-get-day-entries
4601 file date
4602 :deadline :scheduled :timestamp)))
4603 (setq rtnall (append rtnall rtn))))
4604 (if org-agenda-include-diary
4605 (progn
4606 (require 'diary-lib)
4607 (setq rtn (org-get-entries-from-diary date))
4608 (setq rtnall (append rtnall rtn))))
4609 (if (or rtnall org-agenda-show-all-dates)
4610 (progn
4611 (insert (format "%-9s %2d %s %4d\n"
4612 (calendar-day-name date)
4613 (extract-calendar-day date)
4614 (calendar-month-name (extract-calendar-month date))
4615 (extract-calendar-year date)))
4616 (put-text-property s (1- (point)) 'face
4617 'org-link)
4618 (if rtnall (insert
4619 (org-finalize-agenda-entries
4620 (org-agenda-add-time-grid-maybe
4621 rtnall nd todayp))
4622 "\n"))
4623 (put-text-property s (1- (point)) 'day d))))
4624 (goto-char (point-min))
4625 (setq buffer-read-only t)
4626 (org-fit-agenda-window)
4627 (unless (and (pos-visible-in-window-p (point-min))
4628 (pos-visible-in-window-p (point-max)))
4629 (goto-char (1- (point-max)))
4630 (recenter -1)
4631 (if (not (pos-visible-in-window-p (or start-pos 1)))
4632 (progn
4633 (goto-char (or start-pos 1))
4634 (recenter 1))))
4635 (goto-char (or start-pos 1))
4636 (if (not org-select-agenda-window) (select-window win))
4637 (message "")))
4638
4639 (defvar org-select-this-todo-keyword nil)
4640
4641 ;;;###autoload
4642 (defun org-todo-list (arg &optional keep-modes)
4643 "Show all TODO entries from all agenda file in a single list.
4644 The prefix arg can be used to select a specific TODO keyword and limit
4645 the list to these. When using \\[universal-argument], you will be prompted
4646 for a keyword. A numeric prefix directly selects the Nth keyword in
4647 `org-todo-keywords'."
4648 (interactive "P")
4649 (org-agenda-maybe-reset-markers 'force)
4650 (org-compile-prefix-format org-agenda-prefix-format)
4651 (let* ((org-agenda-keep-modes keep-modes)
4652 (today (time-to-days (current-time)))
4653 (date (calendar-gregorian-from-absolute today))
4654 (win (selected-window))
4655 (kwds org-todo-keywords)
4656 (completion-ignore-case t)
4657 (org-select-this-todo-keyword
4658 (if (stringp arg) arg
4659 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4660 rtn rtnall files file pos)
4661 (when (equal arg '(4))
4662 (setq org-select-this-todo-keyword
4663 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4664 nil t)))
4665 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4666 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4667 (progn
4668 (delete-other-windows)
4669 (switch-to-buffer-other-window
4670 (get-buffer-create org-agenda-buffer-name))))
4671 (setq buffer-read-only nil)
4672 (erase-buffer)
4673 (org-agenda-mode) (setq buffer-read-only nil)
4674 (set (make-local-variable 'org-agenda-type) 'todo)
4675 (set (make-local-variable 'org-todo-keywords) kwds)
4676 (set (make-local-variable 'org-agenda-redo-command)
4677 `(org-todo-list (or current-prefix-arg ',arg) t))
4678 (setq files (org-agenda-files)
4679 rtnall nil)
4680 (while (setq file (pop files))
4681 (catch 'nextfile
4682 (org-check-agenda-file file)
4683 (setq rtn (org-agenda-get-day-entries file date :todo))
4684 (setq rtnall (append rtnall rtn))))
4685 (insert "Global list of TODO items of type: ")
4686 (add-text-properties (point-min) (1- (point))
4687 (list 'face 'org-link))
4688 (setq pos (point))
4689 (insert (or org-select-this-todo-keyword "ALL") "\n")
4690 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4691 (setq pos (point))
4692 (insert
4693 "Available with `N r': (0)ALL "
4694 (let ((n 0))
4695 (mapconcat (lambda (x)
4696 (format "(%d)%s" (setq n (1+ n)) x))
4697 org-todo-keywords " "))
4698 "\n")
4699 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4700 (when rtnall
4701 (insert (org-finalize-agenda-entries rtnall) "\n"))
4702 (goto-char (point-min))
4703 (setq buffer-read-only t)
4704 (org-fit-agenda-window)
4705 (if (not org-select-agenda-window) (select-window win))))
4706
4707 (defun org-check-agenda-file (file)
4708 "Make sure FILE exists. If not, ask user what to do."
4709 ;; FIXME: this does not correctly change the menus
4710 ;; Could probably be fixed by explicitly going to the buffer where
4711 ;; the call originated.
4712 (when (not (file-exists-p file))
4713 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4714 file)
4715 (let ((r (downcase (read-char-exclusive))))
4716 (cond
4717 ((equal r ?r)
4718 (org-remove-file file)
4719 (throw 'nextfile t))
4720 (t (error "Abort"))))))
4721
4722 (defun org-agenda-check-type (error &rest types)
4723 "Check if agenda buffer is of allowed type.
4724 If ERROR is non-nil, throw an error, otherwise just return nil."
4725 (if (memq org-agenda-type types)
4726 t
4727 (if error
4728 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
4729 nil)))
4730
4731 (defun org-agenda-quit ()
4732 "Exit agenda by removing the window or the buffer."
4733 (interactive)
4734 (let ((buf (current-buffer)))
4735 (if (not (one-window-p)) (delete-window))
4736 (kill-buffer buf)
4737 (org-agenda-maybe-reset-markers 'force)))
4738
4739 (defun org-agenda-exit ()
4740 "Exit agenda by removing the window or the buffer.
4741 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4742 Org-mode buffers visited directly by the user will not be touched."
4743 (interactive)
4744 (org-release-buffers org-agenda-new-buffers)
4745 (setq org-agenda-new-buffers nil)
4746 (org-agenda-quit))
4747
4748 (defun org-agenda-redo ()
4749 "Rebuild Agenda.
4750 When this is the global TODO list, a prefix argument will be interpreted."
4751 (interactive)
4752 (message "Rebuilding agenda buffer...")
4753 (eval org-agenda-redo-command)
4754 (message "Rebuilding agenda buffer...done"))
4755
4756 (defun org-agenda-goto-today ()
4757 "Go to today."
4758 (interactive)
4759 (org-agenda-check-type t 'timeline 'agenda)
4760 (if (boundp 'starting-day)
4761 (let ((cmd (car org-agenda-redo-command))
4762 (iall (nth 1 org-agenda-redo-command))
4763 (nday (nth 3 org-agenda-redo-command))
4764 (keep (nth 4 org-agenda-redo-command)))
4765 (eval (list cmd iall nil nday keep)))
4766 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4767 (point-min)))))
4768
4769 (defun org-agenda-later (arg)
4770 "Go forward in time by `org-agenda-ndays' days.
4771 With prefix ARG, go forward that many times `org-agenda-ndays'."
4772 (interactive "p")
4773 (org-agenda-check-type t 'agenda)
4774 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4775 (+ starting-day (* arg org-agenda-ndays)) nil t))
4776
4777 (defun org-agenda-earlier (arg)
4778 "Go back in time by `org-agenda-ndays' days.
4779 With prefix ARG, go back that many times `org-agenda-ndays'."
4780 (interactive "p")
4781 (org-agenda-check-type t 'agenda)
4782 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4783 (- starting-day (* arg org-agenda-ndays)) nil t))
4784
4785 (defun org-agenda-week-view ()
4786 "Switch to weekly view for agenda."
4787 (interactive)
4788 (org-agenda-check-type t 'agenda)
4789 (setq org-agenda-ndays 7)
4790 (org-agenda-list include-all-loc
4791 (or (get-text-property (point) 'day)
4792 starting-day)
4793 nil t)
4794 (org-agenda-set-mode-name)
4795 (message "Switched to week view"))
4796
4797 (defun org-agenda-day-view ()
4798 "Switch to weekly view for agenda."
4799 (interactive)
4800 (org-agenda-check-type t 'agenda)
4801 (setq org-agenda-ndays 1)
4802 (org-agenda-list include-all-loc
4803 (or (get-text-property (point) 'day)
4804 starting-day)
4805 nil t)
4806 (org-agenda-set-mode-name)
4807 (message "Switched to day view"))
4808
4809 (defun org-agenda-next-date-line (&optional arg)
4810 "Jump to the next line indicating a date in agenda buffer."
4811 (interactive "p")
4812 (org-agenda-check-type t 'agenda 'timeline)
4813 (beginning-of-line 1)
4814 (if (looking-at "^\\S-") (forward-char 1))
4815 (if (not (re-search-forward "^\\S-" nil t arg))
4816 (progn
4817 (backward-char 1)
4818 (error "No next date after this line in this buffer")))
4819 (goto-char (match-beginning 0)))
4820
4821 (defun org-agenda-previous-date-line (&optional arg)
4822 "Jump to the next line indicating a date in agenda buffer."
4823 (interactive "p")
4824 (org-agenda-check-type t 'agenda 'timeline)
4825 (beginning-of-line 1)
4826 (if (not (re-search-backward "^\\S-" nil t arg))
4827 (error "No previous date before this line in this buffer")))
4828
4829 ;; Initialize the highlight
4830 (defvar org-hl (org-make-overlay 1 1))
4831 (org-overlay-put org-hl 'face 'highlight)
4832
4833 (defun org-highlight (begin end &optional buffer)
4834 "Highlight a region with overlay."
4835 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4836 org-hl begin end (or buffer (current-buffer))))
4837
4838 (defun org-unhighlight ()
4839 "Detach overlay INDEX."
4840 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4841
4842
4843 (defun org-agenda-follow-mode ()
4844 "Toggle follow mode in an agenda buffer."
4845 (interactive)
4846 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4847 (org-agenda-set-mode-name)
4848 (message "Follow mode is %s"
4849 (if org-agenda-follow-mode "on" "off")))
4850
4851 (defun org-agenda-log-mode ()
4852 "Toggle follow mode in an agenda buffer."
4853 (interactive)
4854 (org-agenda-check-type t 'agenda 'timeline)
4855 (setq org-agenda-show-log (not org-agenda-show-log))
4856 (org-agenda-set-mode-name)
4857 (org-agenda-redo)
4858 (message "Log mode is %s"
4859 (if org-agenda-show-log "on" "off")))
4860
4861 (defun org-agenda-toggle-diary ()
4862 "Toggle follow mode in an agenda buffer."
4863 (interactive)
4864 (org-agenda-check-type t 'agenda)
4865 (setq org-agenda-include-diary (not org-agenda-include-diary))
4866 (org-agenda-redo)
4867 (org-agenda-set-mode-name)
4868 (message "Diary inclusion turned %s"
4869 (if org-agenda-include-diary "on" "off")))
4870
4871 (defun org-agenda-toggle-time-grid ()
4872 "Toggle follow mode in an agenda buffer."
4873 (interactive)
4874 (org-agenda-check-type t 'agenda)
4875 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4876 (org-agenda-redo)
4877 (org-agenda-set-mode-name)
4878 (message "Time-grid turned %s"
4879 (if org-agenda-use-time-grid "on" "off")))
4880
4881 (defun org-agenda-set-mode-name ()
4882 "Set the mode name to indicate all the small mode settings."
4883 (setq mode-name
4884 (concat "Org-Agenda"
4885 (if (equal org-agenda-ndays 1) " Day" "")
4886 (if (equal org-agenda-ndays 7) " Week" "")
4887 (if org-agenda-follow-mode " Follow" "")
4888 (if org-agenda-include-diary " Diary" "")
4889 (if org-agenda-use-time-grid " Grid" "")
4890 (if org-agenda-show-log " Log" "")))
4891 (force-mode-line-update))
4892
4893 (defun org-agenda-post-command-hook ()
4894 (and (eolp) (not (bolp)) (backward-char 1))
4895 (if (and org-agenda-follow-mode
4896 (get-text-property (point) 'org-marker))
4897 (org-agenda-show)))
4898
4899 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4900
4901 (defun org-get-entries-from-diary (date)
4902 "Get the (Emacs Calendar) diary entries for DATE."
4903 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4904 (diary-display-hook '(fancy-diary-display))
4905 (list-diary-entries-hook
4906 (cons 'org-diary-default-entry list-diary-entries-hook))
4907 (diary-file-name-prefix-function nil) ; turn this feature off
4908 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4909 entries
4910 (org-disable-agenda-to-diary t))
4911 (save-excursion
4912 (save-window-excursion
4913 (list-diary-entries date 1)))
4914 (if (not (get-buffer fancy-diary-buffer))
4915 (setq entries nil)
4916 (with-current-buffer fancy-diary-buffer
4917 (setq buffer-read-only nil)
4918 (if (= (point-max) 1)
4919 ;; No entries
4920 (setq entries nil)
4921 ;; Omit the date and other unnecessary stuff
4922 (org-agenda-cleanup-fancy-diary)
4923 ;; Add prefix to each line and extend the text properties
4924 (if (= (point-max) 1)
4925 (setq entries nil)
4926 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4927 (set-buffer-modified-p nil)
4928 (kill-buffer fancy-diary-buffer)))
4929 (when entries
4930 (setq entries (org-split-string entries "\n"))
4931 (setq entries
4932 (mapcar
4933 (lambda (x)
4934 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
4935 ;; Extend the text properties to the beginning of the line
4936 (add-text-properties
4937 0 (length x)
4938 (text-properties-at (1- (length x)) x)
4939 x)
4940 x)
4941 entries)))))
4942
4943 (defun org-agenda-cleanup-fancy-diary ()
4944 "Remove unwanted stuff in buffer created by fancy-diary-display.
4945 This gets rid of the date, the underline under the date, and
4946 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4947 date. Itt also removes lines that contain only whitespace."
4948 (goto-char (point-min))
4949 (if (looking-at ".*?:[ \t]*")
4950 (progn
4951 (replace-match "")
4952 (re-search-forward "\n=+$" nil t)
4953 (replace-match "")
4954 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4955 (re-search-forward "\n=+$" nil t)
4956 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4957 (goto-char (point-min))
4958 (while (re-search-forward "^ +\n" nil t)
4959 (replace-match ""))
4960 (goto-char (point-min))
4961 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4962 (replace-match "")))
4963
4964 ;; Make sure entries from the diary have the right text properties.
4965 (eval-after-load "diary-lib"
4966 '(if (boundp 'diary-modify-entry-list-string-function)
4967 ;; We can rely on the hook, nothing to do
4968 nil
4969 ;; Hook not avaiable, must use advice to make this work
4970 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4971 "Make the position visible."
4972 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4973 (stringp string)
4974 buffer-file-name)
4975 (setq string (org-modify-diary-entry-string string))))))
4976
4977 (defun org-modify-diary-entry-string (string)
4978 "Add text properties to string, allowing org-mode to act on it."
4979 (add-text-properties
4980 0 (length string)
4981 (list 'mouse-face 'highlight
4982 'keymap org-agenda-keymap
4983 'help-echo
4984 (format
4985 "mouse-2 or RET jump to diary file %s"
4986 (abbreviate-file-name buffer-file-name))
4987 'org-agenda-diary-link t
4988 'org-marker (org-agenda-new-marker (point-at-bol)))
4989 string)
4990 string)
4991
4992 (defun org-diary-default-entry ()
4993 "Add a dummy entry to the diary.
4994 Needed to avoid empty dates which mess up holiday display."
4995 ;; Catch the error if dealing with the new add-to-diary-alist
4996 (when org-disable-agenda-to-diary
4997 (condition-case nil
4998 (add-to-diary-list original-date "Org-mode dummy" "")
4999 (error
5000 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5001
5002 (defun org-cycle-agenda-files ()
5003 "Cycle through the files in `org-agenda-files'.
5004 If the current buffer visits an agenda file, find the next one in the list.
5005 If the current buffer does not, find the first agenda file."
5006 (interactive)
5007 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5008 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5009 file)
5010 (unless files (error "No agenda files"))
5011 (catch 'exit
5012 (while (setq file (pop files))
5013 (if (equal (file-truename file) tcf)
5014 (when (car files)
5015 (find-file (car files))
5016 (throw 'exit t))))
5017 (find-file (car org-agenda-files)))))
5018
5019 (defun org-agenda-file-to-end ()
5020 "Move/add the current file to the end of the agenda fiole list.
5021 If the file is not present in the list, append it to the list. If it is
5022 present, move it there."
5023 (interactive)
5024 (org-agenda-file-to-front 'to-end))
5025
5026 (defun org-agenda-file-to-front (&optional to-end)
5027 "Move/add the current file to the top of the agenda file list.
5028 If the file is not present in the list, add it to the front. If it is
5029 present, it move it there. With optional argument TO-END, add/move to the
5030 end of the list."
5031 (interactive "P")
5032 (let* ((file-alist (mapcar (lambda (x)
5033 (cons (file-truename x) x))
5034 org-agenda-files))
5035 (ctf (file-truename buffer-file-name))
5036 (had (assoc ctf file-alist))
5037 (x (or had (cons ctf (abbreviate-file-name buffer-file-name)))))
5038 (setq file-alist (if to-end
5039 (append (delq x file-alist) (list x))
5040 (cons x (delq x file-alist))))
5041 (setq org-agenda-files (mapcar 'cdr file-alist))
5042 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5043 (customize-save-variable 'org-agenda-files org-agenda-files))
5044 (org-install-agenda-files-menu)
5045 (message "File %s to %s of agenda file list"
5046 (if had "moved" "added") (if to-end "end" "front"))))
5047
5048 (defun org-remove-file (&optional file)
5049 "Remove current file from the list of files in variable `org-agenda-files'.
5050 These are the files which are being checked for agenda entries.
5051 Optional argument FILE means, use this file instead of the current."
5052 (interactive)
5053 (let* ((file (or file buffer-file-name))
5054 (true-file (file-truename file))
5055 (afile (abbreviate-file-name file))
5056 (files (delq nil (mapcar
5057 (lambda (x)
5058 (if (equal true-file
5059 (file-truename x))
5060 nil x))
5061 org-agenda-files))))
5062 (if (not (= (length files) (length org-agenda-files)))
5063 (progn
5064 (setq org-agenda-files files)
5065 (customize-save-variable 'org-agenda-files org-agenda-files)
5066 (org-install-agenda-files-menu)
5067 (message "Removed file: %s" afile))
5068 (message "File was not in list: %s" afile))))
5069
5070 (defun org-file-menu-entry (file)
5071 (vector file (list 'find-file file) t))
5072 ;; FIXME: Maybe we removed a buffer visited through the menu from
5073 ;; org-agenda-new-buffers, so that the buffer will not be removed
5074 ;; when exiting the agenda????
5075
5076 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5077 "Return a list of all relevant day numbers from BEG to END buffer positions.
5078 If NO-RANGES is non-nil, include only the start and end dates of a range,
5079 not every single day in the range. If FORCE-TODAY is non-nil, make
5080 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5081 inactive time stamps (those in square brackets) are included."
5082 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5083 dates date day day1 day2 ts1 ts2)
5084 (if force-today
5085 (setq dates (list (time-to-days (current-time)))))
5086 (save-excursion
5087 (goto-char beg)
5088 (while (re-search-forward re end t)
5089 (setq day (time-to-days (org-time-string-to-time
5090 (substring (match-string 1) 0 10))))
5091 (or (memq day dates) (push day dates)))
5092 (unless no-ranges
5093 (goto-char beg)
5094 (while (re-search-forward org-tr-regexp end t)
5095 (setq ts1 (substring (match-string 1) 0 10)
5096 ts2 (substring (match-string 2) 0 10)
5097 day1 (time-to-days (org-time-string-to-time ts1))
5098 day2 (time-to-days (org-time-string-to-time ts2)))
5099 (while (< (setq day1 (1+ day1)) day2)
5100 (or (memq day1 dates) (push day1 dates)))))
5101 (sort dates '<))))
5102
5103 ;;;###autoload
5104 (defun org-diary (&rest args)
5105 "Return diary information from org-files.
5106 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5107 It accesses org files and extracts information from those files to be
5108 listed in the diary. The function accepts arguments specifying what
5109 items should be listed. The following arguments are allowed:
5110
5111 :timestamp List the headlines of items containing a date stamp or
5112 date range matching the selected date. Deadlines will
5113 also be listed, on the expiration day.
5114
5115 :deadline List any deadlines past due, or due within
5116 `org-deadline-warning-days'. The listing occurs only
5117 in the diary for *today*, not at any other date. If
5118 an entry is marked DONE, it is no longer listed.
5119
5120 :scheduled List all items which are scheduled for the given date.
5121 The diary for *today* also contains items which were
5122 scheduled earlier and are not yet marked DONE.
5123
5124 :todo List all TODO items from the org-file. This may be a
5125 long list - so this is not turned on by default.
5126 Like deadlines, these entries only show up in the
5127 diary for *today*, not at any other date.
5128
5129 The call in the diary file should look like this:
5130
5131 &%%(org-diary) ~/path/to/some/orgfile.org
5132
5133 Use a separate line for each org file to check. Or, if you omit the file name,
5134 all files listed in `org-agenda-files' will be checked automatically:
5135
5136 &%%(org-diary)
5137
5138 If you don't give any arguments (as in the example above), the default
5139 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5140 also be written as
5141
5142 &%%(org-diary :deadline :timestamp :scheduled)
5143
5144 The function expects the lisp variables `entry' and `date' to be provided
5145 by the caller, because this is how the calendar works. Don't use this
5146 function from a program - use `org-agenda-get-day-entries' instead."
5147 (org-agenda-maybe-reset-markers)
5148 (org-compile-prefix-format org-agenda-prefix-format)
5149 (setq args (or args '(:deadline :scheduled :timestamp)))
5150 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5151 (list entry)
5152 org-agenda-files))
5153 file rtn results)
5154 ;; If this is called during org-agenda, don't return any entries to
5155 ;; the calendar. Org Agenda will list these entries itself.
5156 (if org-disable-agenda-to-diary (setq files nil))
5157 (while (setq file (pop files))
5158 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5159 (setq results (append results rtn)))
5160 (if results
5161 (concat (org-finalize-agenda-entries results) "\n"))))
5162 (defvar org-category-table nil)
5163 (defun org-get-category-table ()
5164 "Get the table of categories and positions in current buffer."
5165 (let (tbl)
5166 (save-excursion
5167 (goto-char (point-min))
5168 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5169 (push (cons (point) (org-trim (match-string 2))) tbl)))
5170 tbl))
5171 (defun org-get-category (&optional pos)
5172 "Get the category applying to position POS."
5173 (if (not org-category-table)
5174 (cond
5175 ((null org-category)
5176 (setq org-category
5177 (if buffer-file-name
5178 (file-name-sans-extension
5179 (file-name-nondirectory buffer-file-name))
5180 "???")))
5181 ((symbolp org-category) (symbol-name org-category))
5182 (t org-category))
5183 (let ((tbl org-category-table)
5184 (pos (or pos (point))))
5185 (while (and tbl (> (caar tbl) pos))
5186 (pop tbl))
5187 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5188 org-category-table))))))
5189
5190 (defun org-agenda-get-day-entries (file date &rest args)
5191 "Does the work for `org-diary' and `org-agenda'.
5192 FILE is the path to a file to be checked for entries. DATE is date like
5193 the one returned by `calendar-current-date'. ARGS are symbols indicating
5194 which kind of entries should be extracted. For details about these, see
5195 the documentation of `org-diary'."
5196 (setq args (or args '(:deadline :scheduled :timestamp)))
5197 (let* ((org-startup-with-deadline-check nil)
5198 (org-startup-folded nil)
5199 (buffer (if (file-exists-p file)
5200 (org-get-agenda-file-buffer file)
5201 (error "No such file %s" file)))
5202 arg results rtn)
5203 (if (not buffer)
5204 ;; If file does not exist, make sure an error message ends up in diary
5205 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5206 (with-current-buffer buffer
5207 (unless (eq major-mode 'org-mode)
5208 (error "Agenda file %s is not in `org-mode'" file))
5209 (setq org-category-table (org-get-category-table))
5210 (let ((case-fold-search nil))
5211 (save-excursion
5212 (save-restriction
5213 (if org-respect-restriction
5214 (if (org-region-active-p)
5215 ;; Respect a region to restrict search
5216 (narrow-to-region (region-beginning) (region-end)))
5217 ;; If we work for the calendar or many files,
5218 ;; get rid of any restriction
5219 (widen))
5220 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5221 (while (setq arg (pop args))
5222 (cond
5223 ((and (eq arg :todo)
5224 (equal date (calendar-current-date)))
5225 (setq rtn (org-agenda-get-todos))
5226 (setq results (append results rtn)))
5227 ((eq arg :timestamp)
5228 (setq rtn (org-agenda-get-blocks))
5229 (setq results (append results rtn))
5230 (setq rtn (org-agenda-get-timestamps))
5231 (setq results (append results rtn)))
5232 ((eq arg :scheduled)
5233 (setq rtn (org-agenda-get-scheduled))
5234 (setq results (append results rtn)))
5235 ((eq arg :closed)
5236 (setq rtn (org-agenda-get-closed))
5237 (setq results (append results rtn)))
5238 ((and (eq arg :deadline)
5239 (equal date (calendar-current-date)))
5240 (setq rtn (org-agenda-get-deadlines))
5241 (setq results (append results rtn))))))))
5242 results))))
5243
5244 (defun org-entry-is-done-p ()
5245 "Is the current entry marked DONE?"
5246 (save-excursion
5247 (and (re-search-backward "[\r\n]\\*" nil t)
5248 (looking-at org-nl-done-regexp))))
5249
5250 (defun org-at-date-range-p ()
5251 "Is the cursor inside a date range?"
5252 (interactive)
5253 (save-excursion
5254 (catch 'exit
5255 (let ((pos (point)))
5256 (skip-chars-backward "^<\r\n")
5257 (skip-chars-backward "<")
5258 (and (looking-at org-tr-regexp)
5259 (>= (match-end 0) pos)
5260 (throw 'exit t))
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 nil)))
5267
5268 (defun org-agenda-get-todos ()
5269 "Return the TODO information for agenda display."
5270 (let* ((props (list 'face nil
5271 'done-face 'org-done
5272 'mouse-face 'highlight
5273 'keymap org-agenda-keymap
5274 'help-echo
5275 (format "mouse-2 or RET jump to org file %s"
5276 (abbreviate-file-name buffer-file-name))))
5277 (regexp (concat "[\n\r]\\*+ *\\("
5278 (if org-select-this-todo-keyword
5279 (concat "\\<\\(" org-select-this-todo-keyword
5280 "\\)\\>")
5281 org-not-done-regexp)
5282 "[^\n\r]*\\)"))
5283 marker priority category tags
5284 ee txt)
5285 (goto-char (point-min))
5286 (while (re-search-forward regexp nil t)
5287 (goto-char (match-beginning 1))
5288 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5289 category (org-get-category)
5290 tags (org-get-tags-at (point))
5291 txt (org-format-agenda-item "" (match-string 1) category tags)
5292 priority
5293 (+ (org-get-priority txt)
5294 (if org-todo-kwd-priority-p
5295 (- org-todo-kwd-max-priority -2
5296 (length
5297 (member (match-string 2) org-todo-keywords)))
5298 1)))
5299 (add-text-properties
5300 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5301 'priority priority 'category category)
5302 props)
5303 txt)
5304 (push txt ee)
5305 (goto-char (match-end 1)))
5306 (nreverse ee)))
5307
5308 (defconst org-agenda-no-heading-message
5309 "No heading for this item in buffer or region")
5310
5311 (defun org-agenda-get-timestamps ()
5312 "Return the date stamp information for agenda display."
5313 (let* ((props (list 'face nil
5314 'mouse-face 'highlight
5315 'keymap org-agenda-keymap
5316 'help-echo
5317 (format "mouse-2 or RET jump to org file %s"
5318 (abbreviate-file-name buffer-file-name))))
5319 (regexp (regexp-quote
5320 (substring
5321 (format-time-string
5322 (car org-time-stamp-formats)
5323 (apply 'encode-time ; DATE bound by calendar
5324 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5325 0 11)))
5326 marker hdmarker deadlinep scheduledp donep tmp priority category
5327 ee txt timestr tags)
5328 (goto-char (point-min))
5329 (while (re-search-forward regexp nil t)
5330 (if (not (save-match-data (org-at-date-range-p)))
5331 (progn
5332 (setq marker (org-agenda-new-marker (match-beginning 0))
5333 category (org-get-category (match-beginning 0))
5334 tmp (buffer-substring (max (point-min)
5335 (- (match-beginning 0)
5336 org-ds-keyword-length))
5337 (match-beginning 0))
5338 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5339 deadlinep (string-match org-deadline-regexp tmp)
5340 scheduledp (string-match org-scheduled-regexp tmp)
5341 donep (org-entry-is-done-p))
5342 (if (string-match ">" timestr)
5343 ;; substring should only run to end of time stamp
5344 (setq timestr (substring timestr 0 (match-end 0))))
5345 (save-excursion
5346 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5347 (progn
5348 (goto-char (match-end 1))
5349 (setq hdmarker (org-agenda-new-marker)
5350 tags (org-get-tags-at))
5351 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5352 (setq txt (org-format-agenda-item
5353 (format "%s%s"
5354 (if deadlinep "Deadline: " "")
5355 (if scheduledp "Scheduled: " ""))
5356 (match-string 1) category tags timestr)))
5357 (setq txt org-agenda-no-heading-message))
5358 (setq priority (org-get-priority txt))
5359 (add-text-properties
5360 0 (length txt) (append (list 'org-marker marker
5361 'org-hd-marker hdmarker) props)
5362 txt)
5363 (if deadlinep
5364 (add-text-properties
5365 0 (length txt)
5366 (list 'face
5367 (if donep 'org-done 'org-warning)
5368 'undone-face 'org-warning
5369 'done-face 'org-done
5370 'category category
5371 'priority (+ 100 priority))
5372 txt)
5373 (if scheduledp
5374 (add-text-properties
5375 0 (length txt)
5376 (list 'face 'org-scheduled-today
5377 'undone-face 'org-scheduled-today
5378 'done-face 'org-done
5379 'category category
5380 priority (+ 99 priority))
5381 txt)
5382 (add-text-properties
5383 0 (length txt)
5384 (list 'priority priority 'category category) txt)))
5385 (push txt ee))
5386 (outline-next-heading))))
5387 (nreverse ee)))
5388
5389 (defun org-agenda-get-closed ()
5390 "Return the loggedd TODO entries for agenda display."
5391 (let* ((props (list 'mouse-face 'highlight
5392 'keymap org-agenda-keymap
5393 'help-echo
5394 (format "mouse-2 or RET jump to org file %s"
5395 (abbreviate-file-name buffer-file-name))))
5396 (regexp (concat
5397 "\\<" org-closed-string " *\\["
5398 (regexp-quote
5399 (substring
5400 (format-time-string
5401 (car org-time-stamp-formats)
5402 (apply 'encode-time ; DATE bound by calendar
5403 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5404 1 11))))
5405 marker hdmarker priority category tags
5406 ee txt timestr)
5407 (goto-char (point-min))
5408 (while (re-search-forward regexp nil t)
5409 (if (not (save-match-data (org-at-date-range-p)))
5410 (progn
5411 (setq marker (org-agenda-new-marker (match-beginning 0))
5412 category (org-get-category (match-beginning 0))
5413 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5414 ;; donep (org-entry-is-done-p)
5415 )
5416 (if (string-match "\\]" timestr)
5417 ;; substring should only run to end of time stamp
5418 (setq timestr (substring timestr 0 (match-end 0))))
5419 (save-excursion
5420 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5421 (progn
5422 (goto-char (match-end 1))
5423 (setq hdmarker (org-agenda-new-marker)
5424 tags (org-get-tags-at))
5425 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5426 (setq txt (org-format-agenda-item
5427 "Closed: "
5428 (match-string 1) category tags timestr)))
5429 (setq txt org-agenda-no-heading-message))
5430 (setq priority 100000)
5431 (add-text-properties
5432 0 (length txt) (append (list 'org-marker marker
5433 'org-hd-marker hdmarker
5434 'face 'org-done
5435 'priority priority
5436 'category category
5437 'undone-face 'org-warning
5438 'done-face 'org-done) props)
5439 txt)
5440 (push txt ee))
5441 (outline-next-heading))))
5442 (nreverse ee)))
5443
5444 (defun org-agenda-get-deadlines ()
5445 "Return the deadline information for agenda display."
5446 (let* ((wdays org-deadline-warning-days)
5447 (props (list 'mouse-face 'highlight
5448 'keymap org-agenda-keymap
5449 'help-echo
5450 (format "mouse-2 or RET jump to org file %s"
5451 (abbreviate-file-name buffer-file-name))))
5452 (regexp org-deadline-time-regexp)
5453 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5454 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5455 d2 diff pos pos1 category tags
5456 ee txt head)
5457 (goto-char (point-min))
5458 (while (re-search-forward regexp nil t)
5459 (setq pos (1- (match-beginning 1))
5460 d2 (time-to-days
5461 (org-time-string-to-time (match-string 1)))
5462 diff (- d2 d1))
5463 ;; When to show a deadline in the calendar:
5464 ;; If the expiration is within wdays warning time.
5465 ;; Past-due deadlines are only shown on the current date
5466 (if (and (< diff wdays) todayp (not (= diff 0)))
5467 (save-excursion
5468 (setq category (org-get-category))
5469 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5470 (progn
5471 (goto-char (match-end 0))
5472 (setq pos1 (match-end 1))
5473 (setq tags (org-get-tags-at pos1))
5474 (setq head (buffer-substring-no-properties
5475 (point)
5476 (progn (skip-chars-forward "^\r\n")
5477 (point))))
5478 (if (string-match org-looking-at-done-regexp head)
5479 (setq txt nil)
5480 (setq txt (org-format-agenda-item
5481 (format "In %3d d.: " diff) head category tags))))
5482 (setq txt org-agenda-no-heading-message))
5483 (when txt
5484 (add-text-properties
5485 0 (length txt)
5486 (append
5487 (list 'org-marker (org-agenda-new-marker pos)
5488 'org-hd-marker (org-agenda-new-marker pos1)
5489 'priority (+ (- 10 diff) (org-get-priority txt))
5490 'category category
5491 'face (cond ((<= diff 0) 'org-warning)
5492 ((<= diff 5) 'org-scheduled-previously)
5493 (t nil))
5494 'undone-face (cond
5495 ((<= diff 0) 'org-warning)
5496 ((<= diff 5) 'org-scheduled-previously)
5497 (t nil))
5498 'done-face 'org-done)
5499 props)
5500 txt)
5501 (push txt ee)))))
5502 ee))
5503
5504 (defun org-agenda-get-scheduled ()
5505 "Return the scheduled information for agenda display."
5506 (let* ((props (list 'face 'org-scheduled-previously
5507 'undone-face 'org-scheduled-previously
5508 'done-face 'org-done
5509 'mouse-face 'highlight
5510 'keymap org-agenda-keymap
5511 'help-echo
5512 (format "mouse-2 or RET jump to org file %s"
5513 (abbreviate-file-name buffer-file-name))))
5514 (regexp org-scheduled-time-regexp)
5515 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5516 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5517 d2 diff pos pos1 category tags
5518 ee txt head)
5519 (goto-char (point-min))
5520 (while (re-search-forward regexp nil t)
5521 (setq pos (1- (match-beginning 1))
5522 d2 (time-to-days
5523 (org-time-string-to-time (match-string 1)))
5524 diff (- d2 d1))
5525 ;; When to show a scheduled item in the calendar:
5526 ;; If it is on or past the date.
5527 (if (and (< diff 0) todayp)
5528 (save-excursion
5529 (setq category (org-get-category))
5530 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5531 (progn
5532 (goto-char (match-end 0))
5533 (setq pos1 (match-end 1))
5534 (setq tags (org-get-tags-at))
5535 (setq head (buffer-substring-no-properties
5536 (point)
5537 (progn (skip-chars-forward "^\r\n") (point))))
5538 (if (string-match org-looking-at-done-regexp head)
5539 (setq txt nil)
5540 (setq txt (org-format-agenda-item
5541 (format "Sched.%2dx: " (- 1 diff)) head
5542 category tags))))
5543 (setq txt org-agenda-no-heading-message))
5544 (when txt
5545 (add-text-properties
5546 0 (length txt)
5547 (append (list 'org-marker (org-agenda-new-marker pos)
5548 'org-hd-marker (org-agenda-new-marker pos1)
5549 'priority (+ (- 5 diff) (org-get-priority txt))
5550 'category category)
5551 props) txt)
5552 (push txt ee)))))
5553 ee))
5554
5555 (defun org-agenda-get-blocks ()
5556 "Return the date-range information for agenda display."
5557 (let* ((props (list 'face nil
5558 'mouse-face 'highlight
5559 'keymap org-agenda-keymap
5560 'help-echo
5561 (format "mouse-2 or RET jump to org file %s"
5562 (abbreviate-file-name buffer-file-name))))
5563 (regexp org-tr-regexp)
5564 (d0 (calendar-absolute-from-gregorian date))
5565 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
5566 (goto-char (point-min))
5567 (while (re-search-forward regexp nil t)
5568 (setq timestr (match-string 0)
5569 s1 (match-string 1)
5570 s2 (match-string 2)
5571 d1 (time-to-days (org-time-string-to-time s1))
5572 d2 (time-to-days (org-time-string-to-time s2)))
5573 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5574 ;; Only allow days between the limits, because the normal
5575 ;; date stamps will catch the limits.
5576 (save-excursion
5577 (setq marker (org-agenda-new-marker (point)))
5578 (setq category (org-get-category))
5579 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5580 (progn
5581 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5582 (goto-char (match-end 1))
5583 (setq tags (org-get-tags-at))
5584 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5585 (setq txt (org-format-agenda-item
5586 (format (if (= d1 d2) "" "(%d/%d): ")
5587 (1+ (- d0 d1)) (1+ (- d2 d1)))
5588 (match-string 1) category tags
5589 (if (= d0 d1) timestr))))
5590 (setq txt org-agenda-no-heading-message))
5591 (add-text-properties
5592 0 (length txt) (append (list 'org-marker marker
5593 'org-hd-marker hdmarker
5594 'priority (org-get-priority txt)
5595 'category category)
5596 props)
5597 txt)
5598 (push txt ee)))
5599 (outline-next-heading))
5600 ;; Sort the entries by expiration date.
5601 (nreverse ee)))
5602
5603 (defconst org-plain-time-of-day-regexp
5604 (concat
5605 "\\(\\<[012]?[0-9]"
5606 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5607 "\\(--?"
5608 "\\(\\<[012]?[0-9]"
5609 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5610 "\\)?")
5611 "Regular expression to match a plain time or time range.
5612 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5613 groups carry important information:
5614 0 the full match
5615 1 the first time, range or not
5616 8 the second time, if it is a range.")
5617
5618 (defconst org-stamp-time-of-day-regexp
5619 (concat
5620 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5621 "\\([012][0-9]:[0-5][0-9]\\)>"
5622 "\\(--?"
5623 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5624 "Regular expression to match a timestamp time or time range.
5625 After a match, the following groups carry important information:
5626 0 the full match
5627 1 date plus weekday, for backreferencing to make sure both times on same day
5628 2 the first time, range or not
5629 4 the second time, if it is a range.")
5630
5631 (defvar org-prefix-has-time nil
5632 "A flag, set by `org-compile-prefix-format'.
5633 The flag is set if the currently compiled format contains a `%t'.")
5634
5635 (defvar time) ;Needed for the eval of the prefix format.
5636 (defvar tag) ;Presumably, same thing as above.
5637 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
5638 "Format TXT to be inserted into the agenda buffer.
5639 In particular, it adds the prefix and corresponding text properties. EXTRA
5640 must be a string and replaces the `%s' specifier in the prefix format.
5641 CATEGORY (string, symbol or nil) may be used to overule the default
5642 category taken from local variable or file name. It will replace the `%c'
5643 specifier in the format. DOTIME, when non-nil, indicates that a
5644 time-of-day should be extracted from TXT for sorting of this entry, and for
5645 the `%t' specifier in the format. When DOTIME is a string, this string is
5646 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5647 only the correctly processes TXT should be returned - this is used by
5648 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
5649 (save-match-data
5650 ;; Diary entries sometimes have extra whitespace at the beginning
5651 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5652 (let* ((category (or category
5653 org-category
5654 (if buffer-file-name
5655 (file-name-sans-extension
5656 (file-name-nondirectory buffer-file-name))
5657 "")))
5658 (tag (or (nth (1- (length tags)) tags) ""))
5659 time ;; needed for the eval of the prefix format
5660 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5661 (time-of-day (and dotime (org-get-time-of-day ts)))
5662 stamp plain s0 s1 s2 rtn)
5663 (when (and dotime time-of-day org-prefix-has-time)
5664 ;; Extract starting and ending time and move them to prefix
5665 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5666 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5667 (setq s0 (match-string 0 ts)
5668 s1 (match-string (if plain 1 2) ts)
5669 s2 (match-string (if plain 8 4) ts))
5670
5671 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5672 ;; them, we might want to remove them there to avoid duplication.
5673 ;; The user can turn this off with a variable.
5674 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5675 (string-match (concat (regexp-quote s0) " *") txt)
5676 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5677 (= (match-beginning 0) 0)
5678 t))
5679 (setq txt (replace-match "" nil nil txt))))
5680 ;; Normalize the time(s) to 24 hour
5681 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5682 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5683
5684 ;; Create the final string
5685 (if noprefix
5686 (setq rtn txt)
5687 ;; Prepare the variables needed in the eval of the compiled format
5688 (setq time (cond (s2 (concat s1 "-" s2))
5689 (s1 (concat s1 "......"))
5690 (t ""))
5691 extra (or extra "")
5692 category (if (symbolp category) (symbol-name category) category))
5693 ;; Evaluate the compiled format
5694 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5695
5696 ;; And finally add the text properties
5697 (add-text-properties
5698 0 (length rtn) (list 'category (downcase category)
5699 'tags tags
5700 'prefix-length (- (length rtn) (length txt))
5701 'time-of-day time-of-day
5702 'dotime dotime)
5703 rtn)
5704 rtn)))
5705
5706 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5707 (catch 'exit
5708 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5709 ((and todayp (member 'today (car org-agenda-time-grid))))
5710 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5711 ((member 'weekly (car org-agenda-time-grid)))
5712 (t (throw 'exit list)))
5713 (let* ((have (delq nil (mapcar
5714 (lambda (x) (get-text-property 1 'time-of-day x))
5715 list)))
5716 (string (nth 1 org-agenda-time-grid))
5717 (gridtimes (nth 2 org-agenda-time-grid))
5718 (req (car org-agenda-time-grid))
5719 (remove (member 'remove-match req))
5720 new time)
5721 (if (and (member 'require-timed req) (not have))
5722 ;; don't show empty grid
5723 (throw 'exit list))
5724 (while (setq time (pop gridtimes))
5725 (unless (and remove (member time have))
5726 (setq time (int-to-string time))
5727 (push (org-format-agenda-item
5728 nil string "" nil ;; FIXME: put a category for the grid?
5729 (concat (substring time 0 -2) ":" (substring time -2)))
5730 new)
5731 (put-text-property
5732 1 (length (car new)) 'face 'org-time-grid (car new))))
5733 (if (member 'time-up org-agenda-sorting-strategy)
5734 (append new list)
5735 (append list new)))))
5736
5737 (defun org-compile-prefix-format (format)
5738 "Compile the prefix format into a Lisp form that can be evaluated.
5739 The resulting form is returned and stored in the variable
5740 `org-prefix-format-compiled'."
5741 (setq org-prefix-has-time nil)
5742 (let ((start 0) varform vars var (s format)e c f opt)
5743 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5744 s start)
5745 (setq var (cdr (assoc (match-string 4 s)
5746 '(("c" . category) ("t" . time) ("s" . extra)
5747 ("T" . tag))))
5748 c (or (match-string 3 s) "")
5749 opt (match-beginning 1)
5750 start (1+ (match-beginning 0)))
5751 (if (equal var 'time) (setq org-prefix-has-time t))
5752 (setq f (concat "%" (match-string 2 s) "s"))
5753 (if opt
5754 (setq varform
5755 `(if (equal "" ,var)
5756 ""
5757 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5758 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5759 (setq s (replace-match "%s" t nil s))
5760 (push varform vars))
5761 (setq vars (nreverse vars))
5762 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5763
5764 (defun org-get-time-of-day (s &optional string)
5765 "Check string S for a time of day.
5766 If found, return it as a military time number between 0 and 2400.
5767 If not found, return nil.
5768 The optional STRING argument forces conversion into a 5 character wide string
5769 HH:MM."
5770 (save-match-data
5771 (when
5772 (or
5773 (string-match
5774 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5775 (string-match
5776 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5777 (let* ((t0 (+ (* 100
5778 (+ (string-to-number (match-string 1 s))
5779 (if (and (match-beginning 4)
5780 (equal (downcase (match-string 4 s)) "pm"))
5781 12 0)))
5782 (if (match-beginning 3)
5783 (string-to-number (match-string 3 s))
5784 0)))
5785 (t1 (concat " "
5786 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
5787 (int-to-string t0))))
5788 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
5789
5790 (defun org-finalize-agenda-entries (list)
5791 "Sort and concatenate the agenda items."
5792 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
5793
5794 (defsubst org-cmp-priority (a b)
5795 "Compare the priorities of string a and b."
5796 (let ((pa (or (get-text-property 1 'priority a) 0))
5797 (pb (or (get-text-property 1 'priority b) 0)))
5798 (cond ((> pa pb) +1)
5799 ((< pa pb) -1)
5800 (t nil))))
5801
5802 (defsubst org-cmp-category (a b)
5803 "Compare the string values of categories of strings a and b."
5804 (let ((ca (or (get-text-property 1 'category a) ""))
5805 (cb (or (get-text-property 1 'category b) "")))
5806 (cond ((string-lessp ca cb) -1)
5807 ((string-lessp cb ca) +1)
5808 (t nil))))
5809
5810 (defsubst org-cmp-time (a b)
5811 "Compare the time-of-day values of strings a and b."
5812 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
5813 (ta (or (get-text-property 1 'time-of-day a) def))
5814 (tb (or (get-text-property 1 'time-of-day b) def)))
5815 (cond ((< ta tb) -1)
5816 ((< tb ta) +1)
5817 (t nil))))
5818
5819 (defvar time-up) (defvar time-down)
5820 (defvar priority-up) (defvar priority-down)
5821 (defvar category-up) (defvar category-down) (defvar category-keep)
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 ((first t)
12078 (level (funcall outline-level)))
12079 (while (and (not (eobp))
12080 (or first (> (funcall outline-level) level)))
12081 (setq first nil)
12082 (outline-next-heading))
12083 (if (memq (preceding-char) '(?\n ?\^M))
12084 (progn
12085 ;; Go to end of line before heading
12086 (forward-char -1)
12087 (if (memq (preceding-char) '(?\n ?\^M))
12088 ;; leave blank line before heading
12089 (forward-char -1))))))
12090
12091 (defun org-show-subtree ()
12092 "Show everything after this heading at deeper levels."
12093 (outline-flag-region
12094 (point)
12095 (save-excursion
12096 (outline-end-of-subtree) (outline-next-heading) (point))
12097 (if org-noutline-p nil ?\n)))
12098
12099 (defun org-show-entry ()
12100 "Show the body directly following this heading.
12101 Show the heading too, if it is currently invisible."
12102 (interactive)
12103 (save-excursion
12104 (org-back-to-heading t)
12105 (outline-flag-region
12106 (1- (point))
12107 (save-excursion
12108 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12109 (or (match-beginning 1) (point-max)))
12110 (if org-noutline-p nil ?\n))))
12111
12112
12113 (defun org-make-options-regexp (kwds)
12114 "Make a regular expression for keyword lines."
12115 (concat
12116 (if org-noutline-p "^" "[\n\r]")
12117 "#?[ \t]*\\+\\("
12118 (mapconcat 'regexp-quote kwds "\\|")
12119 "\\):[ \t]*"
12120 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12121
12122 ;; Make `bookmark-jump' show the jump location if it was hidden.
12123 (eval-after-load "bookmark"
12124 '(if (boundp 'bookmark-after-jump-hook)
12125 ;; We can use the hook
12126 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12127 ;; Hook not available, use advice
12128 (defadvice bookmark-jump (after org-make-visible activate)
12129 "Make the position visible."
12130 (org-bookmark-jump-unhide))))
12131
12132 (defun org-bookmark-jump-unhide ()
12133 "Unhide the current position, to show the bookmark location."
12134 (and (eq major-mode 'org-mode)
12135 (or (org-invisible-p)
12136 (save-excursion (goto-char (max (point-min) (1- (point))))
12137 (org-invisible-p)))
12138 (org-show-hierarchy-above)))
12139
12140 (defun org-get-tags-at (&optional pos)
12141 "Get a list of all headline targs applicable at POS.
12142 POS defaults to point. If tags are inherited, the list contains
12143 the targets in the same sequence as the headlines appear, i.e.
12144 the tags of the current headline come last."
12145 (interactive)
12146 (let (tags)
12147 (save-excursion
12148 (goto-char (or pos (point)))
12149 (save-match-data
12150 (org-back-to-heading t)
12151 (condition-case nil
12152 (while t
12153 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
12154 (setq tags (append (org-split-string (match-string 1) ":") tags)))
12155 (or org-use-tag-inheritance (error ""))
12156 (org-up-heading-all 1))
12157 (error nil))))
12158 (message "%s" tags)
12159 tags))
12160
12161 ;;; Finish up
12162
12163 (provide 'org)
12164
12165 (run-hooks 'org-load-hook)
12166
12167 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12168 ;;; org.el ends here
12169