]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-xemacs-p, org-export-html-show-new-buffer, org-table-may-need-update,
[gnu-emacs] / lisp / textmodes / org.el
1 ;;; org.el --- Outline-based notes management and organize
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 4.06
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.06
85 ;; - HTML exporter treats targeted internal links.
86 ;; - Bug fixes.
87 ;;
88 ;; Version 4.05
89 ;; - Changes to internal link system (thanks to David Wainberg for ideas).
90 ;; - in-file links: [[Search String]] instead of <file:::Search String>
91 ;; - automatic links to "radio targets".
92 ;; - CamelCase not longer active by default, configure org-activate-camels
93 ;; if you want to turn it back on.
94 ;; - After following a link, `C-c &' jumps back to it.
95 ;; - MH-E link support (thanks to Thomas Baumann).
96 ;; - Special table lines are no longer exported.
97 ;; - Bug fixes and minor improvements.
98 ;;
99 ;; Version 4.04
100 ;; - Cleanup tags display in agenda.
101 ;; - Bug fixes.
102 ;;
103 ;; Version 4.03
104 ;; - Table alignment fixed for use with wide characters.
105 ;; - `C-c -' leaves cursor in current table line.
106 ;; - The current TAG can be incorporated into the agenda prefix.
107 ;; See option `org-agenda-prefix-format' for details.
108 ;;
109 ;; Version 4.02
110 ;; - Minor bug fixes and improvements around tag searches.
111 ;; - XEmacs compatibility fixes.
112 ;;
113 ;; Version 4.01
114 ;; - Tags can also be set remotely from agenda buffer.
115 ;; - Boolean logic for tag searches.
116 ;; - Additional agenda commands can be configured through the variable
117 ;; `org-agenda-custom-commands'.
118 ;; - Minor bug fixes.
119 ;;
120 ;;; Code:
121
122 (eval-when-compile (require 'cl) (require 'calendar))
123 (require 'outline)
124 (require 'time-date)
125 (require 'easymenu)
126
127 (defvar calc-embedded-close-formula)
128 (defvar calc-embedded-open-formula)
129 (defvar font-lock-unfontify-region-function)
130
131 ;;; Customization variables
132
133 (defvar org-version "4.06"
134 "The version number of the file org.el.")
135 (defun org-version ()
136 (interactive)
137 (message "Org-mode version %s" org-version))
138
139 ;; The following two constants are for compatibility with different Emacs
140 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
141 ;; The compatibility code in org.el is based on these two constants.
142 (defconst org-xemacs-p (featurep 'xemacs)
143 "Are we running XEmacs?")
144 (defconst org-noutline-p (featurep 'noutline)
145 "Are we using the new outline mode?")
146
147 (defgroup org nil
148 "Outline-based notes management and organizer."
149 :tag "Org"
150 :group 'outlines
151 :group 'hypermedia
152 :group 'calendar)
153
154 (defgroup org-startup nil
155 "Options concerning startup of Org-mode."
156 :tag "Org Startup"
157 :group 'org)
158
159 (defcustom org-CUA-compatible nil
160 "Non-nil means use alternative key bindings for S-<cursor movement>.
161 Org-mode used S-<cursor movement> for changing timestamps and priorities.
162 S-<cursor movement> is also used for example by `CUA-mode' to select text.
163 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
164 alternative bindings. Setting this variable to t will replace the following
165 keys both in Org-mode and in the Org-agenda buffer.
166
167 S-RET -> C-S-RET
168 S-up -> M-p
169 S-down -> M-n
170 S-left -> M--
171 S-right -> M-+
172
173 If you do not like the alternative keys, take a look at the variable
174 `org-disputed-keys'.
175
176 This option is only relevant at load-time of Org-mode. Changing it requires
177 a restart of Emacs to become effective."
178 :group 'org-startup
179 :type 'boolean)
180
181 (defvar org-disputed-keys
182 '((S-up [(shift up)] [(meta ?p)])
183 (S-down [(shift down)] [(meta ?n)])
184 (S-left [(shift left)] [(meta ?-)])
185 (S-right [(shift right)] [(meta ?+)])
186 (S-return [(shift return)] [(control shift return)]))
187 "Keys for which Org-mode and other modes compete.
188 This is an alist, cars are symbols for lookup, 1st element is the default key,
189 second element will be used when `org-CUA-compatible' is t.")
190
191 (defun org-key (key)
192 "Select a key according to `org-CUA-compatible'."
193 (nth (if org-CUA-compatible 2 1)
194 (or (assq key org-disputed-keys)
195 (error "Invalid Key %s in `org-key'" key))))
196
197 (defcustom org-startup-folded t
198 "Non-nil means, entering Org-mode will switch to OVERVIEW.
199 This can also be configured on a per-file basis by adding one of
200 the following lines anywhere in the buffer:
201
202 #+STARTUP: fold
203 #+STARTUP: nofold
204 #+STARTUP: content"
205 :group 'org-startup
206 :type '(choice
207 (const :tag "nofold: show all" nil)
208 (const :tag "fold: overview" t)
209 (const :tag "content: all headlines" content)))
210
211 (defcustom org-startup-truncated t
212 "Non-nil means, entering Org-mode will set `truncate-lines'.
213 This is useful since some lines containing links can be very long and
214 uninteresting. Also tables look terrible when wrapped."
215 :group 'org-startup
216 :type 'boolean)
217
218 (defcustom org-startup-with-deadline-check nil
219 "Non-nil means, entering Org-mode will run the deadline check.
220 This means, if you start editing an org file, you will get an
221 immediate reminder of any due deadlines.
222 This can also be configured on a per-file basis by adding one of
223 the following lines anywhere in the buffer:
224
225 #+STARTUP: dlcheck
226 #+STARTUP: nodlcheck"
227 :group 'org-startup
228 :type 'boolean)
229
230 (defcustom org-insert-mode-line-in-empty-file nil
231 "Non-nil means insert the first line setting Org-mode in empty files.
232 When the function `org-mode' is called interactively in an empty file, this
233 normally means that the file name does not automatically trigger Org-mode.
234 To ensure that the file will always be in Org-mode in the future, a
235 line enforcing Org-mode will be inserted into the buffer, if this option
236 has been set."
237 :group 'org-startup
238 :type 'boolean)
239
240 (defgroup org-keywords nil
241 "Options concerning TODO items in Org-mode."
242 :tag "Org Keywords"
243 :group 'org)
244
245 (defcustom org-todo-keywords '("TODO" "DONE")
246 "List of TODO entry keywords.
247 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
248 considered to mean that the entry is \"done\". All the other mean that
249 action is required, and will make the entry show up in todo lists, diaries
250 etc.
251 The command \\[org-todo] cycles an entry through these states, and an
252 additional state where no keyword is present. For details about this
253 cycling, see also the variable `org-todo-interpretation'
254 Changes become only effective after restarting Emacs."
255 :group 'org-keywords
256 :type '(repeat (string :tag "Keyword")))
257
258 (defcustom org-todo-interpretation 'sequence
259 "Controls how TODO keywords are interpreted.
260 \\<org-mode-map>Possible values are `sequence' and `type'.
261 This variable is only relevant if `org-todo-keywords' contains more than two
262 states. There are two ways how these keywords can be used:
263
264 - As a sequence in the process of working on a TODO item, for example
265 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
266 org-todo-interpretation 'sequence)
267
268 - As different types of TODO items, for example
269 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
270 org-todo-interpretation 'type)
271
272 When the states are interpreted as a sequence, \\[org-todo] always cycles
273 to the next state, in order to walk through all different states. So with
274 \\[org-todo], you turn an empty entry into the state TODO. When you started
275 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
276 later to VERIFY and finally to DONE.
277
278 When the states are interpreted as types, \\[org-todo] still cycles through
279 when it is called several times in direct succession, in order to initially
280 select the type. However, if not called immediately after a previous
281 \\[org-todo], it switches from each type directly to DONE. So with the
282 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
283 RELAXED. If you later return to this entry and press \\[org-todo] again,
284 RELAXED will not be changed REMIND, but directly to DONE.
285
286 You can create a large number of types. To initially select a
287 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
288 type with completion. Of course, you can also type the keyword
289 directly into the buffer. M-TAB completes TODO keywords at the
290 beginning of a headline."
291 :group 'org-keywords
292 :type '(choice (const sequence)
293 (const type)))
294
295 (defcustom org-default-priority ?B
296 "The default priority of TODO items.
297 This is the priority an item get if no explicit priority is given."
298 :group 'org-keywords
299 :type 'character)
300
301 (defcustom org-lowest-priority ?C
302 "The lowest priority of TODO items. A character like ?A, ?B etc."
303 :group 'org-keywords
304 :type 'character)
305
306 (defcustom org-deadline-string "DEADLINE:"
307 "String to mark deadline entries.
308 A deadline is this string, followed by a time stamp. Should be a word,
309 terminated by a colon. You can insert a schedule keyword and
310 a timestamp with \\[org-deadline].
311 Changes become only effective after restarting Emacs."
312 :group 'org-keywords
313 :type 'string)
314
315 (defcustom org-scheduled-string "SCHEDULED:"
316 "String to mark scheduled TODO entries.
317 A schedule is this string, followed by a time stamp. Should be a word,
318 terminated by a colon. You can insert a schedule keyword and
319 a timestamp with \\[org-schedule].
320 Changes become only effective after restarting Emacs."
321 :group 'org-keywords
322 :type 'string)
323
324 (defcustom org-closed-string "CLOSED:"
325 "String used as the prefix for timestamps logging closing a TODO entry."
326 :group 'org-keywords
327 :type 'string)
328
329 (defcustom org-comment-string "COMMENT"
330 "Entries starting with this keyword will never be exported.
331 An entry can be toggled between COMMENT and normal with
332 \\[org-toggle-comment].
333 Changes become only effective after restarting Emacs."
334 :group 'org-keywords
335 :type 'string)
336
337 (defcustom org-quote-string "QUOTE"
338 "Entries starting with this keyword will be exported in fixed-width font.
339 Quoting applies only to the text in the entry following the headline, and does
340 not extend beyond the next headline, even if that is lower level.
341 An entry can be toggled between QUOTE and normal with
342 \\[org-toggle-fixed-width-section]."
343 :group 'org-keywords
344 :type 'string)
345
346 (defcustom org-after-todo-state-change-hook nil
347 "Hook which is run after the state of a TODO item was changed.
348 The new state (a string with a TODO keyword, or nil) is available in the
349 Lisp variable `state'."
350 :group 'org-keywords
351 :type 'hook)
352
353 ;; Variables for pre-computed regular expressions, all buffer local
354 (defvar org-todo-kwd-priority-p nil
355 "Do TODO items have priorities?")
356 (make-variable-buffer-local 'org-todo-kwd-priority-p)
357 (defvar org-todo-kwd-max-priority nil
358 "Maximum priority of TODO items.")
359 (make-variable-buffer-local 'org-todo-kwd-max-priority)
360 (defvar org-ds-keyword-length 12
361 "Maximum length of the Deadline and SCHEDULED keywords.")
362 (make-variable-buffer-local 'org-ds-keyword-length)
363 (defvar org-done-string nil
364 "The last string in `org-todo-keywords', indicating an item is DONE.")
365 (make-variable-buffer-local 'org-done-string)
366 (defvar org-todo-regexp nil
367 "Matches any of the TODO state keywords.")
368 (make-variable-buffer-local 'org-todo-regexp)
369 (defvar org-not-done-regexp nil
370 "Matches any of the TODO state keywords except the last one.")
371 (make-variable-buffer-local 'org-not-done-regexp)
372 (defvar org-todo-line-regexp nil
373 "Matches a headline and puts TODO state into group 2 if present.")
374 (make-variable-buffer-local 'org-todo-line-regexp)
375 (defvar org-nl-done-regexp nil
376 "Matches newline followed by a headline with the DONE keyword.")
377 (make-variable-buffer-local 'org-nl-done-regexp)
378 (defvar org-looking-at-done-regexp nil
379 "Matches the DONE keyword a point.")
380 (make-variable-buffer-local 'org-looking-at-done-regexp)
381 (defvar org-deadline-regexp nil
382 "Matches the DEADLINE keyword.")
383 (make-variable-buffer-local 'org-deadline-regexp)
384 (defvar org-deadline-time-regexp nil
385 "Matches the DEADLINE keyword together with a time stamp.")
386 (make-variable-buffer-local 'org-deadline-time-regexp)
387 (defvar org-deadline-line-regexp nil
388 "Matches the DEADLINE keyword and the rest of the line.")
389 (make-variable-buffer-local 'org-deadline-line-regexp)
390 (defvar org-scheduled-regexp nil
391 "Matches the SCHEDULED keyword.")
392 (make-variable-buffer-local 'org-scheduled-regexp)
393 (defvar org-scheduled-time-regexp nil
394 "Matches the SCHEDULED keyword together with a time stamp.")
395 (make-variable-buffer-local 'org-scheduled-time-regexp)
396
397 (defvar org-category nil
398 "Variable used by org files to set a category for agenda display.
399 Such files should use a file variable to set it, for example
400
401 -*- mode: org; org-category: \"ELisp\"
402
403 or contain a special line
404
405 #+CATEGORY: ELisp
406
407 If the file does not specify a category, then file's base name
408 is used instead.")
409 (make-variable-buffer-local 'org-category)
410
411 (defgroup org-time nil
412 "Options concerning time stamps and deadlines in Org-mode."
413 :tag "Org Time"
414 :group 'org)
415
416 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
417 "Formats for `format-time-string' which are used for time stamps.
418 It is not recommended to change this constant.")
419
420
421 (defcustom org-deadline-warning-days 30
422 "No. of days before expiration during which a deadline becomes active.
423 This variable governs the display in the org file."
424 :group 'org-time
425 :type 'number)
426
427 (defcustom org-popup-calendar-for-date-prompt t
428 "Non-nil means, pop up a calendar when prompting for a date.
429 In the calendar, the date can be selected with mouse-1. However, the
430 minibuffer will also be active, and you can simply enter the date as well.
431 When nil, only the minibuffer will be available."
432 :group 'org-time
433 :type 'number)
434
435 (defcustom org-calendar-follow-timestamp-change t
436 "Non-nil means, make the calendar window follow timestamp changes.
437 When a timestamp is modified and the calendar window is visible, it will be
438 moved to the new date."
439 :group 'org-time
440 :type 'boolean)
441
442 (defcustom org-log-done nil
443 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
444 When the state of an entry is changed from nothing to TODO, remove a previous
445 closing date."
446 :group 'org-time
447 :type 'boolean)
448
449 (defgroup org-agenda nil
450 "Options concerning agenda display Org-mode."
451 :tag "Org Agenda"
452 :group 'org)
453
454 (defcustom org-agenda-files nil
455 "A list of org files for agenda/diary display.
456 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
457 \\[org-remove-file]. You can also use customize to edit the list."
458 :group 'org-agenda
459 :type '(repeat file))
460
461 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
462 "Custom commands for the agenda.
463 These commands will be offered on the splash screen displayed by the
464 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
465
466 key The key (a single char as a string) to be associated with the command.
467 type The command type, any of the following symbols:
468 todo Entries with a specific TODO keyword, in all agenda files.
469 tags Tags match in all agenda files.
470 todo-tree Sparse tree of specific TODO keyword in *current* file.
471 tags-tree Sparse tree with all tags matches in *current* file.
472 occur-tree Occur sparse tree for current file.
473 match What to search for:
474 - a single keyword for TODO keyword searches
475 - a tags match expression for tags searches
476 - a regular expression for occur searches"
477 :group 'org-agenda
478 :type '(repeat
479 (list (string :tag "Key")
480 (choice :tag "Type"
481 (const :tag "Tags search in all agenda files" tags)
482 (const :tag "TODO keyword search in all agenda files" todo)
483 (const :tag "Tags sparse tree in current buffer" tags-tree)
484 (const :tag "TODO keyword tree in current buffer" todo-tree)
485 (const :tag "Occur tree in current buffer" occur-tree))
486 (string :tag "Match"))))
487
488 (defcustom org-select-timeline-window t
489 "Non-nil means, after creating a timeline, move cursor into Timeline window.
490 When nil, cursor will remain in the current window."
491 :group 'org-agenda
492 :type 'boolean)
493
494 (defcustom org-select-agenda-window t
495 "Non-nil means, after creating an agenda, move cursor into Agenda window.
496 When nil, cursor will remain in the current window."
497 :group 'org-agenda
498 :type 'boolean)
499
500 (defcustom org-fit-agenda-window t
501 "Non-nil means, change window size of agenda to fit content."
502 :group 'org-agenda
503 :type 'boolean)
504
505 (defcustom org-agenda-show-all-dates t
506 "Non-nil means, `org-agenda' shows every day in the selected range.
507 When nil, only the days which actually have entries are shown."
508 :group 'org-agenda
509 :type 'boolean)
510
511 ;; FIXME: First day of month works only for current month because it would
512 ;; require a variable ndays treatment.
513 (defcustom org-agenda-start-on-weekday 1
514 "Non-nil means, start the overview always on the specified weekday.
515 0 Denotes Sunday, 1 denotes Monday etc.
516 When nil, always start on the current day."
517 :group 'org-agenda
518 :type '(choice (const :tag "Today" nil)
519 (const :tag "First day of month" t)
520 (number :tag "Weekday No.")))
521
522 (defcustom org-agenda-ndays 7
523 "Number of days to include in overview display."
524 :group 'org-agenda
525 :type 'number)
526
527 (defcustom org-agenda-include-all-todo t
528 "Non-nil means, the agenda will always contain all TODO entries.
529 When nil, date-less entries will only be shown if `org-agenda' is called
530 with a prefix argument.
531 When non-nil, the TODO entries will be listed at the top of the agenda, before
532 the entries for specific days."
533 :group 'org-agenda
534 :type 'boolean)
535
536 (defcustom org-agenda-include-diary nil
537 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
538 :group 'org-agenda
539 :type 'boolean)
540
541 (defcustom org-calendar-to-agenda-key [?c]
542 "The key to be installed in `calendar-mode-map' for switching to the agenda.
543 The command `org-calendar-goto-agenda' will be bound to this key. The
544 default is the character `c' because then `c' can be used to switch back and
545 forth between agenda and calendar."
546 :group 'org-agenda
547 :type 'sexp)
548
549 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
550 "Sorting structure for the agenda items of a single day.
551 This is a list of symbols which will be used in sequence to determine
552 if an entry should be listed before another entry. The following
553 symbols are recognized:
554
555 time-up Put entries with time-of-day indications first, early first
556 time-down Put entries with time-of-day indications first, late first
557 category-keep Keep the default order of categories, corresponding to the
558 sequence in `org-agenda-files'.
559 category-up Sort alphabetically by category, A-Z.
560 category-down Sort alphabetically by category, Z-A.
561 priority-up Sort numerically by priority, high priority last.
562 priority-down Sort numerically by priority, high priority first.
563
564 The different possibilities will be tried in sequence, and testing stops
565 if one comparison returns a \"not-equal\". For example, the default
566 '(time-up category-keep priority-down)
567 means: Pull out all entries having a specified time of day and sort them,
568 in order to make a time schedule for the current day the first thing in the
569 agenda listing for the day. Of the entries without a time indication, keep
570 the grouped in categories, don't sort the categories, but keep them in
571 the sequence given in `org-agenda-files'. Within each category sort by
572 priority.
573
574 Leaving out `category-keep' would mean that items will be sorted across
575 categories by priority."
576 :group 'org-agenda
577 :type '(repeat
578 (choice
579 (const time-up)
580 (const time-down)
581 (const category-keep)
582 (const category-up)
583 (const category-down)
584 (const priority-up)
585 (const priority-down))))
586
587 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
588 "Format specification for the prefix of items in the agenda buffer.
589 This format works similar to a printf format, with the following meaning:
590
591 %c the category of the item, \"Diary\" for entries from the diary, or
592 as given by the CATEGORY keyword or derived from the file name.
593 %T the first tag of the item.
594 %t the time-of-day specification if one applies to the entry, in the
595 format HH:MM
596 %s Scheduling/Deadline information, a short string
597
598 All specifiers work basically like the standard `%s' of printf, but may
599 contain two additional characters: A question mark just after the `%' and
600 a whitespace/punctuation character just before the final letter.
601
602 If the first character after `%' is a question mark, the entire field
603 will only be included if the corresponding value applies to the
604 current entry. This is useful for fields which should have fixed
605 width when present, but zero width when absent. For example,
606 \"%?-12t\" will result in a 12 character time field if a time of the
607 day is specified, but will completely disappear in entries which do
608 not contain a time.
609
610 If there is punctuation or whitespace character just before the final
611 format letter, this character will be appended to the field value if
612 the value is not empty. For example, the format \"%-12:c\" leads to
613 \"Diary: \" if the category is \"Diary\". If the category were be
614 empty, no additional colon would be interted.
615
616 The default value of this option is \" %-12:c%?-12t% s\", meaning:
617 - Indent the line with two space characters
618 - Give the category in a 12 chars wide field, padded with whitespace on
619 the right (because of `-'). Append a colon if there is a category
620 (because of `:').
621 - If there is a time-of-day, put it into a 12 chars wide field. If no
622 time, don't put in an empty field, just skip it (because of '?').
623 - Finally, put the scheduling information and append a whitespace.
624
625 As another example, if you don't want the time-of-day of entries in
626 the prefix, you could use:
627
628 (setq org-agenda-prefix-format \" %-11:c% s\")
629
630 See also the variables `org-agenda-remove-times-when-in-prefix' and
631 `org-agenda-remove-tags-when-in-prefix'."
632 :type 'string
633 :group 'org-agenda)
634
635 (defcustom org-timeline-prefix-format " % s"
636 "Like `org-agenda-prefix-format', but for the timeline of a single file."
637 :type 'string
638 :group 'org-agenda)
639
640 (defvar org-prefix-format-compiled nil
641 "The compiled version of the most recently used prefix format.
642 Depending on which command was used last, this may be the compiled version
643 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
644
645 (defcustom org-agenda-use-time-grid t
646 "Non-nil means, show a time grid in the agenda schedule.
647 A time grid is a set of lines for specific times (like every two hours between
648 8:00 and 20:00). The items scheduled for a day at specific times are
649 sorted in between these lines.
650 For details about when the grid will be shown, and what it will look like, see
651 the variable `org-agenda-time-grid'."
652 :group 'org-agenda
653 :type 'boolean)
654
655 (defcustom org-agenda-time-grid
656 '((daily today require-timed)
657 "----------------"
658 (800 1000 1200 1400 1600 1800 2000))
659
660 "The settings for time grid for agenda display.
661 This is a list of three items. The first item is again a list. It contains
662 symbols specifying conditions when the grid should be displayed:
663
664 daily if the agenda shows a single day
665 weekly if the agenda shows an entire week
666 today show grid on current date, independent of daily/weekly display
667 require-timed show grid only if at least on item has a time specification
668
669 The second item is a string which will be places behing the grid time.
670
671 The third item is a list of integers, indicating the times that should have
672 a grid line."
673 :group 'org-agenda
674 :type
675 '(list
676 (set :greedy t :tag "Grid Display Options"
677 (const :tag "Show grid in single day agenda display" daily)
678 (const :tag "Show grid in weekly agenda display" weekly)
679 (const :tag "Always show grid for today" today)
680 (const :tag "Show grid only if any timed entries are present"
681 require-timed)
682 (const :tag "Skip grid times already present in an entry"
683 remove-match))
684 (string :tag "Grid String")
685 (repeat :tag "Grid Times" (integer :tag "Time"))))
686
687 (defcustom org-agenda-remove-times-when-in-prefix t
688 "Non-nil means, remove duplicate time specifications in agenda items.
689 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
690 time-of-day specification in a headline or diary entry is extracted and
691 placed into the prefix. If this option is non-nil, the original specification
692 \(a timestamp or -range, or just a plain time(range) specification like
693 11:30-4pm) will be removed for agenda display. This makes the agenda less
694 cluttered.
695 The option can be t or nil. It may also be the symbol `beg', indicating
696 that the time should only be removed what it is located at the beginning of
697 the headline/diary entry."
698 :group 'org-agenda
699 :type '(choice
700 (const :tag "Always" t)
701 (const :tag "Never" nil)
702 (const :tag "When at beginning of entry" beg)))
703
704 (defcustom org-sort-agenda-notime-is-late t
705 "Non-nil means, items without time are considered late.
706 This is only relevant for sorting. When t, items which have no explicit
707 time like 15:30 will be considered as 24:01, i.e. later than any items which
708 do have a time. When nil, the default time is before 0:00. You can use this
709 option to decide if the schedule for today should come before or after timeless
710 agenda entries."
711 :group 'org-agenda
712 :type 'boolean)
713
714 (defcustom org-agenda-remove-tags-when-in-prefix nil
715 "Non-nil means, the tags from copy of headline in agenda.
716 When this is the symbol `prefix', only remove tags when
717 `org-agenda-prefix-format' contains a `%T' specifier."
718 :group 'org-agenda
719 :type '(choice
720 (const :tag "Always" t)
721 (const :tag "Never" nil)
722 (const :tag "When prefix format contains %T" prefix)))
723
724 (defgroup org-structure nil
725 "Options concerning structure editing in Org-mode."
726 :tag "Org Structure"
727 :group 'org)
728
729 (defcustom org-cycle-include-plain-lists nil
730 "Non-nil means, include plain lists into visibility cycling.
731 This means that during cycling, plain list items will *temporarily* be
732 interpreted as outline headlines with a level given by 1000+i where i is the
733 indentation of the bullet. In all other operations, plain list items are
734 not seen as headlines. For example, you cannot assign a TODO keyword to
735 such an item."
736 :group 'org-structure
737 :type 'boolean)
738
739 (defcustom org-cycle-emulate-tab t
740 "Where should `org-cycle' emulate TAB.
741 nil Never
742 white Only in completely white lines
743 t Everywhere except in headlines"
744 :group 'org-structure
745 :type '(choice (const :tag "Never" nil)
746 (const :tag "Only in completely white lines" white)
747 (const :tag "Everywhere except in headlines" t)
748 ))
749
750 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
751 "Hook that is run after `org-cycle' has changed the buffer visibility.
752 The function(s) in this hook must accept a single argument which indicates
753 the new state that was set by the most recent `org-cycle' command. The
754 argument is a symbol. After a global state change, it can have the values
755 `overview', `content', or `all'. After a local state change, it can have
756 the values `folded', `children', or `subtree'."
757 :group 'org-structure
758 :type 'hook)
759
760 (defcustom org-highlight-sparse-tree-matches t
761 "Non-nil means, highlight all matches that define a sparse tree.
762 The highlights will automatically disappear the next time the buffer is
763 changed by an edit command."
764 :group 'org-structure
765 :type 'boolean)
766
767 (defcustom org-show-hierarchy-above t
768 "Non-nil means, show full hierarchy when showing a spot in the tree.
769 Turning this off makes sparse trees more compact, but also less clear."
770 :group 'org-structure
771 :type 'boolean)
772
773 (defcustom org-show-following-heading t
774 "Non-nil means, show heading following match in `org-occur'.
775 When doing an `org-occur' it is useful to show the headline which
776 follows the match, even if they do not match the regexp. This makes it
777 easier to edit directly inside the sparse tree. However, if you use
778 `org-occur' mainly as an overview, the following headlines are
779 unnecessary clutter."
780 :group 'org-structure
781 :type 'boolean)
782
783 (defcustom org-occur-hook '(org-first-headline-recenter)
784 "Hook that is run after `org-occur' has constructed a sparse tree.
785 This can be used to recenter the window to show as much of the structure
786 as possible."
787 :group 'org-structure
788 :type 'hook)
789
790 (defcustom org-level-color-stars-only nil
791 "Non-nil means fontify only the stars in each headline.
792 When nil, the entire headline is fontified.
793 Changing it requires restart of Emacs to become effective."
794 :group 'org-structure
795 :type 'boolean)
796
797 (defcustom org-adapt-indentation t
798 "Non-nil means, adapt indentation when promoting and demoting.
799 When this is set and the *entire* text in an entry is indented, the
800 indentation is increased by one space in a demotion command, and
801 decreased by one in a promotion command. If any line in the entry
802 body starts at column 0, indentation is not changed at all."
803 :group 'org-structure
804 :type 'boolean)
805
806 (defcustom org-plain-list-ordered-item-terminator t
807 "The character that makes a line with leading number an ordered list item.
808 Valid values are ?. and ?\). To get both terminators, use t. While
809 ?. may look nicer, it creates the danger that a line with leading
810 number may be incorrectly interpreted as an item. ?\) therefore is
811 the safe choice."
812 :group 'org-structure
813 :type '(choice (const :tag "dot like in \"2.\"" ?.)
814 (const :tag "paren like in \"2)\"" ?\))
815 (const :tab "both" t)))
816
817 (defcustom org-auto-renumber-ordered-lists t
818 "Non-nil means, automatically renumber ordered plain lists.
819 Renumbering happens when the sequence have been changed with
820 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
821 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
822 :group 'org-structure
823 :type 'boolean)
824
825 (defcustom org-enable-fixed-width-editor t
826 "Non-nil means, lines starting with \":\" are treated as fixed-width.
827 This currently only means, they are never auto-wrapped.
828 When nil, such lines will be treated like ordinary lines.
829 See also the QUOTE keyword."
830 :group 'org-structure
831 :type 'boolean)
832
833 (defcustom org-archive-location "%s_archive::"
834 "The location where subtrees should be archived.
835 This string consists of two parts, separated by a double-colon.
836
837 The first part is a file name - when omitted, archiving happens in the same
838 file. %s will be replaced by the current file name (without directory part).
839 Archiving to a different file is useful to keep archived entries from
840 contributing to the Org-mode Agenda.
841
842 The part after the double colon is a headline. The archived entries will be
843 filed under that headline. When omitted, the subtrees are simply filed away
844 at the end of the file, as top-level entries.
845
846 Here are a few examples:
847 \"%s_archive::\"
848 If the current file is Projects.org, archive in file
849 Projects.org_archive, as top-level trees. This is the default.
850
851 \"::* Archived Tasks\"
852 Archive in the current file, under the top-level headline
853 \"* Archived Tasks\".
854
855 \"~/org/archive.org::\"
856 Archive in file ~/org/archive.org (absolute path), as top-level trees.
857
858 \"basement::** Finished Tasks\"
859 Archive in file ./basement (relative path), as level 3 trees
860 below the level 2 heading \"** Finished Tasks\".
861
862 You may set this option on a per-file basis by adding to the buffer a
863 line like
864
865 #+ARCHIVE: basement::** Finished Tasks"
866 :group 'org-structure
867 :type 'string)
868
869 (defcustom org-archive-mark-done t
870 "Non-nil means, mark archived entries as DONE."
871 :group 'org-structure
872 :type 'boolean)
873
874 (defcustom org-archive-stamp-time t
875 "Non-nil means, add a time stamp to archived entries.
876 The time stamp will be added directly after the TODO state keyword in the
877 first line, so it is probably best to use this in combinations with
878 `org-archive-mark-done'."
879 :group 'org-structure
880 :type 'boolean)
881
882 (defgroup org-tags nil
883 "Options concerning startup of Org-mode."
884 :tag "Org Tags"
885 :group 'org)
886
887 (defcustom org-tags-column 48
888 "The column to which tags should be indented in a headline.
889 If this number is positive, it specifies the column. If it is negative,
890 it means that the tags should be flushright to that column. For example,
891 -79 works well for a normal 80 character screen."
892 :group 'org-tags
893 :type 'integer)
894
895 (defcustom org-auto-align-tags t
896 "Non-nil means, realign tags after pro/demotion of TODO state change.
897 These operations change the length of a headline and therefore shift
898 the tags around. With this options turned on, after each such operation
899 the tags are again aligned to `org-tags-column'."
900 :group 'org-tags
901 :type 'boolean)
902
903 (defcustom org-use-tag-inheritance t
904 "Non-nil means, tags in levels apply also for sublevels.
905 When nil, only the tags directly given in a specific line apply there.
906 If you turn off this option, you very likely want to turn on the
907 companion option `org-tags-match-list-sublevels'."
908 :group 'org-tags
909 :type 'boolean)
910
911 (defcustom org-tags-match-list-sublevels nil
912 "Non-nil means list also sublevels of headlines matching tag search.
913 Because of tag inheritance (see variable `org-use-tag-inheritance'),
914 the sublevels of a headline matching a tag search often also match
915 the same search. Listing all of them can create very long lists.
916 Setting this variable to nil causes subtrees to be skipped.
917 This option is off by default, because inheritance in on. If you turn
918 inheritance off, you very likely want to turn this option on.
919
920 As a special case, if the tag search is restricted to TODO items, the
921 value of this variable is ignored and sublevels are always checked, to
922 make sure all corresponding TODO items find their way into the list."
923 :group 'org-tags
924 :type 'boolean)
925
926 (defvar org-tags-history nil
927 "History of minibuffer reads for tags.")
928 (defvar org-last-tags-completion-table nil
929 "The last used completion table for tags.")
930
931 (defgroup org-link nil
932 "Options concerning links in Org-mode."
933 :tag "Org Link"
934 :group 'org)
935
936 (defcustom org-tab-follows-link nil
937 "Non-nil means, on links TAB will follow the link.
938 Needs to be set before org.el is loaded."
939 :group 'org-link
940 :type 'boolean)
941
942 (defcustom org-return-follows-link nil
943 "Non-nil means, on links RET will follow the link.
944 Needs to be set before org.el is loaded."
945 :group 'org-link
946 :type 'boolean)
947
948 (defcustom org-mark-ring-length 4
949 "Number of different positions to be recorded in the ring
950 Changing this requires a restart of Emacs to work correctly."
951 :group 'org-link
952 :type 'interger)
953
954 (defcustom org-link-format "<%s>"
955 "Default format for linkes in the buffer.
956 This is a format string for printf, %s will be replaced by the link text.
957 If you want to make sure that your link is always properly terminated,
958 include angle brackets into this format, like \"<%s>\". Some people also
959 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
960 :group 'org-link
961 :type '(choice
962 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
963 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
964 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
965 (string :tag "Other" :value "<%s>")))
966
967 (defcustom org-allow-space-in-links t
968 "Non-nil means, file names in links may contain space characters.
969 When nil, it becomes possible to put several links into a line.
970 Note that in tables, a link never extends accross fields, so in a table
971 it is always possible to put several links into a line.
972 Changing this variable requires a restart of Emacs of become effective."
973 :group 'org-link
974 :type 'boolean)
975
976 (defcustom org-radio-targets t
977 "Non-nil means activate text matching a link target.
978 Radio targets are strings in triple angular brackets, like <<<My Target>>>.
979 When this option is set, any occurrence of \"my target\" in normal text
980 becomes a link."
981 :group 'org-link
982 :type 'boolean)
983
984 (defcustom org-activate-camels nil
985 "Non-nil means, treat words in CamelCase as in-file links.
986 Changing this requires restart of Emacs to become effective."
987 :group 'org-link
988 :type 'boolean)
989
990 (defcustom org-context-in-file-links t
991 "Non-nil means, file links from `org-store-link' contain context.
992 A search string will be added to the file name with :: as separator and
993 used to find the context when the link is activated by the command
994 `org-open-at-point'.
995 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
996 negates this setting for the duration of the command."
997 :group 'org-link
998 :type 'boolean)
999
1000 (defcustom org-file-link-context-use-camel-case nil
1001 "Non-nil means, use CamelCase to store a search context in a file link.
1002 When nil, the search string simply consists of the words of the string."
1003 :group 'org-link
1004 :type 'boolean)
1005
1006 (defcustom org-keep-stored-link-after-insertion nil
1007 "Non-nil means, keep link in list for entire session.
1008
1009 The command `org-store-link' adds a link pointing to the current
1010 location to an internal list. These links accumulate during a session.
1011 The command `org-insert-link' can be used to insert links into any
1012 Org-mode file (offering completion for all stored links). When this
1013 option is nil, every link which has been inserted once using \\[org-insert-link]
1014 will be removed from the list, to make completing the unused links
1015 more efficient."
1016 :group 'org-link
1017 :type 'boolean)
1018
1019 (defcustom org-link-frame-setup
1020 '((vm . vm-visit-folder-other-frame)
1021 (gnus . gnus-other-frame)
1022 (file . find-file-other-window))
1023 "Setup the frame configuration for following links.
1024 When following a link with Emacs, it may often be useful to display
1025 this link in another window or frame. This variable can be used to
1026 set this up for the different types of links.
1027 For VM, use any of
1028 `vm-visit-folder'
1029 `vm-visit-folder-other-frame'
1030 For Gnus, use any of
1031 `gnus'
1032 `gnus-other-frame'
1033 For FILE, use any of
1034 `find-file'
1035 `find-file-other-window'
1036 `find-file-other-frame'
1037 For the calendar, use the variable `calendar-setup'.
1038 For BBDB, it is currently only possible to display the matches in
1039 another window."
1040 :group 'org-link
1041 :type '(list
1042 (cons (const vm)
1043 (choice
1044 (const vm-visit-folder)
1045 (const vm-visit-folder-other-window)
1046 (const vm-visit-folder-other-frame)))
1047 (cons (const gnus)
1048 (choice
1049 (const gnus)
1050 (const gnus-other-frame)))
1051 (cons (const file)
1052 (choice
1053 (const find-file)
1054 (const find-file-other-window)
1055 (const find-file-other-frame)))))
1056
1057 (defcustom org-usenet-links-prefer-google nil
1058 "Non-nil means, `org-store-link' will create web links to Google groups.
1059 When nil, Gnus will be used for such links.
1060 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1061 negates this setting for the duration of the command."
1062 :group 'org-link
1063 :type 'boolean)
1064
1065 (defcustom org-open-non-existing-files nil
1066 "Non-nil means, `org-open-file' will open non-existing file.
1067 When nil, an error will be generated."
1068 :group 'org-link
1069 :type 'boolean)
1070
1071 (defcustom org-confirm-shell-links t
1072 "Non-nil means, ask for confirmation before executing shell links.
1073 The default is true, to keep new users from shooting into their own foot."
1074 :group 'org-link
1075 :type 'boolean)
1076
1077 (defconst org-file-apps-defaults-gnu
1078 '((t . mailcap))
1079 "Default file applications on a UNIX or GNU/Linux system.
1080 See `org-file-apps'.")
1081
1082 (defconst org-file-apps-defaults-macosx
1083 '((t . "open %s")
1084 ("ps" . "gv %s")
1085 ("ps.gz" . "gv %s")
1086 ("eps" . "gv %s")
1087 ("eps.gz" . "gv %s")
1088 ("dvi" . "xdvi %s")
1089 ("fig" . "xfig %s"))
1090 "Default file applications on a MacOS X system.
1091 The system \"open\" is known as a default, but we use X11 applications
1092 for some files for which the OS does not have a good default.
1093 See `org-file-apps'.")
1094
1095 (defconst org-file-apps-defaults-windowsnt
1096 '((t . (w32-shell-execute "open" file)))
1097 "Default file applications on a Windows NT system.
1098 The system \"open\" is used for most files.
1099 See `org-file-apps'.")
1100
1101 (defcustom org-file-apps
1102 '(
1103 ("txt" . emacs)
1104 ("tex" . emacs)
1105 ("ltx" . emacs)
1106 ("org" . emacs)
1107 ("el" . emacs)
1108 )
1109 "External applications for opening `file:path' items in a document.
1110 Org-mode uses system defaults for different file types, but
1111 you can use this variable to set the application for a given file
1112 extension. The entries in this list are cons cells with a file extension
1113 and the corresponding command. Possible values for the command are:
1114 `emacs' The file will be visited by the current Emacs process.
1115 `default' Use the default application for this file type.
1116 string A command to be executed by a shell; %s will be replaced
1117 by the path to the file.
1118 sexp A Lisp form which will be evaluated. The file path will
1119 be available in the Lisp variable `file'.
1120 For more examples, see the system specific constants
1121 `org-file-apps-defaults-macosx'
1122 `org-file-apps-defaults-windowsnt'
1123 `org-file-apps-defaults-gnu'."
1124 :group 'org-link
1125 :type '(repeat
1126 (cons (choice :value ""
1127 (string :tag "Extension")
1128 (const :tag "Default for unrecognized files" t)
1129 (const :tag "Links to a directory" directory))
1130 (choice :value ""
1131 (const :tag "Visit with Emacs" emacs)
1132 (const :tag "Use system default" default)
1133 (string :tag "Command")
1134 (sexp :tag "Lisp form")))))
1135
1136 (defgroup org-remember nil
1137 "Options concerning interaction with remember.el."
1138 :tag "Org Remember"
1139 :group 'org)
1140
1141 (defcustom org-directory "~/org"
1142 "Directory with org files.
1143 This directory will be used as default to prompt for org files.
1144 Used by the hooks for remember.el."
1145 :group 'org-remember
1146 :type 'directory)
1147
1148 (defcustom org-default-notes-file "~/.notes"
1149 "Default target for storing notes.
1150 Used by the hooks for remember.el. This can be a string, or nil to mean
1151 the value of `remember-data-file'."
1152 :group 'org-remember
1153 :type '(choice
1154 (const :tag "Default from remember-data-file" nil)
1155 file))
1156
1157 (defcustom org-reverse-note-order nil
1158 "Non-nil means, store new notes at the beginning of a file or entry.
1159 When nil, new notes will be filed to the end of a file or entry."
1160 :group 'org-remember
1161 :type '(choice
1162 (const :tag "Reverse always" t)
1163 (const :tag "Reverse never" nil)
1164 (repeat :tag "By file name regexp"
1165 (cons regexp boolean))))
1166
1167 (defgroup org-table nil
1168 "Options concerning tables in Org-mode."
1169 :tag "Org Table"
1170 :group 'org)
1171
1172 (defcustom org-enable-table-editor 'optimized
1173 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1174 When nil, such lines will be treated like ordinary lines.
1175
1176 When equal to the symbol `optimized', the table editor will be optimized to
1177 do the following:
1178 - Use automatic overwrite mode in front of whitespace in table fields.
1179 This make the structure of the table stay in tact as long as the edited
1180 field does not exceed the column width.
1181 - Minimize the number of realigns. Normally, the table is aligned each time
1182 TAB or RET are pressed to move to another field. With optimization this
1183 happens only if changes to a field might have changed the column width.
1184 Optimization requires replacing the functions `self-insert-command',
1185 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1186 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1187 very good at guessing when a re-align will be necessary, but you can always
1188 force one with \\[org-ctrl-c-ctrl-c].
1189
1190 If you would like to use the optimized version in Org-mode, but the
1191 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1192
1193 This variable can be used to turn on and off the table editor during a session,
1194 but in order to toggle optimization, a restart is required.
1195
1196 See also the variable `org-table-auto-blank-field'."
1197 :group 'org-table
1198 :type '(choice
1199 (const :tag "off" nil)
1200 (const :tag "on" t)
1201 (const :tag "on, optimized" optimized)))
1202
1203 ;; FIXME: We could have a third option which makes it jump only over the first
1204 ;; hline in a table.
1205 (defcustom org-table-tab-jumps-over-hlines t
1206 "Non-nil means, tab in the last column of a table with jump over a hline.
1207 If a horizontal separator line is following the current line,
1208 `org-table-next-field' can either create a new row before that line, or jump
1209 over the line. When this option is nil, a new line will be created before
1210 this line."
1211 :group 'org-table
1212 :type 'boolean)
1213
1214 (defcustom org-table-auto-blank-field t
1215 "Non-nil means, automatically blank table field when starting to type into it.
1216 This only happens when typing immediately after a field motion
1217 command (TAB, S-TAB or RET).
1218 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1219 :group 'org-table
1220 :type 'boolean)
1221
1222 (defcustom org-table-default-size "5x2"
1223 "The default size for newly created tables, Columns x Rows."
1224 :group 'org-table
1225 :type 'string)
1226
1227 (defcustom org-table-automatic-realign t
1228 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1229 When nil, aligning is only done with \\[org-table-align], or after column
1230 removal/insertion."
1231 :group 'org-table
1232 :type 'boolean)
1233
1234 (defcustom org-table-spaces-around-separators '(1 . 1)
1235 "The number of spaces to be placed before and after separators."
1236 :group 'org-table
1237 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1238
1239 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1240 "The number of spaces to be placed before and after separators.
1241 This option applies when the column separators have been made invisible."
1242 :group 'org-table
1243 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1244
1245 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1246 "Regular expression for recognizing numbers in table columns.
1247 If a table column contains mostly numbers, it will be aligned to the
1248 right. If not, it will be aligned to the left.
1249
1250 The default value of this option is a regular expression which allows
1251 anything which looks remotely like a number as used in scientific
1252 context. For example, all of the following will be considered a
1253 number:
1254 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1255
1256 Other options offered by the customize interface are more restrictive."
1257 :group 'org-table
1258 :type '(choice
1259 (const :tag "Positive Integers"
1260 "^[0-9]+$")
1261 (const :tag "Integers"
1262 "^[-+]?[0-9]+$")
1263 (const :tag "Floating Point Numbers"
1264 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1265 (const :tag "Floating Point Number or Integer"
1266 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1267 (const :tag "Exponential, Floating point, Integer"
1268 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1269 (const :tag "Very General Number-Like"
1270 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1271 (string :tag "Regexp:")))
1272
1273 (defcustom org-table-number-fraction 0.5
1274 "Fraction of numbers in a column required to make the column align right.
1275 In a column all non-white fields are considered. If at least this
1276 fraction of fields is matched by `org-table-number-fraction',
1277 alignment to the right border applies."
1278 :group 'org-table
1279 :type 'number)
1280
1281 (defcustom org-export-highlight-first-table-line t
1282 "Non-nil means, highlight the first table line.
1283 In HTML export, this means use <th> instead of <td>.
1284 In tables created with table.el, this applies to the first table line.
1285 In Org-mode tables, all lines before the first horizontal separator
1286 line will be formatted with <th> tags."
1287 :group 'org-table
1288 :type 'boolean)
1289
1290 (defcustom org-table-tab-recognizes-table.el t
1291 "Non-nil means, TAB will automatically notice a table.el table.
1292 When it sees such a table, it moves point into it and - if necessary -
1293 calls `table-recognize-table'."
1294 :group 'org-table
1295 :type 'boolean)
1296
1297 (defgroup org-table-calculation nil
1298 "Options concerning tables in Org-mode."
1299 :tag "Org Table Calculation"
1300 :group 'org)
1301
1302 (defcustom org-table-copy-increment t
1303 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1304 :group 'org-table-calculation
1305 :type 'boolean)
1306
1307 (defcustom org-calc-default-modes
1308 '(calc-internal-prec 12
1309 calc-float-format (float 5)
1310 calc-angle-mode deg
1311 calc-prefer-frac nil
1312 calc-symbolic-mode nil
1313 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1314 calc-display-working-message t
1315 )
1316 "List with Calc mode settings for use in calc-eval for table formulas.
1317 The list must contain alternating symbols (Calc modes variables and values).
1318 Don't remove any of the default settings, just change the values. Org-mode
1319 relies on the variables to be present in the list."
1320 :group 'org-table-calculation
1321 :type 'plist)
1322
1323 (defcustom org-table-formula-evaluate-inline t
1324 "Non-nil means, TAB and RET evaluate a formula in current table field.
1325 If the current field starts with an equal sign, it is assumed to be a formula
1326 which should be evaluated as described in the manual and in the documentation
1327 string of the command `org-table-eval-formula'. This feature requires the
1328 Emacs calc package.
1329 When this variable is nil, formula calculation is only available through
1330 the command \\[org-table-eval-formula]."
1331 :group 'org-table-calculation
1332 :type 'boolean)
1333
1334
1335 (defcustom org-table-formula-use-constants t
1336 "Non-nil means, interpret constants in formulas in tables.
1337 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1338 by the value given in `org-table-formula-constants', or by a value obtained
1339 from the `constants.el' package."
1340 :group 'org-table-calculation
1341 :type 'boolean)
1342
1343 (defcustom org-table-formula-constants nil
1344 "Alist with constant names and values, for use in table formulas.
1345 The car of each element is a name of a constant, without the `$' before it.
1346 The cdr is the value as a string. For example, if you'd like to use the
1347 speed of light in a formula, you would configure
1348
1349 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1350
1351 and then use it in an equation like `$1*$c'."
1352 :group 'org-table-calculation
1353 :type '(repeat
1354 (cons (string :tag "name")
1355 (string :tag "value"))))
1356
1357 (defcustom org-table-formula-numbers-only nil
1358 "Non-nil means, calculate only with numbers in table formulas.
1359 Then all input fields will be converted to a number, and the result
1360 must also be a number. When nil, calc's full potential is available
1361 in table calculations, including symbolics etc."
1362 :group 'org-table-calculation
1363 :type 'boolean)
1364
1365 (defcustom org-table-allow-automatic-line-recalculation t
1366 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1367 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1368 :group 'org-table-calculation
1369 :type 'boolean)
1370
1371 (defgroup org-export nil
1372 "Options for exporting org-listings."
1373 :tag "Org Export"
1374 :group 'org)
1375
1376 (defcustom org-export-language-setup
1377 '(("en" "Author" "Date" "Table of Contents")
1378 ("da" "Ophavsmand" "Dato" "Indhold")
1379 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1380 ("es" "Autor" "Fecha" "\xccndice")
1381 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1382 ("it" "Autore" "Data" "Indice")
1383 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1384 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1385 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1386 "Terms used in export text, translated to different languages.
1387 Use the variable `org-export-default-language' to set the language,
1388 or use the +OPTION lines for a per-file setting."
1389 :group 'org-export
1390 :type '(repeat
1391 (list
1392 (string :tag "HTML language tag")
1393 (string :tag "Author")
1394 (string :tag "Date")
1395 (string :tag "Table of Contents"))))
1396
1397 (defcustom org-export-default-language "en"
1398 "The default language of HTML export, as a string.
1399 This should have an association in `org-export-language-setup'."
1400 :group 'org-export
1401 :type 'string)
1402
1403 (defcustom org-export-html-style
1404 "<style type=\"text/css\">
1405 html {
1406 font-family: Times, serif;
1407 font-size: 12pt;
1408 }
1409 .title { text-align: center; }
1410 .todo, .deadline { color: red; }
1411 .done { color: green; }
1412 pre {
1413 border: 1pt solid #AEBDCC;
1414 background-color: #F3F5F7;
1415 padding: 5pt;
1416 font-family: courier, monospace;
1417 }
1418 table { border-collapse: collapse; }
1419 td, th {
1420 vertical-align: top;
1421 border: 1pt solid #ADB9CC;
1422 }
1423 </style>"
1424 "The default style specification for exported HTML files.
1425 Since there are different ways of setting style information, this variable
1426 needs to contain the full HTML structure to provide a style, including the
1427 surrounding HTML tags. The style specifications should include definitions
1428 for new classes todo, done, title, and deadline. For example, legal values
1429 would be:
1430
1431 <style type=\"text/css\">
1432 p { font-weight: normal; color: gray; }
1433 h1 { color: black; }
1434 .title { text-align: center; }
1435 .todo, .deadline { color: red; }
1436 .done { color: green; }
1437 </style>
1438
1439 or, if you want to keep the style in a file,
1440
1441 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1442
1443 As the value of this option simply gets inserted into the HTML <head> header,
1444 you can \"misuse\" it to add arbitrary text to the header."
1445 :group 'org-export
1446 :type 'string)
1447
1448 (defcustom org-export-headline-levels 3
1449 "The last level which is still exported as a headline.
1450 Inferior levels will produce itemize lists when exported.
1451 Note that a numeric prefix argument to an exporter function overrides
1452 this setting.
1453
1454 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1455 :group 'org-export
1456 :type 'number)
1457
1458 (defcustom org-export-with-section-numbers t
1459 "Non-nil means, add section numbers to headlines when exporting.
1460
1461 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1462 :group 'org-export
1463 :type 'boolean)
1464
1465 (defcustom org-export-with-toc t
1466 "Non-nil means, create a table of contents in exported files.
1467 The TOC contains headlines with levels up to`org-export-headline-levels'.
1468
1469 Headlines which contain any TODO items will be marked with \"(*)\" in
1470 ASCII export, and with red color in HTML output.
1471
1472 In HTML output, the TOC will be clickable.
1473
1474 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1475 :group 'org-export
1476 :type 'boolean)
1477
1478 (defcustom org-export-plain-list-max-depth 20
1479 "Maximum depth of hand-formatted lists in HTML export.
1480
1481 Org-mode parses hand-formatted enumeration and bullet lists and
1482 transforms them to HTML open export. Different indentation of the
1483 bullet or number indicates different list nesting levels. To avoid
1484 confusion, only a single level is allowed by default. When this is
1485 larger than 1, deeper indentation leads to deeper list nesting. For
1486 example, the default value of 3 allows the following list to be
1487 formatted correctly in HTML:
1488
1489 * Fruit
1490 - Apple
1491 - Banana
1492 1. from Africa
1493 2. from South America
1494 - Pineapple
1495 * Bread
1496 * Dairy products"
1497 :group 'org-export
1498 :type 'integer)
1499
1500 (defcustom org-export-preserve-breaks nil
1501 "Non-nil means, preserve all line breaks when exporting.
1502 Normally, in HTML output paragraphs will be reformatted. In ASCII
1503 export, line breaks will always be preserved, regardless of this variable.
1504
1505 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1506 :group 'org-export
1507 :type 'boolean)
1508
1509 (defcustom org-export-html-inline-images t
1510 "Non-nil means, inline images into exported HTML pages.
1511 The link will still be to the original location of the image file.
1512 So if you are moving the page, lets say to your public HTML site,
1513 you will have to move the image and maybe change the link."
1514 :group 'org-export
1515 :type 'boolean)
1516
1517 (defcustom org-export-html-expand t
1518 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1519 When nil, these tags will be exported as plain text and therefore
1520 not be interpreted by a browser.
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-export-with-fixed-width t
1527 "Non-nil means, lines starting with \":\" will be in fixed width font.
1528 This can be used to have pre-formatted text, fragments of code etc. For
1529 example:
1530 : ;; Some Lisp examples
1531 : (while (defc cnt)
1532 : (ding))
1533 will be looking just like this in also HTML. In ASCII export, this option
1534 has no effect.
1535
1536 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1537 :group 'org-export
1538 :type 'boolean)
1539
1540 (defcustom org-export-with-tables t
1541 "If non-nil, lines starting with \"|\" define a table.
1542 For example:
1543
1544 | Name | Address | Birthday |
1545 |-------------+----------+-----------|
1546 | Arthur Dent | England | 29.2.2100 |
1547
1548 In ASCII export, this option has no effect.
1549
1550 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1551 :group 'org-export
1552 :type 'boolean)
1553
1554 (defcustom org-export-table-remove-special-lines t
1555 "Remove special lines and marking characters in calculating tables.
1556 This removes the special marking character column from tables that are set
1557 up for spreadsheet calculations. It also removes the entire lines
1558 marked with `!', `_', or `^'. The lines with `$' are kept, because
1559 the values of constants may be useful to have."
1560 :group 'org-export
1561 :type 'boolean)
1562
1563 (defcustom org-export-prefer-native-exporter-for-tables nil
1564 "Non-nil means, always export tables created with table.el natively.
1565 Natively means, use the HTML code generator in table.el.
1566 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1567 the table does not use row- or column-spanning). This has the
1568 advantage, that the automatic HTML conversions for math symbols and
1569 sub/superscripts can be applied. Org-mode's HTML generator is also
1570 much faster."
1571 :group 'org-export
1572 :type 'boolean)
1573
1574 (defcustom org-export-html-table-tag
1575 "<table border=1 cellspacing=0 cellpadding=6>"
1576 "The HTML tag used to start a table.
1577 This must be a <table> tag, but you may change the options like
1578 borders and spacing."
1579 :group 'org-export
1580 :type 'string)
1581
1582 (defcustom org-export-with-emphasize t
1583 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1584 If the export target supports emphasizing text, the word will be
1585 typeset in bold, italic, or underlined, respectively. Works only for
1586 single words, but you can say: I *really* *mean* *this*.
1587 In ASCII export, this option has no effect.
1588
1589 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1590 :group 'org-export
1591 :type 'boolean)
1592
1593 (defcustom org-match-sexp-depth 3
1594 "Number of stacked braces for sub/superscript matching.
1595 This has to be set before loading org.el to be effective."
1596 :group 'org-export
1597 :type 'integer)
1598
1599 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1600 (defcustom org-export-with-sub-superscripts t
1601 "Non-nil means, interpret \"_\" and \"^\" for export.
1602 When this option is turned on, you can use TeX-like syntax for sub- and
1603 superscripts. Several characters after \"_\" or \"^\" will be
1604 considered as a single item - so grouping with {} is normally not
1605 needed. For example, the following things will be parsed as single
1606 sub- or superscripts.
1607
1608 10^24 or 10^tau several digits will be considered 1 item.
1609 10^-12 or 10^-tau a leading sign with digits or a word
1610 x^2-y^3 will be read as x^2 - y^3, because items are
1611 terminated by almost any nonword/nondigit char.
1612 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1613
1614 Still, ambiguity is possible - so when in doubt use {} to enclose the
1615 sub/superscript.
1616 In ASCII export, this option has no effect.
1617
1618 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1619 :group 'org-export
1620 :type 'boolean)
1621
1622 (defcustom org-export-with-TeX-macros t
1623 "Non-nil means, interpret simple TeX-like macros when exporting.
1624 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1625 No only real TeX macros will work here, but the standard HTML entities
1626 for math can be used as macro names as well. For a list of supported
1627 names in HTML export, see the constant `org-html-entities'.
1628 In ASCII export, this option has no effect.
1629
1630 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1631 :group 'org-export
1632 :type 'boolean)
1633
1634 (defcustom org-export-html-with-timestamp nil
1635 "If non-nil, write `org-export-html-html-helper-timestamp'
1636 into the exported html text. Otherwise, the buffer will just be saved
1637 to a file."
1638 :group 'org-export
1639 :type 'boolean)
1640
1641 (defcustom org-export-html-html-helper-timestamp
1642 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1643 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1644 :group 'org-export
1645 :type 'string)
1646
1647 (defcustom org-export-ascii-show-new-buffer t
1648 "Non-nil means, popup buffer containing the exported ASCII text.
1649 Otherwise the buffer will just be saved to a file and stay hidden."
1650 :group 'org-export
1651 :type 'boolean)
1652
1653 (defcustom org-export-html-show-new-buffer nil
1654 "Non-nil means, popup buffer containing the exported HTML text.
1655 Otherwise, the buffer will just be saved to a file and stay hidden."
1656 :group 'org-export
1657 :type 'boolean)
1658
1659 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1660 "The file name for the iCalendar file covering all agenda files.
1661 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1662 :group 'org-export
1663 :type 'file)
1664
1665 (defcustom org-icalendar-include-todo nil
1666 "Non-nil means, export to iCalendar files should also cover TODO items."
1667 :group 'org-export
1668 :type 'boolean)
1669
1670 (defcustom org-icalendar-combined-name "OrgMode"
1671 "Calendar name for the combined iCalendar representing all agenda files."
1672 :group 'org-export
1673 :type 'string)
1674
1675 (defgroup org-faces nil
1676 "Faces for highlighting in Org-mode."
1677 :tag "Org Faces"
1678 :group 'org)
1679
1680 (defface org-level-1 ;; font-lock-function-name-face
1681 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1682 (((class color) (background light)) (:foreground "Blue"))
1683 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1684 (t (:inverse-video t :bold t)))
1685 "Face used for level 1 headlines."
1686 :group 'org-faces)
1687
1688 (defface org-level-2 ;; font-lock-variable-name-face
1689 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1690 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1691 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1692 (t (:bold t :italic t)))
1693 "Face used for level 2 headlines."
1694 :group 'org-faces)
1695
1696 (defface org-level-3 ;; font-lock-keyword-face
1697 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1698 (((class color) (background light)) (:foreground "Purple"))
1699 (((class color) (background dark)) (:foreground "Cyan"))
1700 (t (:bold t)))
1701 "Face used for level 3 headlines."
1702 :group 'org-faces)
1703
1704 (defface org-level-4 ;; font-lock-comment-face
1705 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1706 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1707 (((class color) (background light)) (:foreground "Firebrick"))
1708 (((class color) (background dark)) (:foreground "chocolate1"))
1709 (t (:bold t :italic t)))
1710 "Face used for level 4 headlines."
1711 :group 'org-faces)
1712
1713 (defface org-level-5 ;; font-lock-type-face
1714 '((((type tty) (class color)) (:foreground "green"))
1715 (((class color) (background light)) (:foreground "ForestGreen"))
1716 (((class color) (background dark)) (:foreground "PaleGreen"))
1717 (t (:bold t :underline t)))
1718 "Face used for level 5 headlines."
1719 :group 'org-faces)
1720
1721 (defface org-level-6 ;; font-lock-constant-face
1722 '((((type tty) (class color)) (:foreground "magenta"))
1723 (((class color) (background light)) (:foreground "CadetBlue"))
1724 (((class color) (background dark)) (:foreground "Aquamarine"))
1725 (t (:bold t :underline t)))
1726 "Face used for level 6 headlines."
1727 :group 'org-faces)
1728
1729 (defface org-level-7 ;; font-lock-builtin-face
1730 '((((type tty) (class color)) (:foreground "blue" :weight light))
1731 (((class color) (background light)) (:foreground "Orchid"))
1732 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1733 (t (:bold t)))
1734 "Face used for level 7 headlines."
1735 :group 'org-faces)
1736
1737 (defface org-level-8 ;; font-lock-string-face
1738 '((((type tty) (class color)) (:foreground "green"))
1739 (((class color) (background light)) (:foreground "RosyBrown"))
1740 (((class color) (background dark)) (:foreground "LightSalmon"))
1741 (t (:italic t)))
1742 "Face used for level 8 headlines."
1743 :group 'org-faces)
1744
1745 (defface org-special-keyword ;; font-lock-string-face
1746 '((((type tty) (class color)) (:foreground "green"))
1747 (((class color) (background light)) (:foreground "RosyBrown"))
1748 (((class color) (background dark)) (:foreground "LightSalmon"))
1749 (t (:italic t)))
1750 "Face used for special keywords."
1751 :group 'org-faces)
1752
1753 (defface org-warning ;; font-lock-warning-face
1754 '((((type tty) (class color)) (:foreground "red"))
1755 (((class color) (background light)) (:foreground "Red" :bold t))
1756 (((class color) (background dark)) (:foreground "Red1" :bold t))
1757 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1758 (t (:inverse-video t :bold t)))
1759 "Face for deadlines and TODO keywords."
1760 :group 'org-faces)
1761
1762 (defcustom org-fontify-done-headline nil
1763 "Non-nil means, change the face of a headline if it is marked DONE.
1764 Normally, only the TODO/DONE keyword indicates the state of a headline.
1765 When this is non-nil, the headline after the keyword is set to the
1766 `org-headline-done' as an additional indication."
1767 :group 'org-faces
1768 :type 'boolean)
1769
1770 (defface org-headline-done ;; font-lock-string-face
1771 '((((type tty) (class color)) (:foreground "green"))
1772 (((class color) (background light)) (:foreground "RosyBrown"))
1773 (((class color) (background dark)) (:foreground "LightSalmon"))
1774 (t (:italic t)))
1775 "Face used to indicate that a headline is DONE. See also the variable
1776 `org-fontify-done-headline'."
1777 :group 'org-faces)
1778
1779 ;; Inheritance does not yet work for xemacs. So we just copy...
1780
1781 (defface org-deadline-announce
1782 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1783 (((class color) (background light)) (:foreground "Blue"))
1784 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1785 (t (:inverse-video t :bold t)))
1786 "Face for upcoming deadlines."
1787 :group 'org-faces)
1788
1789 (defface org-scheduled-today
1790 '((((type tty) (class color)) (:foreground "green"))
1791 (((class color) (background light)) (:foreground "DarkGreen"))
1792 (((class color) (background dark)) (:foreground "PaleGreen"))
1793 (t (:bold t :underline t)))
1794 "Face for items scheduled for a certain day."
1795 :group 'org-faces)
1796
1797 (defface org-scheduled-previously
1798 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1799 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1800 (((class color) (background light)) (:foreground "Firebrick"))
1801 (((class color) (background dark)) (:foreground "chocolate1"))
1802 (t (:bold t :italic t)))
1803 "Face for items scheduled previously, and not yet done."
1804 :group 'org-faces)
1805
1806 (defface org-formula
1807 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1808 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1809 (((class color) (background light)) (:foreground "Firebrick"))
1810 (((class color) (background dark)) (:foreground "chocolate1"))
1811 (t (:bold t :italic t)))
1812 "Face for formulas."
1813 :group 'org-faces)
1814
1815 (defface org-link
1816 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1817 (((class color) (background light)) (:foreground "Purple"))
1818 (((class color) (background dark)) (:foreground "Cyan"))
1819 (t (:bold t)))
1820 "Face for links."
1821 :group 'org-faces)
1822
1823 (defface org-done ;; font-lock-type-face
1824 '((((type tty) (class color)) (:foreground "green"))
1825 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1826 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1827 (t (:bold t :underline t)))
1828 "Face used for DONE."
1829 :group 'org-faces)
1830
1831 (defface org-table ;; font-lock-function-name-face
1832 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1833 (((class color) (background light)) (:foreground "Blue"))
1834 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1835 (t (:inverse-video t :bold t)))
1836 "Face used for tables."
1837 :group 'org-faces)
1838
1839 (defface org-time-grid ;; font-lock-variable-name-face
1840 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1841 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1842 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1843 (t (:bold t :italic t)))
1844 "Face used for time grids."
1845 :group 'org-faces)
1846
1847 (defvar org-level-faces
1848 '(
1849 org-level-1
1850 org-level-2
1851 org-level-3
1852 org-level-4
1853 org-level-5
1854 org-level-6
1855 org-level-7
1856 org-level-8
1857 ))
1858 (defvar org-n-levels (length org-level-faces))
1859
1860 (defun org-set-regexps-and-options ()
1861 "Precompute regular expressions for current buffer."
1862 (when (eq major-mode 'org-mode)
1863 (let ((re (org-make-options-regexp
1864 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1865 "STARTUP" "ARCHIVE")))
1866 (splitre "[ \t]+")
1867 kwds int key value cat arch)
1868 (save-excursion
1869 (save-restriction
1870 (widen)
1871 (goto-char (point-min))
1872 (while (re-search-forward re nil t)
1873 (setq key (match-string 1) value (match-string 2))
1874 (cond
1875 ((equal key "CATEGORY")
1876 (if (string-match "[ \t]+$" value)
1877 (setq value (replace-match "" t t value)))
1878 (setq cat (intern value)))
1879 ((equal key "SEQ_TODO")
1880 (setq int 'sequence
1881 kwds (append kwds (org-split-string value splitre))))
1882 ((equal key "PRI_TODO")
1883 (setq int 'priority
1884 kwds (append kwds (org-split-string value splitre))))
1885 ((equal key "TYP_TODO")
1886 (setq int 'type
1887 kwds (append kwds (org-split-string value splitre))))
1888 ((equal key "STARTUP")
1889 (let ((opts (org-split-string value splitre))
1890 (set '(("fold" org-startup-folded t)
1891 ("nofold" org-startup-folded nil)
1892 ("content" org-startup-folded content)
1893 ("dlcheck" org-startup-with-deadline-check t)
1894 ("nodlcheck" org-startup-with-deadline-check nil)))
1895 l var val)
1896 (while (setq l (assoc (pop opts) set))
1897 (setq var (nth 1 l) val (nth 2 l))
1898 (set (make-local-variable var) val))))
1899 ((equal key "ARCHIVE")
1900 (string-match " *$" value)
1901 (setq arch (replace-match "" t t value))
1902 (remove-text-properties 0 (length arch)
1903 '(face t fontified t) arch)))
1904 )))
1905 (and cat (set (make-local-variable 'org-category) cat))
1906 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1907 (and arch (set (make-local-variable 'org-archive-location) arch))
1908 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1909 ;; Compute the regular expressions and other local variables
1910 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1911 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1912 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1913 (length org-scheduled-string)))
1914 org-done-string
1915 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1916 org-todo-regexp
1917 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1918 "\\|") "\\)\\>")
1919 org-not-done-regexp
1920 (concat "\\<\\("
1921 (mapconcat 'regexp-quote
1922 (nreverse (cdr (reverse org-todo-keywords)))
1923 "\\|")
1924 "\\)\\>")
1925 org-todo-line-regexp
1926 (concat "^\\(\\*+\\)[ \t]*\\("
1927 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1928 "\\)? *\\(.*\\)")
1929 org-nl-done-regexp
1930 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1931 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1932 org-deadline-regexp (concat "\\<" org-deadline-string)
1933 org-deadline-time-regexp
1934 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1935 org-deadline-line-regexp
1936 (concat "\\<\\(" org-deadline-string "\\).*")
1937 org-scheduled-regexp
1938 (concat "\\<" org-scheduled-string)
1939 org-scheduled-time-regexp
1940 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1941 (org-set-font-lock-defaults)))
1942
1943 ;; Tell the compiler about dynamically scoped variables,
1944 ;; and variables from other packages
1945 (eval-when-compile
1946 (defvar zmacs-regions)
1947 (defvar original-date)
1948 (defvar org-transient-mark-mode)
1949 (defvar org-old-auto-fill-inhibit-regexp)
1950 (defvar orgtbl-mode-menu)
1951 (defvar org-html-entities)
1952 (defvar org-goto-start-pos)
1953 (defvar org-cursor-color)
1954 (defvar org-time-was-given)
1955 (defvar org-ts-what)
1956 (defvar mark-active)
1957 (defvar timecnt)
1958 (defvar levels-open)
1959 (defvar title)
1960 (defvar author)
1961 (defvar email)
1962 (defvar text)
1963 (defvar entry)
1964 (defvar date)
1965 (defvar language)
1966 (defvar options)
1967 (defvar ans1)
1968 (defvar ans2)
1969 (defvar starting-day)
1970 (defvar include-all-loc)
1971 (defvar vm-message-pointer)
1972 (defvar vm-folder-directory)
1973 (defvar wl-summary-buffer-elmo-folder)
1974 (defvar wl-summary-buffer-folder-name)
1975 (defvar gnus-group-name)
1976 (defvar gnus-article-current)
1977 (defvar w3m-current-url)
1978 (defvar mh-progs)
1979 (defvar mh-current-folder)
1980 (defvar mh-show-folder-buffer)
1981 (defvar mh-index-folder)
1982 (defvar org-selected-point)
1983 (defvar calendar-mode-map)
1984 (defvar remember-save-after-remembering)
1985 (defvar remember-data-file)
1986 (defvar last-arg))
1987
1988
1989 ;;; Define the mode
1990
1991 (defvar org-mode-map (copy-keymap outline-mode-map)
1992 "Keymap for Org-mode.")
1993
1994 (defvar org-struct-menu)
1995 (defvar org-org-menu)
1996 (defvar org-tbl-menu)
1997
1998 ;; We use a before-change function to check if a table might need
1999 ;; an update.
2000 (defvar org-table-may-need-update t
2001 "Indicates that a table might need an update.
2002 This variable is set by `org-before-change-function'.
2003 `org-table-align'sets it back to nil.")
2004 (defvar org-mode-hook nil)
2005 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2006 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2007
2008
2009 ;;;###autoload
2010 (define-derived-mode org-mode outline-mode "Org"
2011 "Outline-based notes management and organizer, alias
2012 \"Carsten's outline-mode for keeping track of everything.\"
2013
2014 Org-mode develops organizational tasks around a NOTES file which
2015 contains information about projects as plain text. Org-mode is
2016 implemented on top of outline-mode, which is ideal to keep the content
2017 of large files well structured. It supports ToDo items, deadlines and
2018 time stamps, which magically appear in the diary listing of the Emacs
2019 calendar. Tables are easily created with a built-in table editor.
2020 Plain text URL-like links connect to websites, emails (VM), Usenet
2021 messages (Gnus), BBDB entries, and any files related to the project.
2022 For printing and sharing of notes, an Org-mode file (or a part of it)
2023 can be exported as a structured ASCII or HTML file.
2024
2025 The following commands are available:
2026
2027 \\{org-mode-map}"
2028 (easy-menu-add org-org-menu)
2029 (easy-menu-add org-tbl-menu)
2030 (org-install-agenda-files-menu)
2031 (setq outline-regexp "\\*+")
2032 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2033 (setq outline-level 'org-outline-level)
2034 (if org-startup-truncated (setq truncate-lines t))
2035 (org-set-regexps-and-options)
2036 (set (make-local-variable 'font-lock-unfontify-region-function)
2037 'org-unfontify-region)
2038 ;; Activate before-change-function
2039 (set (make-local-variable 'org-table-may-need-update) t)
2040 (org-add-hook 'before-change-functions 'org-before-change-function nil
2041 'local)
2042 ;; Paragraphs and auto-filling
2043 (org-set-autofill-regexps)
2044 (org-update-radio-target-regexp)
2045 ;; Settings for Calc embedded mode
2046 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2047 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2048 (if (and org-insert-mode-line-in-empty-file
2049 (interactive-p)
2050 (= (point-min) (point-max)))
2051 (insert " -*- mode: org -*-\n\n"))
2052
2053 ;; Get rid of Outline menus, they are not needed
2054 ;; Need to do this here because define-derived-mode sets up
2055 ;; the keymap so late.
2056 (if org-xemacs-p
2057 (progn
2058 (delete-menu-item '("Headings"))
2059 (delete-menu-item '("Show"))
2060 (delete-menu-item '("Hide"))
2061 (set-menubar-dirty-flag))
2062 (define-key org-mode-map [menu-bar headings] 'undefined)
2063 (define-key org-mode-map [menu-bar hide] 'undefined)
2064 (define-key org-mode-map [menu-bar show] 'undefined))
2065
2066 (unless org-inhibit-startup
2067 (if org-startup-with-deadline-check
2068 (call-interactively 'org-check-deadlines)
2069 (cond
2070 ((eq org-startup-folded t)
2071 (org-cycle '(4)))
2072 ((eq org-startup-folded 'content)
2073 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2074 (org-cycle '(4)) (org-cycle '(4))))))))
2075
2076 (defsubst org-current-line (&optional pos)
2077 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2078
2079
2080 ;; FIXME: Do we need to copy?
2081 (defun org-string-props (string &rest properties)
2082 "Add PROPERTIES to string."
2083 (add-text-properties 0 (length string) properties string)
2084 string)
2085
2086 ;;; Font-Lock stuff
2087
2088 (defvar org-mouse-map (make-sparse-keymap))
2089 (define-key org-mouse-map
2090 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2091 (define-key org-mouse-map
2092 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2093 (when org-tab-follows-link
2094 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2095 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2096 (when org-return-follows-link
2097 (define-key org-mouse-map [(return)] 'org-open-at-point)
2098 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2099
2100 (require 'font-lock)
2101
2102 (defconst org-non-link-chars "\t\n\r|<>\000")
2103 (defconst org-link-regexp
2104 (if org-allow-space-in-links
2105 (concat
2106 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2107 (concat
2108 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2109 )
2110 "Regular expression for matching links.")
2111 (defconst org-link-maybe-angles-regexp
2112 (concat "<?\\(" org-link-regexp "\\)>?")
2113 "Matches a link and optionally surrounding angle brackets.")
2114 (defconst org-protected-link-regexp
2115 (concat "\000" org-link-regexp "\000")
2116 "Matches a link and optionally surrounding angle brackets.")
2117
2118 (defconst org-bracket-link-regexp
2119 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2120 "Matches a link in double brackets.")
2121
2122 (defconst org-ts-lengths
2123 (cons (length (format-time-string (car org-time-stamp-formats)))
2124 (length (format-time-string (cdr org-time-stamp-formats))))
2125 "This holds the lengths of the two different time formats.")
2126 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2127 "Regular expression for fast time stamp matching.")
2128 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2129 "Regular expression for fast time stamp matching.")
2130 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2131 "Regular expression matching time strings for analysis.")
2132 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2133 "Regular expression matching time stamps, with groups.")
2134 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2135 "Regular expression matching a time stamp range.")
2136 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2137 org-ts-regexp "\\)?")
2138 "Regular expression matching a time stamp or time stamp range.")
2139
2140 (defun org-activate-links (limit)
2141 "Run through the buffer and add overlays to links."
2142 (if (re-search-forward org-link-regexp limit t)
2143 (progn
2144 (add-text-properties (match-beginning 0) (match-end 0)
2145 (list 'mouse-face 'highlight
2146 'keymap org-mouse-map))
2147 t)))
2148
2149 (defun org-activate-links2 (limit)
2150 "Run through the buffer and add overlays to links."
2151 (if (re-search-forward org-bracket-link-regexp limit t)
2152 (progn
2153 (add-text-properties (match-beginning 0) (match-end 0)
2154 (list 'mouse-face 'highlight
2155 'keymap org-mouse-map))
2156 t)))
2157
2158 (defun org-activate-dates (limit)
2159 "Run through the buffer and add overlays to dates."
2160 (if (re-search-forward org-tsr-regexp limit t)
2161 (progn
2162 (add-text-properties (match-beginning 0) (match-end 0)
2163 (list 'mouse-face 'highlight
2164 'keymap org-mouse-map))
2165 t)))
2166
2167 (defvar org-target-link-regexp nil
2168 "Regular expression matching radio targets in plain text.")
2169 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2170 "Regular expression matching a link target.")
2171 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2172 "Regular expression matching a link target.")
2173
2174 (defun org-activate-target-links (limit)
2175 "Run through the buffer and add overlays to target matches."
2176 (when org-radio-targets
2177 (let ((case-fold-search t))
2178 (if (re-search-forward org-target-link-regexp limit t)
2179 (progn
2180 (add-text-properties (match-beginning 0) (match-end 0)
2181 (list 'mouse-face 'highlight
2182 'keymap org-mouse-map
2183 'org-linked-text t))
2184 t)))))
2185
2186 (defun org-update-radio-target-regexp ()
2187 "Find all radio targets in this file and update the regular expression."
2188 (interactive)
2189 (when org-radio-targets
2190 (setq org-target-link-regexp
2191 (org-make-target-link-regexp (org-all-targets 'radio)))
2192 (font-lock-mode -1)
2193 (font-lock-mode 1)))
2194
2195 (defun org-all-targets (&optional radio)
2196 "Return a list of all targets in this file.
2197 With optional argument RADIO, only find radio targets."
2198 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2199 rtn)
2200 (save-excursion
2201 (goto-char (point-min))
2202 (while (re-search-forward re nil t)
2203 (add-to-list 'rtn (downcase (match-string-no-properties 1))))
2204 rtn)))
2205
2206 (defun org-make-target-link-regexp (targets)
2207 "Make regular expression matching all strings in TARGETS.
2208 The regular expression finds the targets also if there is a line break
2209 between words."
2210 (concat
2211 "\\<\\("
2212 (mapconcat
2213 (lambda (x)
2214 (while (string-match " +" x)
2215 (setq x (replace-match "\\s-+" t t x)))
2216 x)
2217 targets
2218 "\\|")
2219 "\\)\\>"))
2220
2221 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2222 "Matches CamelCase words, possibly with a star before it.")
2223
2224 (defun org-activate-camels (limit)
2225 "Run through the buffer and add overlays to dates."
2226 (if org-activate-camels
2227 (if (re-search-forward org-camel-regexp limit t)
2228 (progn
2229 (add-text-properties (match-beginning 0) (match-end 0)
2230 (list 'mouse-face 'highlight
2231 'keymap org-mouse-map))
2232 t))))
2233
2234 (defun org-activate-tags (limit)
2235 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2236 (progn
2237 (add-text-properties (match-beginning 1) (match-end 1)
2238 (list 'mouse-face 'highlight
2239 'keymap org-mouse-map))
2240 t)))
2241
2242 (defun org-font-lock-level ()
2243 (save-excursion
2244 (org-back-to-heading t)
2245 (- (match-end 0) (match-beginning 0))))
2246
2247 (defun org-outline-level ()
2248 (save-excursion
2249 (looking-at outline-regexp)
2250 (if (match-beginning 1)
2251 (+ (org-get-string-indentation (match-string 1)) 1000)
2252 (- (match-end 0) (match-beginning 0)))))
2253
2254 (defvar org-font-lock-keywords nil)
2255
2256 (defun org-set-font-lock-defaults ()
2257 (let ((org-font-lock-extra-keywords
2258 (list
2259 '(org-activate-links (0 'org-link t))
2260 '(org-activate-links2 (0 'org-link t))
2261 '(org-activate-target-links (0 'org-link t))
2262 '(org-activate-dates (0 'org-link t))
2263 '(org-activate-camels (0 'org-link t))
2264 '(org-activate-tags (1 'org-link t))
2265 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2266 '(1 'org-warning t))
2267 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2268 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2269 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2270 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2271 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2272 ;; (3 'bold))
2273 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2274 ;; (3 'italic))
2275 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2276 ;; (3 'underline))
2277 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2278 ; '(1 'org-warning t))
2279 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2280 "\\|" org-quote-string "\\)\\>")
2281 '(1 'org-special-keyword t))
2282 '("^#.*" (0 'font-lock-comment-face t))
2283 (if org-fontify-done-headline
2284 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2285 '(1 'org-done t) '(2 'org-headline-done t))
2286 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2287 '(1 'org-done t)))
2288 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2289 (1 'org-table t))
2290 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2291 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2292 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2293 )))
2294 (set (make-local-variable 'org-font-lock-keywords)
2295 (append
2296 (if org-noutline-p ; FIXME: I am not sure if eval will work
2297 ; on XEmacs if noutline is ever ported
2298 `((eval . (list "^\\(\\*+\\).*"
2299 ,(if org-level-color-stars-only 1 0)
2300 '(nth
2301 (% (- (match-end 1) (match-beginning 1) 1)
2302 org-n-levels)
2303 org-level-faces)
2304 nil t)))
2305 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2306 (,(if org-level-color-stars-only 2 0)
2307 (nth (% (- (match-end 2) (match-beginning 2) 1)
2308 org-n-levels)
2309 org-level-faces)
2310 nil t))))
2311 org-font-lock-extra-keywords))
2312 (set (make-local-variable 'font-lock-defaults)
2313 '(org-font-lock-keywords t nil nil backward-paragraph))
2314 (kill-local-variable 'font-lock-keywords) nil))
2315
2316 (defun org-unfontify-region (beg end &optional maybe_loudly)
2317 "Remove fontification and activation overlays from links."
2318 (font-lock-default-unfontify-region beg end)
2319 (let* ((buffer-undo-list t)
2320 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2321 (inhibit-modification-hooks t)
2322 deactivate-mark buffer-file-name buffer-file-truename)
2323 (remove-text-properties beg end
2324 '(mouse-face nil keymap nil org-linked-text nil))))
2325
2326 ;;; Visibility cycling
2327
2328 (defvar org-cycle-global-status nil)
2329 (defvar org-cycle-subtree-status nil)
2330 (defun org-cycle (&optional arg)
2331 "Visibility cycling for Org-mode.
2332
2333 - When this function is called with a prefix argument, rotate the entire
2334 buffer through 3 states (global cycling)
2335 1. OVERVIEW: Show only top-level headlines.
2336 2. CONTENTS: Show all headlines of all levels, but no body text.
2337 3. SHOW ALL: Show everything.
2338
2339 - When point is at the beginning of a headline, rotate the subtree started
2340 by this line through 3 different states (local cycling)
2341 1. FOLDED: Only the main headline is shown.
2342 2. CHILDREN: The main headline and the direct children are shown.
2343 From this state, you can move to one of the children
2344 and zoom in further.
2345 3. SUBTREE: Show the entire subtree, including body text.
2346
2347 - When there is a numeric prefix, go up to a heading with level ARG, do
2348 a `show-subtree' and return to the previous cursor position. If ARG
2349 is negative, go up that many levels.
2350
2351 - When point is not at the beginning of a headline, execute
2352 `indent-relative', like TAB normally does. See the option
2353 `org-cycle-emulate-tab' for details.
2354
2355 - Special case: if point is the the beginning of the buffer and there is
2356 no headline in line 1, this function will act as if called with prefix arg."
2357 (interactive "P")
2358
2359 (if (or (and (bobp) (not (looking-at outline-regexp)))
2360 (equal arg '(4)))
2361 ;; special case: use global cycling
2362 (setq arg t))
2363
2364 (let ((outline-regexp
2365 (if org-cycle-include-plain-lists
2366 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2367 outline-regexp)))
2368
2369 (cond
2370
2371 ((org-at-table-p 'any)
2372 ;; Enter the table or move to the next field in the table
2373 (or (org-table-recognize-table.el)
2374 (progn
2375 (org-table-justify-field-maybe)
2376 (org-table-next-field))))
2377
2378 ((eq arg t) ;; Global cycling
2379
2380 (cond
2381 ((and (eq last-command this-command)
2382 (eq org-cycle-global-status 'overview))
2383 ;; We just created the overview - now do table of contents
2384 ;; This can be slow in very large buffers, so indicate action
2385 (message "CONTENTS...")
2386 (save-excursion
2387 ;; Visit all headings and show their offspring
2388 (goto-char (point-max))
2389 (catch 'exit
2390 (while (and (progn (condition-case nil
2391 (outline-previous-visible-heading 1)
2392 (error (goto-char (point-min))))
2393 t)
2394 (looking-at outline-regexp))
2395 (show-branches)
2396 (if (bobp) (throw 'exit nil))))
2397 (message "CONTENTS...done"))
2398 (setq org-cycle-global-status 'contents)
2399 (run-hook-with-args 'org-cycle-hook 'contents))
2400
2401 ((and (eq last-command this-command)
2402 (eq org-cycle-global-status 'contents))
2403 ;; We just showed the table of contents - now show everything
2404 (show-all)
2405 (message "SHOW ALL")
2406 (setq org-cycle-global-status 'all)
2407 (run-hook-with-args 'org-cycle-hook 'all))
2408
2409 (t
2410 ;; Default action: go to overview
2411 (hide-sublevels 1)
2412 (message "OVERVIEW")
2413 (setq org-cycle-global-status 'overview)
2414 (run-hook-with-args 'org-cycle-hook 'overview))))
2415
2416 ((integerp arg)
2417 ;; Show-subtree, ARG levels up from here.
2418 (save-excursion
2419 (org-back-to-heading)
2420 (outline-up-heading (if (< arg 0) (- arg)
2421 (- (outline-level) arg)))
2422 (org-show-subtree)))
2423
2424 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2425 ;; At a heading: rotate between three different views
2426 (org-back-to-heading)
2427 (let ((goal-column 0) eoh eol eos)
2428 ;; First, some boundaries
2429 (save-excursion
2430 (org-back-to-heading)
2431 (save-excursion
2432 (beginning-of-line 2)
2433 (while (and (not (eobp)) ;; this is like `next-line'
2434 (get-char-property (1- (point)) 'invisible))
2435 (beginning-of-line 2)) (setq eol (point)))
2436 (outline-end-of-heading) (setq eoh (point))
2437 (org-end-of-subtree t) (setq eos (point))
2438 (outline-next-heading))
2439 ;; Find out what to do next and set `this-command'
2440 (cond
2441 ((= eos eoh)
2442 ;; Nothing is hidden behind this heading
2443 (message "EMPTY ENTRY")
2444 (setq org-cycle-subtree-status nil))
2445 ((>= eol eos)
2446 ;; Entire subtree is hidden in one line: open it
2447 (org-show-entry)
2448 (show-children)
2449 (message "CHILDREN")
2450 (setq org-cycle-subtree-status 'children)
2451 (run-hook-with-args 'org-cycle-hook 'children))
2452 ((and (eq last-command this-command)
2453 (eq org-cycle-subtree-status 'children))
2454 ;; We just showed the children, now show everything.
2455 (org-show-subtree)
2456 (message "SUBTREE")
2457 (setq org-cycle-subtree-status 'subtree)
2458 (run-hook-with-args 'org-cycle-hook 'subtree))
2459 (t
2460 ;; Default action: hide the subtree.
2461 (hide-subtree)
2462 (message "FOLDED")
2463 (setq org-cycle-subtree-status 'folded)
2464 (run-hook-with-args 'org-cycle-hook 'folded)))))
2465
2466 ;; TAB emulation
2467 (buffer-read-only (org-back-to-heading))
2468 ((if (and (eq org-cycle-emulate-tab 'white)
2469 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2470 t
2471 (eq org-cycle-emulate-tab t))
2472 (if (and (looking-at "[ \n\r\t]")
2473 (string-match "^[ \t]*$" (buffer-substring
2474 (point-at-bol) (point))))
2475 (progn
2476 (beginning-of-line 1)
2477 (and (looking-at "[ \t]+") (replace-match ""))))
2478 (indent-relative))
2479
2480 (t (save-excursion
2481 (org-back-to-heading)
2482 (org-cycle))))))
2483
2484 (defun org-optimize-window-after-visibility-change (state)
2485 "Adjust the window after a change in outline visibility.
2486 This function is the default value of the hook `org-cycle-hook'."
2487 (cond
2488 ((eq state 'overview) (org-first-headline-recenter 1))
2489 ((eq state 'content) nil)
2490 ((eq state 'all) nil)
2491 ((eq state 'folded) nil)
2492 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2493 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2494
2495 (defun org-subtree-end-visible-p ()
2496 "Is the end of the current subtree visible?"
2497 (pos-visible-in-window-p
2498 (save-excursion (org-end-of-subtree t) (point))))
2499
2500 (defun org-first-headline-recenter (&optional N)
2501 "Move cursor to the first headline and recenter the headline.
2502 Optional argument N means, put the headline into the Nth line of the window."
2503 (goto-char (point-min))
2504 (when (re-search-forward (concat "^" outline-regexp) nil t)
2505 (beginning-of-line)
2506 (recenter (prefix-numeric-value N))))
2507
2508 (defvar org-goto-window-configuration nil)
2509 (defvar org-goto-marker nil)
2510 (defvar org-goto-map (make-sparse-keymap))
2511 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2512 (while (setq cmd (pop cmds))
2513 (substitute-key-definition cmd cmd org-goto-map global-map)))
2514 (define-key org-goto-map "\C-m" 'org-goto-ret)
2515 (define-key org-goto-map [(left)] 'org-goto-left)
2516 (define-key org-goto-map [(right)] 'org-goto-right)
2517 (define-key org-goto-map [(?q)] 'org-goto-quit)
2518 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2519 (define-key org-goto-map "\C-i" 'org-cycle)
2520 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2521 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2522 (define-key org-goto-map "n" 'outline-next-visible-heading)
2523 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2524 (define-key org-goto-map "f" 'outline-forward-same-level)
2525 (define-key org-goto-map "b" 'outline-backward-same-level)
2526 (define-key org-goto-map "u" 'outline-up-heading)
2527 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2528 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2529 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2530 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2531 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2532 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2533 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2534
2535 (defconst org-goto-help
2536 "Select a location to jump to, press RET
2537 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2538
2539 (defun org-goto ()
2540 "Go to a different location of the document, keeping current visibility.
2541
2542 When you want to go to a different location in a document, the fastest way
2543 is often to fold the entire buffer and then dive into the tree. This
2544 method has the disadvantage, that the previous location will be folded,
2545 which may not be what you want.
2546
2547 This command works around this by showing a copy of the current buffer in
2548 overview mode. You can dive into the tree in that copy, to find the
2549 location you want to reach. When pressing RET, the command returns to the
2550 original buffer in which the visibility is still unchanged. It then jumps
2551 to the new location, making it and the headline hierarchy above it visible."
2552 (interactive)
2553 (let* ((org-goto-start-pos (point))
2554 (selected-point
2555 (org-get-location (current-buffer) org-goto-help)))
2556 (if selected-point
2557 (progn
2558 (org-mark-ring-push org-goto-start-pos)
2559 (goto-char selected-point)
2560 (if (or (org-invisible-p) (org-invisible-p2))
2561 (org-show-hierarchy-above)))
2562 (error "Quit"))))
2563
2564 (defun org-get-location (buf help)
2565 "Let the user select a location in the Org-mode buffer BUF.
2566 This function uses a recursive edit. It returns the selected position
2567 or nil."
2568 (let (org-selected-point)
2569 (save-excursion
2570 (save-window-excursion
2571 (delete-other-windows)
2572 (switch-to-buffer (get-buffer-create "*org-goto*"))
2573 (with-output-to-temp-buffer "*Help*"
2574 (princ help))
2575 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2576 (setq buffer-read-only nil)
2577 (erase-buffer)
2578 (insert-buffer-substring buf)
2579 (let ((org-startup-truncated t)
2580 (org-startup-folded t)
2581 (org-startup-with-deadline-check nil))
2582 (org-mode))
2583 (setq buffer-read-only t)
2584 (if (boundp 'org-goto-start-pos)
2585 (goto-char org-goto-start-pos)
2586 (goto-char (point-min)))
2587 (org-beginning-of-line)
2588 (message "Select location and press RET")
2589 ;; now we make sure that during selection, ony very few keys work
2590 ;; and that it is impossible to switch to another window.
2591 (let ((gm (current-global-map))
2592 (overriding-local-map org-goto-map))
2593 (unwind-protect
2594 (progn
2595 (use-global-map org-goto-map)
2596 (recursive-edit))
2597 (use-global-map gm)))))
2598 (kill-buffer "*org-goto*")
2599 org-selected-point))
2600
2601 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2602 (defun org-goto-ret (&optional arg)
2603 "Finish `org-goto' by going to the new location."
2604 (interactive "P")
2605 (setq org-selected-point (point)
2606 current-prefix-arg arg)
2607 (throw 'exit nil))
2608
2609 (defun org-goto-left ()
2610 "Finish `org-goto' by going to the new location."
2611 (interactive)
2612 (if (org-on-heading-p)
2613 (progn
2614 (beginning-of-line 1)
2615 (setq org-selected-point (point)
2616 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2617 (throw 'exit nil))
2618 (error "Not on a heading")))
2619
2620 (defun org-goto-right ()
2621 "Finish `org-goto' by going to the new location."
2622 (interactive)
2623 (if (org-on-heading-p)
2624 (progn
2625 (outline-end-of-subtree)
2626 (or (eobp) (forward-char 1))
2627 (setq org-selected-point (point)
2628 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2629 (throw 'exit nil))
2630 (error "Not on a heading")))
2631
2632 (defun org-goto-quit ()
2633 "Finish `org-goto' without cursor motion."
2634 (interactive)
2635 (setq org-selected-point nil)
2636 (throw 'exit nil))
2637
2638 ;;; Promotion, Demotion, Inserting new headlines
2639
2640 (defvar org-ignore-region nil
2641 "To temporarily disable the active region.")
2642
2643 (defun org-insert-heading (&optional force-heading)
2644 "Insert a new heading or item with same depth at point."
2645 (interactive "P")
2646 (when (or force-heading (not (org-insert-item)))
2647 (let* ((head (save-excursion
2648 (condition-case nil
2649 (org-back-to-heading)
2650 (error (outline-next-heading)))
2651 (prog1 (match-string 0)
2652 (funcall outline-level)))))
2653 (unless (bolp) (newline))
2654 (insert head)
2655 (unless (eolp)
2656 (save-excursion (newline-and-indent)))
2657 (unless (equal (char-before) ?\ )
2658 (insert " "))
2659 (run-hooks 'org-insert-heading-hook))))
2660
2661 (defun org-insert-item ()
2662 "Insert a new item at the current level.
2663 Return t when things worked, nil when we are not in an item."
2664 (when (save-excursion
2665 (condition-case nil
2666 (progn
2667 (org-beginning-of-item)
2668 (org-at-item-p)
2669 t)
2670 (error nil)))
2671 (unless (bolp) (newline))
2672 (insert (match-string 0))
2673 (org-maybe-renumber-ordered-list)
2674 t))
2675
2676 (defun org-insert-todo-heading (arg)
2677 "Insert a new heading with the same level and TODO state as current heading.
2678 If the heading has no TODO state, or if the state is DONE, use the first
2679 state (TODO by default). Also with prefix arg, force first state."
2680 (interactive "P")
2681 (org-insert-heading)
2682 (save-excursion
2683 (org-back-to-heading)
2684 (outline-previous-heading)
2685 (looking-at org-todo-line-regexp))
2686 (if (or arg
2687 (not (match-beginning 2))
2688 (equal (match-string 2) org-done-string))
2689 (insert (car org-todo-keywords) " ")
2690 (insert (match-string 2) " ")))
2691
2692 (defun org-promote-subtree ()
2693 "Promote the entire subtree.
2694 See also `org-promote'."
2695 (interactive)
2696 (save-excursion
2697 (org-map-tree 'org-promote)))
2698
2699 (defun org-demote-subtree ()
2700 "Demote the entire subtree. See `org-demote'.
2701 See also `org-promote'."
2702 (interactive)
2703 (save-excursion
2704 (org-map-tree 'org-demote)))
2705
2706 (defun org-do-promote ()
2707 "Promote the current heading higher up the tree.
2708 If the region is active in `transient-mark-mode', promote all headings
2709 in the region."
2710 (interactive)
2711 (save-excursion
2712 (if (org-region-active-p)
2713 (org-map-region 'org-promote (region-beginning) (region-end))
2714 (org-promote)))
2715 (org-fix-position-after-promote))
2716
2717 (defun org-do-demote ()
2718 "Demote the current heading lower down the tree.
2719 If the region is active in `transient-mark-mode', demote all headings
2720 in the region."
2721 (interactive)
2722 (save-excursion
2723 (if (org-region-active-p)
2724 (org-map-region 'org-demote (region-beginning) (region-end))
2725 (org-demote)))
2726 (org-fix-position-after-promote))
2727
2728 (defun org-fix-position-after-promote ()
2729 "Make sure that after pro/demotion cursor position is right."
2730 (and (equal (char-after) ?\ )
2731 (equal (char-before) ?*)
2732 (forward-char 1)))
2733
2734 (defun org-promote ()
2735 "Promote the current heading higher up the tree.
2736 If the region is active in `transient-mark-mode', promote all headings
2737 in the region."
2738 (org-back-to-heading t)
2739 (let* ((level (save-match-data (funcall outline-level)))
2740 (up-head (make-string (1- level) ?*)))
2741 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2742 (replace-match up-head nil t)
2743 ;; Fixup tag positioning
2744 (and org-auto-align-tags (org-set-tags nil t))
2745 (if org-adapt-indentation
2746 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2747
2748 (defun org-demote ()
2749 "Demote the current heading lower down the tree.
2750 If the region is active in `transient-mark-mode', demote all headings
2751 in the region."
2752 (org-back-to-heading t)
2753 (let* ((level (save-match-data (funcall outline-level)))
2754 (down-head (make-string (1+ level) ?*)))
2755 (replace-match down-head nil t)
2756 ;; Fixup tag positioning
2757 (and org-auto-align-tags (org-set-tags nil t))
2758 (if org-adapt-indentation
2759 (org-fixup-indentation "^ " " " "^\\S-"))))
2760
2761 (defun org-map-tree (fun)
2762 "Call FUN for every heading underneath the current one."
2763 (org-back-to-heading)
2764 (let ((level (outline-level)))
2765 (save-excursion
2766 (funcall fun)
2767 (while (and (progn
2768 (outline-next-heading)
2769 (> (funcall outline-level) level))
2770 (not (eobp)))
2771 (funcall fun)))))
2772
2773 (defun org-map-region (fun beg end)
2774 "Call FUN for every heading between BEG and END."
2775 (let ((org-ignore-region t))
2776 (save-excursion
2777 (setq end (copy-marker end))
2778 (goto-char beg)
2779 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2780 (< (point) end))
2781 (funcall fun))
2782 (while (and (progn
2783 (outline-next-heading)
2784 (< (point) end))
2785 (not (eobp)))
2786 (funcall fun)))))
2787
2788 (defun org-fixup-indentation (from to prohibit)
2789 "Change the indentation in the current entry by re-replacing FROM with TO.
2790 However, if the regexp PROHIBIT matches at all, don't do anything.
2791 This is being used to change indentation along with the length of the
2792 heading marker. But if there are any lines which are not indented, nothing
2793 is changed at all."
2794 (save-excursion
2795 (let ((end (save-excursion (outline-next-heading)
2796 (point-marker))))
2797 (unless (save-excursion (re-search-forward prohibit end t))
2798 (while (re-search-forward from end t)
2799 (replace-match to)
2800 (beginning-of-line 2)))
2801 (move-marker end nil))))
2802
2803 ;;; Vertical tree motion, cutting and pasting of subtrees
2804
2805 (defun org-move-subtree-up (&optional arg)
2806 "Move the current subtree up past ARG headlines of the same level."
2807 (interactive "p")
2808 (org-move-subtree-down (- (prefix-numeric-value arg))))
2809
2810 (defun org-move-subtree-down (&optional arg)
2811 "Move the current subtree down past ARG headlines of the same level."
2812 (interactive "p")
2813 (setq arg (prefix-numeric-value arg))
2814 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2815 'outline-get-last-sibling))
2816 (ins-point (make-marker))
2817 (cnt (abs arg))
2818 beg end txt folded)
2819 ;; Select the tree
2820 (org-back-to-heading)
2821 (setq beg (point))
2822 (save-match-data
2823 (save-excursion (outline-end-of-heading)
2824 (setq folded (org-invisible-p)))
2825 (outline-end-of-subtree))
2826 (outline-next-heading)
2827 (setq end (point))
2828 ;; Find insertion point, with error handling
2829 (goto-char beg)
2830 (while (> cnt 0)
2831 (or (and (funcall movfunc) (looking-at outline-regexp))
2832 (progn (goto-char beg)
2833 (error "Cannot move past superior level or buffer limit")))
2834 (setq cnt (1- cnt)))
2835 (if (> arg 0)
2836 ;; Moving forward - still need to move over subtree
2837 (progn (outline-end-of-subtree)
2838 (outline-next-heading)
2839 (if (not (or (looking-at (concat "^" outline-regexp))
2840 (bolp)))
2841 (newline))))
2842 (move-marker ins-point (point))
2843 (setq txt (buffer-substring beg end))
2844 (delete-region beg end)
2845 (insert txt)
2846 (goto-char ins-point)
2847 (if folded (hide-subtree))
2848 (move-marker ins-point nil)))
2849
2850 (defvar org-subtree-clip ""
2851 "Clipboard for cut and paste of subtrees.
2852 This is actually only a copy of the kill, because we use the normal kill
2853 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2854
2855 (defvar org-subtree-clip-folded nil
2856 "Was the last copied subtree folded?
2857 This is used to fold the tree back after pasting.")
2858
2859 (defun org-cut-subtree ()
2860 "Cut the current subtree into the clipboard.
2861 This is a short-hand for marking the subtree and then cutting it."
2862 (interactive)
2863 (org-copy-subtree 'cut))
2864
2865 (defun org-copy-subtree (&optional cut)
2866 "Cut the current subtree into the clipboard.
2867 This is a short-hand for marking the subtree and then copying it.
2868 If CUT is non nil, actually cut the subtree."
2869 (interactive)
2870 (let (beg end folded)
2871 (org-back-to-heading)
2872 (setq beg (point))
2873 (save-match-data
2874 (save-excursion (outline-end-of-heading)
2875 (setq folded (org-invisible-p)))
2876 (outline-end-of-subtree))
2877 (if (equal (char-after) ?\n) (forward-char 1))
2878 (setq end (point))
2879 (goto-char beg)
2880 (when (> end beg)
2881 (setq org-subtree-clip-folded folded)
2882 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2883 (setq org-subtree-clip (current-kill 0))
2884 (message "%s: Subtree with %d characters"
2885 (if cut "Cut" "Copied")
2886 (length org-subtree-clip)))))
2887
2888 (defun org-paste-subtree (&optional level tree)
2889 "Paste the clipboard as a subtree, with modification of headline level.
2890 The entire subtree is promoted or demoted in order to match a new headline
2891 level. By default, the new level is derived from the visible headings
2892 before and after the insertion point, and taken to be the inferior headline
2893 level of the two. So if the previous visible heading is level 3 and the
2894 next is level 4 (or vice versa), level 4 will be used for insertion.
2895 This makes sure that the subtree remains an independent subtree and does
2896 not swallow low level entries.
2897
2898 You can also force a different level, either by using a numeric prefix
2899 argument, or by inserting the heading marker by hand. For example, if the
2900 cursor is after \"*****\", then the tree will be shifted to level 5.
2901
2902 If you want to insert the tree as is, just use \\[yank].
2903
2904 If optional TREE is given, use this text instead of the kill ring."
2905 (interactive "P")
2906 (unless (org-kill-is-subtree-p tree)
2907 (error
2908 (substitute-command-keys
2909 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2910 (let* ((txt (or tree (current-kill 0)))
2911 (^re (concat "^\\(" outline-regexp "\\)"))
2912 (re (concat "\\(" outline-regexp "\\)"))
2913 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2914
2915 (old-level (if (string-match ^re txt)
2916 (- (match-end 0) (match-beginning 0))
2917 -1))
2918 (force-level (cond (level (prefix-numeric-value level))
2919 ((string-match
2920 ^re_ (buffer-substring (point-at-bol) (point)))
2921 (- (match-end 0) (match-beginning 0)))
2922 (t nil)))
2923 (previous-level (save-excursion
2924 (condition-case nil
2925 (progn
2926 (outline-previous-visible-heading 1)
2927 (if (looking-at re)
2928 (- (match-end 0) (match-beginning 0))
2929 1))
2930 (error 1))))
2931 (next-level (save-excursion
2932 (condition-case nil
2933 (progn
2934 (outline-next-visible-heading 1)
2935 (if (looking-at re)
2936 (- (match-end 0) (match-beginning 0))
2937 1))
2938 (error 1))))
2939 (new-level (or force-level (max previous-level next-level)))
2940 (shift (if (or (= old-level -1)
2941 (= new-level -1)
2942 (= old-level new-level))
2943 0
2944 (- new-level old-level)))
2945 (shift1 shift)
2946 (delta (if (> shift 0) -1 1))
2947 (func (if (> shift 0) 'org-demote 'org-promote))
2948 beg end)
2949 ;; Remove the forces level indicator
2950 (if force-level
2951 (delete-region (point-at-bol) (point)))
2952 ;; Make sure we start at the beginning of an empty line
2953 (if (not (bolp)) (insert "\n"))
2954 (if (not (looking-at "[ \t]*$"))
2955 (progn (insert "\n") (backward-char 1)))
2956 ;; Paste
2957 (setq beg (point))
2958 (insert txt)
2959 (setq end (point))
2960 (goto-char beg)
2961 ;; Shift if necessary
2962 (if (= shift 0)
2963 (message "Pasted at level %d, without shift" new-level)
2964 (save-restriction
2965 (narrow-to-region beg end)
2966 (while (not (= shift 0))
2967 (org-map-region func (point-min) (point-max))
2968 (setq shift (+ delta shift)))
2969 (goto-char (point-min))
2970 (message "Pasted at level %d, with shift by %d levels"
2971 new-level shift1)))
2972 (if (and (eq org-subtree-clip (current-kill 0))
2973 org-subtree-clip-folded)
2974 ;; The tree was folded before it was killed/copied
2975 (hide-subtree))))
2976
2977 (defun org-kill-is-subtree-p (&optional txt)
2978 "Check if the current kill is an outline subtree, or a set of trees.
2979 Returns nil if kill does not start with a headline, or if the first
2980 headline level is not the largest headline level in the tree.
2981 So this will actually accept several entries of equal levels as well,
2982 which is OK for `org-paste-subtree'.
2983 If optional TXT is given, check this string instead of the current kill."
2984 (let* ((kill (or txt (current-kill 0) ""))
2985 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2986 (- (match-end 0) (match-beginning 0))))
2987 (re (concat "^" outline-regexp))
2988 (start 1))
2989 (if (not start-level)
2990 nil ;; does not even start with a heading
2991 (catch 'exit
2992 (while (setq start (string-match re kill (1+ start)))
2993 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2994 (throw 'exit nil)))
2995 t))))
2996
2997 ;;; Plain list items
2998
2999 (defun org-at-item-p ()
3000 "Is point in a line starting a hand-formatted item?"
3001 (let ((llt org-plain-list-ordered-item-terminator))
3002 (save-excursion
3003 (goto-char (point-at-bol))
3004 (looking-at
3005 (cond
3006 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3007 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3008 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3009 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3010
3011 (defun org-get-indentation ()
3012 "Get the indentation of the current line, interpreting tabs."
3013 (save-excursion
3014 (beginning-of-line 1)
3015 (skip-chars-forward " \t")
3016 (current-column)))
3017
3018 (defun org-beginning-of-item ()
3019 "Go to the beginning of the current hand-formatted item.
3020 If the cursor is not in an item, throw an error."
3021 (let ((pos (point))
3022 (limit (save-excursion (org-back-to-heading)
3023 (beginning-of-line 2) (point)))
3024 ind ind1)
3025 (if (org-at-item-p)
3026 (beginning-of-line 1)
3027 (beginning-of-line 1)
3028 (skip-chars-forward " \t")
3029 (setq ind (current-column))
3030 (if (catch 'exit
3031 (while t
3032 (beginning-of-line 0)
3033 (if (< (point) limit) (throw 'exit nil))
3034 (unless (looking-at " \t]*$")
3035 (skip-chars-forward " \t")
3036 (setq ind1 (current-column))
3037 (if (< ind1 ind)
3038 (throw 'exit (org-at-item-p))))))
3039 nil
3040 (goto-char pos)
3041 (error "Not in an item")))))
3042
3043 (defun org-end-of-item ()
3044 "Go to the end of the current hand-formatted item.
3045 If the cursor is not in an item, throw an error."
3046 (let ((pos (point))
3047 (limit (save-excursion (outline-next-heading) (point)))
3048 (ind (save-excursion
3049 (org-beginning-of-item)
3050 (skip-chars-forward " \t")
3051 (current-column)))
3052 ind1)
3053 (if (catch 'exit
3054 (while t
3055 (beginning-of-line 2)
3056 (if (>= (point) limit) (throw 'exit t))
3057 (unless (looking-at "[ \t]*$")
3058 (skip-chars-forward " \t")
3059 (setq ind1 (current-column))
3060 (if (<= ind1 ind) (throw 'exit t)))))
3061 (beginning-of-line 1)
3062 (goto-char pos)
3063 (error "Not in an item"))))
3064
3065 (defun org-move-item-down (arg)
3066 "Move the plain list item at point down, i.e. swap with following item.
3067 Subitems (items with larger indentation) are considered part of the item,
3068 so this really moves item trees."
3069 (interactive "p")
3070 (let (beg end ind ind1 (pos (point)) txt)
3071 (org-beginning-of-item)
3072 (setq beg (point))
3073 (setq ind (org-get-indentation))
3074 (org-end-of-item)
3075 (setq end (point))
3076 (setq ind1 (org-get-indentation))
3077 (if (and (org-at-item-p) (= ind ind1))
3078 (progn
3079 (org-end-of-item)
3080 (setq txt (buffer-substring beg end))
3081 (save-excursion
3082 (delete-region beg end))
3083 (setq pos (point))
3084 (insert txt)
3085 (goto-char pos)
3086 (org-maybe-renumber-ordered-list))
3087 (goto-char pos)
3088 (error "Cannot move this item further down"))))
3089
3090 (defun org-move-item-up (arg)
3091 "Move the plain list item at point up, i.e. swap with previous item.
3092 Subitems (items with larger indentation) are considered part of the item,
3093 so this really moves item trees."
3094 (interactive "p")
3095 (let (beg end ind ind1 (pos (point)) txt)
3096 (org-beginning-of-item)
3097 (setq beg (point))
3098 (setq ind (org-get-indentation))
3099 (org-end-of-item)
3100 (setq end (point))
3101 (goto-char beg)
3102 (catch 'exit
3103 (while t
3104 (beginning-of-line 0)
3105 (if (looking-at "[ \t]*$")
3106 nil
3107 (if (<= (setq ind1 (org-get-indentation)) ind)
3108 (throw 'exit t)))))
3109 (condition-case nil
3110 (org-beginning-of-item)
3111 (error (goto-char beg)
3112 (error "Cannot move this item further up")))
3113 (setq ind1 (org-get-indentation))
3114 (if (and (org-at-item-p) (= ind ind1))
3115 (progn
3116 (setq txt (buffer-substring beg end))
3117 (save-excursion
3118 (delete-region beg end))
3119 (setq pos (point))
3120 (insert txt)
3121 (goto-char pos)
3122 (org-maybe-renumber-ordered-list))
3123 (goto-char pos)
3124 (error "Cannot move this item further up"))))
3125
3126 (defun org-maybe-renumber-ordered-list ()
3127 "Renumber the ordered list at point if setup allows it.
3128 This tests the user option `org-auto-renumber-ordered-lists' before
3129 doing the renumbering."
3130 (and org-auto-renumber-ordered-lists
3131 (org-at-item-p)
3132 (match-beginning 3)
3133 (org-renumber-ordered-list 1)))
3134
3135 (defun org-get-string-indentation (s)
3136 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3137 (let ((n -1) (i 0) (w tab-width) c)
3138 (catch 'exit
3139 (while (< (setq n (1+ n)) (length s))
3140 (setq c (aref s n))
3141 (cond ((= c ?\ ) (setq i (1+ i)))
3142 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3143 (t (throw 'exit t)))))
3144 i))
3145
3146 (defun org-renumber-ordered-list (arg)
3147 "Renumber an ordered plain list.
3148 Cursor next to be in the first line of an item, the line that starts
3149 with something like \"1.\" or \"2)\"."
3150 (interactive "p")
3151 (unless (and (org-at-item-p)
3152 (match-beginning 3))
3153 (error "This is not an ordered list"))
3154 (let ((line (org-current-line))
3155 (col (current-column))
3156 (ind (org-get-string-indentation
3157 (buffer-substring (point-at-bol) (match-beginning 3))))
3158 ;; (term (substring (match-string 3) -1))
3159 ind1 (n (1- arg)))
3160 ;; find where this list begins
3161 (catch 'exit
3162 (while t
3163 (catch 'next
3164 (beginning-of-line 0)
3165 (if (looking-at "[ \t]*$") (throw 'next t))
3166 (skip-chars-forward " \t") (setq ind1 (current-column))
3167 (if (or (< ind1 ind)
3168 (and (= ind1 ind)
3169 (not (org-at-item-p))))
3170 (throw 'exit t)))))
3171 ;; Walk forward and replace these numbers
3172 (catch 'exit
3173 (while t
3174 (catch 'next
3175 (beginning-of-line 2)
3176 (if (eobp) (throw 'exit nil))
3177 (if (looking-at "[ \t]*$") (throw 'next nil))
3178 (skip-chars-forward " \t") (setq ind1 (current-column))
3179 (if (> ind1 ind) (throw 'next t))
3180 (if (< ind1 ind) (throw 'exit t))
3181 (if (not (org-at-item-p)) (throw 'exit nil))
3182 (if (not (match-beginning 3))
3183 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3184 (delete-region (match-beginning 3) (1- (match-end 3)))
3185 (goto-char (match-beginning 3))
3186 (insert (format "%d" (setq n (1+ n)))))))
3187 (goto-line line)
3188 (move-to-column col)))
3189
3190 (defvar org-last-indent-begin-marker (make-marker))
3191 (defvar org-last-indent-end-marker (make-marker))
3192
3193
3194 (defun org-outdent-item (arg)
3195 "Outdent a local list item."
3196 (interactive "p")
3197 (org-indent-item (- arg)))
3198
3199 (defun org-indent-item (arg)
3200 "Indent a local list item."
3201 (interactive "p")
3202 (unless (org-at-item-p)
3203 (error "Not on an item"))
3204 (let (beg end ind ind1)
3205 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3206 (setq beg org-last-indent-begin-marker
3207 end org-last-indent-end-marker)
3208 (org-beginning-of-item)
3209 (setq beg (move-marker org-last-indent-begin-marker (point)))
3210 (org-end-of-item)
3211 (setq end (move-marker org-last-indent-end-marker (point))))
3212 (goto-char beg)
3213 (skip-chars-forward " \t") (setq ind (current-column))
3214 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3215 (while (< (point) end)
3216 (beginning-of-line 1)
3217 (skip-chars-forward " \t") (setq ind1 (current-column))
3218 (delete-region (point-at-bol) (point))
3219 (indent-to-column (+ ind1 arg))
3220 (beginning-of-line 2))
3221 (goto-char beg)))
3222
3223 ;;; Archiving
3224
3225 (defun org-archive-subtree ()
3226 "Move the current subtree to the archive.
3227 The archive can be a certain top-level heading in the current file, or in
3228 a different file. The tree will be moved to that location, the subtree
3229 heading be marked DONE, and the current time will be added."
3230 (interactive)
3231 ;; Save all relevant TODO keyword-relatex variables
3232 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3233 (tr-org-todo-keywords org-todo-keywords)
3234 (tr-org-todo-interpretation org-todo-interpretation)
3235 (tr-org-done-string org-done-string)
3236 (tr-org-todo-regexp org-todo-regexp)
3237 (tr-org-todo-line-regexp org-todo-line-regexp)
3238 (this-buffer (current-buffer))
3239 file heading buffer level newfile-p)
3240 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3241 (progn
3242 (setq file (format (match-string 1 org-archive-location)
3243 (file-name-nondirectory (buffer-file-name)))
3244 heading (match-string 2 org-archive-location)))
3245 (error "Invalid `org-archive-location'"))
3246 (if (> (length file) 0)
3247 (setq newfile-p (not (file-exists-p file))
3248 buffer (find-file-noselect file))
3249 (setq buffer (current-buffer)))
3250 (unless buffer
3251 (error "Cannot access file \"%s\"" file))
3252 (if (and (> (length heading) 0)
3253 (string-match "^\\*+" heading))
3254 (setq level (match-end 0))
3255 (setq heading nil level 0))
3256 (save-excursion
3257 ;; We first only copy, in case something goes wrong
3258 ;; we need to protect this-command, to avoid kill-region sets it,
3259 ;; which would lead to duplication of subtrees
3260 (let (this-command) (org-copy-subtree))
3261 (set-buffer buffer)
3262 ;; Enforce org-mode for the archive buffer
3263 (if (not (eq major-mode 'org-mode))
3264 ;; Force the mode for future visits.
3265 (let ((org-insert-mode-line-in-empty-file t))
3266 (call-interactively 'org-mode)))
3267 (when newfile-p
3268 (goto-char (point-max))
3269 (insert (format "\nArchived entries from file %s\n\n"
3270 (buffer-file-name this-buffer))))
3271 ;; Force the TODO keywords of the original buffer
3272 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3273 (org-todo-keywords tr-org-todo-keywords)
3274 (org-todo-interpretation tr-org-todo-interpretation)
3275 (org-done-string tr-org-done-string)
3276 (org-todo-regexp tr-org-todo-regexp)
3277 (org-todo-line-regexp tr-org-todo-line-regexp))
3278 (goto-char (point-min))
3279 (if heading
3280 (progn
3281 (if (re-search-forward
3282 (concat "\\(^\\|\r\\)"
3283 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3284 nil t)
3285 (goto-char (match-end 0))
3286 ;; Heading not found, just insert it at the end
3287 (goto-char (point-max))
3288 (or (bolp) (insert "\n"))
3289 (insert "\n" heading "\n")
3290 (end-of-line 0))
3291 ;; Make the heading visible, and the following as well
3292 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3293 (if (re-search-forward
3294 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3295 nil t)
3296 (progn (goto-char (match-beginning 0)) (insert "\n")
3297 (beginning-of-line 0))
3298 (goto-char (point-max)) (insert "\n")))
3299 (goto-char (point-max)) (insert "\n"))
3300 ;; Paste
3301 (org-paste-subtree (1+ level))
3302 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3303 (if org-archive-mark-done
3304 (org-todo (length org-todo-keywords)))
3305 ;; Move cursor to right after the TODO keyword
3306 (when org-archive-stamp-time
3307 (beginning-of-line 1)
3308 (looking-at org-todo-line-regexp)
3309 (goto-char (or (match-end 2) (match-beginning 3)))
3310 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3311 (current-time))
3312 ")"))
3313 ;; Save the buffer, if it is not the same buffer.
3314 (if (not (eq this-buffer buffer)) (save-buffer))))
3315 ;; Here we are back in the original buffer. Everything seems to have
3316 ;; worked. So now cut the tree and finish up.
3317 (let (this-command) (org-cut-subtree))
3318 (if (looking-at "[ \t]*$") (kill-line))
3319 (message "Subtree archived %s"
3320 (if (eq this-buffer buffer)
3321 (concat "under heading: " heading)
3322 (concat "in file: " (abbreviate-file-name file))))))
3323
3324 ;;; Completion
3325
3326 (defun org-complete (&optional arg)
3327 "Perform completion on word at point.
3328 At the beginning of a headline, this completes TODO keywords as given in
3329 `org-todo-keywords'.
3330 If the current word is preceded by a backslash, completes the TeX symbols
3331 that are supported for HTML support.
3332 If the current word is preceded by \"#+\", completes special words for
3333 setting file options.
3334 At all other locations, this simply calls `ispell-complete-word'."
3335 (interactive "P")
3336 (catch 'exit
3337 (let* ((end (point))
3338 (beg1 (save-excursion
3339 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3340 (skip-chars-backward "a-zA-Z_@0-9")
3341 (point)))
3342 (beg (save-excursion
3343 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3344 (skip-chars-backward "a-zA-Z0-9_:$")
3345 (point)))
3346 (camel (equal (char-before beg) ?*))
3347 (tag (equal (char-before beg1) ?:))
3348 (texp (equal (char-before beg) ?\\))
3349 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3350 beg)
3351 "#+"))
3352 (completion-ignore-case opt)
3353 (type nil)
3354 (tbl nil)
3355 (table (cond
3356 (opt
3357 (setq type :opt)
3358 (mapcar (lambda (x)
3359 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3360 (cons (match-string 2 x) (match-string 1 x)))
3361 (org-split-string (org-get-current-options) "\n")))
3362 (texp
3363 (setq type :tex)
3364 org-html-entities)
3365 ((string-match "\\`\\*+[ \t]*\\'"
3366 (buffer-substring (point-at-bol) beg))
3367 (setq type :todo)
3368 (mapcar 'list org-todo-keywords))
3369 (camel
3370 (setq type :camel)
3371 (save-excursion
3372 (goto-char (point-min))
3373 (while (re-search-forward org-todo-line-regexp nil t)
3374 (push (list
3375 (if org-file-link-context-use-camel-case
3376 (org-make-org-heading-camel (match-string 3) t)
3377 (org-make-org-heading-search-string
3378 (match-string 3) t)))
3379 tbl)))
3380 tbl)
3381 (tag (setq type :tag beg beg1)
3382 (org-get-buffer-tags))
3383 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3384 (pattern (buffer-substring-no-properties beg end))
3385 (completion (try-completion pattern table)))
3386 (cond ((eq completion t)
3387 (if (equal type :opt)
3388 (insert (substring (cdr (assoc (upcase pattern) table))
3389 (length pattern)))))
3390 ((null completion)
3391 (message "Can't find completion for \"%s\"" pattern)
3392 (ding))
3393 ((not (string= pattern completion))
3394 (delete-region beg end)
3395 (if (string-match " +$" completion)
3396 (setq completion (replace-match "" t t completion)))
3397 (insert completion)
3398 (if (get-buffer-window "*Completions*")
3399 (delete-window (get-buffer-window "*Completions*")))
3400 (if (assoc completion table)
3401 (if (eq type :todo) (insert " ")
3402 (if (eq type :tag) (insert ":"))))
3403 (if (and (equal type :opt) (assoc completion table))
3404 (message "%s" (substitute-command-keys
3405 "Press \\[org-complete] again to insert example settings"))))
3406 (t
3407 (message "Making completion list...")
3408 (let ((list (sort (all-completions pattern table) 'string<)))
3409 (with-output-to-temp-buffer "*Completions*"
3410 (display-completion-list list)))
3411 (message "Making completion list...%s" "done"))))))
3412
3413 ;;; Comments, TODO and DEADLINE
3414
3415 (defun org-toggle-comment ()
3416 "Change the COMMENT state of an entry."
3417 (interactive)
3418 (save-excursion
3419 (org-back-to-heading)
3420 (if (looking-at (concat outline-regexp
3421 "\\( +\\<" org-comment-string "\\>\\)"))
3422 (replace-match "" t t nil 1)
3423 (if (looking-at outline-regexp)
3424 (progn
3425 (goto-char (match-end 0))
3426 (insert " " org-comment-string))))))
3427
3428 (defvar org-last-todo-state-is-todo nil
3429 "This is non-nil when the last TODO state change led to a TODO state.
3430 If the last change removed the TODO tag or switched to DONE, then
3431 this is nil.")
3432
3433 (defun org-todo (&optional arg)
3434 "Change the TODO state of an item.
3435 The state of an item is given by a keyword at the start of the heading,
3436 like
3437 *** TODO Write paper
3438 *** DONE Call mom
3439
3440 The different keywords are specified in the variable `org-todo-keywords'.
3441 By default the available states are \"TODO\" and \"DONE\".
3442 So for this example: when the item starts with TODO, it is changed to DONE.
3443 When it starts with DONE, the DONE is removed. And when neither TODO nor
3444 DONE are present, add TODO at the beginning of the heading.
3445
3446 With prefix arg, use completion to determine the new state. With numeric
3447 prefix arg, switch to that state."
3448 (interactive "P")
3449 (save-excursion
3450 (org-back-to-heading)
3451 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3452 (or (looking-at (concat " +" org-todo-regexp " *"))
3453 (looking-at " *"))
3454 (let* ((this (match-string 1))
3455 (completion-ignore-case t)
3456 (member (member this org-todo-keywords))
3457 (tail (cdr member))
3458 (state (cond
3459 ((equal arg '(4))
3460 ;; Read a state with completion
3461 (completing-read "State: " (mapcar (lambda(x) (list x))
3462 org-todo-keywords)
3463 nil t))
3464 ((eq arg 'right)
3465 (if this
3466 (if tail (car tail) nil)
3467 (car org-todo-keywords)))
3468 ((eq arg 'left)
3469 (if (equal member org-todo-keywords)
3470 nil
3471 (if this
3472 (nth (- (length org-todo-keywords) (length tail) 2)
3473 org-todo-keywords)
3474 org-done-string)))
3475 (arg
3476 ;; user requests a specific state
3477 (nth (1- (prefix-numeric-value arg))
3478 org-todo-keywords))
3479 ((null member) (car org-todo-keywords))
3480 ((null tail) nil) ;; -> first entry
3481 ((eq org-todo-interpretation 'sequence)
3482 (car tail))
3483 ((memq org-todo-interpretation '(type priority))
3484 (if (eq this-command last-command)
3485 (car tail)
3486 (if (> (length tail) 0) org-done-string nil)))
3487 (t nil)))
3488 (next (if state (concat " " state " ") " ")))
3489 (replace-match next t t)
3490 (setq org-last-todo-state-is-todo
3491 (not (equal state org-done-string)))
3492 (when org-log-done
3493 (if (equal state org-done-string)
3494 (org-log-done)
3495 (if (not this)
3496 (org-log-done t))))
3497 ;; Fixup tag positioning
3498 (and org-auto-align-tags (org-set-tags nil t))
3499 (run-hooks 'org-after-todo-state-change-hook)))
3500 ;; Fixup cursor location if close to the keyword
3501 (if (and (outline-on-heading-p)
3502 (not (bolp))
3503 (save-excursion (beginning-of-line 1)
3504 (looking-at org-todo-line-regexp))
3505 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3506 (progn
3507 (goto-char (or (match-end 2) (match-end 1)))
3508 (just-one-space))))
3509
3510 (defun org-log-done (&optional undone)
3511 "Add a time stamp logging that a TODO entry has been closed.
3512 When UNDONE is non-nil, remove such a time stamp again."
3513 (interactive)
3514 (let (beg end col)
3515 (save-excursion
3516 (org-back-to-heading t)
3517 (setq beg (point))
3518 (looking-at (concat outline-regexp " *"))
3519 (goto-char (match-end 0))
3520 (setq col (current-column))
3521 (outline-next-heading)
3522 (setq end (point))
3523 (goto-char beg)
3524 (when (re-search-forward (concat
3525 "[\r\n]\\([ \t]*"
3526 (regexp-quote org-closed-string)
3527 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3528 (delete-region (match-beginning 1) (match-end 1)))
3529 (unless undone
3530 (org-back-to-heading t)
3531 (skip-chars-forward "^\n\r")
3532 (goto-char (min (1+ (point)) (point-max)))
3533 (when (not (member (char-before) '(?\r ?\n)))
3534 (insert "\n"))
3535 (indent-to col)
3536 (insert org-closed-string " "
3537 (format-time-string
3538 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3539 (current-time))
3540 "\n")))))
3541
3542 (defun org-show-todo-tree (arg)
3543 "Make a compact tree which shows all headlines marked with TODO.
3544 The tree will show the lines where the regexp matches, and all higher
3545 headlines above the match.
3546 With \\[universal-argument] prefix, also show the DONE entries.
3547 With a numeric prefix N, construct a sparse tree for the Nth element
3548 of `org-todo-keywords'."
3549 (interactive "P")
3550 (let ((case-fold-search nil)
3551 (kwd-re
3552 (cond ((null arg) org-not-done-regexp)
3553 ((equal arg '(4)) org-todo-regexp)
3554 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3555 (regexp-quote (nth (1- (prefix-numeric-value arg))
3556 org-todo-keywords)))
3557 (t (error "Invalid prefix argument: %s" arg)))))
3558 (message "%d TODO entries found"
3559 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3560
3561 (defun org-deadline ()
3562 "Insert the DEADLINE: string to make a deadline.
3563 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3564 to modify it to the correct date."
3565 (interactive)
3566 (insert
3567 org-deadline-string " "
3568 (format-time-string (car org-time-stamp-formats)
3569 (org-read-date nil 'to-time)))
3570 (message "%s" (substitute-command-keys
3571 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3572
3573 (defun org-schedule ()
3574 "Insert the SCHEDULED: string to schedule a TODO item.
3575 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3576 to modify it to the correct date."
3577 (interactive)
3578 (insert
3579 org-scheduled-string " "
3580 (format-time-string (car org-time-stamp-formats)
3581 (org-read-date nil 'to-time)))
3582 (message "%s" (substitute-command-keys
3583 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3584
3585
3586 (defun org-occur (regexp &optional callback)
3587 "Make a compact tree which shows all matches of REGEXP.
3588 The tree will show the lines where the regexp matches, and all higher
3589 headlines above the match. It will also show the heading after the match,
3590 to make sure editing the matching entry is easy.
3591 If CALLBACK is non-nil, it is a function which is called to confirm
3592 that the match should indeed be shown."
3593 (interactive "sRegexp: ")
3594 (org-remove-occur-highlights nil nil t)
3595 (setq regexp (org-check-occur-regexp regexp))
3596 (let ((cnt 0))
3597 (save-excursion
3598 (goto-char (point-min))
3599 (hide-sublevels 1)
3600 (while (re-search-forward regexp nil t)
3601 (when (or (not callback)
3602 (save-match-data (funcall callback)))
3603 (setq cnt (1+ cnt))
3604 (org-highlight-new-match (match-beginning 0) (match-end 0))
3605 (org-show-hierarchy-above))))
3606 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
3607 nil 'local)
3608 (run-hooks 'org-occur-hook)
3609 (if (interactive-p)
3610 (message "%d match(es) for regexp %s" cnt regexp))
3611 cnt))
3612
3613 (defun org-show-hierarchy-above ()
3614 "Make sure point and the headings hierarchy above is visible."
3615 (catch 'exit
3616 (if (org-on-heading-p t)
3617 (org-flag-heading nil) ; only show the heading
3618 (and (or (org-invisible-p) (org-invisible-p2))
3619 (org-show-hidden-entry))) ; show entire entry
3620 (save-excursion
3621 (and org-show-following-heading
3622 (outline-next-heading)
3623 (org-flag-heading nil))) ; show the next heading
3624 (when org-show-hierarchy-above
3625 (save-excursion ; show all higher headings
3626 (while (and (condition-case nil
3627 (progn (org-up-heading-all 1) t)
3628 (error nil))
3629 (not (bobp)))
3630 (org-flag-heading nil))))))
3631
3632 ;; Overlay compatibility functions
3633 (defun org-make-overlay (beg end &optional buffer)
3634 (if org-xemacs-p (make-extent beg end buffer) (make-overlay beg end buffer)))
3635 (defun org-delete-overlay (ovl)
3636 (if org-xemacs-p (delete-extent ovl) (delete-overlay ovl)))
3637 (defun org-detatch-overlay (ovl)
3638 (if org-xemacs-p (detach-extent ovl) (delete-overlay ovl)))
3639 (defun org-move-overlay (ovl beg end &optional buffer)
3640 (if org-xemacs-p
3641 (set-extent-endpoints ovl beg end buffer)
3642 (move-overlay ovl beg end buffer)))
3643 (defun org-overlay-put (ovl prop value)
3644 (if org-xemacs-p
3645 (set-extent-property ovl prop value)
3646 (overlay-put ovl prop value)))
3647
3648 (defvar org-occur-highlights nil)
3649 (defun org-highlight-new-match (beg end)
3650 "Highlight from BEG to END and mark the highlight is an occur headline."
3651 (let ((ov (org-make-overlay beg end)))
3652 (org-overlay-put ov 'face 'secondary-selection)
3653 (push ov org-occur-highlights)))
3654
3655 (defun org-remove-occur-highlights (&optional beg end noremove)
3656 "Remove the occur highlights from the buffer.
3657 BEG and END are ignored. If NOREMOVE is nil, remove this function
3658 from the `before-change-functions' in the current buffer."
3659 (interactive)
3660 (mapc 'org-delete-overlay org-occur-highlights)
3661 (setq org-occur-highlights nil)
3662 (unless noremove
3663 (remove-hook 'before-change-functions
3664 'org-remove-occur-highlights 'local)))
3665
3666 ;;; Priorities
3667
3668 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3669 "Regular expression matching the priority indicator.")
3670
3671 (defvar org-remove-priority-next-time nil)
3672
3673 (defun org-priority-up ()
3674 "Increase the priority of the current item."
3675 (interactive)
3676 (org-priority 'up))
3677
3678 (defun org-priority-down ()
3679 "Decrease the priority of the current item."
3680 (interactive)
3681 (org-priority 'down))
3682
3683 (defun org-priority (&optional action)
3684 "Change the priority of an item by ARG.
3685 ACTION can be set, up, or down."
3686 (interactive)
3687 (setq action (or action 'set))
3688 (let (current new news have remove)
3689 (save-excursion
3690 (org-back-to-heading)
3691 (if (looking-at org-priority-regexp)
3692 (setq current (string-to-char (match-string 2))
3693 have t)
3694 (setq current org-default-priority))
3695 (cond
3696 ((eq action 'set)
3697 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3698 (setq new (read-char-exclusive))
3699 (cond ((equal new ?\ ) (setq remove t))
3700 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3701 (error "Priority must be between `%c' and `%c'"
3702 ?A org-lowest-priority))))
3703 ((eq action 'up)
3704 (setq new (1- current)))
3705 ((eq action 'down)
3706 (setq new (1+ current)))
3707 (t (error "Invalid action")))
3708 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3709 (setq news (format "%c" new))
3710 (if have
3711 (if remove
3712 (replace-match "" t t nil 1)
3713 (replace-match news t t nil 2))
3714 (if remove
3715 (error "No priority cookie found in line")
3716 (looking-at org-todo-line-regexp)
3717 (if (match-end 2)
3718 (progn
3719 (goto-char (match-end 2))
3720 (insert " [#" news "]"))
3721 (goto-char (match-beginning 3))
3722 (insert "[#" news "] ")))))
3723 (if remove
3724 (message "Priority removed")
3725 (message "Priority of current item set to %s" news))))
3726
3727
3728 (defun org-get-priority (s)
3729 "Find priority cookie and return priority."
3730 (save-match-data
3731 (if (not (string-match org-priority-regexp s))
3732 (* 1000 (- org-lowest-priority org-default-priority))
3733 (* 1000 (- org-lowest-priority
3734 (string-to-char (match-string 2 s)))))))
3735
3736 ;;; Timestamps
3737
3738 (defvar org-last-changed-timestamp nil)
3739
3740 (defun org-time-stamp (arg)
3741 "Prompt for a date/time and insert a time stamp.
3742 If the user specifies a time like HH:MM, or if this command is called
3743 with a prefix argument, the time stamp will contain date and time.
3744 Otherwise, only the date will be included. All parts of a date not
3745 specified by the user will be filled in from the current date/time.
3746 So if you press just return without typing anything, the time stamp
3747 will represent the current date/time. If there is already a timestamp
3748 at the cursor, it will be modified."
3749 (interactive "P")
3750 (let ((fmt (if arg (cdr org-time-stamp-formats)
3751 (car org-time-stamp-formats)))
3752 (org-time-was-given nil)
3753 time)
3754 (cond
3755 ((and (org-at-timestamp-p)
3756 (eq last-command 'org-time-stamp)
3757 (eq this-command 'org-time-stamp))
3758 (insert "--")
3759 (setq time (let ((this-command this-command))
3760 (org-read-date arg 'totime)))
3761 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3762 (insert (format-time-string fmt time)))
3763 ((org-at-timestamp-p)
3764 (setq time (let ((this-command this-command))
3765 (org-read-date arg 'totime)))
3766 (and (org-at-timestamp-p) (replace-match
3767 (setq org-last-changed-timestamp
3768 (format-time-string fmt time))
3769 t t))
3770 (message "Timestamp updated"))
3771 (t
3772 (setq time (let ((this-command this-command))
3773 (org-read-date arg 'totime)))
3774 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3775 (insert (format-time-string fmt time))))))
3776
3777 (defun org-time-stamp-inactive (&optional arg)
3778 "Insert an inactive time stamp.
3779 An inactive time stamp is enclosed in square brackets instead of angle
3780 brackets. It is inactive in the sense that it does not trigger agenda entries,
3781 does not link to the calendar and cannot be changed with the S-cursor keys.
3782 So these are more for recording a certain time/date."
3783 ;; FIXME: Would it be better not to ask for a date/time here?
3784 (interactive "P")
3785 (let ((fmt (if arg (cdr org-time-stamp-formats)
3786 (car org-time-stamp-formats)))
3787 (org-time-was-given nil)
3788 time)
3789 (setq time (org-read-date arg 'totime))
3790 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3791 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3792 (insert (format-time-string fmt time))))
3793
3794 (defvar org-date-ovl (org-make-overlay 1 1))
3795 (org-overlay-put org-date-ovl 'face 'org-warning)
3796 (org-detatch-overlay org-date-ovl)
3797
3798 ;;; FIXME: Make the function take "Fri" as "next friday"
3799 ;;; because these are mostly being used to record the current time.
3800 (defun org-read-date (&optional with-time to-time)
3801 "Read a date and make things smooth for the user.
3802 The prompt will suggest to enter an ISO date, but you can also enter anything
3803 which will at least partially be understood by `parse-time-string'.
3804 Unrecognized parts of the date will default to the current day, month, year,
3805 hour and minute. For example,
3806 3-2-5 --> 2003-02-05
3807 feb 15 --> currentyear-02-15
3808 sep 12 9 --> 2009-09-12
3809 12:45 --> today 12:45
3810 22 sept 0:34 --> currentyear-09-22 0:34
3811 12 --> currentyear-currentmonth-12
3812 etc.
3813 The function understands only English month and weekday abbreviations,
3814 but this can be configured with the variables `parse-time-months' and
3815 `parse-time-weekdays'.
3816
3817 While prompting, a calendar is popped up - you can also select the
3818 date with the mouse (button 1). The calendar shows a period of three
3819 months. To scroll it to other months, use the keys `>' and `<'.
3820 If you don't like the calendar, turn it off with
3821 \(setq org-popup-calendar-for-date-prompt nil)
3822
3823 With optional argument TO-TIME, the date will immediately be converted
3824 to an internal time.
3825 With an optional argument WITH-TIME, the prompt will suggest to also
3826 insert a time. Note that when WITH-TIME is not set, you can still
3827 enter a time, and this function will inform the calling routine about
3828 this change. The calling routine may then choose to change the format
3829 used to insert the time stamp into the buffer to include the time."
3830 (let* ((default-time
3831 ;; Default time is either today, or, when entering a range,
3832 ;; the range start.
3833 (if (save-excursion
3834 (re-search-backward
3835 (concat org-ts-regexp "--\\=")
3836 (- (point) 20) t))
3837 (apply
3838 'encode-time
3839 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3840 (parse-time-string (match-string 1))))
3841 (current-time)))
3842 (calendar-move-hook nil)
3843 (view-diary-entries-initially nil)
3844 (timestr (format-time-string
3845 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3846 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3847 ans ans1 ans2
3848 second minute hour day month year tl)
3849
3850 (if org-popup-calendar-for-date-prompt
3851 ;; Also show a calendar for date selection
3852 ;; Copied (with modifications) from planner.el by John Wiegley
3853 (save-excursion
3854 (save-window-excursion
3855 (calendar)
3856 (calendar-forward-day (- (time-to-days default-time)
3857 (calendar-absolute-from-gregorian
3858 (calendar-current-date))))
3859 (org-eval-in-calendar nil)
3860 (let* ((old-map (current-local-map))
3861 (map (copy-keymap calendar-mode-map))
3862 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3863 (define-key map (kbd "RET") 'org-calendar-select)
3864 (define-key map (if org-xemacs-p [button1] [mouse-1])
3865 'org-calendar-select-mouse)
3866 (define-key map (if org-xemacs-p [button2] [mouse-2])
3867 'org-calendar-select-mouse)
3868 (define-key minibuffer-local-map [(meta shift left)]
3869 (lambda () (interactive)
3870 (org-eval-in-calendar '(calendar-backward-month 1))))
3871 (define-key minibuffer-local-map [(meta shift right)]
3872 (lambda () (interactive)
3873 (org-eval-in-calendar '(calendar-forward-month 1))))
3874 (define-key minibuffer-local-map [(shift up)]
3875 (lambda () (interactive)
3876 (org-eval-in-calendar '(calendar-backward-week 1))))
3877 (define-key minibuffer-local-map [(shift down)]
3878 (lambda () (interactive)
3879 (org-eval-in-calendar '(calendar-forward-week 1))))
3880 (define-key minibuffer-local-map [(shift left)]
3881 (lambda () (interactive)
3882 (org-eval-in-calendar '(calendar-backward-day 1))))
3883 (define-key minibuffer-local-map [(shift right)]
3884 (lambda () (interactive)
3885 (org-eval-in-calendar '(calendar-forward-day 1))))
3886 (define-key minibuffer-local-map ">"
3887 (lambda () (interactive)
3888 (org-eval-in-calendar '(scroll-calendar-left 1))))
3889 (define-key minibuffer-local-map "<"
3890 (lambda () (interactive)
3891 (org-eval-in-calendar '(scroll-calendar-right 1))))
3892 (unwind-protect
3893 (progn
3894 (use-local-map map)
3895 (setq ans (read-string prompt "" nil nil))
3896 (if (not (string-match "\\S-" ans)) (setq ans nil))
3897 (setq ans (or ans1 ans ans2)))
3898 (use-local-map old-map)))))
3899 ;; Naked prompt only
3900 (setq ans (read-string prompt "" nil timestr)))
3901 (org-detatch-overlay org-date-ovl)
3902
3903 (if (string-match
3904 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3905 (progn
3906 (setq year (if (match-end 2)
3907 (string-to-number (match-string 2 ans))
3908 (string-to-number (format-time-string "%Y")))
3909 month (string-to-number (match-string 3 ans))
3910 day (string-to-number (match-string 4 ans)))
3911 (if (< year 100) (setq year (+ 2000 year)))
3912 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3913 t t ans))))
3914 (setq tl (parse-time-string ans)
3915 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3916 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3917 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3918 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3919 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3920 second (or (nth 0 tl) 0))
3921 (if (and (boundp 'org-time-was-given)
3922 (nth 2 tl))
3923 (setq org-time-was-given t))
3924 (if (< year 100) (setq year (+ 2000 year)))
3925 (if to-time
3926 (encode-time second minute hour day month year)
3927 (if (or (nth 1 tl) (nth 2 tl))
3928 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3929 (format "%04d-%02d-%02d" year month day)))))
3930
3931 (defun org-eval-in-calendar (form)
3932 "Eval FORM in the calendar window and return to current window.
3933 Also, store the cursor date in variable ans2."
3934 (let ((sw (selected-window)))
3935 (select-window (get-buffer-window "*Calendar*"))
3936 (eval form)
3937 (when (calendar-cursor-to-date)
3938 (let* ((date (calendar-cursor-to-date))
3939 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3940 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3941 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
3942 (select-window sw)))
3943
3944 (defun org-calendar-select ()
3945 "Return to `org-read-date' with the date currently selected.
3946 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3947 (interactive)
3948 (when (calendar-cursor-to-date)
3949 (let* ((date (calendar-cursor-to-date))
3950 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3951 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3952 (if (active-minibuffer-window) (exit-minibuffer))))
3953
3954 (defun org-calendar-select-mouse (ev)
3955 "Return to `org-read-date' with the date currently selected.
3956 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3957 (interactive "e")
3958 (mouse-set-point ev)
3959 (when (calendar-cursor-to-date)
3960 (let* ((date (calendar-cursor-to-date))
3961 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3962 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3963 (if (active-minibuffer-window) (exit-minibuffer))))
3964
3965 (defun org-check-deadlines (ndays)
3966 "Check if there are any deadlines due or past due.
3967 A deadline is considered due if it happens within `org-deadline-warning-days'
3968 days from today's date. If the deadline appears in an entry marked DONE,
3969 it is not shown. The prefix arg NDAYS can be used to test that many
3970 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3971 (interactive "P")
3972 (let* ((org-warn-days
3973 (cond
3974 ((equal ndays '(4)) 100000)
3975 (ndays (prefix-numeric-value ndays))
3976 (t org-deadline-warning-days)))
3977 (case-fold-search nil)
3978 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3979 (callback
3980 (lambda ()
3981 (and (let ((d1 (time-to-days (current-time)))
3982 (d2 (time-to-days
3983 (org-time-string-to-time (match-string 1)))))
3984 (< (- d2 d1) org-warn-days))
3985 (not (org-entry-is-done-p))))))
3986 (message "%d deadlines past-due or due within %d days"
3987 (org-occur regexp callback)
3988 org-warn-days)))
3989
3990 (defun org-evaluate-time-range (&optional to-buffer)
3991 "Evaluate a time range by computing the difference between start and end.
3992 Normally the result is just printed in the echo area, but with prefix arg
3993 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3994 If the time range is actually in a table, the result is inserted into the
3995 next column.
3996 For time difference computation, a year is assumed to be exactly 365
3997 days in order to avoid rounding problems."
3998 (interactive "P")
3999 (save-excursion
4000 (unless (org-at-date-range-p)
4001 (goto-char (point-at-bol))
4002 (re-search-forward org-tr-regexp (point-at-eol) t))
4003 (if (not (org-at-date-range-p))
4004 (error "Not at a time-stamp range, and none found in current line")))
4005 (let* ((ts1 (match-string 1))
4006 (ts2 (match-string 2))
4007 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4008 (match-end (match-end 0))
4009 (time1 (org-time-string-to-time ts1))
4010 (time2 (org-time-string-to-time ts2))
4011 (t1 (time-to-seconds time1))
4012 (t2 (time-to-seconds time2))
4013 (diff (abs (- t2 t1)))
4014 (negative (< (- t2 t1) 0))
4015 ;; (ys (floor (* 365 24 60 60)))
4016 (ds (* 24 60 60))
4017 (hs (* 60 60))
4018 (fy "%dy %dd %02d:%02d")
4019 (fy1 "%dy %dd")
4020 (fd "%dd %02d:%02d")
4021 (fd1 "%dd")
4022 (fh "%02d:%02d")
4023 y d h m align)
4024 ;; FIXME: Should I re-introduce years, make year refer to same date?
4025 ;; This would be the only useful way to have years, actually.
4026 (if havetime
4027 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4028 y 0
4029 d (floor (/ diff ds)) diff (mod diff ds)
4030 h (floor (/ diff hs)) diff (mod diff hs)
4031 m (floor (/ diff 60)))
4032 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4033 y 0
4034 d (floor (+ (/ diff ds) 0.5))
4035 h 0 m 0))
4036 (if (not to-buffer)
4037 (message (org-make-tdiff-string y d h m))
4038 (when (org-at-table-p)
4039 (goto-char match-end)
4040 (setq align t)
4041 (and (looking-at " *|") (goto-char (match-end 0))))
4042 (if (looking-at
4043 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4044 (replace-match ""))
4045 (if negative (insert " -"))
4046 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4047 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4048 (insert " " (format fh h m))))
4049 (if align (org-table-align))
4050 (message "Time difference inserted"))))
4051
4052 (defun org-make-tdiff-string (y d h m)
4053 (let ((fmt "")
4054 (l nil))
4055 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4056 l (push y l)))
4057 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4058 l (push d l)))
4059 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4060 l (push h l)))
4061 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4062 l (push m l)))
4063 (apply 'format fmt (nreverse l))))
4064
4065 (defun org-time-string-to-time (s)
4066 (apply 'encode-time (org-parse-time-string s)))
4067
4068 (defun org-parse-time-string (s &optional nodefault)
4069 "Parse the standard Org-mode time string.
4070 This should be a lot faster than the normal `parse-time-string'.
4071 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4072 hour and minute fields will be nil if not given."
4073 (if (string-match org-ts-regexp1 s)
4074 (list 0
4075 (if (or (match-beginning 8) (not nodefault))
4076 (string-to-number (or (match-string 8 s) "0")))
4077 (if (or (match-beginning 7) (not nodefault))
4078 (string-to-number (or (match-string 7 s) "0")))
4079 (string-to-number (match-string 4 s))
4080 (string-to-number (match-string 3 s))
4081 (string-to-number (match-string 2 s))
4082 nil nil nil)
4083 (make-list 9 0)))
4084
4085 (defun org-timestamp-up (&optional arg)
4086 "Increase the date item at the cursor by one.
4087 If the cursor is on the year, change the year. If it is on the month or
4088 the day, change that.
4089 With prefix ARG, change by that many units."
4090 (interactive "p")
4091 (org-timestamp-change (prefix-numeric-value arg)))
4092
4093 (defun org-timestamp-down (&optional arg)
4094 "Decrease the date item at the cursor by one.
4095 If the cursor is on the year, change the year. If it is on the month or
4096 the day, change that.
4097 With prefix ARG, change by that many units."
4098 (interactive "p")
4099 (org-timestamp-change (- (prefix-numeric-value arg))))
4100
4101 (defun org-timestamp-up-day (&optional arg)
4102 "Increase the date in the time stamp by one day.
4103 With prefix ARG, change that many days."
4104 (interactive "p")
4105 (if (and (not (org-at-timestamp-p))
4106 (org-on-heading-p))
4107 (org-todo 'up)
4108 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4109
4110 (defun org-timestamp-down-day (&optional arg)
4111 "Decrease the date in the time stamp by one day.
4112 With prefix ARG, change that many days."
4113 (interactive "p")
4114 (if (and (not (org-at-timestamp-p))
4115 (org-on-heading-p))
4116 (org-todo 'down)
4117 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4118
4119 (defsubst org-pos-in-match-range (pos n)
4120 (and (match-beginning n)
4121 (<= (match-beginning n) pos)
4122 (>= (match-end n) pos)))
4123
4124 (defun org-at-timestamp-p ()
4125 "Determine if the cursor is in or at a timestamp."
4126 (interactive)
4127 (let* ((tsr org-ts-regexp2)
4128 (pos (point))
4129 (ans (or (looking-at tsr)
4130 (save-excursion
4131 (skip-chars-backward "^<\n\r\t")
4132 (if (> (point) 1) (backward-char 1))
4133 (and (looking-at tsr)
4134 (> (- (match-end 0) pos) -1))))))
4135 (and (boundp 'org-ts-what)
4136 (setq org-ts-what
4137 (cond
4138 ((org-pos-in-match-range pos 2) 'year)
4139 ((org-pos-in-match-range pos 3) 'month)
4140 ((org-pos-in-match-range pos 7) 'hour)
4141 ((org-pos-in-match-range pos 8) 'minute)
4142 ((or (org-pos-in-match-range pos 4)
4143 (org-pos-in-match-range pos 5)) 'day)
4144 (t 'day))))
4145 ans))
4146
4147 (defun org-timestamp-change (n &optional what)
4148 "Change the date in the time stamp at point.
4149 The date will be changed by N times WHAT. WHAT can be `day', `month',
4150 `year', `minute', `second'. If WHAT is not given, the cursor position
4151 in the timestamp determines what will be changed."
4152 (let ((fmt (car org-time-stamp-formats))
4153 org-ts-what
4154 (pos (point))
4155 ts time time0)
4156 (if (not (org-at-timestamp-p))
4157 (error "Not at a timestamp"))
4158 (setq org-ts-what (or what org-ts-what))
4159 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4160 (- (match-end 0) (match-beginning 0))))
4161 1)
4162 (cdr org-time-stamp-formats)
4163 (car org-time-stamp-formats)))
4164 (setq ts (match-string 0))
4165 (replace-match "")
4166 (setq time0 (org-parse-time-string ts))
4167 (setq time
4168 (apply 'encode-time
4169 (append
4170 (list (or (car time0) 0))
4171 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4172 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4173 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4174 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4175 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4176 (nthcdr 6 time0))))
4177 (if (eq what 'calendar)
4178 (let ((cal-date
4179 (save-excursion
4180 (save-match-data
4181 (set-buffer "*Calendar*")
4182 (calendar-cursor-to-date)))))
4183 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4184 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4185 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4186 (setcar time0 (or (car time0) 0))
4187 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4188 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4189 (setq time (apply 'encode-time time0))))
4190 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4191 (goto-char pos)
4192 ;; Try to recenter the calendar window, if any
4193 (if (and org-calendar-follow-timestamp-change
4194 (get-buffer-window "*Calendar*" t)
4195 (memq org-ts-what '(day month year)))
4196 (org-recenter-calendar (time-to-days time)))))
4197
4198 (defun org-recenter-calendar (date)
4199 "If the calendar is visible, recenter it to DATE."
4200 (let* ((win (selected-window))
4201 (cwin (get-buffer-window "*Calendar*" t))
4202 (calendar-move-hook nil))
4203 (when cwin
4204 (select-window cwin)
4205 (calendar-goto-date (if (listp date) date
4206 (calendar-gregorian-from-absolute date)))
4207 (select-window win))))
4208
4209 (defun org-goto-calendar (&optional arg)
4210 "Go to the Emacs calendar at the current date.
4211 If there is a time stamp in the current line, go to that date.
4212 A prefix ARG can be used to force the current date."
4213 (interactive "P")
4214 (let ((tsr org-ts-regexp) diff
4215 (calendar-move-hook nil)
4216 (view-diary-entries-initially nil))
4217 (if (or (org-at-timestamp-p)
4218 (save-excursion
4219 (beginning-of-line 1)
4220 (looking-at (concat ".*" tsr))))
4221 (let ((d1 (time-to-days (current-time)))
4222 (d2 (time-to-days
4223 (org-time-string-to-time (match-string 1)))))
4224 (setq diff (- d2 d1))))
4225 (calendar)
4226 (calendar-goto-today)
4227 (if (and diff (not arg)) (calendar-forward-day diff))))
4228
4229 (defun org-date-from-calendar ()
4230 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4231 If there is already a time stamp at the cursor position, update it."
4232 (interactive)
4233 (org-timestamp-change 0 'calendar))
4234
4235 ;;; Agenda, and Diary Integration
4236
4237 ;;; Define the mode
4238
4239 (defvar org-agenda-mode-map (make-sparse-keymap)
4240 "Keymap for `org-agenda-mode'.")
4241
4242 (defvar org-agenda-menu)
4243 (defvar org-agenda-follow-mode nil)
4244 (defvar org-agenda-show-log nil)
4245 (defvar org-agenda-buffer-name "*Org Agenda*")
4246 (defvar org-agenda-redo-command nil)
4247 (defvar org-agenda-mode-hook nil)
4248 (defvar org-agenda-type nil)
4249 (defvar org-agenda-force-single-file nil)
4250
4251 ;;;###autoload
4252 (defun org-agenda-mode ()
4253 "Mode for time-sorted view on action items in Org-mode files.
4254
4255 The following commands are available:
4256
4257 \\{org-agenda-mode-map}"
4258 (interactive)
4259 (kill-all-local-variables)
4260 (setq major-mode 'org-agenda-mode)
4261 (setq mode-name "Org-Agenda")
4262 (use-local-map org-agenda-mode-map)
4263 (easy-menu-add org-agenda-menu)
4264 (if org-startup-truncated (setq truncate-lines t))
4265 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4266 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4267 (unless org-agenda-keep-modes
4268 (setq org-agenda-follow-mode nil
4269 org-agenda-show-log nil))
4270 (easy-menu-change
4271 '("Agenda") "Agenda Files"
4272 (append
4273 (list
4274 (vector
4275 (if (get 'org-agenda-files 'org-restrict)
4276 "Restricted to single file"
4277 "Edit File List")
4278 '(customize-variable 'org-agenda-files)
4279 (not (get 'org-agenda-files 'org-restrict)))
4280 "--")
4281 (mapcar 'org-file-menu-entry (org-agenda-files))))
4282 (org-agenda-set-mode-name)
4283 (apply
4284 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4285 (list 'org-agenda-mode-hook)))
4286
4287 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4288 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4289 (define-key org-agenda-mode-map " " 'org-agenda-show)
4290 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4291 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4292 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4293 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4294 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4295 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4296 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4297 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4298 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4299 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4300 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4301 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4302
4303 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4304 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4305 (while l (define-key org-agenda-mode-map
4306 (int-to-string (pop l)) 'digit-argument)))
4307
4308 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4309 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4310 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4311 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4312 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4313 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4314 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4315 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4316 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4317 (define-key org-agenda-mode-map "n" 'next-line)
4318 (define-key org-agenda-mode-map "p" 'previous-line)
4319 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4320 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4321 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4322 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4323 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4324 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4325 (eval-after-load "calendar"
4326 '(define-key calendar-mode-map org-calendar-to-agenda-key
4327 'org-calendar-goto-agenda))
4328 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4329 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4330 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4331 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4332 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4333 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4334 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4335 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4336 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4337 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4338 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4339 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4340 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4341 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4342 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4343 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4344 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4345 "Local keymap for agenda entries from Org-mode.")
4346
4347 (define-key org-agenda-keymap
4348 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4349 (define-key org-agenda-keymap
4350 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4351
4352 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4353 '("Agenda"
4354 ("Agenda Files")
4355 "--"
4356 ["Show" org-agenda-show t]
4357 ["Go To (other window)" org-agenda-goto t]
4358 ["Go To (one window)" org-agenda-switch-to t]
4359 ["Follow Mode" org-agenda-follow-mode
4360 :style toggle :selected org-agenda-follow-mode :active t]
4361 "--"
4362 ["Cycle TODO" org-agenda-todo t]
4363 ("Tags"
4364 ["Show all Tags" org-agenda-show-tags t]
4365 ["Set Tags" org-agenda-set-tags t])
4366 ("Reschedule"
4367 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4368 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4369 "--"
4370 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4371 ("Priority"
4372 ["Set Priority" org-agenda-priority t]
4373 ["Increase Priority" org-agenda-priority-up t]
4374 ["Decrease Priority" org-agenda-priority-down t]
4375 ["Show Priority" org-agenda-show-priority t])
4376 "--"
4377 ;; ["New agenda command" org-agenda t]
4378 ["Rebuild buffer" org-agenda-redo t]
4379 "--"
4380 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4381 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4382 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4383 "--"
4384 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4385 :style radio :selected (equal org-agenda-ndays 1)]
4386 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4387 :style radio :selected (equal org-agenda-ndays 7)]
4388 "--"
4389 ["Show Logbook entries" org-agenda-log-mode
4390 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4391 ["Include Diary" org-agenda-toggle-diary
4392 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4393 ["Use Time Grid" org-agenda-toggle-time-grid
4394 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4395 "--"
4396 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4397 ("Calendar Commands"
4398 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4399 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4400 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4401 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4402 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4403 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4404 "--"
4405 ["Quit" org-agenda-quit t]
4406 ["Exit and Release Buffers" org-agenda-exit t]
4407 ))
4408
4409 ;;;###autoload
4410 (defun org-agenda (arg)
4411 "Dispatch agenda commands to collect entries to the agenda buffer.
4412 Prompts for a character to select a command. Any prefix arg will be passed
4413 on to the selected command. The default selections are:
4414
4415 a Call `org-agenda' to display the agenda for the current day or week.
4416 t Call `org-todo-list' to display the global todo list.
4417 T Call `org-todo-list' to display the global todo list, select only
4418 entries with a specific TODO keyword (the user gets a prompt).
4419 m Call `org-tags-view' to display headlines with tags matching
4420 a condition (the user is prompted for the condition).
4421 M Like `m', but select only TODO entries, no ordinary headlines.
4422
4423 More commands can be added by configuring the variable
4424 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4425 searches can be pre-defined in this way.
4426
4427 If the current buffer is in Org-mode and visiting a file, you can also
4428 first press `1' to indicate that the agenda should be temporarily (until the
4429 next use of \\[org-agenda]) restricted to the current file."
4430 (interactive "P")
4431 (catch 'exit
4432 (let ((restrict-ok (and (buffer-file-name) (eq major-mode 'org-mode)))
4433 (custom org-agenda-custom-commands)
4434 c entry key type string)
4435 (put 'org-agenda-files 'org-restrict nil)
4436 (save-window-excursion
4437 (delete-other-windows)
4438 (switch-to-buffer-other-window " *Agenda Commands*")
4439 (erase-buffer)
4440 (insert
4441 "Press key for an agenda command:
4442 --------------------------------
4443 a Agenda for current week or day
4444 t List of all TODO entries T Entries with special TODO kwd
4445 m Match a TAGS query M Like m, but only TODO entries
4446 C Configure your own agenda commands")
4447 (while (setq entry (pop custom))
4448 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4449 (insert (format "\n%-4s%-14s: %s"
4450 key
4451 (cond
4452 ((eq type 'tags) "Tags query")
4453 ((eq type 'todo) "TODO keyword")
4454 ((eq type 'tags-tree) "Tags tree")
4455 ((eq type 'todo-tree) "TODO kwd tree")
4456 ((eq type 'occur-tree) "Occur tree")
4457 (t "???"))
4458 (org-string-props string 'face 'org-link))))
4459 (goto-char (point-min))
4460 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4461 (message "Press key for agenda command%s"
4462 (if restrict-ok ", or [1] to restrict to current file" ""))
4463 (setq c (read-char-exclusive))
4464 (message "")
4465 (when (equal c ?1)
4466 (if restrict-ok
4467 (put 'org-agenda-files 'org-restrict (list (buffer-file-name)))
4468 (error "Cannot restrict agenda to current buffer"))
4469 (message "Press key for agenda command%s"
4470 (if restrict-ok " (restricted to current file)" ""))
4471 (setq c (read-char-exclusive))
4472 (message "")))
4473 (require 'calendar) ; FIXME: can we avoid this for some commands?
4474 ;; For example the todo list should not need it (but does...)
4475 (cond
4476 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4477 ((equal c ?a) (call-interactively 'org-agenda-list))
4478 ((equal c ?t) (call-interactively 'org-todo-list))
4479 ((equal c ?T)
4480 (setq current-prefix-arg (or arg '(4)))
4481 (call-interactively 'org-todo-list))
4482 ((equal c ?m) (call-interactively 'org-tags-view))
4483 ((equal c ?M)
4484 (setq current-prefix-arg (or arg '(4)))
4485 (call-interactively 'org-tags-view))
4486 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4487 (setq type (nth 1 entry) string (nth 2 entry))
4488 (cond
4489 ((eq type 'tags)
4490 (org-tags-view current-prefix-arg string))
4491 ((eq type 'todo)
4492 (org-todo-list string))
4493 ((eq type 'tags-tree)
4494 (org-check-for-org-mode)
4495 (org-tags-sparse-tree current-prefix-arg string))
4496 ((eq type 'todo-tree)
4497 (org-check-for-org-mode)
4498 (org-occur (concat "^" outline-regexp "[ \t]*"
4499 (regexp-quote string) "\\>")))
4500 ((eq type 'occur-tree)
4501 (org-check-for-org-mode)
4502 (org-occur string))
4503 (t (error "Invalid custom agenda command type %s" type))))
4504 (t (error "Invalid key"))))))
4505
4506 (defun org-check-for-org-mode ()
4507 "Make sure current buffer is in org-mode. Error if not."
4508 (or (eq major-mode 'org-mode)
4509 (error "Cannot execute org-mode agenda command on buffer in %s."
4510 major-mode)))
4511
4512 (defun org-fit-agenda-window ()
4513 "Fit the window to the buffer size."
4514 (and org-fit-agenda-window
4515 (fboundp 'fit-window-to-buffer)
4516 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4517 (/ (frame-height) 2))))
4518
4519 (defun org-agenda-files ()
4520 "Get the list of agenda files."
4521 (or (get 'org-agenda-files 'org-restrict)
4522 org-agenda-files))
4523
4524 (defvar org-agenda-markers nil
4525 "List of all currently active markers created by `org-agenda'.")
4526 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4527 "Creation time of the last agenda marker.")
4528
4529 (defun org-agenda-new-marker (&optional pos)
4530 "Return a new agenda marker.
4531 Org-mode keeps a list of these markers and resets them when they are
4532 no longer in use."
4533 (let ((m (copy-marker (or pos (point)))))
4534 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4535 (push m org-agenda-markers)
4536 m))
4537
4538 (defun org-agenda-maybe-reset-markers (&optional force)
4539 "Reset markers created by `org-agenda'. But only if they are old enough."
4540 (if (or force
4541 (> (- (time-to-seconds (current-time))
4542 org-agenda-last-marker-time)
4543 5))
4544 (while org-agenda-markers
4545 (move-marker (pop org-agenda-markers) nil))))
4546
4547 (defvar org-agenda-new-buffers nil
4548 "Buffers created to visit agenda files.")
4549
4550 (defun org-get-agenda-file-buffer (file)
4551 "Get a buffer visiting FILE. If the buffer needs to be created, add
4552 it to the list of buffers which might be released later."
4553 (let ((buf (find-buffer-visiting file)))
4554 (if buf
4555 buf ; just return it
4556 ;; Make a new buffer and remember it
4557 (setq buf (find-file-noselect file))
4558 (if buf (push buf org-agenda-new-buffers))
4559 buf)))
4560
4561 (defun org-release-buffers (blist)
4562 "Release all buffers in list, asking the user for confirmation when needed.
4563 When a buffer is unmodified, it is just killed. When modified, it is saved
4564 \(if the user agrees) and then killed."
4565 (let (buf file)
4566 (while (setq buf (pop blist))
4567 (setq file (buffer-file-name buf))
4568 (when (and (buffer-modified-p buf)
4569 file
4570 (y-or-n-p (format "Save file %s? " file)))
4571 (with-current-buffer buf (save-buffer)))
4572 (kill-buffer buf))))
4573
4574 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4575
4576 (defun org-timeline (&optional include-all keep-modes)
4577 "Show a time-sorted view of the entries in the current org file.
4578 Only entries with a time stamp of today or later will be listed. With
4579 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4580 under the current date.
4581 If the buffer contains an active region, only check the region for
4582 dates."
4583 (interactive "P")
4584 (require 'calendar)
4585 (org-agenda-maybe-reset-markers 'force)
4586 (org-compile-prefix-format org-timeline-prefix-format)
4587 (let* ((dopast t)
4588 (dotodo include-all)
4589 (doclosed org-agenda-show-log)
4590 (org-agenda-keep-modes keep-modes)
4591 (entry (buffer-file-name))
4592 (org-agenda-files (list (buffer-file-name)))
4593 (date (calendar-current-date))
4594 (win (selected-window))
4595 (pos1 (point))
4596 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4597 (end (if (org-region-active-p) (region-end) (point-max)))
4598 (day-numbers (org-get-all-dates beg end 'no-ranges
4599 t doclosed)) ; always include today
4600 (today (time-to-days (current-time)))
4601 (org-respect-restriction t)
4602 (past t)
4603 args
4604 s e rtn d)
4605 (setq org-agenda-redo-command
4606 (list 'progn
4607 (list 'switch-to-buffer-other-window (current-buffer))
4608 (list 'org-timeline (list 'quote include-all) t)))
4609 (if (not dopast)
4610 ;; Remove past dates from the list of dates.
4611 (setq day-numbers (delq nil (mapcar (lambda(x)
4612 (if (>= x today) x nil))
4613 day-numbers))))
4614 (switch-to-buffer-other-window
4615 (get-buffer-create org-agenda-buffer-name))
4616 (setq buffer-read-only nil)
4617 (erase-buffer)
4618 (org-agenda-mode) (setq buffer-read-only nil)
4619 (set (make-local-variable 'org-agenda-type) 'timeline)
4620 (if doclosed (push :closed args))
4621 (push :timestamp args)
4622 (if dotodo (push :todo args))
4623 (while (setq d (pop day-numbers))
4624 (if (and (>= d today)
4625 dopast
4626 past)
4627 (progn
4628 (setq past nil)
4629 (insert (make-string 79 ?-) "\n")))
4630 (setq date (calendar-gregorian-from-absolute d))
4631 (setq s (point))
4632 (setq rtn (apply 'org-agenda-get-day-entries
4633 entry date args))
4634 (if (or rtn (equal d today))
4635 (progn
4636 (insert (calendar-day-name date) " "
4637 (number-to-string (extract-calendar-day date)) " "
4638 (calendar-month-name (extract-calendar-month date)) " "
4639 (number-to-string (extract-calendar-year date)) "\n")
4640 (put-text-property s (1- (point)) 'face
4641 'org-link)
4642 (if (equal d today)
4643 (put-text-property s (1- (point)) 'org-today t))
4644 (insert (org-finalize-agenda-entries rtn) "\n")
4645 (put-text-property s (1- (point)) 'day d))))
4646 (goto-char (point-min))
4647 (setq buffer-read-only t)
4648 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4649 (point-min)))
4650 (when (not org-select-timeline-window)
4651 (select-window win)
4652 (goto-char pos1))))
4653
4654 ;;;###autoload
4655 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4656 "Produce a weekly view from all files in variable `org-agenda-files'.
4657 The view will be for the current week, but from the overview buffer you
4658 will be able to go to other weeks.
4659 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4660 also be shown, under the current date.
4661 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4662 on the days are also shown. See the variable `org-log-done' for how
4663 to turn on logging.
4664 START-DAY defaults to TODAY, or to the most recent match for the weekday
4665 given in `org-agenda-start-on-weekday'.
4666 NDAYS defaults to `org-agenda-ndays'."
4667 (interactive "P")
4668 (org-agenda-maybe-reset-markers 'force)
4669 (org-compile-prefix-format org-agenda-prefix-format)
4670 (require 'calendar)
4671 (let* ((org-agenda-start-on-weekday
4672 (if (or (equal ndays 1)
4673 (and (null ndays) (equal 1 org-agenda-ndays)))
4674 nil org-agenda-start-on-weekday))
4675 (org-agenda-keep-modes keep-modes)
4676 (files (copy-sequence (org-agenda-files)))
4677 (win (selected-window))
4678 (today (time-to-days (current-time)))
4679 (sd (or start-day today))
4680 (start (if (or (null org-agenda-start-on-weekday)
4681 (< org-agenda-ndays 7))
4682 sd
4683 (let* ((nt (calendar-day-of-week
4684 (calendar-gregorian-from-absolute sd)))
4685 (n1 org-agenda-start-on-weekday)
4686 (d (- nt n1)))
4687 (- sd (+ (if (< d 0) 7 0) d)))))
4688 (day-numbers (list start))
4689 (inhibit-redisplay t)
4690 s e rtn rtnall file date d start-pos end-pos todayp nd)
4691 (setq org-agenda-redo-command
4692 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4693 ;; Make the list of days
4694 (setq ndays (or ndays org-agenda-ndays)
4695 nd ndays)
4696 (while (> ndays 1)
4697 (push (1+ (car day-numbers)) day-numbers)
4698 (setq ndays (1- ndays)))
4699 (setq day-numbers (nreverse day-numbers))
4700 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4701 (progn
4702 (delete-other-windows)
4703 (switch-to-buffer-other-window
4704 (get-buffer-create org-agenda-buffer-name))))
4705 (setq buffer-read-only nil)
4706 (erase-buffer)
4707 (org-agenda-mode) (setq buffer-read-only nil)
4708 (set (make-local-variable 'org-agenda-type) 'agenda)
4709 (set (make-local-variable 'starting-day) (car day-numbers))
4710 (set (make-local-variable 'include-all-loc) include-all)
4711 (when (and (or include-all org-agenda-include-all-todo)
4712 (member today day-numbers))
4713 (setq files (org-agenda-files)
4714 rtnall nil)
4715 (while (setq file (pop files))
4716 (catch 'nextfile
4717 (org-check-agenda-file file)
4718 (setq date (calendar-gregorian-from-absolute today)
4719 rtn (org-agenda-get-day-entries
4720 file date :todo))
4721 (setq rtnall (append rtnall rtn))))
4722 (when rtnall
4723 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4724 (add-text-properties (point-min) (1- (point))
4725 (list 'face 'org-link))
4726 (insert (org-finalize-agenda-entries rtnall) "\n")))
4727 (while (setq d (pop day-numbers))
4728 (setq date (calendar-gregorian-from-absolute d)
4729 s (point))
4730 (if (or (setq todayp (= d today))
4731 (and (not start-pos) (= d sd)))
4732 (setq start-pos (point))
4733 (if (and start-pos (not end-pos))
4734 (setq end-pos (point))))
4735 (setq files (org-agenda-files)
4736 rtnall nil)
4737 (while (setq file (pop files))
4738 (catch 'nextfile
4739 (org-check-agenda-file file)
4740 (if org-agenda-show-log
4741 (setq rtn (org-agenda-get-day-entries
4742 file date
4743 :deadline :scheduled :timestamp :closed))
4744 (setq rtn (org-agenda-get-day-entries
4745 file date
4746 :deadline :scheduled :timestamp)))
4747 (setq rtnall (append rtnall rtn))))
4748 (if org-agenda-include-diary
4749 (progn
4750 (require 'diary-lib)
4751 (setq rtn (org-get-entries-from-diary date))
4752 (setq rtnall (append rtnall rtn))))
4753 (if (or rtnall org-agenda-show-all-dates)
4754 (progn
4755 (insert (format "%-9s %2d %s %4d\n"
4756 (calendar-day-name date)
4757 (extract-calendar-day date)
4758 (calendar-month-name (extract-calendar-month date))
4759 (extract-calendar-year date)))
4760 (put-text-property s (1- (point)) 'face
4761 'org-link)
4762 (if rtnall (insert
4763 (org-finalize-agenda-entries
4764 (org-agenda-add-time-grid-maybe
4765 rtnall nd todayp))
4766 "\n"))
4767 (put-text-property s (1- (point)) 'day d))))
4768 (goto-char (point-min))
4769 (setq buffer-read-only t)
4770 (org-fit-agenda-window)
4771 (unless (and (pos-visible-in-window-p (point-min))
4772 (pos-visible-in-window-p (point-max)))
4773 (goto-char (1- (point-max)))
4774 (recenter -1)
4775 (if (not (pos-visible-in-window-p (or start-pos 1)))
4776 (progn
4777 (goto-char (or start-pos 1))
4778 (recenter 1))))
4779 (goto-char (or start-pos 1))
4780 (if (not org-select-agenda-window) (select-window win))
4781 (message "")))
4782
4783 (defvar org-select-this-todo-keyword nil)
4784
4785 ;;;###autoload
4786 (defun org-todo-list (arg &optional keep-modes)
4787 "Show all TODO entries from all agenda file in a single list.
4788 The prefix arg can be used to select a specific TODO keyword and limit
4789 the list to these. When using \\[universal-argument], you will be prompted
4790 for a keyword. A numeric prefix directly selects the Nth keyword in
4791 `org-todo-keywords'."
4792 (interactive "P")
4793 (org-agenda-maybe-reset-markers 'force)
4794 (org-compile-prefix-format org-agenda-prefix-format)
4795 (let* ((org-agenda-keep-modes keep-modes)
4796 (today (time-to-days (current-time)))
4797 (date (calendar-gregorian-from-absolute today))
4798 (win (selected-window))
4799 (kwds org-todo-keywords)
4800 (completion-ignore-case t)
4801 (org-select-this-todo-keyword
4802 (if (stringp arg) arg
4803 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4804 rtn rtnall files file pos)
4805 (when (equal arg '(4))
4806 (setq org-select-this-todo-keyword
4807 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4808 nil t)))
4809 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4810 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4811 (progn
4812 (delete-other-windows)
4813 (switch-to-buffer-other-window
4814 (get-buffer-create org-agenda-buffer-name))))
4815 (setq buffer-read-only nil)
4816 (erase-buffer)
4817 (org-agenda-mode) (setq buffer-read-only nil)
4818 (set (make-local-variable 'org-agenda-type) 'todo)
4819 (set (make-local-variable 'last-arg) arg)
4820 (set (make-local-variable 'org-todo-keywords) kwds)
4821 (set (make-local-variable 'org-agenda-redo-command)
4822 '(org-todo-list (or current-prefix-arg last-arg) t))
4823 (setq files (org-agenda-files)
4824 rtnall nil)
4825 (while (setq file (pop files))
4826 (catch 'nextfile
4827 (org-check-agenda-file file)
4828 (setq rtn (org-agenda-get-day-entries file date :todo))
4829 (setq rtnall (append rtnall rtn))))
4830 (insert "Global list of TODO items of type: ")
4831 (add-text-properties (point-min) (1- (point))
4832 (list 'face 'org-link))
4833 (setq pos (point))
4834 (insert (or org-select-this-todo-keyword "ALL") "\n")
4835 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4836 (setq pos (point))
4837 (insert
4838 "Available with `N r': (0)ALL "
4839 (let ((n 0))
4840 (mapconcat (lambda (x)
4841 (format "(%d)%s" (setq n (1+ n)) x))
4842 org-todo-keywords " "))
4843 "\n")
4844 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4845 (when rtnall
4846 (insert (org-finalize-agenda-entries rtnall) "\n"))
4847 (goto-char (point-min))
4848 (setq buffer-read-only t)
4849 (org-fit-agenda-window)
4850 (if (not org-select-agenda-window) (select-window win))))
4851
4852 (defun org-check-agenda-file (file)
4853 "Make sure FILE exists. If not, ask user what to do."
4854 ;; FIXME: this does not correctly change the menus
4855 ;; Could probably be fixed by explicitly going to the buffer where
4856 ;; the call originated.
4857 (when (not (file-exists-p file))
4858 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4859 file)
4860 (let ((r (downcase (read-char-exclusive))))
4861 (cond
4862 ((equal r ?r)
4863 (org-remove-file file)
4864 (throw 'nextfile t))
4865 (t (error "Abort"))))))
4866
4867 (defun org-agenda-check-type (error &rest types)
4868 "Check if agenda buffer is of allowed type.
4869 If ERROR is non-nil, throw an error, otherwise just return nil."
4870 (if (memq org-agenda-type types)
4871 t
4872 (if error
4873 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
4874 nil)))
4875
4876 (defun org-agenda-quit ()
4877 "Exit agenda by removing the window or the buffer."
4878 (interactive)
4879 (let ((buf (current-buffer)))
4880 (if (not (one-window-p)) (delete-window))
4881 (kill-buffer buf)
4882 (org-agenda-maybe-reset-markers 'force)))
4883
4884 (defun org-agenda-exit ()
4885 "Exit agenda by removing the window or the buffer.
4886 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4887 Org-mode buffers visited directly by the user will not be touched."
4888 (interactive)
4889 (org-release-buffers org-agenda-new-buffers)
4890 (setq org-agenda-new-buffers nil)
4891 (org-agenda-quit))
4892
4893 (defun org-agenda-redo ()
4894 "Rebuild Agenda.
4895 When this is the global TODO list, a prefix argument will be interpreted."
4896 (interactive)
4897 (message "Rebuilding agenda buffer...")
4898 (eval org-agenda-redo-command)
4899 (message "Rebuilding agenda buffer...done"))
4900
4901 (defun org-agenda-goto-today ()
4902 "Go to today."
4903 (interactive)
4904 (org-agenda-check-type t 'timeline 'agenda)
4905 (if (boundp 'starting-day)
4906 (let ((cmd (car org-agenda-redo-command))
4907 (iall (nth 1 org-agenda-redo-command))
4908 (nday (nth 3 org-agenda-redo-command))
4909 (keep (nth 4 org-agenda-redo-command)))
4910 (eval (list cmd iall nil nday keep)))
4911 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4912 (point-min)))))
4913
4914 (defun org-agenda-later (arg)
4915 "Go forward in time by `org-agenda-ndays' days.
4916 With prefix ARG, go forward that many times `org-agenda-ndays'."
4917 (interactive "p")
4918 (org-agenda-check-type t 'agenda)
4919 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4920 (+ starting-day (* arg org-agenda-ndays)) nil t))
4921
4922 (defun org-agenda-earlier (arg)
4923 "Go back in time by `org-agenda-ndays' days.
4924 With prefix ARG, go back that many times `org-agenda-ndays'."
4925 (interactive "p")
4926 (org-agenda-check-type t 'agenda)
4927 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4928 (- starting-day (* arg org-agenda-ndays)) nil t))
4929
4930 (defun org-agenda-week-view ()
4931 "Switch to weekly view for agenda."
4932 (interactive)
4933 (org-agenda-check-type t 'agenda)
4934 (setq org-agenda-ndays 7)
4935 (org-agenda-list include-all-loc
4936 (or (get-text-property (point) 'day)
4937 starting-day)
4938 nil t)
4939 (org-agenda-set-mode-name)
4940 (message "Switched to week view"))
4941
4942 (defun org-agenda-day-view ()
4943 "Switch to daily view for agenda."
4944 (interactive)
4945 (org-agenda-check-type t 'agenda)
4946 (setq org-agenda-ndays 1)
4947 (org-agenda-list include-all-loc
4948 (or (get-text-property (point) 'day)
4949 starting-day)
4950 nil t)
4951 (org-agenda-set-mode-name)
4952 (message "Switched to day view"))
4953
4954 (defun org-agenda-next-date-line (&optional arg)
4955 "Jump to the next line indicating a date in agenda buffer."
4956 (interactive "p")
4957 (org-agenda-check-type t 'agenda 'timeline)
4958 (beginning-of-line 1)
4959 (if (looking-at "^\\S-") (forward-char 1))
4960 (if (not (re-search-forward "^\\S-" nil t arg))
4961 (progn
4962 (backward-char 1)
4963 (error "No next date after this line in this buffer")))
4964 (goto-char (match-beginning 0)))
4965
4966 (defun org-agenda-previous-date-line (&optional arg)
4967 "Jump to the previous line indicating a date in agenda buffer."
4968 (interactive "p")
4969 (org-agenda-check-type t 'agenda 'timeline)
4970 (beginning-of-line 1)
4971 (if (not (re-search-backward "^\\S-" nil t arg))
4972 (error "No previous date before this line in this buffer")))
4973
4974 ;; Initialize the highlight
4975 (defvar org-hl (org-make-overlay 1 1))
4976 (org-overlay-put org-hl 'face 'highlight)
4977
4978 (defun org-highlight (begin end &optional buffer)
4979 "Highlight a region with overlay."
4980 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4981 org-hl begin end (or buffer (current-buffer))))
4982
4983 (defun org-unhighlight ()
4984 "Detach overlay INDEX."
4985 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4986
4987
4988 (defun org-agenda-follow-mode ()
4989 "Toggle follow mode in an agenda buffer."
4990 (interactive)
4991 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4992 (org-agenda-set-mode-name)
4993 (message "Follow mode is %s"
4994 (if org-agenda-follow-mode "on" "off")))
4995
4996 (defun org-agenda-log-mode ()
4997 "Toggle log mode in an agenda buffer."
4998 (interactive)
4999 (org-agenda-check-type t 'agenda 'timeline)
5000 (setq org-agenda-show-log (not org-agenda-show-log))
5001 (org-agenda-set-mode-name)
5002 (org-agenda-redo)
5003 (message "Log mode is %s"
5004 (if org-agenda-show-log "on" "off")))
5005
5006 (defun org-agenda-toggle-diary ()
5007 "Toggle diary inclusion in an agenda buffer."
5008 (interactive)
5009 (org-agenda-check-type t 'agenda)
5010 (setq org-agenda-include-diary (not org-agenda-include-diary))
5011 (org-agenda-redo)
5012 (org-agenda-set-mode-name)
5013 (message "Diary inclusion turned %s"
5014 (if org-agenda-include-diary "on" "off")))
5015
5016 (defun org-agenda-toggle-time-grid ()
5017 "Toggle time grid in an agenda buffer."
5018 (interactive)
5019 (org-agenda-check-type t 'agenda)
5020 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5021 (org-agenda-redo)
5022 (org-agenda-set-mode-name)
5023 (message "Time-grid turned %s"
5024 (if org-agenda-use-time-grid "on" "off")))
5025
5026 (defun org-agenda-set-mode-name ()
5027 "Set the mode name to indicate all the small mode settings."
5028 (setq mode-name
5029 (concat "Org-Agenda"
5030 (if (equal org-agenda-ndays 1) " Day" "")
5031 (if (equal org-agenda-ndays 7) " Week" "")
5032 (if org-agenda-follow-mode " Follow" "")
5033 (if org-agenda-include-diary " Diary" "")
5034 (if org-agenda-use-time-grid " Grid" "")
5035 (if org-agenda-show-log " Log" "")))
5036 (force-mode-line-update))
5037
5038 (defun org-agenda-post-command-hook ()
5039 (and (eolp) (not (bolp)) (backward-char 1))
5040 (if (and org-agenda-follow-mode
5041 (get-text-property (point) 'org-marker))
5042 (org-agenda-show)))
5043
5044 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5045
5046 (defun org-get-entries-from-diary (date)
5047 "Get the (Emacs Calendar) diary entries for DATE."
5048 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5049 (diary-display-hook '(fancy-diary-display))
5050 (list-diary-entries-hook
5051 (cons 'org-diary-default-entry list-diary-entries-hook))
5052 (diary-file-name-prefix-function nil) ; turn this feature off
5053 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5054 entries
5055 (org-disable-agenda-to-diary t))
5056 (save-excursion
5057 (save-window-excursion
5058 (list-diary-entries date 1)))
5059 (if (not (get-buffer fancy-diary-buffer))
5060 (setq entries nil)
5061 (with-current-buffer fancy-diary-buffer
5062 (setq buffer-read-only nil)
5063 (if (= (point-max) 1)
5064 ;; No entries
5065 (setq entries nil)
5066 ;; Omit the date and other unnecessary stuff
5067 (org-agenda-cleanup-fancy-diary)
5068 ;; Add prefix to each line and extend the text properties
5069 (if (= (point-max) 1)
5070 (setq entries nil)
5071 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5072 (set-buffer-modified-p nil)
5073 (kill-buffer fancy-diary-buffer)))
5074 (when entries
5075 (setq entries (org-split-string entries "\n"))
5076 (setq entries
5077 (mapcar
5078 (lambda (x)
5079 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5080 ;; Extend the text properties to the beginning of the line
5081 (add-text-properties
5082 0 (length x)
5083 (text-properties-at (1- (length x)) x)
5084 x)
5085 x)
5086 entries)))))
5087
5088 (defun org-agenda-cleanup-fancy-diary ()
5089 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5090 This gets rid of the date, the underline under the date, and
5091 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5092 date. It also removes lines that contain only whitespace."
5093 (goto-char (point-min))
5094 (if (looking-at ".*?:[ \t]*")
5095 (progn
5096 (replace-match "")
5097 (re-search-forward "\n=+$" nil t)
5098 (replace-match "")
5099 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5100 (re-search-forward "\n=+$" nil t)
5101 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5102 (goto-char (point-min))
5103 (while (re-search-forward "^ +\n" nil t)
5104 (replace-match ""))
5105 (goto-char (point-min))
5106 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5107 (replace-match "")))
5108
5109 ;; Make sure entries from the diary have the right text properties.
5110 (eval-after-load "diary-lib"
5111 '(if (boundp 'diary-modify-entry-list-string-function)
5112 ;; We can rely on the hook, nothing to do
5113 nil
5114 ;; Hook not avaiable, must use advice to make this work
5115 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5116 "Make the position visible."
5117 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5118 (stringp string)
5119 (buffer-file-name))
5120 (setq string (org-modify-diary-entry-string string))))))
5121
5122 (defun org-modify-diary-entry-string (string)
5123 "Add text properties to string, allowing org-mode to act on it."
5124 (add-text-properties
5125 0 (length string)
5126 (list 'mouse-face 'highlight
5127 'keymap org-agenda-keymap
5128 'help-echo
5129 (format
5130 "mouse-2 or RET jump to diary file %s"
5131 (abbreviate-file-name (buffer-file-name)))
5132 'org-agenda-diary-link t
5133 'org-marker (org-agenda-new-marker (point-at-bol)))
5134 string)
5135 string)
5136
5137 (defun org-diary-default-entry ()
5138 "Add a dummy entry to the diary.
5139 Needed to avoid empty dates which mess up holiday display."
5140 ;; Catch the error if dealing with the new add-to-diary-alist
5141 (when org-disable-agenda-to-diary
5142 (condition-case nil
5143 (add-to-diary-list original-date "Org-mode dummy" "")
5144 (error
5145 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5146
5147 (defun org-cycle-agenda-files ()
5148 "Cycle through the files in `org-agenda-files'.
5149 If the current buffer visits an agenda file, find the next one in the list.
5150 If the current buffer does not, find the first agenda file."
5151 (interactive)
5152 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5153 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
5154 file)
5155 (unless files (error "No agenda files"))
5156 (catch 'exit
5157 (while (setq file (pop files))
5158 (if (equal (file-truename file) tcf)
5159 (when (car files)
5160 (find-file (car files))
5161 (throw 'exit t))))
5162 (find-file (car org-agenda-files)))))
5163
5164 (defun org-agenda-file-to-end (&optional file)
5165 "Move/add the current file to the end of the agenda file list.
5166 If the file is not present in the list, it is appended to the list. If it is
5167 present, it is moved there."
5168 (interactive)
5169 (org-agenda-file-to-front 'to-end file))
5170
5171 (defun org-agenda-file-to-front (&optional to-end file)
5172 "Move/add the current file to the top of the agenda file list.
5173 If the file is not present in the list, it is added to the front. If it is
5174 present, it is moved there. With optional argument TO-END, add/move to the
5175 end of the list."
5176 (interactive "P")
5177 (let ((file-alist (mapcar (lambda (x)
5178 (cons (file-truename x) x))
5179 org-agenda-files))
5180 (ctf (file-truename (buffer-file-name)))
5181 x had)
5182 (setq x (assoc ctf file-alist) had x)
5183
5184 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
5185 (if to-end
5186 (setq file-alist (append (delq x file-alist) (list x)))
5187 (setq file-alist (cons x (delq x file-alist))))
5188 (setq org-agenda-files (mapcar 'cdr file-alist))
5189 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5190 (customize-save-variable 'org-agenda-files org-agenda-files))
5191 (org-install-agenda-files-menu)
5192 (message "File %s to %s of agenda file list"
5193 (if had "moved" "added") (if to-end "end" "front"))))
5194
5195 (defun org-remove-file (&optional file)
5196 "Remove current file from the list of files in variable `org-agenda-files'.
5197 These are the files which are being checked for agenda entries.
5198 Optional argument FILE means, use this file instead of the current."
5199 (interactive)
5200 (let* ((file (or file (buffer-file-name)))
5201 (true-file (file-truename file))
5202 (afile (abbreviate-file-name file))
5203 (files (delq nil (mapcar
5204 (lambda (x)
5205 (if (equal true-file
5206 (file-truename x))
5207 nil x))
5208 org-agenda-files))))
5209 (if (not (= (length files) (length org-agenda-files)))
5210 (progn
5211 (setq org-agenda-files files)
5212 (customize-save-variable 'org-agenda-files org-agenda-files)
5213 (org-install-agenda-files-menu)
5214 (message "Removed file: %s" afile))
5215 (message "File was not in list: %s" afile))))
5216
5217 (defun org-file-menu-entry (file)
5218 (vector file (list 'find-file file) t))
5219 ;; FIXME: Maybe we removed a buffer visited through the menu from
5220 ;; org-agenda-new-buffers, so that the buffer will not be removed
5221 ;; when exiting the agenda????
5222
5223 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5224 "Return a list of all relevant day numbers from BEG to END buffer positions.
5225 If NO-RANGES is non-nil, include only the start and end dates of a range,
5226 not every single day in the range. If FORCE-TODAY is non-nil, make
5227 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5228 inactive time stamps (those in square brackets) are included."
5229 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5230 dates date day day1 day2 ts1 ts2)
5231 (if force-today
5232 (setq dates (list (time-to-days (current-time)))))
5233 (save-excursion
5234 (goto-char beg)
5235 (while (re-search-forward re end t)
5236 (setq day (time-to-days (org-time-string-to-time
5237 (substring (match-string 1) 0 10))))
5238 (or (memq day dates) (push day dates)))
5239 (unless no-ranges
5240 (goto-char beg)
5241 (while (re-search-forward org-tr-regexp end t)
5242 (setq ts1 (substring (match-string 1) 0 10)
5243 ts2 (substring (match-string 2) 0 10)
5244 day1 (time-to-days (org-time-string-to-time ts1))
5245 day2 (time-to-days (org-time-string-to-time ts2)))
5246 (while (< (setq day1 (1+ day1)) day2)
5247 (or (memq day1 dates) (push day1 dates)))))
5248 (sort dates '<))))
5249
5250 ;;;###autoload
5251 (defun org-diary (&rest args)
5252 "Return diary information from org-files.
5253 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5254 It accesses org files and extracts information from those files to be
5255 listed in the diary. The function accepts arguments specifying what
5256 items should be listed. The following arguments are allowed:
5257
5258 :timestamp List the headlines of items containing a date stamp or
5259 date range matching the selected date. Deadlines will
5260 also be listed, on the expiration day.
5261
5262 :deadline List any deadlines past due, or due within
5263 `org-deadline-warning-days'. The listing occurs only
5264 in the diary for *today*, not at any other date. If
5265 an entry is marked DONE, it is no longer listed.
5266
5267 :scheduled List all items which are scheduled for the given date.
5268 The diary for *today* also contains items which were
5269 scheduled earlier and are not yet marked DONE.
5270
5271 :todo List all TODO items from the org-file. This may be a
5272 long list - so this is not turned on by default.
5273 Like deadlines, these entries only show up in the
5274 diary for *today*, not at any other date.
5275
5276 The call in the diary file should look like this:
5277
5278 &%%(org-diary) ~/path/to/some/orgfile.org
5279
5280 Use a separate line for each org file to check. Or, if you omit the file name,
5281 all files listed in `org-agenda-files' will be checked automatically:
5282
5283 &%%(org-diary)
5284
5285 If you don't give any arguments (as in the example above), the default
5286 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5287 also be written as
5288
5289 &%%(org-diary :deadline :timestamp :scheduled)
5290
5291 The function expects the lisp variables `entry' and `date' to be provided
5292 by the caller, because this is how the calendar works. Don't use this
5293 function from a program - use `org-agenda-get-day-entries' instead."
5294 (org-agenda-maybe-reset-markers)
5295 (org-compile-prefix-format org-agenda-prefix-format)
5296 (setq args (or args '(:deadline :scheduled :timestamp)))
5297 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5298 (list entry)
5299 org-agenda-files))
5300 file rtn results)
5301 ;; If this is called during org-agenda, don't return any entries to
5302 ;; the calendar. Org Agenda will list these entries itself.
5303 (if org-disable-agenda-to-diary (setq files nil))
5304 (while (setq file (pop files))
5305 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5306 (setq results (append results rtn)))
5307 (if results
5308 (concat (org-finalize-agenda-entries results) "\n"))))
5309 (defvar org-category-table nil)
5310 (defun org-get-category-table ()
5311 "Get the table of categories and positions in current buffer."
5312 (let (tbl)
5313 (save-excursion
5314 (goto-char (point-min))
5315 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5316 (push (cons (point) (org-trim (match-string 2))) tbl)))
5317 tbl))
5318 (defun org-get-category (&optional pos)
5319 "Get the category applying to position POS."
5320 (if (not org-category-table)
5321 (cond
5322 ((null org-category)
5323 (setq org-category
5324 (if (buffer-file-name)
5325 (file-name-sans-extension
5326 (file-name-nondirectory (buffer-file-name)))
5327 "???")))
5328 ((symbolp org-category) (symbol-name org-category))
5329 (t org-category))
5330 (let ((tbl org-category-table)
5331 (pos (or pos (point))))
5332 (while (and tbl (> (caar tbl) pos))
5333 (pop tbl))
5334 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5335 org-category-table))))))
5336
5337 (defun org-agenda-get-day-entries (file date &rest args)
5338 "Does the work for `org-diary' and `org-agenda'.
5339 FILE is the path to a file to be checked for entries. DATE is date like
5340 the one returned by `calendar-current-date'. ARGS are symbols indicating
5341 which kind of entries should be extracted. For details about these, see
5342 the documentation of `org-diary'."
5343 (setq args (or args '(:deadline :scheduled :timestamp)))
5344 (let* ((org-startup-with-deadline-check nil)
5345 (org-startup-folded nil)
5346 (buffer (if (file-exists-p file)
5347 (org-get-agenda-file-buffer file)
5348 (error "No such file %s" file)))
5349 arg results rtn)
5350 (if (not buffer)
5351 ;; If file does not exist, make sure an error message ends up in diary
5352 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5353 (with-current-buffer buffer
5354 (unless (eq major-mode 'org-mode)
5355 (error "Agenda file %s is not in `org-mode'" file))
5356 (setq org-category-table (org-get-category-table))
5357 (let ((case-fold-search nil))
5358 (save-excursion
5359 (save-restriction
5360 (if org-respect-restriction
5361 (if (org-region-active-p)
5362 ;; Respect a region to restrict search
5363 (narrow-to-region (region-beginning) (region-end)))
5364 ;; If we work for the calendar or many files,
5365 ;; get rid of any restriction
5366 (widen))
5367 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5368 (while (setq arg (pop args))
5369 (cond
5370 ((and (eq arg :todo)
5371 (equal date (calendar-current-date)))
5372 (setq rtn (org-agenda-get-todos))
5373 (setq results (append results rtn)))
5374 ((eq arg :timestamp)
5375 (setq rtn (org-agenda-get-blocks))
5376 (setq results (append results rtn))
5377 (setq rtn (org-agenda-get-timestamps))
5378 (setq results (append results rtn)))
5379 ((eq arg :scheduled)
5380 (setq rtn (org-agenda-get-scheduled))
5381 (setq results (append results rtn)))
5382 ((eq arg :closed)
5383 (setq rtn (org-agenda-get-closed))
5384 (setq results (append results rtn)))
5385 ((and (eq arg :deadline)
5386 (equal date (calendar-current-date)))
5387 (setq rtn (org-agenda-get-deadlines))
5388 (setq results (append results rtn))))))))
5389 results))))
5390
5391 (defun org-entry-is-done-p ()
5392 "Is the current entry marked DONE?"
5393 (save-excursion
5394 (and (re-search-backward "[\r\n]\\*" nil t)
5395 (looking-at org-nl-done-regexp))))
5396
5397 (defun org-at-date-range-p ()
5398 "Is the cursor inside a date range?"
5399 (interactive)
5400 (save-excursion
5401 (catch 'exit
5402 (let ((pos (point)))
5403 (skip-chars-backward "^<\r\n")
5404 (skip-chars-backward "<")
5405 (and (looking-at org-tr-regexp)
5406 (>= (match-end 0) pos)
5407 (throw 'exit t))
5408 (skip-chars-backward "^<\r\n")
5409 (skip-chars-backward "<")
5410 (and (looking-at org-tr-regexp)
5411 (>= (match-end 0) pos)
5412 (throw 'exit t)))
5413 nil)))
5414
5415 (defun org-agenda-get-todos ()
5416 "Return the TODO information for agenda display."
5417 (let* ((props (list 'face nil
5418 'done-face 'org-done
5419 'mouse-face 'highlight
5420 'keymap org-agenda-keymap
5421 'help-echo
5422 (format "mouse-2 or RET jump to org file %s"
5423 (abbreviate-file-name (buffer-file-name)))))
5424 (regexp (concat "[\n\r]\\*+ *\\("
5425 (if org-select-this-todo-keyword
5426 (concat "\\<\\(" org-select-this-todo-keyword
5427 "\\)\\>")
5428 org-not-done-regexp)
5429 "[^\n\r]*\\)"))
5430 marker priority category tags
5431 ee txt)
5432 (goto-char (point-min))
5433 (while (re-search-forward regexp nil t)
5434 (goto-char (match-beginning 1))
5435 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5436 category (org-get-category)
5437 tags (org-get-tags-at (point))
5438 txt (org-format-agenda-item "" (match-string 1) category tags)
5439 priority
5440 (+ (org-get-priority txt)
5441 (if org-todo-kwd-priority-p
5442 (- org-todo-kwd-max-priority -2
5443 (length
5444 (member (match-string 2) org-todo-keywords)))
5445 1)))
5446 (add-text-properties
5447 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5448 'priority priority 'category category)
5449 props)
5450 txt)
5451 (push txt ee)
5452 (goto-char (match-end 1)))
5453 (nreverse ee)))
5454
5455 (defconst org-agenda-no-heading-message
5456 "No heading for this item in buffer or region.")
5457
5458 (defun org-agenda-get-timestamps ()
5459 "Return the date stamp information for agenda display."
5460 (let* ((props (list 'face nil
5461 'mouse-face 'highlight
5462 'keymap org-agenda-keymap
5463 'help-echo
5464 (format "mouse-2 or RET jump to org file %s"
5465 (abbreviate-file-name (buffer-file-name)))))
5466 (regexp (regexp-quote
5467 (substring
5468 (format-time-string
5469 (car org-time-stamp-formats)
5470 (apply 'encode-time ; DATE bound by calendar
5471 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5472 0 11)))
5473 marker hdmarker deadlinep scheduledp donep tmp priority category
5474 ee txt timestr tags)
5475 (goto-char (point-min))
5476 (while (re-search-forward regexp nil t)
5477 (if (not (save-match-data (org-at-date-range-p)))
5478 (progn
5479 (setq marker (org-agenda-new-marker (match-beginning 0))
5480 category (org-get-category (match-beginning 0))
5481 tmp (buffer-substring (max (point-min)
5482 (- (match-beginning 0)
5483 org-ds-keyword-length))
5484 (match-beginning 0))
5485 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5486 deadlinep (string-match org-deadline-regexp tmp)
5487 scheduledp (string-match org-scheduled-regexp tmp)
5488 donep (org-entry-is-done-p))
5489 (if (string-match ">" timestr)
5490 ;; substring should only run to end of time stamp
5491 (setq timestr (substring timestr 0 (match-end 0))))
5492 (save-excursion
5493 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5494 (progn
5495 (goto-char (match-end 1))
5496 (setq hdmarker (org-agenda-new-marker)
5497 tags (org-get-tags-at))
5498 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5499 (setq txt (org-format-agenda-item
5500 (format "%s%s"
5501 (if deadlinep "Deadline: " "")
5502 (if scheduledp "Scheduled: " ""))
5503 (match-string 1) category tags timestr)))
5504 (setq txt org-agenda-no-heading-message))
5505 (setq priority (org-get-priority txt))
5506 (add-text-properties
5507 0 (length txt) (append (list 'org-marker marker
5508 'org-hd-marker hdmarker) props)
5509 txt)
5510 (if deadlinep
5511 (add-text-properties
5512 0 (length txt)
5513 (list 'face
5514 (if donep 'org-done 'org-warning)
5515 'undone-face 'org-warning
5516 'done-face 'org-done
5517 'category category
5518 'priority (+ 100 priority))
5519 txt)
5520 (if scheduledp
5521 (add-text-properties
5522 0 (length txt)
5523 (list 'face 'org-scheduled-today
5524 'undone-face 'org-scheduled-today
5525 'done-face 'org-done
5526 'category category
5527 priority (+ 99 priority))
5528 txt)
5529 (add-text-properties
5530 0 (length txt)
5531 (list 'priority priority 'category category) txt)))
5532 (push txt ee))
5533 (outline-next-heading))))
5534 (nreverse ee)))
5535
5536 (defun org-agenda-get-closed ()
5537 "Return the logged TODO entries for agenda display."
5538 (let* ((props (list 'mouse-face 'highlight
5539 'keymap org-agenda-keymap
5540 'help-echo
5541 (format "mouse-2 or RET jump to org file %s"
5542 (abbreviate-file-name (buffer-file-name)))))
5543 (regexp (concat
5544 "\\<" org-closed-string " *\\["
5545 (regexp-quote
5546 (substring
5547 (format-time-string
5548 (car org-time-stamp-formats)
5549 (apply 'encode-time ; DATE bound by calendar
5550 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5551 1 11))))
5552 marker hdmarker priority category tags
5553 ee txt timestr)
5554 (goto-char (point-min))
5555 (while (re-search-forward regexp nil t)
5556 (if (not (save-match-data (org-at-date-range-p)))
5557 (progn
5558 (setq marker (org-agenda-new-marker (match-beginning 0))
5559 category (org-get-category (match-beginning 0))
5560 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5561 ;; donep (org-entry-is-done-p)
5562 )
5563 (if (string-match "\\]" timestr)
5564 ;; substring should only run to end of time stamp
5565 (setq timestr (substring timestr 0 (match-end 0))))
5566 (save-excursion
5567 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5568 (progn
5569 (goto-char (match-end 1))
5570 (setq hdmarker (org-agenda-new-marker)
5571 tags (org-get-tags-at))
5572 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5573 (setq txt (org-format-agenda-item
5574 "Closed: "
5575 (match-string 1) category tags timestr)))
5576 (setq txt org-agenda-no-heading-message))
5577 (setq priority 100000)
5578 (add-text-properties
5579 0 (length txt) (append (list 'org-marker marker
5580 'org-hd-marker hdmarker
5581 'face 'org-done
5582 'priority priority
5583 'category category
5584 'undone-face 'org-warning
5585 'done-face 'org-done) props)
5586 txt)
5587 (push txt ee))
5588 (outline-next-heading))))
5589 (nreverse ee)))
5590
5591 (defun org-agenda-get-deadlines ()
5592 "Return the deadline information for agenda display."
5593 (let* ((wdays org-deadline-warning-days)
5594 (props (list 'mouse-face 'highlight
5595 'keymap org-agenda-keymap
5596 'help-echo
5597 (format "mouse-2 or RET jump to org file %s"
5598 (abbreviate-file-name (buffer-file-name)))))
5599 (regexp org-deadline-time-regexp)
5600 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5601 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5602 d2 diff pos pos1 category tags
5603 ee txt head)
5604 (goto-char (point-min))
5605 (while (re-search-forward regexp nil t)
5606 (setq pos (1- (match-beginning 1))
5607 d2 (time-to-days
5608 (org-time-string-to-time (match-string 1)))
5609 diff (- d2 d1))
5610 ;; When to show a deadline in the calendar:
5611 ;; If the expiration is within wdays warning time.
5612 ;; Past-due deadlines are only shown on the current date
5613 (if (and (< diff wdays) todayp (not (= diff 0)))
5614 (save-excursion
5615 (setq category (org-get-category))
5616 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5617 (progn
5618 (goto-char (match-end 0))
5619 (setq pos1 (match-end 1))
5620 (setq tags (org-get-tags-at pos1))
5621 (setq head (buffer-substring-no-properties
5622 (point)
5623 (progn (skip-chars-forward "^\r\n")
5624 (point))))
5625 (if (string-match org-looking-at-done-regexp head)
5626 (setq txt nil)
5627 (setq txt (org-format-agenda-item
5628 (format "In %3d d.: " diff) head category tags))))
5629 (setq txt org-agenda-no-heading-message))
5630 (when txt
5631 (add-text-properties
5632 0 (length txt)
5633 (append
5634 (list 'org-marker (org-agenda-new-marker pos)
5635 'org-hd-marker (org-agenda-new-marker pos1)
5636 'priority (+ (- 10 diff) (org-get-priority txt))
5637 'category category
5638 'face (cond ((<= diff 0) 'org-warning)
5639 ((<= diff 5) 'org-scheduled-previously)
5640 (t nil))
5641 'undone-face (cond
5642 ((<= diff 0) 'org-warning)
5643 ((<= diff 5) 'org-scheduled-previously)
5644 (t nil))
5645 'done-face 'org-done)
5646 props)
5647 txt)
5648 (push txt ee)))))
5649 ee))
5650
5651 (defun org-agenda-get-scheduled ()
5652 "Return the scheduled information for agenda display."
5653 (let* ((props (list 'face 'org-scheduled-previously
5654 'undone-face 'org-scheduled-previously
5655 'done-face 'org-done
5656 'mouse-face 'highlight
5657 'keymap org-agenda-keymap
5658 'help-echo
5659 (format "mouse-2 or RET jump to org file %s"
5660 (abbreviate-file-name (buffer-file-name)))))
5661 (regexp org-scheduled-time-regexp)
5662 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5663 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5664 d2 diff pos pos1 category tags
5665 ee txt head)
5666 (goto-char (point-min))
5667 (while (re-search-forward regexp nil t)
5668 (setq pos (1- (match-beginning 1))
5669 d2 (time-to-days
5670 (org-time-string-to-time (match-string 1)))
5671 diff (- d2 d1))
5672 ;; When to show a scheduled item in the calendar:
5673 ;; If it is on or past the date.
5674 (if (and (< diff 0) todayp)
5675 (save-excursion
5676 (setq category (org-get-category))
5677 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5678 (progn
5679 (goto-char (match-end 0))
5680 (setq pos1 (match-end 1))
5681 (setq tags (org-get-tags-at))
5682 (setq head (buffer-substring-no-properties
5683 (point)
5684 (progn (skip-chars-forward "^\r\n") (point))))
5685 (if (string-match org-looking-at-done-regexp head)
5686 (setq txt nil)
5687 (setq txt (org-format-agenda-item
5688 (format "Sched.%2dx: " (- 1 diff)) head
5689 category tags))))
5690 (setq txt org-agenda-no-heading-message))
5691 (when txt
5692 (add-text-properties
5693 0 (length txt)
5694 (append (list 'org-marker (org-agenda-new-marker pos)
5695 'org-hd-marker (org-agenda-new-marker pos1)
5696 'priority (+ (- 5 diff) (org-get-priority txt))
5697 'category category)
5698 props) txt)
5699 (push txt ee)))))
5700 ee))
5701
5702 (defun org-agenda-get-blocks ()
5703 "Return the date-range information for agenda display."
5704 (let* ((props (list 'face nil
5705 'mouse-face 'highlight
5706 'keymap org-agenda-keymap
5707 'help-echo
5708 (format "mouse-2 or RET jump to org file %s"
5709 (abbreviate-file-name (buffer-file-name)))))
5710 (regexp org-tr-regexp)
5711 (d0 (calendar-absolute-from-gregorian date))
5712 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
5713 (goto-char (point-min))
5714 (while (re-search-forward regexp nil t)
5715 (setq timestr (match-string 0)
5716 s1 (match-string 1)
5717 s2 (match-string 2)
5718 d1 (time-to-days (org-time-string-to-time s1))
5719 d2 (time-to-days (org-time-string-to-time s2)))
5720 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5721 ;; Only allow days between the limits, because the normal
5722 ;; date stamps will catch the limits.
5723 (save-excursion
5724 (setq marker (org-agenda-new-marker (point)))
5725 (setq category (org-get-category))
5726 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5727 (progn
5728 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5729 (goto-char (match-end 1))
5730 (setq tags (org-get-tags-at))
5731 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5732 (setq txt (org-format-agenda-item
5733 (format (if (= d1 d2) "" "(%d/%d): ")
5734 (1+ (- d0 d1)) (1+ (- d2 d1)))
5735 (match-string 1) category tags
5736 (if (= d0 d1) timestr))))
5737 (setq txt org-agenda-no-heading-message))
5738 (add-text-properties
5739 0 (length txt) (append (list 'org-marker marker
5740 'org-hd-marker hdmarker
5741 'priority (org-get-priority txt)
5742 'category category)
5743 props)
5744 txt)
5745 (push txt ee)))
5746 (outline-next-heading))
5747 ;; Sort the entries by expiration date.
5748 (nreverse ee)))
5749
5750 (defconst org-plain-time-of-day-regexp
5751 (concat
5752 "\\(\\<[012]?[0-9]"
5753 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5754 "\\(--?"
5755 "\\(\\<[012]?[0-9]"
5756 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5757 "\\)?")
5758 "Regular expression to match a plain time or time range.
5759 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5760 groups carry important information:
5761 0 the full match
5762 1 the first time, range or not
5763 8 the second time, if it is a range.")
5764
5765 (defconst org-stamp-time-of-day-regexp
5766 (concat
5767 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5768 "\\([012][0-9]:[0-5][0-9]\\)>"
5769 "\\(--?"
5770 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5771 "Regular expression to match a timestamp time or time range.
5772 After a match, the following groups carry important information:
5773 0 the full match
5774 1 date plus weekday, for backreferencing to make sure both times on same day
5775 2 the first time, range or not
5776 4 the second time, if it is a range.")
5777
5778 (defvar org-prefix-has-time nil
5779 "A flag, set by `org-compile-prefix-format'.
5780 The flag is set if the currently compiled format contains a `%t'.")
5781 (defvar org-prefix-has-tag nil
5782 "A flag, set by `org-compile-prefix-format'.
5783 The flag is set if the currently compiled format contains a `%T'.")
5784
5785 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
5786 "Format TXT to be inserted into the agenda buffer.
5787 In particular, it adds the prefix and corresponding text properties. EXTRA
5788 must be a string and replaces the `%s' specifier in the prefix format.
5789 CATEGORY (string, symbol or nil) may be used to overrule the default
5790 category taken from local variable or file name. It will replace the `%c'
5791 specifier in the format. DOTIME, when non-nil, indicates that a
5792 time-of-day should be extracted from TXT for sorting of this entry, and for
5793 the `%t' specifier in the format. When DOTIME is a string, this string is
5794 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5795 only the correctly processes TXT should be returned - this is used by
5796 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
5797 (save-match-data
5798 ;; Diary entries sometimes have extra whitespace at the beginning
5799 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5800 (let* ((category (or category
5801 org-category
5802 (if (buffer-file-name)
5803 (file-name-sans-extension
5804 (file-name-nondirectory (buffer-file-name)))
5805 "")))
5806 (tag (or (nth (1- (length tags)) tags) ""))
5807 time ;; needed for the eval of the prefix format
5808 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5809 (time-of-day (and dotime (org-get-time-of-day ts)))
5810 stamp plain s0 s1 s2 rtn)
5811 (when (and dotime time-of-day org-prefix-has-time)
5812 ;; Extract starting and ending time and move them to prefix
5813 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5814 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5815 (setq s0 (match-string 0 ts)
5816 s1 (match-string (if plain 1 2) ts)
5817 s2 (match-string (if plain 8 4) ts))
5818
5819 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5820 ;; them, we might want to remove them there to avoid duplication.
5821 ;; The user can turn this off with a variable.
5822 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5823 (string-match (concat (regexp-quote s0) " *") txt)
5824 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5825 (= (match-beginning 0) 0)
5826 t))
5827 (setq txt (replace-match "" nil nil txt))))
5828 ;; Normalize the time(s) to 24 hour
5829 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5830 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5831
5832 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
5833 (and org-agenda-remove-tags-when-in-prefix
5834 org-prefix-has-tag))
5835 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
5836 (setq txt (replace-match "" t t txt)))
5837
5838 ;; Create the final string
5839 (if noprefix
5840 (setq rtn txt)
5841 ;; Prepare the variables needed in the eval of the compiled format
5842 (setq time (cond (s2 (concat s1 "-" s2))
5843 (s1 (concat s1 "......"))
5844 (t ""))
5845 extra (or extra "")
5846 category (if (symbolp category) (symbol-name category) category))
5847 ;; Evaluate the compiled format
5848 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5849
5850 ;; And finally add the text properties
5851 (add-text-properties
5852 0 (length rtn) (list 'category (downcase category)
5853 'tags tags
5854 'prefix-length (- (length rtn) (length txt))
5855 'time-of-day time-of-day
5856 'dotime dotime)
5857 rtn)
5858 rtn)))
5859
5860 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5861 (catch 'exit
5862 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5863 ((and todayp (member 'today (car org-agenda-time-grid))))
5864 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5865 ((member 'weekly (car org-agenda-time-grid)))
5866 (t (throw 'exit list)))
5867 (let* ((have (delq nil (mapcar
5868 (lambda (x) (get-text-property 1 'time-of-day x))
5869 list)))
5870 (string (nth 1 org-agenda-time-grid))
5871 (gridtimes (nth 2 org-agenda-time-grid))
5872 (req (car org-agenda-time-grid))
5873 (remove (member 'remove-match req))
5874 new time)
5875 (if (and (member 'require-timed req) (not have))
5876 ;; don't show empty grid
5877 (throw 'exit list))
5878 (while (setq time (pop gridtimes))
5879 (unless (and remove (member time have))
5880 (setq time (int-to-string time))
5881 (push (org-format-agenda-item
5882 nil string "" nil ;; FIXME: put a category for the grid?
5883 (concat (substring time 0 -2) ":" (substring time -2)))
5884 new)
5885 (put-text-property
5886 1 (length (car new)) 'face 'org-time-grid (car new))))
5887 (if (member 'time-up org-agenda-sorting-strategy)
5888 (append new list)
5889 (append list new)))))
5890
5891 (defun org-compile-prefix-format (format)
5892 "Compile the prefix format into a Lisp form that can be evaluated.
5893 The resulting form is returned and stored in the variable
5894 `org-prefix-format-compiled'."
5895 (setq org-prefix-has-time nil org-prefix-has-tag nil)
5896 (let ((start 0) varform vars var (s format)e c f opt)
5897 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5898 s start)
5899 (setq var (cdr (assoc (match-string 4 s)
5900 '(("c" . category) ("t" . time) ("s" . extra)
5901 ("T" . tag))))
5902 c (or (match-string 3 s) "")
5903 opt (match-beginning 1)
5904 start (1+ (match-beginning 0)))
5905 (if (equal var 'time) (setq org-prefix-has-time t))
5906 (if (equal var 'tag) (setq org-prefix-has-tag t))
5907 (setq f (concat "%" (match-string 2 s) "s"))
5908 (if opt
5909 (setq varform
5910 `(if (equal "" ,var)
5911 ""
5912 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5913 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5914 (setq s (replace-match "%s" t nil s))
5915 (push varform vars))
5916 (setq vars (nreverse vars))
5917 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5918
5919 (defun org-get-time-of-day (s &optional string)
5920 "Check string S for a time of day.
5921 If found, return it as a military time number between 0 and 2400.
5922 If not found, return nil.
5923 The optional STRING argument forces conversion into a 5 character wide string
5924 HH:MM."
5925 (save-match-data
5926 (when
5927 (or
5928 (string-match
5929 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5930 (string-match
5931 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5932 (let* ((t0 (+ (* 100
5933 (+ (string-to-number (match-string 1 s))
5934 (if (and (match-beginning 4)
5935 (equal (downcase (match-string 4 s)) "pm"))
5936 12 0)))
5937 (if (match-beginning 3)
5938 (string-to-number (match-string 3 s))
5939 0)))
5940 (t1 (concat " "
5941 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
5942 (int-to-string t0))))
5943 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
5944
5945 (defun org-finalize-agenda-entries (list)
5946 "Sort and concatenate the agenda items."
5947 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
5948
5949 (defsubst org-cmp-priority (a b)
5950 "Compare the priorities of string A and B."
5951 (let ((pa (or (get-text-property 1 'priority a) 0))
5952 (pb (or (get-text-property 1 'priority b) 0)))
5953 (cond ((> pa pb) +1)
5954 ((< pa pb) -1)
5955 (t nil))))
5956
5957 (defsubst org-cmp-category (a b)
5958 "Compare the string values of categories of strings A and B."
5959 (let ((ca (or (get-text-property 1 'category a) ""))
5960 (cb (or (get-text-property 1 'category b) "")))
5961 (cond ((string-lessp ca cb) -1)
5962 ((string-lessp cb ca) +1)
5963 (t nil))))
5964
5965 (defsubst org-cmp-time (a b)
5966 "Compare the time-of-day values of strings A and B."
5967 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
5968 (ta (or (get-text-property 1 'time-of-day a) def))
5969 (tb (or (get-text-property 1 'time-of-day b) def)))
5970 (cond ((< ta tb) -1)
5971 ((< tb ta) +1)
5972 (t nil))))
5973
5974 (defun org-entries-lessp (a b)
5975 "Predicate for sorting agenda entries."
5976 ;; The following variables will be used when the form is evaluated.
5977 (let* ((time-up (org-cmp-time a b))
5978 (time-down (if time-up (- time-up) nil))
5979 (priority-up (org-cmp-priority a b))
5980 (priority-down (if priority-up (- priority-up) nil))
5981 (category-up (org-cmp-category a b))
5982 (category-down (if category-up (- category-up) nil))
5983 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
5984 (cdr (assoc
5985 (eval (cons 'or org-agenda-sorting-strategy))
5986 '((-1 . t) (1 . nil) (nil . nil))))))
5987
5988 (defun org-agenda-show-priority ()
5989 "Show the priority of the current item.
5990 This priority is composed of the main priority given with the [#A] cookies,
5991 and by additional input from the age of a schedules or deadline entry."
5992 (interactive)
5993 (let* ((pri (get-text-property (point-at-bol) 'priority)))
5994 (message "Priority is %d" (if pri pri -1000))))
5995
5996 (defun org-agenda-show-tags ()
5997 "Show the tags applicable to the current item."
5998 (interactive)
5999 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6000 (if tags
6001 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6002 (message "No tags associated with this line"))))
6003
6004 (defun org-agenda-goto (&optional highlight)
6005 "Go to the Org-mode file which contains the item at point."
6006 (interactive)
6007 (let* ((marker (or (get-text-property (point) 'org-marker)
6008 (org-agenda-error)))
6009 (buffer (marker-buffer marker))
6010 (pos (marker-position marker)))
6011 (switch-to-buffer-other-window buffer)
6012 (widen)
6013 (goto-char pos)
6014 (when (eq major-mode 'org-mode)
6015 (org-show-hidden-entry)
6016 (save-excursion
6017 (and (outline-next-heading)
6018 (org-flag-heading nil)))) ; show the next heading
6019 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6020
6021 (defun org-agenda-switch-to ()
6022 "Go to the Org-mode file which contains the item at point."
6023 (interactive)
6024 (let* ((marker (or (get-text-property (point) 'org-marker)
6025 (org-agenda-error)))
6026 (buffer (marker-buffer marker))
6027 (pos (marker-position marker)))
6028 (switch-to-buffer buffer)
6029 (delete-other-windows)
6030 (widen)
6031 (goto-char pos)
6032 (when (eq major-mode 'org-mode)
6033 (org-show-hidden-entry)
6034 (save-excursion
6035 (and (outline-next-heading)
6036 (org-flag-heading nil)))))) ; show the next heading
6037
6038 (defun org-agenda-goto-mouse (ev)
6039 "Go to the Org-mode file which contains the item at the mouse click."
6040 (interactive "e")
6041 (mouse-set-point ev)
6042 (org-agenda-goto))
6043
6044 (defun org-agenda-show ()
6045 "Display the Org-mode file which contains the item at point."
6046 (interactive)
6047 (let ((win (selected-window)))
6048 (org-agenda-goto t)
6049 (select-window win)))
6050
6051 (defun org-agenda-recenter (arg)
6052 "Display the Org-mode file which contains the item at point and recenter."
6053 (interactive "P")
6054 (let ((win (selected-window)))
6055 (org-agenda-goto t)
6056 (recenter arg)
6057 (select-window win)))
6058
6059 (defun org-agenda-show-mouse (ev)
6060 "Display the Org-mode file which contains the item at the mouse click."
6061 (interactive "e")
6062 (mouse-set-point ev)
6063 (org-agenda-show))
6064
6065 (defun org-agenda-check-no-diary ()
6066 "Check if the entry is a diary link and abort if yes."
6067 (if (get-text-property (point) 'org-agenda-diary-link)
6068 (org-agenda-error)))
6069
6070 (defun org-agenda-error ()
6071 (error "Command not allowed in this line"))
6072
6073 (defvar org-last-heading-marker (make-marker)
6074 "Marker pointing to the headline that last changed its TODO state
6075 by a remote command from the agenda.")
6076
6077 (defun org-agenda-todo (&optional arg)
6078 "Cycle TODO state of line at point, also in Org-mode file.
6079 This changes the line at point, all other lines in the agenda referring to
6080 the same tree node, and the headline of the tree node in the Org-mode file."
6081 (interactive "P")
6082 (org-agenda-check-no-diary)
6083 (let* ((col (current-column))
6084 (marker (or (get-text-property (point) 'org-marker)
6085 (org-agenda-error)))
6086 (buffer (marker-buffer marker))
6087 (pos (marker-position marker))
6088 (hdmarker (get-text-property (point) 'org-hd-marker))
6089 (buffer-read-only nil)
6090 newhead)
6091 (with-current-buffer buffer
6092 (widen)
6093 (goto-char pos)
6094 (org-show-hidden-entry)
6095 (save-excursion
6096 (and (outline-next-heading)
6097 (org-flag-heading nil))) ; show the next heading
6098 (org-todo arg)
6099 (forward-char 1)
6100 (setq newhead (org-get-heading))
6101 (save-excursion
6102 (org-back-to-heading)
6103 (move-marker org-last-heading-marker (point))))
6104 (beginning-of-line 1)
6105 (save-excursion
6106 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6107 (move-to-column col)))
6108
6109 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6110 "Change all lines in the agenda buffer which match HDMARKER.
6111 The new content of the line will be NEWHEAD (as modified by
6112 `org-format-agenda-item'). HDMARKER is checked with
6113 `equal' against all `org-hd-marker' text properties in the file.
6114 If FIXFACE is non-nil, the face of each item is modified acording to
6115 the new TODO state."
6116 (let* (props m pl undone-face done-face finish new dotime cat tags)
6117 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6118 (save-excursion
6119 (goto-char (point-max))
6120 (beginning-of-line 1)
6121 (while (not finish)
6122 (setq finish (bobp))
6123 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6124 (equal m hdmarker))
6125 (setq props (text-properties-at (point))
6126 dotime (get-text-property (point) 'dotime)
6127 cat (get-text-property (point) 'category)
6128 tags (get-text-property (point) 'tags)
6129 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6130 pl (get-text-property (point) 'prefix-length)
6131 undone-face (get-text-property (point) 'undone-face)
6132 done-face (get-text-property (point) 'done-face))
6133 (move-to-column pl)
6134 (if (looking-at ".*")
6135 (progn
6136 (replace-match new t t)
6137 (beginning-of-line 1)
6138 (add-text-properties (point-at-bol) (point-at-eol) props)
6139 (if fixface
6140 (add-text-properties
6141 (point-at-bol) (point-at-eol)
6142 (list 'face
6143 (if org-last-todo-state-is-todo
6144 undone-face done-face))))
6145 (beginning-of-line 1))
6146 (error "Line update did not work")))
6147 (beginning-of-line 0)))))
6148
6149 (defun org-agenda-priority-up ()
6150 "Increase the priority of line at point, also in Org-mode file."
6151 (interactive)
6152 (org-agenda-priority 'up))
6153
6154 (defun org-agenda-priority-down ()
6155 "Decrease the priority of line at point, also in Org-mode file."
6156 (interactive)
6157 (org-agenda-priority 'down))
6158
6159 (defun org-agenda-priority (&optional force-direction)
6160 "Set the priority of line at point, also in Org-mode file.
6161 This changes the line at point, all other lines in the agenda referring to
6162 the same tree node, and the headline of the tree node in the Org-mode file."
6163 (interactive)
6164 (org-agenda-check-no-diary)
6165 (let* ((marker (or (get-text-property (point) 'org-marker)
6166 (org-agenda-error)))
6167 (buffer (marker-buffer marker))
6168 (pos (marker-position marker))
6169 (hdmarker (get-text-property (point) 'org-hd-marker))
6170 (buffer-read-only nil)
6171 newhead)
6172 (with-current-buffer buffer
6173 (widen)
6174 (goto-char pos)
6175 (org-show-hidden-entry)
6176 (save-excursion
6177 (and (outline-next-heading)
6178 (org-flag-heading nil))) ; show the next heading
6179 (funcall 'org-priority force-direction)
6180 (end-of-line 1)
6181 (setq newhead (org-get-heading)))
6182 (org-agenda-change-all-lines newhead hdmarker)
6183 (beginning-of-line 1)))
6184
6185 (defun org-get-tags-at (&optional pos)
6186 "Get a list of all headline targs applicable at POS.
6187 POS defaults to point. If tags are inherited, the list contains
6188 the targets in the same sequence as the headlines appear, i.e.
6189 the tags of the current headline come last."
6190 (interactive)
6191 (let (tags)
6192 (save-excursion
6193 (goto-char (or pos (point)))
6194 (save-match-data
6195 (org-back-to-heading t)
6196 (condition-case nil
6197 (while t
6198 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6199 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6200 (or org-use-tag-inheritance (error ""))
6201 (org-up-heading-all 1))
6202 (error nil))))
6203 (message "%s" tags)
6204 tags))
6205
6206 (defun org-agenda-set-tags ()
6207 "Set tags for the current headline."
6208 (interactive)
6209 (org-agenda-check-no-diary)
6210 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6211 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6212 (org-agenda-error)))
6213 (buffer (marker-buffer hdmarker))
6214 (pos (marker-position hdmarker))
6215 (buffer-read-only nil)
6216 newhead)
6217 (with-current-buffer buffer
6218 (widen)
6219 (goto-char pos)
6220 (org-show-hidden-entry)
6221 (save-excursion
6222 (and (outline-next-heading)
6223 (org-flag-heading nil))) ; show the next heading
6224 (call-interactively 'org-set-tags)
6225 (end-of-line 1)
6226 (setq newhead (org-get-heading)))
6227 (org-agenda-change-all-lines newhead hdmarker)
6228 (beginning-of-line 1)))
6229
6230 (defun org-agenda-date-later (arg &optional what)
6231 "Change the date of this item to one day later."
6232 (interactive "p")
6233 (org-agenda-check-type t 'agenda 'timeline)
6234 (org-agenda-check-no-diary)
6235 (let* ((marker (or (get-text-property (point) 'org-marker)
6236 (org-agenda-error)))
6237 (buffer (marker-buffer marker))
6238 (pos (marker-position marker)))
6239 (with-current-buffer buffer
6240 (widen)
6241 (goto-char pos)
6242 (if (not (org-at-timestamp-p))
6243 (error "Cannot find time stamp"))
6244 (org-timestamp-change arg (or what 'day))
6245 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6246
6247 (defun org-agenda-date-earlier (arg &optional what)
6248 "Change the date of this item to one day earlier."
6249 (interactive "p")
6250 (org-agenda-date-later (- arg) what))
6251
6252 (defun org-agenda-date-prompt (arg)
6253 "Change the date of this item. Date is prompted for, with default today.
6254 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6255 be used to request time specification in the time stamp."
6256 (interactive "P")
6257 (org-agenda-check-type t 'agenda 'timeline)
6258 (org-agenda-check-no-diary)
6259 (let* ((marker (or (get-text-property (point) 'org-marker)
6260 (org-agenda-error)))
6261 (buffer (marker-buffer marker))
6262 (pos (marker-position marker)))
6263 (with-current-buffer buffer
6264 (widen)
6265 (goto-char pos)
6266 (if (not (org-at-timestamp-p))
6267 (error "Cannot find time stamp"))
6268 (org-time-stamp arg)
6269 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6270
6271 (defun org-get-heading ()
6272 "Return the heading of the current entry, without the stars."
6273 (save-excursion
6274 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6275 ;;FIXME???????? (and (bolp) (end-of-line 1))
6276 (if (and (re-search-backward "[\r\n]\\*" nil t)
6277 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6278 (match-string 1)
6279 "")))
6280
6281 (defun org-agenda-diary-entry ()
6282 "Make a diary entry, like the `i' command from the calendar.
6283 All the standard commands work: block, weekly etc."
6284 (interactive)
6285 (org-agenda-check-type t 'agenda 'timeline)
6286 (require 'diary-lib)
6287 (let* ((char (progn
6288 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6289 (read-char-exclusive)))
6290 (cmd (cdr (assoc char
6291 '((?d . insert-diary-entry)
6292 (?w . insert-weekly-diary-entry)
6293 (?m . insert-monthly-diary-entry)
6294 (?y . insert-yearly-diary-entry)
6295 (?a . insert-anniversary-diary-entry)
6296 (?b . insert-block-diary-entry)
6297 (?c . insert-cyclic-diary-entry)))))
6298 (oldf (symbol-function 'calendar-cursor-to-date))
6299 (point (point))
6300 (mark (or (mark t) (point))))
6301 (unless cmd
6302 (error "No command associated with <%c>" char))
6303 (unless (and (get-text-property point 'day)
6304 (or (not (equal ?b char))
6305 (get-text-property mark 'day)))
6306 (error "Don't know which date to use for diary entry"))
6307 ;; We implement this by hacking the `calendar-cursor-to-date' function
6308 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6309 (let ((calendar-mark-ring
6310 (list (calendar-gregorian-from-absolute
6311 (or (get-text-property mark 'day)
6312 (get-text-property point 'day))))))
6313 (unwind-protect
6314 (progn
6315 (fset 'calendar-cursor-to-date
6316 (lambda (&optional error)
6317 (calendar-gregorian-from-absolute
6318 (get-text-property point 'day))))
6319 (call-interactively cmd))
6320 (fset 'calendar-cursor-to-date oldf)))))
6321
6322
6323 (defun org-agenda-execute-calendar-command (cmd)
6324 "Execute a calendar command from the agenda, with the date associated to
6325 the cursor position."
6326 (org-agenda-check-type t 'agenda 'timeline)
6327 (require 'diary-lib)
6328 (unless (get-text-property (point) 'day)
6329 (error "Don't know which date to use for calendar command"))
6330 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6331 (point (point))
6332 (date (calendar-gregorian-from-absolute
6333 (get-text-property point 'day)))
6334 (displayed-day (extract-calendar-day date))
6335 (displayed-month (extract-calendar-month date))
6336 (displayed-year (extract-calendar-year date)))
6337 (unwind-protect
6338 (progn
6339 (fset 'calendar-cursor-to-date
6340 (lambda (&optional error)
6341 (calendar-gregorian-from-absolute
6342 (get-text-property point 'day))))
6343 (call-interactively cmd))
6344 (fset 'calendar-cursor-to-date oldf))))
6345
6346 (defun org-agenda-phases-of-moon ()
6347 "Display the phases of the moon for the 3 months around the cursor date."
6348 (interactive)
6349 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6350
6351 (defun org-agenda-holidays ()
6352 "Display the holidays for the 3 months around the cursor date."
6353 (interactive)
6354 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6355
6356 (defun org-agenda-sunrise-sunset (arg)
6357 "Display sunrise and sunset for the cursor date.
6358 Latitude and longitude can be specified with the variables
6359 `calendar-latitude' and `calendar-longitude'. When called with prefix
6360 argument, latitude and longitude will be prompted for."
6361 (interactive "P")
6362 (let ((calendar-longitude (if arg nil calendar-longitude))
6363 (calendar-latitude (if arg nil calendar-latitude))
6364 (calendar-location-name
6365 (if arg "the given coordinates" calendar-location-name)))
6366 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6367
6368 (defun org-agenda-goto-calendar ()
6369 "Open the Emacs calendar with the date at the cursor."
6370 (interactive)
6371 (org-agenda-check-type t 'agenda 'timeline)
6372 (let* ((day (or (get-text-property (point) 'day)
6373 (error "Don't know which date to open in calendar")))
6374 (date (calendar-gregorian-from-absolute day))
6375 (calendar-move-hook nil)
6376 (view-diary-entries-initially nil))
6377 (calendar)
6378 (calendar-goto-date date)))
6379
6380 (defun org-calendar-goto-agenda ()
6381 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6382 This is a command that has to be installed in `calendar-mode-map'."
6383 (interactive)
6384 (org-agenda-list nil (calendar-absolute-from-gregorian
6385 (calendar-cursor-to-date))
6386 nil t))
6387
6388 (defun org-agenda-convert-date ()
6389 (interactive)
6390 (org-agenda-check-type t 'agenda 'timeline)
6391 (let ((day (get-text-property (point) 'day))
6392 date s)
6393 (unless day
6394 (error "Don't know which date to convert"))
6395 (setq date (calendar-gregorian-from-absolute day))
6396 (setq s (concat
6397 "Gregorian: " (calendar-date-string date) "\n"
6398 "ISO: " (calendar-iso-date-string date) "\n"
6399 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6400 "Julian: " (calendar-julian-date-string date) "\n"
6401 "Astron. JD: " (calendar-astro-date-string date)
6402 " (Julian date number at noon UTC)\n"
6403 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6404 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6405 "French: " (calendar-french-date-string date) "\n"
6406 "Mayan: " (calendar-mayan-date-string date) "\n"
6407 "Coptic: " (calendar-coptic-date-string date) "\n"
6408 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6409 "Persian: " (calendar-persian-date-string date) "\n"
6410 "Chinese: " (calendar-chinese-date-string date) "\n"))
6411 (with-output-to-temp-buffer "*Dates*"
6412 (princ s))
6413 (if (fboundp 'fit-window-to-buffer)
6414 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6415
6416 ;;; Tags
6417
6418 (defun org-scan-tags (action matcher &optional todo-only)
6419 "Scan headline tags with inheritance and produce output ACTION.
6420 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6421 evaluated, testing if a given set of tags qualifies a headline for
6422 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6423 are included in the output."
6424 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6425 (mapconcat 'regexp-quote
6426 (nreverse (cdr (reverse org-todo-keywords)))
6427 "\\|")
6428 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6429 (props (list 'face nil
6430 'done-face 'org-done
6431 'undone-face nil
6432 'mouse-face 'highlight
6433 'keymap org-agenda-keymap
6434 'help-echo
6435 (format "mouse-2 or RET jump to org file %s"
6436 (abbreviate-file-name (buffer-file-name)))))
6437 lspos
6438 tags tags-list tags-alist (llast 0) rtn level category i txt
6439 todo marker)
6440
6441 (save-excursion
6442 (goto-char (point-min))
6443 (when (eq action 'sparse-tree) (hide-sublevels 1))
6444 (while (re-search-forward re nil t)
6445 (setq todo (if (match-end 1) (match-string 2))
6446 tags (if (match-end 4) (match-string 4)))
6447 (goto-char (setq lspos (1+ (match-beginning 0))))
6448 (setq level (outline-level)
6449 category (org-get-category))
6450 (setq i llast llast level)
6451 ;; remove tag lists from same and sublevels
6452 (while (>= i level)
6453 (when (setq entry (assoc i tags-alist))
6454 (setq tags-alist (delete entry tags-alist)))
6455 (setq i (1- i)))
6456 ;; add the nex tags
6457 (when tags
6458 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6459 tags-alist
6460 (cons (cons level tags) tags-alist)))
6461 ;; compile tags for current headline
6462 (setq tags-list
6463 (if org-use-tag-inheritance
6464 (apply 'append (mapcar 'cdr tags-alist))
6465 tags))
6466 (when (and (or (not todo-only) todo)
6467 (eval matcher))
6468 ;; list this headline
6469 (if (eq action 'sparse-tree)
6470 (progn
6471 (org-show-hierarchy-above))
6472 (setq txt (org-format-agenda-item
6473 ""
6474 (concat
6475 (if org-tags-match-list-sublevels
6476 (make-string (1- level) ?.) "")
6477 (org-get-heading))
6478 category tags-list))
6479 (goto-char lspos)
6480 (setq marker (org-agenda-new-marker))
6481 (add-text-properties
6482 0 (length txt)
6483 (append (list 'org-marker marker 'org-hd-marker marker
6484 'category category)
6485 props)
6486 txt)
6487 (push txt rtn))
6488 ;; if we are to skip sublevels, jump to end of subtree
6489 (point)
6490 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6491 (nreverse rtn)))
6492
6493 (defun org-tags-sparse-tree (&optional arg match)
6494 "Create a sparse tree according to tags search string MATCH.
6495 MATCH can contain positive and negative selection of tags, like
6496 \"+WORK+URGENT-WITHBOSS\"."
6497 (interactive "P")
6498 (let ((org-show-following-heading nil)
6499 (org-show-hierarchy-above nil))
6500 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6501
6502 (defun org-make-tags-matcher (match)
6503 "Create the TAGS matcher form for the tags-selecting string MATCH."
6504 (unless match
6505 ;; Get a new match request, with completion
6506 (setq org-last-tags-completion-table
6507 (or (org-get-buffer-tags)
6508 org-last-tags-completion-table))
6509 (setq match (completing-read
6510 "Tags: " 'org-tags-completion-function nil nil nil
6511 'org-tags-history)))
6512 ;; parse the string and create a lisp form
6513 (let ((match0 match) minus tag mm matcher orterms term orlist)
6514 (setq orterms (org-split-string match "|"))
6515 (while (setq term (pop orterms))
6516 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
6517 (setq minus (and (match-end 1)
6518 (equal (match-string 1 term) "-"))
6519 tag (match-string 2 term)
6520 term (substring term (match-end 0))
6521 mm (list 'member (downcase tag) 'tags-list)
6522 mm (if minus (list 'not mm) mm))
6523 (push mm matcher))
6524 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6525 orlist)
6526 (setq matcher nil))
6527 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6528 ;; Return the string and lisp forms of the matcher
6529 (cons match0 matcher)))
6530
6531 ;;;###autoload
6532 (defun org-tags-view (&optional todo-only match keep-modes)
6533 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
6534 The prefix arg TODO-ONLY limits the search to TODO entries."
6535 (interactive "P")
6536 (org-agenda-maybe-reset-markers 'force)
6537 (org-compile-prefix-format org-agenda-prefix-format)
6538 (let* ((org-agenda-keep-modes keep-modes)
6539 (org-tags-match-list-sublevels
6540 (if todo-only t org-tags-match-list-sublevels))
6541 (win (selected-window))
6542 (completion-ignore-case t)
6543 rtn rtnall files file pos matcher
6544 buffer)
6545 (setq matcher (org-make-tags-matcher match)
6546 match (car matcher) matcher (cdr matcher))
6547 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6548 (progn
6549 (delete-other-windows)
6550 (switch-to-buffer-other-window
6551 (get-buffer-create org-agenda-buffer-name))))
6552 (setq buffer-read-only nil)
6553 (erase-buffer)
6554 (org-agenda-mode) (setq buffer-read-only nil)
6555 (set (make-local-variable 'org-agenda-type) 'tags)
6556 (set (make-local-variable 'org-agenda-redo-command)
6557 (list 'org-tags-view (list 'quote todo-only)
6558 (list 'if 'current-prefix-arg nil match) t))
6559 (setq files (org-agenda-files)
6560 rtnall nil)
6561 (while (setq file (pop files))
6562 (catch 'nextfile
6563 (org-check-agenda-file file)
6564 (setq buffer (if (file-exists-p file)
6565 (org-get-agenda-file-buffer file)
6566 (error "No such file %s" file)))
6567 (if (not buffer)
6568 ;; If file does not exist, merror message to agenda
6569 (setq rtn (list
6570 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6571 rtnall (append rtnall rtn))
6572 (with-current-buffer buffer
6573 (unless (eq major-mode 'org-mode)
6574 (error "Agenda file %s is not in `org-mode'" file))
6575 (save-excursion
6576 (save-restriction
6577 (if org-respect-restriction
6578 (if (org-region-active-p)
6579 ;; Respect a region to restrict search
6580 (narrow-to-region (region-beginning) (region-end)))
6581 ;; If we work for the calendar or many files,
6582 ;; get rid of any restriction
6583 (widen))
6584 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6585 (setq rtnall (append rtnall rtn))))))))
6586 (insert "Headlines with TAGS match: ")
6587 (add-text-properties (point-min) (1- (point))
6588 (list 'face 'org-link))
6589 (setq pos (point))
6590 (insert match "\n")
6591 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6592 (setq pos (point))
6593 (insert "Press `C-u r' to search again with new search string\n")
6594 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6595 (when rtnall
6596 (insert (mapconcat 'identity rtnall "\n")))
6597 (goto-char (point-min))
6598 (setq buffer-read-only t)
6599 (org-fit-agenda-window)
6600 (if (not org-select-agenda-window) (select-window win))))
6601
6602 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6603 (defun org-set-tags (&optional arg just-align)
6604 "Set the tags for the current headline.
6605 With prefix ARG, realign all tags in headings in the current buffer."
6606 (interactive)
6607 (let* (;(inherit (org-get-inherited-tags))
6608 (re (concat "^" outline-regexp))
6609 (col (current-column))
6610 (current (org-get-tags))
6611 tags hd empty invis)
6612 (if arg
6613 (save-excursion
6614 (goto-char (point-min))
6615 (while (re-search-forward re nil t)
6616 (org-set-tags nil t))
6617 (message "All tags realigned to column %d" org-tags-column))
6618 (if just-align
6619 (setq tags current)
6620 (setq org-last-tags-completion-table
6621 (or (org-get-buffer-tags)
6622 org-last-tags-completion-table))
6623 (setq tags
6624 (let ((org-add-colon-after-tag-completion t))
6625 (completing-read "Tags: " 'org-tags-completion-function
6626 nil nil current 'org-tags-history)))
6627 (while (string-match "[-+&]+" tags)
6628 (setq tags (replace-match ":" t t tags)))
6629 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6630 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6631 (unless (string-match "^:" tags) (setq tags (concat ":" tags)))))
6632 (if (equal current "")
6633 (progn
6634 (end-of-line 1)
6635 (or empty (insert-before-markers " ")))
6636 (beginning-of-line 1)
6637 (setq invis (org-invisible-p))
6638 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6639 (setq hd (match-string 1))
6640 (delete-region (match-beginning 0) (match-end 0))
6641 (insert-before-markers (org-trim hd) (if empty "" " ")))
6642 ;; FIXME: What happens when adding a new tag??? Seems OK!!!
6643 (unless (equal tags "")
6644 (move-to-column (max (current-column)
6645 (if (> org-tags-column 0)
6646 org-tags-column
6647 (- (- org-tags-column) (length tags))))
6648 t)
6649 (insert-before-markers tags)
6650 (if (and (not invis) (org-invisible-p))
6651 (outline-flag-region (point-at-bol) (point) nil)))
6652 (move-to-column col))))
6653
6654 (defun org-tags-completion-function (string predicate &optional flag)
6655 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6656 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6657 (setq s1 (match-string 1 string)
6658 s2 (match-string 2 string))
6659 (setq s1 "" s2 string))
6660 (cond
6661 ((eq flag nil)
6662 ;; try completion
6663 (setq rtn (try-completion s2 ctable))
6664 (if (stringp rtn)
6665 (concat s1 s2 (substring rtn (length s2))
6666 (if (and org-add-colon-after-tag-completion
6667 (assoc rtn ctable))
6668 ":" "")))
6669 )
6670 ((eq flag t)
6671 ;; all-completions
6672 (all-completions s2 ctable)
6673 )
6674 ((eq flag 'lambda)
6675 ;; exact match?
6676 (assoc s2 ctable)))
6677 ))
6678
6679 (defun org-get-tags ()
6680 "Get the TAGS string in the current headline."
6681 (unless (org-on-heading-p)
6682 (error "Not on a heading"))
6683 (save-excursion
6684 (beginning-of-line 1)
6685 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
6686 (match-string 1)
6687 "")))
6688
6689 (defun org-get-buffer-tags ()
6690 "Get a table of all tags used in the buffer, for completion."
6691 (let (tags)
6692 (save-excursion
6693 (goto-char (point-min))
6694 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
6695 (mapc (lambda (x) (add-to-list 'tags x))
6696 (org-split-string (match-string 1) ":"))))
6697 (mapcar 'list tags)))
6698
6699 ;;; Link Stuff
6700
6701 (defun org-find-file-at-mouse (ev)
6702 "Open file link or URL at mouse."
6703 (interactive "e")
6704 (mouse-set-point ev)
6705 (org-open-at-point 'in-emacs))
6706
6707 (defun org-open-at-mouse (ev)
6708 "Open file link or URL at mouse."
6709 (interactive "e")
6710 (mouse-set-point ev)
6711 (org-open-at-point))
6712
6713 (defun org-open-at-point (&optional in-emacs)
6714 "Open link at or after point.
6715 If there is no link at point, this function will search forward up to
6716 the end of the current subtree.
6717 Normally, files will be opened by an appropriate application. If the
6718 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6719 (interactive "P")
6720 (org-remove-occur-highlights nil nil t)
6721 (if (org-at-timestamp-p)
6722 (org-agenda-list nil (time-to-days (org-time-string-to-time
6723 (substring (match-string 1) 0 10)))
6724 1)
6725 (let (type path link line search (pos (point)))
6726 (catch 'match
6727 (save-excursion
6728 (skip-chars-forward "^]\n\r")
6729 (when (and (re-search-backward "\\[\\[" nil t)
6730 (looking-at org-bracket-link-regexp)
6731 (<= (match-beginning 0) pos)
6732 (>= (match-end 0) pos))
6733 (setq link (match-string 1))
6734 (while (string-match " *\n *" link)
6735 (setq link (replace-match " " t t link)))
6736 (if (string-match org-link-regexp link)
6737 (setq type (match-string 1)
6738 path (match-string 2))
6739 (setq type "thisfile"
6740 path link))
6741 (throw 'match t)))
6742
6743 (when (get-text-property (point) 'org-linked-text)
6744 (setq type "thisfile"
6745 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6746 (1+ (point)) (point))
6747 path (buffer-substring
6748 (previous-single-property-change pos 'org-linked-text)
6749 (next-single-property-change pos 'org-linked-text)))
6750 (throw 'match t))
6751
6752 (save-excursion
6753 (skip-chars-backward
6754 (concat (if org-allow-space-in-links "^" "^ ")
6755 org-non-link-chars))
6756 (when (or (looking-at org-link-regexp)
6757 (and (re-search-forward org-link-regexp (point-at-eol) t)
6758 (<= (match-beginning 0) pos)
6759 (>= (match-end 0) pos)))
6760 (setq type (match-string 1)
6761 path (match-string 2))
6762 (throw 'match t)))
6763 (save-excursion
6764 (skip-chars-backward "^ \t\n\r")
6765 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
6766 (setq type "tags"
6767 path (match-string 1))
6768 (while (string-match ":" path)
6769 (setq path (replace-match "+" t t path)))
6770 (throw 'match t)))
6771 (save-excursion
6772 (skip-chars-backward "a-zA-Z_")
6773 (when (and org-activate-camels
6774 (looking-at org-camel-regexp))
6775 (setq type "camel" path (match-string 0))
6776 (if (equal (char-before) ?*)
6777 (setq path (concat "*" path))))
6778 (throw 'match t))
6779 (save-excursion
6780 (when (re-search-forward
6781 org-link-regexp
6782 (save-excursion
6783 (condition-case nil
6784 (progn (outline-end-of-subtree) (max pos (point)))
6785 (error (end-of-line 1) (point))))
6786 t)
6787 (setq type (match-string 1)
6788 path (match-string 2)))))
6789 (unless path
6790 (error "No link found"))
6791 ;; Remove any trailing spaces in path
6792 (if (string-match " +\\'" path)
6793 (setq path (replace-match "" t t path)))
6794
6795 (cond
6796
6797 ((string= type "tags")
6798 (org-tags-view in-emacs path))
6799 ((or (string= type "camel")
6800 (string= type "thisfile"))
6801 (org-mark-ring-push)
6802 (org-link-search
6803 path
6804 (cond ((equal in-emacs '(4)) 'occur)
6805 ((equal in-emacs '(16)) 'org-occur)
6806 (t nil))))
6807
6808 ((string= type "file")
6809 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6810 (setq line (string-to-number (match-string 1 path))
6811 path (substring path 0 (match-beginning 0)))
6812 (if (string-match "::\\(.+\\)\\'" path)
6813 (setq search (match-string 1 path)
6814 path (substring path 0 (match-beginning 0)))))
6815 (org-open-file path in-emacs line search))
6816
6817 ((string= type "news")
6818 (org-follow-gnus-link path))
6819
6820 ((string= type "bbdb")
6821 (org-follow-bbdb-link path))
6822
6823 ((string= type "gnus")
6824 (let (group article)
6825 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6826 (error "Error in Gnus link"))
6827 (setq group (match-string 1 path)
6828 article (match-string 3 path))
6829 (org-follow-gnus-link group article)))
6830
6831 ((string= type "vm")
6832 (let (folder article)
6833 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6834 (error "Error in VM link"))
6835 (setq folder (match-string 1 path)
6836 article (match-string 3 path))
6837 ;; in-emacs is the prefix arg, will be interpreted as read-only
6838 (org-follow-vm-link folder article in-emacs)))
6839
6840 ((string= type "wl")
6841 (let (folder article)
6842 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6843 (error "Error in Wanderlust link"))
6844 (setq folder (match-string 1 path)
6845 article (match-string 3 path))
6846 (org-follow-wl-link folder article)))
6847
6848 ((string= type "mhe")
6849 (let (folder article)
6850 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6851 (error "Error in MHE link"))
6852 (setq folder (match-string 1 path)
6853 article (match-string 3 path))
6854 (org-follow-mhe-link folder article)))
6855
6856 ((string= type "rmail")
6857 (let (folder article)
6858 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6859 (error "Error in RMAIL link"))
6860 (setq folder (match-string 1 path)
6861 article (match-string 3 path))
6862 (org-follow-rmail-link folder article)))
6863
6864 ((string= type "shell")
6865 (let ((cmd path))
6866 (while (string-match "@{" cmd)
6867 (setq cmd (replace-match "<" t t cmd)))
6868 (while (string-match "@}" cmd)
6869 (setq cmd (replace-match ">" t t cmd)))
6870 (if (or (not org-confirm-shell-links)
6871 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6872 (shell-command cmd)
6873 (error "Abort"))))
6874
6875 (t
6876 (browse-url-at-point))))))
6877
6878 (defun org-link-search (s &optional type)
6879 "Search for a link search option.
6880 When S is a CamelCaseWord, search for a target, or for a sentence containing
6881 the words. If S is surrounded by forward slashes, it is interpreted as a
6882 regular expression. In org-mode files, this will create an `org-occur'
6883 sparse tree. In ordinary files, `occur' will be used to list matches.
6884 If the current buffer is in `dired-mode', grep will be used to search
6885 in all files."
6886 (let ((case-fold-search t)
6887 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6888 (pos (point))
6889 (pre "") (post "")
6890 words re0 re1 re2 re3 re4 re5 reall camel)
6891 (cond ((save-excursion
6892 (goto-char (point-min))
6893 (and
6894 (re-search-forward
6895 (concat "<<" (regexp-quote s0) ">>") nil t)
6896 (setq pos (match-beginning 0))))
6897 ;; There is an exact target for this
6898 (goto-char pos))
6899 ((string-match "^/\\(.*\\)/$" s)
6900 ;; A regular expression
6901 (cond
6902 ((eq major-mode 'org-mode)
6903 (org-occur (match-string 1 s)))
6904 ;;((eq major-mode 'dired-mode)
6905 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6906 (t (org-do-occur (match-string 1 s)))))
6907 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
6908 t)
6909 ;; A camel or a normal search string
6910 (when (equal (string-to-char s) ?*)
6911 ;; Anchor on headlines, post may include tags.
6912 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6913 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
6914 s (substring s 1)))
6915 (remove-text-properties
6916 0 (length s)
6917 '(face nil mouse-face nil keymap nil fontified nil) s)
6918 ;; Make a series of regular expressions to find a match
6919 (setq words
6920 (if camel
6921 (org-camel-to-words s)
6922 (org-split-string s "[ \n\r\t]+"))
6923 re0 (concat "<<" (regexp-quote s0) ">>")
6924 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6925 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6926 re1 (concat pre re2 post)
6927 re3 (concat pre re4 post)
6928 re5 (concat pre ".*" re4)
6929 re2 (concat pre re2)
6930 re4 (concat pre re4)
6931 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6932 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6933 re5 "\\)"
6934 ))
6935 (cond
6936 ((eq type 'org-occur) (org-occur reall))
6937 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6938 (t (goto-char (point-min))
6939 (if (or (re-search-forward re0 nil t)
6940 (re-search-forward re1 nil t)
6941 (re-search-forward re2 nil t)
6942 (re-search-forward re3 nil t)
6943 (re-search-forward re4 nil t)
6944 (re-search-forward re5 nil t))
6945 (goto-char (match-beginning 0))
6946 (goto-char pos)
6947 (error "No match")))))
6948 (t
6949 ;; Normal string-search
6950 (goto-char (point-min))
6951 (if (search-forward s nil t)
6952 (goto-char (match-beginning 0))
6953 (error "No match"))))
6954 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
6955
6956 (defun org-do-occur (regexp &optional cleanup)
6957 "Call the Emacs command `occur'.
6958 If CLEANUP is non-nil, remove the printout of the regular expression
6959 in the *Occur* buffer. This is useful if the regex is long and not useful
6960 to read."
6961 (occur regexp)
6962 (when cleanup
6963 (let ((cwin (selected-window)) win beg end)
6964 (when (setq win (get-buffer-window "*Occur*"))
6965 (select-window win))
6966 (goto-char (point-min))
6967 (when (re-search-forward "match[a-z]+" nil t)
6968 (setq beg (match-end 0))
6969 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6970 (setq end (1- (match-beginning 0)))))
6971 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
6972 (goto-char (point-min))
6973 (select-window cwin))))
6974
6975 (defvar org-mark-ring nil
6976 "Mark ring for positions before jumps in Org-mode.")
6977 (defvar org-mark-ring-last-goto nil
6978 "Last position in the mark ring used to go back.")
6979 ;; Fill and close the ring
6980 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
6981 (loop for i from 1 to org-mark-ring-length do
6982 (push (make-marker) org-mark-ring))
6983 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
6984 org-mark-ring)
6985
6986 (defun org-mark-ring-push (&optional pos buffer)
6987 "Put the current position or POS into the mark ring and rotate it."
6988 (interactive)
6989 (setq pos (or pos (point)))
6990 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
6991 (move-marker (car org-mark-ring)
6992 (or pos (point))
6993 (or buffer (current-buffer)))
6994 (message
6995 (substitute-command-keys
6996 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
6997
6998 (defun org-mark-ring-goto (&optional n)
6999 "Jump to the previous position in the mark ring.
7000 With prefix arg N, jump back that many stored positions. When
7001 called several times in succession, walk through the entire ring.
7002 Org-mode commands jumping to a different position in the current file,
7003 or to another Org-mode file, automatically push the old position
7004 onto the ring."
7005 (interactive "p")
7006 (let (p m)
7007 (if (eq last-command this-command)
7008 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7009 (setq p org-mark-ring))
7010 (setq org-mark-ring-last-goto p)
7011 (setq m (car p))
7012 (switch-to-buffer (marker-buffer m))
7013 (goto-char m)
7014 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7015
7016 (defun org-camel-to-words (s)
7017 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7018 (let ((case-fold-search nil)
7019 words)
7020 (while (string-match "[a-z][A-Z]" s)
7021 (push (substring s 0 (1+ (match-beginning 0))) words)
7022 (setq s (substring s (1+ (match-beginning 0)))))
7023 (nreverse (cons s words))))
7024
7025 (defun org-remove-angle-brackets (s)
7026 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7027 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7028 s)
7029 (defun org-add-angle-brackets (s)
7030 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7031 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7032 s)
7033
7034 (defun org-follow-bbdb-link (name)
7035 "Follow a BBDB link to NAME."
7036 (require 'bbdb)
7037 (let ((inhibit-redisplay t)
7038 (bbdb-electric-p nil))
7039 (catch 'exit
7040 ;; Exact match on name
7041 (bbdb-name (concat "\\`" name "\\'") nil)
7042 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7043 ;; Exact match on name
7044 (bbdb-company (concat "\\`" name "\\'") nil)
7045 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7046 ;; Partial match on name
7047 (bbdb-name name nil)
7048 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7049 ;; Partial match on company
7050 (bbdb-company name nil)
7051 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7052 ;; General match including network address and notes
7053 (bbdb name nil)
7054 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7055 (delete-window (get-buffer-window "*BBDB*"))
7056 (error "No matching BBDB record")))))
7057
7058 (defun org-follow-gnus-link (&optional group article)
7059 "Follow a Gnus link to GROUP and ARTICLE."
7060 (require 'gnus)
7061 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7062 (if group (gnus-fetch-group group))
7063 (if article
7064 (or (gnus-summary-goto-article article nil 'force)
7065 (if (fboundp 'gnus-summary-insert-cached-articles)
7066 (progn
7067 (gnus-summary-insert-cached-articles)
7068 (gnus-summary-goto-article article nil 'force))
7069 (message "Message could not be found.")))))
7070
7071 (defun org-follow-vm-link (&optional folder article readonly)
7072 "Follow a VM link to FOLDER and ARTICLE."
7073 (require 'vm)
7074 (setq article (org-add-angle-brackets article))
7075 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7076 ;; ange-ftp or efs or tramp access
7077 (let ((user (or (match-string 1 folder) (user-login-name)))
7078 (host (match-string 2 folder))
7079 (file (match-string 3 folder)))
7080 (cond
7081 ((featurep 'tramp)
7082 ;; use tramp to access the file
7083 (if org-xemacs-p
7084 (setq folder (format "[%s@%s]%s" user host file))
7085 (setq folder (format "/%s@%s:%s" user host file))))
7086 (t
7087 ;; use ange-ftp or efs
7088 (require (if org-xemacs-p 'efs 'ange-ftp))
7089 (setq folder (format "/%s@%s:%s" user host file))))))
7090 (when folder
7091 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7092 (sit-for 0.1)
7093 (when article
7094 (vm-select-folder-buffer)
7095 (widen)
7096 (let ((case-fold-search t))
7097 (goto-char (point-min))
7098 (if (not (re-search-forward
7099 (concat "^" "message-id: *" (regexp-quote article))))
7100 (error "Could not find the specified message in this folder"))
7101 (vm-isearch-update)
7102 (vm-isearch-narrow)
7103 (vm-beginning-of-message)
7104 (vm-summarize)))))
7105
7106 (defun org-follow-wl-link (folder article)
7107 "Follow a Wanderlust link to FOLDER and ARTICLE."
7108 (setq article (org-add-angle-brackets article))
7109 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7110 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7111 (wl-summary-redisplay))
7112
7113 (defun org-follow-rmail-link (folder article)
7114 "Follow an RMAIL link to FOLDER and ARTICLE."
7115 (setq article (org-add-angle-brackets article))
7116 (let (message-number)
7117 (save-excursion
7118 (save-window-excursion
7119 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7120 (setq message-number
7121 (save-restriction
7122 (widen)
7123 (goto-char (point-max))
7124 (if (re-search-backward
7125 (concat "^Message-ID:\\s-+" (regexp-quote
7126 (or article "")))
7127 nil t)
7128 (rmail-what-message))))))
7129 (if message-number
7130 (progn
7131 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7132 (rmail-show-message message-number)
7133 message-number)
7134 (error "Message not found"))))
7135
7136 ;; mh-e integration based on planner-mode
7137 (defun org-mhe-get-message-real-folder ()
7138 "Return the name of the current message real folder, so if you use
7139 sequences, it will now work."
7140 (save-excursion
7141 (let* ((folder
7142 (if (equal major-mode 'mh-folder-mode)
7143 mh-current-folder
7144 ;; Refer to the show buffer
7145 mh-show-folder-buffer))
7146 (end-index
7147 (if (boundp 'mh-index-folder)
7148 (min (length mh-index-folder) (length folder))))
7149 )
7150 ;; a simple test on mh-index-data does not work, because
7151 ;; mh-index-data is always nil in a show buffer.
7152 (if (and (boundp 'mh-index-folder)
7153 (string= mh-index-folder (substring folder 0 end-index)))
7154 (if (equal major-mode 'mh-show-mode)
7155 (save-window-excursion
7156 (when (buffer-live-p (get-buffer folder))
7157 (progn
7158 (pop-to-buffer folder)
7159 (org-mhe-get-message-folder-from-index)
7160 )
7161 ))
7162 (org-mhe-get-message-folder-from-index)
7163 )
7164 folder
7165 )
7166 )))
7167
7168 (defun org-mhe-get-message-folder-from-index ()
7169 "Returns the name of the message folder in a index folder buffer."
7170 (save-excursion
7171 (mh-index-previous-folder)
7172 (if (not (re-search-forward "^\\(+.*\\)$" nil t))
7173 (message "Problem getting folder from index.")
7174 (message (match-string 1)))))
7175
7176 (defun org-mhe-get-message-folder ()
7177 "Return the name of the current message folder. Be careful if you
7178 use sequences."
7179 (save-excursion
7180 (if (equal major-mode 'mh-folder-mode)
7181 mh-current-folder
7182 ;; Refer to the show buffer
7183 mh-show-folder-buffer)))
7184
7185 (defun org-mhe-get-message-num ()
7186 "Return the number of the current message. Be careful if you
7187 use sequences."
7188 (save-excursion
7189 (if (equal major-mode 'mh-folder-mode)
7190 (mh-get-msg-num nil)
7191 ;; Refer to the show buffer
7192 (mh-show-buffer-message-number))))
7193
7194 (defun org-mhe-get-header (header)
7195 "Return a header of the message in folder mode. This will create a
7196 show buffer for the corresponding message. If you have a more clever
7197 idea..."
7198 (let* ((folder (org-mhe-get-message-folder))
7199 (num (org-mhe-get-message-num))
7200 (buffer (get-buffer-create (concat "show-" folder)))
7201 (header-field))
7202 (with-current-buffer buffer
7203 (mh-display-msg num folder)
7204 (if (equal major-mode 'mh-folder-mode)
7205 (mh-header-display)
7206 (mh-show-header-display))
7207 (set-buffer buffer)
7208 (setq header-field (mh-get-header-field header))
7209 (if (equal major-mode 'mh-folder-mode)
7210 (mh-show)
7211 (mh-show-show))
7212 header-field)))
7213
7214 (defun org-follow-mhe-link (folder article)
7215 "Follow an MHE link to FOLDER and ARTICLE."
7216 (setq article (org-add-angle-brackets article))
7217 (require 'mh-e)
7218 (mh-find-path)
7219 (let* ((show-buf (concat "show-" folder)))
7220 (mh-visit-folder folder)
7221 (get-buffer-create show-buf)
7222 (mh-show-msg
7223 (string-to-number
7224 (car (split-string
7225 (with-temp-buffer
7226 (call-process
7227 (expand-file-name "pick" mh-progs)
7228 nil t nil
7229 folder
7230 "--message-id"
7231 article)
7232 (buffer-string))
7233 "\n"))))
7234 (pop-to-buffer show-buf)))
7235
7236 (defun org-open-file (path &optional in-emacs line search)
7237 "Open the file at PATH.
7238 First, this expands any special file name abbreviations. Then the
7239 configuration variable `org-file-apps' is checked if it contains an
7240 entry for this file type, and if yes, the corresponding command is launched.
7241 If no application is found, Emacs simply visits the file.
7242 With optional argument IN-EMACS, Emacs will visit the file.
7243 Optional LINE specifies a line to go to, optional SEARCH a string to
7244 search for. If LINE or SEARCH is given, the file will always be
7245 opened in Emacs.
7246 If the file does not exist, an error is thrown."
7247 (setq in-emacs (or in-emacs line search))
7248 (let* ((file (if (equal path "")
7249 (buffer-file-name)
7250 (convert-standard-filename (org-expand-file-name path))))
7251 (dirp (file-directory-p file))
7252 (dfile (downcase file))
7253 (old-buffer (current-buffer))
7254 (old-pos (point))
7255 (old-mode major-mode)
7256 ext cmd apps)
7257 (if (and (not (file-exists-p file))
7258 (not org-open-non-existing-files))
7259 (error "No such file: %s" file))
7260 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7261 (setq ext (match-string 1 dfile))
7262 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7263 (setq ext (match-string 1 dfile))))
7264 (setq apps (append org-file-apps (org-default-apps)))
7265 (if in-emacs
7266 (setq cmd 'emacs)
7267 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7268 (cdr (assoc ext apps))
7269 (cdr (assoc t apps)))))
7270 (when (eq cmd 'mailcap)
7271 (require 'mailcap)
7272 (mailcap-parse-mailcaps)
7273 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7274 (command (mailcap-mime-info mime-type)))
7275 (if (stringp command)
7276 (setq cmd command)
7277 (setq cmd 'emacs))))
7278 (cond
7279 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7280 (setq cmd (format cmd (concat "\"" file "\"")))
7281 (save-window-excursion
7282 (shell-command (concat cmd " &"))))
7283 ((or (stringp cmd)
7284 (eq cmd 'emacs))
7285 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
7286 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7287 (if line (goto-line line)
7288 (if search (org-link-search search))))
7289 ((consp cmd)
7290 (eval cmd))
7291 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7292 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7293 (or (not (equal old-buffer (current-buffer)))
7294 (not (equal old-pos (point))))
7295 (org-mark-ring-push old-pos old-buffer))))
7296
7297 (defun org-default-apps ()
7298 "Return the default applications for this operating system."
7299 (cond
7300 ((eq system-type 'darwin)
7301 org-file-apps-defaults-macosx)
7302 ((eq system-type 'windows-nt)
7303 org-file-apps-defaults-windowsnt)
7304 (t org-file-apps-defaults-gnu)))
7305
7306 (defun org-expand-file-name (path)
7307 "Replace special path abbreviations and expand the file name."
7308 (expand-file-name path))
7309
7310
7311 (defvar org-insert-link-history nil
7312 "Minibuffer history for links inserted with `org-insert-link'.")
7313
7314 (defvar org-stored-links nil
7315 "Contains the links stored with `org-store-link'.")
7316
7317 ;;;###autoload
7318 (defun org-store-link (arg)
7319 "\\<org-mode-map>Store an org-link to the current location.
7320 This link can later be inserted into an org-buffer with
7321 \\[org-insert-link].
7322 For some link types, a prefix arg is interpreted:
7323 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7324 For file links, arg negates `org-context-in-file-links'."
7325 (interactive "P")
7326 (let (link cpltxt txt (pos (point)))
7327 (cond
7328
7329 ((eq major-mode 'bbdb-mode)
7330 (setq cpltxt (concat
7331 "bbdb:"
7332 (or (bbdb-record-name (bbdb-current-record))
7333 (bbdb-record-company (bbdb-current-record))))
7334 link (org-make-link cpltxt)))
7335
7336 ((eq major-mode 'calendar-mode)
7337 (let ((cd (calendar-cursor-to-date)))
7338 (setq link
7339 (format-time-string
7340 (car org-time-stamp-formats)
7341 (apply 'encode-time
7342 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7343 nil nil nil))))))
7344
7345 ((or (eq major-mode 'vm-summary-mode)
7346 (eq major-mode 'vm-presentation-mode))
7347 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7348 (vm-follow-summary-cursor)
7349 (save-excursion
7350 (vm-select-folder-buffer)
7351 (let* ((message (car vm-message-pointer))
7352 (folder (buffer-file-name))
7353 (subject (vm-su-subject message))
7354 (author (vm-su-full-name message))
7355 (message-id (vm-su-message-id message)))
7356 (setq message-id (org-remove-angle-brackets message-id))
7357 (setq folder (abbreviate-file-name folder))
7358 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7359 folder)
7360 (setq folder (replace-match "" t t folder)))
7361 (setq cpltxt (concat author " on: " subject))
7362 (setq link (concat cpltxt "\n "
7363 (org-make-link
7364 "vm:" folder "#" message-id))))))
7365
7366 ((eq major-mode 'wl-summary-mode)
7367 (let* ((msgnum (wl-summary-message-number))
7368 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7369 msgnum 'message-id))
7370 (wl-message-entity (elmo-msgdb-overview-get-entity
7371 msgnum (wl-summary-buffer-msgdb)))
7372 (author (wl-summary-line-from)) ; FIXME: how to get author name?
7373 (subject "???")) ; FIXME: How to get subject of email?
7374 (setq message-id (org-remove-angle-brackets message-id))
7375 (setq cpltxt (concat author " on: " subject))
7376 (setq link (concat cpltxt "\n "
7377 (org-make-link
7378 "wl:" wl-summary-buffer-folder-name
7379 "#" message-id)))))
7380
7381 ((or (equal major-mode 'mh-folder-mode)
7382 (equal major-mode 'mh-show-mode))
7383 (let ((from-header (org-mhe-get-header "From:"))
7384 (to-header (org-mhe-get-header "To:"))
7385 (subject (org-mhe-get-header "Subject:")))
7386 (setq cpltxt (concat from-header " on: " subject))
7387 (setq link (concat cpltxt "\n "
7388 (org-make-link
7389 "mhe:" (org-mhe-get-message-real-folder) "#"
7390 (org-remove-angle-brackets
7391 (org-mhe-get-header "Message-Id:")))))))
7392
7393 ((eq major-mode 'rmail-mode)
7394 (save-excursion
7395 (save-restriction
7396 (rmail-narrow-to-non-pruned-header)
7397 (let ((folder (buffer-file-name))
7398 (message-id (mail-fetch-field "message-id"))
7399 (author (mail-fetch-field "from"))
7400 (subject (mail-fetch-field "subject")))
7401 (setq message-id (org-remove-angle-brackets message-id))
7402 (setq cpltxt (concat author " on: " subject))
7403 (setq link (concat cpltxt "\n "
7404 (org-make-link
7405 "rmail:" folder "#" message-id)))))))
7406
7407 ((eq major-mode 'gnus-group-mode)
7408 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7409 (gnus-group-group-name)) ; version
7410 ((fboundp 'gnus-group-name)
7411 (gnus-group-name))
7412 (t "???"))))
7413 (setq cpltxt (concat
7414 (if (org-xor arg org-usenet-links-prefer-google)
7415 "http://groups.google.com/groups?group="
7416 "gnus:")
7417 group)
7418 link (org-make-link cpltxt))))
7419
7420 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7421 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7422 (gnus-summary-beginning-of-article)
7423 (let* ((group (car gnus-article-current))
7424 (article (cdr gnus-article-current))
7425 (header (gnus-summary-article-header article))
7426 (author (mail-header-from header))
7427 (message-id (mail-header-id header))
7428 (date (mail-header-date header))
7429 (subject (gnus-summary-subject-string)))
7430 (setq cpltxt (concat author " on: " subject))
7431 (if (org-xor arg org-usenet-links-prefer-google)
7432 (setq link
7433 (concat
7434 cpltxt "\n "
7435 (format "http://groups.google.com/groups?as_umsgid=%s"
7436 (org-fixup-message-id-for-http message-id))))
7437 (setq link (concat cpltxt "\n"
7438 (org-make-link
7439 "gnus:" group
7440 "#" (number-to-string article)))))))
7441
7442 ((eq major-mode 'w3-mode)
7443 (setq cpltxt (url-view-url t)
7444 link (org-make-link cpltxt)))
7445 ((eq major-mode 'w3m-mode)
7446 (setq cpltxt w3m-current-url
7447 link (org-make-link cpltxt)))
7448
7449 ((eq major-mode 'org-mode)
7450 ;; Just link to current headline
7451 (setq cpltxt (concat "file:"
7452 (abbreviate-file-name (buffer-file-name))))
7453 ;; Add a context search string
7454 (when (org-xor org-context-in-file-links arg)
7455 ;; Check if we are on a target
7456 (if (save-excursion
7457 (skip-chars-forward "^>\n\r")
7458 (and (re-search-backward "<<" nil t)
7459 (looking-at "<<\\(.*?\\)>>")
7460 (<= (match-beginning 0) pos)
7461 (>= (match-end 0) pos)))
7462 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7463 (setq txt (cond
7464 ((org-on-heading-p) nil)
7465 ((org-region-active-p)
7466 (buffer-substring (region-beginning) (region-end)))
7467 (t (buffer-substring (point-at-bol) (point-at-eol)))))
7468 (setq cpltxt
7469 (concat cpltxt "::"
7470 (if org-file-link-context-use-camel-case
7471 (org-make-org-heading-camel txt)
7472 (org-make-org-heading-search-string txt))))))
7473 (if (string-match "::\\'" cpltxt)
7474 (setq cpltxt (substring cpltxt 0 -2)))
7475 (setq link (org-make-link cpltxt)))
7476
7477 ((buffer-file-name)
7478 ;; Just link to this file here.
7479 (setq cpltxt (concat "file:"
7480 (abbreviate-file-name (buffer-file-name))))
7481 ;; Add a context string
7482 (when (org-xor org-context-in-file-links arg)
7483 (setq txt (if (org-region-active-p)
7484 (buffer-substring (region-beginning) (region-end))
7485 (buffer-substring (point-at-bol) (point-at-eol))))
7486 (setq cpltxt
7487 (concat cpltxt "::"
7488 (if org-file-link-context-use-camel-case
7489 (org-make-org-heading-camel txt)
7490 (org-make-org-heading-search-string txt)))))
7491 (setq link (org-make-link cpltxt)))
7492
7493 ((interactive-p)
7494 (error "Cannot link to a buffer which is not visiting a file"))
7495
7496 (t (setq link nil)))
7497
7498 (if (and (interactive-p) link)
7499 (progn
7500 (setq org-stored-links
7501 (cons (cons (or cpltxt link) link) org-stored-links))
7502 (message "Stored: %s" (or cpltxt link)))
7503 link)))
7504
7505 (defun org-make-org-heading-search-string (&optional string heading)
7506 "Make search string for STRING or current headline."
7507 (interactive)
7508 (let ((s (or string (org-get-heading))))
7509 (unless (and string (not heading))
7510 ;; We are using a headline, clean up garbage in there.
7511 (if (string-match org-todo-regexp s)
7512 (setq s (replace-match "" t t s)))
7513 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7514 (setq s (replace-match "" t t s)))
7515 (setq s (org-trim s))
7516 (if (string-match (concat "^\\(" org-quote-string "\\|"
7517 org-comment-string "\\)") s)
7518 (setq s (replace-match "" t t s)))
7519 (while (string-match org-ts-regexp s)
7520 (setq s (replace-match "" t t s))))
7521 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7522 (setq s (replace-match " " t t s)))
7523 (or string (setq s (concat "*" s))) ; Add * for headlines
7524 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7525
7526 (defun org-make-org-heading-camel (&optional string heading)
7527 "Make a CamelCase string for STRING or the current headline."
7528 (interactive)
7529 (let ((s (or string (org-get-heading))))
7530 (unless (and string (not heading))
7531 ;; We are using a headline, clean up garbage in there.
7532 (if (string-match org-todo-regexp s)
7533 (setq s (replace-match "" t t s)))
7534 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7535 (setq s (replace-match "" t t s)))
7536 (setq s (org-trim s))
7537 (if (string-match (concat "^\\(" org-quote-string "\\|"
7538 org-comment-string "\\)") s)
7539 (setq s (replace-match "" t t s)))
7540 (while (string-match org-ts-regexp s)
7541 (setq s (replace-match "" t t s))))
7542 (while (string-match "[^a-zA-Z_ \t]+" s)
7543 (setq s (replace-match " " t t s)))
7544 (or string (setq s (concat "*" s))) ; Add * for headlines
7545 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7546
7547 (defun org-make-link (&rest strings)
7548 "Concatenate STRINGS, format resulting string with `org-link-format'."
7549 (format org-link-format (apply 'concat strings)))
7550
7551 (defun org-make-link2 (link &optional description)
7552 "Make a link with brackets."
7553 (concat "[[" link "]"
7554 (if description (concat "[" description "]") "")
7555 "]"))
7556
7557 (defun org-xor (a b)
7558 "Exclusive or."
7559 (if a (not b) b))
7560
7561 (defun org-get-header (header)
7562 "Find a header field in the current buffer."
7563 (save-excursion
7564 (goto-char (point-min))
7565 (let ((case-fold-search t) s)
7566 (cond
7567 ((eq header 'from)
7568 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7569 (setq s (match-string 1)))
7570 (while (string-match "\"" s)
7571 (setq s (replace-match "" t t s)))
7572 (if (string-match "[<(].*" s)
7573 (setq s (replace-match "" t t s))))
7574 ((eq header 'message-id)
7575 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7576 (setq s (match-string 1))))
7577 ((eq header 'subject)
7578 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7579 (setq s (match-string 1)))))
7580 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7581 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7582 s)))
7583
7584
7585 (defun org-fixup-message-id-for-http (s)
7586 "Replace special characters in a message id, so it can be used in an http query."
7587 (while (string-match "<" s)
7588 (setq s (replace-match "%3C" t t s)))
7589 (while (string-match ">" s)
7590 (setq s (replace-match "%3E" t t s)))
7591 (while (string-match "@" s)
7592 (setq s (replace-match "%40" t t s)))
7593 s)
7594
7595 (defun org-insert-link (&optional complete-file)
7596 "Insert a link. At the prompt, enter the link.
7597
7598 Completion can be used to select a link previously stored with
7599 `org-store-link'. When the empty string is entered (i.e. if you just
7600 press RET at the prompt), the link defaults to the most recently
7601 stored link. As SPC triggers completion in the minibuffer, you need to
7602 use M-SPC or C-q SPC to force the insertion of a space character.
7603
7604 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7605 selected using completion. The path to the file will be relative to
7606 the current directory if the file is in the current directory or a
7607 subdirectory. Otherwise, the link will be the absolute path as
7608 completed in the minibuffer (i.e. normally ~/path/to/file).
7609
7610 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7611 is in the current directory or below."
7612 (interactive "P")
7613 (let ((link (if complete-file
7614 (read-file-name "File: ")
7615 (completing-read
7616 "Link: " org-stored-links nil nil nil
7617 org-insert-link-history
7618 (or (car (car org-stored-links))))))
7619 linktxt matched)
7620 (if (or (not link) (equal link ""))
7621 (error "No links available"))
7622 (if complete-file
7623 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7624 (cond
7625 ((equal complete-file '(16))
7626 (insert
7627 (org-make-link
7628 "file:" (abbreviate-file-name (expand-file-name link)))))
7629 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7630 (expand-file-name link))
7631 (insert
7632 (org-make-link
7633 "file:" (match-string 1 (expand-file-name link)))))
7634 (t (insert (org-make-link "file:" link)))))
7635 (setq linktxt (cdr (assoc link org-stored-links)))
7636 (if (not org-keep-stored-link-after-insertion)
7637 (setq org-stored-links (delq (assoc link org-stored-links)
7638 org-stored-links)))
7639 (if (not linktxt) (setq link (org-make-link link)))
7640 (setq link (or linktxt link))
7641 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7642 (let* ((path (match-string 1 link))
7643 (case-fold-search nil)
7644 (search (match-string 2 link)))
7645 (when (save-match-data
7646 (equal (file-truename (buffer-file-name))
7647 (file-truename path)))
7648 ;; We are linking to this same file
7649 (if (and org-file-link-context-use-camel-case
7650 (save-match-data
7651 (string-match (concat "^" org-camel-regexp "$") search)))
7652 (setq link (replace-match search t t link)
7653 matched t)
7654 (setq link (replace-match (concat "[[" search "]]")
7655 t t link)
7656 matched t)))))
7657 (let ((lines (org-split-string link "\n")))
7658 (insert (car lines))
7659 (setq matched (or matched (string-match org-link-regexp (car lines))))
7660 (setq lines (cdr lines))
7661 (while lines
7662 (insert "\n")
7663 (if (save-excursion
7664 (beginning-of-line 0)
7665 (looking-at "[ \t]+\\S-"))
7666 (indent-relative))
7667 (setq matched (or matched
7668 (string-match org-link-regexp (car lines))))
7669 (insert (car lines))
7670 (setq lines (cdr lines))))
7671 (unless matched
7672 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7673
7674 ;;; Hooks for remember.el
7675 ;;;###autoload
7676 (defun org-remember-annotation ()
7677 "Return a link to the current location as an annotation for remember.el.
7678 If you are using Org-mode files as target for data storage with
7679 remember.el, then the annotations should include a link compatible with the
7680 conventions in Org-mode. This function returns such a link."
7681 (org-store-link nil))
7682
7683 (defconst org-remember-help
7684 "Select a destination location for the note.
7685 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7686 RET at beg-of-buf -> Append to file as level 2 headline
7687 RET on headline -> Store as sublevel entry to current headline
7688 <left>/<right> -> before/after current headline, same headings level")
7689
7690 ;;;###autoload
7691 (defun org-remember-handler ()
7692 "Store stuff from remember.el into an org file.
7693 First prompts for an org file. If the user just presses return, the value
7694 of `org-default-notes-file' is used.
7695 Then the command offers the headings tree of the selected file in order to
7696 file the text at a specific location.
7697 You can either immediately press RET to get the note appended to the
7698 file, or you can use vertical cursor motion and visibility cycling (TAB) to
7699 find a better place. Then press RET or <left> or <right> in insert the note.
7700
7701 Key Cursor position Note gets inserted
7702 -----------------------------------------------------------------------------
7703 RET buffer-start as level 2 heading at end of file
7704 RET on headline as sublevel of the heading at cursor
7705 RET no heading at cursor position, level taken from context.
7706 Or use prefix arg to specify level manually.
7707 <left> on headline as same level, before current heading
7708 <right> on headline as same level, after current heading
7709
7710 So the fastest way to store the note is to press RET RET to append it to
7711 the default file. This way your current train of thought is not
7712 interrupted, in accordance with the principles of remember.el. But with
7713 little extra effort, you can push it directly to the correct location.
7714
7715 Before being stored away, the function ensures that the text has a
7716 headline, i.e. a first line that starts with a \"*\". If not, a headline
7717 is constructed from the current date and some additional data.
7718
7719 If the variable `org-adapt-indentation' is non-nil, the entire text is
7720 also indented so that it starts in the same column as the headline
7721 \(i.e. after the stars).
7722
7723 See also the variable `org-reverse-note-order'."
7724 (catch 'quit
7725 (let* ((txt (buffer-substring (point-min) (point-max)))
7726 (fastp current-prefix-arg)
7727 (file (if fastp org-default-notes-file (org-get-org-file)))
7728 (visiting (find-buffer-visiting file))
7729 (org-startup-with-deadline-check nil)
7730 (org-startup-folded nil)
7731 spos level indent reversed)
7732 ;; Modify text so that it becomes a nice subtree which can be inserted
7733 ;; into an org tree.
7734 (let* ((lines (split-string txt "\n"))
7735 (first (car lines))
7736 (lines (cdr lines)))
7737 (if (string-match "^\\*+" first)
7738 ;; Is already a headline
7739 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7740 -1) ?\ ))
7741 ;; We need to add a headline: Use time and first buffer line
7742 (setq lines (cons first lines)
7743 first (concat "* " (current-time-string)
7744 " (" (remember-buffer-desc) ")")
7745 indent " "))
7746 (if org-adapt-indentation
7747 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7748 (setq txt (concat first "\n"
7749 (mapconcat 'identity lines "\n"))))
7750 ;; Find the file
7751 (if (not visiting)
7752 (find-file-noselect file))
7753 (with-current-buffer (get-file-buffer file)
7754 (setq reversed (org-notes-order-reversed-p))
7755 (save-excursion
7756 (save-restriction
7757 (widen)
7758 ;; Ask the User for a location
7759 (setq spos (if fastp 1 (org-get-location
7760 (current-buffer)
7761 org-remember-help)))
7762 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7763 ; not handle this note
7764 (goto-char spos)
7765 (cond ((bobp)
7766 ;; Put it at the start or end, as level 2
7767 (save-restriction
7768 (widen)
7769 (goto-char (if reversed (point-min) (point-max)))
7770 (if (not (bolp)) (newline))
7771 (org-paste-subtree (or current-prefix-arg 2) txt)))
7772 ((and (org-on-heading-p nil) (not current-prefix-arg))
7773 ;; Put it below this entry, at the beg/end of the subtree
7774 (org-back-to-heading)
7775 (setq level (outline-level))
7776 (if reversed
7777 (outline-end-of-heading)
7778 (outline-end-of-subtree))
7779 (if (not (bolp)) (newline))
7780 (beginning-of-line 1)
7781 (org-paste-subtree (1+ level) txt))
7782 (t
7783 ;; Put it right there, with automatic level determined by
7784 ;; org-paste-subtree or from prefix arg
7785 (org-paste-subtree current-prefix-arg txt)))
7786 (when remember-save-after-remembering
7787 (save-buffer)
7788 (if (not visiting) (kill-buffer (current-buffer)))))))))
7789 t) ;; return t to indicate that we took care of this note.
7790
7791 (defun org-get-org-file ()
7792 "Read a filename, with default directory `org-directory'."
7793 (let ((default (or org-default-notes-file remember-data-file)))
7794 (read-file-name (format "File name [%s]: " default)
7795 (file-name-as-directory org-directory)
7796 default)))
7797
7798 (defun org-notes-order-reversed-p ()
7799 "Check if the current file should receive notes in reversed order."
7800 (cond
7801 ((not org-reverse-note-order) nil)
7802 ((eq t org-reverse-note-order) t)
7803 ((not (listp org-reverse-note-order)) nil)
7804 (t (catch 'exit
7805 (let ((all org-reverse-note-order)
7806 entry)
7807 (while (setq entry (pop all))
7808 (if (string-match (car entry) (buffer-file-name))
7809 (throw 'exit (cdr entry))))
7810 nil)))))
7811
7812 ;;; Tables
7813
7814 ;; Watch out: Here we are talking about two different kind of tables.
7815 ;; Most of the code is for the tables created with the Org-mode table editor.
7816 ;; Sometimes, we talk about tables created and edited with the table.el
7817 ;; Emacs package. We call the former org-type tables, and the latter
7818 ;; table.el-type tables.
7819
7820
7821 (defun org-before-change-function (beg end)
7822 "Every change indicates that a table might need an update."
7823 (setq org-table-may-need-update t))
7824
7825 (defconst org-table-line-regexp "^[ \t]*|"
7826 "Detects an org-type table line.")
7827 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7828 "Detects an org-type table line.")
7829 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7830 "Detects a table line marked for automatic recalculation.")
7831 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7832 "Detects a table line marked for automatic recalculation.")
7833 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7834 "Detects a table line marked for automatic recalculation.")
7835 (defconst org-table-hline-regexp "^[ \t]*|-"
7836 "Detects an org-type table hline.")
7837 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7838 "Detects a table-type table hline.")
7839 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7840 "Detects an org-type or table-type table.")
7841 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7842 "Searching from within a table (any type) this finds the first line
7843 outside the table.")
7844 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7845 "Searching from within a table (any type) this finds the first line
7846 outside the table.")
7847
7848 (defun org-table-create-with-table.el ()
7849 "Use the table.el package to insert a new table.
7850 If there is already a table at point, convert between Org-mode tables
7851 and table.el tables."
7852 (interactive)
7853 (require 'table)
7854 (cond
7855 ((org-at-table.el-p)
7856 (if (y-or-n-p "Convert table to Org-mode table? ")
7857 (org-table-convert)))
7858 ((org-at-table-p)
7859 (if (y-or-n-p "Convert table to table.el table? ")
7860 (org-table-convert)))
7861 (t (call-interactively 'table-insert))))
7862
7863 (defun org-table-create (&optional size)
7864 "Query for a size and insert a table skeleton.
7865 SIZE is a string Columns x Rows like for example \"3x2\"."
7866 (interactive "P")
7867 (unless size
7868 (setq size (read-string
7869 (concat "Table size Columns x Rows [e.g. "
7870 org-table-default-size "]: ")
7871 "" nil org-table-default-size)))
7872
7873 (let* ((pos (point))
7874 (indent (make-string (current-column) ?\ ))
7875 (split (org-split-string size " *x *"))
7876 (rows (string-to-number (nth 1 split)))
7877 (columns (string-to-number (car split)))
7878 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7879 "\n")))
7880 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7881 (point-at-bol) (point)))
7882 (beginning-of-line 1)
7883 (newline))
7884 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7885 (dotimes (i rows) (insert line))
7886 (goto-char pos)
7887 (if (> rows 1)
7888 ;; Insert a hline after the first row.
7889 (progn
7890 (end-of-line 1)
7891 (insert "\n|-")
7892 (goto-char pos)))
7893 (org-table-align)))
7894
7895 (defun org-table-convert-region (beg0 end0 nspace)
7896 "Convert region to a table.
7897 The region goes from BEG0 to END0, but these borders will be moved
7898 slightly, to make sure a beginning of line in the first line is included.
7899 When NSPACE is non-nil, it indicates the minimum number of spaces that
7900 separate columns (default: just one space)."
7901 (let* ((beg (min beg0 end0))
7902 (end (max beg0 end0))
7903 (tabsep t)
7904 re)
7905 (goto-char beg)
7906 (beginning-of-line 1)
7907 (setq beg (move-marker (make-marker) (point)))
7908 (goto-char end)
7909 (if (bolp) (backward-char 1) (end-of-line 1))
7910 (setq end (move-marker (make-marker) (point)))
7911 ;; Lets see if this is tab-separated material. If every nonempty line
7912 ;; contains a tab, we will assume that it is tab-separated material
7913 (if nspace
7914 (setq tabsep nil)
7915 (goto-char beg)
7916 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7917 (if nspace (setq tabsep nil))
7918 (if tabsep
7919 (setq re "^\\|\t")
7920 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7921 (max 1 (prefix-numeric-value nspace)))))
7922 (goto-char beg)
7923 (while (re-search-forward re end t)
7924 (replace-match "|" t t))
7925 (goto-char beg)
7926 (insert " ")
7927 (org-table-align)))
7928
7929 (defun org-table-import (file arg)
7930 "Import FILE as a table.
7931 The file is assumed to be tab-separated. Such files can be produced by most
7932 spreadsheet and database applications. If no tabs (at least one per line)
7933 are found, lines will be split on whitespace into fields."
7934 (interactive "f\nP")
7935 (or (bolp) (newline))
7936 (let ((beg (point))
7937 (pm (point-max)))
7938 (insert-file-contents file)
7939 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7940
7941 (defun org-table-export ()
7942 "Export table as a tab-separated file.
7943 Such a file can be imported into a spreadsheet program like Excel."
7944 (interactive)
7945 (let* ((beg (org-table-begin))
7946 (end (org-table-end))
7947 (table (buffer-substring beg end))
7948 (file (read-file-name "Export table to: "))
7949 buf)
7950 (unless (or (not (file-exists-p file))
7951 (y-or-n-p (format "Overwrite file %s? " file)))
7952 (error "Abort"))
7953 (with-current-buffer (find-file-noselect file)
7954 (setq buf (current-buffer))
7955 (erase-buffer)
7956 (fundamental-mode)
7957 (insert table)
7958 (goto-char (point-min))
7959 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7960 (replace-match "" t t)
7961 (end-of-line 1))
7962 (goto-char (point-min))
7963 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7964 (replace-match "" t t)
7965 (goto-char (min (1+ (point)) (point-max))))
7966 (goto-char (point-min))
7967 (while (re-search-forward "^-[-+]*$" nil t)
7968 (replace-match "")
7969 (if (looking-at "\n")
7970 (delete-char 1)))
7971 (goto-char (point-min))
7972 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7973 (replace-match "\t" t t))
7974 (save-buffer))
7975 (kill-buffer buf)))
7976
7977 (defvar org-table-aligned-begin-marker (make-marker)
7978 "Marker at the beginning of the table last aligned.
7979 Used to check if cursor still is in that table, to minimize realignment.")
7980 (defvar org-table-aligned-end-marker (make-marker)
7981 "Marker at the end of the table last aligned.
7982 Used to check if cursor still is in that table, to minimize realignment.")
7983 (defvar org-table-last-alignment nil
7984 "List of flags for flushright alignment, from the last re-alignment.
7985 This is being used to correctly align a single field after TAB or RET.")
7986 ;; FIXME: The following is currently not used.
7987 (defvar org-table-last-column-widths nil
7988 "List of max width of fields in each column.
7989 This is being used to correctly align a single field after TAB or RET.")
7990
7991 (defvar org-last-recalc-line nil)
7992
7993 (defun org-table-align ()
7994 "Align the table at point by aligning all vertical bars."
7995 (interactive)
7996 ;; (message "align") (sit-for 2)
7997 (let* (
7998 ;; Limits of table
7999 (beg (org-table-begin))
8000 (end (org-table-end))
8001 ;; Current cursor position
8002 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8003 (colpos (org-table-current-column))
8004 (winstart (window-start))
8005 text lines (new "") lengths l typenums ty fields maxfields i
8006 column
8007 (indent "") cnt frac
8008 rfmt hfmt
8009 (spaces (if (org-in-invisibility-spec-p '(org-table))
8010 org-table-spaces-around-invisible-separators
8011 org-table-spaces-around-separators))
8012 (sp1 (car spaces))
8013 (sp2 (cdr spaces))
8014 (rfmt1 (concat
8015 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8016 (hfmt1 (concat
8017 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8018 emptystrings)
8019 (untabify beg end)
8020 ;; (message "Aligning table...")
8021 ;; Get the rows
8022 (setq lines (org-split-string
8023 (buffer-substring-no-properties beg end) "\n"))
8024 ;; Store the indentation of the first line
8025 (if (string-match "^ *" (car lines))
8026 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8027 ;; Mark the hlines
8028 (setq lines (mapcar (lambda (l)
8029 (if (string-match "^ *|-" l)
8030 nil
8031 (if (string-match "[ \t]+$" l)
8032 (substring l 0 (match-beginning 0))
8033 l)))
8034 lines))
8035 ;; Get the data fields
8036 (setq fields (mapcar
8037 (lambda (l)
8038 (org-split-string l " *| *"))
8039 (delq nil (copy-sequence lines))))
8040 ;; How many fields in the longest line?
8041 (condition-case nil
8042 (setq maxfields (apply 'max (mapcar 'length fields)))
8043 (error
8044 (kill-region beg end)
8045 (org-table-create org-table-default-size)
8046 (error "Empty table - created default table")))
8047 ;; A list of empty string to fill any short rows on output
8048 (setq emptystrings (make-list maxfields ""))
8049 ;; Get the maximum length of a field and the most common datatype
8050 ;; for each column
8051 (setq i -1)
8052 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8053 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8054 ;; maximum length
8055 (push (apply 'max 1 (mapcar 'string-width column)) lengths)
8056 ;; compute the fraction stepwise, ignoring empty fields
8057 (setq cnt 0 frac 0.0)
8058 (mapcar
8059 (lambda (x)
8060 (if (equal x "")
8061 nil
8062 (setq frac ( / (+ (* frac cnt)
8063 (if (string-match org-table-number-regexp x) 1 0))
8064 (setq cnt (1+ cnt))))))
8065 column)
8066 (push (>= frac org-table-number-fraction) typenums))
8067 (setq lengths (nreverse lengths)
8068 typenums (nreverse typenums))
8069 (setq org-table-last-alignment typenums
8070 org-table-last-column-widths lengths)
8071 ;; Compute the formats needed for output of the table
8072 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8073 (while (setq l (pop lengths))
8074 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8075 (setq rfmt (concat rfmt (format rfmt1 ty l))
8076 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8077 (setq rfmt (concat rfmt "\n")
8078 hfmt (concat (substring hfmt 0 -1) "|\n"))
8079 ;; Produce the new table
8080 ;;(while lines
8081 ;; (setq l (pop lines))
8082 ;; (if l
8083 ;; (setq new (concat new (apply 'format rfmt
8084 ;; (append (pop fields) emptystrings))))
8085 ;; (setq new (concat new hfmt))))
8086 (setq new (mapconcat
8087 (lambda (l)
8088 (if l (apply 'format rfmt
8089 (append (pop fields) emptystrings))
8090 hfmt))
8091 lines ""))
8092 ;; Replace the old one
8093 (delete-region beg end)
8094 (move-marker end nil)
8095 (move-marker org-table-aligned-begin-marker (point))
8096 (insert new)
8097 (move-marker org-table-aligned-end-marker (point))
8098 ;; Try to move to the old location (approximately)
8099 (goto-line linepos)
8100 (set-window-start (selected-window) winstart 'noforce)
8101 (org-table-goto-column colpos)
8102 (setq org-table-may-need-update nil)
8103 (if (org-in-invisibility-spec-p '(org-table))
8104 (org-table-add-invisible-to-vertical-lines))
8105 ))
8106
8107 (defun org-table-begin (&optional table-type)
8108 "Find the beginning of the table and return its position.
8109 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8110 (save-excursion
8111 (if (not (re-search-backward
8112 (if table-type org-table-any-border-regexp
8113 org-table-border-regexp)
8114 nil t))
8115 (error "Can't find beginning of table")
8116 (goto-char (match-beginning 0))
8117 (beginning-of-line 2)
8118 (point))))
8119
8120 (defun org-table-end (&optional table-type)
8121 "Find the end of the table and return its position.
8122 With argument TABLE-TYPE, go to the end of a table.el-type table."
8123 (save-excursion
8124 (if (not (re-search-forward
8125 (if table-type org-table-any-border-regexp
8126 org-table-border-regexp)
8127 nil t))
8128 (goto-char (point-max))
8129 (goto-char (match-beginning 0)))
8130 (point-marker)))
8131
8132 (defun org-table-justify-field-maybe (&optional new)
8133 "Justify the current field, text to left, number to right.
8134 Optional argument NEW may specify text to replace the current field content."
8135 (cond
8136 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8137 ((org-at-table-hline-p)
8138 ;; FIXME: I used to enforce realign here, but I think this is not needed.
8139 ;; (setq org-table-may-need-update t)
8140 )
8141 ((and (not new)
8142 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8143 (current-buffer)))
8144 (< (point) org-table-aligned-begin-marker)
8145 (>= (point) org-table-aligned-end-marker)))
8146 ;; This is not the same table, force a full re-align
8147 (setq org-table-may-need-update t))
8148 (t ;; realign the current field, based on previous full realign
8149 (let* ((pos (point)) s
8150 (col (org-table-current-column))
8151 (num (nth (1- col) org-table-last-alignment))
8152 l f n o e)
8153 (when (> col 0)
8154 (skip-chars-backward "^|\n")
8155 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8156 (progn
8157 (setq s (match-string 1)
8158 o (match-string 0)
8159 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8160 e (not (= (match-beginning 2) (match-end 2))))
8161 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8162 l (if e "|" (setq org-table-may-need-update t) ""))
8163 n (format f s t t))
8164 (if new
8165 (if (<= (length new) l)
8166 (setq n (format f new t t)) ;; FIXME: why t t?????
8167 (setq n (concat new "|") org-table-may-need-update t)))
8168 (or (equal n o)
8169 (let (org-table-may-need-update)
8170 (replace-match n))))
8171 (setq org-table-may-need-update t))
8172 (goto-char pos))))))
8173
8174 (defun org-table-next-field ()
8175 "Go to the next field in the current table, creating new lines as needed.
8176 Before doing so, re-align the table if necessary."
8177 (interactive)
8178 (org-table-maybe-eval-formula)
8179 (org-table-maybe-recalculate-line)
8180 (if (and org-table-automatic-realign
8181 org-table-may-need-update)
8182 (org-table-align))
8183 (let ((end (org-table-end)))
8184 (if (org-at-table-hline-p)
8185 (end-of-line 1))
8186 (condition-case nil
8187 (progn
8188 (re-search-forward "|" end)
8189 (if (looking-at "[ \t]*$")
8190 (re-search-forward "|" end))
8191 (if (and (looking-at "-")
8192 org-table-tab-jumps-over-hlines
8193 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8194 (goto-char (match-beginning 1)))
8195 (if (looking-at "-")
8196 (progn
8197 (beginning-of-line 0)
8198 (org-table-insert-row 'below))
8199 (if (looking-at " ") (forward-char 1))))
8200 (error
8201 (org-table-insert-row 'below)))))
8202
8203 (defun org-table-previous-field ()
8204 "Go to the previous field in the table.
8205 Before doing so, re-align the table if necessary."
8206 (interactive)
8207 (org-table-justify-field-maybe)
8208 (org-table-maybe-recalculate-line)
8209 (if (and org-table-automatic-realign
8210 org-table-may-need-update)
8211 (org-table-align))
8212 (if (org-at-table-hline-p)
8213 (end-of-line 1))
8214 (re-search-backward "|" (org-table-begin))
8215 (re-search-backward "|" (org-table-begin))
8216 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8217 (re-search-backward "|" (org-table-begin)))
8218 (if (looking-at "| ?")
8219 (goto-char (match-end 0))))
8220
8221 (defun org-table-next-row ()
8222 "Go to the next row (same column) in the current table.
8223 Before doing so, re-align the table if necessary."
8224 (interactive)
8225 (org-table-maybe-eval-formula)
8226 (org-table-maybe-recalculate-line)
8227 (if (or (looking-at "[ \t]*$")
8228 (save-excursion (skip-chars-backward " \t") (bolp)))
8229 (newline)
8230 (if (and org-table-automatic-realign
8231 org-table-may-need-update)
8232 (org-table-align))
8233 (let ((col (org-table-current-column)))
8234 (beginning-of-line 2)
8235 (if (or (not (org-at-table-p))
8236 (org-at-table-hline-p))
8237 (progn
8238 (beginning-of-line 0)
8239 (org-table-insert-row 'below)))
8240 (org-table-goto-column col)
8241 (skip-chars-backward "^|\n\r")
8242 (if (looking-at " ") (forward-char 1)))))
8243
8244 (defun org-table-copy-down (n)
8245 "Copy a field down in the current column.
8246 If the field at the cursor is empty, copy into it the content of the nearest
8247 non-empty field above. With argument N, use the Nth non-empty field.
8248 If the current field is not empty, it is copied down to the next row, and
8249 the cursor is moved with it. Therefore, repeating this command causes the
8250 column to be filled row-by-row.
8251 If the variable `org-table-copy-increment' is non-nil and the field is an
8252 integer, it will be incremented while copying."
8253 (interactive "p")
8254 (let* ((colpos (org-table-current-column))
8255 (field (org-table-get-field))
8256 (non-empty (string-match "[^ \t]" field))
8257 (beg (org-table-begin))
8258 txt)
8259 (org-table-check-inside-data-field)
8260 (if non-empty
8261 (progn
8262 (setq txt (org-trim field))
8263 (org-table-next-row)
8264 (org-table-blank-field))
8265 (save-excursion
8266 (setq txt
8267 (catch 'exit
8268 (while (progn (beginning-of-line 1)
8269 (re-search-backward org-table-dataline-regexp
8270 beg t))
8271 (org-table-goto-column colpos t)
8272 (if (and (looking-at
8273 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8274 (= (setq n (1- n)) 0))
8275 (throw 'exit (match-string 1))))))))
8276 (if txt
8277 (progn
8278 (if (and org-table-copy-increment
8279 (string-match "^[0-9]+$" txt))
8280 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8281 (insert txt)
8282 (org-table-maybe-recalculate-line)
8283 (org-table-align))
8284 (error "No non-empty field found"))))
8285
8286 (defun org-table-check-inside-data-field ()
8287 "Is point inside a table data field?
8288 I.e. not on a hline or before the first or after the last column?
8289 This actually throws an error, so it aborts the current command."
8290 (if (or (not (org-at-table-p))
8291 (= (org-table-current-column) 0)
8292 (org-at-table-hline-p)
8293 (looking-at "[ \t]*$"))
8294 (error "Not in table data field")))
8295
8296 (defvar org-table-clip nil
8297 "Clipboard for table regions.")
8298
8299 (defun org-table-blank-field ()
8300 "Blank the current table field or active region."
8301 (interactive)
8302 (org-table-check-inside-data-field)
8303 (if (and (interactive-p) (org-region-active-p))
8304 (let (org-table-clip)
8305 (org-table-cut-region (region-beginning) (region-end)))
8306 (skip-chars-backward "^|")
8307 (backward-char 1)
8308 (if (looking-at "|[^|\n]+")
8309 (let* ((pos (match-beginning 0))
8310 (match (match-string 0))
8311 (len (string-width match)))
8312 (replace-match (concat "|" (make-string (1- len) ?\ )))
8313 (goto-char (+ 2 pos))
8314 (substring match 1)))))
8315
8316 (defun org-table-get-field (&optional n replace)
8317 "Return the value of the field in column N of current row.
8318 N defaults to current field.
8319 If REPLACE is a string, replace field with this value. The return value
8320 is always the old value."
8321 (and n (org-table-goto-column n))
8322 (skip-chars-backward "^|\n")
8323 (backward-char 1)
8324 (if (looking-at "|[^|\r\n]*")
8325 (let* ((pos (match-beginning 0))
8326 (val (buffer-substring (1+ pos) (match-end 0))))
8327 (if replace
8328 (replace-match (concat "|" replace)))
8329 (goto-char (min (point-at-eol) (+ 2 pos)))
8330 val)
8331 (forward-char 1) ""))
8332
8333 (defun org-table-current-column ()
8334 "Find out which column we are in.
8335 When called interactively, column is also displayed in echo area."
8336 (interactive)
8337 (if (interactive-p) (org-table-check-inside-data-field))
8338 (save-excursion
8339 (let ((cnt 0) (pos (point)))
8340 (beginning-of-line 1)
8341 (while (search-forward "|" pos t)
8342 (setq cnt (1+ cnt)))
8343 (if (interactive-p) (message "This is table column %d" cnt))
8344 cnt)))
8345
8346 (defun org-table-goto-column (n &optional on-delim force)
8347 "Move the cursor to the Nth column in the current table line.
8348 With optional argument ON-DELIM, stop with point before the left delimiter
8349 of the field.
8350 If there are less than N fields, just go to after the last delimiter.
8351 However, when FORCE is non-nil, create new columns if necessary."
8352 (interactive "p")
8353 (let ((pos (point-at-eol)))
8354 (beginning-of-line 1)
8355 (when (> n 0)
8356 (while (and (> (setq n (1- n)) -1)
8357 (or (search-forward "|" pos t)
8358 (and force
8359 (progn (end-of-line 1)
8360 (skip-chars-backward "^|")
8361 (insert " | "))))))
8362 ; (backward-char 2) t)))))
8363 (when (and force (not (looking-at ".*|")))
8364 (save-excursion (end-of-line 1) (insert " | ")))
8365 (if on-delim
8366 (backward-char 1)
8367 (if (looking-at " ") (forward-char 1))))))
8368
8369 (defun org-at-table-p (&optional table-type)
8370 "Return t if the cursor is inside an org-type table.
8371 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8372 (if org-enable-table-editor
8373 (save-excursion
8374 (beginning-of-line 1)
8375 (looking-at (if table-type org-table-any-line-regexp
8376 org-table-line-regexp)))
8377 nil))
8378
8379 (defun org-at-table.el-p ()
8380 "Return t if and only if we are at a table.el table."
8381 (and (org-at-table-p 'any)
8382 (save-excursion
8383 (goto-char (org-table-begin 'any))
8384 (looking-at org-table1-hline-regexp))))
8385
8386 (defun org-table-recognize-table.el ()
8387 "If there is a table.el table nearby, recognize it and move into it."
8388 (if org-table-tab-recognizes-table.el
8389 (if (org-at-table.el-p)
8390 (progn
8391 (beginning-of-line 1)
8392 (if (looking-at org-table-dataline-regexp)
8393 nil
8394 (if (looking-at org-table1-hline-regexp)
8395 (progn
8396 (beginning-of-line 2)
8397 (if (looking-at org-table-any-border-regexp)
8398 (beginning-of-line -1)))))
8399 (if (re-search-forward "|" (org-table-end t) t)
8400 (progn
8401 (require 'table)
8402 (if (table--at-cell-p (point))
8403 t
8404 (message "recognizing table.el table...")
8405 (table-recognize-table)
8406 (message "recognizing table.el table...done")))
8407 (error "This should not happen..."))
8408 t)
8409 nil)
8410 nil))
8411
8412 (defun org-at-table-hline-p ()
8413 "Return t if the cursor is inside a hline in a table."
8414 (if org-enable-table-editor
8415 (save-excursion
8416 (beginning-of-line 1)
8417 (looking-at org-table-hline-regexp))
8418 nil))
8419
8420 (defun org-table-insert-column ()
8421 "Insert a new column into the table."
8422 (interactive)
8423 (if (not (org-at-table-p))
8424 (error "Not at a table"))
8425 (org-table-find-dataline)
8426 (let* ((col (max 1 (org-table-current-column)))
8427 (beg (org-table-begin))
8428 (end (org-table-end))
8429 ;; Current cursor position
8430 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8431 (colpos col))
8432 (goto-char beg)
8433 (while (< (point) end)
8434 (if (org-at-table-hline-p)
8435 nil
8436 (org-table-goto-column col t)
8437 (insert "| "))
8438 (beginning-of-line 2))
8439 (move-marker end nil)
8440 (goto-line linepos)
8441 (org-table-goto-column colpos)
8442 (org-table-align)
8443 (org-table-modify-formulas 'insert col)))
8444
8445 (defun org-table-find-dataline ()
8446 "Find a dataline in the current table, which is needed for column commands."
8447 (if (and (org-at-table-p)
8448 (not (org-at-table-hline-p)))
8449 t
8450 (let ((col (current-column))
8451 (end (org-table-end)))
8452 (move-to-column col)
8453 (while (and (< (point) end)
8454 (or (not (= (current-column) col))
8455 (org-at-table-hline-p)))
8456 (beginning-of-line 2)
8457 (move-to-column col))
8458 (if (and (org-at-table-p)
8459 (not (org-at-table-hline-p)))
8460 t
8461 (error
8462 "Please position cursor in a data line for column operations")))))
8463
8464 (defun org-table-delete-column ()
8465 "Delete a column into the table."
8466 (interactive)
8467 (if (not (org-at-table-p))
8468 (error "Not at a table"))
8469 (org-table-find-dataline)
8470 (org-table-check-inside-data-field)
8471 (let* ((col (org-table-current-column))
8472 (beg (org-table-begin))
8473 (end (org-table-end))
8474 ;; Current cursor position
8475 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8476 (colpos col))
8477 (goto-char beg)
8478 (while (< (point) end)
8479 (if (org-at-table-hline-p)
8480 nil
8481 (org-table-goto-column col t)
8482 (and (looking-at "|[^|\n]+|")
8483 (replace-match "|")))
8484 (beginning-of-line 2))
8485 (move-marker end nil)
8486 (goto-line linepos)
8487 (org-table-goto-column colpos)
8488 (org-table-align)
8489 (org-table-modify-formulas 'remove col)))
8490
8491 (defun org-table-move-column-right ()
8492 "Move column to the right."
8493 (interactive)
8494 (org-table-move-column nil))
8495 (defun org-table-move-column-left ()
8496 "Move column to the left."
8497 (interactive)
8498 (org-table-move-column 'left))
8499
8500 (defun org-table-move-column (&optional left)
8501 "Move the current column to the right. With arg LEFT, move to the left."
8502 (interactive "P")
8503 (if (not (org-at-table-p))
8504 (error "Not at a table"))
8505 (org-table-find-dataline)
8506 (org-table-check-inside-data-field)
8507 (let* ((col (org-table-current-column))
8508 (col1 (if left (1- col) col))
8509 (beg (org-table-begin))
8510 (end (org-table-end))
8511 ;; Current cursor position
8512 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8513 (colpos (if left (1- col) (1+ col))))
8514 (if (and left (= col 1))
8515 (error "Cannot move column further left"))
8516 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8517 (error "Cannot move column further right"))
8518 (goto-char beg)
8519 (while (< (point) end)
8520 (if (org-at-table-hline-p)
8521 nil
8522 (org-table-goto-column col1 t)
8523 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8524 (replace-match "|\\2|\\1|")))
8525 (beginning-of-line 2))
8526 (move-marker end nil)
8527 (goto-line linepos)
8528 (org-table-goto-column colpos)
8529 (org-table-align)
8530 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8531
8532 (defun org-table-move-row-down ()
8533 "Move table row down."
8534 (interactive)
8535 (org-table-move-row nil))
8536 (defun org-table-move-row-up ()
8537 "Move table row up."
8538 (interactive)
8539 (org-table-move-row 'up))
8540
8541 (defun org-table-move-row (&optional up)
8542 "Move the current table line down. With arg UP, move it up."
8543 (interactive "P")
8544 (let ((col (current-column))
8545 (pos (point))
8546 (tonew (if up 0 2))
8547 txt)
8548 (beginning-of-line tonew)
8549 (if (not (org-at-table-p))
8550 (progn
8551 (goto-char pos)
8552 (error "Cannot move row further")))
8553 (goto-char pos)
8554 (beginning-of-line 1)
8555 (setq pos (point))
8556 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8557 (delete-region (point) (1+ (point-at-eol)))
8558 (beginning-of-line tonew)
8559 (insert txt)
8560 (beginning-of-line 0)
8561 (move-to-column col)))
8562
8563 (defun org-table-insert-row (&optional arg)
8564 "Insert a new row above the current line into the table.
8565 With prefix ARG, insert below the current line."
8566 (interactive "P")
8567 (if (not (org-at-table-p))
8568 (error "Not at a table"))
8569 (let* ((line
8570 (org-expand-wide-chars
8571 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8572 new)
8573 (if (string-match "^[ \t]*|-" line)
8574 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8575 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8576 ;; Fix the first field if necessary
8577 (setq new (concat new))
8578 (if (string-match "^[ \t]*| *[#$] *|" line)
8579 (setq new (replace-match (match-string 0 line) t t new)))
8580 (beginning-of-line (if arg 2 1))
8581 (let (org-table-may-need-update)
8582 (insert-before-markers new)
8583 (insert-before-markers "\n"))
8584 (beginning-of-line 0)
8585 (re-search-forward "| ?" (point-at-eol) t)
8586 (and org-table-may-need-update (org-table-align))))
8587
8588 (defun org-table-insert-hline (&optional arg)
8589 "Insert a horizontal-line below the current line into the table.
8590 With prefix ARG, insert above the current line."
8591 (interactive "P")
8592 (if (not (org-at-table-p))
8593 (error "Not at a table"))
8594 (let ((line
8595 (org-expand-wide-chars
8596 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8597 (col (current-column))
8598 start)
8599 (if (string-match "^[ \t]*|-" line)
8600 (setq line
8601 (mapcar (lambda (x) (if (member x '(?| ?+))
8602 (prog1 (if start ?+ ?|) (setq start t))
8603 (if start ?- ?\ )))
8604 line))
8605 (setq line
8606 (mapcar (lambda (x) (if (equal x ?|)
8607 (prog1 (if start ?+ ?|) (setq start t))
8608 (if start ?- ?\ )))
8609 line)))
8610 (beginning-of-line (if arg 1 2))
8611 (apply 'insert line)
8612 (if (equal (char-before (point)) ?+)
8613 (progn (backward-delete-char 1) (insert "|")))
8614 (insert "\n")
8615 (beginning-of-line (if arg 1 -1))
8616 (move-to-column col)))
8617
8618 (defun org-expand-wide-chars (s)
8619 "Expand wide characters to spaces."
8620 (let (w a)
8621 (mapconcat
8622 (lambda (x)
8623 (if (> (setq w (string-width (setq a (char-to-string x)))) 1)
8624 (make-string w ?\ )
8625 a))
8626 s "")))
8627
8628 (defun org-table-kill-row ()
8629 "Delete the current row or horizontal line from the table."
8630 (interactive)
8631 (if (not (org-at-table-p))
8632 (error "Not at a table"))
8633 (let ((col (current-column)))
8634 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8635 (if (not (org-at-table-p)) (beginning-of-line 0))
8636 (move-to-column col)))
8637
8638 (defun org-table-sort-lines (beg end numericp)
8639 "Sort table lines in region.
8640 Point and mark define the first and last line to include. Both point and
8641 mark should be in the column that is used for sorting. For example, to
8642 sort according to column 3, put the mark in the first line to sort, in
8643 table column 3. Put point into the last line to be included in the sorting,
8644 also in table column 3. The command will prompt for the sorting method
8645 \(n for numerical, a for alphanumeric)."
8646 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8647 (setq numericp (string-match "[nN]" numericp))
8648 (org-table-align) ;; Just to be safe
8649 (let* (bcol ecol cmp column lns)
8650 (goto-char beg)
8651 (org-table-check-inside-data-field)
8652 (setq column (org-table-current-column)
8653 beg (move-marker (make-marker) (point-at-bol)))
8654 (goto-char end)
8655 (org-table-check-inside-data-field)
8656 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8657 (untabify beg end)
8658 (goto-char beg)
8659 (org-table-goto-column column)
8660 (skip-chars-backward "^|")
8661 (setq bcol (current-column))
8662 (org-table-goto-column (1+ column))
8663 (skip-chars-backward "^|")
8664 (setq ecol (1- (current-column)))
8665 (setq cmp (if numericp
8666 (lambda (a b) (< (car a) (car b)))
8667 (lambda (a b) (string< (car a) (car b)))))
8668 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8669 (split-string (buffer-substring beg end) "\n")))
8670 (if numericp
8671 (setq lns (mapcar (lambda(x)
8672 (cons (string-to-number (car x)) (cdr x)))
8673 lns)))
8674 (delete-region beg end)
8675 (move-marker beg nil)
8676 (move-marker end nil)
8677 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8678 (message "%d lines sorted %s based on column %d"
8679 (length lns)
8680 (if numericp "numerically" "alphabetically") column)))
8681
8682 (defun org-table-cut-region (beg end)
8683 "Copy region in table to the clipboard and blank all relevant fields."
8684 (interactive "r")
8685 (org-table-copy-region beg end 'cut))
8686
8687 (defun org-table-copy-region (beg end &optional cut)
8688 "Copy rectangular region in table to clipboard.
8689 A special clipboard is used which can only be accessed
8690 with `org-table-paste-rectangle'."
8691 (interactive "rP")
8692 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8693 region cols
8694 (rpl (if cut " " nil)))
8695 (goto-char beg)
8696 (org-table-check-inside-data-field)
8697 (setq l01 (count-lines (point-min) (point))
8698 c01 (org-table-current-column))
8699 (goto-char end)
8700 (org-table-check-inside-data-field)
8701 (setq l02 (count-lines (point-min) (point))
8702 c02 (org-table-current-column))
8703 (setq l1 (min l01 l02) l2 (max l01 l02)
8704 c1 (min c01 c02) c2 (max c01 c02))
8705 (catch 'exit
8706 (while t
8707 (catch 'nextline
8708 (if (> l1 l2) (throw 'exit t))
8709 (goto-line l1)
8710 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8711 (setq cols nil ic1 c1 ic2 c2)
8712 (while (< ic1 (1+ ic2))
8713 (push (org-table-get-field ic1 rpl) cols)
8714 (setq ic1 (1+ ic1)))
8715 (push (nreverse cols) region)
8716 (setq l1 (1+ l1)))))
8717 (setq org-table-clip (nreverse region))
8718 (if cut (org-table-align))
8719 org-table-clip))
8720
8721 (defun org-table-paste-rectangle ()
8722 "Paste a rectangular region into a table.
8723 The upper right corner ends up in the current field. All involved fields
8724 will be overwritten. If the rectangle does not fit into the present table,
8725 the table is enlarged as needed. The process ignores horizontal separator
8726 lines."
8727 (interactive)
8728 (unless (and org-table-clip (listp org-table-clip))
8729 (error "First cut/copy a region to paste!"))
8730 (org-table-check-inside-data-field)
8731 (let* ((clip org-table-clip)
8732 (line (count-lines (point-min) (point)))
8733 (col (org-table-current-column))
8734 (org-enable-table-editor t)
8735 (org-table-automatic-realign nil)
8736 c cols field)
8737 (while (setq cols (pop clip))
8738 (while (org-at-table-hline-p) (beginning-of-line 2))
8739 (if (not (org-at-table-p))
8740 (progn (end-of-line 0) (org-table-next-field)))
8741 (setq c col)
8742 (while (setq field (pop cols))
8743 (org-table-goto-column c nil 'force)
8744 (org-table-get-field nil field)
8745 (setq c (1+ c)))
8746 (beginning-of-line 2))
8747 (goto-line line)
8748 (org-table-goto-column col)
8749 (org-table-align)))
8750
8751 (defun org-table-convert ()
8752 "Convert from `org-mode' table to table.el and back.
8753 Obviously, this only works within limits. When an Org-mode table is
8754 converted to table.el, all horizontal separator lines get lost, because
8755 table.el uses these as cell boundaries and has no notion of horizontal lines.
8756 A table.el table can be converted to an Org-mode table only if it does not
8757 do row or column spanning. Multiline cells will become multiple cells.
8758 Beware, Org-mode does not test if the table can be successfully converted - it
8759 blindly applies a recipe that works for simple tables."
8760 (interactive)
8761 (require 'table)
8762 (if (org-at-table.el-p)
8763 ;; convert to Org-mode table
8764 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8765 (end (move-marker (make-marker) (org-table-end t))))
8766 (table-unrecognize-region beg end)
8767 (goto-char beg)
8768 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8769 (replace-match ""))
8770 (goto-char beg))
8771 (if (org-at-table-p)
8772 ;; convert to table.el table
8773 (let ((beg (move-marker (make-marker) (org-table-begin)))
8774 (end (move-marker (make-marker) (org-table-end))))
8775 ;; first, get rid of all horizontal lines
8776 (goto-char beg)
8777 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8778 (replace-match ""))
8779 ;; insert a hline before first
8780 (goto-char beg)
8781 (org-table-insert-hline 'above)
8782 (beginning-of-line -1)
8783 ;; insert a hline after each line
8784 (while (progn (beginning-of-line 3) (< (point) end))
8785 (org-table-insert-hline))
8786 (goto-char beg)
8787 (setq end (move-marker end (org-table-end)))
8788 ;; replace "+" at beginning and ending of hlines
8789 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8790 (replace-match "\\1+-"))
8791 (goto-char beg)
8792 (while (re-search-forward "-|[ \t]*$" end t)
8793 (replace-match "-+"))
8794 (goto-char beg)))))
8795
8796 (defun org-table-wrap-region (arg)
8797 "Wrap several fields in a column like a paragraph.
8798 This is useful if you'd like to spread the contents of a field over several
8799 lines, in order to keep the table compact.
8800
8801 If there is an active region, and both point and mark are in the same column,
8802 the text in the column is wrapped to minimum width for the given number of
8803 lines. Generally, this makes the table more compact. A prefix ARG may be
8804 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8805 formats the selected text to two lines. If the region was longer than two
8806 lines, the remaining lines remain empty. A negative prefix argument reduces
8807 the current number of lines by that amount. The wrapped text is pasted back
8808 into the table. If you formatted it to more lines than it was before, fields
8809 further down in the table get overwritten - so you might need to make space in
8810 the table first.
8811
8812 If there is no region, the current field is split at the cursor position and
8813 the text fragment to the right of the cursor is prepended to the field one
8814 line down.
8815
8816 If there is no region, but you specify a prefix ARG, the current field gets
8817 blank, and the content is appended to the field above."
8818 (interactive "P")
8819 (org-table-check-inside-data-field)
8820 (if (org-region-active-p)
8821 ;; There is a region: fill as a paragraph
8822 (let ((beg (region-beginning))
8823 nlines)
8824 (org-table-cut-region (region-beginning) (region-end))
8825 (if (> (length (car org-table-clip)) 1)
8826 (error "Region must be limited to single column"))
8827 (setq nlines (if arg
8828 (if (< arg 1)
8829 (+ (length org-table-clip) arg)
8830 arg)
8831 (length org-table-clip)))
8832 (setq org-table-clip
8833 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8834 nil nlines)))
8835 (goto-char beg)
8836 (org-table-paste-rectangle))
8837 ;; No region, split the current field at point
8838 (if arg
8839 ;; combine with field above
8840 (let ((s (org-table-blank-field))
8841 (col (org-table-current-column)))
8842 (beginning-of-line 0)
8843 (while (org-at-table-hline-p) (beginning-of-line 0))
8844 (org-table-goto-column col)
8845 (skip-chars-forward "^|")
8846 (skip-chars-backward " ")
8847 (insert " " (org-trim s))
8848 (org-table-align))
8849 ;; split field
8850 (when (looking-at "\\([^|]+\\)+|")
8851 (let ((s (match-string 1)))
8852 (replace-match " |")
8853 (goto-char (match-beginning 0))
8854 (org-table-next-row)
8855 (insert (org-trim s) " ")
8856 (org-table-align))))))
8857
8858 (defun org-trim (s)
8859 "Remove whitespace at beginning and end of string."
8860 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8861 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8862 s)
8863
8864 (defun org-wrap (string &optional width lines)
8865 "Wrap string to either a number of lines, or a width in characters.
8866 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8867 that costs. If there is a word longer than WIDTH, the text is actually
8868 wrapped to the length of that word.
8869 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8870 many lines, whatever width that takes.
8871 The return value is a list of lines, without newlines at the end."
8872 (let* ((words (org-split-string string "[ \t\n]+"))
8873 (maxword (apply 'max (mapcar 'string-width words)))
8874 w ll)
8875 (cond (width
8876 (org-do-wrap words (max maxword width)))
8877 (lines
8878 (setq w maxword)
8879 (setq ll (org-do-wrap words maxword))
8880 (if (<= (length ll) lines)
8881 ll
8882 (setq ll words)
8883 (while (> (length ll) lines)
8884 (setq w (1+ w))
8885 (setq ll (org-do-wrap words w)))
8886 ll))
8887 (t (error "Cannot wrap this")))))
8888
8889
8890 (defun org-do-wrap (words width)
8891 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8892 (let (lines line)
8893 (while words
8894 (setq line (pop words))
8895 (while (and words (< (+ (length line) (length (car words))) width))
8896 (setq line (concat line " " (pop words))))
8897 (setq lines (push line lines)))
8898 (nreverse lines)))
8899
8900 ;; FIXME: I think I can make this more efficient
8901 (defun org-split-string (string &optional separators)
8902 "Splits STRING into substrings at SEPARATORS.
8903 No empty strings are returned if there are matches at the beginning
8904 and end of string."
8905 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8906 (start 0)
8907 notfirst
8908 (list nil))
8909 (while (and (string-match rexp string
8910 (if (and notfirst
8911 (= start (match-beginning 0))
8912 (< start (length string)))
8913 (1+ start) start))
8914 (< (match-beginning 0) (length string)))
8915 (setq notfirst t)
8916 (or (eq (match-beginning 0) 0)
8917 (and (eq (match-beginning 0) (match-end 0))
8918 (eq (match-beginning 0) start))
8919 (setq list
8920 (cons (substring string start (match-beginning 0))
8921 list)))
8922 (setq start (match-end 0)))
8923 (or (eq start (length string))
8924 (setq list
8925 (cons (substring string start)
8926 list)))
8927 (nreverse list)))
8928
8929 (defun org-table-add-invisible-to-vertical-lines ()
8930 "Add an `invisible' property to vertical lines of current table."
8931 (interactive)
8932 (let* ((beg (org-table-begin))
8933 (end (org-table-end))
8934 (end1))
8935 (save-excursion
8936 (goto-char beg)
8937 (while (< (point) end)
8938 (setq end1 (point-at-eol))
8939 (if (looking-at org-table-dataline-regexp)
8940 (while (re-search-forward "|" end1 t)
8941 (add-text-properties (1- (point)) (point)
8942 '(invisible org-table)))
8943 (while (re-search-forward "[+|]" end1 t)
8944 (add-text-properties (1- (point)) (point)
8945 '(invisible org-table))))
8946 (beginning-of-line 2)))))
8947
8948 (defun org-table-toggle-vline-visibility (&optional arg)
8949 "Toggle the visibility of table vertical lines.
8950 The effect is immediate and on all tables in the file.
8951 With prefix ARG, make lines invisible when ARG is positive, make lines
8952 visible when ARG is not positive."
8953 (interactive "P")
8954 (let ((action (cond
8955 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
8956 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
8957 (t (if (org-in-invisibility-spec-p '(org-table))
8958 'off
8959 'on)))))
8960 (if (eq action 'off)
8961 (progn
8962 (org-remove-from-invisibility-spec '(org-table))
8963 (org-table-map-tables 'org-table-align)
8964 (message "Vertical table lines visible")
8965 (if (org-at-table-p)
8966 (org-table-align)))
8967 (org-add-to-invisibility-spec '(org-table))
8968 (org-table-map-tables 'org-table-align)
8969 (message "Vertical table lines invisible"))
8970 (redraw-frame (selected-frame))))
8971
8972 (defun org-table-map-tables (function)
8973 "Apply FUNCTION to the start of all tables in the buffer."
8974 (save-excursion
8975 (save-restriction
8976 (widen)
8977 (goto-char (point-min))
8978 (while (re-search-forward org-table-any-line-regexp nil t)
8979 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8980 (beginning-of-line 1)
8981 (if (looking-at org-table-line-regexp)
8982 (save-excursion (funcall function)))
8983 (re-search-forward org-table-any-border-regexp nil 1)))))
8984
8985 (defun org-table-sum (&optional beg end nlast)
8986 "Sum numbers in region of current table column.
8987 The result will be displayed in the echo area, and will be available
8988 as kill to be inserted with \\[yank].
8989
8990 If there is an active region, it is interpreted as a rectangle and all
8991 numbers in that rectangle will be summed. If there is no active
8992 region and point is located in a table column, sum all numbers in that
8993 column.
8994
8995 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8996 numbers are assumed to be times as well (in decimal hours) and the
8997 numbers are added as such.
8998
8999 If NLAST is a number, only the NLAST fields will actually be summed."
9000 (interactive)
9001 (save-excursion
9002 (let (col (timecnt 0) diff h m s org-table-clip)
9003 (cond
9004 ((and beg end)) ; beg and end given explicitly
9005 ((org-region-active-p)
9006 (setq beg (region-beginning) end (region-end)))
9007 (t
9008 (setq col (org-table-current-column))
9009 (goto-char (org-table-begin))
9010 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9011 (error "No table data"))
9012 (org-table-goto-column col)
9013 ;not needed? (skip-chars-backward "^|")
9014 (setq beg (point))
9015 (goto-char (org-table-end))
9016 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9017 (error "No table data"))
9018 (org-table-goto-column col)
9019 ;not needed? (skip-chars-forward "^|")
9020 (setq end (point))))
9021 (let* ((items (apply 'append (org-table-copy-region beg end)))
9022 (items1 (cond ((not nlast) items)
9023 ((>= nlast (length items)) items)
9024 (t (setq items (reverse items))
9025 (setcdr (nthcdr (1- nlast) items) nil)
9026 (nreverse items))))
9027 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9028 items1)))
9029 (res (apply '+ numbers))
9030 (sres (if (= timecnt 0)
9031 (format "%g" res)
9032 (setq diff (* 3600 res)
9033 h (floor (/ diff 3600)) diff (mod diff 3600)
9034 m (floor (/ diff 60)) diff (mod diff 60)
9035 s diff)
9036 (format "%d:%02d:%02d" h m s))))
9037 (kill-new sres)
9038 (if (interactive-p)
9039 (message "%s"
9040 (substitute-command-keys
9041 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9042 (length numbers) sres))))
9043 sres))))
9044
9045 (defun org-table-get-number-for-summing (s)
9046 (let (n)
9047 (if (string-match "^ *|? *" s)
9048 (setq s (replace-match "" nil nil s)))
9049 (if (string-match " *|? *$" s)
9050 (setq s (replace-match "" nil nil s)))
9051 (setq n (string-to-number s))
9052 (cond
9053 ((and (string-match "0" s)
9054 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9055 ((string-match "\\`[ \t]+\\'" s) nil)
9056 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9057 (let ((h (string-to-number (or (match-string 1 s) "0")))
9058 (m (string-to-number (or (match-string 2 s) "0")))
9059 (s (string-to-number (or (match-string 4 s) "0"))))
9060 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9061 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9062 ((equal n 0) nil)
9063 (t n))))
9064
9065 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9066 "Get a calc vector from a column, accorting to descriptor DESC.
9067 Optional arguments TBEG and COL can give the beginning of the table and
9068 the current column, to avoid unnecessary parsing."
9069 (save-excursion
9070 (or tbeg (setq tbeg (org-table-begin)))
9071 (or col (setq col (org-table-current-column)))
9072 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9073 (cond
9074 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9075 (setq n1 (- (match-end 1) (match-beginning 1)))
9076 (if (match-beginning 3)
9077 (setq n2 (- (match-end 2) (match-beginning 3))))
9078 (setq n (if n2 (max n1 n2) n1))
9079 (setq n1 (if n2 (min n1 n2)))
9080 (setq nn n)
9081 (while (and (> nn 0)
9082 (re-search-backward org-table-hline-regexp tbeg t))
9083 (push (org-current-line) hline-list)
9084 (setq nn (1- nn)))
9085 (setq hline-list (nreverse hline-list))
9086 (goto-line (nth (1- n) hline-list))
9087 (when (re-search-forward org-table-dataline-regexp)
9088 (org-table-goto-column col)
9089 (setq beg (point)))
9090 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9091 (when (re-search-backward org-table-dataline-regexp)
9092 (org-table-goto-column col)
9093 (setq end (point)))
9094 (setq l (apply 'append (org-table-copy-region beg end)))
9095 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9096 (if (equal x "") "0" x))
9097 l ",") "]"))
9098 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9099 (setq n1 (string-to-number (match-string 1 desc))
9100 n2 (string-to-number (match-string 2 desc)))
9101 (beginning-of-line 1)
9102 (save-excursion
9103 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9104 (org-table-goto-column col)
9105 (setq beg (point))))
9106 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9107 (org-table-goto-column col)
9108 (setq end (point)))
9109 (setq l (apply 'append (org-table-copy-region beg end)))
9110 (concat "[" (mapconcat
9111 (lambda (x) (setq x (org-trim x))
9112 (if (equal x "") "0" x))
9113 l ",") "]"))
9114 ((string-match "\\([0-9]+\\)" desc)
9115 (beginning-of-line 1)
9116 (when (re-search-backward org-table-dataline-regexp tbeg t
9117 (string-to-number (match-string 0 desc)))
9118 (org-table-goto-column col)
9119 (org-trim (org-table-get-field))))))))
9120
9121 (defvar org-table-formula-history nil)
9122
9123 (defvar org-table-column-names nil
9124 "Alist with column names, derived from the `!' line.")
9125 (defvar org-table-column-name-regexp nil
9126 "Regular expression matching the current column names.")
9127 (defvar org-table-local-parameters nil
9128 "Alist with parameter names, derived from the `$' line.")
9129 (defvar org-table-named-field-locations nil
9130 "Alist with locations of named fields.")
9131
9132 (defun org-table-get-formula (&optional equation named)
9133 "Read a formula from the minibuffer, offer stored formula as default."
9134 (let* ((name (car (rassoc (list (org-current-line)
9135 (org-table-current-column))
9136 org-table-named-field-locations)))
9137 (scol (if named
9138 (if name name
9139 (error "Not in a named field"))
9140 (int-to-string (org-table-current-column))))
9141 (dummy (and name (not named)
9142 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9143 (error "Abort")))
9144 (org-table-may-need-update nil)
9145 (stored-list (org-table-get-stored-formulas))
9146 (stored (cdr (assoc scol stored-list)))
9147 (eq (cond
9148 ((and stored equation (string-match "^ *=? *$" equation))
9149 stored)
9150 ((stringp equation)
9151 equation)
9152 (t (read-string
9153 (format "%s formula $%s=" (if named "Field" "Column") scol)
9154 (or stored "") 'org-table-formula-history
9155 ;stored
9156 ))))
9157 mustsave)
9158 (when (not (string-match "\\S-" eq))
9159 ;; remove formula
9160 (setq stored-list (delq (assoc scol stored-list) stored-list))
9161 (org-table-store-formulas stored-list)
9162 (error "Formula removed"))
9163 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9164 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9165 (if (and name (not named))
9166 ;; We set the column equation, delete the named one.
9167 (setq stored-list (delq (assoc name stored-list) stored-list)
9168 mustsave t))
9169 (if stored
9170 (setcdr (assoc scol stored-list) eq)
9171 (setq stored-list (cons (cons scol eq) stored-list)))
9172 (if (or mustsave (not (equal stored eq)))
9173 (org-table-store-formulas stored-list))
9174 eq))
9175
9176 (defun org-table-store-formulas (alist)
9177 "Store the list of formulas below the current table."
9178 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9179 (save-excursion
9180 (goto-char (org-table-end))
9181 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9182 (delete-region (point) (match-end 0)))
9183 (insert "#+TBLFM: "
9184 (mapconcat (lambda (x)
9185 (concat "$" (car x) "=" (cdr x)))
9186 alist "::")
9187 "\n")))
9188
9189 (defun org-table-get-stored-formulas ()
9190 "Return an alist with the t=stored formulas directly after current table."
9191 (interactive)
9192 (let (scol eq eq-alist strings string seen)
9193 (save-excursion
9194 (goto-char (org-table-end))
9195 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9196 (setq strings (org-split-string (match-string 2) " *:: *"))
9197 (while (setq string (pop strings))
9198 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9199 (setq scol (match-string 1 string)
9200 eq (match-string 2 string)
9201 eq-alist (cons (cons scol eq) eq-alist))
9202 (if (member scol seen)
9203 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9204 (push scol seen))))))
9205 (nreverse eq-alist)))
9206
9207 (defun org-table-modify-formulas (action &rest columns)
9208 "Modify the formulas stored below the current table.
9209 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9210 expected, for the other actions only a single column number is needed."
9211 (let ((list (org-table-get-stored-formulas))
9212 (nmax (length (org-split-string
9213 (buffer-substring (point-at-bol) (point-at-eol))
9214 "|")))
9215 col col1 col2 scol si sc1 sc2)
9216 (cond
9217 ((null list)) ; No action needed if there are no stored formulas
9218 ((eq action 'remove)
9219 (setq col (car columns)
9220 scol (int-to-string col))
9221 (org-table-replace-in-formulas list scol "INVALID")
9222 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9223 (loop for i from (1+ col) upto nmax by 1 do
9224 (setq si (int-to-string i))
9225 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9226 (if (assoc si list) (setcar (assoc si list)
9227 (int-to-string (1- i))))))
9228 ((eq action 'insert)
9229 (setq col (car columns))
9230 (loop for i from nmax downto col by 1 do
9231 (setq si (int-to-string i))
9232 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9233 (if (assoc si list) (setcar (assoc si list)
9234 (int-to-string (1+ i))))))
9235 ((eq action 'swap)
9236 (setq col1 (car columns) col2 (nth 1 columns)
9237 sc1 (int-to-string col1) sc2 (int-to-string col2))
9238 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
9239 (org-table-replace-in-formulas list sc1 "ZqZ")
9240 (org-table-replace-in-formulas list sc2 sc1)
9241 (org-table-replace-in-formulas list "ZqZ" sc2)
9242 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
9243 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9244 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
9245 (t (error "Invalid action in `org-table-modify-formulas'")))
9246 (if list (org-table-store-formulas list))))
9247
9248 (defun org-table-replace-in-formulas (list s1 s2)
9249 (let (elt re s)
9250 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9251 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
9252 re (concat (regexp-quote s1) "\\>"))
9253 (while (setq elt (pop list))
9254 (setq s (cdr elt))
9255 (while (string-match re s)
9256 (setq s (replace-match s2 t t s)))
9257 (setcdr elt s))))
9258
9259 (defun org-table-get-specials ()
9260 "Get the column names and local parameters for this table."
9261 (save-excursion
9262 (let ((beg (org-table-begin)) (end (org-table-end))
9263 names name fields fields1 field cnt c v line col)
9264 (setq org-table-column-names nil
9265 org-table-local-parameters nil
9266 org-table-named-field-locations nil)
9267 (goto-char beg)
9268 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9269 (setq names (org-split-string (match-string 1) " *| *")
9270 cnt 1)
9271 (while (setq name (pop names))
9272 (setq cnt (1+ cnt))
9273 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9274 (push (cons name (int-to-string cnt)) org-table-column-names))))
9275 (setq org-table-column-names (nreverse org-table-column-names))
9276 (setq org-table-column-name-regexp
9277 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9278 (goto-char beg)
9279 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9280 (setq fields (org-split-string (match-string 1) " *| *"))
9281 (while (setq field (pop fields))
9282 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9283 (push (cons (match-string 1 field) (match-string 2 field))
9284 org-table-local-parameters))))
9285 (goto-char beg)
9286 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9287 (setq c (match-string 1)
9288 fields (org-split-string (match-string 2) " *| *"))
9289 (save-excursion
9290 (beginning-of-line (if (equal c "_") 2 0))
9291 (setq line (org-current-line) col 1)
9292 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9293 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9294 (while (and fields1 (setq field (pop fields)))
9295 (setq v (pop fields1) col (1+ col))
9296 (when (and (stringp field) (stringp v)
9297 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9298 (push (cons field v) org-table-local-parameters)
9299 (push (list field line col) org-table-named-field-locations)))))))
9300
9301 (defun org-this-word ()
9302 ;; Get the current word
9303 (save-excursion
9304 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
9305 (end (progn (skip-chars-forward "^ \t\n") (point))))
9306 (buffer-substring-no-properties beg end))))
9307
9308 (defun org-table-maybe-eval-formula ()
9309 "Check if the current field starts with \"=\" or \":=\".
9310 If yes, store the formula and apply it."
9311 ;; We already know we are in a table. Get field will only return a formula
9312 ;; when appropriate. It might return a separator line, but no problem.
9313 (when org-table-formula-evaluate-inline
9314 (let* ((field (org-trim (or (org-table-get-field) "")))
9315 named eq)
9316 (when (string-match "^:?=\\(.*\\)" field)
9317 (setq named (equal (string-to-char field) ?:)
9318 eq (match-string 1 field))
9319 (if (fboundp 'calc-eval)
9320 (org-table-eval-formula (if named '(4) nil) eq))))))
9321
9322 (defvar org-recalc-commands nil
9323 "List of commands triggering the recalculation of a line.
9324 Will be filled automatically during use.")
9325
9326 (defvar org-recalc-marks
9327 '((" " . "Unmarked: no special line, no automatic recalculation")
9328 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9329 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9330 ("!" . "Column name definition line. Reference in formula as $name.")
9331 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9332 ("_" . "Names for values in row below this one.")
9333 ("^" . "Names for values in row above this one.")))
9334
9335 (defun org-table-rotate-recalc-marks (&optional newchar)
9336 "Rotate the recalculation mark in the first column.
9337 If in any row, the first field is not consistent with a mark,
9338 insert a new column for the markers.
9339 When there is an active region, change all the lines in the region,
9340 after prompting for the marking character.
9341 After each change, a message will be displayed indicating the meaning
9342 of the new mark."
9343 (interactive)
9344 (unless (org-at-table-p) (error "Not at a table"))
9345 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9346 (beg (org-table-begin))
9347 (end (org-table-end))
9348 (l (org-current-line))
9349 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9350 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9351 (have-col
9352 (save-excursion
9353 (goto-char beg)
9354 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9355 (col (org-table-current-column))
9356 (forcenew (car (assoc newchar org-recalc-marks)))
9357 epos new)
9358 (when l1
9359 (message "Change region to what mark? Type # * ! $ or SPC: ")
9360 (setq newchar (char-to-string (read-char-exclusive))
9361 forcenew (car (assoc newchar org-recalc-marks))))
9362 (if (and newchar (not forcenew))
9363 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9364 newchar))
9365 (if l1 (goto-line l1))
9366 (save-excursion
9367 (beginning-of-line 1)
9368 (unless (looking-at org-table-dataline-regexp)
9369 (error "Not at a table data line")))
9370 (unless have-col
9371 (org-table-goto-column 1)
9372 (org-table-insert-column)
9373 (org-table-goto-column (1+ col)))
9374 (setq epos (point-at-eol))
9375 (save-excursion
9376 (beginning-of-line 1)
9377 (org-table-get-field
9378 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9379 (concat " "
9380 (setq new (or forcenew
9381 (cadr (member (match-string 1) marks))))
9382 " ")
9383 " # ")))
9384 (if (and l1 l2)
9385 (progn
9386 (goto-line l1)
9387 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9388 (and (looking-at org-table-dataline-regexp)
9389 (org-table-get-field 1 (concat " " new " "))))
9390 (goto-line l1)))
9391 (if (not (= epos (point-at-eol))) (org-table-align))
9392 (goto-line l)
9393 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9394
9395 (defun org-table-maybe-recalculate-line ()
9396 "Recompute the current line if marked for it, and if we haven't just done it."
9397 (interactive)
9398 (and org-table-allow-automatic-line-recalculation
9399 (not (and (memq last-command org-recalc-commands)
9400 (equal org-last-recalc-line (org-current-line))))
9401 (save-excursion (beginning-of-line 1)
9402 (looking-at org-table-auto-recalculate-regexp))
9403 (fboundp 'calc-eval)
9404 (org-table-recalculate) t))
9405
9406 (defvar org-table-formula-debug nil
9407 "Non-nil means, debug table formulas.
9408 When nil, simply write \"#ERROR\" in corrupted fields.")
9409
9410 (defvar modes)
9411 (defsubst org-set-calc-mode (var &optional value)
9412 (if (stringp var)
9413 (setq var (assoc var '(("D" calc-angle-mode deg)
9414 ("R" calc-angle-mode rad)
9415 ("F" calc-prefer-frac t)
9416 ("S" calc-symbolic-mode t)))
9417 value (nth 2 var) var (nth 1 var)))
9418 (if (memq var modes)
9419 (setcar (cdr (memq var modes)) value)
9420 (cons var (cons value modes)))
9421 modes)
9422
9423 (defun org-table-eval-formula (&optional arg equation
9424 suppress-align suppress-const
9425 suppress-store)
9426 "Replace the table field value at the cursor by the result of a calculation.
9427
9428 This function makes use of Dave Gillespie's Calc package, in my view the
9429 most exciting program ever written for GNU Emacs. So you need to have Calc
9430 installed in order to use this function.
9431
9432 In a table, this command replaces the value in the current field with the
9433 result of a formula. It also installs the formula as the \"current\" column
9434 formula, by storing it in a special line below the table. When called
9435 with a `C-u' prefix, the current field must ba a named field, and the
9436 formula is installed as valid in only this specific field.
9437
9438 When called, the command first prompts for a formula, which is read in
9439 the minibuffer. Previously entered formulas are available through the
9440 history list, and the last used formula is offered as a default.
9441 These stored formulas are adapted correctly when moving, inserting, or
9442 deleting columns with the corresponding commands.
9443
9444 The formula can be any algebraic expression understood by the Calc package.
9445 For details, see the Org-mode manual.
9446
9447 This function can also be called from Lisp programs and offers
9448 additional arguments: EQUATION can be the formula to apply. If this
9449 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9450 used to speed-up recursive calls by by-passing unnecessary aligns.
9451 SUPPRESS-CONST suppresses the interpretation of constants in the
9452 formula, assuming that this has been done already outside the function.
9453 SUPPRESS-STORE means the formula should not be stored, either because
9454 it is already stored, or because it is a modified equation that should
9455 not overwrite the stored one."
9456 (interactive "P")
9457 (require 'calc)
9458 (org-table-check-inside-data-field)
9459 (org-table-get-specials)
9460 (let* (fields
9461 (ndown (if (integerp arg) arg 1))
9462 (org-table-automatic-realign nil)
9463 (case-fold-search nil)
9464 (down (> ndown 1))
9465 (formula (if (and equation suppress-store)
9466 equation
9467 (org-table-get-formula equation (equal arg '(4)))))
9468 (n0 (org-table-current-column))
9469 (modes (copy-sequence org-calc-default-modes))
9470 n form fmt x ev orig c)
9471 ;; Parse the format string. Since we have a lot of modes, this is
9472 ;; a lot of work. However, I think calc still uses most of the time.
9473 (if (string-match ";" formula)
9474 (let ((tmp (org-split-string formula ";")))
9475 (setq formula (car tmp)
9476 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9477 (nth 1 tmp)))
9478 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9479 (setq c (string-to-char (match-string 1 fmt))
9480 n (string-to-number (or (match-string 1 fmt) "")))
9481 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9482 (setq modes (org-set-calc-mode
9483 'calc-float-format
9484 (list (cdr (assoc c '((?n . float) (?f . fix)
9485 (?s . sci) (?e . eng))))
9486 n))))
9487 (setq fmt (replace-match "" t t fmt)))
9488 (while (string-match "[DRFS]" fmt)
9489 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9490 (setq fmt (replace-match "" t t fmt)))
9491 (unless (string-match "\\S-" fmt)
9492 (setq fmt nil))))
9493 (if (and (not suppress-const) org-table-formula-use-constants)
9494 (setq formula (org-table-formula-substitute-names formula)))
9495 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9496 (while (> ndown 0)
9497 (setq fields (org-split-string
9498 (buffer-substring
9499 (point-at-bol) (point-at-eol)) " *| *"))
9500 (if org-table-formula-numbers-only
9501 (setq fields (mapcar
9502 (lambda (x) (number-to-string (string-to-number x)))
9503 fields)))
9504 (setq ndown (1- ndown))
9505 (setq form (copy-sequence formula))
9506 ;; Insert the references to fields in same row
9507 (while (string-match "\\$\\([0-9]+\\)?" form)
9508 (setq n (if (match-beginning 1)
9509 (string-to-number (match-string 1 form))
9510 n0)
9511 x (nth (1- n) fields))
9512 (unless x (error "Invalid field specifier \"%s\""
9513 (match-string 0 form)))
9514 (if (equal x "") (setq x "0"))
9515 (setq form (replace-match (concat "(" x ")") t t form)))
9516 ;; Insert ranges in current column
9517 (while (string-match "\\&[-I0-9]+" form)
9518 (setq form (replace-match
9519 (save-match-data
9520 (org-table-get-vertical-vector (match-string 0 form)
9521 nil n0))
9522 t t form)))
9523 (setq ev (calc-eval (cons form modes)
9524 (if org-table-formula-numbers-only 'num)))
9525
9526 (when org-table-formula-debug
9527 (with-output-to-temp-buffer "*Help*"
9528 (princ (format "Substitution history of formula
9529 Orig: %s
9530 $xyz-> %s
9531 $1-> %s\n" orig formula form))
9532 (if (listp ev)
9533 (princ (format " %s^\nError: %s"
9534 (make-string (car ev) ?\-) (nth 1 ev)))
9535 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9536 ev (or fmt "NONE")
9537 (if fmt (format fmt (string-to-number ev)) ev)))))
9538 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9539 (unless (and (interactive-p) (not ndown))
9540 (unless (let (inhibit-redisplay)
9541 (y-or-n-p "Debugging Formula. Continue to next? "))
9542 (org-table-align)
9543 (error "Abort"))
9544 (delete-window (get-buffer-window "*Help*"))
9545 (message "")))
9546 (if (listp ev) (setq fmt nil ev "#ERROR"))
9547 (org-table-justify-field-maybe
9548 (if fmt (format fmt (string-to-number ev)) ev))
9549 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9550 (call-interactively 'org-return)
9551 (setq ndown 0)))
9552 (and down (org-table-maybe-recalculate-line))
9553 (or suppress-align (and org-table-may-need-update
9554 (org-table-align)))))
9555
9556 (defun org-table-recalculate (&optional all noalign)
9557 "Recalculate the current table line by applying all stored formulas."
9558 (interactive "P")
9559 (or (memq this-command org-recalc-commands)
9560 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9561 (unless (org-at-table-p) (error "Not at a table"))
9562 (org-table-get-specials)
9563 (let* ((eqlist (sort (org-table-get-stored-formulas)
9564 (lambda (a b) (string< (car a) (car b)))))
9565 (inhibit-redisplay t)
9566 (line-re org-table-dataline-regexp)
9567 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9568 (thiscol (org-table-current-column))
9569 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9570 ;; Insert constants in all formulas
9571 (setq eqlist
9572 (mapcar (lambda (x)
9573 (setcdr x (org-table-formula-substitute-names (cdr x)))
9574 x)
9575 eqlist))
9576 ;; Split the equation list
9577 (while (setq eq (pop eqlist))
9578 (if (<= (string-to-char (car eq)) ?9)
9579 (push eq eqlnum)
9580 (push eq eqlname)))
9581 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9582 (if all
9583 (progn
9584 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9585 (goto-char (setq beg (org-table-begin)))
9586 (if (re-search-forward org-table-calculate-mark-regexp end t)
9587 ;; This is a table with marked lines, only compute selected lines
9588 (setq line-re org-table-recalculate-regexp)
9589 ;; Move forward to the first non-header line
9590 (if (and (re-search-forward org-table-dataline-regexp end t)
9591 (re-search-forward org-table-hline-regexp end t)
9592 (re-search-forward org-table-dataline-regexp end t))
9593 (setq beg (match-beginning 0))
9594 nil))) ;; just leave beg where it is
9595 (setq beg (point-at-bol)
9596 end (move-marker (make-marker) (1+ (point-at-eol)))))
9597 (goto-char beg)
9598 (and all (message "Re-applying formulas to full table..."))
9599 (while (re-search-forward line-re end t)
9600 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9601 ;; Unprotected line, recalculate
9602 (and all (message "Re-applying formulas to full table...(line %d)"
9603 (setq cnt (1+ cnt))))
9604 (setq org-last-recalc-line (org-current-line))
9605 (setq eql eqlnum)
9606 (while (setq entry (pop eql))
9607 (goto-line org-last-recalc-line)
9608 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9609 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9610 (goto-line thisline)
9611 (org-table-goto-column thiscol)
9612 (or noalign (and org-table-may-need-update (org-table-align))
9613 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9614 ;; Now do the names fields
9615 (while (setq eq (pop eqlname))
9616 (setq name (car eq)
9617 a (assoc name org-table-named-field-locations))
9618 (when a
9619 (message "Re-applying formula to named field: %s" name)
9620 (goto-line (nth 1 a))
9621 (org-table-goto-column (nth 2 a))
9622 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9623 ;; back to initial position
9624 (goto-line thisline)
9625 (org-table-goto-column thiscol)
9626 (or noalign (and org-table-may-need-update (org-table-align))
9627 (and all (message "Re-applying formulas...done")))))
9628
9629 (defun org-table-formula-substitute-names (f)
9630 "Replace $const with values in string F."
9631 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9632 ;; First, check for column names
9633 (while (setq start (string-match org-table-column-name-regexp f start))
9634 (setq start (1+ start))
9635 (setq a (assoc (match-string 1 f) org-table-column-names))
9636 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9637 ;; Expand ranges to vectors
9638 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9639 (setq n1 (string-to-number (match-string 1 f))
9640 n2 (string-to-number (match-string 2 f))
9641 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9642 s (concat "[($" (number-to-string (1- nn1)) ")"))
9643 (loop for i from nn1 upto nn2 do
9644 (setq s (concat s ",($" (int-to-string i) ")")))
9645 (setq s (concat s "]"))
9646 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9647 (setq f (replace-match s t t f)))
9648 ;; Parameters and constants
9649 (setq start 0)
9650 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9651 (setq start (1+ start))
9652 (if (setq a (save-match-data
9653 (org-table-get-constant (match-string 1 f))))
9654 (setq f (replace-match (concat "(" a ")") t t f))))
9655 (if org-table-formula-debug
9656 (put-text-property 0 (length f) :orig-formula f1 f))
9657 f))
9658
9659 (defun org-table-get-constant (const)
9660 "Find the value for a parameter or constant in a formula.
9661 Parameters get priority."
9662 (or (cdr (assoc const org-table-local-parameters))
9663 (cdr (assoc const org-table-formula-constants))
9664 (and (fboundp 'constants-get) (constants-get const))
9665 "#UNDEFINED_NAME"))
9666
9667 (defvar org-edit-formulas-map (make-sparse-keymap))
9668 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9669 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9670 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9671
9672 (defvar org-pos)
9673 (defvar org-window-configuration)
9674
9675 (defun org-table-edit-formulas ()
9676 "Edit the formulas of the current table in a separate buffer."
9677 (interactive)
9678 (unless (org-at-table-p)
9679 (error "Not at a table"))
9680 (org-table-get-specials)
9681 (let ((eql (org-table-get-stored-formulas))
9682 (pos (move-marker (make-marker) (point)))
9683 (wc (current-window-configuration))
9684 entry loc s)
9685 (switch-to-buffer-other-window "*Edit Formulas*")
9686 (erase-buffer)
9687 (fundamental-mode)
9688 (set (make-local-variable 'org-pos) pos)
9689 (set (make-local-variable 'org-window-configuration) wc)
9690 (use-local-map org-edit-formulas-map)
9691 (setq s "# Edit formulas and finish with `C-c C-c'.
9692 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9693 # Use `C-c ?' to get information about $name at point.
9694 # To cancel editing, press `C-c C-q'.\n")
9695 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9696 (insert s)
9697 (while (setq entry (pop eql))
9698 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9699 (setq s (format "# Named formula, referring to column %d in line %d\n"
9700 (nth 2 loc) (nth 1 loc)))
9701 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9702 (insert s))
9703 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9704 (remove-text-properties 0 (length s) '(face nil) s)
9705 (insert s))
9706 (goto-char (point-min))
9707 (message "Edit formulas and finish with `C-c C-c'.")))
9708
9709 (defun org-show-variable ()
9710 "Show the location/value of the $ expression at point."
9711 (interactive)
9712 (let (var (pos org-pos) (win (selected-window)) e)
9713 (save-excursion
9714 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9715 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9716 (setq var (match-string 1))
9717 (error "No variable at point")))
9718 (cond
9719 ((setq e (assoc var org-table-named-field-locations))
9720 (switch-to-buffer-other-window (marker-buffer pos))
9721 (goto-line (nth 1 e))
9722 (org-table-goto-column (nth 2 e))
9723 (select-window win)
9724 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9725 ((setq e (assoc var org-table-column-names))
9726 (switch-to-buffer-other-window (marker-buffer pos))
9727 (goto-char pos)
9728 (goto-char (org-table-begin))
9729 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9730 (org-table-end) t)
9731 (progn
9732 (goto-char (match-beginning 1))
9733 (message "Named column (column %s)" (cdr e)))
9734 (error "Column name not found"))
9735 (select-window win))
9736 ((string-match "^[0-9]$" var)
9737 ;; column number
9738 (switch-to-buffer-other-window (marker-buffer pos))
9739 (goto-char pos)
9740 (goto-char (org-table-begin))
9741 (recenter 1)
9742 (if (re-search-forward org-table-dataline-regexp
9743 (org-table-end) t)
9744 (progn
9745 (goto-char (match-beginning 0))
9746 (org-table-goto-column (string-to-number var))
9747 (message "Column %s" var))
9748 (error "Column name not found"))
9749 (select-window win))
9750 ((setq e (assoc var org-table-local-parameters))
9751 (switch-to-buffer-other-window (marker-buffer pos))
9752 (goto-char pos)
9753 (goto-char (org-table-begin))
9754 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9755 (progn
9756 (goto-char (match-beginning 1))
9757 (message "Local parameter."))
9758 (error "Parameter not found"))
9759 (select-window win))
9760 (t
9761 (cond
9762 ((setq e (assoc var org-table-formula-constants))
9763 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9764 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9765 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9766 (t (error "Undefined name $%s" var)))))))
9767
9768 (defun org-finish-edit-formulas (&optional arg)
9769 "Parse the buffer for formula definitions and install them.
9770 With prefix ARG, apply the new formulas to the table."
9771 (interactive "P")
9772 (let ((pos org-pos) eql)
9773 (goto-char (point-min))
9774 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9775 (push (cons (match-string 1) (match-string 2)) eql))
9776 (set-window-configuration org-window-configuration)
9777 (select-window (get-buffer-window (marker-buffer pos)))
9778 (goto-char pos)
9779 (unless (org-at-table-p)
9780 (error "Lost table position - cannot install formulae"))
9781 (org-table-store-formulas eql)
9782 (move-marker pos nil)
9783 (kill-buffer "*Edit Formulas*")
9784 (if arg
9785 (org-table-recalculate 'all)
9786 (message "New formulas installed - press C-u C-c C-c to apply."))))
9787
9788 (defun org-abort-edit-formulas ()
9789 "Abort editing formulas, without installing the changes."
9790 (interactive)
9791 (let ((pos org-pos))
9792 (set-window-configuration org-window-configuration)
9793 (select-window (get-buffer-window (marker-buffer pos)))
9794 (goto-char pos)
9795 (message "Formula editing aborted without installing changes")))
9796
9797 ;;; The orgtbl minor mode
9798
9799 ;; Define a minor mode which can be used in other modes in order to
9800 ;; integrate the org-mode table editor.
9801
9802 ;; This is really a hack, because the org-mode table editor uses several
9803 ;; keys which normally belong to the major mode, for example the TAB and
9804 ;; RET keys. Here is how it works: The minor mode defines all the keys
9805 ;; necessary to operate the table editor, but wraps the commands into a
9806 ;; function which tests if the cursor is currently inside a table. If that
9807 ;; is the case, the table editor command is executed. However, when any of
9808 ;; those keys is used outside a table, the function uses `key-binding' to
9809 ;; look up if the key has an associated command in another currently active
9810 ;; keymap (minor modes, major mode, global), and executes that command.
9811 ;; There might be problems if any of the keys used by the table editor is
9812 ;; otherwise used as a prefix key.
9813
9814 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9815 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9816 ;; addresses this by checking explicitly for both bindings.
9817
9818 ;; The optimized version (see variable `orgtbl-optimized') takes over
9819 ;; all keys which are bound to `self-insert-command' in the *global map*.
9820 ;; Some modes bind other commands to simple characters, for example
9821 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9822 ;; active, this binding is ignored inside tables and replaced with a
9823 ;; modified self-insert.
9824
9825 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9826 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9827 In the optimized version, the table editor takes over all simple keys that
9828 normally just insert a character. In tables, the characters are inserted
9829 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9830 for empty fields). Outside tables, the correct binding of the keys is
9831 restored.
9832
9833 The default for this option is t if the optimized version is also used in
9834 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9835 this variable requires a restart of Emacs to become effective."
9836 :group 'org-table
9837 :type 'boolean)
9838
9839 (defvar orgtbl-mode nil
9840 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9841 table editor in arbitrary modes.")
9842 (make-variable-buffer-local 'orgtbl-mode)
9843
9844 (defvar orgtbl-mode-map (make-keymap)
9845 "Keymap for `orgtbl-mode'.")
9846
9847 ;;;###autoload
9848 (defun turn-on-orgtbl ()
9849 "Unconditionally turn on `orgtbl-mode'."
9850 (orgtbl-mode 1))
9851
9852 ;;;###autoload
9853 (defun orgtbl-mode (&optional arg)
9854 "The `org-mode' table editor as a minor mode for use in other modes."
9855 (interactive)
9856 (if (eq major-mode 'org-mode)
9857 ;; Exit without error, in case some hook functions calls this
9858 ;; by accident in org-mode.
9859 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9860 (setq orgtbl-mode
9861 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9862 (if orgtbl-mode
9863 (progn
9864 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9865 ;; Make sure we are first in minor-mode-map-alist
9866 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9867 (and c (setq minor-mode-map-alist
9868 (cons c (delq c minor-mode-map-alist)))))
9869 (set (make-local-variable (quote org-table-may-need-update)) t)
9870 (org-add-hook 'before-change-functions 'org-before-change-function
9871 nil 'local)
9872 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
9873 auto-fill-inhibit-regexp)
9874 (set (make-local-variable 'auto-fill-inhibit-regexp)
9875 (if auto-fill-inhibit-regexp
9876 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
9877 "[ \t]*|"))
9878 (easy-menu-add orgtbl-mode-menu)
9879 (run-hooks 'orgtbl-mode-hook))
9880 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9881 (remove-hook 'before-change-functions 'org-before-change-function t)
9882 (easy-menu-remove orgtbl-mode-menu)
9883 (force-mode-line-update 'all))))
9884
9885 ;; Install it as a minor mode.
9886 (put 'orgtbl-mode :included t)
9887 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9888 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9889
9890 (defun orgtbl-make-binding (fun n &rest keys)
9891 "Create a function for binding in the table minor mode.
9892 FUN is the command to call inside a table. N is used to create a unique
9893 command name. KEYS are keys that should be checked in for a command
9894 to execute outside of tables."
9895 (eval
9896 (list 'defun
9897 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9898 '(arg)
9899 (concat "In tables, run `" (symbol-name fun) "'.\n"
9900 "Outside of tables, run the binding of `"
9901 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9902 "'.")
9903 '(interactive "p")
9904 (list 'if
9905 '(org-at-table-p)
9906 (list 'call-interactively (list 'quote fun))
9907 (list 'let '(orgtbl-mode)
9908 (list 'call-interactively
9909 (append '(or)
9910 (mapcar (lambda (k)
9911 (list 'key-binding k))
9912 keys)
9913 '('orgtbl-error))))))))
9914
9915 (defun orgtbl-error ()
9916 "Error when there is no default binding for a table key."
9917 (interactive)
9918 (error "This key is has no function outside tables"))
9919
9920 (defun orgtbl-setup ()
9921 "Setup orgtbl keymaps."
9922 (let ((nfunc 0)
9923 (bindings
9924 (list
9925 '([(meta shift left)] org-table-delete-column)
9926 '([(meta left)] org-table-move-column-left)
9927 '([(meta right)] org-table-move-column-right)
9928 '([(meta shift right)] org-table-insert-column)
9929 '([(meta shift up)] org-table-kill-row)
9930 '([(meta shift down)] org-table-insert-row)
9931 '([(meta up)] org-table-move-row-up)
9932 '([(meta down)] org-table-move-row-down)
9933 '("\C-c\C-w" org-table-cut-region)
9934 '("\C-c\M-w" org-table-copy-region)
9935 '("\C-c\C-y" org-table-paste-rectangle)
9936 '("\C-c-" org-table-insert-hline)
9937 ; '([(shift tab)] org-table-previous-field)
9938 '("\C-m" org-table-next-row)
9939 (list (org-key 'S-return) 'org-table-copy-down)
9940 '([(meta return)] org-table-wrap-region)
9941 '("\C-c\C-q" org-table-wrap-region)
9942 '("\C-c?" org-table-current-column)
9943 '("\C-c " org-table-blank-field)
9944 '("\C-c+" org-table-sum)
9945 '("\C-c|" org-table-toggle-vline-visibility)
9946 '("\C-c=" org-table-eval-formula)
9947 '("\C-c'" org-table-edit-formulas)
9948 '("\C-c*" org-table-recalculate)
9949 '("\C-c^" org-table-sort-lines)
9950 '([(control ?#)] org-table-rotate-recalc-marks)))
9951 elt key fun cmd)
9952 (while (setq elt (pop bindings))
9953 (setq nfunc (1+ nfunc))
9954 (setq key (car elt)
9955 fun (nth 1 elt)
9956 cmd (orgtbl-make-binding fun nfunc key))
9957 (define-key orgtbl-mode-map key cmd))
9958 ;; Special treatment needed for TAB and RET
9959 (define-key orgtbl-mode-map [(return)]
9960 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9961 (define-key orgtbl-mode-map "\C-m"
9962 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9963 (define-key orgtbl-mode-map [(tab)]
9964 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9965 (define-key orgtbl-mode-map "\C-i"
9966 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
9967 (define-key orgtbl-mode-map "\C-i"
9968 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
9969 (define-key orgtbl-mode-map "\C-c\C-c"
9970 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
9971 (when orgtbl-optimized
9972 ;; If the user wants maximum table support, we need to hijack
9973 ;; some standard editing functions
9974 (org-remap orgtbl-mode-map
9975 'self-insert-command 'orgtbl-self-insert-command
9976 'delete-char 'orgtbl-delete-char
9977 'delete-backward-char 'orgtbl-delete-backward-char)
9978 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
9979 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
9980 '("OrgTbl"
9981 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
9982 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
9983 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
9984 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
9985 "--"
9986 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
9987 ["Copy Field from Above"
9988 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
9989 "--"
9990 ("Column"
9991 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
9992 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
9993 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
9994 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
9995 ("Row"
9996 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
9997 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
9998 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
9999 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10000 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10001 "--"
10002 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10003 ("Rectangle"
10004 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10005 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10006 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10007 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10008 "--"
10009 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10010 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10011 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10012 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10013 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10014 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10015 ["Sum Column/Rectangle" org-table-sum
10016 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10017 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10018 ["Debug Formulas"
10019 (setq org-table-formula-debug (not org-table-formula-debug))
10020 :style toggle :selected org-table-formula-debug]
10021 ))
10022 t)
10023
10024 (defun orgtbl-tab ()
10025 "Justification and field motion for `orgtbl-mode'."
10026 (interactive)
10027 (org-table-justify-field-maybe)
10028 (org-table-next-field))
10029
10030 (defun orgtbl-ret ()
10031 "Justification and field motion for `orgtbl-mode'."
10032 (interactive)
10033 (org-table-justify-field-maybe)
10034 (org-table-next-row))
10035
10036 (defun orgtbl-self-insert-command (N)
10037 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10038 If the cursor is in a table looking at whitespace, the whitespace is
10039 overwritten, and the table is not marked as requiring realignment."
10040 (interactive "p")
10041 (if (and (org-at-table-p)
10042 (or
10043 (and org-table-auto-blank-field
10044 (member last-command
10045 '(orgtbl-hijacker-command-100
10046 orgtbl-hijacker-command-101
10047 orgtbl-hijacker-command-102
10048 orgtbl-hijacker-command-103
10049 orgtbl-hijacker-command-104
10050 orgtbl-hijacker-command-105))
10051 (org-table-blank-field))
10052 t)
10053 (eq N 1)
10054 (looking-at "[^|\n]* +|"))
10055 (let (org-table-may-need-update)
10056 (goto-char (1- (match-end 0)))
10057 (delete-backward-char 1)
10058 (goto-char (match-beginning 0))
10059 (self-insert-command N))
10060 (setq org-table-may-need-update t)
10061 (let (orgtbl-mode)
10062 (call-interactively (key-binding (vector last-input-event))))))
10063
10064 (defun org-force-self-insert (N)
10065 "Needed to enforce self-insert under remapping."
10066 (interactive "p")
10067 (self-insert-command N))
10068
10069 (defun orgtbl-delete-backward-char (N)
10070 "Like `delete-backward-char', insert whitespace at field end in tables.
10071 When deleting backwards, in tables this function will insert whitespace in
10072 front of the next \"|\" separator, to keep the table aligned. The table will
10073 still be marked for re-alignment, because a narrow field may lead to a
10074 reduced column width."
10075 (interactive "p")
10076 (if (and (org-at-table-p)
10077 (eq N 1)
10078 (string-match "|" (buffer-substring (point-at-bol) (point)))
10079 (looking-at ".*?|"))
10080 (let ((pos (point)))
10081 (backward-delete-char N)
10082 (skip-chars-forward "^|")
10083 (insert " ")
10084 (goto-char (1- pos)))
10085 (delete-backward-char N)))
10086
10087 (defun orgtbl-delete-char (N)
10088 "Like `delete-char', but insert whitespace at field end in tables.
10089 When deleting characters, in tables this function will insert whitespace in
10090 front of the next \"|\" separator, to keep the table aligned. The table
10091 will still be marked for re-alignment, because a narrow field may lead to
10092 a reduced column width."
10093 (interactive "p")
10094 (if (and (org-at-table-p)
10095 (not (bolp))
10096 (not (= (char-after) ?|))
10097 (eq N 1))
10098 (if (looking-at ".*?|")
10099 (let ((pos (point)))
10100 (replace-match (concat
10101 (substring (match-string 0) 1 -1)
10102 " |"))
10103 (goto-char pos)))
10104 (delete-char N)))
10105
10106 ;;; Exporting
10107
10108 (defconst org-level-max 20)
10109
10110 (defun org-export-find-first-heading-line (list)
10111 "Remove all lines from LIST which are before the first headline."
10112 (let ((orig-list list)
10113 (re (concat "^" outline-regexp)))
10114 (while (and list
10115 (not (string-match re (car list))))
10116 (pop list))
10117 (or list orig-list)))
10118
10119 (defun org-skip-comments (lines)
10120 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10121 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10122 (re2 "^\\(\\*+\\)[ \t\n\r]")
10123 rtn line level)
10124 (while (setq line (pop lines))
10125 (cond
10126 ((and (string-match re1 line)
10127 (setq level (- (match-end 1) (match-beginning 1))))
10128 ;; Beginning of a COMMENT subtree. Skip it.
10129 (while (and (setq line (pop lines))
10130 (or (not (string-match re2 line))
10131 (> (- (match-end 1) (match-beginning 1)) level))))
10132 (setq lines (cons line lines)))
10133 ((string-match "^#" line)
10134 ;; an ordinary comment line
10135 )
10136 ((and org-export-table-remove-special-lines
10137 (string-match "^[ \t]*| *[!_^] *|" line))
10138 ;; a special table line that should be removed
10139 )
10140 (t (setq rtn (cons line rtn)))))
10141 (nreverse rtn)))
10142
10143 ;; ASCII
10144
10145 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10146 "Characters for underlining headings in ASCII export.")
10147
10148 (defconst org-html-entities
10149 '(("nbsp")
10150 ("iexcl")
10151 ("cent")
10152 ("pound")
10153 ("curren")
10154 ("yen")
10155 ("brvbar")
10156 ("sect")
10157 ("uml")
10158 ("copy")
10159 ("ordf")
10160 ("laquo")
10161 ("not")
10162 ("shy")
10163 ("reg")
10164 ("macr")
10165 ("deg")
10166 ("plusmn")
10167 ("sup2")
10168 ("sup3")
10169 ("acute")
10170 ("micro")
10171 ("para")
10172 ("middot")
10173 ("odot"."o")
10174 ("star"."*")
10175 ("cedil")
10176 ("sup1")
10177 ("ordm")
10178 ("raquo")
10179 ("frac14")
10180 ("frac12")
10181 ("frac34")
10182 ("iquest")
10183 ("Agrave")
10184 ("Aacute")
10185 ("Acirc")
10186 ("Atilde")
10187 ("Auml")
10188 ("Aring") ("AA"."&Aring;")
10189 ("AElig")
10190 ("Ccedil")
10191 ("Egrave")
10192 ("Eacute")
10193 ("Ecirc")
10194 ("Euml")
10195 ("Igrave")
10196 ("Iacute")
10197 ("Icirc")
10198 ("Iuml")
10199 ("ETH")
10200 ("Ntilde")
10201 ("Ograve")
10202 ("Oacute")
10203 ("Ocirc")
10204 ("Otilde")
10205 ("Ouml")
10206 ("times")
10207 ("Oslash")
10208 ("Ugrave")
10209 ("Uacute")
10210 ("Ucirc")
10211 ("Uuml")
10212 ("Yacute")
10213 ("THORN")
10214 ("szlig")
10215 ("agrave")
10216 ("aacute")
10217 ("acirc")
10218 ("atilde")
10219 ("auml")
10220 ("aring")
10221 ("aelig")
10222 ("ccedil")
10223 ("egrave")
10224 ("eacute")
10225 ("ecirc")
10226 ("euml")
10227 ("igrave")
10228 ("iacute")
10229 ("icirc")
10230 ("iuml")
10231 ("eth")
10232 ("ntilde")
10233 ("ograve")
10234 ("oacute")
10235 ("ocirc")
10236 ("otilde")
10237 ("ouml")
10238 ("divide")
10239 ("oslash")
10240 ("ugrave")
10241 ("uacute")
10242 ("ucirc")
10243 ("uuml")
10244 ("yacute")
10245 ("thorn")
10246 ("yuml")
10247 ("fnof")
10248 ("Alpha")
10249 ("Beta")
10250 ("Gamma")
10251 ("Delta")
10252 ("Epsilon")
10253 ("Zeta")
10254 ("Eta")
10255 ("Theta")
10256 ("Iota")
10257 ("Kappa")
10258 ("Lambda")
10259 ("Mu")
10260 ("Nu")
10261 ("Xi")
10262 ("Omicron")
10263 ("Pi")
10264 ("Rho")
10265 ("Sigma")
10266 ("Tau")
10267 ("Upsilon")
10268 ("Phi")
10269 ("Chi")
10270 ("Psi")
10271 ("Omega")
10272 ("alpha")
10273 ("beta")
10274 ("gamma")
10275 ("delta")
10276 ("epsilon")
10277 ("varepsilon"."&epsilon;")
10278 ("zeta")
10279 ("eta")
10280 ("theta")
10281 ("iota")
10282 ("kappa")
10283 ("lambda")
10284 ("mu")
10285 ("nu")
10286 ("xi")
10287 ("omicron")
10288 ("pi")
10289 ("rho")
10290 ("sigmaf") ("varsigma"."&sigmaf;")
10291 ("sigma")
10292 ("tau")
10293 ("upsilon")
10294 ("phi")
10295 ("chi")
10296 ("psi")
10297 ("omega")
10298 ("thetasym") ("vartheta"."&thetasym;")
10299 ("upsih")
10300 ("piv")
10301 ("bull") ("bullet"."&bull;")
10302 ("hellip") ("dots"."&hellip;")
10303 ("prime")
10304 ("Prime")
10305 ("oline")
10306 ("frasl")
10307 ("weierp")
10308 ("image")
10309 ("real")
10310 ("trade")
10311 ("alefsym")
10312 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
10313 ("uarr") ("uparrow"."&uarr;")
10314 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
10315 ("darr")("downarrow"."&darr;")
10316 ("harr") ("leftrightarrow"."&harr;")
10317 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
10318 ("lArr") ("Leftarrow"."&lArr;")
10319 ("uArr") ("Uparrow"."&uArr;")
10320 ("rArr") ("Rightarrow"."&rArr;")
10321 ("dArr") ("Downarrow"."&dArr;")
10322 ("hArr") ("Leftrightarrow"."&hArr;")
10323 ("forall")
10324 ("part") ("partial"."&part;")
10325 ("exist") ("exists"."&exist;")
10326 ("empty") ("emptyset"."&empty;")
10327 ("nabla")
10328 ("isin") ("in"."&isin;")
10329 ("notin")
10330 ("ni")
10331 ("prod")
10332 ("sum")
10333 ("minus")
10334 ("lowast") ("ast"."&lowast;")
10335 ("radic")
10336 ("prop") ("proptp"."&prop;")
10337 ("infin") ("infty"."&infin;")
10338 ("ang") ("angle"."&ang;")
10339 ("and") ("vee"."&and;")
10340 ("or") ("wedge"."&or;")
10341 ("cap")
10342 ("cup")
10343 ("int")
10344 ("there4")
10345 ("sim")
10346 ("cong") ("simeq"."&cong;")
10347 ("asymp")("approx"."&asymp;")
10348 ("ne") ("neq"."&ne;")
10349 ("equiv")
10350 ("le")
10351 ("ge")
10352 ("sub") ("subset"."&sub;")
10353 ("sup") ("supset"."&sup;")
10354 ("nsub")
10355 ("sube")
10356 ("supe")
10357 ("oplus")
10358 ("otimes")
10359 ("perp")
10360 ("sdot") ("cdot"."&sdot;")
10361 ("lceil")
10362 ("rceil")
10363 ("lfloor")
10364 ("rfloor")
10365 ("lang")
10366 ("rang")
10367 ("loz") ("Diamond"."&loz;")
10368 ("spades") ("spadesuit"."&spades;")
10369 ("clubs") ("clubsuit"."&clubs;")
10370 ("hearts") ("diamondsuit"."&hearts;")
10371 ("diams") ("diamondsuit"."&diams;")
10372 ("quot")
10373 ("amp")
10374 ("lt")
10375 ("gt")
10376 ("OElig")
10377 ("oelig")
10378 ("Scaron")
10379 ("scaron")
10380 ("Yuml")
10381 ("circ")
10382 ("tilde")
10383 ("ensp")
10384 ("emsp")
10385 ("thinsp")
10386 ("zwnj")
10387 ("zwj")
10388 ("lrm")
10389 ("rlm")
10390 ("ndash")
10391 ("mdash")
10392 ("lsquo")
10393 ("rsquo")
10394 ("sbquo")
10395 ("ldquo")
10396 ("rdquo")
10397 ("bdquo")
10398 ("dagger")
10399 ("Dagger")
10400 ("permil")
10401 ("lsaquo")
10402 ("rsaquo")
10403 ("euro")
10404
10405 ("arccos"."arccos")
10406 ("arcsin"."arcsin")
10407 ("arctan"."arctan")
10408 ("arg"."arg")
10409 ("cos"."cos")
10410 ("cosh"."cosh")
10411 ("cot"."cot")
10412 ("coth"."coth")
10413 ("csc"."csc")
10414 ("deg"."deg")
10415 ("det"."det")
10416 ("dim"."dim")
10417 ("exp"."exp")
10418 ("gcd"."gcd")
10419 ("hom"."hom")
10420 ("inf"."inf")
10421 ("ker"."ker")
10422 ("lg"."lg")
10423 ("lim"."lim")
10424 ("liminf"."liminf")
10425 ("limsup"."limsup")
10426 ("ln"."ln")
10427 ("log"."log")
10428 ("max"."max")
10429 ("min"."min")
10430 ("Pr"."Pr")
10431 ("sec"."sec")
10432 ("sin"."sin")
10433 ("sinh"."sinh")
10434 ("sup"."sup")
10435 ("tan"."tan")
10436 ("tanh"."tanh")
10437 )
10438 "Entities for TeX->HTML translation.
10439 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
10440 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
10441 In that case, \"\\ent\" will be translated to \"&other;\".
10442 The list contains HTML entities for Latin-1, Greek and other symbols.
10443 It is supplemented by a number of commonly used TeX macros with appropriate
10444 translations. There is currently no way for users to extend this.")
10445
10446 (defun org-cleaned-string-for-export (string)
10447 "Cleanup a buffer substring so that links can be created safely."
10448 (interactive)
10449 (let* ((cb (current-buffer))
10450 (re-radio (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)"))
10451 rtn)
10452 (save-excursion
10453 (set-buffer (get-buffer-create " org-mode-tmp"))
10454 (erase-buffer)
10455 (insert string)
10456 (org-mode)
10457 ;; Find targets in comments and move them out of comments
10458 (goto-char (point-min))
10459 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
10460 (replace-match "\\1"))
10461 ;; Find matches for radio targets and turn them into links
10462 (goto-char (point-min))
10463 (while (re-search-forward re-radio nil t)
10464 (replace-match "\\1[[\\2]]"))
10465 ;; Find all links that contain a newline and put them into a single line
10466 (goto-char (point-min))
10467 (while (re-search-forward "\\(\\[\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\]\\)" nil t)
10468 (replace-match "\\1 \\2")
10469 (goto-char (match-beginning 0)))
10470 ;; Remove comments
10471 (goto-char (point-min))
10472 (while (re-search-forward "^#.*\n?" nil t)
10473 (replace-match ""))
10474 (setq rtn (buffer-string)))
10475 (kill-buffer " org-mode-tmp")
10476 rtn))
10477
10478 (defun org-solidify-link-text (s)
10479 "Take link text and make a safe target out of it."
10480 (save-match-data
10481 (mapconcat
10482 'identity
10483 (org-split-string s "[ \t\r\n]+") "--")))
10484
10485 (defvar org-last-level nil) ; dynamically scoped variable
10486
10487 (defun org-export-as-ascii (arg)
10488 "Export the outline as a pretty ASCII file.
10489 If there is an active region, export only the region.
10490 The prefix ARG specifies how many levels of the outline should become
10491 underlined headlines. The default is 3."
10492 (interactive "P")
10493 (setq-default org-todo-line-regexp org-todo-line-regexp)
10494 (let* ((region
10495 (buffer-substring
10496 (if (org-region-active-p) (region-beginning) (point-min))
10497 (if (org-region-active-p) (region-end) (point-max))))
10498 (lines (org-export-find-first-heading-line
10499 (org-skip-comments
10500 (org-split-string
10501 (org-cleaned-string-for-export region)
10502 "[\r\n]"))))
10503 (org-startup-with-deadline-check nil)
10504 (level 0) line txt
10505 (umax nil)
10506 (case-fold-search nil)
10507 (filename (concat (file-name-sans-extension (buffer-file-name))
10508 ".txt"))
10509 (buffer (find-file-noselect filename))
10510 (levels-open (make-vector org-level-max nil))
10511 (date (format-time-string "%Y/%m/%d" (current-time)))
10512 (time (format-time-string "%X" (current-time)))
10513 (author user-full-name)
10514 (title (buffer-name))
10515 (options nil)
10516 (email user-mail-address)
10517 (language org-export-default-language)
10518 (text nil)
10519 (todo nil)
10520 (lang-words nil))
10521
10522 (setq org-last-level 1)
10523 (org-init-section-numbers)
10524
10525 (find-file-noselect filename)
10526
10527 ;; Search for the export key lines
10528 (org-parse-key-lines)
10529
10530 (setq lang-words (or (assoc language org-export-language-setup)
10531 (assoc "en" org-export-language-setup)))
10532 (if org-export-ascii-show-new-buffer
10533 (switch-to-buffer-other-window buffer)
10534 (set-buffer buffer))
10535 (erase-buffer)
10536 (fundamental-mode)
10537 (if options (org-parse-export-options options))
10538 (setq umax (if arg (prefix-numeric-value arg)
10539 org-export-headline-levels))
10540
10541 ;; File header
10542 (if title (org-insert-centered title ?=))
10543 (insert "\n")
10544 (if (or author email)
10545 (insert (concat (nth 1 lang-words) ": " (or author "")
10546 (if email (concat " <" email ">") "")
10547 "\n")))
10548 (if (and date time)
10549 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10550 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10551
10552 (insert "\n\n")
10553
10554 (if org-export-with-toc
10555 (progn
10556 (insert (nth 3 lang-words) "\n"
10557 (make-string (length (nth 3 lang-words)) ?=) "\n")
10558 (mapcar '(lambda (line)
10559 (if (string-match org-todo-line-regexp
10560 line)
10561 ;; This is a headline
10562 (progn
10563 (setq level (- (match-end 1) (match-beginning 1))
10564 txt (match-string 3 line)
10565 todo
10566 (or (and (match-beginning 2)
10567 (not (equal (match-string 2 line)
10568 org-done-string)))
10569 ; TODO, not DONE
10570 (and (= level umax)
10571 (org-search-todo-below
10572 line lines level))))
10573 (setq txt (org-html-expand-for-ascii txt))
10574
10575 (if org-export-with-section-numbers
10576 (setq txt (concat (org-section-number level)
10577 " " txt)))
10578 (if (<= level umax)
10579 (progn
10580 (insert
10581 (make-string (* (1- level) 4) ?\ )
10582 (format (if todo "%s (*)\n" "%s\n") txt))
10583 (setq org-last-level level))
10584 ))))
10585 lines)))
10586
10587 (org-init-section-numbers)
10588 (while (setq line (pop lines))
10589 ;; Remove the quoted HTML tags.
10590 (setq line (org-html-expand-for-ascii line))
10591 ;; Remove targets
10592 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
10593 (setq line (replace-match "" t t line)))
10594 ;; Replace internal links
10595 (while (string-match org-bracket-link-regexp line)
10596 (setq line (replace-match
10597 (if (match-end 3) "[\\3]" "[\\1]")
10598 t nil line)))
10599 (cond
10600 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10601 ;; a Headline
10602 (setq level (- (match-end 1) (match-beginning 1))
10603 txt (match-string 2 line))
10604 (org-ascii-level-start level txt umax))
10605 (t (insert line "\n"))))
10606 (normal-mode)
10607 (save-buffer)
10608 (goto-char (point-min))))
10609
10610 (defun org-search-todo-below (line lines level)
10611 "Search the subtree below LINE for any TODO entries."
10612 (let ((rest (cdr (memq line lines)))
10613 (re org-todo-line-regexp)
10614 line lv todo)
10615 (catch 'exit
10616 (while (setq line (pop rest))
10617 (if (string-match re line)
10618 (progn
10619 (setq lv (- (match-end 1) (match-beginning 1))
10620 todo (and (match-beginning 2)
10621 (not (equal (match-string 2 line)
10622 org-done-string))))
10623 ; TODO, not DONE
10624 (if (<= lv level) (throw 'exit nil))
10625 (if todo (throw 'exit t))))))))
10626
10627 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10628 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10629 (defun org-html-expand-for-ascii (line)
10630 "Handle quoted HTML for ASCII export."
10631 (if org-export-html-expand
10632 (while (string-match "@<[^<>\n]*>" line)
10633 ;; We just remove the tags for now.
10634 (setq line (replace-match "" nil nil line))))
10635 line)
10636
10637 (defun org-insert-centered (s &optional underline)
10638 "Insert the string S centered and underline it with character UNDERLINE."
10639 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
10640 (insert (make-string ind ?\ ) s "\n")
10641 (if underline
10642 (insert (make-string ind ?\ )
10643 (make-string (length s) underline)
10644 "\n"))))
10645
10646 (defun org-ascii-level-start (level title umax)
10647 "Insert a new level in ASCII export."
10648 (let (char)
10649 (if (> level umax)
10650 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10651 (if (or (not (equal (char-before) ?\n))
10652 (not (equal (char-before (1- (point))) ?\n)))
10653 (insert "\n"))
10654 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10655 (if org-export-with-section-numbers
10656 (setq title (concat (org-section-number level) " " title)))
10657 (insert title "\n" (make-string (string-width title) char) "\n"))))
10658
10659 (defun org-export-copy-visible ()
10660 "Copy the visible part of the buffer to another buffer, for printing.
10661 Also removes the first line of the buffer if it specifies a mode,
10662 and all options lines."
10663 (interactive)
10664 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
10665 ".txt"))
10666 (buffer (find-file-noselect filename))
10667 (ore (concat
10668 (org-make-options-regexp
10669 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10670 "STARTUP" "ARCHIVE"
10671 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10672 (if org-noutline-p "\\(\n\\|$\\)" "")))
10673 s e)
10674 (with-current-buffer buffer
10675 (erase-buffer)
10676 (text-mode))
10677 (save-excursion
10678 (setq s (goto-char (point-min)))
10679 (while (not (= (point) (point-max)))
10680 (goto-char (org-find-invisible))
10681 (append-to-buffer buffer s (point))
10682 (setq s (goto-char (org-find-visible)))))
10683 (switch-to-buffer-other-window buffer)
10684 (newline)
10685 (goto-char (point-min))
10686 (if (looking-at ".*-\\*- mode:.*\n")
10687 (replace-match ""))
10688 (while (re-search-forward ore nil t)
10689 (replace-match ""))
10690 (goto-char (point-min))))
10691
10692 (defun org-find-visible ()
10693 (if (featurep 'noutline)
10694 (let ((s (point)))
10695 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10696 (get-char-property s 'invisible)))
10697 s)
10698 (skip-chars-forward "^\n")
10699 (point)))
10700 (defun org-find-invisible ()
10701 (if (featurep 'noutline)
10702 (let ((s (point)))
10703 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10704 (not (get-char-property s 'invisible))))
10705 s)
10706 (skip-chars-forward "^\r")
10707 (point)))
10708
10709 ;; HTML
10710
10711 (defun org-get-current-options ()
10712 "Return a string with current options as keyword options.
10713 Does include HTML export options as well as TODO and CATEGORY stuff."
10714 (format
10715 "#+TITLE: %s
10716 #+AUTHOR: %s
10717 #+EMAIL: %s
10718 #+LANGUAGE: %s
10719 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10720 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10721 #+CATEGORY: %s
10722 #+SEQ_TODO: %s
10723 #+TYP_TODO: %s
10724 #+STARTUP: %s %s
10725 #+ARCHIVE: %s
10726 "
10727 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10728 org-export-headline-levels
10729 org-export-with-section-numbers
10730 org-export-with-toc
10731 org-export-preserve-breaks
10732 org-export-html-expand
10733 org-export-with-fixed-width
10734 org-export-with-tables
10735 org-export-with-sub-superscripts
10736 org-export-with-emphasize
10737 org-export-with-TeX-macros
10738 (file-name-nondirectory (buffer-file-name))
10739 (if (equal org-todo-interpretation 'sequence)
10740 (mapconcat 'identity org-todo-keywords " ")
10741 "TODO FEEDBACK VERIFY DONE")
10742 (if (equal org-todo-interpretation 'type)
10743 (mapconcat 'identity org-todo-keywords " ")
10744 "Me Jason Marie DONE")
10745 (cdr (assoc org-startup-folded
10746 '((nil . "nofold")(t . "fold")(content . "content"))))
10747 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10748 org-archive-location
10749 ))
10750
10751 (defun org-insert-export-options-template ()
10752 "Insert into the buffer a template with information for exporting."
10753 (interactive)
10754 (if (not (bolp)) (newline))
10755 (let ((s (org-get-current-options)))
10756 (and (string-match "#\\+CATEGORY" s)
10757 (setq s (substring s 0 (match-beginning 0))))
10758 (insert s)))
10759
10760 (defun org-toggle-fixed-width-section (arg)
10761 "Toggle the fixed-width export.
10762 If there is no active region, the QUOTE keyword at the current headline is
10763 inserted or removed. When present, it causes the text between this headline
10764 and the next to be exported as fixed-width text, and unmodified.
10765 If there is an active region, this command adds or removes a colon as the
10766 first character of this line. If the first character of a line is a colon,
10767 this line is also exported in fixed-width font."
10768 (interactive "P")
10769 (let* ((cc 0)
10770 (regionp (org-region-active-p))
10771 (beg (if regionp (region-beginning) (point)))
10772 (end (if regionp (region-end)))
10773 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10774 (re "[ \t]*\\(:\\)")
10775 off)
10776 (if regionp
10777 (save-excursion
10778 (goto-char beg)
10779 (setq cc (current-column))
10780 (beginning-of-line 1)
10781 (setq off (looking-at re))
10782 (while (> nlines 0)
10783 (setq nlines (1- nlines))
10784 (beginning-of-line 1)
10785 (cond
10786 (arg
10787 (move-to-column cc t)
10788 (insert ":\n")
10789 (forward-line -1))
10790 ((and off (looking-at re))
10791 (replace-match "" t t nil 1))
10792 ((not off) (move-to-column cc t) (insert ":")))
10793 (forward-line 1)))
10794 (save-excursion
10795 (org-back-to-heading)
10796 (if (looking-at (concat outline-regexp
10797 "\\( +\\<" org-quote-string "\\>\\)"))
10798 (replace-match "" t t nil 1)
10799 (if (looking-at outline-regexp)
10800 (progn
10801 (goto-char (match-end 0))
10802 (insert " " org-quote-string))))))))
10803
10804 (defun org-export-as-html-and-open (arg)
10805 "Export the outline as HTML and immediately open it with a browser.
10806 If there is an active region, export only the region.
10807 The prefix ARG specifies how many levels of the outline should become
10808 headlines. The default is 3. Lower levels will become bulleted lists."
10809 (interactive "P")
10810 (org-export-as-html arg 'hidden)
10811 (org-open-file (buffer-file-name)))
10812
10813 (defun org-export-as-html-batch ()
10814 "Call `org-export-as-html', may be used in batch processing as
10815 emacs --batch
10816 --load=$HOME/lib/emacs/org.el
10817 --eval \"(setq org-export-headline-levels 2)\"
10818 --visit=MyFile --funcall org-export-as-html-batch"
10819 (org-export-as-html org-export-headline-levels 'hidden))
10820
10821 (defun org-export-as-html (arg &optional hidden)
10822 "Export the outline as a pretty HTML file.
10823 If there is an active region, export only the region.
10824 The prefix ARG specifies how many levels of the outline should become
10825 headlines. The default is 3. Lower levels will become bulleted lists."
10826 (interactive "P")
10827 (setq-default org-todo-line-regexp org-todo-line-regexp)
10828 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
10829 (setq-default org-done-string org-done-string)
10830 (let* ((style org-export-html-style)
10831 (region-p (org-region-active-p))
10832 (region
10833 (buffer-substring
10834 (if region-p (region-beginning) (point-min))
10835 (if region-p (region-end) (point-max))))
10836 (all_lines
10837 (org-skip-comments (org-split-string
10838 (org-cleaned-string-for-export region)
10839 "[\r\n]")))
10840 (lines (org-export-find-first-heading-line all_lines))
10841 (level 0) (line "") (origline "") txt todo
10842 (umax nil)
10843 (filename (concat (file-name-sans-extension (buffer-file-name))
10844 ".html"))
10845 (buffer (find-file-noselect filename))
10846 (levels-open (make-vector org-level-max nil))
10847 (date (format-time-string "%Y/%m/%d" (current-time)))
10848 (time (format-time-string "%X" (current-time)))
10849 (author user-full-name)
10850 (title (buffer-name))
10851 (options nil)
10852 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
10853 (inquote nil)
10854 (infixed nil)
10855 (in-local-list nil)
10856 (local-list-num nil)
10857 (local-list-indent nil)
10858 (llt org-plain-list-ordered-item-terminator)
10859 (email user-mail-address)
10860 (language org-export-default-language)
10861 (text nil)
10862 (lang-words nil)
10863 (head-count 0) cnt
10864 (start 0)
10865 ;; FIXME: The following returns always nil under XEmacs
10866 (coding-system (and (fboundp 'coding-system-get)
10867 (boundp 'buffer-file-coding-system)
10868 buffer-file-coding-system))
10869 (coding-system-for-write (or coding-system coding-system-for-write))
10870 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
10871 (charset (and coding-system
10872 (coding-system-get coding-system 'mime-charset)))
10873 table-open type
10874 table-buffer table-orig-buffer
10875 ind start-is-num starter
10876 )
10877 (message "Exporting...")
10878
10879 (setq org-last-level 1)
10880 (org-init-section-numbers)
10881
10882 ;; Search for the export key lines
10883 (org-parse-key-lines)
10884 (setq lang-words (or (assoc language org-export-language-setup)
10885 (assoc "en" org-export-language-setup)))
10886
10887 ;; Switch to the output buffer
10888 (if (or hidden (not org-export-html-show-new-buffer))
10889 (set-buffer buffer)
10890 (switch-to-buffer-other-window buffer))
10891 (erase-buffer)
10892 (fundamental-mode)
10893 (let ((case-fold-search nil))
10894 (if options (org-parse-export-options options))
10895 (setq umax (if arg (prefix-numeric-value arg)
10896 org-export-headline-levels))
10897
10898 ;; File header
10899 (insert (format
10900 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
10901 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
10902 <html lang=\"%s\"><head>
10903 <title>%s</title>
10904 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
10905 <meta name=generator content=\"Org-mode\">
10906 <meta name=generated content=\"%s %s\">
10907 <meta name=author content=\"%s\">
10908 %s
10909 </head><body>
10910 "
10911 language (org-html-expand title) (or charset "iso-8859-1")
10912 date time author style))
10913 (if title (insert (concat "<H1 class=\"title\">"
10914 (org-html-expand title) "</H1>\n")))
10915 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
10916 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
10917 email "&gt;</a>\n")))
10918 (if (or author email) (insert "<br>\n"))
10919 (if (and date time) (insert (concat (nth 2 lang-words) ": "
10920 date " " time "<br>\n")))
10921 (if text (insert (concat "<p>\n" (org-html-expand text))))
10922 (if org-export-with-toc
10923 (progn
10924 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
10925 (insert "<ul>\n")
10926 (mapcar '(lambda (line)
10927 (if (string-match org-todo-line-regexp line)
10928 ;; This is a headline
10929 (progn
10930 (setq level (- (match-end 1) (match-beginning 1))
10931 txt (save-match-data
10932 (org-html-expand
10933 (match-string 3 line)))
10934 todo
10935 (or (and (match-beginning 2)
10936 (not (equal (match-string 2 line)
10937 org-done-string)))
10938 ; TODO, not DONE
10939 (and (= level umax)
10940 (org-search-todo-below
10941 line lines level))))
10942 (if org-export-with-section-numbers
10943 (setq txt (concat (org-section-number level)
10944 " " txt)))
10945 (if (<= level umax)
10946 (progn
10947 (setq head-count (+ head-count 1))
10948 (if (> level org-last-level)
10949 (progn
10950 (setq cnt (- level org-last-level))
10951 (while (>= (setq cnt (1- cnt)) 0)
10952 (insert "<ul>"))
10953 (insert "\n")))
10954 (if (< level org-last-level)
10955 (progn
10956 (setq cnt (- org-last-level level))
10957 (while (>= (setq cnt (1- cnt)) 0)
10958 (insert "</ul>"))
10959 (insert "\n")))
10960 (insert
10961 (format
10962 (if todo
10963 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
10964 "<li><a href=\"#sec-%d\">%s</a>\n")
10965 head-count txt))
10966 (setq org-last-level level))
10967 ))))
10968 lines)
10969 (while (> org-last-level 0)
10970 (setq org-last-level (1- org-last-level))
10971 (insert "</ul>\n"))
10972 ))
10973 (setq head-count 0)
10974 (org-init-section-numbers)
10975
10976 (while (setq line (pop lines) origline line)
10977 (catch 'nextline
10978
10979 ;; end of quote section?
10980 (when (and inquote (string-match "^\\*+" line))
10981 (insert "</pre>\n")
10982 (setq inquote nil))
10983 ;; inside a quote section?
10984 (when inquote
10985 (insert (org-html-protect line) "\n")
10986 (throw 'nextline nil))
10987
10988 ;; verbatim lines
10989 (when (and org-export-with-fixed-width
10990 (string-match "^[ \t]*:\\(.*\\)" line))
10991 (when (not infixed)
10992 (setq infixed t)
10993 (insert "<pre>\n"))
10994 (insert (org-html-protect (match-string 1 line)) "\n")
10995 (when (and lines
10996 (not (string-match "^[ \t]*\\(:.*\\)"
10997 (car lines))))
10998 (setq infixed nil)
10999 (insert "</pre>\n"))
11000 (throw 'nextline nil))
11001
11002
11003 ;; make targets to anchors
11004 (while (string-match "<<<?\\([^<>]*\\)>>>?[ \t]*\n?" line)
11005 (setq line (replace-match
11006 (concat "@<a name=\""
11007 (org-solidify-link-text (match-string 1 line))
11008 "\">\\nbsp@</a>")
11009 t t line)))
11010 ;; Replace internal links
11011 (while (string-match org-bracket-link-regexp line)
11012 (setq line (replace-match
11013 (concat
11014 "@<a href=\"#"
11015 (org-solidify-link-text (match-string 1 line))
11016 "\">"
11017 (match-string (if (match-end 3) 3 1) line)
11018 "@</a>")
11019 t t line)))
11020
11021 ;; Protect the external links
11022 (setq start 0)
11023 (while (string-match org-link-maybe-angles-regexp line start)
11024 (setq start (match-end 0))
11025 (setq line (replace-match
11026 (concat "\000" (match-string 1 line) "\000")
11027 t t line)))
11028
11029 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11030 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11031 (setq line (org-html-expand line))
11032
11033 ;; Format the links
11034 (setq start 0)
11035 (while (string-match org-protected-link-regexp line start)
11036 (setq start (- (match-end 0) 2))
11037 (setq type (match-string 1 line))
11038 (cond
11039 ((member type '("http" "https" "ftp" "mailto" "news"))
11040 ;; standard URL
11041 (setq line (replace-match
11042 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
11043 "<a href=\"\\1:\\2\">\\1:\\2</a>"
11044 nil nil line)))
11045 ((string= type "file")
11046 ;; FILE link
11047 (let* ((filename (match-string 2 line))
11048 (abs-p (file-name-absolute-p filename))
11049 (thefile (if abs-p (expand-file-name filename) filename))
11050 (thefile (save-match-data
11051 (if (string-match ":[0-9]+$" thefile)
11052 (replace-match "" t t thefile)
11053 thefile)))
11054 (file-is-image-p
11055 (save-match-data
11056 (string-match (org-image-file-name-regexp) thefile))))
11057 (setq line (replace-match
11058 (if (and org-export-html-inline-images
11059 file-is-image-p)
11060 (concat "<img src=\"" thefile "\"/>")
11061 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
11062 nil nil line))))
11063
11064 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11065 (setq line (replace-match
11066 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
11067
11068 ;; TODO items
11069 (if (and (string-match org-todo-line-regexp line)
11070 (match-beginning 2))
11071 (if (equal (match-string 2 line) org-done-string)
11072 (setq line (replace-match
11073 "<span class=\"done\">\\2</span>"
11074 nil nil line 2))
11075 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11076 nil nil line 2))))
11077
11078 ;; DEADLINES
11079 (if (string-match org-deadline-line-regexp line)
11080 (progn
11081 (if (save-match-data
11082 (string-match "<a href"
11083 (substring line 0 (match-beginning 0))))
11084 nil ; Don't do the replacement - it is inside a link
11085 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11086 nil nil line 1)))))
11087 (cond
11088 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11089 ;; This is a headline
11090 (setq level (- (match-end 1) (match-beginning 1))
11091 txt (match-string 2 line))
11092 (if (<= level umax) (setq head-count (+ head-count 1)))
11093 (when in-local-list
11094 ;; Close any local lists before inserting a new header line
11095 (while local-list-num
11096 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11097 (pop local-list-num))
11098 (setq local-list-indent nil
11099 in-local-list nil))
11100 (org-html-level-start level txt umax
11101 (and org-export-with-toc (<= level umax))
11102 head-count)
11103 ;; QUOTES
11104 (when (string-match quote-re line)
11105 (insert "<pre>")
11106 (setq inquote t)))
11107
11108 ((and org-export-with-tables
11109 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11110 (if (not table-open)
11111 ;; New table starts
11112 (setq table-open t table-buffer nil table-orig-buffer nil))
11113 ;; Accumulate lines
11114 (setq table-buffer (cons line table-buffer)
11115 table-orig-buffer (cons origline table-orig-buffer))
11116 (when (or (not lines)
11117 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11118 (car lines))))
11119 (setq table-open nil
11120 table-buffer (nreverse table-buffer)
11121 table-orig-buffer (nreverse table-orig-buffer))
11122 (insert (org-format-table-html table-buffer table-orig-buffer))))
11123 (t
11124 ;; Normal lines
11125 (when (and (> org-export-plain-list-max-depth 0)
11126 (string-match
11127 (cond
11128 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11129 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11130 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11131 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11132 line))
11133 (setq ind (org-get-string-indentation line)
11134 start-is-num (match-beginning 4)
11135 starter (if (match-beginning 2) (match-string 2 line))
11136 line (substring line (match-beginning 5)))
11137 (unless (string-match "[^ \t]" line)
11138 ;; empty line. Pretend indentation is large.
11139 (setq ind (1+ (or (car local-list-indent) 1))))
11140 (while (and in-local-list
11141 (or (and (= ind (car local-list-indent))
11142 (not starter))
11143 (< ind (car local-list-indent))))
11144 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11145 (pop local-list-num) (pop local-list-indent)
11146 (setq in-local-list local-list-indent))
11147 (cond
11148 ((and starter
11149 (or (not in-local-list)
11150 (> ind (car local-list-indent)))
11151 (< (length local-list-indent)
11152 org-export-plain-list-max-depth))
11153 ;; Start new (level of ) list
11154 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11155 (push start-is-num local-list-num)
11156 (push ind local-list-indent)
11157 (setq in-local-list t))
11158 (starter
11159 ;; continue current list
11160 (insert "<li>\n"))))
11161 ;; Empty lines start a new paragraph. If hand-formatted lists
11162 ;; are not fully interpreted, lines starting with "-", "+", "*"
11163 ;; also start a new paragraph.
11164 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11165 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11166 ))
11167 (if org-export-html-with-timestamp
11168 (insert org-export-html-html-helper-timestamp))
11169 (insert "</body>\n</html>\n")
11170 (normal-mode)
11171 (save-buffer)
11172 (goto-char (point-min)))))
11173
11174 (defun org-format-table-html (lines olines)
11175 "Find out which HTML converter to use and return the HTML code."
11176 (if (string-match "^[ \t]*|" (car lines))
11177 ;; A normal org table
11178 (org-format-org-table-html lines)
11179 ;; Table made by table.el - test for spanning
11180 (let* ((hlines (delq nil (mapcar
11181 (lambda (x)
11182 (if (string-match "^[ \t]*\\+-" x) x
11183 nil))
11184 lines)))
11185 (first (car hlines))
11186 (ll (and (string-match "\\S-+" first)
11187 (match-string 0 first)))
11188 (re (concat "^[ \t]*" (regexp-quote ll)))
11189 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
11190 hlines))))
11191 (if (and (not spanning)
11192 (not org-export-prefer-native-exporter-for-tables))
11193 ;; We can use my own converter with HTML conversions
11194 (org-format-table-table-html lines)
11195 ;; Need to use the code generator in table.el, with the original text.
11196 (org-format-table-table-html-using-table-generate-source olines)))))
11197
11198 (defun org-format-org-table-html (lines)
11199 "Format a table into HTML."
11200 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11201 (setq lines (nreverse lines))
11202 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11203 (setq lines (nreverse lines))
11204 (when org-export-table-remove-special-lines
11205 ;; Check if the table has a marking column. If yes remove the
11206 ;; column and the special lines
11207 (let* ((special
11208 (not
11209 (memq nil
11210 (mapcar
11211 (lambda (x)
11212 (or (string-match "^[ \t]*|-" x)
11213 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
11214 lines)))))
11215 (if special
11216 (setq lines
11217 (delq nil
11218 (mapcar
11219 (lambda (x)
11220 (if (string-match "^[ \t]*| *[!_^] *|" x)
11221 nil ; ignore this line
11222 (and (or (string-match "^[ \t]*|-+\\+" x)
11223 (string-match "^[ \t]*|[^|]*|" x))
11224 (replace-match "|" t t x))))
11225 lines))))))
11226
11227 (let ((head (and org-export-highlight-first-table-line
11228 (delq nil (mapcar
11229 (lambda (x) (string-match "^[ \t]*|-" x))
11230 (cdr lines)))))
11231 line fields html)
11232 (setq html (concat org-export-html-table-tag "\n"))
11233 (while (setq line (pop lines))
11234 (catch 'next-line
11235 (if (string-match "^[ \t]*|-" line)
11236 (progn
11237 (setq head nil) ;; head ends here, first time around
11238 ;; ignore this line
11239 (throw 'next-line t)))
11240 ;; Break the line into fields
11241 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11242 (setq html (concat
11243 html
11244 "<tr>"
11245 (mapconcat (lambda (x)
11246 (if head
11247 (concat "<th>" x "</th>")
11248 (concat "<td>" x "</td>")))
11249 fields "")
11250 "</tr>\n"))))
11251 (setq html (concat html "</table>\n"))
11252 html))
11253
11254 (defun org-fake-empty-table-line (line)
11255 "Replace everything except \"|\" with spaces."
11256 (let ((i (length line))
11257 (newstr (copy-sequence line)))
11258 (while (> i 0)
11259 (setq i (1- i))
11260 (if (not (eq (aref newstr i) ?|))
11261 (aset newstr i ?\ )))
11262 newstr))
11263
11264 (defun org-format-table-table-html (lines)
11265 "Format a table generated by table.el into HTML.
11266 This conversion does *not* use `table-generate-source' from table.el.
11267 This has the advantage that Org-mode's HTML conversions can be used.
11268 But it has the disadvantage, that no cell- or row-spanning is allowed."
11269 (let (line field-buffer
11270 (head org-export-highlight-first-table-line)
11271 fields html empty)
11272 (setq html (concat org-export-html-table-tag "\n"))
11273 (while (setq line (pop lines))
11274 (setq empty "&nbsp")
11275 (catch 'next-line
11276 (if (string-match "^[ \t]*\\+-" line)
11277 (progn
11278 (if field-buffer
11279 (progn
11280 (setq html (concat
11281 html
11282 "<tr>"
11283 (mapconcat
11284 (lambda (x)
11285 (if (equal x "") (setq x empty))
11286 (if head
11287 (concat "<th>" x "</th>\n")
11288 (concat "<td>" x "</td>\n")))
11289 field-buffer "\n")
11290 "</tr>\n"))
11291 (setq head nil)
11292 (setq field-buffer nil)))
11293 ;; Ignore this line
11294 (throw 'next-line t)))
11295 ;; Break the line into fields and store the fields
11296 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11297 (if field-buffer
11298 (setq field-buffer (mapcar
11299 (lambda (x)
11300 (concat x "<br>" (pop fields)))
11301 field-buffer))
11302 (setq field-buffer fields))))
11303 (setq html (concat html "</table>\n"))
11304 html))
11305
11306 (defun org-format-table-table-html-using-table-generate-source (lines)
11307 "Format a table into html, using `table-generate-source' from table.el.
11308 This has the advantage that cell- or row-spanning is allowed.
11309 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
11310 (require 'table)
11311 (with-current-buffer (get-buffer-create " org-tmp1 ")
11312 (erase-buffer)
11313 (insert (mapconcat 'identity lines "\n"))
11314 (goto-char (point-min))
11315 (if (not (re-search-forward "|[^+]" nil t))
11316 (error "Error processing table"))
11317 (table-recognize-table)
11318 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
11319 (table-generate-source 'html " org-tmp2 ")
11320 (set-buffer " org-tmp2 ")
11321 (buffer-substring (point-min) (point-max))))
11322
11323 (defun org-html-protect (s)
11324 ;; convert & to &amp;, < to &lt; and > to &gt;
11325 (let ((start 0))
11326 (while (string-match "&" s start)
11327 (setq s (replace-match "&amp;" t t s)
11328 start (1+ (match-beginning 0))))
11329 (while (string-match "<" s)
11330 (setq s (replace-match "&lt;" t t s)))
11331 (while (string-match ">" s)
11332 (setq s (replace-match "&gt;" t t s))))
11333 s)
11334
11335 (defun org-html-expand (string)
11336 "Prepare STRING for HTML export. Applies all active conversions."
11337 ;; First check if there is a link in the line - if yes, apply conversions
11338 ;; only before the start of the link.
11339 ;; FIXME: This is no longer correct, because links now have an end.
11340 (let* ((m (string-match org-link-regexp string))
11341 (s (if m (substring string 0 m) string))
11342 (r (if m (substring string m) "")))
11343 ;; convert & to &amp;, < to &lt; and > to &gt;
11344 (setq s (org-html-protect s))
11345 (if org-export-html-expand
11346 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
11347 (setq s (replace-match "<\\1>" nil nil s))))
11348 (if org-export-with-emphasize
11349 (setq s (org-export-html-convert-emphasize s)))
11350 (if org-export-with-sub-superscripts
11351 (setq s (org-export-html-convert-sub-super s)))
11352 (if org-export-with-TeX-macros
11353 (let ((start 0) wd ass)
11354 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
11355 (setq wd (match-string 1 s))
11356 (if (setq ass (assoc wd org-html-entities))
11357 (setq s (replace-match (or (cdr ass)
11358 (concat "&" (car ass) ";"))
11359 t t s))
11360 (setq start (+ start (length wd)))))))
11361 (concat s r)))
11362
11363 (defun org-create-multibrace-regexp (left right n)
11364 "Create a regular expression which will match a balanced sexp.
11365 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
11366 as single character strings.
11367 The regexp returned will match the entire expression including the
11368 delimiters. It will also define a single group which contains the
11369 match except for the outermost delimiters. The maximum depth of
11370 stacked delimiters is N. Escaping delimiters is not possible."
11371 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
11372 (or "\\|")
11373 (re nothing)
11374 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
11375 (while (> n 1)
11376 (setq n (1- n)
11377 re (concat re or next)
11378 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
11379 (concat left "\\(" re "\\)" right)))
11380
11381 (defvar org-match-substring-regexp
11382 (concat
11383 "\\([^\\]\\)\\([_^]\\)\\("
11384 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
11385 "\\|"
11386 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
11387 "\\|"
11388 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
11389 "The regular expression matching a sub- or superscript.")
11390
11391 (defun org-export-html-convert-sub-super (string)
11392 "Convert sub- and superscripts in STRING to HTML."
11393 (let (key c)
11394 (while (string-match org-match-substring-regexp string)
11395 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
11396 (setq c (or (match-string 8 string)
11397 (match-string 6 string)
11398 (match-string 5 string)))
11399 (setq string (replace-match
11400 (concat (match-string 1 string)
11401 "<" key ">" c "</" key ">")
11402 t t string)))
11403 (while (string-match "\\\\\\([_^]\\)" string)
11404 (setq string (replace-match (match-string 1 string) t t string))))
11405 string)
11406
11407 (defun org-export-html-convert-emphasize (string)
11408 (while (string-match
11409 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
11410 string)
11411 (setq string (replace-match
11412 (concat "<b>" (match-string 3 string) "</b>")
11413 t t string 2)))
11414 (while (string-match
11415 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
11416 string)
11417 (setq string (replace-match
11418 (concat "<i>" (match-string 3 string) "</i>")
11419 t t string 2)))
11420 (while (string-match
11421 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
11422 string)
11423 (setq string (replace-match
11424 (concat "<u>" (match-string 3 string) "</u>")
11425 t t string 2)))
11426 string)
11427
11428 (defun org-parse-key-lines ()
11429 "Find the special key lines with the information for exporters."
11430 (save-excursion
11431 (goto-char 0)
11432 (let ((re (org-make-options-regexp
11433 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
11434 key)
11435 (while (re-search-forward re nil t)
11436 (setq key (match-string 1))
11437 (cond ((string-equal key "TITLE")
11438 (setq title (match-string 2)))
11439 ((string-equal key "AUTHOR")
11440 (setq author (match-string 2)))
11441 ((string-equal key "EMAIL")
11442 (setq email (match-string 2)))
11443 ((string-equal key "LANGUAGE")
11444 (setq language (match-string 2)))
11445 ((string-equal key "TEXT")
11446 (setq text (concat text "\n" (match-string 2))))
11447 ((string-equal key "OPTIONS")
11448 (setq options (match-string 2))))))))
11449
11450 (defun org-parse-export-options (s)
11451 "Parse the export options line."
11452 (let ((op '(("H" . org-export-headline-levels)
11453 ("num" . org-export-with-section-numbers)
11454 ("toc" . org-export-with-toc)
11455 ("\\n" . org-export-preserve-breaks)
11456 ("@" . org-export-html-expand)
11457 (":" . org-export-with-fixed-width)
11458 ("|" . org-export-with-tables)
11459 ("^" . org-export-with-sub-superscripts)
11460 ("*" . org-export-with-emphasize)
11461 ("TeX" . org-export-with-TeX-macros)))
11462 o)
11463 (while (setq o (pop op))
11464 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
11465 s)
11466 (set (make-local-variable (cdr o))
11467 (car (read-from-string (match-string 1 s))))))))
11468
11469 (defun org-html-level-start (level title umax with-toc head-count)
11470 "Insert a new level in HTML export."
11471 (let ((l (1+ (max level umax))))
11472 (while (<= l org-level-max)
11473 (if (aref levels-open (1- l))
11474 (progn
11475 (org-html-level-close l)
11476 (aset levels-open (1- l) nil)))
11477 (setq l (1+ l)))
11478 (if (> level umax)
11479 (progn
11480 (if (aref levels-open (1- level))
11481 (insert "<li>" title "<p>\n")
11482 (aset levels-open (1- level) t)
11483 (insert "<ul><li>" title "<p>\n")))
11484 (if org-export-with-section-numbers
11485 (setq title (concat (org-section-number level) " " title)))
11486 (setq level (+ level 1))
11487 (if with-toc
11488 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
11489 level head-count title level))
11490 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
11491
11492 (defun org-html-level-close (&rest args)
11493 "Terminate one level in HTML export."
11494 (insert "</ul>"))
11495
11496 ;; Variable holding the vector with section numbers
11497 (defvar org-section-numbers (make-vector org-level-max 0))
11498
11499 (defun org-init-section-numbers ()
11500 "Initialize the vector for the section numbers."
11501 (let* ((level -1)
11502 (numbers (nreverse (org-split-string "" "\\.")))
11503 (depth (1- (length org-section-numbers)))
11504 (i depth) number-string)
11505 (while (>= i 0)
11506 (if (> i level)
11507 (aset org-section-numbers i 0)
11508 (setq number-string (or (car numbers) "0"))
11509 (if (string-match "\\`[A-Z]\\'" number-string)
11510 (aset org-section-numbers i
11511 (- (string-to-char number-string) ?A -1))
11512 (aset org-section-numbers i (string-to-number number-string)))
11513 (pop numbers))
11514 (setq i (1- i)))))
11515
11516 (defun org-section-number (&optional level)
11517 "Return a string with the current section number.
11518 When LEVEL is non-nil, increase section numbers on that level."
11519 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
11520 (when level
11521 (when (> level -1)
11522 (aset org-section-numbers
11523 level (1+ (aref org-section-numbers level))))
11524 (setq idx (1+ level))
11525 (while (<= idx depth)
11526 (if (not (= idx 1))
11527 (aset org-section-numbers idx 0))
11528 (setq idx (1+ idx))))
11529 (setq idx 0)
11530 (while (<= idx depth)
11531 (setq n (aref org-section-numbers idx))
11532 (setq string (concat string (if (not (string= string "")) "." "")
11533 (int-to-string n)))
11534 (setq idx (1+ idx)))
11535 (save-match-data
11536 (if (string-match "\\`\\([@0]\\.\\)+" string)
11537 (setq string (replace-match "" nil nil string)))
11538 (if (string-match "\\(\\.0\\)+\\'" string)
11539 (setq string (replace-match "" nil nil string))))
11540 string))
11541
11542
11543 (defun org-export-icalendar-this-file ()
11544 "Export current file as an iCalendar file.
11545 The iCalendar file will be located in the same directory as the Org-mode
11546 file, but with extension `.ics'."
11547 (interactive)
11548 (org-export-icalendar nil (buffer-file-name)))
11549
11550 ;;;###autoload
11551 (defun org-export-icalendar-all-agenda-files ()
11552 "Export all files in `org-agenda-files' to iCalendar .ics files.
11553 Each iCalendar file will be located in the same directory as the Org-mode
11554 file, but with extension `.ics'."
11555 (interactive)
11556 (apply 'org-export-icalendar nil org-agenda-files))
11557
11558 ;;;###autoload
11559 (defun org-export-icalendar-combine-agenda-files ()
11560 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11561 The file is stored under the name `org-combined-agenda-icalendar-file'."
11562 (interactive)
11563 (apply 'org-export-icalendar t org-agenda-files))
11564
11565 (defun org-export-icalendar (combine &rest files)
11566 "Create iCalendar files for all elements of FILES.
11567 If COMBINE is non-nil, combine all calendar entries into a single large
11568 file and store it under the name `org-combined-agenda-icalendar-file'."
11569 (save-excursion
11570 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11571 (when combine
11572 (setq ical-file org-combined-agenda-icalendar-file
11573 ical-buffer (org-get-agenda-file-buffer ical-file))
11574 (set-buffer ical-buffer) (erase-buffer))
11575 (while (setq file (pop files))
11576 (catch 'nextfile
11577 (org-check-agenda-file file)
11578 (unless combine
11579 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11580 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11581 (set-buffer ical-buffer) (erase-buffer))
11582 (set-buffer (org-get-agenda-file-buffer file))
11583 (setq category (or org-category
11584 (file-name-sans-extension
11585 (file-name-nondirectory (buffer-file-name)))))
11586 (if (symbolp category) (setq category (symbol-name category)))
11587 (let ((standard-output ical-buffer))
11588 (if combine
11589 (and (not started) (setq started t)
11590 (org-start-icalendar-file org-icalendar-combined-name))
11591 (org-start-icalendar-file category))
11592 (org-print-icalendar-entries combine category)
11593 (when (or (and combine (not files)) (not combine))
11594 (org-finish-icalendar-file)
11595 (set-buffer ical-buffer)
11596 (save-buffer)
11597 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11598 (org-release-buffers org-agenda-new-buffers))))
11599
11600 (defvar org-after-save-iCalendar-file-hook nil
11601 "Hook run after an iCalendar file has been saved.
11602 The iCalendar buffer is still current when this hook is run.
11603 A good way to use this is to tell a desktop calenndar application to re-read
11604 the iCalendar file.")
11605
11606 (defun org-print-icalendar-entries (&optional combine category)
11607 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11608 When COMBINE is non nil, add the category to each line."
11609 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11610 (dts (org-ical-ts-to-string
11611 (format-time-string (cdr org-time-stamp-formats) (current-time))
11612 "DTSTART"))
11613 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11614 (save-excursion
11615 (goto-char (point-min))
11616 (while (re-search-forward org-ts-regexp nil t)
11617 (setq pos (match-beginning 0)
11618 ts (match-string 0)
11619 inc t
11620 hd (org-get-heading))
11621 (if (looking-at re2)
11622 (progn
11623 (goto-char (match-end 0))
11624 (setq ts2 (match-string 1) inc nil))
11625 (setq ts2 ts
11626 tmp (buffer-substring (max (point-min)
11627 (- pos org-ds-keyword-length))
11628 pos)
11629 deadlinep (string-match org-deadline-regexp tmp)
11630 scheduledp (string-match org-scheduled-regexp tmp)
11631 ;; donep (org-entry-is-done-p)
11632 ))
11633 (if (or (string-match org-tr-regexp hd)
11634 (string-match org-ts-regexp hd))
11635 (setq hd (replace-match "" t t hd)))
11636 (if combine
11637 (setq hd (concat hd " (category " category ")")))
11638 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11639 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11640 (princ (format "BEGIN:VEVENT
11641 %s
11642 %s
11643 SUMMARY:%s
11644 END:VEVENT\n"
11645 (org-ical-ts-to-string ts "DTSTART")
11646 (org-ical-ts-to-string ts2 "DTEND" inc)
11647 hd)))
11648 (when org-icalendar-include-todo
11649 (goto-char (point-min))
11650 (while (re-search-forward org-todo-line-regexp nil t)
11651 (setq state (match-string 1))
11652 (unless (equal state org-done-string)
11653 (setq hd (match-string 3))
11654 (if (string-match org-priority-regexp hd)
11655 (setq pri (string-to-char (match-string 2 hd))
11656 hd (concat (substring hd 0 (match-beginning 1))
11657 (substring hd (- (match-end 1)))))
11658 (setq pri org-default-priority))
11659 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11660 (- org-lowest-priority ?A))))))
11661
11662 (princ (format "BEGIN:VTODO
11663 %s
11664 SUMMARY:%s
11665 SEQUENCE:1
11666 PRIORITY:%d
11667 END:VTODO\n"
11668 dts hd pri))))))))
11669
11670 (defun org-start-icalendar-file (name)
11671 "Start an iCalendar file by inserting the header."
11672 (let ((user user-full-name)
11673 (name (or name "unknown"))
11674 (timezone (cadr (current-time-zone))))
11675 (princ
11676 (format "BEGIN:VCALENDAR
11677 VERSION:2.0
11678 X-WR-CALNAME:%s
11679 PRODID:-//%s//Emacs with Org-mode//EN
11680 X-WR-TIMEZONE:%s
11681 CALSCALE:GREGORIAN\n" name user timezone))))
11682
11683 (defun org-finish-icalendar-file ()
11684 "Finish an iCalendar file by inserting the END statement."
11685 (princ "END:VCALENDAR\n"))
11686
11687 (defun org-ical-ts-to-string (s keyword &optional inc)
11688 "Take a time string S and convert it to iCalendar format.
11689 KEYWORD is added in front, to make a complete line like DTSTART....
11690 When INC is non-nil, increase the hour by two (if time string contains
11691 a time), or the day by one (if it does not contain a time)."
11692 (let ((t1 (org-parse-time-string s 'nodefault))
11693 t2 fmt have-time time)
11694 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11695 (setq t2 t1 have-time t)
11696 (setq t2 (org-parse-time-string s)))
11697 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11698 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11699 (when inc
11700 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11701 (setq time (encode-time s mi h d m y)))
11702 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11703 (concat keyword (format-time-string fmt time))))
11704
11705
11706 ;;; Key bindings
11707
11708 ;; - Bindings in Org-mode map are currently
11709 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11710 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
11711 ;; e (?) useful from outline-mode
11712 ;; i k @ expendable from outline-mode
11713 ;; 0123456789 % & ()_{} " ` free
11714
11715 ;; Make `C-c C-x' a prefix key
11716 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11717
11718 ;; TAB key with modifiers
11719 (define-key org-mode-map "\C-i" 'org-cycle)
11720 (define-key org-mode-map [(meta tab)] 'org-complete)
11721 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11722 ;; The following line is necessary under Suse GNU/Linux
11723 (unless org-xemacs-p
11724 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11725 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11726
11727 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11728 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11729 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11730 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11731 (define-key org-mode-map [(meta return)] 'org-meta-return)
11732 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11733 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11734
11735 ;; Cursor keys with modifiers
11736 (define-key org-mode-map [(meta left)] 'org-metaleft)
11737 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11738 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11739 (define-key org-mode-map [(meta right)] 'org-metaright)
11740 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11741 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11742 (define-key org-mode-map [(meta up)] 'org-metaup)
11743 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11744 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11745 (define-key org-mode-map [(meta down)] 'org-metadown)
11746 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11747 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11748
11749 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11750 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11751 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11752 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11753 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11754 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11755 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11756 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11757 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11758 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11759 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11760 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11761 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11762 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11763 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11764 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11765
11766 ;; All the other keys
11767 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11768 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11769 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11770 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11771 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11772 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11773 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11774 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11775 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11776 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11777 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11778 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11779 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11780 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11781 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
11782 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
11783 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11784 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11785 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11786 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11787 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11788 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11789 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11790 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11791 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
11792 (define-key org-mode-map "\C-c]" 'org-remove-file)
11793 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
11794 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
11795 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
11796 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11797 (define-key org-mode-map "\C-m" 'org-return)
11798 (define-key org-mode-map "\C-c?" 'org-table-current-column)
11799 (define-key org-mode-map "\C-c " 'org-table-blank-field)
11800 (define-key org-mode-map "\C-c+" 'org-table-sum)
11801 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
11802 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
11803 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
11804 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
11805 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11806 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
11807 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11808 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
11809 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
11810 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
11811 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
11812 ;; OPML support is only an option for the future
11813 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
11814 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
11815 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
11816 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
11817 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
11818 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11819 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
11820 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11821 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
11822 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
11823 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
11824
11825 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11826 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11827 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11828
11829 (defsubst org-table-p () (org-at-table-p))
11830
11831 (defun org-self-insert-command (N)
11832 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11833 If the cursor is in a table looking at whitespace, the whitespace is
11834 overwritten, and the table is not marked as requiring realignment."
11835 (interactive "p")
11836 (if (and (org-table-p)
11837 (or
11838 (and org-table-auto-blank-field
11839 (member last-command
11840 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11841 (org-table-blank-field))
11842 t)
11843 (eq N 1)
11844 (looking-at "[^|\n]* +|"))
11845 (let (org-table-may-need-update)
11846 (goto-char (1- (match-end 0)))
11847 (delete-backward-char 1)
11848 (goto-char (match-beginning 0))
11849 (self-insert-command N))
11850 (setq org-table-may-need-update t)
11851 (self-insert-command N)))
11852
11853 ;; FIXME:
11854 ;; The following two functions might still be optimized to trigger
11855 ;; re-alignment less frequently.
11856
11857 (defun org-delete-backward-char (N)
11858 "Like `delete-backward-char', insert whitespace at field end in tables.
11859 When deleting backwards, in tables this function will insert whitespace in
11860 front of the next \"|\" separator, to keep the table aligned. The table will
11861 still be marked for re-alignment, because a narrow field may lead to a
11862 reduced column width."
11863 (interactive "p")
11864 (if (and (org-table-p)
11865 (eq N 1)
11866 (string-match "|" (buffer-substring (point-at-bol) (point)))
11867 (looking-at ".*?|"))
11868 (let ((pos (point)))
11869 (backward-delete-char N)
11870 (skip-chars-forward "^|")
11871 (insert " ")
11872 (goto-char (1- pos)))
11873 (backward-delete-char N)))
11874
11875 (defun org-delete-char (N)
11876 "Like `delete-char', but insert whitespace at field end in tables.
11877 When deleting characters, in tables this function will insert whitespace in
11878 front of the next \"|\" separator, to keep the table aligned. The table
11879 will still be marked for re-alignment, because a narrow field may lead to
11880 a reduced column width."
11881 (interactive "p")
11882 (if (and (org-table-p)
11883 (not (bolp))
11884 (not (= (char-after) ?|))
11885 (eq N 1))
11886 (if (looking-at ".*?|")
11887 (let ((pos (point)))
11888 (replace-match (concat
11889 (substring (match-string 0) 1 -1)
11890 " |"))
11891 (goto-char pos)))
11892 (delete-char N)))
11893
11894 ;; How to do this: Measure non-white length of current string
11895 ;; If equal to column width, we should realign.
11896
11897 (defun org-remap (map &rest commands)
11898 "In MAP, remap the functions given in COMMANDS.
11899 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11900 (let (new old)
11901 (while commands
11902 (setq old (pop commands) new (pop commands))
11903 (if (fboundp 'command-remapping)
11904 (define-key map (vector 'remap old) new)
11905 (substitute-key-definition old new map global-map)))))
11906
11907 (when (eq org-enable-table-editor 'optimized)
11908 ;; If the user wants maximum table support, we need to hijack
11909 ;; some standard editing functions
11910 (org-remap org-mode-map
11911 'self-insert-command 'org-self-insert-command
11912 'delete-char 'org-delete-char
11913 'delete-backward-char 'org-delete-backward-char)
11914 (define-key org-mode-map "|" 'org-force-self-insert))
11915
11916 (defun org-shiftcursor-error ()
11917 "Throw an error because Shift-Cursor command was applied in wrong context."
11918 (error "This command is active in special context like tables, headlines or timestamps"))
11919
11920 (defun org-shifttab ()
11921 "Global visibility cycling or move to previous table field.
11922 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
11923 See the individual commands for more information."
11924 (interactive)
11925 (cond
11926 ((org-at-table-p) (org-table-previous-field))
11927 (t (org-cycle '(4)))))
11928
11929 (defun org-shiftmetaleft ()
11930 "Promote subtree or delete table column.
11931 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
11932 See the individual commands for more information."
11933 (interactive)
11934 (cond
11935 ((org-at-table-p) (org-table-delete-column))
11936 ((org-on-heading-p) (org-promote-subtree))
11937 ((org-at-item-p) (call-interactively 'org-outdent-item))
11938 (t (org-shiftcursor-error))))
11939
11940 (defun org-shiftmetaright ()
11941 "Demote subtree or insert table column.
11942 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
11943 See the individual commands for more information."
11944 (interactive)
11945 (cond
11946 ((org-at-table-p) (org-table-insert-column))
11947 ((org-on-heading-p) (org-demote-subtree))
11948 ((org-at-item-p) (call-interactively 'org-indent-item))
11949 (t (org-shiftcursor-error))))
11950
11951 (defun org-shiftmetaup (&optional arg)
11952 "Move subtree up or kill table row.
11953 Calls `org-move-subtree-up' or `org-table-kill-row' or
11954 `org-move-item-up' depending on context. See the individual commands
11955 for more information."
11956 (interactive "P")
11957 (cond
11958 ((org-at-table-p) (org-table-kill-row))
11959 ((org-on-heading-p) (org-move-subtree-up arg))
11960 ((org-at-item-p) (org-move-item-up arg))
11961 (t (org-shiftcursor-error))))
11962 (defun org-shiftmetadown (&optional arg)
11963 "Move subtree down or insert table row.
11964 Calls `org-move-subtree-down' or `org-table-insert-row' or
11965 `org-move-item-down', depending on context. See the individual
11966 commands for more information."
11967 (interactive "P")
11968 (cond
11969 ((org-at-table-p) (org-table-insert-row arg))
11970 ((org-on-heading-p) (org-move-subtree-down arg))
11971 ((org-at-item-p) (org-move-item-down arg))
11972 (t (org-shiftcursor-error))))
11973
11974 (defun org-metaleft (&optional arg)
11975 "Promote heading or move table column to left.
11976 Calls `org-do-promote' or `org-table-move-column', depending on context.
11977 With no specific context, calls the Emacs default `backward-word'.
11978 See the individual commands for more information."
11979 (interactive "P")
11980 (cond
11981 ((org-at-table-p) (org-table-move-column 'left))
11982 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
11983 (t (backward-word (prefix-numeric-value arg)))))
11984
11985 (defun org-metaright (&optional arg)
11986 "Demote subtree or move table column to right.
11987 Calls `org-do-demote' or `org-table-move-column', depending on context.
11988 With no specific context, calls the Emacs default `forward-word'.
11989 See the individual commands for more information."
11990 (interactive "P")
11991 (cond
11992 ((org-at-table-p) (org-table-move-column nil))
11993 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
11994 (t (forward-word (prefix-numeric-value arg)))))
11995
11996 (defun org-metaup (&optional arg)
11997 "Move subtree up or move table row up.
11998 Calls `org-move-subtree-up' or `org-table-move-row' or
11999 `org-move-item-up', depending on context. See the individual commands
12000 for more information."
12001 (interactive "P")
12002 (cond
12003 ((org-at-table-p) (org-table-move-row 'up))
12004 ((org-on-heading-p) (org-move-subtree-up arg))
12005 ((org-at-item-p) (org-move-item-up arg))
12006 (t (org-shiftcursor-error))))
12007
12008 (defun org-metadown (&optional arg)
12009 "Move subtree down or move table row down.
12010 Calls `org-move-subtree-down' or `org-table-move-row' or
12011 `org-move-item-down', depending on context. See the individual
12012 commands for more information."
12013 (interactive "P")
12014 (cond
12015 ((org-at-table-p) (org-table-move-row nil))
12016 ((org-on-heading-p) (org-move-subtree-down arg))
12017 ((org-at-item-p) (org-move-item-down arg))
12018 (t (org-shiftcursor-error))))
12019
12020 (defun org-shiftup (&optional arg)
12021 "Increase item in timestamp or increase priority of current item.
12022 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12023 See the individual commands for more information."
12024 (interactive "P")
12025 (cond
12026 ((org-at-timestamp-p) (org-timestamp-up arg))
12027 (t (org-priority-up))))
12028
12029 (defun org-shiftdown (&optional arg)
12030 "Decrease item in timestamp or decrease priority of current item.
12031 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12032 See the individual commands for more information."
12033 (interactive "P")
12034 (cond
12035 ((org-at-timestamp-p) (org-timestamp-down arg))
12036 (t (org-priority-down))))
12037
12038 (defun org-shiftright ()
12039 "Next TODO keyword or timestamp one day later, depending on context."
12040 (interactive)
12041 (cond
12042 ((org-at-timestamp-p) (org-timestamp-up-day))
12043 ((org-on-heading-p) (org-todo 'right))
12044 (t (org-shiftcursor-error))))
12045
12046 (defun org-shiftleft ()
12047 "Previous TODO keyword or timestamp one day earlier, depending on context."
12048 (interactive)
12049 (cond
12050 ((org-at-timestamp-p) (org-timestamp-down-day))
12051 ((org-on-heading-p) (org-todo 'left))
12052 (t (org-shiftcursor-error))))
12053
12054 (defun org-copy-special ()
12055 "Copy region in table or copy current subtree.
12056 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12057 See the individual commands for more information."
12058 (interactive)
12059 (call-interactively
12060 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12061
12062 (defun org-cut-special ()
12063 "Cut region in table or cut current subtree.
12064 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12065 See the individual commands for more information."
12066 (interactive)
12067 (call-interactively
12068 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12069
12070 (defun org-paste-special (arg)
12071 "Paste rectangular region into table, or past subtree relative to level.
12072 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12073 See the individual commands for more information."
12074 (interactive "P")
12075 (if (org-at-table-p)
12076 (org-table-paste-rectangle)
12077 (org-paste-subtree arg)))
12078
12079 (defun org-ctrl-c-ctrl-c (&optional arg)
12080 "Call realign table, or recognize a table.el table, or update keywords.
12081 When the cursor is inside a table created by the table.el package,
12082 activate that table. Otherwise, if the cursor is at a normal table
12083 created with org.el, re-align that table. This command works even if
12084 the automatic table editor has been turned off.
12085
12086 If the cursor is in a headline, prompt for tags and insert them into
12087 the current line, aligned to `org-tags-column'. When in a headline and
12088 called with prefix arg, realign all tags in the current buffer.
12089
12090 If the cursor is in one of the special #+KEYWORD lines, this triggers
12091 scanning the buffer for these lines and updating the information.
12092 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
12093 (interactive "P")
12094 (let ((org-enable-table-editor t))
12095 (cond
12096 ((org-on-target-p) (org-update-radio-target-regexp))
12097 ((org-on-heading-p) (org-set-tags arg))
12098 ((org-at-table.el-p)
12099 (require 'table)
12100 (beginning-of-line 1)
12101 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12102 (table-recognize-table))
12103 ((org-at-table-p)
12104 (org-table-maybe-eval-formula)
12105 (if arg
12106 (org-table-recalculate t)
12107 (org-table-maybe-recalculate-line))
12108 (org-table-align))
12109 ((org-at-item-p)
12110 (org-renumber-ordered-list (prefix-numeric-value arg)))
12111 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12112 (cond
12113 ((equal (match-string 1) "TBLFM")
12114 ;; Recalculate the table before this line
12115 (save-excursion
12116 (beginning-of-line 1)
12117 (skip-chars-backward " \r\n\t")
12118 (if (org-at-table-p) (org-table-recalculate t))))
12119 (t
12120 (org-mode-restart))))
12121 ((org-region-active-p)
12122 (org-table-convert-region (region-beginning) (region-end) arg))
12123 ((condition-case nil
12124 (and (region-beginning) (region-end))
12125 (error nil))
12126 (if (y-or-n-p "Convert inactive region to table? ")
12127 (org-table-convert-region (region-beginning) (region-end) arg)
12128 (error "Abort")))
12129 (t (error "C-c C-c can do nothing useful at this location.")))))
12130
12131 (defun org-mode-restart ()
12132 "Restart Org-mode, to scan again for special lines.
12133 Also updates the keyword regular expressions."
12134 (interactive)
12135 (let ((org-inhibit-startup t)) (org-mode))
12136 (message "Org-mode restarted to refresh keyword and special line setup"))
12137
12138 (defun org-return ()
12139 "Goto next table row or insert a newline.
12140 Calls `org-table-next-row' or `newline', depending on context.
12141 See the individual commands for more information."
12142 (interactive)
12143 (cond
12144 ((org-at-table-p)
12145 (org-table-justify-field-maybe)
12146 (org-table-next-row))
12147 (t (newline))))
12148
12149 (defun org-meta-return (&optional arg)
12150 "Insert a new heading or wrap a region in a table.
12151 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12152 See the individual commands for more information."
12153 (interactive "P")
12154 (cond
12155 ((org-at-table-p)
12156 (org-table-wrap-region arg))
12157 (t (org-insert-heading arg))))
12158
12159 ;;; Menu entries
12160
12161 ;; Define the Org-mode menus
12162 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12163 '("Tbl"
12164 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
12165 ["Next Field" org-cycle (org-at-table-p)]
12166 ["Previous Field" org-shifttab (org-at-table-p)]
12167 ["Next Row" org-return (org-at-table-p)]
12168 "--"
12169 ["Blank Field" org-table-blank-field (org-at-table-p)]
12170 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12171 "--"
12172 ("Column"
12173 ["Move Column Left" org-metaleft (org-at-table-p)]
12174 ["Move Column Right" org-metaright (org-at-table-p)]
12175 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12176 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12177 ("Row"
12178 ["Move Row Up" org-metaup (org-at-table-p)]
12179 ["Move Row Down" org-metadown (org-at-table-p)]
12180 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12181 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12182 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12183 "--"
12184 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
12185 ("Rectangle"
12186 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12187 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12188 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12189 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12190 "--"
12191 ("Calculate"
12192 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12193 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12194 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12195 "--"
12196 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12197 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12198 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12199 "--"
12200 ["Sum Column/Rectangle" org-table-sum
12201 (or (org-at-table-p) (org-region-active-p))]
12202 ["Which Column?" org-table-current-column (org-at-table-p)])
12203 ["Debug Formulas"
12204 (setq org-table-formula-debug (not org-table-formula-debug))
12205 :style toggle :selected org-table-formula-debug]
12206 "--"
12207 ["Invisible Vlines" org-table-toggle-vline-visibility
12208 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
12209 "--"
12210 ["Create" org-table-create (and (not (org-at-table-p))
12211 org-enable-table-editor)]
12212 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
12213 ["Import from File" org-table-import (not (org-at-table-p))]
12214 ["Export to File" org-table-export (org-at-table-p)]
12215 "--"
12216 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12217
12218 (easy-menu-define org-org-menu org-mode-map "Org menu"
12219 '("Org"
12220 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
12221 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
12222 ["Sparse Tree" org-occur t]
12223 ["Show All" show-all t]
12224 "--"
12225 ["New Heading" org-insert-heading t]
12226 ("Navigate Headings"
12227 ["Up" outline-up-heading t]
12228 ["Next" outline-next-visible-heading t]
12229 ["Previous" outline-previous-visible-heading t]
12230 ["Next Same Level" outline-forward-same-level t]
12231 ["Previous Same Level" outline-backward-same-level t]
12232 "--"
12233 ["Jump" org-goto t])
12234 ("Edit Structure"
12235 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12236 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12237 "--"
12238 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12239 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12240 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12241 "--"
12242 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12243 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12244 ["Demote Heading" org-metaright (not (org-at-table-p))]
12245 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12246 "--"
12247 ["Archive Subtree" org-archive-subtree t])
12248 "--"
12249 ("TODO Lists"
12250 ["TODO/DONE/-" org-todo t]
12251 ["Show TODO Tree" org-show-todo-tree t]
12252 ["Global TODO list" org-todo-list t]
12253 "--"
12254 ["Set Priority" org-priority t]
12255 ["Priority Up" org-shiftup t]
12256 ["Priority Down" org-shiftdown t])
12257 ("Dates and Scheduling"
12258 ["Timestamp" org-time-stamp t]
12259 ["Timestamp (inactive)" org-time-stamp-inactive t]
12260 ("Change Date"
12261 ["1 Day Later" org-timestamp-up-day t]
12262 ["1 Day Earlier" org-timestamp-down-day t]
12263 ["1 ... Later" org-shiftup t]
12264 ["1 ... Earlier" org-shiftdown t])
12265 ["Compute Time Range" org-evaluate-time-range t]
12266 ["Schedule Item" org-schedule t]
12267 ["Deadline" org-deadline t]
12268 "--"
12269 ["Goto Calendar" org-goto-calendar t]
12270 ["Date from Calendar" org-date-from-calendar t])
12271 "--"
12272 ["Agenda Command" org-agenda t]
12273 ("File List for Agenda")
12274 ("Special views current file"
12275 ["TODO Tree" org-show-todo-tree t]
12276 ["Check Deadlines" org-check-deadlines t]
12277 ["Timeline" org-timeline t]
12278 ["Tags Tree" org-tags-sparse-tree t])
12279 "--"
12280 ("Hyperlinks"
12281 ["Store Link (Global)" org-store-link t]
12282 ["Insert Link" org-insert-link t]
12283 ["Follow Link" org-open-at-point t])
12284 "--"
12285 ("Export"
12286 ["ASCII" org-export-as-ascii t]
12287 ["Extract Visible Text" org-export-copy-visible t]
12288 ["HTML" org-export-as-html t]
12289 ["HTML and Open" org-export-as-html-and-open t]
12290 ; ["OPML" org-export-as-opml nil]
12291 "--"
12292 ["iCalendar this file" org-export-icalendar-this-file t]
12293 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
12294 :active t :keys "C-c C-x C-i"]
12295 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
12296 "--"
12297 ["Option Template" org-insert-export-options-template t]
12298 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
12299 "--"
12300 ("Documentation"
12301 ["Show Version" org-version t]
12302 ["Info Documentation" org-info t])
12303 ("Customize"
12304 ["Browse Org Group" org-customize t]
12305 "--"
12306 ["Build Full Customize Menu" org-create-customize-menu
12307 (fboundp 'customize-menu-create)])
12308 "--"
12309 ["Refresh setup" org-mode-restart t]
12310 ))
12311
12312 (defun org-info (&optional node)
12313 "Read documentation for Org-mode in the info system.
12314 With optional NODE, go directly to that node."
12315 (interactive)
12316 (require 'info)
12317 (Info-goto-node (format "(org)%s" (or node ""))))
12318
12319 (defun org-install-agenda-files-menu ()
12320 (easy-menu-change
12321 '("Org") "File List for Agenda"
12322 (append
12323 (list
12324 ["Edit File List" (customize-variable 'org-agenda-files) t]
12325 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12326 ["Remove Current File from List" org-remove-file t]
12327 ["Cycle through agenda files" org-cycle-agenda-files t]
12328 "--")
12329 (mapcar 'org-file-menu-entry org-agenda-files))))
12330
12331 ;;; Documentation
12332
12333 (defun org-customize ()
12334 "Call the customize function with org as argument."
12335 (interactive)
12336 (customize-browse 'org))
12337
12338 (defun org-create-customize-menu ()
12339 "Create a full customization menu for Org-mode, insert it into the menu."
12340 (interactive)
12341 (if (fboundp 'customize-menu-create)
12342 (progn
12343 (easy-menu-change
12344 '("Org") "Customize"
12345 `(["Browse Org group" org-customize t]
12346 "--"
12347 ,(customize-menu-create 'org)
12348 ["Set" Custom-set t]
12349 ["Save" Custom-save t]
12350 ["Reset to Current" Custom-reset-current t]
12351 ["Reset to Saved" Custom-reset-saved t]
12352 ["Reset to Standard Settings" Custom-reset-standard t]))
12353 (message "\"Org\"-menu now contains full customization menu"))
12354 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12355
12356 ;;; Miscellaneous stuff
12357
12358 (defun org-move-line-down (arg)
12359 "Move the current line down. With prefix argument, move it past ARG lines."
12360 (interactive "p")
12361 (let ((col (current-column))
12362 beg end pos)
12363 (beginning-of-line 1) (setq beg (point))
12364 (beginning-of-line 2) (setq end (point))
12365 (beginning-of-line (+ 1 arg))
12366 (setq pos (move-marker (make-marker) (point)))
12367 (insert (delete-and-extract-region beg end))
12368 (goto-char pos)
12369 (move-to-column col)))
12370
12371 (defun org-move-line-up (arg)
12372 "Move the current line up. With prefix argument, move it past ARG lines."
12373 (interactive "p")
12374 (let ((col (current-column))
12375 beg end pos)
12376 (beginning-of-line 1) (setq beg (point))
12377 (beginning-of-line 2) (setq end (point))
12378 (beginning-of-line (- arg))
12379 (setq pos (move-marker (make-marker) (point)))
12380 (insert (delete-and-extract-region beg end))
12381 (goto-char pos)
12382 (move-to-column col)))
12383
12384 ;; Paragraph filling stuff.
12385 ;; We want this to be just right, so use the full arsenal.
12386 ;; FIXME: This very likely does not work correctly for XEmacs, because the
12387 ;; filladapt package works slightly differently.
12388
12389 (defun org-set-autofill-regexps ()
12390 (interactive)
12391 ;; In the paragraph separator we include headlines, because filling
12392 ;; text in a line directly attached to a headline would otherwise
12393 ;; fill the headline as well.
12394 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
12395 ;; The paragraph starter includes hand-formatted lists.
12396 (set (make-local-variable 'paragraph-start)
12397 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
12398 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
12399 ;; But only if the user has not turned off tables or fixed-width regions
12400 (set (make-local-variable 'auto-fill-inhibit-regexp)
12401 (concat "\\*\\|#"
12402 (if (or org-enable-table-editor org-enable-fixed-width-editor)
12403 (concat
12404 "\\|[ \t]*["
12405 (if org-enable-table-editor "|" "")
12406 (if org-enable-fixed-width-editor ":" "")
12407 "]"))))
12408 ;; We use our own fill-paragraph function, to make sure that tables
12409 ;; and fixed-width regions are not wrapped. That function will pass
12410 ;; through to `fill-paragraph' when appropriate.
12411 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
12412 ;; Adaptive filling: To get full control, first make sure that
12413 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
12414 (setq adaptive-fill-regexp "\000")
12415 (setq adaptive-fill-function 'org-adaptive-fill-function))
12416
12417 (defun org-fill-paragraph (&optional justify)
12418 "Re-align a table, pass through to fill-paragraph if no table."
12419 (let ((table-p (org-at-table-p))
12420 (table.el-p (org-at-table.el-p)))
12421 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
12422 (table.el-p t) ; skip table.el tables
12423 (table-p (org-table-align) t) ; align org-mode tables
12424 (t nil)))) ; call paragraph-fill
12425
12426 ;; For reference, this is the default value of adaptive-fill-regexp
12427 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
12428
12429 (defun org-adaptive-fill-function ()
12430 "Return a fill prefix for org-mode files.
12431 In particular, this makes sure hanging paragraphs for hand-formatted lists
12432 work correctly."
12433 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
12434 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
12435
12436 ;; Functions needed for Emacs/XEmacs region compatibility
12437
12438 (defun org-add-hook (hook function &optional append local)
12439 "Add-hook, compatible with both Emacsen."
12440 (if (and local org-xemacs-p)
12441 (add-local-hook hook function append)
12442 (add-hook hook function append local)))
12443
12444 (defun org-region-active-p ()
12445 "Is `transient-mark-mode' on and the region active?
12446 Works on both Emacs and XEmacs."
12447 (if org-ignore-region
12448 nil
12449 (if org-xemacs-p
12450 (and zmacs-regions (region-active-p))
12451 (and transient-mark-mode mark-active))))
12452
12453 (defun org-add-to-invisibility-spec (arg)
12454 "Add elements to `buffer-invisibility-spec'.
12455 See documentation for `buffer-invisibility-spec' for the kind of elements
12456 that can be added."
12457 (cond
12458 ((fboundp 'add-to-invisibility-spec)
12459 (add-to-invisibility-spec arg))
12460 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
12461 (setq buffer-invisibility-spec (list arg)))
12462 (t
12463 (setq buffer-invisibility-spec
12464 (cons arg buffer-invisibility-spec)))))
12465
12466 (defun org-remove-from-invisibility-spec (arg)
12467 "Remove elements from `buffer-invisibility-spec'."
12468 (if (fboundp 'remove-from-invisibility-spec)
12469 (remove-from-invisibility-spec arg)
12470 (if (consp buffer-invisibility-spec)
12471 (setq buffer-invisibility-spec
12472 (delete arg buffer-invisibility-spec)))))
12473
12474 (defun org-in-invisibility-spec-p (arg)
12475 "Is ARG a member of `buffer-invisibility-spec'?"
12476 (if (consp buffer-invisibility-spec)
12477 (member arg buffer-invisibility-spec)
12478 nil))
12479
12480 (defun org-image-file-name-regexp ()
12481 "Return regexp matching the file names of images."
12482 (if (fboundp 'image-file-name-regexp)
12483 (image-file-name-regexp)
12484 (let ((image-file-name-extensions
12485 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
12486 "xbm" "xpm" "pbm" "pgm" "ppm")))
12487 (concat "\\."
12488 (regexp-opt (nconc (mapcar 'upcase
12489 image-file-name-extensions)
12490 image-file-name-extensions)
12491 t)
12492 "\\'"))))
12493
12494 ;; Functions needed for compatibility with old outline.el.
12495
12496 ;; Programming for the old outline.el (that uses selective display
12497 ;; instead of `invisible' text properties) is a nightmare, mostly
12498 ;; because regular expressions can no longer be anchored at
12499 ;; beginning/end of line. Therefore a number of function need special
12500 ;; treatment when the old outline.el is being used.
12501
12502 ;; The following functions capture almost the entire compatibility code
12503 ;; between the different versions of outline-mode. The only other
12504 ;; places where this is important are the font-lock-keywords, and in
12505 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
12506
12507 ;; C-a should go to the beginning of a *visible* line, also in the
12508 ;; new outline.el. I guess this should be patched into Emacs?
12509 (defun org-beginning-of-line ()
12510 "Go to the beginning of the current line. If that is invisible, continue
12511 to a visible line beginning. This makes the function of C-a more intuitive."
12512 (interactive)
12513 (beginning-of-line 1)
12514 (if (bobp)
12515 nil
12516 (backward-char 1)
12517 (if (org-invisible-p)
12518 (while (and (not (bobp)) (org-invisible-p))
12519 (backward-char 1)
12520 (beginning-of-line 1))
12521 (forward-char 1))))
12522
12523 (when org-noutline-p
12524 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
12525 ;; FIXME: should I use substitute-key-definition to reach other bindings
12526 ;; of beginning-of-line?
12527
12528 (defun org-invisible-p ()
12529 "Check if point is at a character currently not visible."
12530 (if org-noutline-p
12531 ;; Early versions of noutline don't have `outline-invisible-p'.
12532 (if (fboundp 'outline-invisible-p)
12533 (outline-invisible-p)
12534 (get-char-property (point) 'invisible))
12535 (save-excursion
12536 (skip-chars-backward "^\r\n")
12537 (equal (char-before) ?\r))))
12538
12539 (defun org-invisible-p2 ()
12540 "Check if point is at a character currently not visible."
12541 (save-excursion
12542 (if org-noutline-p
12543 (progn
12544 (if (and (eolp) (not (bobp))) (backward-char 1))
12545 ;; Early versions of noutline don't have `outline-invisible-p'.
12546 (if (fboundp 'outline-invisible-p)
12547 (outline-invisible-p)
12548 (get-char-property (point) 'invisible)))
12549 (skip-chars-backward "^\r\n")
12550 (equal (char-before) ?\r))))
12551
12552 (defun org-back-to-heading (&optional invisible-ok)
12553 "Move to previous heading line, or beg of this line if it's a heading.
12554 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
12555 (if org-noutline-p
12556 (outline-back-to-heading invisible-ok)
12557 (if (and (memq (char-before) '(?\n ?\r))
12558 (looking-at outline-regexp))
12559 t
12560 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
12561 outline-regexp)
12562 nil t)
12563 (if invisible-ok
12564 (progn (goto-char (match-end 1))
12565 (looking-at outline-regexp)))
12566 (error "Before first heading")))))
12567
12568 (defun org-on-heading-p (&optional invisible-ok)
12569 "Return t if point is on a (visible) heading line.
12570 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12571 (if org-noutline-p
12572 (outline-on-heading-p 'invisible-ok)
12573 (save-excursion
12574 (skip-chars-backward "^\n\r")
12575 (and (looking-at outline-regexp)
12576 (or invisible-ok
12577 (bobp)
12578 (equal (char-before) ?\n))))))
12579
12580 (defun org-on-target-p ()
12581 (let ((pos (point)))
12582 (save-excursion
12583 (skip-chars-forward "<")
12584 (and (re-search-backward "<<" nil t)
12585 (or (looking-at org-target-regexp)
12586 (looking-at org-radio-target-regexp))
12587 (<= (match-beginning 0) pos)
12588 (>= (match-end 0) pos)))))
12589
12590 (defun org-up-heading-all (arg)
12591 "Move to the heading line of which the present line is a subheading.
12592 This function considers both visible and invisible heading lines.
12593 With argument, move up ARG levels."
12594 (if org-noutline-p
12595 (if (fboundp 'outline-up-heading-all)
12596 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12597 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12598 (org-back-to-heading t)
12599 (looking-at outline-regexp)
12600 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12601 (error "Cannot move up %d levels" arg)
12602 (re-search-backward
12603 (concat "[\n\r]" (regexp-quote
12604 (make-string (- (match-end 0) (match-beginning 0) arg)
12605 ?*))
12606 "[^*]"))
12607 (forward-char 1))))
12608
12609 (defun org-show-hidden-entry ()
12610 "Show an entry where even the heading is hidden."
12611 (save-excursion
12612 (if (not org-noutline-p)
12613 (progn
12614 (org-back-to-heading t)
12615 (org-flag-heading nil)))
12616 (org-show-entry)))
12617
12618 (defun org-check-occur-regexp (regexp)
12619 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12620 Of course, only for the old outline mode."
12621 (if org-noutline-p
12622 regexp
12623 (if (string-match "^\\^" regexp)
12624 (concat "[\n\r]" (substring regexp 1))
12625 regexp)))
12626
12627 (defun org-flag-heading (flag &optional entry)
12628 "Flag the current heading. FLAG non-nil means make invisible.
12629 When ENTRY is non-nil, show the entire entry."
12630 (save-excursion
12631 (org-back-to-heading t)
12632 (if (not org-noutline-p)
12633 ;; Make the current headline visible
12634 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12635 ;; Check if we should show the entire entry
12636 (if entry
12637 (progn
12638 (org-show-entry)
12639 (save-excursion ;; FIXME: Is this the fix for points in the -|
12640 ;; middle of text? |
12641 (and (outline-next-heading) ;; |
12642 (org-flag-heading nil)))) ; show the next heading _|
12643 (outline-flag-region (max 1 (1- (point)))
12644 (save-excursion (outline-end-of-heading) (point))
12645 (if org-noutline-p
12646 flag
12647 (if flag ?\r ?\n))))))
12648
12649 (defun org-end-of-subtree (&optional invisible-OK)
12650 ;; This is an exact copy of the original function, but it uses
12651 ;; `org-back-to-heading', to make it work also in invisible
12652 ;; trees. And is uses an invisible-OK argument.
12653 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
12654 (org-back-to-heading invisible-OK)
12655 (let ((first t)
12656 (level (funcall outline-level)))
12657 (while (and (not (eobp))
12658 (or first (> (funcall outline-level) level)))
12659 (setq first nil)
12660 (outline-next-heading))
12661 (if (memq (preceding-char) '(?\n ?\^M))
12662 (progn
12663 ;; Go to end of line before heading
12664 (forward-char -1)
12665 (if (memq (preceding-char) '(?\n ?\^M))
12666 ;; leave blank line before heading
12667 (forward-char -1))))))
12668
12669 (defun org-show-subtree ()
12670 "Show everything after this heading at deeper levels."
12671 (outline-flag-region
12672 (point)
12673 (save-excursion
12674 (outline-end-of-subtree) (outline-next-heading) (point))
12675 (if org-noutline-p nil ?\n)))
12676
12677 (defun org-show-entry ()
12678 "Show the body directly following this heading.
12679 Show the heading too, if it is currently invisible."
12680 (interactive)
12681 (save-excursion
12682 (org-back-to-heading t)
12683 (outline-flag-region
12684 (1- (point))
12685 (save-excursion
12686 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12687 (or (match-beginning 1) (point-max)))
12688 (if org-noutline-p nil ?\n))))
12689
12690
12691 (defun org-make-options-regexp (kwds)
12692 "Make a regular expression for keyword lines."
12693 (concat
12694 (if org-noutline-p "^" "[\n\r]")
12695 "#?[ \t]*\\+\\("
12696 (mapconcat 'regexp-quote kwds "\\|")
12697 "\\):[ \t]*"
12698 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12699
12700 ;; Make `bookmark-jump' show the jump location if it was hidden.
12701 (eval-after-load "bookmark"
12702 '(if (boundp 'bookmark-after-jump-hook)
12703 ;; We can use the hook
12704 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12705 ;; Hook not available, use advice
12706 (defadvice bookmark-jump (after org-make-visible activate)
12707 "Make the position visible."
12708 (org-bookmark-jump-unhide))))
12709
12710 (defun org-bookmark-jump-unhide ()
12711 "Unhide the current position, to show the bookmark location."
12712 (and (eq major-mode 'org-mode)
12713 (or (org-invisible-p)
12714 (save-excursion (goto-char (max (point-min) (1- (point))))
12715 (org-invisible-p)))
12716 (org-show-hierarchy-above)))
12717
12718 ;;; Finish up
12719
12720 (provide 'org)
12721
12722 (run-hooks 'org-load-hook)
12723
12724 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12725 ;;; org.el ends here
12726