]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-paste-subtree): Removed forgotten (debug)
[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.07
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.07
85 ;; - Bug fixes.
86 ;; - Leading stars in headlines can be hidden, so make the outline look
87 ;; cleaner.
88 ;; - Mouse-1 can be used to follow links.
89 ;;
90 ;; Version 4.06
91 ;; - HTML exporter treats targeted internal links.
92 ;; - Bug fixes.
93 ;;
94 ;; Version 4.05
95 ;; - Changes to internal link system (thanks to David Wainberg for ideas).
96 ;; - in-file links: [[Search String]] instead of <file:::Search String>
97 ;; - automatic links to "radio targets".
98 ;; - CamelCase not longer active by default, configure org-activate-camels
99 ;; if you want to turn it back on.
100 ;; - After following a link, `C-c &' jumps back to it.
101 ;; - MH-E link support (thanks to Thomas Baumann).
102 ;; - Special table lines are no longer exported.
103 ;; - Bug fixes and minor improvements.
104 ;;
105 ;; Version 4.04
106 ;; - Cleanup tags display in agenda.
107 ;; - Bug fixes.
108 ;;
109 ;; Version 4.03
110 ;; - Table alignment fixed for use with wide characters.
111 ;; - `C-c -' leaves cursor in current table line.
112 ;; - The current TAG can be incorporated into the agenda prefix.
113 ;; See option `org-agenda-prefix-format' for details.
114 ;;
115 ;; Version 4.02
116 ;; - Minor bug fixes and improvements around tag searches.
117 ;; - XEmacs compatibility fixes.
118 ;;
119 ;; Version 4.01
120 ;; - Tags can also be set remotely from agenda buffer.
121 ;; - Boolean logic for tag searches.
122 ;; - Additional agenda commands can be configured through the variable
123 ;; `org-agenda-custom-commands'.
124 ;; - Minor bug fixes.
125 ;;
126 ;;; Code:
127
128 (eval-when-compile (require 'cl) (require 'calendar))
129 (require 'outline)
130 (require 'time-date)
131 (require 'easymenu)
132
133 (defvar calc-embedded-close-formula)
134 (defvar calc-embedded-open-formula)
135 (defvar font-lock-unfontify-region-function)
136
137 ;;; Customization variables
138
139 (defvar org-version "4.07"
140 "The version number of the file org.el.")
141 (defun org-version ()
142 (interactive)
143 (message "Org-mode version %s" org-version))
144
145 ;; The following two constants are for compatibility with different Emacs
146 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
147 ;; The compatibility code in org.el is based on these two constants.
148 (defconst org-xemacs-p (featurep 'xemacs)
149 "Are we running XEmacs?")
150 (defconst org-noutline-p (featurep 'noutline)
151 "Are we using the new outline mode?")
152
153 (defgroup org nil
154 "Outline-based notes management and organizer."
155 :tag "Org"
156 :group 'outlines
157 :group 'hypermedia
158 :group 'calendar)
159
160 (defgroup org-startup nil
161 "Options concerning startup of Org-mode."
162 :tag "Org Startup"
163 :group 'org)
164
165 (defcustom org-CUA-compatible nil
166 "Non-nil means use alternative key bindings for S-<cursor movement>.
167 Org-mode used S-<cursor movement> for changing timestamps and priorities.
168 S-<cursor movement> is also used for example by `CUA-mode' to select text.
169 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
170 alternative bindings. Setting this variable to t will replace the following
171 keys both in Org-mode and in the Org-agenda buffer.
172
173 S-RET -> C-S-RET
174 S-up -> M-p
175 S-down -> M-n
176 S-left -> M--
177 S-right -> M-+
178
179 If you do not like the alternative keys, take a look at the variable
180 `org-disputed-keys'.
181
182 This option is only relevant at load-time of Org-mode. Changing it requires
183 a restart of Emacs to become effective."
184 :group 'org-startup
185 :type 'boolean)
186
187 (defvar org-disputed-keys
188 '((S-up [(shift up)] [(meta ?p)])
189 (S-down [(shift down)] [(meta ?n)])
190 (S-left [(shift left)] [(meta ?-)])
191 (S-right [(shift right)] [(meta ?+)])
192 (S-return [(shift return)] [(control shift return)]))
193 "Keys for which Org-mode and other modes compete.
194 This is an alist, cars are symbols for lookup, 1st element is the default key,
195 second element will be used when `org-CUA-compatible' is t.")
196
197 (defun org-key (key)
198 "Select a key according to `org-CUA-compatible'."
199 (nth (if org-CUA-compatible 2 1)
200 (or (assq key org-disputed-keys)
201 (error "Invalid Key %s in `org-key'" key))))
202
203 (defcustom org-startup-folded t
204 "Non-nil means, entering Org-mode will switch to OVERVIEW.
205 This can also be configured on a per-file basis by adding one of
206 the following lines anywhere in the buffer:
207
208 #+STARTUP: fold
209 #+STARTUP: nofold
210 #+STARTUP: content"
211 :group 'org-startup
212 :type '(choice
213 (const :tag "nofold: show all" nil)
214 (const :tag "fold: overview" t)
215 (const :tag "content: all headlines" content)))
216
217 (defcustom org-startup-truncated t
218 "Non-nil means, entering Org-mode will set `truncate-lines'.
219 This is useful since some lines containing links can be very long and
220 uninteresting. Also tables look terrible when wrapped."
221 :group 'org-startup
222 :type 'boolean)
223
224 (defcustom org-startup-with-deadline-check nil
225 "Non-nil means, entering Org-mode will run the deadline check.
226 This means, if you start editing an org file, you will get an
227 immediate reminder of any due deadlines.
228 This can also be configured on a per-file basis by adding one of
229 the following lines anywhere in the buffer:
230
231 #+STARTUP: dlcheck
232 #+STARTUP: nodlcheck"
233 :group 'org-startup
234 :type 'boolean)
235
236 (defcustom org-insert-mode-line-in-empty-file nil
237 "Non-nil means insert the first line setting Org-mode in empty files.
238 When the function `org-mode' is called interactively in an empty file, this
239 normally means that the file name does not automatically trigger Org-mode.
240 To ensure that the file will always be in Org-mode in the future, a
241 line enforcing Org-mode will be inserted into the buffer, if this option
242 has been set."
243 :group 'org-startup
244 :type 'boolean)
245
246 (defgroup org-keywords nil
247 "Options concerning TODO items in Org-mode."
248 :tag "Org Keywords"
249 :group 'org)
250
251 (defcustom org-todo-keywords '("TODO" "DONE")
252 "List of TODO entry keywords.
253 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
254 considered to mean that the entry is \"done\". All the other mean that
255 action is required, and will make the entry show up in todo lists, diaries
256 etc.
257 The command \\[org-todo] cycles an entry through these states, and an
258 additional state where no keyword is present. For details about this
259 cycling, see also the variable `org-todo-interpretation'
260 Changes become only effective after restarting Emacs."
261 :group 'org-keywords
262 :type '(repeat (string :tag "Keyword")))
263
264 (defcustom org-todo-interpretation 'sequence
265 "Controls how TODO keywords are interpreted.
266 \\<org-mode-map>Possible values are `sequence' and `type'.
267 This variable is only relevant if `org-todo-keywords' contains more than two
268 states. There are two ways how these keywords can be used:
269
270 - As a sequence in the process of working on a TODO item, for example
271 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
272 org-todo-interpretation 'sequence)
273
274 - As different types of TODO items, for example
275 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
276 org-todo-interpretation 'type)
277
278 When the states are interpreted as a sequence, \\[org-todo] always cycles
279 to the next state, in order to walk through all different states. So with
280 \\[org-todo], you turn an empty entry into the state TODO. When you started
281 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
282 later to VERIFY and finally to DONE.
283
284 When the states are interpreted as types, \\[org-todo] still cycles through
285 when it is called several times in direct succession, in order to initially
286 select the type. However, if not called immediately after a previous
287 \\[org-todo], it switches from each type directly to DONE. So with the
288 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
289 RELAXED. If you later return to this entry and press \\[org-todo] again,
290 RELAXED will not be changed REMIND, but directly to DONE.
291
292 You can create a large number of types. To initially select a
293 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
294 type with completion. Of course, you can also type the keyword
295 directly into the buffer. M-TAB completes TODO keywords at the
296 beginning of a headline."
297 :group 'org-keywords
298 :type '(choice (const sequence)
299 (const type)))
300
301 (defcustom org-default-priority ?B
302 "The default priority of TODO items.
303 This is the priority an item get if no explicit priority is given."
304 :group 'org-keywords
305 :type 'character)
306
307 (defcustom org-lowest-priority ?C
308 "The lowest priority of TODO items. A character like ?A, ?B etc."
309 :group 'org-keywords
310 :type 'character)
311
312 (defcustom org-deadline-string "DEADLINE:"
313 "String to mark deadline entries.
314 A deadline is this string, followed by a time stamp. Should be a word,
315 terminated by a colon. You can insert a schedule keyword and
316 a timestamp with \\[org-deadline].
317 Changes become only effective after restarting Emacs."
318 :group 'org-keywords
319 :type 'string)
320
321 (defcustom org-scheduled-string "SCHEDULED:"
322 "String to mark scheduled TODO entries.
323 A schedule is this string, followed by a time stamp. Should be a word,
324 terminated by a colon. You can insert a schedule keyword and
325 a timestamp with \\[org-schedule].
326 Changes become only effective after restarting Emacs."
327 :group 'org-keywords
328 :type 'string)
329
330 (defcustom org-closed-string "CLOSED:"
331 "String used as the prefix for timestamps logging closing a TODO entry."
332 :group 'org-keywords
333 :type 'string)
334
335 (defcustom org-comment-string "COMMENT"
336 "Entries starting with this keyword will never be exported.
337 An entry can be toggled between COMMENT and normal with
338 \\[org-toggle-comment].
339 Changes become only effective after restarting Emacs."
340 :group 'org-keywords
341 :type 'string)
342
343 (defcustom org-quote-string "QUOTE"
344 "Entries starting with this keyword will be exported in fixed-width font.
345 Quoting applies only to the text in the entry following the headline, and does
346 not extend beyond the next headline, even if that is lower level.
347 An entry can be toggled between QUOTE and normal with
348 \\[org-toggle-fixed-width-section]."
349 :group 'org-keywords
350 :type 'string)
351
352 (defcustom org-after-todo-state-change-hook nil
353 "Hook which is run after the state of a TODO item was changed.
354 The new state (a string with a TODO keyword, or nil) is available in the
355 Lisp variable `state'."
356 :group 'org-keywords
357 :type 'hook)
358
359 ;; Variables for pre-computed regular expressions, all buffer local
360 (defvar org-todo-kwd-priority-p nil
361 "Do TODO items have priorities?")
362 (make-variable-buffer-local 'org-todo-kwd-priority-p)
363 (defvar org-todo-kwd-max-priority nil
364 "Maximum priority of TODO items.")
365 (make-variable-buffer-local 'org-todo-kwd-max-priority)
366 (defvar org-ds-keyword-length 12
367 "Maximum length of the Deadline and SCHEDULED keywords.")
368 (make-variable-buffer-local 'org-ds-keyword-length)
369 (defvar org-done-string nil
370 "The last string in `org-todo-keywords', indicating an item is DONE.")
371 (make-variable-buffer-local 'org-done-string)
372 (defvar org-todo-regexp nil
373 "Matches any of the TODO state keywords.")
374 (make-variable-buffer-local 'org-todo-regexp)
375 (defvar org-not-done-regexp nil
376 "Matches any of the TODO state keywords except the last one.")
377 (make-variable-buffer-local 'org-not-done-regexp)
378 (defvar org-todo-line-regexp nil
379 "Matches a headline and puts TODO state into group 2 if present.")
380 (make-variable-buffer-local 'org-todo-line-regexp)
381 (defvar org-nl-done-regexp nil
382 "Matches newline followed by a headline with the DONE keyword.")
383 (make-variable-buffer-local 'org-nl-done-regexp)
384 (defvar org-looking-at-done-regexp nil
385 "Matches the DONE keyword a point.")
386 (make-variable-buffer-local 'org-looking-at-done-regexp)
387 (defvar org-deadline-regexp nil
388 "Matches the DEADLINE keyword.")
389 (make-variable-buffer-local 'org-deadline-regexp)
390 (defvar org-deadline-time-regexp nil
391 "Matches the DEADLINE keyword together with a time stamp.")
392 (make-variable-buffer-local 'org-deadline-time-regexp)
393 (defvar org-deadline-line-regexp nil
394 "Matches the DEADLINE keyword and the rest of the line.")
395 (make-variable-buffer-local 'org-deadline-line-regexp)
396 (defvar org-scheduled-regexp nil
397 "Matches the SCHEDULED keyword.")
398 (make-variable-buffer-local 'org-scheduled-regexp)
399 (defvar org-scheduled-time-regexp nil
400 "Matches the SCHEDULED keyword together with a time stamp.")
401 (make-variable-buffer-local 'org-scheduled-time-regexp)
402
403 (defvar org-category nil
404 "Variable used by org files to set a category for agenda display.
405 Such files should use a file variable to set it, for example
406
407 -*- mode: org; org-category: \"ELisp\"
408
409 or contain a special line
410
411 #+CATEGORY: ELisp
412
413 If the file does not specify a category, then file's base name
414 is used instead.")
415 (make-variable-buffer-local 'org-category)
416
417 (defgroup org-time nil
418 "Options concerning time stamps and deadlines in Org-mode."
419 :tag "Org Time"
420 :group 'org)
421
422 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
423 "Formats for `format-time-string' which are used for time stamps.
424 It is not recommended to change this constant.")
425
426
427 (defcustom org-deadline-warning-days 30
428 "No. of days before expiration during which a deadline becomes active.
429 This variable governs the display in the org file."
430 :group 'org-time
431 :type 'number)
432
433 (defcustom org-popup-calendar-for-date-prompt t
434 "Non-nil means, pop up a calendar when prompting for a date.
435 In the calendar, the date can be selected with mouse-1. However, the
436 minibuffer will also be active, and you can simply enter the date as well.
437 When nil, only the minibuffer will be available."
438 :group 'org-time
439 :type 'number)
440
441 (defcustom org-calendar-follow-timestamp-change t
442 "Non-nil means, make the calendar window follow timestamp changes.
443 When a timestamp is modified and the calendar window is visible, it will be
444 moved to the new date."
445 :group 'org-time
446 :type 'boolean)
447
448 (defcustom org-log-done nil
449 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
450 When the state of an entry is changed from nothing to TODO, remove a previous
451 closing date."
452 :group 'org-time
453 :type 'boolean)
454
455 (defgroup org-agenda nil
456 "Options concerning agenda display Org-mode."
457 :tag "Org Agenda"
458 :group 'org)
459
460 (defcustom org-agenda-files nil
461 "A list of org files for agenda/diary display.
462 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
463 \\[org-remove-file]. You can also use customize to edit the list."
464 :group 'org-agenda
465 :type '(repeat file))
466
467 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
468 "Custom commands for the agenda.
469 These commands will be offered on the splash screen displayed by the
470 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
471
472 key The key (a single char as a string) to be associated with the command.
473 type The command type, any of the following symbols:
474 todo Entries with a specific TODO keyword, in all agenda files.
475 tags Tags match in all agenda files.
476 todo-tree Sparse tree of specific TODO keyword in *current* file.
477 tags-tree Sparse tree with all tags matches in *current* file.
478 occur-tree Occur sparse tree for current file.
479 match What to search for:
480 - a single keyword for TODO keyword searches
481 - a tags match expression for tags searches
482 - a regular expression for occur searches"
483 :group 'org-agenda
484 :type '(repeat
485 (list (string :tag "Key")
486 (choice :tag "Type"
487 (const :tag "Tags search in all agenda files" tags)
488 (const :tag "TODO keyword search in all agenda files" todo)
489 (const :tag "Tags sparse tree in current buffer" tags-tree)
490 (const :tag "TODO keyword tree in current buffer" todo-tree)
491 (const :tag "Occur tree in current buffer" occur-tree))
492 (string :tag "Match"))))
493
494 (defcustom org-select-timeline-window t
495 "Non-nil means, after creating a timeline, move cursor into Timeline window.
496 When nil, cursor will remain in the current window."
497 :group 'org-agenda
498 :type 'boolean)
499
500 (defcustom org-select-agenda-window t
501 "Non-nil means, after creating an agenda, move cursor into Agenda window.
502 When nil, cursor will remain in the current window."
503 :group 'org-agenda
504 :type 'boolean)
505
506 (defcustom org-fit-agenda-window t
507 "Non-nil means, change window size of agenda to fit content."
508 :group 'org-agenda
509 :type 'boolean)
510
511 (defcustom org-agenda-show-all-dates t
512 "Non-nil means, `org-agenda' shows every day in the selected range.
513 When nil, only the days which actually have entries are shown."
514 :group 'org-agenda
515 :type 'boolean)
516
517 ;; FIXME: First day of month works only for current month because it would
518 ;; require a variable ndays treatment.
519 (defcustom org-agenda-start-on-weekday 1
520 "Non-nil means, start the overview always on the specified weekday.
521 0 Denotes Sunday, 1 denotes Monday etc.
522 When nil, always start on the current day."
523 :group 'org-agenda
524 :type '(choice (const :tag "Today" nil)
525 (const :tag "First day of month" t)
526 (number :tag "Weekday No.")))
527
528 (defcustom org-agenda-ndays 7
529 "Number of days to include in overview display."
530 :group 'org-agenda
531 :type 'number)
532
533 (defcustom org-agenda-include-all-todo t
534 "Non-nil means, the agenda will always contain all TODO entries.
535 When nil, date-less entries will only be shown if `org-agenda' is called
536 with a prefix argument.
537 When non-nil, the TODO entries will be listed at the top of the agenda, before
538 the entries for specific days."
539 :group 'org-agenda
540 :type 'boolean)
541
542 (defcustom org-agenda-include-diary nil
543 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
544 :group 'org-agenda
545 :type 'boolean)
546
547 (defcustom org-calendar-to-agenda-key [?c]
548 "The key to be installed in `calendar-mode-map' for switching to the agenda.
549 The command `org-calendar-goto-agenda' will be bound to this key. The
550 default is the character `c' because then `c' can be used to switch back and
551 forth between agenda and calendar."
552 :group 'org-agenda
553 :type 'sexp)
554
555 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
556 "Sorting structure for the agenda items of a single day.
557 This is a list of symbols which will be used in sequence to determine
558 if an entry should be listed before another entry. The following
559 symbols are recognized:
560
561 time-up Put entries with time-of-day indications first, early first
562 time-down Put entries with time-of-day indications first, late first
563 category-keep Keep the default order of categories, corresponding to the
564 sequence in `org-agenda-files'.
565 category-up Sort alphabetically by category, A-Z.
566 category-down Sort alphabetically by category, Z-A.
567 priority-up Sort numerically by priority, high priority last.
568 priority-down Sort numerically by priority, high priority first.
569
570 The different possibilities will be tried in sequence, and testing stops
571 if one comparison returns a \"not-equal\". For example, the default
572 '(time-up category-keep priority-down)
573 means: Pull out all entries having a specified time of day and sort them,
574 in order to make a time schedule for the current day the first thing in the
575 agenda listing for the day. Of the entries without a time indication, keep
576 the grouped in categories, don't sort the categories, but keep them in
577 the sequence given in `org-agenda-files'. Within each category sort by
578 priority.
579
580 Leaving out `category-keep' would mean that items will be sorted across
581 categories by priority."
582 :group 'org-agenda
583 :type '(repeat
584 (choice
585 (const time-up)
586 (const time-down)
587 (const category-keep)
588 (const category-up)
589 (const category-down)
590 (const priority-up)
591 (const priority-down))))
592
593 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
594 "Format specification for the prefix of items in the agenda buffer.
595 This format works similar to a printf format, with the following meaning:
596
597 %c the category of the item, \"Diary\" for entries from the diary, or
598 as given by the CATEGORY keyword or derived from the file name.
599 %T the first tag of the item.
600 %t the time-of-day specification if one applies to the entry, in the
601 format HH:MM
602 %s Scheduling/Deadline information, a short string
603
604 All specifiers work basically like the standard `%s' of printf, but may
605 contain two additional characters: A question mark just after the `%' and
606 a whitespace/punctuation character just before the final letter.
607
608 If the first character after `%' is a question mark, the entire field
609 will only be included if the corresponding value applies to the
610 current entry. This is useful for fields which should have fixed
611 width when present, but zero width when absent. For example,
612 \"%?-12t\" will result in a 12 character time field if a time of the
613 day is specified, but will completely disappear in entries which do
614 not contain a time.
615
616 If there is punctuation or whitespace character just before the final
617 format letter, this character will be appended to the field value if
618 the value is not empty. For example, the format \"%-12:c\" leads to
619 \"Diary: \" if the category is \"Diary\". If the category were be
620 empty, no additional colon would be interted.
621
622 The default value of this option is \" %-12:c%?-12t% s\", meaning:
623 - Indent the line with two space characters
624 - Give the category in a 12 chars wide field, padded with whitespace on
625 the right (because of `-'). Append a colon if there is a category
626 (because of `:').
627 - If there is a time-of-day, put it into a 12 chars wide field. If no
628 time, don't put in an empty field, just skip it (because of '?').
629 - Finally, put the scheduling information and append a whitespace.
630
631 As another example, if you don't want the time-of-day of entries in
632 the prefix, you could use:
633
634 (setq org-agenda-prefix-format \" %-11:c% s\")
635
636 See also the variables `org-agenda-remove-times-when-in-prefix' and
637 `org-agenda-remove-tags-when-in-prefix'."
638 :type 'string
639 :group 'org-agenda)
640
641 (defcustom org-timeline-prefix-format " % s"
642 "Like `org-agenda-prefix-format', but for the timeline of a single file."
643 :type 'string
644 :group 'org-agenda)
645
646 (defvar org-prefix-format-compiled nil
647 "The compiled version of the most recently used prefix format.
648 Depending on which command was used last, this may be the compiled version
649 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
650
651 (defcustom org-agenda-use-time-grid t
652 "Non-nil means, show a time grid in the agenda schedule.
653 A time grid is a set of lines for specific times (like every two hours between
654 8:00 and 20:00). The items scheduled for a day at specific times are
655 sorted in between these lines.
656 For details about when the grid will be shown, and what it will look like, see
657 the variable `org-agenda-time-grid'."
658 :group 'org-agenda
659 :type 'boolean)
660
661 (defcustom org-agenda-time-grid
662 '((daily today require-timed)
663 "----------------"
664 (800 1000 1200 1400 1600 1800 2000))
665
666 "The settings for time grid for agenda display.
667 This is a list of three items. The first item is again a list. It contains
668 symbols specifying conditions when the grid should be displayed:
669
670 daily if the agenda shows a single day
671 weekly if the agenda shows an entire week
672 today show grid on current date, independent of daily/weekly display
673 require-timed show grid only if at least on item has a time specification
674
675 The second item is a string which will be places behing the grid time.
676
677 The third item is a list of integers, indicating the times that should have
678 a grid line."
679 :group 'org-agenda
680 :type
681 '(list
682 (set :greedy t :tag "Grid Display Options"
683 (const :tag "Show grid in single day agenda display" daily)
684 (const :tag "Show grid in weekly agenda display" weekly)
685 (const :tag "Always show grid for today" today)
686 (const :tag "Show grid only if any timed entries are present"
687 require-timed)
688 (const :tag "Skip grid times already present in an entry"
689 remove-match))
690 (string :tag "Grid String")
691 (repeat :tag "Grid Times" (integer :tag "Time"))))
692
693 (defcustom org-agenda-remove-times-when-in-prefix t
694 "Non-nil means, remove duplicate time specifications in agenda items.
695 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
696 time-of-day specification in a headline or diary entry is extracted and
697 placed into the prefix. If this option is non-nil, the original specification
698 \(a timestamp or -range, or just a plain time(range) specification like
699 11:30-4pm) will be removed for agenda display. This makes the agenda less
700 cluttered.
701 The option can be t or nil. It may also be the symbol `beg', indicating
702 that the time should only be removed what it is located at the beginning of
703 the headline/diary entry."
704 :group 'org-agenda
705 :type '(choice
706 (const :tag "Always" t)
707 (const :tag "Never" nil)
708 (const :tag "When at beginning of entry" beg)))
709
710 (defcustom org-sort-agenda-notime-is-late t
711 "Non-nil means, items without time are considered late.
712 This is only relevant for sorting. When t, items which have no explicit
713 time like 15:30 will be considered as 24:01, i.e. later than any items which
714 do have a time. When nil, the default time is before 0:00. You can use this
715 option to decide if the schedule for today should come before or after timeless
716 agenda entries."
717 :group 'org-agenda
718 :type 'boolean)
719
720 (defcustom org-agenda-remove-tags-when-in-prefix nil
721 "Non-nil means, the tags from copy of headline in agenda.
722 When this is the symbol `prefix', only remove tags when
723 `org-agenda-prefix-format' contains a `%T' specifier."
724 :group 'org-agenda
725 :type '(choice
726 (const :tag "Always" t)
727 (const :tag "Never" nil)
728 (const :tag "When prefix format contains %T" prefix)))
729
730 (defgroup org-structure nil
731 "Options concerning structure editing in Org-mode."
732 :tag "Org Structure"
733 :group 'org)
734
735 (defcustom org-cycle-include-plain-lists nil
736 "Non-nil means, include plain lists into visibility cycling.
737 This means that during cycling, plain list items will *temporarily* be
738 interpreted as outline headlines with a level given by 1000+i where i is the
739 indentation of the bullet. In all other operations, plain list items are
740 not seen as headlines. For example, you cannot assign a TODO keyword to
741 such an item."
742 :group 'org-structure
743 :type 'boolean)
744
745 (defcustom org-cycle-emulate-tab t
746 "Where should `org-cycle' emulate TAB.
747 nil Never
748 white Only in completely white lines
749 t Everywhere except in headlines"
750 :group 'org-structure
751 :type '(choice (const :tag "Never" nil)
752 (const :tag "Only in completely white lines" white)
753 (const :tag "Everywhere except in headlines" t)
754 ))
755
756 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
757 "Hook that is run after `org-cycle' has changed the buffer visibility.
758 The function(s) in this hook must accept a single argument which indicates
759 the new state that was set by the most recent `org-cycle' command. The
760 argument is a symbol. After a global state change, it can have the values
761 `overview', `content', or `all'. After a local state change, it can have
762 the values `folded', `children', or `subtree'."
763 :group 'org-structure
764 :type 'hook)
765
766 (defcustom org-highlight-sparse-tree-matches t
767 "Non-nil means, highlight all matches that define a sparse tree.
768 The highlights will automatically disappear the next time the buffer is
769 changed by an edit command."
770 :group 'org-structure
771 :type 'boolean)
772
773 (defcustom org-show-hierarchy-above t
774 "Non-nil means, show full hierarchy when showing a spot in the tree.
775 Turning this off makes sparse trees more compact, but also less clear."
776 :group 'org-structure
777 :type 'boolean)
778
779 (defcustom org-show-following-heading t
780 "Non-nil means, show heading following match in `org-occur'.
781 When doing an `org-occur' it is useful to show the headline which
782 follows the match, even if they do not match the regexp. This makes it
783 easier to edit directly inside the sparse tree. However, if you use
784 `org-occur' mainly as an overview, the following headlines are
785 unnecessary clutter."
786 :group 'org-structure
787 :type 'boolean)
788
789 (defcustom org-occur-hook '(org-first-headline-recenter)
790 "Hook that is run after `org-occur' has constructed a sparse tree.
791 This can be used to recenter the window to show as much of the structure
792 as possible."
793 :group 'org-structure
794 :type 'hook)
795
796 (defcustom org-level-color-stars-only nil
797 "Non-nil means fontify only the stars in each headline.
798 When nil, the entire headline is fontified.
799 Changing it requires restart of Emacs to become effective."
800 :group 'org-structure
801 :type 'boolean)
802
803 (defcustom org-hide-leading-stars nil
804 "Non-nil means, hide the first N-1 stars in a headline.
805 This works by using the face `org-hide' for these stars. This
806 face is white for a light background, and black for a dark
807 background. You may have to customize the face `org-hide' to
808 make this work.
809 Changing the variable requires restart of Emacs to become effective."
810 :group 'org-structure
811 :type 'boolean)
812
813 (defcustom org-odd-levels-only nil
814 "Non-nil means, skip even levels and only use odd levels for the outline.
815 This has the effect that two stars are being added/taken away in
816 promotion/demotion commands. It also influences how levels are
817 handled by the exporters."
818 :group 'org-structure
819 :type 'boolean)
820
821 (defcustom org-adapt-indentation t
822 "Non-nil means, adapt indentation when promoting and demoting.
823 When this is set and the *entire* text in an entry is indented, the
824 indentation is increased by one space in a demotion command, and
825 decreased by one in a promotion command. If any line in the entry
826 body starts at column 0, indentation is not changed at all."
827 :group 'org-structure
828 :type 'boolean)
829
830 (defcustom org-plain-list-ordered-item-terminator t
831 "The character that makes a line with leading number an ordered list item.
832 Valid values are ?. and ?\). To get both terminators, use t. While
833 ?. may look nicer, it creates the danger that a line with leading
834 number may be incorrectly interpreted as an item. ?\) therefore is
835 the safe choice."
836 :group 'org-structure
837 :type '(choice (const :tag "dot like in \"2.\"" ?.)
838 (const :tag "paren like in \"2)\"" ?\))
839 (const :tab "both" t)))
840
841 (defcustom org-auto-renumber-ordered-lists t
842 "Non-nil means, automatically renumber ordered plain lists.
843 Renumbering happens when the sequence have been changed with
844 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
845 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
846 :group 'org-structure
847 :type 'boolean)
848
849 (defcustom org-enable-fixed-width-editor t
850 "Non-nil means, lines starting with \":\" are treated as fixed-width.
851 This currently only means, they are never auto-wrapped.
852 When nil, such lines will be treated like ordinary lines.
853 See also the QUOTE keyword."
854 :group 'org-structure
855 :type 'boolean)
856
857 (defcustom org-archive-location "%s_archive::"
858 "The location where subtrees should be archived.
859 This string consists of two parts, separated by a double-colon.
860
861 The first part is a file name - when omitted, archiving happens in the same
862 file. %s will be replaced by the current file name (without directory part).
863 Archiving to a different file is useful to keep archived entries from
864 contributing to the Org-mode Agenda.
865
866 The part after the double colon is a headline. The archived entries will be
867 filed under that headline. When omitted, the subtrees are simply filed away
868 at the end of the file, as top-level entries.
869
870 Here are a few examples:
871 \"%s_archive::\"
872 If the current file is Projects.org, archive in file
873 Projects.org_archive, as top-level trees. This is the default.
874
875 \"::* Archived Tasks\"
876 Archive in the current file, under the top-level headline
877 \"* Archived Tasks\".
878
879 \"~/org/archive.org::\"
880 Archive in file ~/org/archive.org (absolute path), as top-level trees.
881
882 \"basement::** Finished Tasks\"
883 Archive in file ./basement (relative path), as level 3 trees
884 below the level 2 heading \"** Finished Tasks\".
885
886 You may set this option on a per-file basis by adding to the buffer a
887 line like
888
889 #+ARCHIVE: basement::** Finished Tasks"
890 :group 'org-structure
891 :type 'string)
892
893 (defcustom org-archive-mark-done t
894 "Non-nil means, mark archived entries as DONE."
895 :group 'org-structure
896 :type 'boolean)
897
898 (defcustom org-archive-stamp-time t
899 "Non-nil means, add a time stamp to archived entries.
900 The time stamp will be added directly after the TODO state keyword in the
901 first line, so it is probably best to use this in combinations with
902 `org-archive-mark-done'."
903 :group 'org-structure
904 :type 'boolean)
905
906 (defgroup org-tags nil
907 "Options concerning startup of Org-mode."
908 :tag "Org Tags"
909 :group 'org)
910
911 (defcustom org-tags-column 48
912 "The column to which tags should be indented in a headline.
913 If this number is positive, it specifies the column. If it is negative,
914 it means that the tags should be flushright to that column. For example,
915 -79 works well for a normal 80 character screen."
916 :group 'org-tags
917 :type 'integer)
918
919 (defcustom org-auto-align-tags t
920 "Non-nil means, realign tags after pro/demotion of TODO state change.
921 These operations change the length of a headline and therefore shift
922 the tags around. With this options turned on, after each such operation
923 the tags are again aligned to `org-tags-column'."
924 :group 'org-tags
925 :type 'boolean)
926
927 (defcustom org-use-tag-inheritance t
928 "Non-nil means, tags in levels apply also for sublevels.
929 When nil, only the tags directly given in a specific line apply there.
930 If you turn off this option, you very likely want to turn on the
931 companion option `org-tags-match-list-sublevels'."
932 :group 'org-tags
933 :type 'boolean)
934
935 (defcustom org-tags-match-list-sublevels nil
936 "Non-nil means list also sublevels of headlines matching tag search.
937 Because of tag inheritance (see variable `org-use-tag-inheritance'),
938 the sublevels of a headline matching a tag search often also match
939 the same search. Listing all of them can create very long lists.
940 Setting this variable to nil causes subtrees to be skipped.
941 This option is off by default, because inheritance in on. If you turn
942 inheritance off, you very likely want to turn this option on.
943
944 As a special case, if the tag search is restricted to TODO items, the
945 value of this variable is ignored and sublevels are always checked, to
946 make sure all corresponding TODO items find their way into the list."
947 :group 'org-tags
948 :type 'boolean)
949
950 (defvar org-tags-history nil
951 "History of minibuffer reads for tags.")
952 (defvar org-last-tags-completion-table nil
953 "The last used completion table for tags.")
954
955 (defgroup org-link nil
956 "Options concerning links in Org-mode."
957 :tag "Org Link"
958 :group 'org)
959
960 (defcustom org-tab-follows-link nil
961 "Non-nil means, on links TAB will follow the link.
962 Needs to be set before org.el is loaded."
963 :group 'org-link
964 :type 'boolean)
965
966 (defcustom org-return-follows-link nil
967 "Non-nil means, on links RET will follow the link.
968 Needs to be set before org.el is loaded."
969 :group 'org-link
970 :type 'boolean)
971
972 (defcustom org-mark-ring-length 4
973 "Number of different positions to be recorded in the ring
974 Changing this requires a restart of Emacs to work correctly."
975 :group 'org-link
976 :type 'interger)
977
978 (defcustom org-link-format "<%s>"
979 "Default format for linkes in the buffer.
980 This is a format string for printf, %s will be replaced by the link text.
981 If you want to make sure that your link is always properly terminated,
982 include angle brackets into this format, like \"<%s>\". Some people also
983 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
984 :group 'org-link
985 :type '(choice
986 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
987 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
988 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
989 (string :tag "Other" :value "<%s>")))
990
991 (defcustom org-allow-space-in-links t
992 "Non-nil means, file names in links may contain space characters.
993 When nil, it becomes possible to put several links into a line.
994 Note that in tables, a link never extends accross fields, so in a table
995 it is always possible to put several links into a line.
996 Changing this variable requires a restart of Emacs of become effective."
997 :group 'org-link
998 :type 'boolean)
999
1000 (defcustom org-radio-targets t
1001 "Non-nil means activate text matching a link target.
1002 Radio targets are strings in triple angular brackets, like <<<My Target>>>.
1003 When this option is set, any occurrence of \"my target\" in normal text
1004 becomes a link."
1005 :group 'org-link
1006 :type 'boolean)
1007
1008 (defcustom org-activate-camels nil
1009 "Non-nil means, treat words in CamelCase as in-file links.
1010 Changing this requires restart of Emacs to become effective."
1011 :group 'org-link
1012 :type 'boolean)
1013
1014 (defcustom org-context-in-file-links t
1015 "Non-nil means, file links from `org-store-link' contain context.
1016 A search string will be added to the file name with :: as separator and
1017 used to find the context when the link is activated by the command
1018 `org-open-at-point'.
1019 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1020 negates this setting for the duration of the command."
1021 :group 'org-link
1022 :type 'boolean)
1023
1024 (defcustom org-file-link-context-use-camel-case nil
1025 "Non-nil means, use CamelCase to store a search context in a file link.
1026 When nil, the search string simply consists of the words of the string."
1027 :group 'org-link
1028 :type 'boolean)
1029
1030 (defcustom org-keep-stored-link-after-insertion nil
1031 "Non-nil means, keep link in list for entire session.
1032
1033 The command `org-store-link' adds a link pointing to the current
1034 location to an internal list. These links accumulate during a session.
1035 The command `org-insert-link' can be used to insert links into any
1036 Org-mode file (offering completion for all stored links). When this
1037 option is nil, every link which has been inserted once using \\[org-insert-link]
1038 will be removed from the list, to make completing the unused links
1039 more efficient."
1040 :group 'org-link
1041 :type 'boolean)
1042
1043 (defcustom org-link-frame-setup
1044 '((vm . vm-visit-folder-other-frame)
1045 (gnus . gnus-other-frame)
1046 (file . find-file-other-window))
1047 "Setup the frame configuration for following links.
1048 When following a link with Emacs, it may often be useful to display
1049 this link in another window or frame. This variable can be used to
1050 set this up for the different types of links.
1051 For VM, use any of
1052 `vm-visit-folder'
1053 `vm-visit-folder-other-frame'
1054 For Gnus, use any of
1055 `gnus'
1056 `gnus-other-frame'
1057 For FILE, use any of
1058 `find-file'
1059 `find-file-other-window'
1060 `find-file-other-frame'
1061 For the calendar, use the variable `calendar-setup'.
1062 For BBDB, it is currently only possible to display the matches in
1063 another window."
1064 :group 'org-link
1065 :type '(list
1066 (cons (const vm)
1067 (choice
1068 (const vm-visit-folder)
1069 (const vm-visit-folder-other-window)
1070 (const vm-visit-folder-other-frame)))
1071 (cons (const gnus)
1072 (choice
1073 (const gnus)
1074 (const gnus-other-frame)))
1075 (cons (const file)
1076 (choice
1077 (const find-file)
1078 (const find-file-other-window)
1079 (const find-file-other-frame)))))
1080
1081 (defcustom org-usenet-links-prefer-google nil
1082 "Non-nil means, `org-store-link' will create web links to Google groups.
1083 When nil, Gnus will be used for such links.
1084 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1085 negates this setting for the duration of the command."
1086 :group 'org-link
1087 :type 'boolean)
1088
1089 (defcustom org-open-non-existing-files nil
1090 "Non-nil means, `org-open-file' will open non-existing file.
1091 When nil, an error will be generated."
1092 :group 'org-link
1093 :type 'boolean)
1094
1095 (defcustom org-confirm-shell-links t
1096 "Non-nil means, ask for confirmation before executing shell links.
1097 The default is true, to keep new users from shooting into their own foot."
1098 :group 'org-link
1099 :type 'boolean)
1100
1101 (defconst org-file-apps-defaults-gnu
1102 '((t . mailcap))
1103 "Default file applications on a UNIX or GNU/Linux system.
1104 See `org-file-apps'.")
1105
1106 (defconst org-file-apps-defaults-macosx
1107 '((t . "open %s")
1108 ("ps" . "gv %s")
1109 ("ps.gz" . "gv %s")
1110 ("eps" . "gv %s")
1111 ("eps.gz" . "gv %s")
1112 ("dvi" . "xdvi %s")
1113 ("fig" . "xfig %s"))
1114 "Default file applications on a MacOS X system.
1115 The system \"open\" is known as a default, but we use X11 applications
1116 for some files for which the OS does not have a good default.
1117 See `org-file-apps'.")
1118
1119 (defconst org-file-apps-defaults-windowsnt
1120 '((t . (w32-shell-execute "open" file)))
1121 "Default file applications on a Windows NT system.
1122 The system \"open\" is used for most files.
1123 See `org-file-apps'.")
1124
1125 (defcustom org-file-apps
1126 '(
1127 ("txt" . emacs)
1128 ("tex" . emacs)
1129 ("ltx" . emacs)
1130 ("org" . emacs)
1131 ("el" . emacs)
1132 )
1133 "External applications for opening `file:path' items in a document.
1134 Org-mode uses system defaults for different file types, but
1135 you can use this variable to set the application for a given file
1136 extension. The entries in this list are cons cells with a file extension
1137 and the corresponding command. Possible values for the command are:
1138 `emacs' The file will be visited by the current Emacs process.
1139 `default' Use the default application for this file type.
1140 string A command to be executed by a shell; %s will be replaced
1141 by the path to the file.
1142 sexp A Lisp form which will be evaluated. The file path will
1143 be available in the Lisp variable `file'.
1144 For more examples, see the system specific constants
1145 `org-file-apps-defaults-macosx'
1146 `org-file-apps-defaults-windowsnt'
1147 `org-file-apps-defaults-gnu'."
1148 :group 'org-link
1149 :type '(repeat
1150 (cons (choice :value ""
1151 (string :tag "Extension")
1152 (const :tag "Default for unrecognized files" t)
1153 (const :tag "Links to a directory" directory))
1154 (choice :value ""
1155 (const :tag "Visit with Emacs" emacs)
1156 (const :tag "Use system default" default)
1157 (string :tag "Command")
1158 (sexp :tag "Lisp form")))))
1159
1160 (defgroup org-remember nil
1161 "Options concerning interaction with remember.el."
1162 :tag "Org Remember"
1163 :group 'org)
1164
1165 (defcustom org-directory "~/org"
1166 "Directory with org files.
1167 This directory will be used as default to prompt for org files.
1168 Used by the hooks for remember.el."
1169 :group 'org-remember
1170 :type 'directory)
1171
1172 (defcustom org-default-notes-file "~/.notes"
1173 "Default target for storing notes.
1174 Used by the hooks for remember.el. This can be a string, or nil to mean
1175 the value of `remember-data-file'."
1176 :group 'org-remember
1177 :type '(choice
1178 (const :tag "Default from remember-data-file" nil)
1179 file))
1180
1181 (defcustom org-reverse-note-order nil
1182 "Non-nil means, store new notes at the beginning of a file or entry.
1183 When nil, new notes will be filed to the end of a file or entry."
1184 :group 'org-remember
1185 :type '(choice
1186 (const :tag "Reverse always" t)
1187 (const :tag "Reverse never" nil)
1188 (repeat :tag "By file name regexp"
1189 (cons regexp boolean))))
1190
1191 (defgroup org-table nil
1192 "Options concerning tables in Org-mode."
1193 :tag "Org Table"
1194 :group 'org)
1195
1196 (defcustom org-enable-table-editor 'optimized
1197 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1198 When nil, such lines will be treated like ordinary lines.
1199
1200 When equal to the symbol `optimized', the table editor will be optimized to
1201 do the following:
1202 - Use automatic overwrite mode in front of whitespace in table fields.
1203 This make the structure of the table stay in tact as long as the edited
1204 field does not exceed the column width.
1205 - Minimize the number of realigns. Normally, the table is aligned each time
1206 TAB or RET are pressed to move to another field. With optimization this
1207 happens only if changes to a field might have changed the column width.
1208 Optimization requires replacing the functions `self-insert-command',
1209 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1210 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1211 very good at guessing when a re-align will be necessary, but you can always
1212 force one with \\[org-ctrl-c-ctrl-c].
1213
1214 If you would like to use the optimized version in Org-mode, but the
1215 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1216
1217 This variable can be used to turn on and off the table editor during a session,
1218 but in order to toggle optimization, a restart is required.
1219
1220 See also the variable `org-table-auto-blank-field'."
1221 :group 'org-table
1222 :type '(choice
1223 (const :tag "off" nil)
1224 (const :tag "on" t)
1225 (const :tag "on, optimized" optimized)))
1226
1227 ;; FIXME: We could have a third option which makes it jump only over the first
1228 ;; hline in a table.
1229 (defcustom org-table-tab-jumps-over-hlines t
1230 "Non-nil means, tab in the last column of a table with jump over a hline.
1231 If a horizontal separator line is following the current line,
1232 `org-table-next-field' can either create a new row before that line, or jump
1233 over the line. When this option is nil, a new line will be created before
1234 this line."
1235 :group 'org-table
1236 :type 'boolean)
1237
1238 (defcustom org-table-auto-blank-field t
1239 "Non-nil means, automatically blank table field when starting to type into it.
1240 This only happens when typing immediately after a field motion
1241 command (TAB, S-TAB or RET).
1242 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1243 :group 'org-table
1244 :type 'boolean)
1245
1246 (defcustom org-table-default-size "5x2"
1247 "The default size for newly created tables, Columns x Rows."
1248 :group 'org-table
1249 :type 'string)
1250
1251 (defcustom org-table-automatic-realign t
1252 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1253 When nil, aligning is only done with \\[org-table-align], or after column
1254 removal/insertion."
1255 :group 'org-table
1256 :type 'boolean)
1257
1258 (defcustom org-table-spaces-around-separators '(1 . 1)
1259 "The number of spaces to be placed before and after separators."
1260 :group 'org-table
1261 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1262
1263 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1264 "The number of spaces to be placed before and after separators.
1265 This option applies when the column separators have been made invisible."
1266 :group 'org-table
1267 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1268
1269 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1270 "Regular expression for recognizing numbers in table columns.
1271 If a table column contains mostly numbers, it will be aligned to the
1272 right. If not, it will be aligned to the left.
1273
1274 The default value of this option is a regular expression which allows
1275 anything which looks remotely like a number as used in scientific
1276 context. For example, all of the following will be considered a
1277 number:
1278 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1279
1280 Other options offered by the customize interface are more restrictive."
1281 :group 'org-table
1282 :type '(choice
1283 (const :tag "Positive Integers"
1284 "^[0-9]+$")
1285 (const :tag "Integers"
1286 "^[-+]?[0-9]+$")
1287 (const :tag "Floating Point Numbers"
1288 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1289 (const :tag "Floating Point Number or Integer"
1290 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1291 (const :tag "Exponential, Floating point, Integer"
1292 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1293 (const :tag "Very General Number-Like"
1294 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1295 (string :tag "Regexp:")))
1296
1297 (defcustom org-table-number-fraction 0.5
1298 "Fraction of numbers in a column required to make the column align right.
1299 In a column all non-white fields are considered. If at least this
1300 fraction of fields is matched by `org-table-number-fraction',
1301 alignment to the right border applies."
1302 :group 'org-table
1303 :type 'number)
1304
1305 (defcustom org-export-highlight-first-table-line t
1306 "Non-nil means, highlight the first table line.
1307 In HTML export, this means use <th> instead of <td>.
1308 In tables created with table.el, this applies to the first table line.
1309 In Org-mode tables, all lines before the first horizontal separator
1310 line will be formatted with <th> tags."
1311 :group 'org-table
1312 :type 'boolean)
1313
1314 (defcustom org-table-tab-recognizes-table.el t
1315 "Non-nil means, TAB will automatically notice a table.el table.
1316 When it sees such a table, it moves point into it and - if necessary -
1317 calls `table-recognize-table'."
1318 :group 'org-table
1319 :type 'boolean)
1320
1321 (defgroup org-table-calculation nil
1322 "Options concerning tables in Org-mode."
1323 :tag "Org Table Calculation"
1324 :group 'org)
1325
1326 (defcustom org-table-copy-increment t
1327 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1328 :group 'org-table-calculation
1329 :type 'boolean)
1330
1331 (defcustom org-calc-default-modes
1332 '(calc-internal-prec 12
1333 calc-float-format (float 5)
1334 calc-angle-mode deg
1335 calc-prefer-frac nil
1336 calc-symbolic-mode nil
1337 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1338 calc-display-working-message t
1339 )
1340 "List with Calc mode settings for use in calc-eval for table formulas.
1341 The list must contain alternating symbols (Calc modes variables and values).
1342 Don't remove any of the default settings, just change the values. Org-mode
1343 relies on the variables to be present in the list."
1344 :group 'org-table-calculation
1345 :type 'plist)
1346
1347 (defcustom org-table-formula-evaluate-inline t
1348 "Non-nil means, TAB and RET evaluate a formula in current table field.
1349 If the current field starts with an equal sign, it is assumed to be a formula
1350 which should be evaluated as described in the manual and in the documentation
1351 string of the command `org-table-eval-formula'. This feature requires the
1352 Emacs calc package.
1353 When this variable is nil, formula calculation is only available through
1354 the command \\[org-table-eval-formula]."
1355 :group 'org-table-calculation
1356 :type 'boolean)
1357
1358
1359 (defcustom org-table-formula-use-constants t
1360 "Non-nil means, interpret constants in formulas in tables.
1361 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1362 by the value given in `org-table-formula-constants', or by a value obtained
1363 from the `constants.el' package."
1364 :group 'org-table-calculation
1365 :type 'boolean)
1366
1367 (defcustom org-table-formula-constants nil
1368 "Alist with constant names and values, for use in table formulas.
1369 The car of each element is a name of a constant, without the `$' before it.
1370 The cdr is the value as a string. For example, if you'd like to use the
1371 speed of light in a formula, you would configure
1372
1373 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1374
1375 and then use it in an equation like `$1*$c'."
1376 :group 'org-table-calculation
1377 :type '(repeat
1378 (cons (string :tag "name")
1379 (string :tag "value"))))
1380
1381 (defcustom org-table-formula-numbers-only nil
1382 "Non-nil means, calculate only with numbers in table formulas.
1383 Then all input fields will be converted to a number, and the result
1384 must also be a number. When nil, calc's full potential is available
1385 in table calculations, including symbolics etc."
1386 :group 'org-table-calculation
1387 :type 'boolean)
1388
1389 (defcustom org-table-allow-automatic-line-recalculation t
1390 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1391 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1392 :group 'org-table-calculation
1393 :type 'boolean)
1394
1395 (defgroup org-export nil
1396 "Options for exporting org-listings."
1397 :tag "Org Export"
1398 :group 'org)
1399
1400 (defcustom org-export-language-setup
1401 '(("en" "Author" "Date" "Table of Contents")
1402 ("da" "Ophavsmand" "Dato" "Indhold")
1403 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1404 ("es" "Autor" "Fecha" "\xccndice")
1405 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1406 ("it" "Autore" "Data" "Indice")
1407 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1408 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1409 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1410 "Terms used in export text, translated to different languages.
1411 Use the variable `org-export-default-language' to set the language,
1412 or use the +OPTION lines for a per-file setting."
1413 :group 'org-export
1414 :type '(repeat
1415 (list
1416 (string :tag "HTML language tag")
1417 (string :tag "Author")
1418 (string :tag "Date")
1419 (string :tag "Table of Contents"))))
1420
1421 (defcustom org-export-default-language "en"
1422 "The default language of HTML export, as a string.
1423 This should have an association in `org-export-language-setup'."
1424 :group 'org-export
1425 :type 'string)
1426
1427 (defcustom org-export-html-style
1428 "<style type=\"text/css\">
1429 html {
1430 font-family: Times, serif;
1431 font-size: 12pt;
1432 }
1433 .title { text-align: center; }
1434 .todo, .deadline { color: red; }
1435 .done { color: green; }
1436 .target { background-color: lavender; }
1437 pre {
1438 border: 1pt solid #AEBDCC;
1439 background-color: #F3F5F7;
1440 padding: 5pt;
1441 font-family: courier, monospace;
1442 }
1443 table { border-collapse: collapse; }
1444 td, th {
1445 vertical-align: top;
1446 border: 1pt solid #ADB9CC;
1447 }
1448 </style>"
1449 "The default style specification for exported HTML files.
1450 Since there are different ways of setting style information, this variable
1451 needs to contain the full HTML structure to provide a style, including the
1452 surrounding HTML tags. The style specifications should include definitions
1453 for new classes todo, done, title, and deadline. For example, legal values
1454 would be:
1455
1456 <style type=\"text/css\">
1457 p { font-weight: normal; color: gray; }
1458 h1 { color: black; }
1459 .title { text-align: center; }
1460 .todo, .deadline { color: red; }
1461 .done { color: green; }
1462 </style>
1463
1464 or, if you want to keep the style in a file,
1465
1466 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1467
1468 As the value of this option simply gets inserted into the HTML <head> header,
1469 you can \"misuse\" it to add arbitrary text to the header."
1470 :group 'org-export
1471 :type 'string)
1472
1473 (defcustom org-export-headline-levels 3
1474 "The last level which is still exported as a headline.
1475 Inferior levels will produce itemize lists when exported.
1476 Note that a numeric prefix argument to an exporter function overrides
1477 this setting.
1478
1479 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1480 :group 'org-export
1481 :type 'number)
1482
1483 (defcustom org-export-with-section-numbers t
1484 "Non-nil means, add section numbers to headlines when exporting.
1485
1486 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1487 :group 'org-export
1488 :type 'boolean)
1489
1490 (defcustom org-export-with-toc t
1491 "Non-nil means, create a table of contents in exported files.
1492 The TOC contains headlines with levels up to`org-export-headline-levels'.
1493
1494 Headlines which contain any TODO items will be marked with \"(*)\" in
1495 ASCII export, and with red color in HTML output.
1496
1497 In HTML output, the TOC will be clickable.
1498
1499 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1500 :group 'org-export
1501 :type 'boolean)
1502
1503 (defcustom org-export-plain-list-max-depth 20
1504 "Maximum depth of hand-formatted lists in HTML export.
1505
1506 Org-mode parses hand-formatted enumeration and bullet lists and
1507 transforms them to HTML open export. Different indentation of the
1508 bullet or number indicates different list nesting levels. To avoid
1509 confusion, only a single level is allowed by default. When this is
1510 larger than 1, deeper indentation leads to deeper list nesting. For
1511 example, the default value of 3 allows the following list to be
1512 formatted correctly in HTML:
1513
1514 * Fruit
1515 - Apple
1516 - Banana
1517 1. from Africa
1518 2. from South America
1519 - Pineapple
1520 * Bread
1521 * Dairy products"
1522 :group 'org-export
1523 :type 'integer)
1524
1525 (defcustom org-export-preserve-breaks nil
1526 "Non-nil means, preserve all line breaks when exporting.
1527 Normally, in HTML output paragraphs will be reformatted. In ASCII
1528 export, line breaks will always be preserved, regardless of this variable.
1529
1530 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1531 :group 'org-export
1532 :type 'boolean)
1533
1534 (defcustom org-export-html-inline-images t
1535 "Non-nil means, inline images into exported HTML pages.
1536 The link will still be to the original location of the image file.
1537 So if you are moving the page, lets say to your public HTML site,
1538 you will have to move the image and maybe change the link."
1539 :group 'org-export
1540 :type 'boolean)
1541
1542 (defcustom org-export-html-expand t
1543 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1544 When nil, these tags will be exported as plain text and therefore
1545 not be interpreted by a browser.
1546
1547 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1548 :group 'org-export
1549 :type 'boolean)
1550
1551 (defcustom org-export-with-fixed-width t
1552 "Non-nil means, lines starting with \":\" will be in fixed width font.
1553 This can be used to have pre-formatted text, fragments of code etc. For
1554 example:
1555 : ;; Some Lisp examples
1556 : (while (defc cnt)
1557 : (ding))
1558 will be looking just like this in also HTML. In ASCII export, this option
1559 has no effect.
1560
1561 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1562 :group 'org-export
1563 :type 'boolean)
1564
1565 (defcustom org-export-with-tables t
1566 "If non-nil, lines starting with \"|\" define a table.
1567 For example:
1568
1569 | Name | Address | Birthday |
1570 |-------------+----------+-----------|
1571 | Arthur Dent | England | 29.2.2100 |
1572
1573 In ASCII export, this option has no effect.
1574
1575 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1576 :group 'org-export
1577 :type 'boolean)
1578
1579 (defcustom org-export-table-remove-special-lines t
1580 "Remove special lines and marking characters in calculating tables.
1581 This removes the special marking character column from tables that are set
1582 up for spreadsheet calculations. It also removes the entire lines
1583 marked with `!', `_', or `^'. The lines with `$' are kept, because
1584 the values of constants may be useful to have."
1585 :group 'org-export
1586 :type 'boolean)
1587
1588 (defcustom org-export-prefer-native-exporter-for-tables nil
1589 "Non-nil means, always export tables created with table.el natively.
1590 Natively means, use the HTML code generator in table.el.
1591 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1592 the table does not use row- or column-spanning). This has the
1593 advantage, that the automatic HTML conversions for math symbols and
1594 sub/superscripts can be applied. Org-mode's HTML generator is also
1595 much faster."
1596 :group 'org-export
1597 :type 'boolean)
1598
1599 (defcustom org-export-html-table-tag
1600 "<table border=1 cellspacing=0 cellpadding=6>"
1601 "The HTML tag used to start a table.
1602 This must be a <table> tag, but you may change the options like
1603 borders and spacing."
1604 :group 'org-export
1605 :type 'string)
1606
1607 (defcustom org-export-with-emphasize t
1608 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1609 If the export target supports emphasizing text, the word will be
1610 typeset in bold, italic, or underlined, respectively. Works only for
1611 single words, but you can say: I *really* *mean* *this*.
1612 In ASCII export, this option has no effect.
1613
1614 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1615 :group 'org-export
1616 :type 'boolean)
1617
1618 (defcustom org-match-sexp-depth 3
1619 "Number of stacked braces for sub/superscript matching.
1620 This has to be set before loading org.el to be effective."
1621 :group 'org-export
1622 :type 'integer)
1623
1624 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1625 (defcustom org-export-with-sub-superscripts t
1626 "Non-nil means, interpret \"_\" and \"^\" for export.
1627 When this option is turned on, you can use TeX-like syntax for sub- and
1628 superscripts. Several characters after \"_\" or \"^\" will be
1629 considered as a single item - so grouping with {} is normally not
1630 needed. For example, the following things will be parsed as single
1631 sub- or superscripts.
1632
1633 10^24 or 10^tau several digits will be considered 1 item.
1634 10^-12 or 10^-tau a leading sign with digits or a word
1635 x^2-y^3 will be read as x^2 - y^3, because items are
1636 terminated by almost any nonword/nondigit char.
1637 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1638
1639 Still, ambiguity is possible - so when in doubt use {} to enclose the
1640 sub/superscript.
1641 In ASCII export, this option has no effect.
1642
1643 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1644 :group 'org-export
1645 :type 'boolean)
1646
1647 (defcustom org-export-with-TeX-macros t
1648 "Non-nil means, interpret simple TeX-like macros when exporting.
1649 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1650 No only real TeX macros will work here, but the standard HTML entities
1651 for math can be used as macro names as well. For a list of supported
1652 names in HTML export, see the constant `org-html-entities'.
1653 In ASCII export, this option has no effect.
1654
1655 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1656 :group 'org-export
1657 :type 'boolean)
1658
1659 (defcustom org-export-html-with-timestamp nil
1660 "If non-nil, write `org-export-html-html-helper-timestamp'
1661 into the exported HTML text. Otherwise, the buffer will just be saved
1662 to a file."
1663 :group 'org-export
1664 :type 'boolean)
1665
1666 (defcustom org-export-html-html-helper-timestamp
1667 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1668 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1669 :group 'org-export
1670 :type 'string)
1671
1672 (defcustom org-export-ascii-show-new-buffer t
1673 "Non-nil means, popup buffer containing the exported ASCII text.
1674 Otherwise the buffer will just be saved to a file and stay hidden."
1675 :group 'org-export
1676 :type 'boolean)
1677
1678 (defcustom org-export-html-show-new-buffer nil
1679 "Non-nil means, popup buffer containing the exported html text.
1680 Otherwise, the buffer will just be saved to a file and stay hidden."
1681 :group 'org-export
1682 :type 'boolean)
1683
1684 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1685 "The file name for the iCalendar file covering all agenda files.
1686 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1687 :group 'org-export
1688 :type 'file)
1689
1690 (defcustom org-icalendar-include-todo nil
1691 "Non-nil means, export to iCalendar files should also cover TODO items."
1692 :group 'org-export
1693 :type 'boolean)
1694
1695 (defcustom org-icalendar-combined-name "OrgMode"
1696 "Calendar name for the combined iCalendar representing all agenda files."
1697 :group 'org-export
1698 :type 'string)
1699
1700 (defgroup org-faces nil
1701 "Faces for highlighting in Org-mode."
1702 :tag "Org Faces"
1703 :group 'org)
1704
1705 (defface org-hide
1706 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1707 (((class color) (background light)) (:foreground "white"))
1708 (((class color) (background dark)) (:foreground "black"))
1709 ; (((class color) (background light)) (:foreground "grey90"))
1710 ; (((class color) (background dark)) (:foreground "grey10"))
1711 (t (:inverse-video nil)))
1712 "Face used for level 1 headlines."
1713 :group 'org-faces)
1714
1715 (defface org-level-1 ;; font-lock-function-name-face
1716 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1717 (((class color) (background light)) (:foreground "Blue"))
1718 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1719 (t (:inverse-video t :bold t)))
1720 "Face used for level 1 headlines."
1721 :group 'org-faces)
1722
1723 (defface org-level-2 ;; font-lock-variable-name-face
1724 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1725 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1726 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1727 (t (:bold t :italic t)))
1728 "Face used for level 2 headlines."
1729 :group 'org-faces)
1730
1731 (defface org-level-3 ;; font-lock-keyword-face
1732 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1733 (((class color) (background light)) (:foreground "Purple"))
1734 (((class color) (background dark)) (:foreground "Cyan"))
1735 (t (:bold t)))
1736 "Face used for level 3 headlines."
1737 :group 'org-faces)
1738
1739 (defface org-level-4 ;; font-lock-comment-face
1740 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1741 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1742 (((class color) (background light)) (:foreground "Firebrick"))
1743 (((class color) (background dark)) (:foreground "chocolate1"))
1744 (t (:bold t :italic t)))
1745 "Face used for level 4 headlines."
1746 :group 'org-faces)
1747
1748 (defface org-level-5 ;; font-lock-type-face
1749 '((((type tty) (class color)) (:foreground "green"))
1750 (((class color) (background light)) (:foreground "ForestGreen"))
1751 (((class color) (background dark)) (:foreground "PaleGreen"))
1752 (t (:bold t :underline t)))
1753 "Face used for level 5 headlines."
1754 :group 'org-faces)
1755
1756 (defface org-level-6 ;; font-lock-constant-face
1757 '((((type tty) (class color)) (:foreground "magenta"))
1758 (((class color) (background light)) (:foreground "CadetBlue"))
1759 (((class color) (background dark)) (:foreground "Aquamarine"))
1760 (t (:bold t :underline t)))
1761 "Face used for level 6 headlines."
1762 :group 'org-faces)
1763
1764 (defface org-level-7 ;; font-lock-builtin-face
1765 '((((type tty) (class color)) (:foreground "blue" :weight light))
1766 (((class color) (background light)) (:foreground "Orchid"))
1767 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1768 (t (:bold t)))
1769 "Face used for level 7 headlines."
1770 :group 'org-faces)
1771
1772 (defface org-level-8 ;; font-lock-string-face
1773 '((((type tty) (class color)) (:foreground "green"))
1774 (((class color) (background light)) (:foreground "RosyBrown"))
1775 (((class color) (background dark)) (:foreground "LightSalmon"))
1776 (t (:italic t)))
1777 "Face used for level 8 headlines."
1778 :group 'org-faces)
1779
1780 (defface org-special-keyword ;; font-lock-string-face
1781 '((((type tty) (class color)) (:foreground "green"))
1782 (((class color) (background light)) (:foreground "RosyBrown"))
1783 (((class color) (background dark)) (:foreground "LightSalmon"))
1784 (t (:italic t)))
1785 "Face used for special keywords."
1786 :group 'org-faces)
1787
1788 (defface org-warning ;; font-lock-warning-face
1789 '((((type tty) (class color)) (:foreground "red"))
1790 (((class color) (background light)) (:foreground "Red" :bold t))
1791 (((class color) (background dark)) (:foreground "Red1" :bold t))
1792 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1793 (t (:inverse-video t :bold t)))
1794 "Face for deadlines and TODO keywords."
1795 :group 'org-faces)
1796
1797 (defcustom org-fontify-done-headline nil
1798 "Non-nil means, change the face of a headline if it is marked DONE.
1799 Normally, only the TODO/DONE keyword indicates the state of a headline.
1800 When this is non-nil, the headline after the keyword is set to the
1801 `org-headline-done' as an additional indication."
1802 :group 'org-faces
1803 :type 'boolean)
1804
1805 (defface org-headline-done ;; font-lock-string-face
1806 '((((type tty) (class color)) (:foreground "green"))
1807 (((class color) (background light)) (:foreground "RosyBrown"))
1808 (((class color) (background dark)) (:foreground "LightSalmon"))
1809 (t (:italic t)))
1810 "Face used to indicate that a headline is DONE. See also the variable
1811 `org-fontify-done-headline'."
1812 :group 'org-faces)
1813
1814 ;; Inheritance does not yet work for xemacs. So we just copy...
1815
1816 (defface org-deadline-announce
1817 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1818 (((class color) (background light)) (:foreground "Blue"))
1819 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1820 (t (:inverse-video t :bold t)))
1821 "Face for upcoming deadlines."
1822 :group 'org-faces)
1823
1824 (defface org-scheduled-today
1825 '((((type tty) (class color)) (:foreground "green"))
1826 (((class color) (background light)) (:foreground "DarkGreen"))
1827 (((class color) (background dark)) (:foreground "PaleGreen"))
1828 (t (:bold t :underline t)))
1829 "Face for items scheduled for a certain day."
1830 :group 'org-faces)
1831
1832 (defface org-scheduled-previously
1833 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1834 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1835 (((class color) (background light)) (:foreground "Firebrick"))
1836 (((class color) (background dark)) (:foreground "chocolate1"))
1837 (t (:bold t :italic t)))
1838 "Face for items scheduled previously, and not yet done."
1839 :group 'org-faces)
1840
1841 (defface org-formula
1842 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1843 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1844 (((class color) (background light)) (:foreground "Firebrick"))
1845 (((class color) (background dark)) (:foreground "chocolate1"))
1846 (t (:bold t :italic t)))
1847 "Face for formulas."
1848 :group 'org-faces)
1849
1850 (defface org-link
1851 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1852 (((class color) (background light)) (:foreground "Purple"))
1853 (((class color) (background dark)) (:foreground "Cyan"))
1854 (t (:bold t)))
1855 "Face for links."
1856 :group 'org-faces)
1857
1858 (defface org-done ;; font-lock-type-face
1859 '((((type tty) (class color)) (:foreground "green"))
1860 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1861 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1862 (t (:bold t :underline t)))
1863 "Face used for DONE."
1864 :group 'org-faces)
1865
1866 (defface org-table ;; font-lock-function-name-face
1867 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1868 (((class color) (background light)) (:foreground "Blue"))
1869 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1870 (t (:inverse-video t :bold t)))
1871 "Face used for tables."
1872 :group 'org-faces)
1873
1874 (defface org-time-grid ;; font-lock-variable-name-face
1875 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1876 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1877 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1878 (t (:bold t :italic t)))
1879 "Face used for time grids."
1880 :group 'org-faces)
1881
1882 (defvar org-level-faces nil)
1883
1884 (when (not org-level-faces)
1885 (setq org-level-faces
1886 '(
1887 org-level-1
1888 org-level-2
1889 org-level-3
1890 org-level-4
1891 org-level-5
1892 org-level-6
1893 org-level-7
1894 org-level-8
1895 ))
1896 (when org-odd-levels-only
1897 (setq org-level-faces (apply 'append (mapcar (lambda (x) (list x x))
1898 org-level-faces)))
1899 (setq org-level-faces (append (cdr org-level-faces) (list 'org-level-1)))))
1900
1901 (defvar org-n-levels (length org-level-faces))
1902
1903 (defun org-set-regexps-and-options ()
1904 "Precompute regular expressions for current buffer."
1905 (when (eq major-mode 'org-mode)
1906 (let ((re (org-make-options-regexp
1907 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1908 "STARTUP" "ARCHIVE")))
1909 (splitre "[ \t]+")
1910 kwds int key value cat arch)
1911 (save-excursion
1912 (save-restriction
1913 (widen)
1914 (goto-char (point-min))
1915 (while (re-search-forward re nil t)
1916 (setq key (match-string 1) value (match-string 2))
1917 (cond
1918 ((equal key "CATEGORY")
1919 (if (string-match "[ \t]+$" value)
1920 (setq value (replace-match "" t t value)))
1921 (setq cat (intern value)))
1922 ((equal key "SEQ_TODO")
1923 (setq int 'sequence
1924 kwds (append kwds (org-split-string value splitre))))
1925 ((equal key "PRI_TODO")
1926 (setq int 'priority
1927 kwds (append kwds (org-split-string value splitre))))
1928 ((equal key "TYP_TODO")
1929 (setq int 'type
1930 kwds (append kwds (org-split-string value splitre))))
1931 ((equal key "STARTUP")
1932 (let ((opts (org-split-string value splitre))
1933 (set '(("fold" org-startup-folded t)
1934 ("nofold" org-startup-folded nil)
1935 ("content" org-startup-folded content)
1936 ("dlcheck" org-startup-with-deadline-check t)
1937 ("nodlcheck" org-startup-with-deadline-check nil)))
1938 l var val)
1939 (while (setq l (assoc (pop opts) set))
1940 (setq var (nth 1 l) val (nth 2 l))
1941 (set (make-local-variable var) val))))
1942 ((equal key "ARCHIVE")
1943 (string-match " *$" value)
1944 (setq arch (replace-match "" t t value))
1945 (remove-text-properties 0 (length arch)
1946 '(face t fontified t) arch)))
1947 )))
1948 (and cat (set (make-local-variable 'org-category) cat))
1949 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1950 (and arch (set (make-local-variable 'org-archive-location) arch))
1951 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1952 ;; Compute the regular expressions and other local variables
1953 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1954 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1955 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1956 (length org-scheduled-string)))
1957 org-done-string
1958 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1959 org-todo-regexp
1960 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1961 "\\|") "\\)\\>")
1962 org-not-done-regexp
1963 (concat "\\<\\("
1964 (mapconcat 'regexp-quote
1965 (nreverse (cdr (reverse org-todo-keywords)))
1966 "\\|")
1967 "\\)\\>")
1968 org-todo-line-regexp
1969 (concat "^\\(\\*+\\)[ \t]*\\("
1970 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1971 "\\)? *\\(.*\\)")
1972 org-nl-done-regexp
1973 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1974 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1975 org-deadline-regexp (concat "\\<" org-deadline-string)
1976 org-deadline-time-regexp
1977 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1978 org-deadline-line-regexp
1979 (concat "\\<\\(" org-deadline-string "\\).*")
1980 org-scheduled-regexp
1981 (concat "\\<" org-scheduled-string)
1982 org-scheduled-time-regexp
1983 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1984 (org-set-font-lock-defaults)))
1985
1986 ;; Tell the compiler about dynamically scoped variables,
1987 ;; and variables from other packages
1988 (eval-when-compile
1989 (defvar zmacs-regions)
1990 (defvar original-date)
1991 (defvar org-transient-mark-mode)
1992 (defvar org-old-auto-fill-inhibit-regexp)
1993 (defvar orgtbl-mode-menu)
1994 (defvar org-html-entities)
1995 (defvar org-goto-start-pos)
1996 (defvar org-cursor-color)
1997 (defvar org-time-was-given)
1998 (defvar org-ts-what)
1999 (defvar mark-active)
2000 (defvar timecnt)
2001 (defvar levels-open)
2002 (defvar title)
2003 (defvar author)
2004 (defvar email)
2005 (defvar text)
2006 (defvar entry)
2007 (defvar date)
2008 (defvar language)
2009 (defvar options)
2010 (defvar ans1)
2011 (defvar ans2)
2012 (defvar starting-day)
2013 (defvar include-all-loc)
2014 (defvar vm-message-pointer)
2015 (defvar vm-folder-directory)
2016 (defvar wl-summary-buffer-elmo-folder)
2017 (defvar wl-summary-buffer-folder-name)
2018 (defvar gnus-group-name)
2019 (defvar gnus-article-current)
2020 (defvar w3m-current-url)
2021 (defvar mh-progs)
2022 (defvar mh-current-folder)
2023 (defvar mh-show-folder-buffer)
2024 (defvar mh-index-folder)
2025 (defvar org-selected-point)
2026 (defvar calendar-mode-map)
2027 (defvar remember-save-after-remembering)
2028 (defvar remember-data-file)
2029 (defvar last-arg))
2030
2031 ;;; Define the mode
2032
2033 (defvar org-mode-map (copy-keymap outline-mode-map)
2034 "Keymap for Org-mode.")
2035
2036 (defvar org-struct-menu)
2037 (defvar org-org-menu)
2038 (defvar org-tbl-menu)
2039
2040 ;; We use a before-change function to check if a table might need
2041 ;; an update.
2042 (defvar org-table-may-need-update t
2043 "Indicates that a table might need an update.
2044 This variable is set by `org-before-change-function'.
2045 `org-table-align' sets it back to nil.")
2046 (defvar org-mode-hook nil)
2047 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2048 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2049
2050
2051 ;;;###autoload
2052 (define-derived-mode org-mode outline-mode "Org"
2053 "Outline-based notes management and organizer, alias
2054 \"Carsten's outline-mode for keeping track of everything.\"
2055
2056 Org-mode develops organizational tasks around a NOTES file which
2057 contains information about projects as plain text. Org-mode is
2058 implemented on top of outline-mode, which is ideal to keep the content
2059 of large files well structured. It supports ToDo items, deadlines and
2060 time stamps, which magically appear in the diary listing of the Emacs
2061 calendar. Tables are easily created with a built-in table editor.
2062 Plain text URL-like links connect to websites, emails (VM), Usenet
2063 messages (Gnus), BBDB entries, and any files related to the project.
2064 For printing and sharing of notes, an Org-mode file (or a part of it)
2065 can be exported as a structured ASCII or HTML file.
2066
2067 The following commands are available:
2068
2069 \\{org-mode-map}"
2070 (easy-menu-add org-org-menu)
2071 (easy-menu-add org-tbl-menu)
2072 (org-install-agenda-files-menu)
2073 (setq outline-regexp "\\*+")
2074 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2075 (setq outline-level 'org-outline-level)
2076 (if org-startup-truncated (setq truncate-lines t))
2077 (org-set-regexps-and-options)
2078 (set (make-local-variable 'font-lock-unfontify-region-function)
2079 'org-unfontify-region)
2080 ;; Activate before-change-function
2081 (set (make-local-variable 'org-table-may-need-update) t)
2082 (org-add-hook 'before-change-functions 'org-before-change-function nil
2083 'local)
2084 ;; Paragraphs and auto-filling
2085 (org-set-autofill-regexps)
2086 (org-update-radio-target-regexp)
2087 ;; Settings for Calc embedded mode
2088 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2089 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2090 (if (and org-insert-mode-line-in-empty-file
2091 (interactive-p)
2092 (= (point-min) (point-max)))
2093 (insert " -*- mode: org -*-\n\n"))
2094
2095 ;; Get rid of Outline menus, they are not needed
2096 ;; Need to do this here because define-derived-mode sets up
2097 ;; the keymap so late.
2098 (if org-xemacs-p
2099 (progn
2100 (delete-menu-item '("Headings"))
2101 (delete-menu-item '("Show"))
2102 (delete-menu-item '("Hide"))
2103 (set-menubar-dirty-flag))
2104 (define-key org-mode-map [menu-bar headings] 'undefined)
2105 (define-key org-mode-map [menu-bar hide] 'undefined)
2106 (define-key org-mode-map [menu-bar show] 'undefined))
2107
2108 (unless org-inhibit-startup
2109 (if org-startup-with-deadline-check
2110 (call-interactively 'org-check-deadlines)
2111 (cond
2112 ((eq org-startup-folded t)
2113 (org-cycle '(4)))
2114 ((eq org-startup-folded 'content)
2115 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2116 (org-cycle '(4)) (org-cycle '(4))))))))
2117
2118 (defsubst org-current-line (&optional pos)
2119 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2120
2121
2122 ;; FIXME: Do we need to copy?
2123 (defun org-string-props (string &rest properties)
2124 "Add PROPERTIES to string."
2125 (add-text-properties 0 (length string) properties string)
2126 string)
2127
2128 ;;; Font-Lock stuff
2129
2130 (defvar org-mouse-map (make-sparse-keymap))
2131 (define-key org-mouse-map
2132 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2133 (define-key org-mouse-map
2134 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2135 (define-key org-mouse-map [follow-link] 'mouse-face)
2136 (when org-tab-follows-link
2137 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2138 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2139 (when org-return-follows-link
2140 (define-key org-mouse-map [(return)] 'org-open-at-point)
2141 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2142
2143 (require 'font-lock)
2144
2145 (defconst org-non-link-chars "\t\n\r|<>\000")
2146 (defconst org-link-regexp
2147 (if org-allow-space-in-links
2148 (concat
2149 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2150 (concat
2151 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2152 )
2153 "Regular expression for matching links.")
2154 (defconst org-link-maybe-angles-regexp
2155 (concat "<?\\(" org-link-regexp "\\)>?")
2156 "Matches a link and optionally surrounding angle brackets.")
2157 (defconst org-protected-link-regexp
2158 (concat "\000" org-link-regexp "\000")
2159 "Matches a link and optionally surrounding angle brackets.")
2160
2161 (defconst org-bracket-link-regexp
2162 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2163 "Matches a link in double brackets.")
2164
2165 (defconst org-ts-lengths
2166 (cons (length (format-time-string (car org-time-stamp-formats)))
2167 (length (format-time-string (cdr org-time-stamp-formats))))
2168 "This holds the lengths of the two different time formats.")
2169 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2170 "Regular expression for fast time stamp matching.")
2171 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2172 "Regular expression for fast time stamp matching.")
2173 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2174 "Regular expression matching time strings for analysis.")
2175 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2176 "Regular expression matching time stamps, with groups.")
2177 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2178 "Regular expression matching a time stamp range.")
2179 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2180 org-ts-regexp "\\)?")
2181 "Regular expression matching a time stamp or time stamp range.")
2182
2183 (defun org-activate-links (limit)
2184 "Run through the buffer and add overlays to links."
2185 (if (re-search-forward org-link-regexp limit t)
2186 (progn
2187 (add-text-properties (match-beginning 0) (match-end 0)
2188 (list 'mouse-face 'highlight
2189 'keymap org-mouse-map))
2190 t)))
2191
2192 (defun org-activate-links2 (limit)
2193 "Run through the buffer and add overlays to links."
2194 (if (re-search-forward org-bracket-link-regexp limit t)
2195 (progn
2196 (add-text-properties (match-beginning 0) (match-end 0)
2197 (list 'mouse-face 'highlight
2198 'keymap org-mouse-map))
2199 t)))
2200
2201 (defun org-activate-dates (limit)
2202 "Run through the buffer and add overlays to dates."
2203 (if (re-search-forward org-tsr-regexp limit t)
2204 (progn
2205 (add-text-properties (match-beginning 0) (match-end 0)
2206 (list 'mouse-face 'highlight
2207 'keymap org-mouse-map))
2208 t)))
2209
2210 (defvar org-target-link-regexp nil
2211 "Regular expression matching radio targets in plain text.")
2212 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2213 "Regular expression matching a link target.")
2214 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2215 "Regular expression matching a link target.")
2216
2217 (defun org-activate-target-links (limit)
2218 "Run through the buffer and add overlays to target matches."
2219 (when org-radio-targets
2220 (let ((case-fold-search t))
2221 (if (re-search-forward org-target-link-regexp limit t)
2222 (progn
2223 (add-text-properties (match-beginning 0) (match-end 0)
2224 (list 'mouse-face 'highlight
2225 'keymap org-mouse-map
2226 'org-linked-text t))
2227 t)))))
2228
2229 (defun org-update-radio-target-regexp ()
2230 "Find all radio targets in this file and update the regular expression."
2231 (interactive)
2232 (when org-radio-targets
2233 (setq org-target-link-regexp
2234 (org-make-target-link-regexp (org-all-targets 'radio)))
2235 (font-lock-mode -1)
2236 (font-lock-mode 1)))
2237
2238 (defun org-all-targets (&optional radio)
2239 "Return a list of all targets in this file.
2240 With optional argument RADIO, only find radio targets."
2241 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2242 rtn)
2243 (save-excursion
2244 (goto-char (point-min))
2245 (while (re-search-forward re nil t)
2246 (add-to-list 'rtn (downcase
2247 (if (fboundp 'match-string-no-properties)
2248 (match-string-no-properties 1)
2249 (match-string 1)))))
2250 rtn)))
2251
2252 (defun org-make-target-link-regexp (targets)
2253 "Make regular expression matching all strings in TARGETS.
2254 The regular expression finds the targets also if there is a line break
2255 between words."
2256 (concat
2257 "\\<\\("
2258 (mapconcat
2259 (lambda (x)
2260 (while (string-match " +" x)
2261 (setq x (replace-match "\\s-+" t t x)))
2262 x)
2263 targets
2264 "\\|")
2265 "\\)\\>"))
2266
2267 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2268 "Matches CamelCase words, possibly with a star before it.")
2269
2270 (defun org-activate-camels (limit)
2271 "Run through the buffer and add overlays to dates."
2272 (if org-activate-camels
2273 (if (re-search-forward org-camel-regexp limit t)
2274 (progn
2275 (add-text-properties (match-beginning 0) (match-end 0)
2276 (list 'mouse-face 'highlight
2277 'keymap org-mouse-map))
2278 t))))
2279
2280 (defun org-activate-tags (limit)
2281 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2282 (progn
2283 (add-text-properties (match-beginning 1) (match-end 1)
2284 (list 'mouse-face 'highlight
2285 'keymap org-mouse-map))
2286 t)))
2287
2288 (defun org-font-lock-level ()
2289 (save-excursion
2290 (org-back-to-heading t)
2291 (- (match-end 0) (match-beginning 0))))
2292
2293 (defun org-outline-level ()
2294 (save-excursion
2295 (looking-at outline-regexp)
2296 (if (match-beginning 1)
2297 (+ (org-get-string-indentation (match-string 1)) 1000)
2298 (- (match-end 0) (match-beginning 0)))))
2299
2300 (defvar org-font-lock-keywords nil)
2301
2302 (defun org-set-font-lock-defaults ()
2303 (let ((org-font-lock-extra-keywords
2304 (list
2305 '(org-activate-links (0 'org-link t))
2306 '(org-activate-links2 (0 'org-link t))
2307 '(org-activate-target-links (0 'org-link t))
2308 '(org-activate-dates (0 'org-link t))
2309 '(org-activate-camels (0 'org-link t))
2310 '(org-activate-tags (1 'org-link t))
2311 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2312 '(1 'org-warning t))
2313 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2314 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2315 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2316 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2317 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2318 ;; (3 'bold))
2319 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2320 ;; (3 'italic))
2321 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2322 ;; (3 'underline))
2323 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2324 "\\|" org-quote-string "\\)\\>")
2325 '(1 'org-special-keyword t))
2326 '("^#.*" (0 'font-lock-comment-face t))
2327 (if org-fontify-done-headline
2328 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2329 '(1 'org-done t) '(2 'org-headline-done t))
2330 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2331 '(1 'org-done t)))
2332 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2333 (1 'org-table t))
2334 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2335 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2336 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2337 ))
2338 (exp
2339 ;; The font-lock expression for headlines is complicated. It depends
2340 ;; on two user options, and it needs to determine the level in
2341 ;; order to compute the level.
2342 (cond
2343 ((and org-level-color-stars-only (not org-hide-leading-stars))
2344 '("^\\(\\*+\\).*" 1 (nth (% (- (match-end 1) (match-beginning 1) 1) org-n-levels) org-level-faces) nil t))
2345 ((and (not org-level-color-stars-only) org-hide-leading-stars)
2346 '("^\\(\\**\\)\\(\\*.*\\)" (1 'org-hide) (2 (nth (% (- (match-end 1) (match-beginning 1)) org-n-levels) org-level-faces) nil t)))
2347 ((and org-level-color-stars-only org-hide-leading-stars)
2348 '("^\\(\\**\\)\\(\\*\\).*" (1 'org-hide) (2 (nth (% (- (match-end 1) (match-beginning 1)) org-n-levels) org-level-faces) nil t)))
2349 (t
2350 '("^\\(\\*+\\).*" 0 (nth (% (- (match-end 1) (match-beginning 1) 1) org-n-levels) org-level-faces) nil t)))))
2351
2352 ;; Now set the full font-lock-keywords
2353 (set (make-local-variable 'org-font-lock-keywords)
2354 (append
2355 (if org-xemacs-p (list exp) (list (cons 'eval (list 'quote exp))))
2356 org-font-lock-extra-keywords))
2357 (set (make-local-variable 'font-lock-defaults)
2358 '(org-font-lock-keywords t nil nil backward-paragraph))
2359 (kill-local-variable 'font-lock-keywords) nil))
2360
2361 (defun org-unfontify-region (beg end &optional maybe_loudly)
2362 "Remove fontification and activation overlays from links."
2363 (font-lock-default-unfontify-region beg end)
2364 (let* ((buffer-undo-list t)
2365 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2366 (inhibit-modification-hooks t)
2367 deactivate-mark buffer-file-name buffer-file-truename)
2368 (remove-text-properties beg end
2369 '(mouse-face nil keymap nil org-linked-text nil))))
2370
2371 ;;; Visibility cycling
2372
2373 (defvar org-cycle-global-status nil)
2374 (defvar org-cycle-subtree-status nil)
2375 (defun org-cycle (&optional arg)
2376 "Visibility cycling for Org-mode.
2377
2378 - When this function is called with a prefix argument, rotate the entire
2379 buffer through 3 states (global cycling)
2380 1. OVERVIEW: Show only top-level headlines.
2381 2. CONTENTS: Show all headlines of all levels, but no body text.
2382 3. SHOW ALL: Show everything.
2383
2384 - When point is at the beginning of a headline, rotate the subtree started
2385 by this line through 3 different states (local cycling)
2386 1. FOLDED: Only the main headline is shown.
2387 2. CHILDREN: The main headline and the direct children are shown.
2388 From this state, you can move to one of the children
2389 and zoom in further.
2390 3. SUBTREE: Show the entire subtree, including body text.
2391
2392 - When there is a numeric prefix, go up to a heading with level ARG, do
2393 a `show-subtree' and return to the previous cursor position. If ARG
2394 is negative, go up that many levels.
2395
2396 - When point is not at the beginning of a headline, execute
2397 `indent-relative', like TAB normally does. See the option
2398 `org-cycle-emulate-tab' for details.
2399
2400 - Special case: if point is the the beginning of the buffer and there is
2401 no headline in line 1, this function will act as if called with prefix arg."
2402 (interactive "P")
2403
2404 (if (or (and (bobp) (not (looking-at outline-regexp)))
2405 (equal arg '(4)))
2406 ;; special case: use global cycling
2407 (setq arg t))
2408
2409 (let ((outline-regexp
2410 (if org-cycle-include-plain-lists
2411 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2412 outline-regexp)))
2413
2414 (cond
2415
2416 ((org-at-table-p 'any)
2417 ;; Enter the table or move to the next field in the table
2418 (or (org-table-recognize-table.el)
2419 (progn
2420 (org-table-justify-field-maybe)
2421 (org-table-next-field))))
2422
2423 ((eq arg t) ;; Global cycling
2424
2425 (cond
2426 ((and (eq last-command this-command)
2427 (eq org-cycle-global-status 'overview))
2428 ;; We just created the overview - now do table of contents
2429 ;; This can be slow in very large buffers, so indicate action
2430 (message "CONTENTS...")
2431 (save-excursion
2432 ;; Visit all headings and show their offspring
2433 (goto-char (point-max))
2434 (catch 'exit
2435 (while (and (progn (condition-case nil
2436 (outline-previous-visible-heading 1)
2437 (error (goto-char (point-min))))
2438 t)
2439 (looking-at outline-regexp))
2440 (show-branches)
2441 (if (bobp) (throw 'exit nil))))
2442 (message "CONTENTS...done"))
2443 (setq org-cycle-global-status 'contents)
2444 (run-hook-with-args 'org-cycle-hook 'contents))
2445
2446 ((and (eq last-command this-command)
2447 (eq org-cycle-global-status 'contents))
2448 ;; We just showed the table of contents - now show everything
2449 (show-all)
2450 (message "SHOW ALL")
2451 (setq org-cycle-global-status 'all)
2452 (run-hook-with-args 'org-cycle-hook 'all))
2453
2454 (t
2455 ;; Default action: go to overview
2456 (hide-sublevels 1)
2457 (message "OVERVIEW")
2458 (setq org-cycle-global-status 'overview)
2459 (run-hook-with-args 'org-cycle-hook 'overview))))
2460
2461 ((integerp arg)
2462 ;; Show-subtree, ARG levels up from here.
2463 (save-excursion
2464 (org-back-to-heading)
2465 (outline-up-heading (if (< arg 0) (- arg)
2466 (- (outline-level) arg)))
2467 (org-show-subtree)))
2468
2469 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2470 ;; At a heading: rotate between three different views
2471 (org-back-to-heading)
2472 (let ((goal-column 0) eoh eol eos)
2473 ;; First, some boundaries
2474 (save-excursion
2475 (org-back-to-heading)
2476 (save-excursion
2477 (beginning-of-line 2)
2478 (while (and (not (eobp)) ;; this is like `next-line'
2479 (get-char-property (1- (point)) 'invisible))
2480 (beginning-of-line 2)) (setq eol (point)))
2481 (outline-end-of-heading) (setq eoh (point))
2482 (org-end-of-subtree t) (setq eos (point))
2483 (outline-next-heading))
2484 ;; Find out what to do next and set `this-command'
2485 (cond
2486 ((= eos eoh)
2487 ;; Nothing is hidden behind this heading
2488 (message "EMPTY ENTRY")
2489 (setq org-cycle-subtree-status nil))
2490 ((>= eol eos)
2491 ;; Entire subtree is hidden in one line: open it
2492 (org-show-entry)
2493 (show-children)
2494 (message "CHILDREN")
2495 (setq org-cycle-subtree-status 'children)
2496 (run-hook-with-args 'org-cycle-hook 'children))
2497 ((and (eq last-command this-command)
2498 (eq org-cycle-subtree-status 'children))
2499 ;; We just showed the children, now show everything.
2500 (org-show-subtree)
2501 (message "SUBTREE")
2502 (setq org-cycle-subtree-status 'subtree)
2503 (run-hook-with-args 'org-cycle-hook 'subtree))
2504 (t
2505 ;; Default action: hide the subtree.
2506 (hide-subtree)
2507 (message "FOLDED")
2508 (setq org-cycle-subtree-status 'folded)
2509 (run-hook-with-args 'org-cycle-hook 'folded)))))
2510
2511 ;; TAB emulation
2512 (buffer-read-only (org-back-to-heading))
2513 ((if (and (eq org-cycle-emulate-tab 'white)
2514 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2515 t
2516 (eq org-cycle-emulate-tab t))
2517 (if (and (looking-at "[ \n\r\t]")
2518 (string-match "^[ \t]*$" (buffer-substring
2519 (point-at-bol) (point))))
2520 (progn
2521 (beginning-of-line 1)
2522 (and (looking-at "[ \t]+") (replace-match ""))))
2523 (indent-relative))
2524
2525 (t (save-excursion
2526 (org-back-to-heading)
2527 (org-cycle))))))
2528
2529 (defun org-optimize-window-after-visibility-change (state)
2530 "Adjust the window after a change in outline visibility.
2531 This function is the default value of the hook `org-cycle-hook'."
2532 (cond
2533 ((eq state 'overview) (org-first-headline-recenter 1))
2534 ((eq state 'content) nil)
2535 ((eq state 'all) nil)
2536 ((eq state 'folded) nil)
2537 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2538 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2539
2540 (defun org-subtree-end-visible-p ()
2541 "Is the end of the current subtree visible?"
2542 (pos-visible-in-window-p
2543 (save-excursion (org-end-of-subtree t) (point))))
2544
2545 (defun org-first-headline-recenter (&optional N)
2546 "Move cursor to the first headline and recenter the headline.
2547 Optional argument N means, put the headline into the Nth line of the window."
2548 (goto-char (point-min))
2549 (when (re-search-forward (concat "^" outline-regexp) nil t)
2550 (beginning-of-line)
2551 (recenter (prefix-numeric-value N))))
2552
2553 (defvar org-goto-window-configuration nil)
2554 (defvar org-goto-marker nil)
2555 (defvar org-goto-map (make-sparse-keymap))
2556 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2557 (while (setq cmd (pop cmds))
2558 (substitute-key-definition cmd cmd org-goto-map global-map)))
2559 (define-key org-goto-map "\C-m" 'org-goto-ret)
2560 (define-key org-goto-map [(left)] 'org-goto-left)
2561 (define-key org-goto-map [(right)] 'org-goto-right)
2562 (define-key org-goto-map [(?q)] 'org-goto-quit)
2563 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2564 (define-key org-goto-map "\C-i" 'org-cycle)
2565 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2566 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2567 (define-key org-goto-map "n" 'outline-next-visible-heading)
2568 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2569 (define-key org-goto-map "f" 'outline-forward-same-level)
2570 (define-key org-goto-map "b" 'outline-backward-same-level)
2571 (define-key org-goto-map "u" 'outline-up-heading)
2572 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2573 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2574 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2575 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2576 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2577 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2578 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2579
2580 (defconst org-goto-help
2581 "Select a location to jump to, press RET
2582 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2583
2584 (defun org-goto ()
2585 "Go to a different location of the document, keeping current visibility.
2586
2587 When you want to go to a different location in a document, the fastest way
2588 is often to fold the entire buffer and then dive into the tree. This
2589 method has the disadvantage, that the previous location will be folded,
2590 which may not be what you want.
2591
2592 This command works around this by showing a copy of the current buffer in
2593 overview mode. You can dive into the tree in that copy, to find the
2594 location you want to reach. When pressing RET, the command returns to the
2595 original buffer in which the visibility is still unchanged. It then jumps
2596 to the new location, making it and the headline hierarchy above it visible."
2597 (interactive)
2598 (let* ((org-goto-start-pos (point))
2599 (selected-point
2600 (org-get-location (current-buffer) org-goto-help)))
2601 (if selected-point
2602 (progn
2603 (org-mark-ring-push org-goto-start-pos)
2604 (goto-char selected-point)
2605 (if (or (org-invisible-p) (org-invisible-p2))
2606 (org-show-hierarchy-above)))
2607 (error "Quit"))))
2608
2609 (defun org-get-location (buf help)
2610 "Let the user select a location in the Org-mode buffer BUF.
2611 This function uses a recursive edit. It returns the selected position
2612 or nil."
2613 (let (org-selected-point)
2614 (save-excursion
2615 (save-window-excursion
2616 (delete-other-windows)
2617 (switch-to-buffer (get-buffer-create "*org-goto*"))
2618 (with-output-to-temp-buffer "*Help*"
2619 (princ help))
2620 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2621 (setq buffer-read-only nil)
2622 (erase-buffer)
2623 (insert-buffer-substring buf)
2624 (let ((org-startup-truncated t)
2625 (org-startup-folded t)
2626 (org-startup-with-deadline-check nil))
2627 (org-mode))
2628 (setq buffer-read-only t)
2629 (if (boundp 'org-goto-start-pos)
2630 (goto-char org-goto-start-pos)
2631 (goto-char (point-min)))
2632 (org-beginning-of-line)
2633 (message "Select location and press RET")
2634 ;; now we make sure that during selection, ony very few keys work
2635 ;; and that it is impossible to switch to another window.
2636 (let ((gm (current-global-map))
2637 (overriding-local-map org-goto-map))
2638 (unwind-protect
2639 (progn
2640 (use-global-map org-goto-map)
2641 (recursive-edit))
2642 (use-global-map gm)))))
2643 (kill-buffer "*org-goto*")
2644 org-selected-point))
2645
2646 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2647 (defun org-goto-ret (&optional arg)
2648 "Finish `org-goto' by going to the new location."
2649 (interactive "P")
2650 (setq org-selected-point (point)
2651 current-prefix-arg arg)
2652 (throw 'exit nil))
2653
2654 (defun org-goto-left ()
2655 "Finish `org-goto' by going to the new location."
2656 (interactive)
2657 (if (org-on-heading-p)
2658 (progn
2659 (beginning-of-line 1)
2660 (setq org-selected-point (point)
2661 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2662 (throw 'exit nil))
2663 (error "Not on a heading")))
2664
2665 (defun org-goto-right ()
2666 "Finish `org-goto' by going to the new location."
2667 (interactive)
2668 (if (org-on-heading-p)
2669 (progn
2670 (outline-end-of-subtree)
2671 (or (eobp) (forward-char 1))
2672 (setq org-selected-point (point)
2673 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2674 (throw 'exit nil))
2675 (error "Not on a heading")))
2676
2677 (defun org-goto-quit ()
2678 "Finish `org-goto' without cursor motion."
2679 (interactive)
2680 (setq org-selected-point nil)
2681 (throw 'exit nil))
2682
2683 ;;; Promotion, Demotion, Inserting new headlines
2684
2685 (defvar org-ignore-region nil
2686 "To temporarily disable the active region.")
2687
2688 (defun org-insert-heading (&optional force-heading)
2689 "Insert a new heading or item with same depth at point."
2690 (interactive "P")
2691 (when (or force-heading (not (org-insert-item)))
2692 (let* ((head (save-excursion
2693 (condition-case nil
2694 (org-back-to-heading)
2695 (error (outline-next-heading)))
2696 (prog1 (match-string 0)
2697 (funcall outline-level)))))
2698 (unless (bolp) (newline))
2699 (insert head)
2700 (unless (eolp)
2701 (save-excursion (newline-and-indent)))
2702 (unless (equal (char-before) ?\ )
2703 (insert " "))
2704 (run-hooks 'org-insert-heading-hook))))
2705
2706 (defun org-insert-item ()
2707 "Insert a new item at the current level.
2708 Return t when things worked, nil when we are not in an item."
2709 (when (save-excursion
2710 (condition-case nil
2711 (progn
2712 (org-beginning-of-item)
2713 (org-at-item-p)
2714 t)
2715 (error nil)))
2716 (unless (bolp) (newline))
2717 (insert (match-string 0))
2718 (org-maybe-renumber-ordered-list)
2719 t))
2720
2721 (defun org-insert-todo-heading (arg)
2722 "Insert a new heading with the same level and TODO state as current heading.
2723 If the heading has no TODO state, or if the state is DONE, use the first
2724 state (TODO by default). Also with prefix arg, force first state."
2725 (interactive "P")
2726 (org-insert-heading)
2727 (save-excursion
2728 (org-back-to-heading)
2729 (outline-previous-heading)
2730 (looking-at org-todo-line-regexp))
2731 (if (or arg
2732 (not (match-beginning 2))
2733 (equal (match-string 2) org-done-string))
2734 (insert (car org-todo-keywords) " ")
2735 (insert (match-string 2) " ")))
2736
2737 (defun org-promote-subtree ()
2738 "Promote the entire subtree.
2739 See also `org-promote'."
2740 (interactive)
2741 (save-excursion
2742 (org-map-tree 'org-promote)))
2743
2744 (defun org-demote-subtree ()
2745 "Demote the entire subtree. See `org-demote'.
2746 See also `org-promote'."
2747 (interactive)
2748 (save-excursion
2749 (org-map-tree 'org-demote)))
2750
2751 (defun org-do-promote ()
2752 "Promote the current heading higher up the tree.
2753 If the region is active in `transient-mark-mode', promote all headings
2754 in the region."
2755 (interactive)
2756 (save-excursion
2757 (if (org-region-active-p)
2758 (org-map-region 'org-promote (region-beginning) (region-end))
2759 (org-promote)))
2760 (org-fix-position-after-promote))
2761
2762 (defun org-do-demote ()
2763 "Demote the current heading lower down the tree.
2764 If the region is active in `transient-mark-mode', demote all headings
2765 in the region."
2766 (interactive)
2767 (save-excursion
2768 (if (org-region-active-p)
2769 (org-map-region 'org-demote (region-beginning) (region-end))
2770 (org-demote)))
2771 (org-fix-position-after-promote))
2772
2773 (defun org-fix-position-after-promote ()
2774 "Make sure that after pro/demotion cursor position is right."
2775 (and (equal (char-after) ?\ )
2776 (equal (char-before) ?*)
2777 (forward-char 1)))
2778
2779 (defun org-get-legal-level (level change)
2780 "Rectify a level change under the influence of `org-odd-levels-only'
2781 LEVEL is a current level, CHANGE is by how much the level should be
2782 modified. Even if CHANGE is nil, LEVEL may be returned modified because
2783 even level numbers will become the next higher odd number."
2784 (if org-odd-levels-only
2785 (cond ((not change) (1+ (* 2 (/ level 2))))
2786 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
2787 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
2788 (max 1 (+ level change))))
2789
2790 (defun org-promote ()
2791 "Promote the current heading higher up the tree.
2792 If the region is active in `transient-mark-mode', promote all headings
2793 in the region."
2794 (org-back-to-heading t)
2795 (let* ((level (save-match-data (funcall outline-level)))
2796 (up-head (make-string (org-get-legal-level level -1) ?*))
2797 (diff (abs (- level (length up-head)))))
2798 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2799 (replace-match up-head nil t)
2800 ;; Fixup tag positioning
2801 (and org-auto-align-tags (org-set-tags nil t))
2802 (if org-adapt-indentation
2803 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
2804 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
2805
2806 (defun org-demote ()
2807 "Demote the current heading lower down the tree.
2808 If the region is active in `transient-mark-mode', demote all headings
2809 in the region."
2810 (org-back-to-heading t)
2811 (let* ((level (save-match-data (funcall outline-level)))
2812 (down-head (make-string (org-get-legal-level level 1) ?*))
2813 (diff (abs (- level (length down-head)))))
2814 (replace-match down-head nil t)
2815 ;; Fixup tag positioning
2816 (and org-auto-align-tags (org-set-tags nil t))
2817 (if org-adapt-indentation
2818 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
2819
2820 (defun org-map-tree (fun)
2821 "Call FUN for every heading underneath the current one."
2822 (org-back-to-heading)
2823 (let ((level (outline-level)))
2824 (save-excursion
2825 (funcall fun)
2826 (while (and (progn
2827 (outline-next-heading)
2828 (> (funcall outline-level) level))
2829 (not (eobp)))
2830 (funcall fun)))))
2831
2832 (defun org-map-region (fun beg end)
2833 "Call FUN for every heading between BEG and END."
2834 (let ((org-ignore-region t))
2835 (save-excursion
2836 (setq end (copy-marker end))
2837 (goto-char beg)
2838 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2839 (< (point) end))
2840 (funcall fun))
2841 (while (and (progn
2842 (outline-next-heading)
2843 (< (point) end))
2844 (not (eobp)))
2845 (funcall fun)))))
2846
2847 (defun org-fixup-indentation (from to prohibit)
2848 "Change the indentation in the current entry by re-replacing FROM with TO.
2849 However, if the regexp PROHIBIT matches at all, don't do anything.
2850 This is being used to change indentation along with the length of the
2851 heading marker. But if there are any lines which are not indented, nothing
2852 is changed at all."
2853 (save-excursion
2854 (let ((end (save-excursion (outline-next-heading)
2855 (point-marker))))
2856 (unless (save-excursion (re-search-forward prohibit end t))
2857 (while (re-search-forward from end t)
2858 (replace-match to)
2859 (beginning-of-line 2)))
2860 (move-marker end nil))))
2861
2862 ;;; Vertical tree motion, cutting and pasting of subtrees
2863
2864 (defun org-move-subtree-up (&optional arg)
2865 "Move the current subtree up past ARG headlines of the same level."
2866 (interactive "p")
2867 (org-move-subtree-down (- (prefix-numeric-value arg))))
2868
2869 (defun org-move-subtree-down (&optional arg)
2870 "Move the current subtree down past ARG headlines of the same level."
2871 (interactive "p")
2872 (setq arg (prefix-numeric-value arg))
2873 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2874 'outline-get-last-sibling))
2875 (ins-point (make-marker))
2876 (cnt (abs arg))
2877 beg end txt folded)
2878 ;; Select the tree
2879 (org-back-to-heading)
2880 (setq beg (point))
2881 (save-match-data
2882 (save-excursion (outline-end-of-heading)
2883 (setq folded (org-invisible-p)))
2884 (outline-end-of-subtree))
2885 (outline-next-heading)
2886 (setq end (point))
2887 ;; Find insertion point, with error handling
2888 (goto-char beg)
2889 (while (> cnt 0)
2890 (or (and (funcall movfunc) (looking-at outline-regexp))
2891 (progn (goto-char beg)
2892 (error "Cannot move past superior level or buffer limit")))
2893 (setq cnt (1- cnt)))
2894 (if (> arg 0)
2895 ;; Moving forward - still need to move over subtree
2896 (progn (outline-end-of-subtree)
2897 (outline-next-heading)
2898 (if (not (or (looking-at (concat "^" outline-regexp))
2899 (bolp)))
2900 (newline))))
2901 (move-marker ins-point (point))
2902 (setq txt (buffer-substring beg end))
2903 (delete-region beg end)
2904 (insert txt)
2905 (goto-char ins-point)
2906 (if folded (hide-subtree))
2907 (move-marker ins-point nil)))
2908
2909 (defvar org-subtree-clip ""
2910 "Clipboard for cut and paste of subtrees.
2911 This is actually only a copy of the kill, because we use the normal kill
2912 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2913
2914 (defvar org-subtree-clip-folded nil
2915 "Was the last copied subtree folded?
2916 This is used to fold the tree back after pasting.")
2917
2918 (defun org-cut-subtree ()
2919 "Cut the current subtree into the clipboard.
2920 This is a short-hand for marking the subtree and then cutting it."
2921 (interactive)
2922 (org-copy-subtree 'cut))
2923
2924 (defun org-copy-subtree (&optional cut)
2925 "Cut the current subtree into the clipboard.
2926 This is a short-hand for marking the subtree and then copying it.
2927 If CUT is non nil, actually cut the subtree."
2928 (interactive)
2929 (let (beg end folded)
2930 (org-back-to-heading)
2931 (setq beg (point))
2932 (save-match-data
2933 (save-excursion (outline-end-of-heading)
2934 (setq folded (org-invisible-p)))
2935 (outline-end-of-subtree))
2936 (if (equal (char-after) ?\n) (forward-char 1))
2937 (setq end (point))
2938 (goto-char beg)
2939 (when (> end beg)
2940 (setq org-subtree-clip-folded folded)
2941 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2942 (setq org-subtree-clip (current-kill 0))
2943 (message "%s: Subtree with %d characters"
2944 (if cut "Cut" "Copied")
2945 (length org-subtree-clip)))))
2946
2947 ;; FIXME: this needs to be adapted for the odd-level-only stuff.
2948 (defun org-paste-subtree (&optional level tree)
2949 "Paste the clipboard as a subtree, with modification of headline level.
2950 The entire subtree is promoted or demoted in order to match a new headline
2951 level. By default, the new level is derived from the visible headings
2952 before and after the insertion point, and taken to be the inferior headline
2953 level of the two. So if the previous visible heading is level 3 and the
2954 next is level 4 (or vice versa), level 4 will be used for insertion.
2955 This makes sure that the subtree remains an independent subtree and does
2956 not swallow low level entries.
2957
2958 You can also force a different level, either by using a numeric prefix
2959 argument, or by inserting the heading marker by hand. For example, if the
2960 cursor is after \"*****\", then the tree will be shifted to level 5.
2961
2962 If you want to insert the tree as is, just use \\[yank].
2963
2964 If optional TREE is given, use this text instead of the kill ring."
2965 (interactive "P")
2966 (unless (org-kill-is-subtree-p tree)
2967 (error
2968 (substitute-command-keys
2969 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2970 (let* ((txt (or tree (current-kill 0)))
2971 (^re (concat "^\\(" outline-regexp "\\)"))
2972 (re (concat "\\(" outline-regexp "\\)"))
2973 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2974
2975 (old-level (if (string-match ^re txt)
2976 (- (match-end 0) (match-beginning 0))
2977 -1))
2978 (force-level (cond (level (prefix-numeric-value level))
2979 ((string-match
2980 ^re_ (buffer-substring (point-at-bol) (point)))
2981 (- (match-end 0) (match-beginning 0)))
2982 (t nil)))
2983 (previous-level (save-excursion
2984 (condition-case nil
2985 (progn
2986 (outline-previous-visible-heading 1)
2987 (if (looking-at re)
2988 (- (match-end 0) (match-beginning 0))
2989 1))
2990 (error 1))))
2991 (next-level (save-excursion
2992 (condition-case nil
2993 (progn
2994 (outline-next-visible-heading 1)
2995 (if (looking-at re)
2996 (- (match-end 0) (match-beginning 0))
2997 1))
2998 (error 1))))
2999 (new-level (or force-level (max previous-level next-level)))
3000 (shift (if (or (= old-level -1)
3001 (= new-level -1)
3002 (= old-level new-level))
3003 0
3004 (- new-level old-level)))
3005 (shift1 shift)
3006 (delta (if (> shift 0) -1 1))
3007 (func (if (> shift 0) 'org-demote 'org-promote))
3008 (org-odd-levels-only nil)
3009 beg end)
3010 ;; Remove the forces level indicator
3011 (if force-level
3012 (delete-region (point-at-bol) (point)))
3013 ;; Make sure we start at the beginning of an empty line
3014 (if (not (bolp)) (insert "\n"))
3015 (if (not (looking-at "[ \t]*$"))
3016 (progn (insert "\n") (backward-char 1)))
3017 ;; Paste
3018 (setq beg (point))
3019 (insert txt)
3020 (setq end (point))
3021 (goto-char beg)
3022 ;; Shift if necessary
3023 (if (= shift 0)
3024 (message "Pasted at level %d, without shift" new-level)
3025 (save-restriction
3026 (narrow-to-region beg end)
3027 (while (not (= shift 0))
3028 (org-map-region func (point-min) (point-max))
3029 (setq shift (+ delta shift)))
3030 (goto-char (point-min))
3031 (message "Pasted at level %d, with shift by %d levels"
3032 new-level shift1)))
3033 (if (and (eq org-subtree-clip (current-kill 0))
3034 org-subtree-clip-folded)
3035 ;; The tree was folded before it was killed/copied
3036 (hide-subtree))))
3037
3038 (defun org-kill-is-subtree-p (&optional txt)
3039 "Check if the current kill is an outline subtree, or a set of trees.
3040 Returns nil if kill does not start with a headline, or if the first
3041 headline level is not the largest headline level in the tree.
3042 So this will actually accept several entries of equal levels as well,
3043 which is OK for `org-paste-subtree'.
3044 If optional TXT is given, check this string instead of the current kill."
3045 (let* ((kill (or txt (current-kill 0) ""))
3046 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3047 (- (match-end 0) (match-beginning 0))))
3048 (re (concat "^" outline-regexp))
3049 (start 1))
3050 (if (not start-level)
3051 nil ;; does not even start with a heading
3052 (catch 'exit
3053 (while (setq start (string-match re kill (1+ start)))
3054 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3055 (throw 'exit nil)))
3056 t))))
3057
3058 ;;; Plain list items
3059
3060 (defun org-at-item-p ()
3061 "Is point in a line starting a hand-formatted item?"
3062 (let ((llt org-plain-list-ordered-item-terminator))
3063 (save-excursion
3064 (goto-char (point-at-bol))
3065 (looking-at
3066 (cond
3067 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3068 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3069 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3070 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3071
3072 (defun org-get-indentation ()
3073 "Get the indentation of the current line, interpreting tabs."
3074 (save-excursion
3075 (beginning-of-line 1)
3076 (skip-chars-forward " \t")
3077 (current-column)))
3078
3079 (defun org-beginning-of-item ()
3080 "Go to the beginning of the current hand-formatted item.
3081 If the cursor is not in an item, throw an error."
3082 (let ((pos (point))
3083 (limit (save-excursion (org-back-to-heading)
3084 (beginning-of-line 2) (point)))
3085 ind ind1)
3086 (if (org-at-item-p)
3087 (beginning-of-line 1)
3088 (beginning-of-line 1)
3089 (skip-chars-forward " \t")
3090 (setq ind (current-column))
3091 (if (catch 'exit
3092 (while t
3093 (beginning-of-line 0)
3094 (if (< (point) limit) (throw 'exit nil))
3095 (unless (looking-at " \t]*$")
3096 (skip-chars-forward " \t")
3097 (setq ind1 (current-column))
3098 (if (< ind1 ind)
3099 (throw 'exit (org-at-item-p))))))
3100 nil
3101 (goto-char pos)
3102 (error "Not in an item")))))
3103
3104 (defun org-end-of-item ()
3105 "Go to the end of the current hand-formatted item.
3106 If the cursor is not in an item, throw an error."
3107 (let ((pos (point))
3108 (limit (save-excursion (outline-next-heading) (point)))
3109 (ind (save-excursion
3110 (org-beginning-of-item)
3111 (skip-chars-forward " \t")
3112 (current-column)))
3113 ind1)
3114 (if (catch 'exit
3115 (while t
3116 (beginning-of-line 2)
3117 (if (>= (point) limit) (throw 'exit t))
3118 (unless (looking-at "[ \t]*$")
3119 (skip-chars-forward " \t")
3120 (setq ind1 (current-column))
3121 (if (<= ind1 ind) (throw 'exit t)))))
3122 (beginning-of-line 1)
3123 (goto-char pos)
3124 (error "Not in an item"))))
3125
3126 (defun org-move-item-down (arg)
3127 "Move the plain list item at point down, i.e. swap with following item.
3128 Subitems (items with larger indentation) are considered part of the item,
3129 so this really moves item trees."
3130 (interactive "p")
3131 (let (beg end ind ind1 (pos (point)) txt)
3132 (org-beginning-of-item)
3133 (setq beg (point))
3134 (setq ind (org-get-indentation))
3135 (org-end-of-item)
3136 (setq end (point))
3137 (setq ind1 (org-get-indentation))
3138 (if (and (org-at-item-p) (= ind ind1))
3139 (progn
3140 (org-end-of-item)
3141 (setq txt (buffer-substring beg end))
3142 (save-excursion
3143 (delete-region beg end))
3144 (setq pos (point))
3145 (insert txt)
3146 (goto-char pos)
3147 (org-maybe-renumber-ordered-list))
3148 (goto-char pos)
3149 (error "Cannot move this item further down"))))
3150
3151 (defun org-move-item-up (arg)
3152 "Move the plain list item at point up, i.e. swap with previous item.
3153 Subitems (items with larger indentation) are considered part of the item,
3154 so this really moves item trees."
3155 (interactive "p")
3156 (let (beg end ind ind1 (pos (point)) txt)
3157 (org-beginning-of-item)
3158 (setq beg (point))
3159 (setq ind (org-get-indentation))
3160 (org-end-of-item)
3161 (setq end (point))
3162 (goto-char beg)
3163 (catch 'exit
3164 (while t
3165 (beginning-of-line 0)
3166 (if (looking-at "[ \t]*$")
3167 nil
3168 (if (<= (setq ind1 (org-get-indentation)) ind)
3169 (throw 'exit t)))))
3170 (condition-case nil
3171 (org-beginning-of-item)
3172 (error (goto-char beg)
3173 (error "Cannot move this item further up")))
3174 (setq ind1 (org-get-indentation))
3175 (if (and (org-at-item-p) (= ind ind1))
3176 (progn
3177 (setq txt (buffer-substring beg end))
3178 (save-excursion
3179 (delete-region beg end))
3180 (setq pos (point))
3181 (insert txt)
3182 (goto-char pos)
3183 (org-maybe-renumber-ordered-list))
3184 (goto-char pos)
3185 (error "Cannot move this item further up"))))
3186
3187 (defun org-maybe-renumber-ordered-list ()
3188 "Renumber the ordered list at point if setup allows it.
3189 This tests the user option `org-auto-renumber-ordered-lists' before
3190 doing the renumbering."
3191 (and org-auto-renumber-ordered-lists
3192 (org-at-item-p)
3193 (match-beginning 3)
3194 (org-renumber-ordered-list 1)))
3195
3196 (defun org-get-string-indentation (s)
3197 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3198 (let ((n -1) (i 0) (w tab-width) c)
3199 (catch 'exit
3200 (while (< (setq n (1+ n)) (length s))
3201 (setq c (aref s n))
3202 (cond ((= c ?\ ) (setq i (1+ i)))
3203 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3204 (t (throw 'exit t)))))
3205 i))
3206
3207 (defun org-renumber-ordered-list (arg)
3208 "Renumber an ordered plain list.
3209 Cursor next to be in the first line of an item, the line that starts
3210 with something like \"1.\" or \"2)\"."
3211 (interactive "p")
3212 (unless (and (org-at-item-p)
3213 (match-beginning 3))
3214 (error "This is not an ordered list"))
3215 (let ((line (org-current-line))
3216 (col (current-column))
3217 (ind (org-get-string-indentation
3218 (buffer-substring (point-at-bol) (match-beginning 3))))
3219 ;; (term (substring (match-string 3) -1))
3220 ind1 (n (1- arg)))
3221 ;; find where this list begins
3222 (catch 'exit
3223 (while t
3224 (catch 'next
3225 (beginning-of-line 0)
3226 (if (looking-at "[ \t]*$") (throw 'next t))
3227 (skip-chars-forward " \t") (setq ind1 (current-column))
3228 (if (or (< ind1 ind)
3229 (and (= ind1 ind)
3230 (not (org-at-item-p))))
3231 (throw 'exit t)))))
3232 ;; Walk forward and replace these numbers
3233 (catch 'exit
3234 (while t
3235 (catch 'next
3236 (beginning-of-line 2)
3237 (if (eobp) (throw 'exit nil))
3238 (if (looking-at "[ \t]*$") (throw 'next nil))
3239 (skip-chars-forward " \t") (setq ind1 (current-column))
3240 (if (> ind1 ind) (throw 'next t))
3241 (if (< ind1 ind) (throw 'exit t))
3242 (if (not (org-at-item-p)) (throw 'exit nil))
3243 (if (not (match-beginning 3))
3244 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3245 (delete-region (match-beginning 3) (1- (match-end 3)))
3246 (goto-char (match-beginning 3))
3247 (insert (format "%d" (setq n (1+ n)))))))
3248 (goto-line line)
3249 (move-to-column col)))
3250
3251 (defvar org-last-indent-begin-marker (make-marker))
3252 (defvar org-last-indent-end-marker (make-marker))
3253
3254
3255 (defun org-outdent-item (arg)
3256 "Outdent a local list item."
3257 (interactive "p")
3258 (org-indent-item (- arg)))
3259
3260 (defun org-indent-item (arg)
3261 "Indent a local list item."
3262 (interactive "p")
3263 (unless (org-at-item-p)
3264 (error "Not on an item"))
3265 (let (beg end ind ind1)
3266 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3267 (setq beg org-last-indent-begin-marker
3268 end org-last-indent-end-marker)
3269 (org-beginning-of-item)
3270 (setq beg (move-marker org-last-indent-begin-marker (point)))
3271 (org-end-of-item)
3272 (setq end (move-marker org-last-indent-end-marker (point))))
3273 (goto-char beg)
3274 (skip-chars-forward " \t") (setq ind (current-column))
3275 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3276 (while (< (point) end)
3277 (beginning-of-line 1)
3278 (skip-chars-forward " \t") (setq ind1 (current-column))
3279 (delete-region (point-at-bol) (point))
3280 (indent-to-column (+ ind1 arg))
3281 (beginning-of-line 2))
3282 (goto-char beg)))
3283
3284 ;;; Archiving
3285
3286 (defun org-archive-subtree ()
3287 "Move the current subtree to the archive.
3288 The archive can be a certain top-level heading in the current file, or in
3289 a different file. The tree will be moved to that location, the subtree
3290 heading be marked DONE, and the current time will be added."
3291 (interactive)
3292 ;; Save all relevant TODO keyword-relatex variables
3293 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3294 (tr-org-todo-keywords org-todo-keywords)
3295 (tr-org-todo-interpretation org-todo-interpretation)
3296 (tr-org-done-string org-done-string)
3297 (tr-org-todo-regexp org-todo-regexp)
3298 (tr-org-todo-line-regexp org-todo-line-regexp)
3299 (this-buffer (current-buffer))
3300 file heading buffer level newfile-p)
3301 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3302 (progn
3303 (setq file (format (match-string 1 org-archive-location)
3304 (file-name-nondirectory (buffer-file-name)))
3305 heading (match-string 2 org-archive-location)))
3306 (error "Invalid `org-archive-location'"))
3307 (if (> (length file) 0)
3308 (setq newfile-p (not (file-exists-p file))
3309 buffer (find-file-noselect file))
3310 (setq buffer (current-buffer)))
3311 (unless buffer
3312 (error "Cannot access file \"%s\"" file))
3313 (if (and (> (length heading) 0)
3314 (string-match "^\\*+" heading))
3315 (setq level (match-end 0))
3316 (setq heading nil level 0))
3317 (save-excursion
3318 ;; We first only copy, in case something goes wrong
3319 ;; we need to protect this-command, to avoid kill-region sets it,
3320 ;; which would lead to duplication of subtrees
3321 (let (this-command) (org-copy-subtree))
3322 (set-buffer buffer)
3323 ;; Enforce org-mode for the archive buffer
3324 (if (not (eq major-mode 'org-mode))
3325 ;; Force the mode for future visits.
3326 (let ((org-insert-mode-line-in-empty-file t))
3327 (call-interactively 'org-mode)))
3328 (when newfile-p
3329 (goto-char (point-max))
3330 (insert (format "\nArchived entries from file %s\n\n"
3331 (buffer-file-name this-buffer))))
3332 ;; Force the TODO keywords of the original buffer
3333 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3334 (org-todo-keywords tr-org-todo-keywords)
3335 (org-todo-interpretation tr-org-todo-interpretation)
3336 (org-done-string tr-org-done-string)
3337 (org-todo-regexp tr-org-todo-regexp)
3338 (org-todo-line-regexp tr-org-todo-line-regexp))
3339 (goto-char (point-min))
3340 (if heading
3341 (progn
3342 (if (re-search-forward
3343 (concat "\\(^\\|\r\\)"
3344 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3345 nil t)
3346 (goto-char (match-end 0))
3347 ;; Heading not found, just insert it at the end
3348 (goto-char (point-max))
3349 (or (bolp) (insert "\n"))
3350 (insert "\n" heading "\n")
3351 (end-of-line 0))
3352 ;; Make the heading visible, and the following as well
3353 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3354 (if (re-search-forward
3355 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3356 nil t)
3357 (progn (goto-char (match-beginning 0)) (insert "\n")
3358 (beginning-of-line 0))
3359 (goto-char (point-max)) (insert "\n")))
3360 (goto-char (point-max)) (insert "\n"))
3361 ;; Paste
3362 (org-paste-subtree (1+ level))
3363 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3364 (if org-archive-mark-done
3365 (org-todo (length org-todo-keywords)))
3366 ;; Move cursor to right after the TODO keyword
3367 (when org-archive-stamp-time
3368 (beginning-of-line 1)
3369 (looking-at org-todo-line-regexp)
3370 (goto-char (or (match-end 2) (match-beginning 3)))
3371 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3372 (current-time))
3373 ")"))
3374 ;; Save the buffer, if it is not the same buffer.
3375 (if (not (eq this-buffer buffer)) (save-buffer))))
3376 ;; Here we are back in the original buffer. Everything seems to have
3377 ;; worked. So now cut the tree and finish up.
3378 (let (this-command) (org-cut-subtree))
3379 (if (looking-at "[ \t]*$") (kill-line))
3380 (message "Subtree archived %s"
3381 (if (eq this-buffer buffer)
3382 (concat "under heading: " heading)
3383 (concat "in file: " (abbreviate-file-name file))))))
3384
3385 ;;; Completion
3386
3387 (defun org-complete (&optional arg)
3388 "Perform completion on word at point.
3389 At the beginning of a headline, this completes TODO keywords as given in
3390 `org-todo-keywords'.
3391 If the current word is preceded by a backslash, completes the TeX symbols
3392 that are supported for HTML support.
3393 If the current word is preceded by \"#+\", completes special words for
3394 setting file options.
3395 At all other locations, this simply calls `ispell-complete-word'."
3396 (interactive "P")
3397 (catch 'exit
3398 (let* ((end (point))
3399 (beg1 (save-excursion
3400 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3401 (skip-chars-backward "a-zA-Z_@0-9")
3402 (point)))
3403 (beg (save-excursion
3404 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3405 (skip-chars-backward "a-zA-Z0-9_:$")
3406 (point)))
3407 (camel (equal (char-before beg) ?*))
3408 (tag (equal (char-before beg1) ?:))
3409 (texp (equal (char-before beg) ?\\))
3410 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3411 beg)
3412 "#+"))
3413 (completion-ignore-case opt)
3414 (type nil)
3415 (tbl nil)
3416 (table (cond
3417 (opt
3418 (setq type :opt)
3419 (mapcar (lambda (x)
3420 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3421 (cons (match-string 2 x) (match-string 1 x)))
3422 (org-split-string (org-get-current-options) "\n")))
3423 (texp
3424 (setq type :tex)
3425 org-html-entities)
3426 ((string-match "\\`\\*+[ \t]*\\'"
3427 (buffer-substring (point-at-bol) beg))
3428 (setq type :todo)
3429 (mapcar 'list org-todo-keywords))
3430 (camel
3431 (setq type :camel)
3432 (save-excursion
3433 (goto-char (point-min))
3434 (while (re-search-forward org-todo-line-regexp nil t)
3435 (push (list
3436 (if org-file-link-context-use-camel-case
3437 (org-make-org-heading-camel (match-string 3) t)
3438 (org-make-org-heading-search-string
3439 (match-string 3) t)))
3440 tbl)))
3441 tbl)
3442 (tag (setq type :tag beg beg1)
3443 (org-get-buffer-tags))
3444 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3445 (pattern (buffer-substring-no-properties beg end))
3446 (completion (try-completion pattern table)))
3447 (cond ((eq completion t)
3448 (if (equal type :opt)
3449 (insert (substring (cdr (assoc (upcase pattern) table))
3450 (length pattern)))))
3451 ((null completion)
3452 (message "Can't find completion for \"%s\"" pattern)
3453 (ding))
3454 ((not (string= pattern completion))
3455 (delete-region beg end)
3456 (if (string-match " +$" completion)
3457 (setq completion (replace-match "" t t completion)))
3458 (insert completion)
3459 (if (get-buffer-window "*Completions*")
3460 (delete-window (get-buffer-window "*Completions*")))
3461 (if (assoc completion table)
3462 (if (eq type :todo) (insert " ")
3463 (if (eq type :tag) (insert ":"))))
3464 (if (and (equal type :opt) (assoc completion table))
3465 (message "%s" (substitute-command-keys
3466 "Press \\[org-complete] again to insert example settings"))))
3467 (t
3468 (message "Making completion list...")
3469 (let ((list (sort (all-completions pattern table) 'string<)))
3470 (with-output-to-temp-buffer "*Completions*"
3471 (display-completion-list list)))
3472 (message "Making completion list...%s" "done"))))))
3473
3474 ;;; Comments, TODO and DEADLINE
3475
3476 (defun org-toggle-comment ()
3477 "Change the COMMENT state of an entry."
3478 (interactive)
3479 (save-excursion
3480 (org-back-to-heading)
3481 (if (looking-at (concat outline-regexp
3482 "\\( +\\<" org-comment-string "\\>\\)"))
3483 (replace-match "" t t nil 1)
3484 (if (looking-at outline-regexp)
3485 (progn
3486 (goto-char (match-end 0))
3487 (insert " " org-comment-string))))))
3488
3489 (defvar org-last-todo-state-is-todo nil
3490 "This is non-nil when the last TODO state change led to a TODO state.
3491 If the last change removed the TODO tag or switched to DONE, then
3492 this is nil.")
3493
3494 (defun org-todo (&optional arg)
3495 "Change the TODO state of an item.
3496 The state of an item is given by a keyword at the start of the heading,
3497 like
3498 *** TODO Write paper
3499 *** DONE Call mom
3500
3501 The different keywords are specified in the variable `org-todo-keywords'.
3502 By default the available states are \"TODO\" and \"DONE\".
3503 So for this example: when the item starts with TODO, it is changed to DONE.
3504 When it starts with DONE, the DONE is removed. And when neither TODO nor
3505 DONE are present, add TODO at the beginning of the heading.
3506
3507 With prefix arg, use completion to determine the new state. With numeric
3508 prefix arg, switch to that state."
3509 (interactive "P")
3510 (save-excursion
3511 (org-back-to-heading)
3512 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3513 (or (looking-at (concat " +" org-todo-regexp " *"))
3514 (looking-at " *"))
3515 (let* ((this (match-string 1))
3516 (completion-ignore-case t)
3517 (member (member this org-todo-keywords))
3518 (tail (cdr member))
3519 (state (cond
3520 ((equal arg '(4))
3521 ;; Read a state with completion
3522 (completing-read "State: " (mapcar (lambda(x) (list x))
3523 org-todo-keywords)
3524 nil t))
3525 ((eq arg 'right)
3526 (if this
3527 (if tail (car tail) nil)
3528 (car org-todo-keywords)))
3529 ((eq arg 'left)
3530 (if (equal member org-todo-keywords)
3531 nil
3532 (if this
3533 (nth (- (length org-todo-keywords) (length tail) 2)
3534 org-todo-keywords)
3535 org-done-string)))
3536 (arg
3537 ;; user requests a specific state
3538 (nth (1- (prefix-numeric-value arg))
3539 org-todo-keywords))
3540 ((null member) (car org-todo-keywords))
3541 ((null tail) nil) ;; -> first entry
3542 ((eq org-todo-interpretation 'sequence)
3543 (car tail))
3544 ((memq org-todo-interpretation '(type priority))
3545 (if (eq this-command last-command)
3546 (car tail)
3547 (if (> (length tail) 0) org-done-string nil)))
3548 (t nil)))
3549 (next (if state (concat " " state " ") " ")))
3550 (replace-match next t t)
3551 (setq org-last-todo-state-is-todo
3552 (not (equal state org-done-string)))
3553 (when org-log-done
3554 (if (equal state org-done-string)
3555 (org-log-done)
3556 (if (not this)
3557 (org-log-done t))))
3558 ;; Fixup tag positioning
3559 (and org-auto-align-tags (org-set-tags nil t))
3560 (run-hooks 'org-after-todo-state-change-hook)))
3561 ;; Fixup cursor location if close to the keyword
3562 (if (and (outline-on-heading-p)
3563 (not (bolp))
3564 (save-excursion (beginning-of-line 1)
3565 (looking-at org-todo-line-regexp))
3566 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3567 (progn
3568 (goto-char (or (match-end 2) (match-end 1)))
3569 (just-one-space))))
3570
3571 (defun org-log-done (&optional undone)
3572 "Add a time stamp logging that a TODO entry has been closed.
3573 When UNDONE is non-nil, remove such a time stamp again."
3574 (interactive)
3575 (let (beg end col)
3576 (save-excursion
3577 (org-back-to-heading t)
3578 (setq beg (point))
3579 (looking-at (concat outline-regexp " *"))
3580 (goto-char (match-end 0))
3581 (setq col (current-column))
3582 (outline-next-heading)
3583 (setq end (point))
3584 (goto-char beg)
3585 (when (re-search-forward (concat
3586 "[\r\n]\\([ \t]*"
3587 (regexp-quote org-closed-string)
3588 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3589 (delete-region (match-beginning 1) (match-end 1)))
3590 (unless undone
3591 (org-back-to-heading t)
3592 (skip-chars-forward "^\n\r")
3593 (goto-char (min (1+ (point)) (point-max)))
3594 (when (not (member (char-before) '(?\r ?\n)))
3595 (insert "\n"))
3596 (indent-to col)
3597 (insert org-closed-string " "
3598 (format-time-string
3599 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3600 (current-time))
3601 "\n")))))
3602
3603 (defun org-show-todo-tree (arg)
3604 "Make a compact tree which shows all headlines marked with TODO.
3605 The tree will show the lines where the regexp matches, and all higher
3606 headlines above the match.
3607 With \\[universal-argument] prefix, also show the DONE entries.
3608 With a numeric prefix N, construct a sparse tree for the Nth element
3609 of `org-todo-keywords'."
3610 (interactive "P")
3611 (let ((case-fold-search nil)
3612 (kwd-re
3613 (cond ((null arg) org-not-done-regexp)
3614 ((equal arg '(4)) org-todo-regexp)
3615 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3616 (regexp-quote (nth (1- (prefix-numeric-value arg))
3617 org-todo-keywords)))
3618 (t (error "Invalid prefix argument: %s" arg)))))
3619 (message "%d TODO entries found"
3620 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3621
3622 (defun org-deadline ()
3623 "Insert the DEADLINE: string to make a deadline.
3624 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3625 to modify it to the correct date."
3626 (interactive)
3627 (insert
3628 org-deadline-string " "
3629 (format-time-string (car org-time-stamp-formats)
3630 (org-read-date nil 'to-time)))
3631 (message "%s" (substitute-command-keys
3632 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3633
3634 (defun org-schedule ()
3635 "Insert the SCHEDULED: string to schedule a TODO item.
3636 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3637 to modify it to the correct date."
3638 (interactive)
3639 (insert
3640 org-scheduled-string " "
3641 (format-time-string (car org-time-stamp-formats)
3642 (org-read-date nil 'to-time)))
3643 (message "%s" (substitute-command-keys
3644 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3645
3646
3647 (defun org-occur (regexp &optional callback)
3648 "Make a compact tree which shows all matches of REGEXP.
3649 The tree will show the lines where the regexp matches, and all higher
3650 headlines above the match. It will also show the heading after the match,
3651 to make sure editing the matching entry is easy.
3652 If CALLBACK is non-nil, it is a function which is called to confirm
3653 that the match should indeed be shown."
3654 (interactive "sRegexp: ")
3655 (org-remove-occur-highlights nil nil t)
3656 (setq regexp (org-check-occur-regexp regexp))
3657 (let ((cnt 0))
3658 (save-excursion
3659 (goto-char (point-min))
3660 (hide-sublevels 1)
3661 (while (re-search-forward regexp nil t)
3662 (when (or (not callback)
3663 (save-match-data (funcall callback)))
3664 (setq cnt (1+ cnt))
3665 (org-highlight-new-match (match-beginning 0) (match-end 0))
3666 (org-show-hierarchy-above))))
3667 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
3668 nil 'local)
3669 (run-hooks 'org-occur-hook)
3670 (if (interactive-p)
3671 (message "%d match(es) for regexp %s" cnt regexp))
3672 cnt))
3673
3674 (defun org-show-hierarchy-above ()
3675 "Make sure point and the headings hierarchy above is visible."
3676 (catch 'exit
3677 (if (org-on-heading-p t)
3678 (org-flag-heading nil) ; only show the heading
3679 (and (or (org-invisible-p) (org-invisible-p2))
3680 (org-show-hidden-entry))) ; show entire entry
3681 (save-excursion
3682 (and org-show-following-heading
3683 (outline-next-heading)
3684 (org-flag-heading nil))) ; show the next heading
3685 (when org-show-hierarchy-above
3686 (save-excursion ; show all higher headings
3687 (while (and (condition-case nil
3688 (progn (org-up-heading-all 1) t)
3689 (error nil))
3690 (not (bobp)))
3691 (org-flag-heading nil))))))
3692
3693 ;; Overlay compatibility functions
3694 (defun org-make-overlay (beg end &optional buffer)
3695 (if org-xemacs-p (make-extent beg end buffer) (make-overlay beg end buffer)))
3696 (defun org-delete-overlay (ovl)
3697 (if org-xemacs-p (delete-extent ovl) (delete-overlay ovl)))
3698 (defun org-detatch-overlay (ovl)
3699 (if org-xemacs-p (detach-extent ovl) (delete-overlay ovl)))
3700 (defun org-move-overlay (ovl beg end &optional buffer)
3701 (if org-xemacs-p
3702 (set-extent-endpoints ovl beg end buffer)
3703 (move-overlay ovl beg end buffer)))
3704 (defun org-overlay-put (ovl prop value)
3705 (if org-xemacs-p
3706 (set-extent-property ovl prop value)
3707 (overlay-put ovl prop value)))
3708
3709 (defvar org-occur-highlights nil)
3710 (defun org-highlight-new-match (beg end)
3711 "Highlight from BEG to END and mark the highlight is an occur headline."
3712 (let ((ov (org-make-overlay beg end)))
3713 (org-overlay-put ov 'face 'secondary-selection)
3714 (push ov org-occur-highlights)))
3715
3716 (defun org-remove-occur-highlights (&optional beg end noremove)
3717 "Remove the occur highlights from the buffer.
3718 BEG and END are ignored. If NOREMOVE is nil, remove this function
3719 from the `before-change-functions' in the current buffer."
3720 (interactive)
3721 (mapc 'org-delete-overlay org-occur-highlights)
3722 (setq org-occur-highlights nil)
3723 (unless noremove
3724 (remove-hook 'before-change-functions
3725 'org-remove-occur-highlights 'local)))
3726
3727 ;;; Priorities
3728
3729 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3730 "Regular expression matching the priority indicator.")
3731
3732 (defvar org-remove-priority-next-time nil)
3733
3734 (defun org-priority-up ()
3735 "Increase the priority of the current item."
3736 (interactive)
3737 (org-priority 'up))
3738
3739 (defun org-priority-down ()
3740 "Decrease the priority of the current item."
3741 (interactive)
3742 (org-priority 'down))
3743
3744 (defun org-priority (&optional action)
3745 "Change the priority of an item by ARG.
3746 ACTION can be set, up, or down."
3747 (interactive)
3748 (setq action (or action 'set))
3749 (let (current new news have remove)
3750 (save-excursion
3751 (org-back-to-heading)
3752 (if (looking-at org-priority-regexp)
3753 (setq current (string-to-char (match-string 2))
3754 have t)
3755 (setq current org-default-priority))
3756 (cond
3757 ((eq action 'set)
3758 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3759 (setq new (read-char-exclusive))
3760 (cond ((equal new ?\ ) (setq remove t))
3761 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3762 (error "Priority must be between `%c' and `%c'"
3763 ?A org-lowest-priority))))
3764 ((eq action 'up)
3765 (setq new (1- current)))
3766 ((eq action 'down)
3767 (setq new (1+ current)))
3768 (t (error "Invalid action")))
3769 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3770 (setq news (format "%c" new))
3771 (if have
3772 (if remove
3773 (replace-match "" t t nil 1)
3774 (replace-match news t t nil 2))
3775 (if remove
3776 (error "No priority cookie found in line")
3777 (looking-at org-todo-line-regexp)
3778 (if (match-end 2)
3779 (progn
3780 (goto-char (match-end 2))
3781 (insert " [#" news "]"))
3782 (goto-char (match-beginning 3))
3783 (insert "[#" news "] ")))))
3784 (if remove
3785 (message "Priority removed")
3786 (message "Priority of current item set to %s" news))))
3787
3788
3789 (defun org-get-priority (s)
3790 "Find priority cookie and return priority."
3791 (save-match-data
3792 (if (not (string-match org-priority-regexp s))
3793 (* 1000 (- org-lowest-priority org-default-priority))
3794 (* 1000 (- org-lowest-priority
3795 (string-to-char (match-string 2 s)))))))
3796
3797 ;;; Timestamps
3798
3799 (defvar org-last-changed-timestamp nil)
3800
3801 (defun org-time-stamp (arg)
3802 "Prompt for a date/time and insert a time stamp.
3803 If the user specifies a time like HH:MM, or if this command is called
3804 with a prefix argument, the time stamp will contain date and time.
3805 Otherwise, only the date will be included. All parts of a date not
3806 specified by the user will be filled in from the current date/time.
3807 So if you press just return without typing anything, the time stamp
3808 will represent the current date/time. If there is already a timestamp
3809 at the cursor, it will be modified."
3810 (interactive "P")
3811 (let ((fmt (if arg (cdr org-time-stamp-formats)
3812 (car org-time-stamp-formats)))
3813 (org-time-was-given nil)
3814 time)
3815 (cond
3816 ((and (org-at-timestamp-p)
3817 (eq last-command 'org-time-stamp)
3818 (eq this-command 'org-time-stamp))
3819 (insert "--")
3820 (setq time (let ((this-command this-command))
3821 (org-read-date arg 'totime)))
3822 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3823 (insert (format-time-string fmt time)))
3824 ((org-at-timestamp-p)
3825 (setq time (let ((this-command this-command))
3826 (org-read-date arg 'totime)))
3827 (and (org-at-timestamp-p) (replace-match
3828 (setq org-last-changed-timestamp
3829 (format-time-string fmt time))
3830 t t))
3831 (message "Timestamp updated"))
3832 (t
3833 (setq time (let ((this-command this-command))
3834 (org-read-date arg 'totime)))
3835 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3836 (insert (format-time-string fmt time))))))
3837
3838 (defun org-time-stamp-inactive (&optional arg)
3839 "Insert an inactive time stamp.
3840 An inactive time stamp is enclosed in square brackets instead of angle
3841 brackets. It is inactive in the sense that it does not trigger agenda entries,
3842 does not link to the calendar and cannot be changed with the S-cursor keys.
3843 So these are more for recording a certain time/date."
3844 ;; FIXME: Would it be better not to ask for a date/time here?
3845 (interactive "P")
3846 (let ((fmt (if arg (cdr org-time-stamp-formats)
3847 (car org-time-stamp-formats)))
3848 (org-time-was-given nil)
3849 time)
3850 (setq time (org-read-date arg 'totime))
3851 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3852 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3853 (insert (format-time-string fmt time))))
3854
3855 (defvar org-date-ovl (org-make-overlay 1 1))
3856 (org-overlay-put org-date-ovl 'face 'org-warning)
3857 (org-detatch-overlay org-date-ovl)
3858
3859 ;;; FIXME: Make the function take "Fri" as "next friday"
3860 ;;; because these are mostly being used to record the current time.
3861 (defun org-read-date (&optional with-time to-time)
3862 "Read a date and make things smooth for the user.
3863 The prompt will suggest to enter an ISO date, but you can also enter anything
3864 which will at least partially be understood by `parse-time-string'.
3865 Unrecognized parts of the date will default to the current day, month, year,
3866 hour and minute. For example,
3867 3-2-5 --> 2003-02-05
3868 feb 15 --> currentyear-02-15
3869 sep 12 9 --> 2009-09-12
3870 12:45 --> today 12:45
3871 22 sept 0:34 --> currentyear-09-22 0:34
3872 12 --> currentyear-currentmonth-12
3873 etc.
3874 The function understands only English month and weekday abbreviations,
3875 but this can be configured with the variables `parse-time-months' and
3876 `parse-time-weekdays'.
3877
3878 While prompting, a calendar is popped up - you can also select the
3879 date with the mouse (button 1). The calendar shows a period of three
3880 months. To scroll it to other months, use the keys `>' and `<'.
3881 If you don't like the calendar, turn it off with
3882 \(setq org-popup-calendar-for-date-prompt nil)
3883
3884 With optional argument TO-TIME, the date will immediately be converted
3885 to an internal time.
3886 With an optional argument WITH-TIME, the prompt will suggest to also
3887 insert a time. Note that when WITH-TIME is not set, you can still
3888 enter a time, and this function will inform the calling routine about
3889 this change. The calling routine may then choose to change the format
3890 used to insert the time stamp into the buffer to include the time."
3891 (require 'parse-time)
3892 (let* ((default-time
3893 ;; Default time is either today, or, when entering a range,
3894 ;; the range start.
3895 (if (save-excursion
3896 (re-search-backward
3897 (concat org-ts-regexp "--\\=")
3898 (- (point) 20) t))
3899 (apply
3900 'encode-time
3901 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3902 (parse-time-string (match-string 1))))
3903 (current-time)))
3904 (calendar-move-hook nil)
3905 (view-diary-entries-initially nil)
3906 (timestr (format-time-string
3907 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3908 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3909 ans ans1 ans2
3910 second minute hour day month year tl)
3911
3912 (if org-popup-calendar-for-date-prompt
3913 ;; Also show a calendar for date selection
3914 ;; Copied (with modifications) from planner.el by John Wiegley
3915 (save-excursion
3916 (save-window-excursion
3917 (calendar)
3918 (calendar-forward-day (- (time-to-days default-time)
3919 (calendar-absolute-from-gregorian
3920 (calendar-current-date))))
3921 (org-eval-in-calendar nil)
3922 (let* ((old-map (current-local-map))
3923 (map (copy-keymap calendar-mode-map))
3924 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3925 (define-key map (kbd "RET") 'org-calendar-select)
3926 (define-key map (if org-xemacs-p [button1] [mouse-1])
3927 'org-calendar-select-mouse)
3928 (define-key map (if org-xemacs-p [button2] [mouse-2])
3929 'org-calendar-select-mouse)
3930 (define-key minibuffer-local-map [(meta shift left)]
3931 (lambda () (interactive)
3932 (org-eval-in-calendar '(calendar-backward-month 1))))
3933 (define-key minibuffer-local-map [(meta shift right)]
3934 (lambda () (interactive)
3935 (org-eval-in-calendar '(calendar-forward-month 1))))
3936 (define-key minibuffer-local-map [(shift up)]
3937 (lambda () (interactive)
3938 (org-eval-in-calendar '(calendar-backward-week 1))))
3939 (define-key minibuffer-local-map [(shift down)]
3940 (lambda () (interactive)
3941 (org-eval-in-calendar '(calendar-forward-week 1))))
3942 (define-key minibuffer-local-map [(shift left)]
3943 (lambda () (interactive)
3944 (org-eval-in-calendar '(calendar-backward-day 1))))
3945 (define-key minibuffer-local-map [(shift right)]
3946 (lambda () (interactive)
3947 (org-eval-in-calendar '(calendar-forward-day 1))))
3948 (define-key minibuffer-local-map ">"
3949 (lambda () (interactive)
3950 (org-eval-in-calendar '(scroll-calendar-left 1))))
3951 (define-key minibuffer-local-map "<"
3952 (lambda () (interactive)
3953 (org-eval-in-calendar '(scroll-calendar-right 1))))
3954 (unwind-protect
3955 (progn
3956 (use-local-map map)
3957 (setq ans (read-string prompt "" nil nil))
3958 (if (not (string-match "\\S-" ans)) (setq ans nil))
3959 (setq ans (or ans1 ans ans2)))
3960 (use-local-map old-map)))))
3961 ;; Naked prompt only
3962 (setq ans (read-string prompt "" nil timestr)))
3963 (org-detatch-overlay org-date-ovl)
3964
3965 (if (string-match
3966 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3967 (progn
3968 (setq year (if (match-end 2)
3969 (string-to-number (match-string 2 ans))
3970 (string-to-number (format-time-string "%Y")))
3971 month (string-to-number (match-string 3 ans))
3972 day (string-to-number (match-string 4 ans)))
3973 (if (< year 100) (setq year (+ 2000 year)))
3974 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3975 t t ans))))
3976 (setq tl (parse-time-string ans)
3977 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3978 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3979 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3980 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3981 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3982 second (or (nth 0 tl) 0))
3983 (if (and (boundp 'org-time-was-given)
3984 (nth 2 tl))
3985 (setq org-time-was-given t))
3986 (if (< year 100) (setq year (+ 2000 year)))
3987 (if to-time
3988 (encode-time second minute hour day month year)
3989 (if (or (nth 1 tl) (nth 2 tl))
3990 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3991 (format "%04d-%02d-%02d" year month day)))))
3992
3993 (defun org-eval-in-calendar (form)
3994 "Eval FORM in the calendar window and return to current window.
3995 Also, store the cursor date in variable ans2."
3996 (let ((sw (selected-window)))
3997 (select-window (get-buffer-window "*Calendar*"))
3998 (eval form)
3999 (when (calendar-cursor-to-date)
4000 (let* ((date (calendar-cursor-to-date))
4001 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4002 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4003 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4004 (select-window sw)))
4005
4006 (defun org-calendar-select ()
4007 "Return to `org-read-date' with the date currently selected.
4008 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4009 (interactive)
4010 (when (calendar-cursor-to-date)
4011 (let* ((date (calendar-cursor-to-date))
4012 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4013 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4014 (if (active-minibuffer-window) (exit-minibuffer))))
4015
4016 (defun org-calendar-select-mouse (ev)
4017 "Return to `org-read-date' with the date currently selected.
4018 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4019 (interactive "e")
4020 (mouse-set-point ev)
4021 (when (calendar-cursor-to-date)
4022 (let* ((date (calendar-cursor-to-date))
4023 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4024 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4025 (if (active-minibuffer-window) (exit-minibuffer))))
4026
4027 (defun org-check-deadlines (ndays)
4028 "Check if there are any deadlines due or past due.
4029 A deadline is considered due if it happens within `org-deadline-warning-days'
4030 days from today's date. If the deadline appears in an entry marked DONE,
4031 it is not shown. The prefix arg NDAYS can be used to test that many
4032 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4033 (interactive "P")
4034 (let* ((org-warn-days
4035 (cond
4036 ((equal ndays '(4)) 100000)
4037 (ndays (prefix-numeric-value ndays))
4038 (t org-deadline-warning-days)))
4039 (case-fold-search nil)
4040 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4041 (callback
4042 (lambda ()
4043 (and (let ((d1 (time-to-days (current-time)))
4044 (d2 (time-to-days
4045 (org-time-string-to-time (match-string 1)))))
4046 (< (- d2 d1) org-warn-days))
4047 (not (org-entry-is-done-p))))))
4048 (message "%d deadlines past-due or due within %d days"
4049 (org-occur regexp callback)
4050 org-warn-days)))
4051
4052 (defun org-evaluate-time-range (&optional to-buffer)
4053 "Evaluate a time range by computing the difference between start and end.
4054 Normally the result is just printed in the echo area, but with prefix arg
4055 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4056 If the time range is actually in a table, the result is inserted into the
4057 next column.
4058 For time difference computation, a year is assumed to be exactly 365
4059 days in order to avoid rounding problems."
4060 (interactive "P")
4061 (save-excursion
4062 (unless (org-at-date-range-p)
4063 (goto-char (point-at-bol))
4064 (re-search-forward org-tr-regexp (point-at-eol) t))
4065 (if (not (org-at-date-range-p))
4066 (error "Not at a time-stamp range, and none found in current line")))
4067 (let* ((ts1 (match-string 1))
4068 (ts2 (match-string 2))
4069 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4070 (match-end (match-end 0))
4071 (time1 (org-time-string-to-time ts1))
4072 (time2 (org-time-string-to-time ts2))
4073 (t1 (time-to-seconds time1))
4074 (t2 (time-to-seconds time2))
4075 (diff (abs (- t2 t1)))
4076 (negative (< (- t2 t1) 0))
4077 ;; (ys (floor (* 365 24 60 60)))
4078 (ds (* 24 60 60))
4079 (hs (* 60 60))
4080 (fy "%dy %dd %02d:%02d")
4081 (fy1 "%dy %dd")
4082 (fd "%dd %02d:%02d")
4083 (fd1 "%dd")
4084 (fh "%02d:%02d")
4085 y d h m align)
4086 ;; FIXME: Should I re-introduce years, make year refer to same date?
4087 ;; This would be the only useful way to have years, actually.
4088 (if havetime
4089 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4090 y 0
4091 d (floor (/ diff ds)) diff (mod diff ds)
4092 h (floor (/ diff hs)) diff (mod diff hs)
4093 m (floor (/ diff 60)))
4094 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4095 y 0
4096 d (floor (+ (/ diff ds) 0.5))
4097 h 0 m 0))
4098 (if (not to-buffer)
4099 (message (org-make-tdiff-string y d h m))
4100 (when (org-at-table-p)
4101 (goto-char match-end)
4102 (setq align t)
4103 (and (looking-at " *|") (goto-char (match-end 0))))
4104 (if (looking-at
4105 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4106 (replace-match ""))
4107 (if negative (insert " -"))
4108 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4109 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4110 (insert " " (format fh h m))))
4111 (if align (org-table-align))
4112 (message "Time difference inserted"))))
4113
4114 (defun org-make-tdiff-string (y d h m)
4115 (let ((fmt "")
4116 (l nil))
4117 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4118 l (push y l)))
4119 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4120 l (push d l)))
4121 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4122 l (push h l)))
4123 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4124 l (push m l)))
4125 (apply 'format fmt (nreverse l))))
4126
4127 (defun org-time-string-to-time (s)
4128 (apply 'encode-time (org-parse-time-string s)))
4129
4130 (defun org-parse-time-string (s &optional nodefault)
4131 "Parse the standard Org-mode time string.
4132 This should be a lot faster than the normal `parse-time-string'.
4133 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4134 hour and minute fields will be nil if not given."
4135 (if (string-match org-ts-regexp1 s)
4136 (list 0
4137 (if (or (match-beginning 8) (not nodefault))
4138 (string-to-number (or (match-string 8 s) "0")))
4139 (if (or (match-beginning 7) (not nodefault))
4140 (string-to-number (or (match-string 7 s) "0")))
4141 (string-to-number (match-string 4 s))
4142 (string-to-number (match-string 3 s))
4143 (string-to-number (match-string 2 s))
4144 nil nil nil)
4145 (make-list 9 0)))
4146
4147 (defun org-timestamp-up (&optional arg)
4148 "Increase the date item at the cursor by one.
4149 If the cursor is on the year, change the year. If it is on the month or
4150 the day, change that.
4151 With prefix ARG, change by that many units."
4152 (interactive "p")
4153 (org-timestamp-change (prefix-numeric-value arg)))
4154
4155 (defun org-timestamp-down (&optional arg)
4156 "Decrease the date item at the cursor by one.
4157 If the cursor is on the year, change the year. If it is on the month or
4158 the day, change that.
4159 With prefix ARG, change by that many units."
4160 (interactive "p")
4161 (org-timestamp-change (- (prefix-numeric-value arg))))
4162
4163 (defun org-timestamp-up-day (&optional arg)
4164 "Increase the date in the time stamp by one day.
4165 With prefix ARG, change that many days."
4166 (interactive "p")
4167 (if (and (not (org-at-timestamp-p))
4168 (org-on-heading-p))
4169 (org-todo 'up)
4170 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4171
4172 (defun org-timestamp-down-day (&optional arg)
4173 "Decrease the date in the time stamp by one day.
4174 With prefix ARG, change that many days."
4175 (interactive "p")
4176 (if (and (not (org-at-timestamp-p))
4177 (org-on-heading-p))
4178 (org-todo 'down)
4179 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4180
4181 (defsubst org-pos-in-match-range (pos n)
4182 (and (match-beginning n)
4183 (<= (match-beginning n) pos)
4184 (>= (match-end n) pos)))
4185
4186 (defun org-at-timestamp-p ()
4187 "Determine if the cursor is in or at a timestamp."
4188 (interactive)
4189 (let* ((tsr org-ts-regexp2)
4190 (pos (point))
4191 (ans (or (looking-at tsr)
4192 (save-excursion
4193 (skip-chars-backward "^<\n\r\t")
4194 (if (> (point) 1) (backward-char 1))
4195 (and (looking-at tsr)
4196 (> (- (match-end 0) pos) -1))))))
4197 (and (boundp 'org-ts-what)
4198 (setq org-ts-what
4199 (cond
4200 ((org-pos-in-match-range pos 2) 'year)
4201 ((org-pos-in-match-range pos 3) 'month)
4202 ((org-pos-in-match-range pos 7) 'hour)
4203 ((org-pos-in-match-range pos 8) 'minute)
4204 ((or (org-pos-in-match-range pos 4)
4205 (org-pos-in-match-range pos 5)) 'day)
4206 (t 'day))))
4207 ans))
4208
4209 (defun org-timestamp-change (n &optional what)
4210 "Change the date in the time stamp at point.
4211 The date will be changed by N times WHAT. WHAT can be `day', `month',
4212 `year', `minute', `second'. If WHAT is not given, the cursor position
4213 in the timestamp determines what will be changed."
4214 (let ((fmt (car org-time-stamp-formats))
4215 org-ts-what
4216 (pos (point))
4217 ts time time0)
4218 (if (not (org-at-timestamp-p))
4219 (error "Not at a timestamp"))
4220 (setq org-ts-what (or what org-ts-what))
4221 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4222 (- (match-end 0) (match-beginning 0))))
4223 1)
4224 (cdr org-time-stamp-formats)
4225 (car org-time-stamp-formats)))
4226 (setq ts (match-string 0))
4227 (replace-match "")
4228 (setq time0 (org-parse-time-string ts))
4229 (setq time
4230 (apply 'encode-time
4231 (append
4232 (list (or (car time0) 0))
4233 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4234 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4235 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4236 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4237 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4238 (nthcdr 6 time0))))
4239 (if (eq what 'calendar)
4240 (let ((cal-date
4241 (save-excursion
4242 (save-match-data
4243 (set-buffer "*Calendar*")
4244 (calendar-cursor-to-date)))))
4245 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4246 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4247 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4248 (setcar time0 (or (car time0) 0))
4249 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4250 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4251 (setq time (apply 'encode-time time0))))
4252 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4253 (goto-char pos)
4254 ;; Try to recenter the calendar window, if any
4255 (if (and org-calendar-follow-timestamp-change
4256 (get-buffer-window "*Calendar*" t)
4257 (memq org-ts-what '(day month year)))
4258 (org-recenter-calendar (time-to-days time)))))
4259
4260 (defun org-recenter-calendar (date)
4261 "If the calendar is visible, recenter it to DATE."
4262 (let* ((win (selected-window))
4263 (cwin (get-buffer-window "*Calendar*" t))
4264 (calendar-move-hook nil))
4265 (when cwin
4266 (select-window cwin)
4267 (calendar-goto-date (if (listp date) date
4268 (calendar-gregorian-from-absolute date)))
4269 (select-window win))))
4270
4271 (defun org-goto-calendar (&optional arg)
4272 "Go to the Emacs calendar at the current date.
4273 If there is a time stamp in the current line, go to that date.
4274 A prefix ARG can be used to force the current date."
4275 (interactive "P")
4276 (let ((tsr org-ts-regexp) diff
4277 (calendar-move-hook nil)
4278 (view-diary-entries-initially nil))
4279 (if (or (org-at-timestamp-p)
4280 (save-excursion
4281 (beginning-of-line 1)
4282 (looking-at (concat ".*" tsr))))
4283 (let ((d1 (time-to-days (current-time)))
4284 (d2 (time-to-days
4285 (org-time-string-to-time (match-string 1)))))
4286 (setq diff (- d2 d1))))
4287 (calendar)
4288 (calendar-goto-today)
4289 (if (and diff (not arg)) (calendar-forward-day diff))))
4290
4291 (defun org-date-from-calendar ()
4292 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4293 If there is already a time stamp at the cursor position, update it."
4294 (interactive)
4295 (org-timestamp-change 0 'calendar))
4296
4297 ;;; Agenda, and Diary Integration
4298
4299 ;;; Define the mode
4300
4301 (defvar org-agenda-mode-map (make-sparse-keymap)
4302 "Keymap for `org-agenda-mode'.")
4303
4304 (defvar org-agenda-menu)
4305 (defvar org-agenda-follow-mode nil)
4306 (defvar org-agenda-show-log nil)
4307 (defvar org-agenda-buffer-name "*Org Agenda*")
4308 (defvar org-agenda-redo-command nil)
4309 (defvar org-agenda-mode-hook nil)
4310 (defvar org-agenda-type nil)
4311 (defvar org-agenda-force-single-file nil)
4312
4313 ;;;###autoload
4314 (defun org-agenda-mode ()
4315 "Mode for time-sorted view on action items in Org-mode files.
4316
4317 The following commands are available:
4318
4319 \\{org-agenda-mode-map}"
4320 (interactive)
4321 (kill-all-local-variables)
4322 (setq major-mode 'org-agenda-mode)
4323 (setq mode-name "Org-Agenda")
4324 (use-local-map org-agenda-mode-map)
4325 (easy-menu-add org-agenda-menu)
4326 (if org-startup-truncated (setq truncate-lines t))
4327 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4328 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4329 (unless org-agenda-keep-modes
4330 (setq org-agenda-follow-mode nil
4331 org-agenda-show-log nil))
4332 (easy-menu-change
4333 '("Agenda") "Agenda Files"
4334 (append
4335 (list
4336 (vector
4337 (if (get 'org-agenda-files 'org-restrict)
4338 "Restricted to single file"
4339 "Edit File List")
4340 '(customize-variable 'org-agenda-files)
4341 (not (get 'org-agenda-files 'org-restrict)))
4342 "--")
4343 (mapcar 'org-file-menu-entry (org-agenda-files))))
4344 (org-agenda-set-mode-name)
4345 (apply
4346 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4347 (list 'org-agenda-mode-hook)))
4348
4349 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4350 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4351 (define-key org-agenda-mode-map " " 'org-agenda-show)
4352 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4353 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4354 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4355 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4356 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4357 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4358 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4359 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4360 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4361 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4362 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4363 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4364
4365 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4366 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4367 (while l (define-key org-agenda-mode-map
4368 (int-to-string (pop l)) 'digit-argument)))
4369
4370 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4371 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4372 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4373 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4374 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4375 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4376 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4377 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4378 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4379 (define-key org-agenda-mode-map "n" 'next-line)
4380 (define-key org-agenda-mode-map "p" 'previous-line)
4381 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4382 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4383 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4384 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4385 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4386 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4387 (eval-after-load "calendar"
4388 '(define-key calendar-mode-map org-calendar-to-agenda-key
4389 'org-calendar-goto-agenda))
4390 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4391 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4392 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4393 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4394 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4395 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4396 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4397 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4398 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4399 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4400 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4401 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4402 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4403 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4404 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4405 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4406 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4407 "Local keymap for agenda entries from Org-mode.")
4408
4409 (define-key org-agenda-keymap
4410 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4411 (define-key org-agenda-keymap
4412 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4413 (define-key org-agenda-keymap [follow-link] 'mouse-face)
4414 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4415 '("Agenda"
4416 ("Agenda Files")
4417 "--"
4418 ["Show" org-agenda-show t]
4419 ["Go To (other window)" org-agenda-goto t]
4420 ["Go To (one window)" org-agenda-switch-to t]
4421 ["Follow Mode" org-agenda-follow-mode
4422 :style toggle :selected org-agenda-follow-mode :active t]
4423 "--"
4424 ["Cycle TODO" org-agenda-todo t]
4425 ("Tags"
4426 ["Show all Tags" org-agenda-show-tags t]
4427 ["Set Tags" org-agenda-set-tags t])
4428 ("Reschedule"
4429 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4430 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4431 "--"
4432 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4433 ("Priority"
4434 ["Set Priority" org-agenda-priority t]
4435 ["Increase Priority" org-agenda-priority-up t]
4436 ["Decrease Priority" org-agenda-priority-down t]
4437 ["Show Priority" org-agenda-show-priority t])
4438 "--"
4439 ;; ["New agenda command" org-agenda t]
4440 ["Rebuild buffer" org-agenda-redo t]
4441 "--"
4442 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4443 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4444 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4445 "--"
4446 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4447 :style radio :selected (equal org-agenda-ndays 1)]
4448 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4449 :style radio :selected (equal org-agenda-ndays 7)]
4450 "--"
4451 ["Show Logbook entries" org-agenda-log-mode
4452 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4453 ["Include Diary" org-agenda-toggle-diary
4454 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4455 ["Use Time Grid" org-agenda-toggle-time-grid
4456 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4457 "--"
4458 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4459 ("Calendar Commands"
4460 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4461 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4462 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4463 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4464 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4465 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4466 "--"
4467 ["Quit" org-agenda-quit t]
4468 ["Exit and Release Buffers" org-agenda-exit t]
4469 ))
4470
4471 ;;;###autoload
4472 (defun org-agenda (arg)
4473 "Dispatch agenda commands to collect entries to the agenda buffer.
4474 Prompts for a character to select a command. Any prefix arg will be passed
4475 on to the selected command. The default selections are:
4476
4477 a Call `org-agenda' to display the agenda for the current day or week.
4478 t Call `org-todo-list' to display the global todo list.
4479 T Call `org-todo-list' to display the global todo list, select only
4480 entries with a specific TODO keyword (the user gets a prompt).
4481 m Call `org-tags-view' to display headlines with tags matching
4482 a condition (the user is prompted for the condition).
4483 M Like `m', but select only TODO entries, no ordinary headlines.
4484
4485 More commands can be added by configuring the variable
4486 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4487 searches can be pre-defined in this way.
4488
4489 If the current buffer is in Org-mode and visiting a file, you can also
4490 first press `1' to indicate that the agenda should be temporarily (until the
4491 next use of \\[org-agenda]) restricted to the current file."
4492 (interactive "P")
4493 (catch 'exit
4494 (let ((restrict-ok (and (buffer-file-name) (eq major-mode 'org-mode)))
4495 (custom org-agenda-custom-commands)
4496 c entry key type string)
4497 (put 'org-agenda-files 'org-restrict nil)
4498 (save-window-excursion
4499 (delete-other-windows)
4500 (switch-to-buffer-other-window " *Agenda Commands*")
4501 (erase-buffer)
4502 (insert
4503 "Press key for an agenda command:
4504 --------------------------------
4505 a Agenda for current week or day
4506 t List of all TODO entries T Entries with special TODO kwd
4507 m Match a TAGS query M Like m, but only TODO entries
4508 C Configure your own agenda commands")
4509 (while (setq entry (pop custom))
4510 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4511 (insert (format "\n%-4s%-14s: %s"
4512 key
4513 (cond
4514 ((eq type 'tags) "Tags query")
4515 ((eq type 'todo) "TODO keyword")
4516 ((eq type 'tags-tree) "Tags tree")
4517 ((eq type 'todo-tree) "TODO kwd tree")
4518 ((eq type 'occur-tree) "Occur tree")
4519 (t "???"))
4520 (org-string-props string 'face 'org-link))))
4521 (goto-char (point-min))
4522 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4523 (message "Press key for agenda command%s"
4524 (if restrict-ok ", or [1] to restrict to current file" ""))
4525 (setq c (read-char-exclusive))
4526 (message "")
4527 (when (equal c ?1)
4528 (if restrict-ok
4529 (put 'org-agenda-files 'org-restrict (list (buffer-file-name)))
4530 (error "Cannot restrict agenda to current buffer"))
4531 (message "Press key for agenda command%s"
4532 (if restrict-ok " (restricted to current file)" ""))
4533 (setq c (read-char-exclusive))
4534 (message "")))
4535 (require 'calendar) ; FIXME: can we avoid this for some commands?
4536 ;; For example the todo list should not need it (but does...)
4537 (cond
4538 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4539 ((equal c ?a) (call-interactively 'org-agenda-list))
4540 ((equal c ?t) (call-interactively 'org-todo-list))
4541 ((equal c ?T)
4542 (setq current-prefix-arg (or arg '(4)))
4543 (call-interactively 'org-todo-list))
4544 ((equal c ?m) (call-interactively 'org-tags-view))
4545 ((equal c ?M)
4546 (setq current-prefix-arg (or arg '(4)))
4547 (call-interactively 'org-tags-view))
4548 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4549 (setq type (nth 1 entry) string (nth 2 entry))
4550 (cond
4551 ((eq type 'tags)
4552 (org-tags-view current-prefix-arg string))
4553 ((eq type 'todo)
4554 (org-todo-list string))
4555 ((eq type 'tags-tree)
4556 (org-check-for-org-mode)
4557 (org-tags-sparse-tree current-prefix-arg string))
4558 ((eq type 'todo-tree)
4559 (org-check-for-org-mode)
4560 (org-occur (concat "^" outline-regexp "[ \t]*"
4561 (regexp-quote string) "\\>")))
4562 ((eq type 'occur-tree)
4563 (org-check-for-org-mode)
4564 (org-occur string))
4565 (t (error "Invalid custom agenda command type %s" type))))
4566 (t (error "Invalid key"))))))
4567
4568 (defun org-check-for-org-mode ()
4569 "Make sure current buffer is in org-mode. Error if not."
4570 (or (eq major-mode 'org-mode)
4571 (error "Cannot execute org-mode agenda command on buffer in %s."
4572 major-mode)))
4573
4574 (defun org-fit-agenda-window ()
4575 "Fit the window to the buffer size."
4576 (and org-fit-agenda-window
4577 (fboundp 'fit-window-to-buffer)
4578 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4579 (/ (frame-height) 2))))
4580
4581 (defun org-agenda-files ()
4582 "Get the list of agenda files."
4583 (or (get 'org-agenda-files 'org-restrict)
4584 org-agenda-files))
4585
4586 (defvar org-agenda-markers nil
4587 "List of all currently active markers created by `org-agenda'.")
4588 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4589 "Creation time of the last agenda marker.")
4590
4591 (defun org-agenda-new-marker (&optional pos)
4592 "Return a new agenda marker.
4593 Org-mode keeps a list of these markers and resets them when they are
4594 no longer in use."
4595 (let ((m (copy-marker (or pos (point)))))
4596 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4597 (push m org-agenda-markers)
4598 m))
4599
4600 (defun org-agenda-maybe-reset-markers (&optional force)
4601 "Reset markers created by `org-agenda'. But only if they are old enough."
4602 (if (or force
4603 (> (- (time-to-seconds (current-time))
4604 org-agenda-last-marker-time)
4605 5))
4606 (while org-agenda-markers
4607 (move-marker (pop org-agenda-markers) nil))))
4608
4609 (defvar org-agenda-new-buffers nil
4610 "Buffers created to visit agenda files.")
4611
4612 (defun org-get-agenda-file-buffer (file)
4613 "Get a buffer visiting FILE. If the buffer needs to be created, add
4614 it to the list of buffers which might be released later."
4615 (let ((buf (find-buffer-visiting file)))
4616 (if buf
4617 buf ; just return it
4618 ;; Make a new buffer and remember it
4619 (setq buf (find-file-noselect file))
4620 (if buf (push buf org-agenda-new-buffers))
4621 buf)))
4622
4623 (defun org-release-buffers (blist)
4624 "Release all buffers in list, asking the user for confirmation when needed.
4625 When a buffer is unmodified, it is just killed. When modified, it is saved
4626 \(if the user agrees) and then killed."
4627 (let (buf file)
4628 (while (setq buf (pop blist))
4629 (setq file (buffer-file-name buf))
4630 (when (and (buffer-modified-p buf)
4631 file
4632 (y-or-n-p (format "Save file %s? " file)))
4633 (with-current-buffer buf (save-buffer)))
4634 (kill-buffer buf))))
4635
4636 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4637
4638 (defun org-timeline (&optional include-all keep-modes)
4639 "Show a time-sorted view of the entries in the current org file.
4640 Only entries with a time stamp of today or later will be listed. With
4641 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4642 under the current date.
4643 If the buffer contains an active region, only check the region for
4644 dates."
4645 (interactive "P")
4646 (require 'calendar)
4647 (org-agenda-maybe-reset-markers 'force)
4648 (org-compile-prefix-format org-timeline-prefix-format)
4649 (let* ((dopast t)
4650 (dotodo include-all)
4651 (doclosed org-agenda-show-log)
4652 (org-agenda-keep-modes keep-modes)
4653 (entry (buffer-file-name))
4654 (org-agenda-files (list (buffer-file-name)))
4655 (date (calendar-current-date))
4656 (win (selected-window))
4657 (pos1 (point))
4658 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4659 (end (if (org-region-active-p) (region-end) (point-max)))
4660 (day-numbers (org-get-all-dates beg end 'no-ranges
4661 t doclosed)) ; always include today
4662 (today (time-to-days (current-time)))
4663 (org-respect-restriction t)
4664 (past t)
4665 args
4666 s e rtn d)
4667 (setq org-agenda-redo-command
4668 (list 'progn
4669 (list 'switch-to-buffer-other-window (current-buffer))
4670 (list 'org-timeline (list 'quote include-all) t)))
4671 (if (not dopast)
4672 ;; Remove past dates from the list of dates.
4673 (setq day-numbers (delq nil (mapcar (lambda(x)
4674 (if (>= x today) x nil))
4675 day-numbers))))
4676 (switch-to-buffer-other-window
4677 (get-buffer-create org-agenda-buffer-name))
4678 (setq buffer-read-only nil)
4679 (erase-buffer)
4680 (org-agenda-mode) (setq buffer-read-only nil)
4681 (set (make-local-variable 'org-agenda-type) 'timeline)
4682 (if doclosed (push :closed args))
4683 (push :timestamp args)
4684 (if dotodo (push :todo args))
4685 (while (setq d (pop day-numbers))
4686 (if (and (>= d today)
4687 dopast
4688 past)
4689 (progn
4690 (setq past nil)
4691 (insert (make-string 79 ?-) "\n")))
4692 (setq date (calendar-gregorian-from-absolute d))
4693 (setq s (point))
4694 (setq rtn (apply 'org-agenda-get-day-entries
4695 entry date args))
4696 (if (or rtn (equal d today))
4697 (progn
4698 (insert (calendar-day-name date) " "
4699 (number-to-string (extract-calendar-day date)) " "
4700 (calendar-month-name (extract-calendar-month date)) " "
4701 (number-to-string (extract-calendar-year date)) "\n")
4702 (put-text-property s (1- (point)) 'face
4703 'org-link)
4704 (if (equal d today)
4705 (put-text-property s (1- (point)) 'org-today t))
4706 (insert (org-finalize-agenda-entries rtn) "\n")
4707 (put-text-property s (1- (point)) 'day d))))
4708 (goto-char (point-min))
4709 (setq buffer-read-only t)
4710 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4711 (point-min)))
4712 (when (not org-select-timeline-window)
4713 (select-window win)
4714 (goto-char pos1))))
4715
4716 ;;;###autoload
4717 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4718 "Produce a weekly view from all files in variable `org-agenda-files'.
4719 The view will be for the current week, but from the overview buffer you
4720 will be able to go to other weeks.
4721 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4722 also be shown, under the current date.
4723 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4724 on the days are also shown. See the variable `org-log-done' for how
4725 to turn on logging.
4726 START-DAY defaults to TODAY, or to the most recent match for the weekday
4727 given in `org-agenda-start-on-weekday'.
4728 NDAYS defaults to `org-agenda-ndays'."
4729 (interactive "P")
4730 (org-agenda-maybe-reset-markers 'force)
4731 (org-compile-prefix-format org-agenda-prefix-format)
4732 (require 'calendar)
4733 (let* ((org-agenda-start-on-weekday
4734 (if (or (equal ndays 1)
4735 (and (null ndays) (equal 1 org-agenda-ndays)))
4736 nil org-agenda-start-on-weekday))
4737 (org-agenda-keep-modes keep-modes)
4738 (files (copy-sequence (org-agenda-files)))
4739 (win (selected-window))
4740 (today (time-to-days (current-time)))
4741 (sd (or start-day today))
4742 (start (if (or (null org-agenda-start-on-weekday)
4743 (< org-agenda-ndays 7))
4744 sd
4745 (let* ((nt (calendar-day-of-week
4746 (calendar-gregorian-from-absolute sd)))
4747 (n1 org-agenda-start-on-weekday)
4748 (d (- nt n1)))
4749 (- sd (+ (if (< d 0) 7 0) d)))))
4750 (day-numbers (list start))
4751 (inhibit-redisplay t)
4752 s e rtn rtnall file date d start-pos end-pos todayp nd)
4753 (setq org-agenda-redo-command
4754 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4755 ;; Make the list of days
4756 (setq ndays (or ndays org-agenda-ndays)
4757 nd ndays)
4758 (while (> ndays 1)
4759 (push (1+ (car day-numbers)) day-numbers)
4760 (setq ndays (1- ndays)))
4761 (setq day-numbers (nreverse day-numbers))
4762 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4763 (progn
4764 (delete-other-windows)
4765 (switch-to-buffer-other-window
4766 (get-buffer-create org-agenda-buffer-name))))
4767 (setq buffer-read-only nil)
4768 (erase-buffer)
4769 (org-agenda-mode) (setq buffer-read-only nil)
4770 (set (make-local-variable 'org-agenda-type) 'agenda)
4771 (set (make-local-variable 'starting-day) (car day-numbers))
4772 (set (make-local-variable 'include-all-loc) include-all)
4773 (when (and (or include-all org-agenda-include-all-todo)
4774 (member today day-numbers))
4775 (setq files (org-agenda-files)
4776 rtnall nil)
4777 (while (setq file (pop files))
4778 (catch 'nextfile
4779 (org-check-agenda-file file)
4780 (setq date (calendar-gregorian-from-absolute today)
4781 rtn (org-agenda-get-day-entries
4782 file date :todo))
4783 (setq rtnall (append rtnall rtn))))
4784 (when rtnall
4785 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4786 (add-text-properties (point-min) (1- (point))
4787 (list 'face 'org-link))
4788 (insert (org-finalize-agenda-entries rtnall) "\n")))
4789 (while (setq d (pop day-numbers))
4790 (setq date (calendar-gregorian-from-absolute d)
4791 s (point))
4792 (if (or (setq todayp (= d today))
4793 (and (not start-pos) (= d sd)))
4794 (setq start-pos (point))
4795 (if (and start-pos (not end-pos))
4796 (setq end-pos (point))))
4797 (setq files (org-agenda-files)
4798 rtnall nil)
4799 (while (setq file (pop files))
4800 (catch 'nextfile
4801 (org-check-agenda-file file)
4802 (if org-agenda-show-log
4803 (setq rtn (org-agenda-get-day-entries
4804 file date
4805 :deadline :scheduled :timestamp :closed))
4806 (setq rtn (org-agenda-get-day-entries
4807 file date
4808 :deadline :scheduled :timestamp)))
4809 (setq rtnall (append rtnall rtn))))
4810 (if org-agenda-include-diary
4811 (progn
4812 (require 'diary-lib)
4813 (setq rtn (org-get-entries-from-diary date))
4814 (setq rtnall (append rtnall rtn))))
4815 (if (or rtnall org-agenda-show-all-dates)
4816 (progn
4817 (insert (format "%-9s %2d %s %4d\n"
4818 (calendar-day-name date)
4819 (extract-calendar-day date)
4820 (calendar-month-name (extract-calendar-month date))
4821 (extract-calendar-year date)))
4822 (put-text-property s (1- (point)) 'face
4823 'org-link)
4824 (if rtnall (insert
4825 (org-finalize-agenda-entries
4826 (org-agenda-add-time-grid-maybe
4827 rtnall nd todayp))
4828 "\n"))
4829 (put-text-property s (1- (point)) 'day d))))
4830 (goto-char (point-min))
4831 (setq buffer-read-only t)
4832 (org-fit-agenda-window)
4833 (unless (and (pos-visible-in-window-p (point-min))
4834 (pos-visible-in-window-p (point-max)))
4835 (goto-char (1- (point-max)))
4836 (recenter -1)
4837 (if (not (pos-visible-in-window-p (or start-pos 1)))
4838 (progn
4839 (goto-char (or start-pos 1))
4840 (recenter 1))))
4841 (goto-char (or start-pos 1))
4842 (if (not org-select-agenda-window) (select-window win))
4843 (message "")))
4844
4845 (defvar org-select-this-todo-keyword nil)
4846
4847 ;;;###autoload
4848 (defun org-todo-list (arg &optional keep-modes)
4849 "Show all TODO entries from all agenda file in a single list.
4850 The prefix arg can be used to select a specific TODO keyword and limit
4851 the list to these. When using \\[universal-argument], you will be prompted
4852 for a keyword. A numeric prefix directly selects the Nth keyword in
4853 `org-todo-keywords'."
4854 (interactive "P")
4855 (org-agenda-maybe-reset-markers 'force)
4856 (org-compile-prefix-format org-agenda-prefix-format)
4857 (let* ((org-agenda-keep-modes keep-modes)
4858 (today (time-to-days (current-time)))
4859 (date (calendar-gregorian-from-absolute today))
4860 (win (selected-window))
4861 (kwds org-todo-keywords)
4862 (completion-ignore-case t)
4863 (org-select-this-todo-keyword
4864 (if (stringp arg) arg
4865 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4866 rtn rtnall files file pos)
4867 (when (equal arg '(4))
4868 (setq org-select-this-todo-keyword
4869 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4870 nil t)))
4871 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4872 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4873 (progn
4874 (delete-other-windows)
4875 (switch-to-buffer-other-window
4876 (get-buffer-create org-agenda-buffer-name))))
4877 (setq buffer-read-only nil)
4878 (erase-buffer)
4879 (org-agenda-mode) (setq buffer-read-only nil)
4880 (set (make-local-variable 'org-agenda-type) 'todo)
4881 (set (make-local-variable 'last-arg) arg)
4882 (set (make-local-variable 'org-todo-keywords) kwds)
4883 (set (make-local-variable 'org-agenda-redo-command)
4884 '(org-todo-list (or current-prefix-arg last-arg) t))
4885 (setq files (org-agenda-files)
4886 rtnall nil)
4887 (while (setq file (pop files))
4888 (catch 'nextfile
4889 (org-check-agenda-file file)
4890 (setq rtn (org-agenda-get-day-entries file date :todo))
4891 (setq rtnall (append rtnall rtn))))
4892 (insert "Global list of TODO items of type: ")
4893 (add-text-properties (point-min) (1- (point))
4894 (list 'face 'org-link))
4895 (setq pos (point))
4896 (insert (or org-select-this-todo-keyword "ALL") "\n")
4897 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4898 (setq pos (point))
4899 (insert
4900 "Available with `N r': (0)ALL "
4901 (let ((n 0))
4902 (mapconcat (lambda (x)
4903 (format "(%d)%s" (setq n (1+ n)) x))
4904 org-todo-keywords " "))
4905 "\n")
4906 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4907 (when rtnall
4908 (insert (org-finalize-agenda-entries rtnall) "\n"))
4909 (goto-char (point-min))
4910 (setq buffer-read-only t)
4911 (org-fit-agenda-window)
4912 (if (not org-select-agenda-window) (select-window win))))
4913
4914 (defun org-check-agenda-file (file)
4915 "Make sure FILE exists. If not, ask user what to do."
4916 ;; FIXME: this does not correctly change the menus
4917 ;; Could probably be fixed by explicitly going to the buffer where
4918 ;; the call originated.
4919 (when (not (file-exists-p file))
4920 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4921 file)
4922 (let ((r (downcase (read-char-exclusive))))
4923 (cond
4924 ((equal r ?r)
4925 (org-remove-file file)
4926 (throw 'nextfile t))
4927 (t (error "Abort"))))))
4928
4929 (defun org-agenda-check-type (error &rest types)
4930 "Check if agenda buffer is of allowed type.
4931 If ERROR is non-nil, throw an error, otherwise just return nil."
4932 (if (memq org-agenda-type types)
4933 t
4934 (if error
4935 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
4936 nil)))
4937
4938 (defun org-agenda-quit ()
4939 "Exit agenda by removing the window or the buffer."
4940 (interactive)
4941 (let ((buf (current-buffer)))
4942 (if (not (one-window-p)) (delete-window))
4943 (kill-buffer buf)
4944 (org-agenda-maybe-reset-markers 'force)))
4945
4946 (defun org-agenda-exit ()
4947 "Exit agenda by removing the window or the buffer.
4948 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4949 Org-mode buffers visited directly by the user will not be touched."
4950 (interactive)
4951 (org-release-buffers org-agenda-new-buffers)
4952 (setq org-agenda-new-buffers nil)
4953 (org-agenda-quit))
4954
4955 (defun org-agenda-redo ()
4956 "Rebuild Agenda.
4957 When this is the global TODO list, a prefix argument will be interpreted."
4958 (interactive)
4959 (message "Rebuilding agenda buffer...")
4960 (eval org-agenda-redo-command)
4961 (message "Rebuilding agenda buffer...done"))
4962
4963 (defun org-agenda-goto-today ()
4964 "Go to today."
4965 (interactive)
4966 (org-agenda-check-type t 'timeline 'agenda)
4967 (if (boundp 'starting-day)
4968 (let ((cmd (car org-agenda-redo-command))
4969 (iall (nth 1 org-agenda-redo-command))
4970 (nday (nth 3 org-agenda-redo-command))
4971 (keep (nth 4 org-agenda-redo-command)))
4972 (eval (list cmd iall nil nday keep)))
4973 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4974 (point-min)))))
4975
4976 (defun org-agenda-later (arg)
4977 "Go forward in time by `org-agenda-ndays' days.
4978 With prefix ARG, go forward that many times `org-agenda-ndays'."
4979 (interactive "p")
4980 (org-agenda-check-type t 'agenda)
4981 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4982 (+ starting-day (* arg org-agenda-ndays)) nil t))
4983
4984 (defun org-agenda-earlier (arg)
4985 "Go back in time by `org-agenda-ndays' days.
4986 With prefix ARG, go back that many times `org-agenda-ndays'."
4987 (interactive "p")
4988 (org-agenda-check-type t 'agenda)
4989 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4990 (- starting-day (* arg org-agenda-ndays)) nil t))
4991
4992 (defun org-agenda-week-view ()
4993 "Switch to weekly view for agenda."
4994 (interactive)
4995 (org-agenda-check-type t 'agenda)
4996 (setq org-agenda-ndays 7)
4997 (org-agenda-list include-all-loc
4998 (or (get-text-property (point) 'day)
4999 starting-day)
5000 nil t)
5001 (org-agenda-set-mode-name)
5002 (message "Switched to week view"))
5003
5004 (defun org-agenda-day-view ()
5005 "Switch to daily view for agenda."
5006 (interactive)
5007 (org-agenda-check-type t 'agenda)
5008 (setq org-agenda-ndays 1)
5009 (org-agenda-list include-all-loc
5010 (or (get-text-property (point) 'day)
5011 starting-day)
5012 nil t)
5013 (org-agenda-set-mode-name)
5014 (message "Switched to day view"))
5015
5016 (defun org-agenda-next-date-line (&optional arg)
5017 "Jump to the next line indicating a date in agenda buffer."
5018 (interactive "p")
5019 (org-agenda-check-type t 'agenda 'timeline)
5020 (beginning-of-line 1)
5021 (if (looking-at "^\\S-") (forward-char 1))
5022 (if (not (re-search-forward "^\\S-" nil t arg))
5023 (progn
5024 (backward-char 1)
5025 (error "No next date after this line in this buffer")))
5026 (goto-char (match-beginning 0)))
5027
5028 (defun org-agenda-previous-date-line (&optional arg)
5029 "Jump to the previous line indicating a date in agenda buffer."
5030 (interactive "p")
5031 (org-agenda-check-type t 'agenda 'timeline)
5032 (beginning-of-line 1)
5033 (if (not (re-search-backward "^\\S-" nil t arg))
5034 (error "No previous date before this line in this buffer")))
5035
5036 ;; Initialize the highlight
5037 (defvar org-hl (org-make-overlay 1 1))
5038 (org-overlay-put org-hl 'face 'highlight)
5039
5040 (defun org-highlight (begin end &optional buffer)
5041 "Highlight a region with overlay."
5042 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
5043 org-hl begin end (or buffer (current-buffer))))
5044
5045 (defun org-unhighlight ()
5046 "Detach overlay INDEX."
5047 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
5048
5049
5050 (defun org-agenda-follow-mode ()
5051 "Toggle follow mode in an agenda buffer."
5052 (interactive)
5053 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5054 (org-agenda-set-mode-name)
5055 (message "Follow mode is %s"
5056 (if org-agenda-follow-mode "on" "off")))
5057
5058 (defun org-agenda-log-mode ()
5059 "Toggle log mode in an agenda buffer."
5060 (interactive)
5061 (org-agenda-check-type t 'agenda 'timeline)
5062 (setq org-agenda-show-log (not org-agenda-show-log))
5063 (org-agenda-set-mode-name)
5064 (org-agenda-redo)
5065 (message "Log mode is %s"
5066 (if org-agenda-show-log "on" "off")))
5067
5068 (defun org-agenda-toggle-diary ()
5069 "Toggle diary inclusion in an agenda buffer."
5070 (interactive)
5071 (org-agenda-check-type t 'agenda)
5072 (setq org-agenda-include-diary (not org-agenda-include-diary))
5073 (org-agenda-redo)
5074 (org-agenda-set-mode-name)
5075 (message "Diary inclusion turned %s"
5076 (if org-agenda-include-diary "on" "off")))
5077
5078 (defun org-agenda-toggle-time-grid ()
5079 "Toggle time grid in an agenda buffer."
5080 (interactive)
5081 (org-agenda-check-type t 'agenda)
5082 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5083 (org-agenda-redo)
5084 (org-agenda-set-mode-name)
5085 (message "Time-grid turned %s"
5086 (if org-agenda-use-time-grid "on" "off")))
5087
5088 (defun org-agenda-set-mode-name ()
5089 "Set the mode name to indicate all the small mode settings."
5090 (setq mode-name
5091 (concat "Org-Agenda"
5092 (if (equal org-agenda-ndays 1) " Day" "")
5093 (if (equal org-agenda-ndays 7) " Week" "")
5094 (if org-agenda-follow-mode " Follow" "")
5095 (if org-agenda-include-diary " Diary" "")
5096 (if org-agenda-use-time-grid " Grid" "")
5097 (if org-agenda-show-log " Log" "")))
5098 (force-mode-line-update))
5099
5100 (defun org-agenda-post-command-hook ()
5101 (and (eolp) (not (bolp)) (backward-char 1))
5102 (if (and org-agenda-follow-mode
5103 (get-text-property (point) 'org-marker))
5104 (org-agenda-show)))
5105
5106 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5107
5108 (defun org-get-entries-from-diary (date)
5109 "Get the (Emacs Calendar) diary entries for DATE."
5110 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5111 (diary-display-hook '(fancy-diary-display))
5112 (list-diary-entries-hook
5113 (cons 'org-diary-default-entry list-diary-entries-hook))
5114 (diary-file-name-prefix-function nil) ; turn this feature off
5115 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5116 entries
5117 (org-disable-agenda-to-diary t))
5118 (save-excursion
5119 (save-window-excursion
5120 (list-diary-entries date 1)))
5121 (if (not (get-buffer fancy-diary-buffer))
5122 (setq entries nil)
5123 (with-current-buffer fancy-diary-buffer
5124 (setq buffer-read-only nil)
5125 (if (= (point-max) 1)
5126 ;; No entries
5127 (setq entries nil)
5128 ;; Omit the date and other unnecessary stuff
5129 (org-agenda-cleanup-fancy-diary)
5130 ;; Add prefix to each line and extend the text properties
5131 (if (= (point-max) 1)
5132 (setq entries nil)
5133 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5134 (set-buffer-modified-p nil)
5135 (kill-buffer fancy-diary-buffer)))
5136 (when entries
5137 (setq entries (org-split-string entries "\n"))
5138 (setq entries
5139 (mapcar
5140 (lambda (x)
5141 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5142 ;; Extend the text properties to the beginning of the line
5143 (add-text-properties
5144 0 (length x)
5145 (text-properties-at (1- (length x)) x)
5146 x)
5147 x)
5148 entries)))))
5149
5150 (defun org-agenda-cleanup-fancy-diary ()
5151 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5152 This gets rid of the date, the underline under the date, and
5153 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5154 date. It also removes lines that contain only whitespace."
5155 (goto-char (point-min))
5156 (if (looking-at ".*?:[ \t]*")
5157 (progn
5158 (replace-match "")
5159 (re-search-forward "\n=+$" nil t)
5160 (replace-match "")
5161 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5162 (re-search-forward "\n=+$" nil t)
5163 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5164 (goto-char (point-min))
5165 (while (re-search-forward "^ +\n" nil t)
5166 (replace-match ""))
5167 (goto-char (point-min))
5168 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5169 (replace-match "")))
5170
5171 ;; Make sure entries from the diary have the right text properties.
5172 (eval-after-load "diary-lib"
5173 '(if (boundp 'diary-modify-entry-list-string-function)
5174 ;; We can rely on the hook, nothing to do
5175 nil
5176 ;; Hook not avaiable, must use advice to make this work
5177 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5178 "Make the position visible."
5179 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5180 (stringp string)
5181 (buffer-file-name))
5182 (setq string (org-modify-diary-entry-string string))))))
5183
5184 (defun org-modify-diary-entry-string (string)
5185 "Add text properties to string, allowing org-mode to act on it."
5186 (add-text-properties
5187 0 (length string)
5188 (list 'mouse-face 'highlight
5189 'keymap org-agenda-keymap
5190 'help-echo
5191 (format
5192 "mouse-2 or RET jump to diary file %s"
5193 (abbreviate-file-name (buffer-file-name)))
5194 'org-agenda-diary-link t
5195 'org-marker (org-agenda-new-marker (point-at-bol)))
5196 string)
5197 string)
5198
5199 (defun org-diary-default-entry ()
5200 "Add a dummy entry to the diary.
5201 Needed to avoid empty dates which mess up holiday display."
5202 ;; Catch the error if dealing with the new add-to-diary-alist
5203 (when org-disable-agenda-to-diary
5204 (condition-case nil
5205 (add-to-diary-list original-date "Org-mode dummy" "")
5206 (error
5207 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5208
5209 (defun org-cycle-agenda-files ()
5210 "Cycle through the files in `org-agenda-files'.
5211 If the current buffer visits an agenda file, find the next one in the list.
5212 If the current buffer does not, find the first agenda file."
5213 (interactive)
5214 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5215 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
5216 file)
5217 (unless files (error "No agenda files"))
5218 (catch 'exit
5219 (while (setq file (pop files))
5220 (if (equal (file-truename file) tcf)
5221 (when (car files)
5222 (find-file (car files))
5223 (throw 'exit t))))
5224 (find-file (car org-agenda-files)))))
5225
5226 (defun org-agenda-file-to-end (&optional file)
5227 "Move/add the current file to the end of the agenda file list.
5228 If the file is not present in the list, it is appended to the list. If it is
5229 present, it is moved there."
5230 (interactive)
5231 (org-agenda-file-to-front 'to-end file))
5232
5233 (defun org-agenda-file-to-front (&optional to-end file)
5234 "Move/add the current file to the top of the agenda file list.
5235 If the file is not present in the list, it is added to the front. If it is
5236 present, it is moved there. With optional argument TO-END, add/move to the
5237 end of the list."
5238 (interactive "P")
5239 (let ((file-alist (mapcar (lambda (x)
5240 (cons (file-truename x) x))
5241 org-agenda-files))
5242 (ctf (file-truename (buffer-file-name)))
5243 x had)
5244 (setq x (assoc ctf file-alist) had x)
5245
5246 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
5247 (if to-end
5248 (setq file-alist (append (delq x file-alist) (list x)))
5249 (setq file-alist (cons x (delq x file-alist))))
5250 (setq org-agenda-files (mapcar 'cdr file-alist))
5251 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5252 (customize-save-variable 'org-agenda-files org-agenda-files))
5253 (org-install-agenda-files-menu)
5254 (message "File %s to %s of agenda file list"
5255 (if had "moved" "added") (if to-end "end" "front"))))
5256
5257 (defun org-remove-file (&optional file)
5258 "Remove current file from the list of files in variable `org-agenda-files'.
5259 These are the files which are being checked for agenda entries.
5260 Optional argument FILE means, use this file instead of the current."
5261 (interactive)
5262 (let* ((file (or file (buffer-file-name)))
5263 (true-file (file-truename file))
5264 (afile (abbreviate-file-name file))
5265 (files (delq nil (mapcar
5266 (lambda (x)
5267 (if (equal true-file
5268 (file-truename x))
5269 nil x))
5270 org-agenda-files))))
5271 (if (not (= (length files) (length org-agenda-files)))
5272 (progn
5273 (setq org-agenda-files files)
5274 (customize-save-variable 'org-agenda-files org-agenda-files)
5275 (org-install-agenda-files-menu)
5276 (message "Removed file: %s" afile))
5277 (message "File was not in list: %s" afile))))
5278
5279 (defun org-file-menu-entry (file)
5280 (vector file (list 'find-file file) t))
5281 ;; FIXME: Maybe we removed a buffer visited through the menu from
5282 ;; org-agenda-new-buffers, so that the buffer will not be removed
5283 ;; when exiting the agenda????
5284
5285 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5286 "Return a list of all relevant day numbers from BEG to END buffer positions.
5287 If NO-RANGES is non-nil, include only the start and end dates of a range,
5288 not every single day in the range. If FORCE-TODAY is non-nil, make
5289 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5290 inactive time stamps (those in square brackets) are included."
5291 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5292 dates date day day1 day2 ts1 ts2)
5293 (if force-today
5294 (setq dates (list (time-to-days (current-time)))))
5295 (save-excursion
5296 (goto-char beg)
5297 (while (re-search-forward re end t)
5298 (setq day (time-to-days (org-time-string-to-time
5299 (substring (match-string 1) 0 10))))
5300 (or (memq day dates) (push day dates)))
5301 (unless no-ranges
5302 (goto-char beg)
5303 (while (re-search-forward org-tr-regexp end t)
5304 (setq ts1 (substring (match-string 1) 0 10)
5305 ts2 (substring (match-string 2) 0 10)
5306 day1 (time-to-days (org-time-string-to-time ts1))
5307 day2 (time-to-days (org-time-string-to-time ts2)))
5308 (while (< (setq day1 (1+ day1)) day2)
5309 (or (memq day1 dates) (push day1 dates)))))
5310 (sort dates '<))))
5311
5312 ;;;###autoload
5313 (defun org-diary (&rest args)
5314 "Return diary information from org-files.
5315 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5316 It accesses org files and extracts information from those files to be
5317 listed in the diary. The function accepts arguments specifying what
5318 items should be listed. The following arguments are allowed:
5319
5320 :timestamp List the headlines of items containing a date stamp or
5321 date range matching the selected date. Deadlines will
5322 also be listed, on the expiration day.
5323
5324 :deadline List any deadlines past due, or due within
5325 `org-deadline-warning-days'. The listing occurs only
5326 in the diary for *today*, not at any other date. If
5327 an entry is marked DONE, it is no longer listed.
5328
5329 :scheduled List all items which are scheduled for the given date.
5330 The diary for *today* also contains items which were
5331 scheduled earlier and are not yet marked DONE.
5332
5333 :todo List all TODO items from the org-file. This may be a
5334 long list - so this is not turned on by default.
5335 Like deadlines, these entries only show up in the
5336 diary for *today*, not at any other date.
5337
5338 The call in the diary file should look like this:
5339
5340 &%%(org-diary) ~/path/to/some/orgfile.org
5341
5342 Use a separate line for each org file to check. Or, if you omit the file name,
5343 all files listed in `org-agenda-files' will be checked automatically:
5344
5345 &%%(org-diary)
5346
5347 If you don't give any arguments (as in the example above), the default
5348 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5349 also be written as
5350
5351 &%%(org-diary :deadline :timestamp :scheduled)
5352
5353 The function expects the lisp variables `entry' and `date' to be provided
5354 by the caller, because this is how the calendar works. Don't use this
5355 function from a program - use `org-agenda-get-day-entries' instead."
5356 (org-agenda-maybe-reset-markers)
5357 (org-compile-prefix-format org-agenda-prefix-format)
5358 (setq args (or args '(:deadline :scheduled :timestamp)))
5359 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5360 (list entry)
5361 org-agenda-files))
5362 file rtn results)
5363 ;; If this is called during org-agenda, don't return any entries to
5364 ;; the calendar. Org Agenda will list these entries itself.
5365 (if org-disable-agenda-to-diary (setq files nil))
5366 (while (setq file (pop files))
5367 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5368 (setq results (append results rtn)))
5369 (if results
5370 (concat (org-finalize-agenda-entries results) "\n"))))
5371 (defvar org-category-table nil)
5372 (defun org-get-category-table ()
5373 "Get the table of categories and positions in current buffer."
5374 (let (tbl)
5375 (save-excursion
5376 (goto-char (point-min))
5377 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5378 (push (cons (point) (org-trim (match-string 2))) tbl)))
5379 tbl))
5380 (defun org-get-category (&optional pos)
5381 "Get the category applying to position POS."
5382 (if (not org-category-table)
5383 (cond
5384 ((null org-category)
5385 (setq org-category
5386 (if (buffer-file-name)
5387 (file-name-sans-extension
5388 (file-name-nondirectory (buffer-file-name)))
5389 "???")))
5390 ((symbolp org-category) (symbol-name org-category))
5391 (t org-category))
5392 (let ((tbl org-category-table)
5393 (pos (or pos (point))))
5394 (while (and tbl (> (caar tbl) pos))
5395 (pop tbl))
5396 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5397 org-category-table))))))
5398
5399 (defun org-agenda-get-day-entries (file date &rest args)
5400 "Does the work for `org-diary' and `org-agenda'.
5401 FILE is the path to a file to be checked for entries. DATE is date like
5402 the one returned by `calendar-current-date'. ARGS are symbols indicating
5403 which kind of entries should be extracted. For details about these, see
5404 the documentation of `org-diary'."
5405 (setq args (or args '(:deadline :scheduled :timestamp)))
5406 (let* ((org-startup-with-deadline-check nil)
5407 (org-startup-folded nil)
5408 (buffer (if (file-exists-p file)
5409 (org-get-agenda-file-buffer file)
5410 (error "No such file %s" file)))
5411 arg results rtn)
5412 (if (not buffer)
5413 ;; If file does not exist, make sure an error message ends up in diary
5414 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5415 (with-current-buffer buffer
5416 (unless (eq major-mode 'org-mode)
5417 (error "Agenda file %s is not in `org-mode'" file))
5418 (setq org-category-table (org-get-category-table))
5419 (let ((case-fold-search nil))
5420 (save-excursion
5421 (save-restriction
5422 (if org-respect-restriction
5423 (if (org-region-active-p)
5424 ;; Respect a region to restrict search
5425 (narrow-to-region (region-beginning) (region-end)))
5426 ;; If we work for the calendar or many files,
5427 ;; get rid of any restriction
5428 (widen))
5429 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5430 (while (setq arg (pop args))
5431 (cond
5432 ((and (eq arg :todo)
5433 (equal date (calendar-current-date)))
5434 (setq rtn (org-agenda-get-todos))
5435 (setq results (append results rtn)))
5436 ((eq arg :timestamp)
5437 (setq rtn (org-agenda-get-blocks))
5438 (setq results (append results rtn))
5439 (setq rtn (org-agenda-get-timestamps))
5440 (setq results (append results rtn)))
5441 ((eq arg :scheduled)
5442 (setq rtn (org-agenda-get-scheduled))
5443 (setq results (append results rtn)))
5444 ((eq arg :closed)
5445 (setq rtn (org-agenda-get-closed))
5446 (setq results (append results rtn)))
5447 ((and (eq arg :deadline)
5448 (equal date (calendar-current-date)))
5449 (setq rtn (org-agenda-get-deadlines))
5450 (setq results (append results rtn))))))))
5451 results))))
5452
5453 (defun org-entry-is-done-p ()
5454 "Is the current entry marked DONE?"
5455 (save-excursion
5456 (and (re-search-backward "[\r\n]\\*" nil t)
5457 (looking-at org-nl-done-regexp))))
5458
5459 (defun org-at-date-range-p ()
5460 "Is the cursor inside a date range?"
5461 (interactive)
5462 (save-excursion
5463 (catch 'exit
5464 (let ((pos (point)))
5465 (skip-chars-backward "^<\r\n")
5466 (skip-chars-backward "<")
5467 (and (looking-at org-tr-regexp)
5468 (>= (match-end 0) pos)
5469 (throw 'exit t))
5470 (skip-chars-backward "^<\r\n")
5471 (skip-chars-backward "<")
5472 (and (looking-at org-tr-regexp)
5473 (>= (match-end 0) pos)
5474 (throw 'exit t)))
5475 nil)))
5476
5477 (defun org-agenda-get-todos ()
5478 "Return the TODO information for agenda display."
5479 (let* ((props (list 'face nil
5480 'done-face 'org-done
5481 'mouse-face 'highlight
5482 'keymap org-agenda-keymap
5483 'help-echo
5484 (format "mouse-2 or RET jump to org file %s"
5485 (abbreviate-file-name (buffer-file-name)))))
5486 (regexp (concat "[\n\r]\\*+ *\\("
5487 (if org-select-this-todo-keyword
5488 (concat "\\<\\(" org-select-this-todo-keyword
5489 "\\)\\>")
5490 org-not-done-regexp)
5491 "[^\n\r]*\\)"))
5492 marker priority category tags
5493 ee txt)
5494 (goto-char (point-min))
5495 (while (re-search-forward regexp nil t)
5496 (goto-char (match-beginning 1))
5497 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5498 category (org-get-category)
5499 tags (org-get-tags-at (point))
5500 txt (org-format-agenda-item "" (match-string 1) category tags)
5501 priority
5502 (+ (org-get-priority txt)
5503 (if org-todo-kwd-priority-p
5504 (- org-todo-kwd-max-priority -2
5505 (length
5506 (member (match-string 2) org-todo-keywords)))
5507 1)))
5508 (add-text-properties
5509 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5510 'priority priority 'category category)
5511 props)
5512 txt)
5513 (push txt ee)
5514 (goto-char (match-end 1)))
5515 (nreverse ee)))
5516
5517 (defconst org-agenda-no-heading-message
5518 "No heading for this item in buffer or region.")
5519
5520 (defun org-agenda-get-timestamps ()
5521 "Return the date stamp information for agenda display."
5522 (let* ((props (list 'face nil
5523 'mouse-face 'highlight
5524 'keymap org-agenda-keymap
5525 'help-echo
5526 (format "mouse-2 or RET jump to org file %s"
5527 (abbreviate-file-name (buffer-file-name)))))
5528 (regexp (regexp-quote
5529 (substring
5530 (format-time-string
5531 (car org-time-stamp-formats)
5532 (apply 'encode-time ; DATE bound by calendar
5533 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5534 0 11)))
5535 marker hdmarker deadlinep scheduledp donep tmp priority category
5536 ee txt timestr tags)
5537 (goto-char (point-min))
5538 (while (re-search-forward regexp nil t)
5539 (if (not (save-match-data (org-at-date-range-p)))
5540 (progn
5541 (setq marker (org-agenda-new-marker (match-beginning 0))
5542 category (org-get-category (match-beginning 0))
5543 tmp (buffer-substring (max (point-min)
5544 (- (match-beginning 0)
5545 org-ds-keyword-length))
5546 (match-beginning 0))
5547 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5548 deadlinep (string-match org-deadline-regexp tmp)
5549 scheduledp (string-match org-scheduled-regexp tmp)
5550 donep (org-entry-is-done-p))
5551 (if (string-match ">" timestr)
5552 ;; substring should only run to end of time stamp
5553 (setq timestr (substring timestr 0 (match-end 0))))
5554 (save-excursion
5555 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5556 (progn
5557 (goto-char (match-end 1))
5558 (setq hdmarker (org-agenda-new-marker)
5559 tags (org-get-tags-at))
5560 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5561 (setq txt (org-format-agenda-item
5562 (format "%s%s"
5563 (if deadlinep "Deadline: " "")
5564 (if scheduledp "Scheduled: " ""))
5565 (match-string 1) category tags timestr)))
5566 (setq txt org-agenda-no-heading-message))
5567 (setq priority (org-get-priority txt))
5568 (add-text-properties
5569 0 (length txt) (append (list 'org-marker marker
5570 'org-hd-marker hdmarker) props)
5571 txt)
5572 (if deadlinep
5573 (add-text-properties
5574 0 (length txt)
5575 (list 'face
5576 (if donep 'org-done 'org-warning)
5577 'undone-face 'org-warning
5578 'done-face 'org-done
5579 'category category
5580 'priority (+ 100 priority))
5581 txt)
5582 (if scheduledp
5583 (add-text-properties
5584 0 (length txt)
5585 (list 'face 'org-scheduled-today
5586 'undone-face 'org-scheduled-today
5587 'done-face 'org-done
5588 'category category
5589 priority (+ 99 priority))
5590 txt)
5591 (add-text-properties
5592 0 (length txt)
5593 (list 'priority priority 'category category) txt)))
5594 (push txt ee))
5595 (outline-next-heading))))
5596 (nreverse ee)))
5597
5598 (defun org-agenda-get-closed ()
5599 "Return the logged TODO entries for agenda display."
5600 (let* ((props (list 'mouse-face 'highlight
5601 'keymap org-agenda-keymap
5602 'help-echo
5603 (format "mouse-2 or RET jump to org file %s"
5604 (abbreviate-file-name (buffer-file-name)))))
5605 (regexp (concat
5606 "\\<" org-closed-string " *\\["
5607 (regexp-quote
5608 (substring
5609 (format-time-string
5610 (car org-time-stamp-formats)
5611 (apply 'encode-time ; DATE bound by calendar
5612 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5613 1 11))))
5614 marker hdmarker priority category tags
5615 ee txt timestr)
5616 (goto-char (point-min))
5617 (while (re-search-forward regexp nil t)
5618 (if (not (save-match-data (org-at-date-range-p)))
5619 (progn
5620 (setq marker (org-agenda-new-marker (match-beginning 0))
5621 category (org-get-category (match-beginning 0))
5622 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5623 ;; donep (org-entry-is-done-p)
5624 )
5625 (if (string-match "\\]" timestr)
5626 ;; substring should only run to end of time stamp
5627 (setq timestr (substring timestr 0 (match-end 0))))
5628 (save-excursion
5629 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5630 (progn
5631 (goto-char (match-end 1))
5632 (setq hdmarker (org-agenda-new-marker)
5633 tags (org-get-tags-at))
5634 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5635 (setq txt (org-format-agenda-item
5636 "Closed: "
5637 (match-string 1) category tags timestr)))
5638 (setq txt org-agenda-no-heading-message))
5639 (setq priority 100000)
5640 (add-text-properties
5641 0 (length txt) (append (list 'org-marker marker
5642 'org-hd-marker hdmarker
5643 'face 'org-done
5644 'priority priority
5645 'category category
5646 'undone-face 'org-warning
5647 'done-face 'org-done) props)
5648 txt)
5649 (push txt ee))
5650 (outline-next-heading))))
5651 (nreverse ee)))
5652
5653 (defun org-agenda-get-deadlines ()
5654 "Return the deadline information for agenda display."
5655 (let* ((wdays org-deadline-warning-days)
5656 (props (list '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-deadline-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 deadline in the calendar:
5673 ;; If the expiration is within wdays warning time.
5674 ;; Past-due deadlines are only shown on the current date
5675 (if (and (< diff wdays) todayp (not (= diff 0)))
5676 (save-excursion
5677 (setq category (org-get-category))
5678 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5679 (progn
5680 (goto-char (match-end 0))
5681 (setq pos1 (match-end 1))
5682 (setq tags (org-get-tags-at pos1))
5683 (setq head (buffer-substring-no-properties
5684 (point)
5685 (progn (skip-chars-forward "^\r\n")
5686 (point))))
5687 (if (string-match org-looking-at-done-regexp head)
5688 (setq txt nil)
5689 (setq txt (org-format-agenda-item
5690 (format "In %3d d.: " diff) head category tags))))
5691 (setq txt org-agenda-no-heading-message))
5692 (when txt
5693 (add-text-properties
5694 0 (length txt)
5695 (append
5696 (list 'org-marker (org-agenda-new-marker pos)
5697 'org-hd-marker (org-agenda-new-marker pos1)
5698 'priority (+ (- 10 diff) (org-get-priority txt))
5699 'category category
5700 'face (cond ((<= diff 0) 'org-warning)
5701 ((<= diff 5) 'org-scheduled-previously)
5702 (t nil))
5703 'undone-face (cond
5704 ((<= diff 0) 'org-warning)
5705 ((<= diff 5) 'org-scheduled-previously)
5706 (t nil))
5707 'done-face 'org-done)
5708 props)
5709 txt)
5710 (push txt ee)))))
5711 ee))
5712
5713 (defun org-agenda-get-scheduled ()
5714 "Return the scheduled information for agenda display."
5715 (let* ((props (list 'face 'org-scheduled-previously
5716 'undone-face 'org-scheduled-previously
5717 'done-face 'org-done
5718 'mouse-face 'highlight
5719 'keymap org-agenda-keymap
5720 'help-echo
5721 (format "mouse-2 or RET jump to org file %s"
5722 (abbreviate-file-name (buffer-file-name)))))
5723 (regexp org-scheduled-time-regexp)
5724 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5725 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5726 d2 diff pos pos1 category tags
5727 ee txt head)
5728 (goto-char (point-min))
5729 (while (re-search-forward regexp nil t)
5730 (setq pos (1- (match-beginning 1))
5731 d2 (time-to-days
5732 (org-time-string-to-time (match-string 1)))
5733 diff (- d2 d1))
5734 ;; When to show a scheduled item in the calendar:
5735 ;; If it is on or past the date.
5736 (if (and (< diff 0) todayp)
5737 (save-excursion
5738 (setq category (org-get-category))
5739 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5740 (progn
5741 (goto-char (match-end 0))
5742 (setq pos1 (match-end 1))
5743 (setq tags (org-get-tags-at))
5744 (setq head (buffer-substring-no-properties
5745 (point)
5746 (progn (skip-chars-forward "^\r\n") (point))))
5747 (if (string-match org-looking-at-done-regexp head)
5748 (setq txt nil)
5749 (setq txt (org-format-agenda-item
5750 (format "Sched.%2dx: " (- 1 diff)) head
5751 category tags))))
5752 (setq txt org-agenda-no-heading-message))
5753 (when txt
5754 (add-text-properties
5755 0 (length txt)
5756 (append (list 'org-marker (org-agenda-new-marker pos)
5757 'org-hd-marker (org-agenda-new-marker pos1)
5758 'priority (+ (- 5 diff) (org-get-priority txt))
5759 'category category)
5760 props) txt)
5761 (push txt ee)))))
5762 ee))
5763
5764 (defun org-agenda-get-blocks ()
5765 "Return the date-range information for agenda display."
5766 (let* ((props (list 'face nil
5767 'mouse-face 'highlight
5768 'keymap org-agenda-keymap
5769 'help-echo
5770 (format "mouse-2 or RET jump to org file %s"
5771 (abbreviate-file-name (buffer-file-name)))))
5772 (regexp org-tr-regexp)
5773 (d0 (calendar-absolute-from-gregorian date))
5774 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
5775 (goto-char (point-min))
5776 (while (re-search-forward regexp nil t)
5777 (setq timestr (match-string 0)
5778 s1 (match-string 1)
5779 s2 (match-string 2)
5780 d1 (time-to-days (org-time-string-to-time s1))
5781 d2 (time-to-days (org-time-string-to-time s2)))
5782 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5783 ;; Only allow days between the limits, because the normal
5784 ;; date stamps will catch the limits.
5785 (save-excursion
5786 (setq marker (org-agenda-new-marker (point)))
5787 (setq category (org-get-category))
5788 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5789 (progn
5790 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5791 (goto-char (match-end 1))
5792 (setq tags (org-get-tags-at))
5793 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5794 (setq txt (org-format-agenda-item
5795 (format (if (= d1 d2) "" "(%d/%d): ")
5796 (1+ (- d0 d1)) (1+ (- d2 d1)))
5797 (match-string 1) category tags
5798 (if (= d0 d1) timestr))))
5799 (setq txt org-agenda-no-heading-message))
5800 (add-text-properties
5801 0 (length txt) (append (list 'org-marker marker
5802 'org-hd-marker hdmarker
5803 'priority (org-get-priority txt)
5804 'category category)
5805 props)
5806 txt)
5807 (push txt ee)))
5808 (outline-next-heading))
5809 ;; Sort the entries by expiration date.
5810 (nreverse ee)))
5811
5812 (defconst org-plain-time-of-day-regexp
5813 (concat
5814 "\\(\\<[012]?[0-9]"
5815 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5816 "\\(--?"
5817 "\\(\\<[012]?[0-9]"
5818 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5819 "\\)?")
5820 "Regular expression to match a plain time or time range.
5821 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5822 groups carry important information:
5823 0 the full match
5824 1 the first time, range or not
5825 8 the second time, if it is a range.")
5826
5827 (defconst org-stamp-time-of-day-regexp
5828 (concat
5829 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5830 "\\([012][0-9]:[0-5][0-9]\\)>"
5831 "\\(--?"
5832 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5833 "Regular expression to match a timestamp time or time range.
5834 After a match, the following groups carry important information:
5835 0 the full match
5836 1 date plus weekday, for backreferencing to make sure both times on same day
5837 2 the first time, range or not
5838 4 the second time, if it is a range.")
5839
5840 (defvar org-prefix-has-time nil
5841 "A flag, set by `org-compile-prefix-format'.
5842 The flag is set if the currently compiled format contains a `%t'.")
5843 (defvar org-prefix-has-tag nil
5844 "A flag, set by `org-compile-prefix-format'.
5845 The flag is set if the currently compiled format contains a `%T'.")
5846
5847 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
5848 "Format TXT to be inserted into the agenda buffer.
5849 In particular, it adds the prefix and corresponding text properties. EXTRA
5850 must be a string and replaces the `%s' specifier in the prefix format.
5851 CATEGORY (string, symbol or nil) may be used to overrule the default
5852 category taken from local variable or file name. It will replace the `%c'
5853 specifier in the format. DOTIME, when non-nil, indicates that a
5854 time-of-day should be extracted from TXT for sorting of this entry, and for
5855 the `%t' specifier in the format. When DOTIME is a string, this string is
5856 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5857 only the correctly processes TXT should be returned - this is used by
5858 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
5859 (save-match-data
5860 ;; Diary entries sometimes have extra whitespace at the beginning
5861 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5862 (let* ((category (or category
5863 org-category
5864 (if (buffer-file-name)
5865 (file-name-sans-extension
5866 (file-name-nondirectory (buffer-file-name)))
5867 "")))
5868 (tag (or (nth (1- (length tags)) tags) ""))
5869 time ;; needed for the eval of the prefix format
5870 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5871 (time-of-day (and dotime (org-get-time-of-day ts)))
5872 stamp plain s0 s1 s2 rtn)
5873 (when (and dotime time-of-day org-prefix-has-time)
5874 ;; Extract starting and ending time and move them to prefix
5875 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5876 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5877 (setq s0 (match-string 0 ts)
5878 s1 (match-string (if plain 1 2) ts)
5879 s2 (match-string (if plain 8 4) ts))
5880
5881 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5882 ;; them, we might want to remove them there to avoid duplication.
5883 ;; The user can turn this off with a variable.
5884 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5885 (string-match (concat (regexp-quote s0) " *") txt)
5886 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5887 (= (match-beginning 0) 0)
5888 t))
5889 (setq txt (replace-match "" nil nil txt))))
5890 ;; Normalize the time(s) to 24 hour
5891 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5892 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5893
5894 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
5895 (and org-agenda-remove-tags-when-in-prefix
5896 org-prefix-has-tag))
5897 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
5898 (setq txt (replace-match "" t t txt)))
5899
5900 ;; Create the final string
5901 (if noprefix
5902 (setq rtn txt)
5903 ;; Prepare the variables needed in the eval of the compiled format
5904 (setq time (cond (s2 (concat s1 "-" s2))
5905 (s1 (concat s1 "......"))
5906 (t ""))
5907 extra (or extra "")
5908 category (if (symbolp category) (symbol-name category) category))
5909 ;; Evaluate the compiled format
5910 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5911
5912 ;; And finally add the text properties
5913 (add-text-properties
5914 0 (length rtn) (list 'category (downcase category)
5915 'tags tags
5916 'prefix-length (- (length rtn) (length txt))
5917 'time-of-day time-of-day
5918 'dotime dotime)
5919 rtn)
5920 rtn)))
5921
5922 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5923 (catch 'exit
5924 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5925 ((and todayp (member 'today (car org-agenda-time-grid))))
5926 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5927 ((member 'weekly (car org-agenda-time-grid)))
5928 (t (throw 'exit list)))
5929 (let* ((have (delq nil (mapcar
5930 (lambda (x) (get-text-property 1 'time-of-day x))
5931 list)))
5932 (string (nth 1 org-agenda-time-grid))
5933 (gridtimes (nth 2 org-agenda-time-grid))
5934 (req (car org-agenda-time-grid))
5935 (remove (member 'remove-match req))
5936 new time)
5937 (if (and (member 'require-timed req) (not have))
5938 ;; don't show empty grid
5939 (throw 'exit list))
5940 (while (setq time (pop gridtimes))
5941 (unless (and remove (member time have))
5942 (setq time (int-to-string time))
5943 (push (org-format-agenda-item
5944 nil string "" nil ;; FIXME: put a category for the grid?
5945 (concat (substring time 0 -2) ":" (substring time -2)))
5946 new)
5947 (put-text-property
5948 1 (length (car new)) 'face 'org-time-grid (car new))))
5949 (if (member 'time-up org-agenda-sorting-strategy)
5950 (append new list)
5951 (append list new)))))
5952
5953 (defun org-compile-prefix-format (format)
5954 "Compile the prefix format into a Lisp form that can be evaluated.
5955 The resulting form is returned and stored in the variable
5956 `org-prefix-format-compiled'."
5957 (setq org-prefix-has-time nil org-prefix-has-tag nil)
5958 (let ((start 0) varform vars var (s format)e c f opt)
5959 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5960 s start)
5961 (setq var (cdr (assoc (match-string 4 s)
5962 '(("c" . category) ("t" . time) ("s" . extra)
5963 ("T" . tag))))
5964 c (or (match-string 3 s) "")
5965 opt (match-beginning 1)
5966 start (1+ (match-beginning 0)))
5967 (if (equal var 'time) (setq org-prefix-has-time t))
5968 (if (equal var 'tag) (setq org-prefix-has-tag t))
5969 (setq f (concat "%" (match-string 2 s) "s"))
5970 (if opt
5971 (setq varform
5972 `(if (equal "" ,var)
5973 ""
5974 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5975 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5976 (setq s (replace-match "%s" t nil s))
5977 (push varform vars))
5978 (setq vars (nreverse vars))
5979 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5980
5981 (defun org-get-time-of-day (s &optional string)
5982 "Check string S for a time of day.
5983 If found, return it as a military time number between 0 and 2400.
5984 If not found, return nil.
5985 The optional STRING argument forces conversion into a 5 character wide string
5986 HH:MM."
5987 (save-match-data
5988 (when
5989 (or
5990 (string-match
5991 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5992 (string-match
5993 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5994 (let* ((t0 (+ (* 100
5995 (+ (string-to-number (match-string 1 s))
5996 (if (and (match-beginning 4)
5997 (equal (downcase (match-string 4 s)) "pm"))
5998 12 0)))
5999 (if (match-beginning 3)
6000 (string-to-number (match-string 3 s))
6001 0)))
6002 (t1 (concat " "
6003 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6004 (int-to-string t0))))
6005 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6006
6007 (defun org-finalize-agenda-entries (list)
6008 "Sort and concatenate the agenda items."
6009 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6010
6011 (defsubst org-cmp-priority (a b)
6012 "Compare the priorities of string A and B."
6013 (let ((pa (or (get-text-property 1 'priority a) 0))
6014 (pb (or (get-text-property 1 'priority b) 0)))
6015 (cond ((> pa pb) +1)
6016 ((< pa pb) -1)
6017 (t nil))))
6018
6019 (defsubst org-cmp-category (a b)
6020 "Compare the string values of categories of strings A and B."
6021 (let ((ca (or (get-text-property 1 'category a) ""))
6022 (cb (or (get-text-property 1 'category b) "")))
6023 (cond ((string-lessp ca cb) -1)
6024 ((string-lessp cb ca) +1)
6025 (t nil))))
6026
6027 (defsubst org-cmp-time (a b)
6028 "Compare the time-of-day values of strings A and B."
6029 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6030 (ta (or (get-text-property 1 'time-of-day a) def))
6031 (tb (or (get-text-property 1 'time-of-day b) def)))
6032 (cond ((< ta tb) -1)
6033 ((< tb ta) +1)
6034 (t nil))))
6035
6036 (defun org-entries-lessp (a b)
6037 "Predicate for sorting agenda entries."
6038 ;; The following variables will be used when the form is evaluated.
6039 (let* ((time-up (org-cmp-time a b))
6040 (time-down (if time-up (- time-up) nil))
6041 (priority-up (org-cmp-priority a b))
6042 (priority-down (if priority-up (- priority-up) nil))
6043 (category-up (org-cmp-category a b))
6044 (category-down (if category-up (- category-up) nil))
6045 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
6046 (cdr (assoc
6047 (eval (cons 'or org-agenda-sorting-strategy))
6048 '((-1 . t) (1 . nil) (nil . nil))))))
6049
6050 (defun org-agenda-show-priority ()
6051 "Show the priority of the current item.
6052 This priority is composed of the main priority given with the [#A] cookies,
6053 and by additional input from the age of a schedules or deadline entry."
6054 (interactive)
6055 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6056 (message "Priority is %d" (if pri pri -1000))))
6057
6058 (defun org-agenda-show-tags ()
6059 "Show the tags applicable to the current item."
6060 (interactive)
6061 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6062 (if tags
6063 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6064 (message "No tags associated with this line"))))
6065
6066 (defun org-agenda-goto (&optional highlight)
6067 "Go to the Org-mode file which contains the item at point."
6068 (interactive)
6069 (let* ((marker (or (get-text-property (point) 'org-marker)
6070 (org-agenda-error)))
6071 (buffer (marker-buffer marker))
6072 (pos (marker-position marker)))
6073 (switch-to-buffer-other-window buffer)
6074 (widen)
6075 (goto-char pos)
6076 (when (eq major-mode 'org-mode)
6077 (org-show-hidden-entry)
6078 (save-excursion
6079 (and (outline-next-heading)
6080 (org-flag-heading nil)))) ; show the next heading
6081 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6082
6083 (defun org-agenda-switch-to ()
6084 "Go to the Org-mode file which contains the item at point."
6085 (interactive)
6086 (let* ((marker (or (get-text-property (point) 'org-marker)
6087 (org-agenda-error)))
6088 (buffer (marker-buffer marker))
6089 (pos (marker-position marker)))
6090 (switch-to-buffer buffer)
6091 (delete-other-windows)
6092 (widen)
6093 (goto-char pos)
6094 (when (eq major-mode 'org-mode)
6095 (org-show-hidden-entry)
6096 (save-excursion
6097 (and (outline-next-heading)
6098 (org-flag-heading nil)))))) ; show the next heading
6099
6100 (defun org-agenda-goto-mouse (ev)
6101 "Go to the Org-mode file which contains the item at the mouse click."
6102 (interactive "e")
6103 (mouse-set-point ev)
6104 (org-agenda-goto))
6105
6106 (defun org-agenda-show ()
6107 "Display the Org-mode file which contains the item at point."
6108 (interactive)
6109 (let ((win (selected-window)))
6110 (org-agenda-goto t)
6111 (select-window win)))
6112
6113 (defun org-agenda-recenter (arg)
6114 "Display the Org-mode file which contains the item at point and recenter."
6115 (interactive "P")
6116 (let ((win (selected-window)))
6117 (org-agenda-goto t)
6118 (recenter arg)
6119 (select-window win)))
6120
6121 (defun org-agenda-show-mouse (ev)
6122 "Display the Org-mode file which contains the item at the mouse click."
6123 (interactive "e")
6124 (mouse-set-point ev)
6125 (org-agenda-show))
6126
6127 (defun org-agenda-check-no-diary ()
6128 "Check if the entry is a diary link and abort if yes."
6129 (if (get-text-property (point) 'org-agenda-diary-link)
6130 (org-agenda-error)))
6131
6132 (defun org-agenda-error ()
6133 (error "Command not allowed in this line"))
6134
6135 (defvar org-last-heading-marker (make-marker)
6136 "Marker pointing to the headline that last changed its TODO state
6137 by a remote command from the agenda.")
6138
6139 (defun org-agenda-todo (&optional arg)
6140 "Cycle TODO state of line at point, also in Org-mode file.
6141 This changes the line at point, all other lines in the agenda referring to
6142 the same tree node, and the headline of the tree node in the Org-mode file."
6143 (interactive "P")
6144 (org-agenda-check-no-diary)
6145 (let* ((col (current-column))
6146 (marker (or (get-text-property (point) 'org-marker)
6147 (org-agenda-error)))
6148 (buffer (marker-buffer marker))
6149 (pos (marker-position marker))
6150 (hdmarker (get-text-property (point) 'org-hd-marker))
6151 (buffer-read-only nil)
6152 newhead)
6153 (with-current-buffer buffer
6154 (widen)
6155 (goto-char pos)
6156 (org-show-hidden-entry)
6157 (save-excursion
6158 (and (outline-next-heading)
6159 (org-flag-heading nil))) ; show the next heading
6160 (org-todo arg)
6161 (forward-char 1)
6162 (setq newhead (org-get-heading))
6163 (save-excursion
6164 (org-back-to-heading)
6165 (move-marker org-last-heading-marker (point))))
6166 (beginning-of-line 1)
6167 (save-excursion
6168 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6169 (move-to-column col)))
6170
6171 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6172 "Change all lines in the agenda buffer which match HDMARKER.
6173 The new content of the line will be NEWHEAD (as modified by
6174 `org-format-agenda-item'). HDMARKER is checked with
6175 `equal' against all `org-hd-marker' text properties in the file.
6176 If FIXFACE is non-nil, the face of each item is modified acording to
6177 the new TODO state."
6178 (let* (props m pl undone-face done-face finish new dotime cat tags)
6179 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6180 (save-excursion
6181 (goto-char (point-max))
6182 (beginning-of-line 1)
6183 (while (not finish)
6184 (setq finish (bobp))
6185 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6186 (equal m hdmarker))
6187 (setq props (text-properties-at (point))
6188 dotime (get-text-property (point) 'dotime)
6189 cat (get-text-property (point) 'category)
6190 tags (get-text-property (point) 'tags)
6191 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6192 pl (get-text-property (point) 'prefix-length)
6193 undone-face (get-text-property (point) 'undone-face)
6194 done-face (get-text-property (point) 'done-face))
6195 (move-to-column pl)
6196 (if (looking-at ".*")
6197 (progn
6198 (replace-match new t t)
6199 (beginning-of-line 1)
6200 (add-text-properties (point-at-bol) (point-at-eol) props)
6201 (if fixface
6202 (add-text-properties
6203 (point-at-bol) (point-at-eol)
6204 (list 'face
6205 (if org-last-todo-state-is-todo
6206 undone-face done-face))))
6207 (beginning-of-line 1))
6208 (error "Line update did not work")))
6209 (beginning-of-line 0)))))
6210
6211 (defun org-agenda-priority-up ()
6212 "Increase the priority of line at point, also in Org-mode file."
6213 (interactive)
6214 (org-agenda-priority 'up))
6215
6216 (defun org-agenda-priority-down ()
6217 "Decrease the priority of line at point, also in Org-mode file."
6218 (interactive)
6219 (org-agenda-priority 'down))
6220
6221 (defun org-agenda-priority (&optional force-direction)
6222 "Set the priority of line at point, also in Org-mode file.
6223 This changes the line at point, all other lines in the agenda referring to
6224 the same tree node, and the headline of the tree node in the Org-mode file."
6225 (interactive)
6226 (org-agenda-check-no-diary)
6227 (let* ((marker (or (get-text-property (point) 'org-marker)
6228 (org-agenda-error)))
6229 (buffer (marker-buffer marker))
6230 (pos (marker-position marker))
6231 (hdmarker (get-text-property (point) 'org-hd-marker))
6232 (buffer-read-only nil)
6233 newhead)
6234 (with-current-buffer buffer
6235 (widen)
6236 (goto-char pos)
6237 (org-show-hidden-entry)
6238 (save-excursion
6239 (and (outline-next-heading)
6240 (org-flag-heading nil))) ; show the next heading
6241 (funcall 'org-priority force-direction)
6242 (end-of-line 1)
6243 (setq newhead (org-get-heading)))
6244 (org-agenda-change-all-lines newhead hdmarker)
6245 (beginning-of-line 1)))
6246
6247 (defun org-get-tags-at (&optional pos)
6248 "Get a list of all headline targs applicable at POS.
6249 POS defaults to point. If tags are inherited, the list contains
6250 the targets in the same sequence as the headlines appear, i.e.
6251 the tags of the current headline come last."
6252 (interactive)
6253 (let (tags)
6254 (save-excursion
6255 (goto-char (or pos (point)))
6256 (save-match-data
6257 (org-back-to-heading t)
6258 (condition-case nil
6259 (while t
6260 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6261 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6262 (or org-use-tag-inheritance (error ""))
6263 (org-up-heading-all 1))
6264 (error nil))))
6265 (message "%s" tags)
6266 tags))
6267
6268 (defun org-agenda-set-tags ()
6269 "Set tags for the current headline."
6270 (interactive)
6271 (org-agenda-check-no-diary)
6272 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6273 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6274 (org-agenda-error)))
6275 (buffer (marker-buffer hdmarker))
6276 (pos (marker-position hdmarker))
6277 (buffer-read-only nil)
6278 newhead)
6279 (with-current-buffer buffer
6280 (widen)
6281 (goto-char pos)
6282 (org-show-hidden-entry)
6283 (save-excursion
6284 (and (outline-next-heading)
6285 (org-flag-heading nil))) ; show the next heading
6286 (call-interactively 'org-set-tags)
6287 (end-of-line 1)
6288 (setq newhead (org-get-heading)))
6289 (org-agenda-change-all-lines newhead hdmarker)
6290 (beginning-of-line 1)))
6291
6292 (defun org-agenda-date-later (arg &optional what)
6293 "Change the date of this item to one day later."
6294 (interactive "p")
6295 (org-agenda-check-type t 'agenda 'timeline)
6296 (org-agenda-check-no-diary)
6297 (let* ((marker (or (get-text-property (point) 'org-marker)
6298 (org-agenda-error)))
6299 (buffer (marker-buffer marker))
6300 (pos (marker-position marker)))
6301 (with-current-buffer buffer
6302 (widen)
6303 (goto-char pos)
6304 (if (not (org-at-timestamp-p))
6305 (error "Cannot find time stamp"))
6306 (org-timestamp-change arg (or what 'day))
6307 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6308
6309 (defun org-agenda-date-earlier (arg &optional what)
6310 "Change the date of this item to one day earlier."
6311 (interactive "p")
6312 (org-agenda-date-later (- arg) what))
6313
6314 (defun org-agenda-date-prompt (arg)
6315 "Change the date of this item. Date is prompted for, with default today.
6316 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6317 be used to request time specification in the time stamp."
6318 (interactive "P")
6319 (org-agenda-check-type t 'agenda 'timeline)
6320 (org-agenda-check-no-diary)
6321 (let* ((marker (or (get-text-property (point) 'org-marker)
6322 (org-agenda-error)))
6323 (buffer (marker-buffer marker))
6324 (pos (marker-position marker)))
6325 (with-current-buffer buffer
6326 (widen)
6327 (goto-char pos)
6328 (if (not (org-at-timestamp-p))
6329 (error "Cannot find time stamp"))
6330 (org-time-stamp arg)
6331 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6332
6333 (defun org-get-heading ()
6334 "Return the heading of the current entry, without the stars."
6335 (save-excursion
6336 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6337 ;;FIXME???????? (and (bolp) (end-of-line 1))
6338 (if (and (re-search-backward "[\r\n]\\*" nil t)
6339 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6340 (match-string 1)
6341 "")))
6342
6343 (defun org-agenda-diary-entry ()
6344 "Make a diary entry, like the `i' command from the calendar.
6345 All the standard commands work: block, weekly etc."
6346 (interactive)
6347 (org-agenda-check-type t 'agenda 'timeline)
6348 (require 'diary-lib)
6349 (let* ((char (progn
6350 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6351 (read-char-exclusive)))
6352 (cmd (cdr (assoc char
6353 '((?d . insert-diary-entry)
6354 (?w . insert-weekly-diary-entry)
6355 (?m . insert-monthly-diary-entry)
6356 (?y . insert-yearly-diary-entry)
6357 (?a . insert-anniversary-diary-entry)
6358 (?b . insert-block-diary-entry)
6359 (?c . insert-cyclic-diary-entry)))))
6360 (oldf (symbol-function 'calendar-cursor-to-date))
6361 (point (point))
6362 (mark (or (mark t) (point))))
6363 (unless cmd
6364 (error "No command associated with <%c>" char))
6365 (unless (and (get-text-property point 'day)
6366 (or (not (equal ?b char))
6367 (get-text-property mark 'day)))
6368 (error "Don't know which date to use for diary entry"))
6369 ;; We implement this by hacking the `calendar-cursor-to-date' function
6370 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6371 (let ((calendar-mark-ring
6372 (list (calendar-gregorian-from-absolute
6373 (or (get-text-property mark 'day)
6374 (get-text-property point 'day))))))
6375 (unwind-protect
6376 (progn
6377 (fset 'calendar-cursor-to-date
6378 (lambda (&optional error)
6379 (calendar-gregorian-from-absolute
6380 (get-text-property point 'day))))
6381 (call-interactively cmd))
6382 (fset 'calendar-cursor-to-date oldf)))))
6383
6384
6385 (defun org-agenda-execute-calendar-command (cmd)
6386 "Execute a calendar command from the agenda, with the date associated to
6387 the cursor position."
6388 (org-agenda-check-type t 'agenda 'timeline)
6389 (require 'diary-lib)
6390 (unless (get-text-property (point) 'day)
6391 (error "Don't know which date to use for calendar command"))
6392 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6393 (point (point))
6394 (date (calendar-gregorian-from-absolute
6395 (get-text-property point 'day)))
6396 (displayed-day (extract-calendar-day date))
6397 (displayed-month (extract-calendar-month date))
6398 (displayed-year (extract-calendar-year date)))
6399 (unwind-protect
6400 (progn
6401 (fset 'calendar-cursor-to-date
6402 (lambda (&optional error)
6403 (calendar-gregorian-from-absolute
6404 (get-text-property point 'day))))
6405 (call-interactively cmd))
6406 (fset 'calendar-cursor-to-date oldf))))
6407
6408 (defun org-agenda-phases-of-moon ()
6409 "Display the phases of the moon for the 3 months around the cursor date."
6410 (interactive)
6411 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6412
6413 (defun org-agenda-holidays ()
6414 "Display the holidays for the 3 months around the cursor date."
6415 (interactive)
6416 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6417
6418 (defun org-agenda-sunrise-sunset (arg)
6419 "Display sunrise and sunset for the cursor date.
6420 Latitude and longitude can be specified with the variables
6421 `calendar-latitude' and `calendar-longitude'. When called with prefix
6422 argument, latitude and longitude will be prompted for."
6423 (interactive "P")
6424 (let ((calendar-longitude (if arg nil calendar-longitude))
6425 (calendar-latitude (if arg nil calendar-latitude))
6426 (calendar-location-name
6427 (if arg "the given coordinates" calendar-location-name)))
6428 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6429
6430 (defun org-agenda-goto-calendar ()
6431 "Open the Emacs calendar with the date at the cursor."
6432 (interactive)
6433 (org-agenda-check-type t 'agenda 'timeline)
6434 (let* ((day (or (get-text-property (point) 'day)
6435 (error "Don't know which date to open in calendar")))
6436 (date (calendar-gregorian-from-absolute day))
6437 (calendar-move-hook nil)
6438 (view-diary-entries-initially nil))
6439 (calendar)
6440 (calendar-goto-date date)))
6441
6442 (defun org-calendar-goto-agenda ()
6443 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6444 This is a command that has to be installed in `calendar-mode-map'."
6445 (interactive)
6446 (org-agenda-list nil (calendar-absolute-from-gregorian
6447 (calendar-cursor-to-date))
6448 nil t))
6449
6450 (defun org-agenda-convert-date ()
6451 (interactive)
6452 (org-agenda-check-type t 'agenda 'timeline)
6453 (let ((day (get-text-property (point) 'day))
6454 date s)
6455 (unless day
6456 (error "Don't know which date to convert"))
6457 (setq date (calendar-gregorian-from-absolute day))
6458 (setq s (concat
6459 "Gregorian: " (calendar-date-string date) "\n"
6460 "ISO: " (calendar-iso-date-string date) "\n"
6461 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6462 "Julian: " (calendar-julian-date-string date) "\n"
6463 "Astron. JD: " (calendar-astro-date-string date)
6464 " (Julian date number at noon UTC)\n"
6465 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6466 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6467 "French: " (calendar-french-date-string date) "\n"
6468 "Mayan: " (calendar-mayan-date-string date) "\n"
6469 "Coptic: " (calendar-coptic-date-string date) "\n"
6470 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6471 "Persian: " (calendar-persian-date-string date) "\n"
6472 "Chinese: " (calendar-chinese-date-string date) "\n"))
6473 (with-output-to-temp-buffer "*Dates*"
6474 (princ s))
6475 (if (fboundp 'fit-window-to-buffer)
6476 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6477
6478 ;;; Tags
6479
6480 (defun org-scan-tags (action matcher &optional todo-only)
6481 "Scan headline tags with inheritance and produce output ACTION.
6482 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6483 evaluated, testing if a given set of tags qualifies a headline for
6484 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6485 are included in the output."
6486 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6487 (mapconcat 'regexp-quote
6488 (nreverse (cdr (reverse org-todo-keywords)))
6489 "\\|")
6490 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6491 (props (list 'face nil
6492 'done-face 'org-done
6493 'undone-face nil
6494 'mouse-face 'highlight
6495 'keymap org-agenda-keymap
6496 'help-echo
6497 (format "mouse-2 or RET jump to org file %s"
6498 (abbreviate-file-name (buffer-file-name)))))
6499 lspos
6500 tags tags-list tags-alist (llast 0) rtn level category i txt
6501 todo marker)
6502
6503 (save-excursion
6504 (goto-char (point-min))
6505 (when (eq action 'sparse-tree) (hide-sublevels 1))
6506 (while (re-search-forward re nil t)
6507 (setq todo (if (match-end 1) (match-string 2))
6508 tags (if (match-end 4) (match-string 4)))
6509 (goto-char (setq lspos (1+ (match-beginning 0))))
6510 (setq level (outline-level)
6511 category (org-get-category))
6512 (setq i llast llast level)
6513 ;; remove tag lists from same and sublevels
6514 (while (>= i level)
6515 (when (setq entry (assoc i tags-alist))
6516 (setq tags-alist (delete entry tags-alist)))
6517 (setq i (1- i)))
6518 ;; add the nex tags
6519 (when tags
6520 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6521 tags-alist
6522 (cons (cons level tags) tags-alist)))
6523 ;; compile tags for current headline
6524 (setq tags-list
6525 (if org-use-tag-inheritance
6526 (apply 'append (mapcar 'cdr tags-alist))
6527 tags))
6528 (when (and (or (not todo-only) todo)
6529 (eval matcher))
6530 ;; list this headline
6531 (if (eq action 'sparse-tree)
6532 (progn
6533 (org-show-hierarchy-above))
6534 (setq txt (org-format-agenda-item
6535 ""
6536 (concat
6537 (if org-tags-match-list-sublevels
6538 (make-string (1- level) ?.) "")
6539 (org-get-heading))
6540 category tags-list))
6541 (goto-char lspos)
6542 (setq marker (org-agenda-new-marker))
6543 (add-text-properties
6544 0 (length txt)
6545 (append (list 'org-marker marker 'org-hd-marker marker
6546 'category category)
6547 props)
6548 txt)
6549 (push txt rtn))
6550 ;; if we are to skip sublevels, jump to end of subtree
6551 (point)
6552 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6553 (nreverse rtn)))
6554
6555 (defun org-tags-sparse-tree (&optional arg match)
6556 "Create a sparse tree according to tags search string MATCH.
6557 MATCH can contain positive and negative selection of tags, like
6558 \"+WORK+URGENT-WITHBOSS\"."
6559 (interactive "P")
6560 (let ((org-show-following-heading nil)
6561 (org-show-hierarchy-above nil))
6562 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6563
6564 (defun org-make-tags-matcher (match)
6565 "Create the TAGS matcher form for the tags-selecting string MATCH."
6566 (unless match
6567 ;; Get a new match request, with completion
6568 (setq org-last-tags-completion-table
6569 (or (org-get-buffer-tags)
6570 org-last-tags-completion-table))
6571 (setq match (completing-read
6572 "Tags: " 'org-tags-completion-function nil nil nil
6573 'org-tags-history)))
6574 ;; parse the string and create a lisp form
6575 (let ((match0 match) minus tag mm matcher orterms term orlist)
6576 (setq orterms (org-split-string match "|"))
6577 (while (setq term (pop orterms))
6578 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
6579 (setq minus (and (match-end 1)
6580 (equal (match-string 1 term) "-"))
6581 tag (match-string 2 term)
6582 term (substring term (match-end 0))
6583 mm (list 'member (downcase tag) 'tags-list)
6584 mm (if minus (list 'not mm) mm))
6585 (push mm matcher))
6586 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6587 orlist)
6588 (setq matcher nil))
6589 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6590 ;; Return the string and lisp forms of the matcher
6591 (cons match0 matcher)))
6592
6593 ;;;###autoload
6594 (defun org-tags-view (&optional todo-only match keep-modes)
6595 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
6596 The prefix arg TODO-ONLY limits the search to TODO entries."
6597 (interactive "P")
6598 (org-agenda-maybe-reset-markers 'force)
6599 (org-compile-prefix-format org-agenda-prefix-format)
6600 (let* ((org-agenda-keep-modes keep-modes)
6601 (org-tags-match-list-sublevels
6602 (if todo-only t org-tags-match-list-sublevels))
6603 (win (selected-window))
6604 (completion-ignore-case t)
6605 rtn rtnall files file pos matcher
6606 buffer)
6607 (setq matcher (org-make-tags-matcher match)
6608 match (car matcher) matcher (cdr matcher))
6609 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6610 (progn
6611 (delete-other-windows)
6612 (switch-to-buffer-other-window
6613 (get-buffer-create org-agenda-buffer-name))))
6614 (setq buffer-read-only nil)
6615 (erase-buffer)
6616 (org-agenda-mode) (setq buffer-read-only nil)
6617 (set (make-local-variable 'org-agenda-type) 'tags)
6618 (set (make-local-variable 'org-agenda-redo-command)
6619 (list 'org-tags-view (list 'quote todo-only)
6620 (list 'if 'current-prefix-arg nil match) t))
6621 (setq files (org-agenda-files)
6622 rtnall nil)
6623 (while (setq file (pop files))
6624 (catch 'nextfile
6625 (org-check-agenda-file file)
6626 (setq buffer (if (file-exists-p file)
6627 (org-get-agenda-file-buffer file)
6628 (error "No such file %s" file)))
6629 (if (not buffer)
6630 ;; If file does not exist, merror message to agenda
6631 (setq rtn (list
6632 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6633 rtnall (append rtnall rtn))
6634 (with-current-buffer buffer
6635 (unless (eq major-mode 'org-mode)
6636 (error "Agenda file %s is not in `org-mode'" file))
6637 (save-excursion
6638 (save-restriction
6639 (if org-respect-restriction
6640 (if (org-region-active-p)
6641 ;; Respect a region to restrict search
6642 (narrow-to-region (region-beginning) (region-end)))
6643 ;; If we work for the calendar or many files,
6644 ;; get rid of any restriction
6645 (widen))
6646 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6647 (setq rtnall (append rtnall rtn))))))))
6648 (insert "Headlines with TAGS match: ")
6649 (add-text-properties (point-min) (1- (point))
6650 (list 'face 'org-link))
6651 (setq pos (point))
6652 (insert match "\n")
6653 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6654 (setq pos (point))
6655 (insert "Press `C-u r' to search again with new search string\n")
6656 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6657 (when rtnall
6658 (insert (mapconcat 'identity rtnall "\n")))
6659 (goto-char (point-min))
6660 (setq buffer-read-only t)
6661 (org-fit-agenda-window)
6662 (if (not org-select-agenda-window) (select-window win))))
6663
6664 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6665 (defun org-set-tags (&optional arg just-align)
6666 "Set the tags for the current headline.
6667 With prefix ARG, realign all tags in headings in the current buffer."
6668 (interactive)
6669 (let* (;(inherit (org-get-inherited-tags))
6670 (re (concat "^" outline-regexp))
6671 (col (current-column))
6672 (current (org-get-tags))
6673 tags hd empty invis)
6674 (if arg
6675 (save-excursion
6676 (goto-char (point-min))
6677 (while (re-search-forward re nil t)
6678 (org-set-tags nil t))
6679 (message "All tags realigned to column %d" org-tags-column))
6680 (if just-align
6681 (setq tags current)
6682 (setq org-last-tags-completion-table
6683 (or (org-get-buffer-tags)
6684 org-last-tags-completion-table))
6685 (setq tags
6686 (let ((org-add-colon-after-tag-completion t))
6687 (completing-read "Tags: " 'org-tags-completion-function
6688 nil nil current 'org-tags-history)))
6689 (while (string-match "[-+&]+" tags)
6690 (setq tags (replace-match ":" t t tags))))
6691 ;; FIXME: still optimize this byt not checking when JUST-ALIGN?
6692 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6693 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6694 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
6695 (if (equal current "")
6696 (progn
6697 (end-of-line 1)
6698 (or empty (insert-before-markers " ")))
6699 (beginning-of-line 1)
6700 (setq invis (org-invisible-p))
6701 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6702 (setq hd (match-string 1))
6703 (delete-region (match-beginning 0) (match-end 0))
6704 (insert-before-markers (org-trim hd) (if empty "" " ")))
6705 ;; FIXME: What happens when adding a new tag??? Seems OK!!!
6706 (unless (equal tags "")
6707 (move-to-column (max (current-column)
6708 (if (> org-tags-column 0)
6709 org-tags-column
6710 (- (- org-tags-column) (length tags))))
6711 t)
6712 (insert-before-markers tags)
6713 (if (and (not invis) (org-invisible-p))
6714 (outline-flag-region (point-at-bol) (point) nil)))
6715 (move-to-column col))))
6716
6717 (defun org-tags-completion-function (string predicate &optional flag)
6718 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6719 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6720 (setq s1 (match-string 1 string)
6721 s2 (match-string 2 string))
6722 (setq s1 "" s2 string))
6723 (cond
6724 ((eq flag nil)
6725 ;; try completion
6726 (setq rtn (try-completion s2 ctable))
6727 (if (stringp rtn)
6728 (concat s1 s2 (substring rtn (length s2))
6729 (if (and org-add-colon-after-tag-completion
6730 (assoc rtn ctable))
6731 ":" "")))
6732 )
6733 ((eq flag t)
6734 ;; all-completions
6735 (all-completions s2 ctable)
6736 )
6737 ((eq flag 'lambda)
6738 ;; exact match?
6739 (assoc s2 ctable)))
6740 ))
6741
6742 (defun org-get-tags ()
6743 "Get the TAGS string in the current headline."
6744 (unless (org-on-heading-p)
6745 (error "Not on a heading"))
6746 (save-excursion
6747 (beginning-of-line 1)
6748 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
6749 (match-string 1)
6750 "")))
6751
6752 (defun org-get-buffer-tags ()
6753 "Get a table of all tags used in the buffer, for completion."
6754 (let (tags)
6755 (save-excursion
6756 (goto-char (point-min))
6757 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
6758 (mapc (lambda (x) (add-to-list 'tags x))
6759 (org-split-string (match-string 1) ":"))))
6760 (mapcar 'list tags)))
6761
6762 ;;; Link Stuff
6763
6764 (defun org-find-file-at-mouse (ev)
6765 "Open file link or URL at mouse."
6766 (interactive "e")
6767 (mouse-set-point ev)
6768 (org-open-at-point 'in-emacs))
6769
6770 (defun org-open-at-mouse (ev)
6771 "Open file link or URL at mouse."
6772 (interactive "e")
6773 (mouse-set-point ev)
6774 (org-open-at-point))
6775
6776 (defun org-open-at-point (&optional in-emacs)
6777 "Open link at or after point.
6778 If there is no link at point, this function will search forward up to
6779 the end of the current subtree.
6780 Normally, files will be opened by an appropriate application. If the
6781 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6782 (interactive "P")
6783 (org-remove-occur-highlights nil nil t)
6784 (if (org-at-timestamp-p)
6785 (org-agenda-list nil (time-to-days (org-time-string-to-time
6786 (substring (match-string 1) 0 10)))
6787 1)
6788 (let (type path link line search (pos (point)))
6789 (catch 'match
6790 (save-excursion
6791 (skip-chars-forward "^]\n\r")
6792 (when (and (re-search-backward "\\[\\[" nil t)
6793 (looking-at org-bracket-link-regexp)
6794 (<= (match-beginning 0) pos)
6795 (>= (match-end 0) pos))
6796 (setq link (match-string 1))
6797 (while (string-match " *\n *" link)
6798 (setq link (replace-match " " t t link)))
6799 (if (string-match org-link-regexp link)
6800 (setq type (match-string 1)
6801 path (match-string 2))
6802 (setq type "thisfile"
6803 path link))
6804 (throw 'match t)))
6805
6806 (when (get-text-property (point) 'org-linked-text)
6807 (setq type "thisfile"
6808 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6809 (1+ (point)) (point))
6810 path (buffer-substring
6811 (previous-single-property-change pos 'org-linked-text)
6812 (next-single-property-change pos 'org-linked-text)))
6813 (throw 'match t))
6814
6815 (save-excursion
6816 (skip-chars-backward
6817 (concat (if org-allow-space-in-links "^" "^ ")
6818 org-non-link-chars))
6819 (when (or (looking-at org-link-regexp)
6820 (and (re-search-forward org-link-regexp (point-at-eol) t)
6821 (<= (match-beginning 0) pos)
6822 (>= (match-end 0) pos)))
6823 (setq type (match-string 1)
6824 path (match-string 2))
6825 (throw 'match t)))
6826 (save-excursion
6827 (skip-chars-backward "^ \t\n\r")
6828 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
6829 (setq type "tags"
6830 path (match-string 1))
6831 (while (string-match ":" path)
6832 (setq path (replace-match "+" t t path)))
6833 (throw 'match t)))
6834 (save-excursion
6835 (skip-chars-backward "a-zA-Z_")
6836 (when (and org-activate-camels
6837 (looking-at org-camel-regexp))
6838 (setq type "camel" path (match-string 0))
6839 (if (equal (char-before) ?*)
6840 (setq path (concat "*" path))))
6841 (throw 'match t))
6842 (save-excursion
6843 (when (re-search-forward
6844 org-link-regexp
6845 (save-excursion
6846 (condition-case nil
6847 (progn (outline-end-of-subtree) (max pos (point)))
6848 (error (end-of-line 1) (point))))
6849 t)
6850 (setq type (match-string 1)
6851 path (match-string 2)))))
6852 (unless path
6853 (error "No link found"))
6854 ;; Remove any trailing spaces in path
6855 (if (string-match " +\\'" path)
6856 (setq path (replace-match "" t t path)))
6857
6858 (cond
6859
6860 ((string= type "tags")
6861 (org-tags-view in-emacs path))
6862 ((or (string= type "camel")
6863 (string= type "thisfile"))
6864 (org-mark-ring-push)
6865 (org-link-search
6866 path
6867 (cond ((equal in-emacs '(4)) 'occur)
6868 ((equal in-emacs '(16)) 'org-occur)
6869 (t nil))))
6870
6871 ((string= type "file")
6872 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6873 (setq line (string-to-number (match-string 1 path))
6874 path (substring path 0 (match-beginning 0)))
6875 (if (string-match "::\\(.+\\)\\'" path)
6876 (setq search (match-string 1 path)
6877 path (substring path 0 (match-beginning 0)))))
6878 (org-open-file path in-emacs line search))
6879
6880 ((string= type "news")
6881 (org-follow-gnus-link path))
6882
6883 ((string= type "bbdb")
6884 (org-follow-bbdb-link path))
6885
6886 ((string= type "gnus")
6887 (let (group article)
6888 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6889 (error "Error in Gnus link"))
6890 (setq group (match-string 1 path)
6891 article (match-string 3 path))
6892 (org-follow-gnus-link group article)))
6893
6894 ((string= type "vm")
6895 (let (folder article)
6896 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6897 (error "Error in VM link"))
6898 (setq folder (match-string 1 path)
6899 article (match-string 3 path))
6900 ;; in-emacs is the prefix arg, will be interpreted as read-only
6901 (org-follow-vm-link folder article in-emacs)))
6902
6903 ((string= type "wl")
6904 (let (folder article)
6905 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6906 (error "Error in Wanderlust link"))
6907 (setq folder (match-string 1 path)
6908 article (match-string 3 path))
6909 (org-follow-wl-link folder article)))
6910
6911 ((string= type "mhe")
6912 (let (folder article)
6913 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6914 (error "Error in MHE link"))
6915 (setq folder (match-string 1 path)
6916 article (match-string 3 path))
6917 (org-follow-mhe-link folder article)))
6918
6919 ((string= type "rmail")
6920 (let (folder article)
6921 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6922 (error "Error in RMAIL link"))
6923 (setq folder (match-string 1 path)
6924 article (match-string 3 path))
6925 (org-follow-rmail-link folder article)))
6926
6927 ((string= type "shell")
6928 (let ((cmd path))
6929 (while (string-match "@{" cmd)
6930 (setq cmd (replace-match "<" t t cmd)))
6931 (while (string-match "@}" cmd)
6932 (setq cmd (replace-match ">" t t cmd)))
6933 (if (or (not org-confirm-shell-links)
6934 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6935 (shell-command cmd)
6936 (error "Abort"))))
6937
6938 (t
6939 (browse-url-at-point))))))
6940
6941 (defun org-link-search (s &optional type)
6942 "Search for a link search option.
6943 When S is a CamelCaseWord, search for a target, or for a sentence containing
6944 the words. If S is surrounded by forward slashes, it is interpreted as a
6945 regular expression. In org-mode files, this will create an `org-occur'
6946 sparse tree. In ordinary files, `occur' will be used to list matches.
6947 If the current buffer is in `dired-mode', grep will be used to search
6948 in all files."
6949 (let ((case-fold-search t)
6950 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6951 (pos (point))
6952 (pre "") (post "")
6953 words re0 re1 re2 re3 re4 re5 reall camel)
6954 (cond ((save-excursion
6955 (goto-char (point-min))
6956 (and
6957 (re-search-forward
6958 (concat "<<" (regexp-quote s0) ">>") nil t)
6959 (setq pos (match-beginning 0))))
6960 ;; There is an exact target for this
6961 (goto-char pos))
6962 ((string-match "^/\\(.*\\)/$" s)
6963 ;; A regular expression
6964 (cond
6965 ((eq major-mode 'org-mode)
6966 (org-occur (match-string 1 s)))
6967 ;;((eq major-mode 'dired-mode)
6968 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6969 (t (org-do-occur (match-string 1 s)))))
6970 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
6971 t)
6972 ;; A camel or a normal search string
6973 (when (equal (string-to-char s) ?*)
6974 ;; Anchor on headlines, post may include tags.
6975 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6976 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
6977 s (substring s 1)))
6978 (remove-text-properties
6979 0 (length s)
6980 '(face nil mouse-face nil keymap nil fontified nil) s)
6981 ;; Make a series of regular expressions to find a match
6982 (setq words
6983 (if camel
6984 (org-camel-to-words s)
6985 (org-split-string s "[ \n\r\t]+"))
6986 re0 (concat "<<" (regexp-quote s0) ">>")
6987 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6988 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6989 re1 (concat pre re2 post)
6990 re3 (concat pre re4 post)
6991 re5 (concat pre ".*" re4)
6992 re2 (concat pre re2)
6993 re4 (concat pre re4)
6994 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6995 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6996 re5 "\\)"
6997 ))
6998 (cond
6999 ((eq type 'org-occur) (org-occur reall))
7000 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7001 (t (goto-char (point-min))
7002 (if (or (re-search-forward re0 nil t)
7003 (re-search-forward re1 nil t)
7004 (re-search-forward re2 nil t)
7005 (re-search-forward re3 nil t)
7006 (re-search-forward re4 nil t)
7007 (re-search-forward re5 nil t))
7008 (goto-char (match-beginning 0))
7009 (goto-char pos)
7010 (error "No match")))))
7011 (t
7012 ;; Normal string-search
7013 (goto-char (point-min))
7014 (if (search-forward s nil t)
7015 (goto-char (match-beginning 0))
7016 (error "No match"))))
7017 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7018
7019 (defun org-do-occur (regexp &optional cleanup)
7020 "Call the Emacs command `occur'.
7021 If CLEANUP is non-nil, remove the printout of the regular expression
7022 in the *Occur* buffer. This is useful if the regex is long and not useful
7023 to read."
7024 (occur regexp)
7025 (when cleanup
7026 (let ((cwin (selected-window)) win beg end)
7027 (when (setq win (get-buffer-window "*Occur*"))
7028 (select-window win))
7029 (goto-char (point-min))
7030 (when (re-search-forward "match[a-z]+" nil t)
7031 (setq beg (match-end 0))
7032 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7033 (setq end (1- (match-beginning 0)))))
7034 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7035 (goto-char (point-min))
7036 (select-window cwin))))
7037
7038 (defvar org-mark-ring nil
7039 "Mark ring for positions before jumps in Org-mode.")
7040 (defvar org-mark-ring-last-goto nil
7041 "Last position in the mark ring used to go back.")
7042 ;; Fill and close the ring
7043 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7044 (loop for i from 1 to org-mark-ring-length do
7045 (push (make-marker) org-mark-ring))
7046 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7047 org-mark-ring)
7048
7049 (defun org-mark-ring-push (&optional pos buffer)
7050 "Put the current position or POS into the mark ring and rotate it."
7051 (interactive)
7052 (setq pos (or pos (point)))
7053 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7054 (move-marker (car org-mark-ring)
7055 (or pos (point))
7056 (or buffer (current-buffer)))
7057 (message
7058 (substitute-command-keys
7059 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7060
7061 (defun org-mark-ring-goto (&optional n)
7062 "Jump to the previous position in the mark ring.
7063 With prefix arg N, jump back that many stored positions. When
7064 called several times in succession, walk through the entire ring.
7065 Org-mode commands jumping to a different position in the current file,
7066 or to another Org-mode file, automatically push the old position
7067 onto the ring."
7068 (interactive "p")
7069 (let (p m)
7070 (if (eq last-command this-command)
7071 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7072 (setq p org-mark-ring))
7073 (setq org-mark-ring-last-goto p)
7074 (setq m (car p))
7075 (switch-to-buffer (marker-buffer m))
7076 (goto-char m)
7077 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7078
7079 (defun org-camel-to-words (s)
7080 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7081 (let ((case-fold-search nil)
7082 words)
7083 (while (string-match "[a-z][A-Z]" s)
7084 (push (substring s 0 (1+ (match-beginning 0))) words)
7085 (setq s (substring s (1+ (match-beginning 0)))))
7086 (nreverse (cons s words))))
7087
7088 (defun org-remove-angle-brackets (s)
7089 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7090 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7091 s)
7092 (defun org-add-angle-brackets (s)
7093 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7094 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7095 s)
7096
7097 (defun org-follow-bbdb-link (name)
7098 "Follow a BBDB link to NAME."
7099 (require 'bbdb)
7100 (let ((inhibit-redisplay t)
7101 (bbdb-electric-p nil))
7102 (catch 'exit
7103 ;; Exact match on name
7104 (bbdb-name (concat "\\`" name "\\'") nil)
7105 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7106 ;; Exact match on name
7107 (bbdb-company (concat "\\`" name "\\'") nil)
7108 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7109 ;; Partial match on name
7110 (bbdb-name name nil)
7111 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7112 ;; Partial match on company
7113 (bbdb-company name nil)
7114 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7115 ;; General match including network address and notes
7116 (bbdb name nil)
7117 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7118 (delete-window (get-buffer-window "*BBDB*"))
7119 (error "No matching BBDB record")))))
7120
7121 (defun org-follow-gnus-link (&optional group article)
7122 "Follow a Gnus link to GROUP and ARTICLE."
7123 (require 'gnus)
7124 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7125 (if group (gnus-fetch-group group))
7126 (if article
7127 (or (gnus-summary-goto-article article nil 'force)
7128 (if (fboundp 'gnus-summary-insert-cached-articles)
7129 (progn
7130 (gnus-summary-insert-cached-articles)
7131 (gnus-summary-goto-article article nil 'force))
7132 (message "Message could not be found.")))))
7133
7134 (defun org-follow-vm-link (&optional folder article readonly)
7135 "Follow a VM link to FOLDER and ARTICLE."
7136 (require 'vm)
7137 (setq article (org-add-angle-brackets article))
7138 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7139 ;; ange-ftp or efs or tramp access
7140 (let ((user (or (match-string 1 folder) (user-login-name)))
7141 (host (match-string 2 folder))
7142 (file (match-string 3 folder)))
7143 (cond
7144 ((featurep 'tramp)
7145 ;; use tramp to access the file
7146 (if org-xemacs-p
7147 (setq folder (format "[%s@%s]%s" user host file))
7148 (setq folder (format "/%s@%s:%s" user host file))))
7149 (t
7150 ;; use ange-ftp or efs
7151 (require (if org-xemacs-p 'efs 'ange-ftp))
7152 (setq folder (format "/%s@%s:%s" user host file))))))
7153 (when folder
7154 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7155 (sit-for 0.1)
7156 (when article
7157 (vm-select-folder-buffer)
7158 (widen)
7159 (let ((case-fold-search t))
7160 (goto-char (point-min))
7161 (if (not (re-search-forward
7162 (concat "^" "message-id: *" (regexp-quote article))))
7163 (error "Could not find the specified message in this folder"))
7164 (vm-isearch-update)
7165 (vm-isearch-narrow)
7166 (vm-beginning-of-message)
7167 (vm-summarize)))))
7168
7169 (defun org-follow-wl-link (folder article)
7170 "Follow a Wanderlust link to FOLDER and ARTICLE."
7171 (setq article (org-add-angle-brackets article))
7172 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7173 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7174 (wl-summary-redisplay))
7175
7176 (defun org-follow-rmail-link (folder article)
7177 "Follow an RMAIL link to FOLDER and ARTICLE."
7178 (setq article (org-add-angle-brackets article))
7179 (let (message-number)
7180 (save-excursion
7181 (save-window-excursion
7182 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7183 (setq message-number
7184 (save-restriction
7185 (widen)
7186 (goto-char (point-max))
7187 (if (re-search-backward
7188 (concat "^Message-ID:\\s-+" (regexp-quote
7189 (or article "")))
7190 nil t)
7191 (rmail-what-message))))))
7192 (if message-number
7193 (progn
7194 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7195 (rmail-show-message message-number)
7196 message-number)
7197 (error "Message not found"))))
7198
7199 ;; mh-e integration based on planner-mode
7200 (defun org-mhe-get-message-real-folder ()
7201 "Return the name of the current message real folder, so if you use
7202 sequences, it will now work."
7203 (save-excursion
7204 (let* ((folder
7205 (if (equal major-mode 'mh-folder-mode)
7206 mh-current-folder
7207 ;; Refer to the show buffer
7208 mh-show-folder-buffer))
7209 (end-index
7210 (if (boundp 'mh-index-folder)
7211 (min (length mh-index-folder) (length folder))))
7212 )
7213 ;; a simple test on mh-index-data does not work, because
7214 ;; mh-index-data is always nil in a show buffer.
7215 (if (and (boundp 'mh-index-folder)
7216 (string= mh-index-folder (substring folder 0 end-index)))
7217 (if (equal major-mode 'mh-show-mode)
7218 (save-window-excursion
7219 (when (buffer-live-p (get-buffer folder))
7220 (progn
7221 (pop-to-buffer folder)
7222 (org-mhe-get-message-folder-from-index)
7223 )
7224 ))
7225 (org-mhe-get-message-folder-from-index)
7226 )
7227 folder
7228 )
7229 )))
7230
7231 (defun org-mhe-get-message-folder-from-index ()
7232 "Returns the name of the message folder in a index folder buffer."
7233 (save-excursion
7234 (mh-index-previous-folder)
7235 (if (not (re-search-forward "^\\(+.*\\)$" nil t))
7236 (message "Problem getting folder from index.")
7237 (message (match-string 1)))))
7238
7239 (defun org-mhe-get-message-folder ()
7240 "Return the name of the current message folder. Be careful if you
7241 use sequences."
7242 (save-excursion
7243 (if (equal major-mode 'mh-folder-mode)
7244 mh-current-folder
7245 ;; Refer to the show buffer
7246 mh-show-folder-buffer)))
7247
7248 (defun org-mhe-get-message-num ()
7249 "Return the number of the current message. Be careful if you
7250 use sequences."
7251 (save-excursion
7252 (if (equal major-mode 'mh-folder-mode)
7253 (mh-get-msg-num nil)
7254 ;; Refer to the show buffer
7255 (mh-show-buffer-message-number))))
7256
7257 (defun org-mhe-get-header (header)
7258 "Return a header of the message in folder mode. This will create a
7259 show buffer for the corresponding message. If you have a more clever
7260 idea..."
7261 (let* ((folder (org-mhe-get-message-folder))
7262 (num (org-mhe-get-message-num))
7263 (buffer (get-buffer-create (concat "show-" folder)))
7264 (header-field))
7265 (with-current-buffer buffer
7266 (mh-display-msg num folder)
7267 (if (equal major-mode 'mh-folder-mode)
7268 (mh-header-display)
7269 (mh-show-header-display))
7270 (set-buffer buffer)
7271 (setq header-field (mh-get-header-field header))
7272 (if (equal major-mode 'mh-folder-mode)
7273 (mh-show)
7274 (mh-show-show))
7275 header-field)))
7276
7277 (defun org-follow-mhe-link (folder article)
7278 "Follow an MHE link to FOLDER and ARTICLE."
7279 (setq article (org-add-angle-brackets article))
7280 (require 'mh-e)
7281 (mh-find-path)
7282 (let* ((show-buf (concat "show-" folder)))
7283 (mh-visit-folder folder)
7284 (get-buffer-create show-buf)
7285 (mh-show-msg
7286 (string-to-number
7287 (car (split-string
7288 (with-temp-buffer
7289 (call-process
7290 (expand-file-name "pick" mh-progs)
7291 nil t nil
7292 folder
7293 "--message-id"
7294 article)
7295 (buffer-string))
7296 "\n"))))
7297 (pop-to-buffer show-buf)))
7298
7299 (defun org-open-file (path &optional in-emacs line search)
7300 "Open the file at PATH.
7301 First, this expands any special file name abbreviations. Then the
7302 configuration variable `org-file-apps' is checked if it contains an
7303 entry for this file type, and if yes, the corresponding command is launched.
7304 If no application is found, Emacs simply visits the file.
7305 With optional argument IN-EMACS, Emacs will visit the file.
7306 Optional LINE specifies a line to go to, optional SEARCH a string to
7307 search for. If LINE or SEARCH is given, the file will always be
7308 opened in Emacs.
7309 If the file does not exist, an error is thrown."
7310 (setq in-emacs (or in-emacs line search))
7311 (let* ((file (if (equal path "")
7312 (buffer-file-name)
7313 (convert-standard-filename (org-expand-file-name path))))
7314 (dirp (file-directory-p file))
7315 (dfile (downcase file))
7316 (old-buffer (current-buffer))
7317 (old-pos (point))
7318 (old-mode major-mode)
7319 ext cmd apps)
7320 (if (and (not (file-exists-p file))
7321 (not org-open-non-existing-files))
7322 (error "No such file: %s" file))
7323 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7324 (setq ext (match-string 1 dfile))
7325 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7326 (setq ext (match-string 1 dfile))))
7327 (setq apps (append org-file-apps (org-default-apps)))
7328 (if in-emacs
7329 (setq cmd 'emacs)
7330 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7331 (cdr (assoc ext apps))
7332 (cdr (assoc t apps)))))
7333 (when (eq cmd 'mailcap)
7334 (require 'mailcap)
7335 (mailcap-parse-mailcaps)
7336 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7337 (command (mailcap-mime-info mime-type)))
7338 (if (stringp command)
7339 (setq cmd command)
7340 (setq cmd 'emacs))))
7341 (cond
7342 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7343 (setq cmd (format cmd (concat "\"" file "\"")))
7344 (save-window-excursion
7345 (shell-command (concat cmd " &"))))
7346 ((or (stringp cmd)
7347 (eq cmd 'emacs))
7348 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
7349 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7350 (if line (goto-line line)
7351 (if search (org-link-search search))))
7352 ((consp cmd)
7353 (eval cmd))
7354 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7355 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7356 (or (not (equal old-buffer (current-buffer)))
7357 (not (equal old-pos (point))))
7358 (org-mark-ring-push old-pos old-buffer))))
7359
7360 (defun org-default-apps ()
7361 "Return the default applications for this operating system."
7362 (cond
7363 ((eq system-type 'darwin)
7364 org-file-apps-defaults-macosx)
7365 ((eq system-type 'windows-nt)
7366 org-file-apps-defaults-windowsnt)
7367 (t org-file-apps-defaults-gnu)))
7368
7369 (defun org-expand-file-name (path)
7370 "Replace special path abbreviations and expand the file name."
7371 (expand-file-name path))
7372
7373
7374 (defvar org-insert-link-history nil
7375 "Minibuffer history for links inserted with `org-insert-link'.")
7376
7377 (defvar org-stored-links nil
7378 "Contains the links stored with `org-store-link'.")
7379
7380 ;;;###autoload
7381 (defun org-store-link (arg)
7382 "\\<org-mode-map>Store an org-link to the current location.
7383 This link can later be inserted into an org-buffer with
7384 \\[org-insert-link].
7385 For some link types, a prefix arg is interpreted:
7386 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7387 For file links, arg negates `org-context-in-file-links'."
7388 (interactive "P")
7389 (let (link cpltxt txt (pos (point)))
7390 (cond
7391
7392 ((eq major-mode 'bbdb-mode)
7393 (setq cpltxt (concat
7394 "bbdb:"
7395 (or (bbdb-record-name (bbdb-current-record))
7396 (bbdb-record-company (bbdb-current-record))))
7397 link (org-make-link cpltxt)))
7398
7399 ((eq major-mode 'calendar-mode)
7400 (let ((cd (calendar-cursor-to-date)))
7401 (setq link
7402 (format-time-string
7403 (car org-time-stamp-formats)
7404 (apply 'encode-time
7405 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7406 nil nil nil))))))
7407
7408 ((or (eq major-mode 'vm-summary-mode)
7409 (eq major-mode 'vm-presentation-mode))
7410 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7411 (vm-follow-summary-cursor)
7412 (save-excursion
7413 (vm-select-folder-buffer)
7414 (let* ((message (car vm-message-pointer))
7415 (folder (buffer-file-name))
7416 (subject (vm-su-subject message))
7417 (author (vm-su-full-name message))
7418 (message-id (vm-su-message-id message)))
7419 (setq message-id (org-remove-angle-brackets message-id))
7420 (setq folder (abbreviate-file-name folder))
7421 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7422 folder)
7423 (setq folder (replace-match "" t t folder)))
7424 (setq cpltxt (concat author " on: " subject))
7425 (setq link (concat cpltxt "\n "
7426 (org-make-link
7427 "vm:" folder "#" message-id))))))
7428
7429 ((eq major-mode 'wl-summary-mode)
7430 (let* ((msgnum (wl-summary-message-number))
7431 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7432 msgnum 'message-id))
7433 (wl-message-entity (elmo-msgdb-overview-get-entity
7434 msgnum (wl-summary-buffer-msgdb)))
7435 (author (wl-summary-line-from)) ; FIXME: how to get author name?
7436 (subject "???")) ; FIXME: How to get subject of email?
7437 (setq message-id (org-remove-angle-brackets message-id))
7438 (setq cpltxt (concat author " on: " subject))
7439 (setq link (concat cpltxt "\n "
7440 (org-make-link
7441 "wl:" wl-summary-buffer-folder-name
7442 "#" message-id)))))
7443
7444 ((or (equal major-mode 'mh-folder-mode)
7445 (equal major-mode 'mh-show-mode))
7446 (let ((from-header (org-mhe-get-header "From:"))
7447 (to-header (org-mhe-get-header "To:"))
7448 (subject (org-mhe-get-header "Subject:")))
7449 (setq cpltxt (concat from-header " on: " subject))
7450 (setq link (concat cpltxt "\n "
7451 (org-make-link
7452 "mhe:" (org-mhe-get-message-real-folder) "#"
7453 (org-remove-angle-brackets
7454 (org-mhe-get-header "Message-Id:")))))))
7455
7456 ((eq major-mode 'rmail-mode)
7457 (save-excursion
7458 (save-restriction
7459 (rmail-narrow-to-non-pruned-header)
7460 (let ((folder (buffer-file-name))
7461 (message-id (mail-fetch-field "message-id"))
7462 (author (mail-fetch-field "from"))
7463 (subject (mail-fetch-field "subject")))
7464 (setq message-id (org-remove-angle-brackets message-id))
7465 (setq cpltxt (concat author " on: " subject))
7466 (setq link (concat cpltxt "\n "
7467 (org-make-link
7468 "rmail:" folder "#" message-id)))))))
7469
7470 ((eq major-mode 'gnus-group-mode)
7471 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7472 (gnus-group-group-name)) ; version
7473 ((fboundp 'gnus-group-name)
7474 (gnus-group-name))
7475 (t "???"))))
7476 (setq cpltxt (concat
7477 (if (org-xor arg org-usenet-links-prefer-google)
7478 "http://groups.google.com/groups?group="
7479 "gnus:")
7480 group)
7481 link (org-make-link cpltxt))))
7482
7483 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7484 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7485 (gnus-summary-beginning-of-article)
7486 (let* ((group (car gnus-article-current))
7487 (article (cdr gnus-article-current))
7488 (header (gnus-summary-article-header article))
7489 (author (mail-header-from header))
7490 (message-id (mail-header-id header))
7491 (date (mail-header-date header))
7492 (subject (gnus-summary-subject-string)))
7493 (setq cpltxt (concat author " on: " subject))
7494 (if (org-xor arg org-usenet-links-prefer-google)
7495 (setq link
7496 (concat
7497 cpltxt "\n "
7498 (format "http://groups.google.com/groups?as_umsgid=%s"
7499 (org-fixup-message-id-for-http message-id))))
7500 (setq link (concat cpltxt "\n"
7501 (org-make-link
7502 "gnus:" group
7503 "#" (number-to-string article)))))))
7504
7505 ((eq major-mode 'w3-mode)
7506 (setq cpltxt (url-view-url t)
7507 link (org-make-link cpltxt)))
7508 ((eq major-mode 'w3m-mode)
7509 (setq cpltxt w3m-current-url
7510 link (org-make-link cpltxt)))
7511
7512 ((eq major-mode 'org-mode)
7513 ;; Just link to current headline
7514 (setq cpltxt (concat "file:"
7515 (abbreviate-file-name (buffer-file-name))))
7516 ;; Add a context search string
7517 (when (org-xor org-context-in-file-links arg)
7518 ;; Check if we are on a target
7519 (if (save-excursion
7520 (skip-chars-forward "^>\n\r")
7521 (and (re-search-backward "<<" nil t)
7522 (looking-at "<<\\(.*?\\)>>")
7523 (<= (match-beginning 0) pos)
7524 (>= (match-end 0) pos)))
7525 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7526 (setq txt (cond
7527 ((org-on-heading-p) nil)
7528 ((org-region-active-p)
7529 (buffer-substring (region-beginning) (region-end)))
7530 (t (buffer-substring (point-at-bol) (point-at-eol)))))
7531 (setq cpltxt
7532 (concat cpltxt "::"
7533 (if org-file-link-context-use-camel-case
7534 (org-make-org-heading-camel txt)
7535 (org-make-org-heading-search-string txt))))))
7536 (if (string-match "::\\'" cpltxt)
7537 (setq cpltxt (substring cpltxt 0 -2)))
7538 (setq link (org-make-link cpltxt)))
7539
7540 ((buffer-file-name)
7541 ;; Just link to this file here.
7542 (setq cpltxt (concat "file:"
7543 (abbreviate-file-name (buffer-file-name))))
7544 ;; Add a context string
7545 (when (org-xor org-context-in-file-links arg)
7546 (setq txt (if (org-region-active-p)
7547 (buffer-substring (region-beginning) (region-end))
7548 (buffer-substring (point-at-bol) (point-at-eol))))
7549 (setq cpltxt
7550 (concat cpltxt "::"
7551 (if org-file-link-context-use-camel-case
7552 (org-make-org-heading-camel txt)
7553 (org-make-org-heading-search-string txt)))))
7554 (setq link (org-make-link cpltxt)))
7555
7556 ((interactive-p)
7557 (error "Cannot link to a buffer which is not visiting a file"))
7558
7559 (t (setq link nil)))
7560
7561 (if (and (interactive-p) link)
7562 (progn
7563 (setq org-stored-links
7564 (cons (cons (or cpltxt link) link) org-stored-links))
7565 (message "Stored: %s" (or cpltxt link)))
7566 link)))
7567
7568 (defun org-make-org-heading-search-string (&optional string heading)
7569 "Make search string for STRING or current headline."
7570 (interactive)
7571 (let ((s (or string (org-get-heading))))
7572 (unless (and string (not heading))
7573 ;; We are using a headline, clean up garbage in there.
7574 (if (string-match org-todo-regexp s)
7575 (setq s (replace-match "" t t s)))
7576 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7577 (setq s (replace-match "" t t s)))
7578 (setq s (org-trim s))
7579 (if (string-match (concat "^\\(" org-quote-string "\\|"
7580 org-comment-string "\\)") s)
7581 (setq s (replace-match "" t t s)))
7582 (while (string-match org-ts-regexp s)
7583 (setq s (replace-match "" t t s))))
7584 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7585 (setq s (replace-match " " t t s)))
7586 (or string (setq s (concat "*" s))) ; Add * for headlines
7587 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7588
7589 (defun org-make-org-heading-camel (&optional string heading)
7590 "Make a CamelCase string for STRING or the current headline."
7591 (interactive)
7592 (let ((s (or string (org-get-heading))))
7593 (unless (and string (not heading))
7594 ;; We are using a headline, clean up garbage in there.
7595 (if (string-match org-todo-regexp s)
7596 (setq s (replace-match "" t t s)))
7597 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7598 (setq s (replace-match "" t t s)))
7599 (setq s (org-trim s))
7600 (if (string-match (concat "^\\(" org-quote-string "\\|"
7601 org-comment-string "\\)") s)
7602 (setq s (replace-match "" t t s)))
7603 (while (string-match org-ts-regexp s)
7604 (setq s (replace-match "" t t s))))
7605 (while (string-match "[^a-zA-Z_ \t]+" s)
7606 (setq s (replace-match " " t t s)))
7607 (or string (setq s (concat "*" s))) ; Add * for headlines
7608 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7609
7610 (defun org-make-link (&rest strings)
7611 "Concatenate STRINGS, format resulting string with `org-link-format'."
7612 (format org-link-format (apply 'concat strings)))
7613
7614 (defun org-make-link2 (link &optional description)
7615 "Make a link with brackets."
7616 (concat "[[" link "]"
7617 (if description (concat "[" description "]") "")
7618 "]"))
7619
7620 (defun org-xor (a b)
7621 "Exclusive or."
7622 (if a (not b) b))
7623
7624 (defun org-get-header (header)
7625 "Find a header field in the current buffer."
7626 (save-excursion
7627 (goto-char (point-min))
7628 (let ((case-fold-search t) s)
7629 (cond
7630 ((eq header 'from)
7631 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7632 (setq s (match-string 1)))
7633 (while (string-match "\"" s)
7634 (setq s (replace-match "" t t s)))
7635 (if (string-match "[<(].*" s)
7636 (setq s (replace-match "" t t s))))
7637 ((eq header 'message-id)
7638 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7639 (setq s (match-string 1))))
7640 ((eq header 'subject)
7641 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7642 (setq s (match-string 1)))))
7643 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7644 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7645 s)))
7646
7647
7648 (defun org-fixup-message-id-for-http (s)
7649 "Replace special characters in a message id, so it can be used in an http query."
7650 (while (string-match "<" s)
7651 (setq s (replace-match "%3C" t t s)))
7652 (while (string-match ">" s)
7653 (setq s (replace-match "%3E" t t s)))
7654 (while (string-match "@" s)
7655 (setq s (replace-match "%40" t t s)))
7656 s)
7657
7658 (defun org-insert-link (&optional complete-file)
7659 "Insert a link. At the prompt, enter the link.
7660
7661 Completion can be used to select a link previously stored with
7662 `org-store-link'. When the empty string is entered (i.e. if you just
7663 press RET at the prompt), the link defaults to the most recently
7664 stored link. As SPC triggers completion in the minibuffer, you need to
7665 use M-SPC or C-q SPC to force the insertion of a space character.
7666
7667 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7668 selected using completion. The path to the file will be relative to
7669 the current directory if the file is in the current directory or a
7670 subdirectory. Otherwise, the link will be the absolute path as
7671 completed in the minibuffer (i.e. normally ~/path/to/file).
7672
7673 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7674 is in the current directory or below."
7675 (interactive "P")
7676 (let ((link (if complete-file
7677 (read-file-name "File: ")
7678 (completing-read
7679 "Link: " org-stored-links nil nil nil
7680 org-insert-link-history
7681 (or (car (car org-stored-links))))))
7682 linktxt matched)
7683 (if (or (not link) (equal link ""))
7684 (error "No links available"))
7685 (if complete-file
7686 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7687 (cond
7688 ((equal complete-file '(16))
7689 (insert
7690 (org-make-link
7691 "file:" (abbreviate-file-name (expand-file-name link)))))
7692 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7693 (expand-file-name link))
7694 (insert
7695 (org-make-link
7696 "file:" (match-string 1 (expand-file-name link)))))
7697 (t (insert (org-make-link "file:" link)))))
7698 (setq linktxt (cdr (assoc link org-stored-links)))
7699 (if (not org-keep-stored-link-after-insertion)
7700 (setq org-stored-links (delq (assoc link org-stored-links)
7701 org-stored-links)))
7702 (if (not linktxt) (setq link (org-make-link link)))
7703 (setq link (or linktxt link))
7704 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7705 (let* ((path (match-string 1 link))
7706 (case-fold-search nil)
7707 (search (match-string 2 link)))
7708 (when (save-match-data
7709 (equal (file-truename (buffer-file-name))
7710 (file-truename path)))
7711 ;; We are linking to this same file
7712 (if (and org-file-link-context-use-camel-case
7713 (save-match-data
7714 (string-match (concat "^" org-camel-regexp "$") search)))
7715 (setq link (replace-match search t t link)
7716 matched t)
7717 (setq link (replace-match (concat "[[" search "]]")
7718 t t link)
7719 matched t)))))
7720 (let ((lines (org-split-string link "\n")))
7721 (insert (car lines))
7722 (setq matched (or matched (string-match org-link-regexp (car lines))))
7723 (setq lines (cdr lines))
7724 (while lines
7725 (insert "\n")
7726 (if (save-excursion
7727 (beginning-of-line 0)
7728 (looking-at "[ \t]+\\S-"))
7729 (indent-relative))
7730 (setq matched (or matched
7731 (string-match org-link-regexp (car lines))))
7732 (insert (car lines))
7733 (setq lines (cdr lines))))
7734 (unless matched
7735 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7736
7737 ;;; Hooks for remember.el
7738 ;;;###autoload
7739 (defun org-remember-annotation ()
7740 "Return a link to the current location as an annotation for remember.el.
7741 If you are using Org-mode files as target for data storage with
7742 remember.el, then the annotations should include a link compatible with the
7743 conventions in Org-mode. This function returns such a link."
7744 (org-store-link nil))
7745
7746 (defconst org-remember-help
7747 "Select a destination location for the note.
7748 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7749 RET at beg-of-buf -> Append to file as level 2 headline
7750 RET on headline -> Store as sublevel entry to current headline
7751 <left>/<right> -> before/after current headline, same headings level")
7752
7753 ;;;###autoload
7754 (defun org-remember-handler ()
7755 "Store stuff from remember.el into an org file.
7756 First prompts for an org file. If the user just presses return, the value
7757 of `org-default-notes-file' is used.
7758 Then the command offers the headings tree of the selected file in order to
7759 file the text at a specific location.
7760 You can either immediately press RET to get the note appended to the
7761 file, or you can use vertical cursor motion and visibility cycling (TAB) to
7762 find a better place. Then press RET or <left> or <right> in insert the note.
7763
7764 Key Cursor position Note gets inserted
7765 -----------------------------------------------------------------------------
7766 RET buffer-start as level 2 heading at end of file
7767 RET on headline as sublevel of the heading at cursor
7768 RET no heading at cursor position, level taken from context.
7769 Or use prefix arg to specify level manually.
7770 <left> on headline as same level, before current heading
7771 <right> on headline as same level, after current heading
7772
7773 So the fastest way to store the note is to press RET RET to append it to
7774 the default file. This way your current train of thought is not
7775 interrupted, in accordance with the principles of remember.el. But with
7776 little extra effort, you can push it directly to the correct location.
7777
7778 Before being stored away, the function ensures that the text has a
7779 headline, i.e. a first line that starts with a \"*\". If not, a headline
7780 is constructed from the current date and some additional data.
7781
7782 If the variable `org-adapt-indentation' is non-nil, the entire text is
7783 also indented so that it starts in the same column as the headline
7784 \(i.e. after the stars).
7785
7786 See also the variable `org-reverse-note-order'."
7787 (catch 'quit
7788 (let* ((txt (buffer-substring (point-min) (point-max)))
7789 (fastp current-prefix-arg)
7790 (file (if fastp org-default-notes-file (org-get-org-file)))
7791 (visiting (find-buffer-visiting file))
7792 (org-startup-with-deadline-check nil)
7793 (org-startup-folded nil)
7794 spos level indent reversed)
7795 ;; Modify text so that it becomes a nice subtree which can be inserted
7796 ;; into an org tree.
7797 (let* ((lines (split-string txt "\n"))
7798 (first (car lines))
7799 (lines (cdr lines)))
7800 (if (string-match "^\\*+" first)
7801 ;; Is already a headline
7802 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7803 -1) ?\ ))
7804 ;; We need to add a headline: Use time and first buffer line
7805 (setq lines (cons first lines)
7806 first (concat "* " (current-time-string)
7807 " (" (remember-buffer-desc) ")")
7808 indent " "))
7809 (if org-adapt-indentation
7810 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7811 (setq txt (concat first "\n"
7812 (mapconcat 'identity lines "\n"))))
7813 ;; Find the file
7814 (if (not visiting)
7815 (find-file-noselect file))
7816 (with-current-buffer (get-file-buffer file)
7817 (setq reversed (org-notes-order-reversed-p))
7818 (save-excursion
7819 (save-restriction
7820 (widen)
7821 ;; Ask the User for a location
7822 (setq spos (if fastp 1 (org-get-location
7823 (current-buffer)
7824 org-remember-help)))
7825 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7826 ; not handle this note
7827 (goto-char spos)
7828 (cond ((bobp)
7829 ;; Put it at the start or end, as level 2
7830 (save-restriction
7831 (widen)
7832 (goto-char (if reversed (point-min) (point-max)))
7833 (if (not (bolp)) (newline))
7834 (org-paste-subtree (or current-prefix-arg 2) txt)))
7835 ((and (org-on-heading-p nil) (not current-prefix-arg))
7836 ;; Put it below this entry, at the beg/end of the subtree
7837 (org-back-to-heading)
7838 (setq level (outline-level))
7839 (if reversed
7840 (outline-end-of-heading)
7841 (outline-end-of-subtree))
7842 (if (not (bolp)) (newline))
7843 (beginning-of-line 1)
7844 (org-paste-subtree (1+ level) txt))
7845 (t
7846 ;; Put it right there, with automatic level determined by
7847 ;; org-paste-subtree or from prefix arg
7848 (org-paste-subtree current-prefix-arg txt)))
7849 (when remember-save-after-remembering
7850 (save-buffer)
7851 (if (not visiting) (kill-buffer (current-buffer)))))))))
7852 t) ;; return t to indicate that we took care of this note.
7853
7854 (defun org-get-org-file ()
7855 "Read a filename, with default directory `org-directory'."
7856 (let ((default (or org-default-notes-file remember-data-file)))
7857 (read-file-name (format "File name [%s]: " default)
7858 (file-name-as-directory org-directory)
7859 default)))
7860
7861 (defun org-notes-order-reversed-p ()
7862 "Check if the current file should receive notes in reversed order."
7863 (cond
7864 ((not org-reverse-note-order) nil)
7865 ((eq t org-reverse-note-order) t)
7866 ((not (listp org-reverse-note-order)) nil)
7867 (t (catch 'exit
7868 (let ((all org-reverse-note-order)
7869 entry)
7870 (while (setq entry (pop all))
7871 (if (string-match (car entry) (buffer-file-name))
7872 (throw 'exit (cdr entry))))
7873 nil)))))
7874
7875 ;;; Tables
7876
7877 ;; Watch out: Here we are talking about two different kind of tables.
7878 ;; Most of the code is for the tables created with the Org-mode table editor.
7879 ;; Sometimes, we talk about tables created and edited with the table.el
7880 ;; Emacs package. We call the former org-type tables, and the latter
7881 ;; table.el-type tables.
7882
7883
7884 (defun org-before-change-function (beg end)
7885 "Every change indicates that a table might need an update."
7886 (setq org-table-may-need-update t))
7887
7888 (defconst org-table-line-regexp "^[ \t]*|"
7889 "Detects an org-type table line.")
7890 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7891 "Detects an org-type table line.")
7892 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7893 "Detects a table line marked for automatic recalculation.")
7894 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7895 "Detects a table line marked for automatic recalculation.")
7896 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7897 "Detects a table line marked for automatic recalculation.")
7898 (defconst org-table-hline-regexp "^[ \t]*|-"
7899 "Detects an org-type table hline.")
7900 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7901 "Detects a table-type table hline.")
7902 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7903 "Detects an org-type or table-type table.")
7904 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7905 "Searching from within a table (any type) this finds the first line
7906 outside the table.")
7907 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7908 "Searching from within a table (any type) this finds the first line
7909 outside the table.")
7910
7911 (defun org-table-create-with-table.el ()
7912 "Use the table.el package to insert a new table.
7913 If there is already a table at point, convert between Org-mode tables
7914 and table.el tables."
7915 (interactive)
7916 (require 'table)
7917 (cond
7918 ((org-at-table.el-p)
7919 (if (y-or-n-p "Convert table to Org-mode table? ")
7920 (org-table-convert)))
7921 ((org-at-table-p)
7922 (if (y-or-n-p "Convert table to table.el table? ")
7923 (org-table-convert)))
7924 (t (call-interactively 'table-insert))))
7925
7926 (defun org-table-create (&optional size)
7927 "Query for a size and insert a table skeleton.
7928 SIZE is a string Columns x Rows like for example \"3x2\"."
7929 (interactive "P")
7930 (unless size
7931 (setq size (read-string
7932 (concat "Table size Columns x Rows [e.g. "
7933 org-table-default-size "]: ")
7934 "" nil org-table-default-size)))
7935
7936 (let* ((pos (point))
7937 (indent (make-string (current-column) ?\ ))
7938 (split (org-split-string size " *x *"))
7939 (rows (string-to-number (nth 1 split)))
7940 (columns (string-to-number (car split)))
7941 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7942 "\n")))
7943 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7944 (point-at-bol) (point)))
7945 (beginning-of-line 1)
7946 (newline))
7947 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7948 (dotimes (i rows) (insert line))
7949 (goto-char pos)
7950 (if (> rows 1)
7951 ;; Insert a hline after the first row.
7952 (progn
7953 (end-of-line 1)
7954 (insert "\n|-")
7955 (goto-char pos)))
7956 (org-table-align)))
7957
7958 (defun org-table-convert-region (beg0 end0 nspace)
7959 "Convert region to a table.
7960 The region goes from BEG0 to END0, but these borders will be moved
7961 slightly, to make sure a beginning of line in the first line is included.
7962 When NSPACE is non-nil, it indicates the minimum number of spaces that
7963 separate columns (default: just one space)."
7964 (let* ((beg (min beg0 end0))
7965 (end (max beg0 end0))
7966 (tabsep t)
7967 re)
7968 (goto-char beg)
7969 (beginning-of-line 1)
7970 (setq beg (move-marker (make-marker) (point)))
7971 (goto-char end)
7972 (if (bolp) (backward-char 1) (end-of-line 1))
7973 (setq end (move-marker (make-marker) (point)))
7974 ;; Lets see if this is tab-separated material. If every nonempty line
7975 ;; contains a tab, we will assume that it is tab-separated material
7976 (if nspace
7977 (setq tabsep nil)
7978 (goto-char beg)
7979 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7980 (if nspace (setq tabsep nil))
7981 (if tabsep
7982 (setq re "^\\|\t")
7983 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7984 (max 1 (prefix-numeric-value nspace)))))
7985 (goto-char beg)
7986 (while (re-search-forward re end t)
7987 (replace-match "|" t t))
7988 (goto-char beg)
7989 (insert " ")
7990 (org-table-align)))
7991
7992 (defun org-table-import (file arg)
7993 "Import FILE as a table.
7994 The file is assumed to be tab-separated. Such files can be produced by most
7995 spreadsheet and database applications. If no tabs (at least one per line)
7996 are found, lines will be split on whitespace into fields."
7997 (interactive "f\nP")
7998 (or (bolp) (newline))
7999 (let ((beg (point))
8000 (pm (point-max)))
8001 (insert-file-contents file)
8002 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8003
8004 (defun org-table-export ()
8005 "Export table as a tab-separated file.
8006 Such a file can be imported into a spreadsheet program like Excel."
8007 (interactive)
8008 (let* ((beg (org-table-begin))
8009 (end (org-table-end))
8010 (table (buffer-substring beg end))
8011 (file (read-file-name "Export table to: "))
8012 buf)
8013 (unless (or (not (file-exists-p file))
8014 (y-or-n-p (format "Overwrite file %s? " file)))
8015 (error "Abort"))
8016 (with-current-buffer (find-file-noselect file)
8017 (setq buf (current-buffer))
8018 (erase-buffer)
8019 (fundamental-mode)
8020 (insert table)
8021 (goto-char (point-min))
8022 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8023 (replace-match "" t t)
8024 (end-of-line 1))
8025 (goto-char (point-min))
8026 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8027 (replace-match "" t t)
8028 (goto-char (min (1+ (point)) (point-max))))
8029 (goto-char (point-min))
8030 (while (re-search-forward "^-[-+]*$" nil t)
8031 (replace-match "")
8032 (if (looking-at "\n")
8033 (delete-char 1)))
8034 (goto-char (point-min))
8035 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8036 (replace-match "\t" t t))
8037 (save-buffer))
8038 (kill-buffer buf)))
8039
8040 (defvar org-table-aligned-begin-marker (make-marker)
8041 "Marker at the beginning of the table last aligned.
8042 Used to check if cursor still is in that table, to minimize realignment.")
8043 (defvar org-table-aligned-end-marker (make-marker)
8044 "Marker at the end of the table last aligned.
8045 Used to check if cursor still is in that table, to minimize realignment.")
8046 (defvar org-table-last-alignment nil
8047 "List of flags for flushright alignment, from the last re-alignment.
8048 This is being used to correctly align a single field after TAB or RET.")
8049 ;; FIXME: The following is currently not used.
8050 (defvar org-table-last-column-widths nil
8051 "List of max width of fields in each column.
8052 This is being used to correctly align a single field after TAB or RET.")
8053
8054 (defvar org-last-recalc-line nil)
8055
8056 (defun org-table-align ()
8057 "Align the table at point by aligning all vertical bars."
8058 (interactive)
8059 ;; (message "align") (sit-for 2)
8060 (let* (
8061 ;; Limits of table
8062 (beg (org-table-begin))
8063 (end (org-table-end))
8064 ;; Current cursor position
8065 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8066 (colpos (org-table-current-column))
8067 (winstart (window-start))
8068 text lines (new "") lengths l typenums ty fields maxfields i
8069 column
8070 (indent "") cnt frac
8071 rfmt hfmt
8072 (spaces (if (org-in-invisibility-spec-p '(org-table))
8073 org-table-spaces-around-invisible-separators
8074 org-table-spaces-around-separators))
8075 (sp1 (car spaces))
8076 (sp2 (cdr spaces))
8077 (rfmt1 (concat
8078 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8079 (hfmt1 (concat
8080 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8081 emptystrings)
8082 (untabify beg end)
8083 ;; (message "Aligning table...")
8084 ;; Get the rows
8085 (setq lines (org-split-string
8086 (buffer-substring-no-properties beg end) "\n"))
8087 ;; Store the indentation of the first line
8088 (if (string-match "^ *" (car lines))
8089 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8090 ;; Mark the hlines
8091 (setq lines (mapcar (lambda (l)
8092 (if (string-match "^ *|-" l)
8093 nil
8094 (if (string-match "[ \t]+$" l)
8095 (substring l 0 (match-beginning 0))
8096 l)))
8097 lines))
8098 ;; Get the data fields
8099 (setq fields (mapcar
8100 (lambda (l)
8101 (org-split-string l " *| *"))
8102 (delq nil (copy-sequence lines))))
8103 ;; How many fields in the longest line?
8104 (condition-case nil
8105 (setq maxfields (apply 'max (mapcar 'length fields)))
8106 (error
8107 (kill-region beg end)
8108 (org-table-create org-table-default-size)
8109 (error "Empty table - created default table")))
8110 ;; A list of empty string to fill any short rows on output
8111 (setq emptystrings (make-list maxfields ""))
8112 ;; Get the maximum length of a field and the most common datatype
8113 ;; for each column
8114 (setq i -1)
8115 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8116 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8117 ;; maximum length
8118 (push (apply 'max 1 (mapcar 'string-width column)) lengths)
8119 ;; compute the fraction stepwise, ignoring empty fields
8120 (setq cnt 0 frac 0.0)
8121 (mapcar
8122 (lambda (x)
8123 (if (equal x "")
8124 nil
8125 (setq frac ( / (+ (* frac cnt)
8126 (if (string-match org-table-number-regexp x) 1 0))
8127 (setq cnt (1+ cnt))))))
8128 column)
8129 (push (>= frac org-table-number-fraction) typenums))
8130 (setq lengths (nreverse lengths)
8131 typenums (nreverse typenums))
8132 (setq org-table-last-alignment typenums
8133 org-table-last-column-widths lengths)
8134 ;; Compute the formats needed for output of the table
8135 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8136 (while (setq l (pop lengths))
8137 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8138 (setq rfmt (concat rfmt (format rfmt1 ty l))
8139 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8140 (setq rfmt (concat rfmt "\n")
8141 hfmt (concat (substring hfmt 0 -1) "|\n"))
8142 ;; Produce the new table
8143 ;;(while lines
8144 ;; (setq l (pop lines))
8145 ;; (if l
8146 ;; (setq new (concat new (apply 'format rfmt
8147 ;; (append (pop fields) emptystrings))))
8148 ;; (setq new (concat new hfmt))))
8149 (setq new (mapconcat
8150 (lambda (l)
8151 (if l (apply 'format rfmt
8152 (append (pop fields) emptystrings))
8153 hfmt))
8154 lines ""))
8155 ;; Replace the old one
8156 (delete-region beg end)
8157 (move-marker end nil)
8158 (move-marker org-table-aligned-begin-marker (point))
8159 (insert new)
8160 (move-marker org-table-aligned-end-marker (point))
8161 ;; Try to move to the old location (approximately)
8162 (goto-line linepos)
8163 (set-window-start (selected-window) winstart 'noforce)
8164 (org-table-goto-column colpos)
8165 (setq org-table-may-need-update nil)
8166 (if (org-in-invisibility-spec-p '(org-table))
8167 (org-table-add-invisible-to-vertical-lines))
8168 ))
8169
8170 (defun org-table-begin (&optional table-type)
8171 "Find the beginning of the table and return its position.
8172 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8173 (save-excursion
8174 (if (not (re-search-backward
8175 (if table-type org-table-any-border-regexp
8176 org-table-border-regexp)
8177 nil t))
8178 (error "Can't find beginning of table")
8179 (goto-char (match-beginning 0))
8180 (beginning-of-line 2)
8181 (point))))
8182
8183 (defun org-table-end (&optional table-type)
8184 "Find the end of the table and return its position.
8185 With argument TABLE-TYPE, go to the end of a table.el-type table."
8186 (save-excursion
8187 (if (not (re-search-forward
8188 (if table-type org-table-any-border-regexp
8189 org-table-border-regexp)
8190 nil t))
8191 (goto-char (point-max))
8192 (goto-char (match-beginning 0)))
8193 (point-marker)))
8194
8195 (defun org-table-justify-field-maybe (&optional new)
8196 "Justify the current field, text to left, number to right.
8197 Optional argument NEW may specify text to replace the current field content."
8198 (cond
8199 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8200 ((org-at-table-hline-p)
8201 ;; FIXME: I used to enforce realign here, but I think this is not needed.
8202 ;; (setq org-table-may-need-update t)
8203 )
8204 ((and (not new)
8205 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8206 (current-buffer)))
8207 (< (point) org-table-aligned-begin-marker)
8208 (>= (point) org-table-aligned-end-marker)))
8209 ;; This is not the same table, force a full re-align
8210 (setq org-table-may-need-update t))
8211 (t ;; realign the current field, based on previous full realign
8212 (let* ((pos (point)) s
8213 (col (org-table-current-column))
8214 (num (nth (1- col) org-table-last-alignment))
8215 l f n o e)
8216 (when (> col 0)
8217 (skip-chars-backward "^|\n")
8218 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8219 (progn
8220 (setq s (match-string 1)
8221 o (match-string 0)
8222 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8223 e (not (= (match-beginning 2) (match-end 2))))
8224 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8225 l (if e "|" (setq org-table-may-need-update t) ""))
8226 n (format f s t t))
8227 (if new
8228 (if (<= (length new) l)
8229 (setq n (format f new t t)) ;; FIXME: why t t?????
8230 (setq n (concat new "|") org-table-may-need-update t)))
8231 (or (equal n o)
8232 (let (org-table-may-need-update)
8233 (replace-match n))))
8234 (setq org-table-may-need-update t))
8235 (goto-char pos))))))
8236
8237 (defun org-table-next-field ()
8238 "Go to the next field in the current table, creating new lines as needed.
8239 Before doing so, re-align the table if necessary."
8240 (interactive)
8241 (org-table-maybe-eval-formula)
8242 (org-table-maybe-recalculate-line)
8243 (if (and org-table-automatic-realign
8244 org-table-may-need-update)
8245 (org-table-align))
8246 (let ((end (org-table-end)))
8247 (if (org-at-table-hline-p)
8248 (end-of-line 1))
8249 (condition-case nil
8250 (progn
8251 (re-search-forward "|" end)
8252 (if (looking-at "[ \t]*$")
8253 (re-search-forward "|" end))
8254 (if (and (looking-at "-")
8255 org-table-tab-jumps-over-hlines
8256 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8257 (goto-char (match-beginning 1)))
8258 (if (looking-at "-")
8259 (progn
8260 (beginning-of-line 0)
8261 (org-table-insert-row 'below))
8262 (if (looking-at " ") (forward-char 1))))
8263 (error
8264 (org-table-insert-row 'below)))))
8265
8266 (defun org-table-previous-field ()
8267 "Go to the previous field in the table.
8268 Before doing so, re-align the table if necessary."
8269 (interactive)
8270 (org-table-justify-field-maybe)
8271 (org-table-maybe-recalculate-line)
8272 (if (and org-table-automatic-realign
8273 org-table-may-need-update)
8274 (org-table-align))
8275 (if (org-at-table-hline-p)
8276 (end-of-line 1))
8277 (re-search-backward "|" (org-table-begin))
8278 (re-search-backward "|" (org-table-begin))
8279 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8280 (re-search-backward "|" (org-table-begin)))
8281 (if (looking-at "| ?")
8282 (goto-char (match-end 0))))
8283
8284 (defun org-table-next-row ()
8285 "Go to the next row (same column) in the current table.
8286 Before doing so, re-align the table if necessary."
8287 (interactive)
8288 (org-table-maybe-eval-formula)
8289 (org-table-maybe-recalculate-line)
8290 (if (or (looking-at "[ \t]*$")
8291 (save-excursion (skip-chars-backward " \t") (bolp)))
8292 (newline)
8293 (if (and org-table-automatic-realign
8294 org-table-may-need-update)
8295 (org-table-align))
8296 (let ((col (org-table-current-column)))
8297 (beginning-of-line 2)
8298 (if (or (not (org-at-table-p))
8299 (org-at-table-hline-p))
8300 (progn
8301 (beginning-of-line 0)
8302 (org-table-insert-row 'below)))
8303 (org-table-goto-column col)
8304 (skip-chars-backward "^|\n\r")
8305 (if (looking-at " ") (forward-char 1)))))
8306
8307 (defun org-table-copy-down (n)
8308 "Copy a field down in the current column.
8309 If the field at the cursor is empty, copy into it the content of the nearest
8310 non-empty field above. With argument N, use the Nth non-empty field.
8311 If the current field is not empty, it is copied down to the next row, and
8312 the cursor is moved with it. Therefore, repeating this command causes the
8313 column to be filled row-by-row.
8314 If the variable `org-table-copy-increment' is non-nil and the field is an
8315 integer, it will be incremented while copying."
8316 (interactive "p")
8317 (let* ((colpos (org-table-current-column))
8318 (field (org-table-get-field))
8319 (non-empty (string-match "[^ \t]" field))
8320 (beg (org-table-begin))
8321 txt)
8322 (org-table-check-inside-data-field)
8323 (if non-empty
8324 (progn
8325 (setq txt (org-trim field))
8326 (org-table-next-row)
8327 (org-table-blank-field))
8328 (save-excursion
8329 (setq txt
8330 (catch 'exit
8331 (while (progn (beginning-of-line 1)
8332 (re-search-backward org-table-dataline-regexp
8333 beg t))
8334 (org-table-goto-column colpos t)
8335 (if (and (looking-at
8336 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8337 (= (setq n (1- n)) 0))
8338 (throw 'exit (match-string 1))))))))
8339 (if txt
8340 (progn
8341 (if (and org-table-copy-increment
8342 (string-match "^[0-9]+$" txt))
8343 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8344 (insert txt)
8345 (org-table-maybe-recalculate-line)
8346 (org-table-align))
8347 (error "No non-empty field found"))))
8348
8349 (defun org-table-check-inside-data-field ()
8350 "Is point inside a table data field?
8351 I.e. not on a hline or before the first or after the last column?
8352 This actually throws an error, so it aborts the current command."
8353 (if (or (not (org-at-table-p))
8354 (= (org-table-current-column) 0)
8355 (org-at-table-hline-p)
8356 (looking-at "[ \t]*$"))
8357 (error "Not in table data field")))
8358
8359 (defvar org-table-clip nil
8360 "Clipboard for table regions.")
8361
8362 (defun org-table-blank-field ()
8363 "Blank the current table field or active region."
8364 (interactive)
8365 (org-table-check-inside-data-field)
8366 (if (and (interactive-p) (org-region-active-p))
8367 (let (org-table-clip)
8368 (org-table-cut-region (region-beginning) (region-end)))
8369 (skip-chars-backward "^|")
8370 (backward-char 1)
8371 (if (looking-at "|[^|\n]+")
8372 (let* ((pos (match-beginning 0))
8373 (match (match-string 0))
8374 (len (string-width match)))
8375 (replace-match (concat "|" (make-string (1- len) ?\ )))
8376 (goto-char (+ 2 pos))
8377 (substring match 1)))))
8378
8379 (defun org-table-get-field (&optional n replace)
8380 "Return the value of the field in column N of current row.
8381 N defaults to current field.
8382 If REPLACE is a string, replace field with this value. The return value
8383 is always the old value."
8384 (and n (org-table-goto-column n))
8385 (skip-chars-backward "^|\n")
8386 (backward-char 1)
8387 (if (looking-at "|[^|\r\n]*")
8388 (let* ((pos (match-beginning 0))
8389 (val (buffer-substring (1+ pos) (match-end 0))))
8390 (if replace
8391 (replace-match (concat "|" replace)))
8392 (goto-char (min (point-at-eol) (+ 2 pos)))
8393 val)
8394 (forward-char 1) ""))
8395
8396 (defun org-table-current-column ()
8397 "Find out which column we are in.
8398 When called interactively, column is also displayed in echo area."
8399 (interactive)
8400 (if (interactive-p) (org-table-check-inside-data-field))
8401 (save-excursion
8402 (let ((cnt 0) (pos (point)))
8403 (beginning-of-line 1)
8404 (while (search-forward "|" pos t)
8405 (setq cnt (1+ cnt)))
8406 (if (interactive-p) (message "This is table column %d" cnt))
8407 cnt)))
8408
8409 (defun org-table-goto-column (n &optional on-delim force)
8410 "Move the cursor to the Nth column in the current table line.
8411 With optional argument ON-DELIM, stop with point before the left delimiter
8412 of the field.
8413 If there are less than N fields, just go to after the last delimiter.
8414 However, when FORCE is non-nil, create new columns if necessary."
8415 (interactive "p")
8416 (let ((pos (point-at-eol)))
8417 (beginning-of-line 1)
8418 (when (> n 0)
8419 (while (and (> (setq n (1- n)) -1)
8420 (or (search-forward "|" pos t)
8421 (and force
8422 (progn (end-of-line 1)
8423 (skip-chars-backward "^|")
8424 (insert " | "))))))
8425 ; (backward-char 2) t)))))
8426 (when (and force (not (looking-at ".*|")))
8427 (save-excursion (end-of-line 1) (insert " | ")))
8428 (if on-delim
8429 (backward-char 1)
8430 (if (looking-at " ") (forward-char 1))))))
8431
8432 (defun org-at-table-p (&optional table-type)
8433 "Return t if the cursor is inside an org-type table.
8434 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8435 (if org-enable-table-editor
8436 (save-excursion
8437 (beginning-of-line 1)
8438 (looking-at (if table-type org-table-any-line-regexp
8439 org-table-line-regexp)))
8440 nil))
8441
8442 (defun org-at-table.el-p ()
8443 "Return t if and only if we are at a table.el table."
8444 (and (org-at-table-p 'any)
8445 (save-excursion
8446 (goto-char (org-table-begin 'any))
8447 (looking-at org-table1-hline-regexp))))
8448
8449 (defun org-table-recognize-table.el ()
8450 "If there is a table.el table nearby, recognize it and move into it."
8451 (if org-table-tab-recognizes-table.el
8452 (if (org-at-table.el-p)
8453 (progn
8454 (beginning-of-line 1)
8455 (if (looking-at org-table-dataline-regexp)
8456 nil
8457 (if (looking-at org-table1-hline-regexp)
8458 (progn
8459 (beginning-of-line 2)
8460 (if (looking-at org-table-any-border-regexp)
8461 (beginning-of-line -1)))))
8462 (if (re-search-forward "|" (org-table-end t) t)
8463 (progn
8464 (require 'table)
8465 (if (table--at-cell-p (point))
8466 t
8467 (message "recognizing table.el table...")
8468 (table-recognize-table)
8469 (message "recognizing table.el table...done")))
8470 (error "This should not happen..."))
8471 t)
8472 nil)
8473 nil))
8474
8475 (defun org-at-table-hline-p ()
8476 "Return t if the cursor is inside a hline in a table."
8477 (if org-enable-table-editor
8478 (save-excursion
8479 (beginning-of-line 1)
8480 (looking-at org-table-hline-regexp))
8481 nil))
8482
8483 (defun org-table-insert-column ()
8484 "Insert a new column into the table."
8485 (interactive)
8486 (if (not (org-at-table-p))
8487 (error "Not at a table"))
8488 (org-table-find-dataline)
8489 (let* ((col (max 1 (org-table-current-column)))
8490 (beg (org-table-begin))
8491 (end (org-table-end))
8492 ;; Current cursor position
8493 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8494 (colpos col))
8495 (goto-char beg)
8496 (while (< (point) end)
8497 (if (org-at-table-hline-p)
8498 nil
8499 (org-table-goto-column col t)
8500 (insert "| "))
8501 (beginning-of-line 2))
8502 (move-marker end nil)
8503 (goto-line linepos)
8504 (org-table-goto-column colpos)
8505 (org-table-align)
8506 (org-table-modify-formulas 'insert col)))
8507
8508 (defun org-table-find-dataline ()
8509 "Find a dataline in the current table, which is needed for column commands."
8510 (if (and (org-at-table-p)
8511 (not (org-at-table-hline-p)))
8512 t
8513 (let ((col (current-column))
8514 (end (org-table-end)))
8515 (move-to-column col)
8516 (while (and (< (point) end)
8517 (or (not (= (current-column) col))
8518 (org-at-table-hline-p)))
8519 (beginning-of-line 2)
8520 (move-to-column col))
8521 (if (and (org-at-table-p)
8522 (not (org-at-table-hline-p)))
8523 t
8524 (error
8525 "Please position cursor in a data line for column operations")))))
8526
8527 (defun org-table-delete-column ()
8528 "Delete a column into the table."
8529 (interactive)
8530 (if (not (org-at-table-p))
8531 (error "Not at a table"))
8532 (org-table-find-dataline)
8533 (org-table-check-inside-data-field)
8534 (let* ((col (org-table-current-column))
8535 (beg (org-table-begin))
8536 (end (org-table-end))
8537 ;; Current cursor position
8538 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8539 (colpos col))
8540 (goto-char beg)
8541 (while (< (point) end)
8542 (if (org-at-table-hline-p)
8543 nil
8544 (org-table-goto-column col t)
8545 (and (looking-at "|[^|\n]+|")
8546 (replace-match "|")))
8547 (beginning-of-line 2))
8548 (move-marker end nil)
8549 (goto-line linepos)
8550 (org-table-goto-column colpos)
8551 (org-table-align)
8552 (org-table-modify-formulas 'remove col)))
8553
8554 (defun org-table-move-column-right ()
8555 "Move column to the right."
8556 (interactive)
8557 (org-table-move-column nil))
8558 (defun org-table-move-column-left ()
8559 "Move column to the left."
8560 (interactive)
8561 (org-table-move-column 'left))
8562
8563 (defun org-table-move-column (&optional left)
8564 "Move the current column to the right. With arg LEFT, move to the left."
8565 (interactive "P")
8566 (if (not (org-at-table-p))
8567 (error "Not at a table"))
8568 (org-table-find-dataline)
8569 (org-table-check-inside-data-field)
8570 (let* ((col (org-table-current-column))
8571 (col1 (if left (1- col) col))
8572 (beg (org-table-begin))
8573 (end (org-table-end))
8574 ;; Current cursor position
8575 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8576 (colpos (if left (1- col) (1+ col))))
8577 (if (and left (= col 1))
8578 (error "Cannot move column further left"))
8579 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8580 (error "Cannot move column further right"))
8581 (goto-char beg)
8582 (while (< (point) end)
8583 (if (org-at-table-hline-p)
8584 nil
8585 (org-table-goto-column col1 t)
8586 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8587 (replace-match "|\\2|\\1|")))
8588 (beginning-of-line 2))
8589 (move-marker end nil)
8590 (goto-line linepos)
8591 (org-table-goto-column colpos)
8592 (org-table-align)
8593 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8594
8595 (defun org-table-move-row-down ()
8596 "Move table row down."
8597 (interactive)
8598 (org-table-move-row nil))
8599 (defun org-table-move-row-up ()
8600 "Move table row up."
8601 (interactive)
8602 (org-table-move-row 'up))
8603
8604 (defun org-table-move-row (&optional up)
8605 "Move the current table line down. With arg UP, move it up."
8606 (interactive "P")
8607 (let ((col (current-column))
8608 (pos (point))
8609 (tonew (if up 0 2))
8610 txt)
8611 (beginning-of-line tonew)
8612 (if (not (org-at-table-p))
8613 (progn
8614 (goto-char pos)
8615 (error "Cannot move row further")))
8616 (goto-char pos)
8617 (beginning-of-line 1)
8618 (setq pos (point))
8619 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8620 (delete-region (point) (1+ (point-at-eol)))
8621 (beginning-of-line tonew)
8622 (insert txt)
8623 (beginning-of-line 0)
8624 (move-to-column col)))
8625
8626 (defun org-table-insert-row (&optional arg)
8627 "Insert a new row above the current line into the table.
8628 With prefix ARG, insert below the current line."
8629 (interactive "P")
8630 (if (not (org-at-table-p))
8631 (error "Not at a table"))
8632 (let* ((line
8633 (org-expand-wide-chars
8634 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8635 new)
8636 (if (string-match "^[ \t]*|-" line)
8637 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8638 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8639 ;; Fix the first field if necessary
8640 (setq new (concat new))
8641 (if (string-match "^[ \t]*| *[#$] *|" line)
8642 (setq new (replace-match (match-string 0 line) t t new)))
8643 (beginning-of-line (if arg 2 1))
8644 (let (org-table-may-need-update)
8645 (insert-before-markers new)
8646 (insert-before-markers "\n"))
8647 (beginning-of-line 0)
8648 (re-search-forward "| ?" (point-at-eol) t)
8649 (and org-table-may-need-update (org-table-align))))
8650
8651 (defun org-table-insert-hline (&optional arg)
8652 "Insert a horizontal-line below the current line into the table.
8653 With prefix ARG, insert above the current line."
8654 (interactive "P")
8655 (if (not (org-at-table-p))
8656 (error "Not at a table"))
8657 (let ((line
8658 (org-expand-wide-chars
8659 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8660 (col (current-column))
8661 start)
8662 (if (string-match "^[ \t]*|-" line)
8663 (setq line
8664 (mapcar (lambda (x) (if (member x '(?| ?+))
8665 (prog1 (if start ?+ ?|) (setq start t))
8666 (if start ?- ?\ )))
8667 line))
8668 (setq line
8669 (mapcar (lambda (x) (if (equal x ?|)
8670 (prog1 (if start ?+ ?|) (setq start t))
8671 (if start ?- ?\ )))
8672 line)))
8673 (beginning-of-line (if arg 1 2))
8674 (apply 'insert line)
8675 (if (equal (char-before (point)) ?+)
8676 (progn (backward-delete-char 1) (insert "|")))
8677 (insert "\n")
8678 (beginning-of-line (if arg 1 -1))
8679 (move-to-column col)))
8680
8681 (defun org-expand-wide-chars (s)
8682 "Expand wide characters to spaces."
8683 (let (w a)
8684 (mapconcat
8685 (lambda (x)
8686 (if (> (setq w (string-width (setq a (char-to-string x)))) 1)
8687 (make-string w ?\ )
8688 a))
8689 s "")))
8690
8691 (defun org-table-kill-row ()
8692 "Delete the current row or horizontal line from the table."
8693 (interactive)
8694 (if (not (org-at-table-p))
8695 (error "Not at a table"))
8696 (let ((col (current-column)))
8697 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8698 (if (not (org-at-table-p)) (beginning-of-line 0))
8699 (move-to-column col)))
8700
8701 (defun org-table-sort-lines (beg end numericp)
8702 "Sort table lines in region.
8703 Point and mark define the first and last line to include. Both point and
8704 mark should be in the column that is used for sorting. For example, to
8705 sort according to column 3, put the mark in the first line to sort, in
8706 table column 3. Put point into the last line to be included in the sorting,
8707 also in table column 3. The command will prompt for the sorting method
8708 \(n for numerical, a for alphanumeric)."
8709 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8710 (setq numericp (string-match "[nN]" numericp))
8711 (org-table-align) ;; Just to be safe
8712 (let* (bcol ecol cmp column lns)
8713 (goto-char beg)
8714 (org-table-check-inside-data-field)
8715 (setq column (org-table-current-column)
8716 beg (move-marker (make-marker) (point-at-bol)))
8717 (goto-char end)
8718 (org-table-check-inside-data-field)
8719 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8720 (untabify beg end)
8721 (goto-char beg)
8722 (org-table-goto-column column)
8723 (skip-chars-backward "^|")
8724 (setq bcol (current-column))
8725 (org-table-goto-column (1+ column))
8726 (skip-chars-backward "^|")
8727 (setq ecol (1- (current-column)))
8728 (setq cmp (if numericp
8729 (lambda (a b) (< (car a) (car b)))
8730 (lambda (a b) (string< (car a) (car b)))))
8731 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8732 (split-string (buffer-substring beg end) "\n")))
8733 (if numericp
8734 (setq lns (mapcar (lambda(x)
8735 (cons (string-to-number (car x)) (cdr x)))
8736 lns)))
8737 (delete-region beg end)
8738 (move-marker beg nil)
8739 (move-marker end nil)
8740 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8741 (message "%d lines sorted %s based on column %d"
8742 (length lns)
8743 (if numericp "numerically" "alphabetically") column)))
8744
8745 (defun org-table-cut-region (beg end)
8746 "Copy region in table to the clipboard and blank all relevant fields."
8747 (interactive "r")
8748 (org-table-copy-region beg end 'cut))
8749
8750 (defun org-table-copy-region (beg end &optional cut)
8751 "Copy rectangular region in table to clipboard.
8752 A special clipboard is used which can only be accessed
8753 with `org-table-paste-rectangle'."
8754 (interactive "rP")
8755 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8756 region cols
8757 (rpl (if cut " " nil)))
8758 (goto-char beg)
8759 (org-table-check-inside-data-field)
8760 (setq l01 (count-lines (point-min) (point))
8761 c01 (org-table-current-column))
8762 (goto-char end)
8763 (org-table-check-inside-data-field)
8764 (setq l02 (count-lines (point-min) (point))
8765 c02 (org-table-current-column))
8766 (setq l1 (min l01 l02) l2 (max l01 l02)
8767 c1 (min c01 c02) c2 (max c01 c02))
8768 (catch 'exit
8769 (while t
8770 (catch 'nextline
8771 (if (> l1 l2) (throw 'exit t))
8772 (goto-line l1)
8773 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8774 (setq cols nil ic1 c1 ic2 c2)
8775 (while (< ic1 (1+ ic2))
8776 (push (org-table-get-field ic1 rpl) cols)
8777 (setq ic1 (1+ ic1)))
8778 (push (nreverse cols) region)
8779 (setq l1 (1+ l1)))))
8780 (setq org-table-clip (nreverse region))
8781 (if cut (org-table-align))
8782 org-table-clip))
8783
8784 (defun org-table-paste-rectangle ()
8785 "Paste a rectangular region into a table.
8786 The upper right corner ends up in the current field. All involved fields
8787 will be overwritten. If the rectangle does not fit into the present table,
8788 the table is enlarged as needed. The process ignores horizontal separator
8789 lines."
8790 (interactive)
8791 (unless (and org-table-clip (listp org-table-clip))
8792 (error "First cut/copy a region to paste!"))
8793 (org-table-check-inside-data-field)
8794 (let* ((clip org-table-clip)
8795 (line (count-lines (point-min) (point)))
8796 (col (org-table-current-column))
8797 (org-enable-table-editor t)
8798 (org-table-automatic-realign nil)
8799 c cols field)
8800 (while (setq cols (pop clip))
8801 (while (org-at-table-hline-p) (beginning-of-line 2))
8802 (if (not (org-at-table-p))
8803 (progn (end-of-line 0) (org-table-next-field)))
8804 (setq c col)
8805 (while (setq field (pop cols))
8806 (org-table-goto-column c nil 'force)
8807 (org-table-get-field nil field)
8808 (setq c (1+ c)))
8809 (beginning-of-line 2))
8810 (goto-line line)
8811 (org-table-goto-column col)
8812 (org-table-align)))
8813
8814 (defun org-table-convert ()
8815 "Convert from `org-mode' table to table.el and back.
8816 Obviously, this only works within limits. When an Org-mode table is
8817 converted to table.el, all horizontal separator lines get lost, because
8818 table.el uses these as cell boundaries and has no notion of horizontal lines.
8819 A table.el table can be converted to an Org-mode table only if it does not
8820 do row or column spanning. Multiline cells will become multiple cells.
8821 Beware, Org-mode does not test if the table can be successfully converted - it
8822 blindly applies a recipe that works for simple tables."
8823 (interactive)
8824 (require 'table)
8825 (if (org-at-table.el-p)
8826 ;; convert to Org-mode table
8827 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8828 (end (move-marker (make-marker) (org-table-end t))))
8829 (table-unrecognize-region beg end)
8830 (goto-char beg)
8831 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8832 (replace-match ""))
8833 (goto-char beg))
8834 (if (org-at-table-p)
8835 ;; convert to table.el table
8836 (let ((beg (move-marker (make-marker) (org-table-begin)))
8837 (end (move-marker (make-marker) (org-table-end))))
8838 ;; first, get rid of all horizontal lines
8839 (goto-char beg)
8840 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8841 (replace-match ""))
8842 ;; insert a hline before first
8843 (goto-char beg)
8844 (org-table-insert-hline 'above)
8845 (beginning-of-line -1)
8846 ;; insert a hline after each line
8847 (while (progn (beginning-of-line 3) (< (point) end))
8848 (org-table-insert-hline))
8849 (goto-char beg)
8850 (setq end (move-marker end (org-table-end)))
8851 ;; replace "+" at beginning and ending of hlines
8852 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8853 (replace-match "\\1+-"))
8854 (goto-char beg)
8855 (while (re-search-forward "-|[ \t]*$" end t)
8856 (replace-match "-+"))
8857 (goto-char beg)))))
8858
8859 (defun org-table-wrap-region (arg)
8860 "Wrap several fields in a column like a paragraph.
8861 This is useful if you'd like to spread the contents of a field over several
8862 lines, in order to keep the table compact.
8863
8864 If there is an active region, and both point and mark are in the same column,
8865 the text in the column is wrapped to minimum width for the given number of
8866 lines. Generally, this makes the table more compact. A prefix ARG may be
8867 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8868 formats the selected text to two lines. If the region was longer than two
8869 lines, the remaining lines remain empty. A negative prefix argument reduces
8870 the current number of lines by that amount. The wrapped text is pasted back
8871 into the table. If you formatted it to more lines than it was before, fields
8872 further down in the table get overwritten - so you might need to make space in
8873 the table first.
8874
8875 If there is no region, the current field is split at the cursor position and
8876 the text fragment to the right of the cursor is prepended to the field one
8877 line down.
8878
8879 If there is no region, but you specify a prefix ARG, the current field gets
8880 blank, and the content is appended to the field above."
8881 (interactive "P")
8882 (org-table-check-inside-data-field)
8883 (if (org-region-active-p)
8884 ;; There is a region: fill as a paragraph
8885 (let ((beg (region-beginning))
8886 nlines)
8887 (org-table-cut-region (region-beginning) (region-end))
8888 (if (> (length (car org-table-clip)) 1)
8889 (error "Region must be limited to single column"))
8890 (setq nlines (if arg
8891 (if (< arg 1)
8892 (+ (length org-table-clip) arg)
8893 arg)
8894 (length org-table-clip)))
8895 (setq org-table-clip
8896 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8897 nil nlines)))
8898 (goto-char beg)
8899 (org-table-paste-rectangle))
8900 ;; No region, split the current field at point
8901 (if arg
8902 ;; combine with field above
8903 (let ((s (org-table-blank-field))
8904 (col (org-table-current-column)))
8905 (beginning-of-line 0)
8906 (while (org-at-table-hline-p) (beginning-of-line 0))
8907 (org-table-goto-column col)
8908 (skip-chars-forward "^|")
8909 (skip-chars-backward " ")
8910 (insert " " (org-trim s))
8911 (org-table-align))
8912 ;; split field
8913 (when (looking-at "\\([^|]+\\)+|")
8914 (let ((s (match-string 1)))
8915 (replace-match " |")
8916 (goto-char (match-beginning 0))
8917 (org-table-next-row)
8918 (insert (org-trim s) " ")
8919 (org-table-align))))))
8920
8921 (defun org-trim (s)
8922 "Remove whitespace at beginning and end of string."
8923 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8924 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8925 s)
8926
8927 (defun org-wrap (string &optional width lines)
8928 "Wrap string to either a number of lines, or a width in characters.
8929 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8930 that costs. If there is a word longer than WIDTH, the text is actually
8931 wrapped to the length of that word.
8932 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8933 many lines, whatever width that takes.
8934 The return value is a list of lines, without newlines at the end."
8935 (let* ((words (org-split-string string "[ \t\n]+"))
8936 (maxword (apply 'max (mapcar 'string-width words)))
8937 w ll)
8938 (cond (width
8939 (org-do-wrap words (max maxword width)))
8940 (lines
8941 (setq w maxword)
8942 (setq ll (org-do-wrap words maxword))
8943 (if (<= (length ll) lines)
8944 ll
8945 (setq ll words)
8946 (while (> (length ll) lines)
8947 (setq w (1+ w))
8948 (setq ll (org-do-wrap words w)))
8949 ll))
8950 (t (error "Cannot wrap this")))))
8951
8952
8953 (defun org-do-wrap (words width)
8954 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8955 (let (lines line)
8956 (while words
8957 (setq line (pop words))
8958 (while (and words (< (+ (length line) (length (car words))) width))
8959 (setq line (concat line " " (pop words))))
8960 (setq lines (push line lines)))
8961 (nreverse lines)))
8962
8963 ;; FIXME: I think I can make this more efficient
8964 (defun org-split-string (string &optional separators)
8965 "Splits STRING into substrings at SEPARATORS.
8966 No empty strings are returned if there are matches at the beginning
8967 and end of string."
8968 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8969 (start 0)
8970 notfirst
8971 (list nil))
8972 (while (and (string-match rexp string
8973 (if (and notfirst
8974 (= start (match-beginning 0))
8975 (< start (length string)))
8976 (1+ start) start))
8977 (< (match-beginning 0) (length string)))
8978 (setq notfirst t)
8979 (or (eq (match-beginning 0) 0)
8980 (and (eq (match-beginning 0) (match-end 0))
8981 (eq (match-beginning 0) start))
8982 (setq list
8983 (cons (substring string start (match-beginning 0))
8984 list)))
8985 (setq start (match-end 0)))
8986 (or (eq start (length string))
8987 (setq list
8988 (cons (substring string start)
8989 list)))
8990 (nreverse list)))
8991
8992 (defun org-table-add-invisible-to-vertical-lines ()
8993 "Add an `invisible' property to vertical lines of current table."
8994 (interactive)
8995 (let* ((beg (org-table-begin))
8996 (end (org-table-end))
8997 (end1))
8998 (save-excursion
8999 (goto-char beg)
9000 (while (< (point) end)
9001 (setq end1 (point-at-eol))
9002 (if (looking-at org-table-dataline-regexp)
9003 (while (re-search-forward "|" end1 t)
9004 (add-text-properties (1- (point)) (point)
9005 '(invisible org-table)))
9006 (while (re-search-forward "[+|]" end1 t)
9007 (add-text-properties (1- (point)) (point)
9008 '(invisible org-table))))
9009 (beginning-of-line 2)))))
9010
9011 (defun org-table-toggle-vline-visibility (&optional arg)
9012 "Toggle the visibility of table vertical lines.
9013 The effect is immediate and on all tables in the file.
9014 With prefix ARG, make lines invisible when ARG is positive, make lines
9015 visible when ARG is not positive."
9016 (interactive "P")
9017 (let ((action (cond
9018 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
9019 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
9020 (t (if (org-in-invisibility-spec-p '(org-table))
9021 'off
9022 'on)))))
9023 (if (eq action 'off)
9024 (progn
9025 (org-remove-from-invisibility-spec '(org-table))
9026 (org-table-map-tables 'org-table-align)
9027 (message "Vertical table lines visible")
9028 (if (org-at-table-p)
9029 (org-table-align)))
9030 (org-add-to-invisibility-spec '(org-table))
9031 (org-table-map-tables 'org-table-align)
9032 (message "Vertical table lines invisible"))
9033 (redraw-frame (selected-frame))))
9034
9035 (defun org-table-map-tables (function)
9036 "Apply FUNCTION to the start of all tables in the buffer."
9037 (save-excursion
9038 (save-restriction
9039 (widen)
9040 (goto-char (point-min))
9041 (while (re-search-forward org-table-any-line-regexp nil t)
9042 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9043 (beginning-of-line 1)
9044 (if (looking-at org-table-line-regexp)
9045 (save-excursion (funcall function)))
9046 (re-search-forward org-table-any-border-regexp nil 1)))))
9047
9048 (defun org-table-sum (&optional beg end nlast)
9049 "Sum numbers in region of current table column.
9050 The result will be displayed in the echo area, and will be available
9051 as kill to be inserted with \\[yank].
9052
9053 If there is an active region, it is interpreted as a rectangle and all
9054 numbers in that rectangle will be summed. If there is no active
9055 region and point is located in a table column, sum all numbers in that
9056 column.
9057
9058 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9059 numbers are assumed to be times as well (in decimal hours) and the
9060 numbers are added as such.
9061
9062 If NLAST is a number, only the NLAST fields will actually be summed."
9063 (interactive)
9064 (save-excursion
9065 (let (col (timecnt 0) diff h m s org-table-clip)
9066 (cond
9067 ((and beg end)) ; beg and end given explicitly
9068 ((org-region-active-p)
9069 (setq beg (region-beginning) end (region-end)))
9070 (t
9071 (setq col (org-table-current-column))
9072 (goto-char (org-table-begin))
9073 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9074 (error "No table data"))
9075 (org-table-goto-column col)
9076 ;not needed? (skip-chars-backward "^|")
9077 (setq beg (point))
9078 (goto-char (org-table-end))
9079 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9080 (error "No table data"))
9081 (org-table-goto-column col)
9082 ;not needed? (skip-chars-forward "^|")
9083 (setq end (point))))
9084 (let* ((items (apply 'append (org-table-copy-region beg end)))
9085 (items1 (cond ((not nlast) items)
9086 ((>= nlast (length items)) items)
9087 (t (setq items (reverse items))
9088 (setcdr (nthcdr (1- nlast) items) nil)
9089 (nreverse items))))
9090 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9091 items1)))
9092 (res (apply '+ numbers))
9093 (sres (if (= timecnt 0)
9094 (format "%g" res)
9095 (setq diff (* 3600 res)
9096 h (floor (/ diff 3600)) diff (mod diff 3600)
9097 m (floor (/ diff 60)) diff (mod diff 60)
9098 s diff)
9099 (format "%d:%02d:%02d" h m s))))
9100 (kill-new sres)
9101 (if (interactive-p)
9102 (message "%s"
9103 (substitute-command-keys
9104 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9105 (length numbers) sres))))
9106 sres))))
9107
9108 (defun org-table-get-number-for-summing (s)
9109 (let (n)
9110 (if (string-match "^ *|? *" s)
9111 (setq s (replace-match "" nil nil s)))
9112 (if (string-match " *|? *$" s)
9113 (setq s (replace-match "" nil nil s)))
9114 (setq n (string-to-number s))
9115 (cond
9116 ((and (string-match "0" s)
9117 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9118 ((string-match "\\`[ \t]+\\'" s) nil)
9119 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9120 (let ((h (string-to-number (or (match-string 1 s) "0")))
9121 (m (string-to-number (or (match-string 2 s) "0")))
9122 (s (string-to-number (or (match-string 4 s) "0"))))
9123 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9124 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9125 ((equal n 0) nil)
9126 (t n))))
9127
9128 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9129 "Get a calc vector from a column, accorting to descriptor DESC.
9130 Optional arguments TBEG and COL can give the beginning of the table and
9131 the current column, to avoid unnecessary parsing."
9132 (save-excursion
9133 (or tbeg (setq tbeg (org-table-begin)))
9134 (or col (setq col (org-table-current-column)))
9135 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9136 (cond
9137 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9138 (setq n1 (- (match-end 1) (match-beginning 1)))
9139 (if (match-beginning 3)
9140 (setq n2 (- (match-end 2) (match-beginning 3))))
9141 (setq n (if n2 (max n1 n2) n1))
9142 (setq n1 (if n2 (min n1 n2)))
9143 (setq nn n)
9144 (while (and (> nn 0)
9145 (re-search-backward org-table-hline-regexp tbeg t))
9146 (push (org-current-line) hline-list)
9147 (setq nn (1- nn)))
9148 (setq hline-list (nreverse hline-list))
9149 (goto-line (nth (1- n) hline-list))
9150 (when (re-search-forward org-table-dataline-regexp)
9151 (org-table-goto-column col)
9152 (setq beg (point)))
9153 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9154 (when (re-search-backward org-table-dataline-regexp)
9155 (org-table-goto-column col)
9156 (setq end (point)))
9157 (setq l (apply 'append (org-table-copy-region beg end)))
9158 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9159 (if (equal x "") "0" x))
9160 l ",") "]"))
9161 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9162 (setq n1 (string-to-number (match-string 1 desc))
9163 n2 (string-to-number (match-string 2 desc)))
9164 (beginning-of-line 1)
9165 (save-excursion
9166 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9167 (org-table-goto-column col)
9168 (setq beg (point))))
9169 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9170 (org-table-goto-column col)
9171 (setq end (point)))
9172 (setq l (apply 'append (org-table-copy-region beg end)))
9173 (concat "[" (mapconcat
9174 (lambda (x) (setq x (org-trim x))
9175 (if (equal x "") "0" x))
9176 l ",") "]"))
9177 ((string-match "\\([0-9]+\\)" desc)
9178 (beginning-of-line 1)
9179 (when (re-search-backward org-table-dataline-regexp tbeg t
9180 (string-to-number (match-string 0 desc)))
9181 (org-table-goto-column col)
9182 (org-trim (org-table-get-field))))))))
9183
9184 (defvar org-table-formula-history nil)
9185
9186 (defvar org-table-column-names nil
9187 "Alist with column names, derived from the `!' line.")
9188 (defvar org-table-column-name-regexp nil
9189 "Regular expression matching the current column names.")
9190 (defvar org-table-local-parameters nil
9191 "Alist with parameter names, derived from the `$' line.")
9192 (defvar org-table-named-field-locations nil
9193 "Alist with locations of named fields.")
9194
9195 (defun org-table-get-formula (&optional equation named)
9196 "Read a formula from the minibuffer, offer stored formula as default."
9197 (let* ((name (car (rassoc (list (org-current-line)
9198 (org-table-current-column))
9199 org-table-named-field-locations)))
9200 (scol (if named
9201 (if name name
9202 (error "Not in a named field"))
9203 (int-to-string (org-table-current-column))))
9204 (dummy (and name (not named)
9205 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9206 (error "Abort")))
9207 (org-table-may-need-update nil)
9208 (stored-list (org-table-get-stored-formulas))
9209 (stored (cdr (assoc scol stored-list)))
9210 (eq (cond
9211 ((and stored equation (string-match "^ *=? *$" equation))
9212 stored)
9213 ((stringp equation)
9214 equation)
9215 (t (read-string
9216 (format "%s formula $%s=" (if named "Field" "Column") scol)
9217 (or stored "") 'org-table-formula-history
9218 ;stored
9219 ))))
9220 mustsave)
9221 (when (not (string-match "\\S-" eq))
9222 ;; remove formula
9223 (setq stored-list (delq (assoc scol stored-list) stored-list))
9224 (org-table-store-formulas stored-list)
9225 (error "Formula removed"))
9226 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9227 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9228 (if (and name (not named))
9229 ;; We set the column equation, delete the named one.
9230 (setq stored-list (delq (assoc name stored-list) stored-list)
9231 mustsave t))
9232 (if stored
9233 (setcdr (assoc scol stored-list) eq)
9234 (setq stored-list (cons (cons scol eq) stored-list)))
9235 (if (or mustsave (not (equal stored eq)))
9236 (org-table-store-formulas stored-list))
9237 eq))
9238
9239 (defun org-table-store-formulas (alist)
9240 "Store the list of formulas below the current table."
9241 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9242 (save-excursion
9243 (goto-char (org-table-end))
9244 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9245 (delete-region (point) (match-end 0)))
9246 (insert "#+TBLFM: "
9247 (mapconcat (lambda (x)
9248 (concat "$" (car x) "=" (cdr x)))
9249 alist "::")
9250 "\n")))
9251
9252 (defun org-table-get-stored-formulas ()
9253 "Return an alist with the t=stored formulas directly after current table."
9254 (interactive)
9255 (let (scol eq eq-alist strings string seen)
9256 (save-excursion
9257 (goto-char (org-table-end))
9258 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9259 (setq strings (org-split-string (match-string 2) " *:: *"))
9260 (while (setq string (pop strings))
9261 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9262 (setq scol (match-string 1 string)
9263 eq (match-string 2 string)
9264 eq-alist (cons (cons scol eq) eq-alist))
9265 (if (member scol seen)
9266 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9267 (push scol seen))))))
9268 (nreverse eq-alist)))
9269
9270 (defun org-table-modify-formulas (action &rest columns)
9271 "Modify the formulas stored below the current table.
9272 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9273 expected, for the other actions only a single column number is needed."
9274 (let ((list (org-table-get-stored-formulas))
9275 (nmax (length (org-split-string
9276 (buffer-substring (point-at-bol) (point-at-eol))
9277 "|")))
9278 col col1 col2 scol si sc1 sc2)
9279 (cond
9280 ((null list)) ; No action needed if there are no stored formulas
9281 ((eq action 'remove)
9282 (setq col (car columns)
9283 scol (int-to-string col))
9284 (org-table-replace-in-formulas list scol "INVALID")
9285 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9286 (loop for i from (1+ col) upto nmax by 1 do
9287 (setq si (int-to-string i))
9288 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9289 (if (assoc si list) (setcar (assoc si list)
9290 (int-to-string (1- i))))))
9291 ((eq action 'insert)
9292 (setq col (car columns))
9293 (loop for i from nmax downto col by 1 do
9294 (setq si (int-to-string i))
9295 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9296 (if (assoc si list) (setcar (assoc si list)
9297 (int-to-string (1+ i))))))
9298 ((eq action 'swap)
9299 (setq col1 (car columns) col2 (nth 1 columns)
9300 sc1 (int-to-string col1) sc2 (int-to-string col2))
9301 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
9302 (org-table-replace-in-formulas list sc1 "ZqZ")
9303 (org-table-replace-in-formulas list sc2 sc1)
9304 (org-table-replace-in-formulas list "ZqZ" sc2)
9305 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
9306 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9307 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
9308 (t (error "Invalid action in `org-table-modify-formulas'")))
9309 (if list (org-table-store-formulas list))))
9310
9311 (defun org-table-replace-in-formulas (list s1 s2)
9312 (let (elt re s)
9313 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9314 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
9315 re (concat (regexp-quote s1) "\\>"))
9316 (while (setq elt (pop list))
9317 (setq s (cdr elt))
9318 (while (string-match re s)
9319 (setq s (replace-match s2 t t s)))
9320 (setcdr elt s))))
9321
9322 (defun org-table-get-specials ()
9323 "Get the column names and local parameters for this table."
9324 (save-excursion
9325 (let ((beg (org-table-begin)) (end (org-table-end))
9326 names name fields fields1 field cnt c v line col)
9327 (setq org-table-column-names nil
9328 org-table-local-parameters nil
9329 org-table-named-field-locations nil)
9330 (goto-char beg)
9331 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9332 (setq names (org-split-string (match-string 1) " *| *")
9333 cnt 1)
9334 (while (setq name (pop names))
9335 (setq cnt (1+ cnt))
9336 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9337 (push (cons name (int-to-string cnt)) org-table-column-names))))
9338 (setq org-table-column-names (nreverse org-table-column-names))
9339 (setq org-table-column-name-regexp
9340 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9341 (goto-char beg)
9342 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9343 (setq fields (org-split-string (match-string 1) " *| *"))
9344 (while (setq field (pop fields))
9345 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9346 (push (cons (match-string 1 field) (match-string 2 field))
9347 org-table-local-parameters))))
9348 (goto-char beg)
9349 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9350 (setq c (match-string 1)
9351 fields (org-split-string (match-string 2) " *| *"))
9352 (save-excursion
9353 (beginning-of-line (if (equal c "_") 2 0))
9354 (setq line (org-current-line) col 1)
9355 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9356 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9357 (while (and fields1 (setq field (pop fields)))
9358 (setq v (pop fields1) col (1+ col))
9359 (when (and (stringp field) (stringp v)
9360 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9361 (push (cons field v) org-table-local-parameters)
9362 (push (list field line col) org-table-named-field-locations)))))))
9363
9364 (defun org-this-word ()
9365 ;; Get the current word
9366 (save-excursion
9367 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
9368 (end (progn (skip-chars-forward "^ \t\n") (point))))
9369 (buffer-substring-no-properties beg end))))
9370
9371 (defun org-table-maybe-eval-formula ()
9372 "Check if the current field starts with \"=\" or \":=\".
9373 If yes, store the formula and apply it."
9374 ;; We already know we are in a table. Get field will only return a formula
9375 ;; when appropriate. It might return a separator line, but no problem.
9376 (when org-table-formula-evaluate-inline
9377 (let* ((field (org-trim (or (org-table-get-field) "")))
9378 named eq)
9379 (when (string-match "^:?=\\(.*\\)" field)
9380 (setq named (equal (string-to-char field) ?:)
9381 eq (match-string 1 field))
9382 (if (fboundp 'calc-eval)
9383 (org-table-eval-formula (if named '(4) nil) eq))))))
9384
9385 (defvar org-recalc-commands nil
9386 "List of commands triggering the recalculation of a line.
9387 Will be filled automatically during use.")
9388
9389 (defvar org-recalc-marks
9390 '((" " . "Unmarked: no special line, no automatic recalculation")
9391 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9392 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9393 ("!" . "Column name definition line. Reference in formula as $name.")
9394 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9395 ("_" . "Names for values in row below this one.")
9396 ("^" . "Names for values in row above this one.")))
9397
9398 (defun org-table-rotate-recalc-marks (&optional newchar)
9399 "Rotate the recalculation mark in the first column.
9400 If in any row, the first field is not consistent with a mark,
9401 insert a new column for the markers.
9402 When there is an active region, change all the lines in the region,
9403 after prompting for the marking character.
9404 After each change, a message will be displayed indicating the meaning
9405 of the new mark."
9406 (interactive)
9407 (unless (org-at-table-p) (error "Not at a table"))
9408 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9409 (beg (org-table-begin))
9410 (end (org-table-end))
9411 (l (org-current-line))
9412 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9413 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9414 (have-col
9415 (save-excursion
9416 (goto-char beg)
9417 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9418 (col (org-table-current-column))
9419 (forcenew (car (assoc newchar org-recalc-marks)))
9420 epos new)
9421 (when l1
9422 (message "Change region to what mark? Type # * ! $ or SPC: ")
9423 (setq newchar (char-to-string (read-char-exclusive))
9424 forcenew (car (assoc newchar org-recalc-marks))))
9425 (if (and newchar (not forcenew))
9426 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9427 newchar))
9428 (if l1 (goto-line l1))
9429 (save-excursion
9430 (beginning-of-line 1)
9431 (unless (looking-at org-table-dataline-regexp)
9432 (error "Not at a table data line")))
9433 (unless have-col
9434 (org-table-goto-column 1)
9435 (org-table-insert-column)
9436 (org-table-goto-column (1+ col)))
9437 (setq epos (point-at-eol))
9438 (save-excursion
9439 (beginning-of-line 1)
9440 (org-table-get-field
9441 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9442 (concat " "
9443 (setq new (or forcenew
9444 (cadr (member (match-string 1) marks))))
9445 " ")
9446 " # ")))
9447 (if (and l1 l2)
9448 (progn
9449 (goto-line l1)
9450 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9451 (and (looking-at org-table-dataline-regexp)
9452 (org-table-get-field 1 (concat " " new " "))))
9453 (goto-line l1)))
9454 (if (not (= epos (point-at-eol))) (org-table-align))
9455 (goto-line l)
9456 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9457
9458 (defun org-table-maybe-recalculate-line ()
9459 "Recompute the current line if marked for it, and if we haven't just done it."
9460 (interactive)
9461 (and org-table-allow-automatic-line-recalculation
9462 (not (and (memq last-command org-recalc-commands)
9463 (equal org-last-recalc-line (org-current-line))))
9464 (save-excursion (beginning-of-line 1)
9465 (looking-at org-table-auto-recalculate-regexp))
9466 (fboundp 'calc-eval)
9467 (org-table-recalculate) t))
9468
9469 (defvar org-table-formula-debug nil
9470 "Non-nil means, debug table formulas.
9471 When nil, simply write \"#ERROR\" in corrupted fields.")
9472
9473 (defvar modes)
9474 (defsubst org-set-calc-mode (var &optional value)
9475 (if (stringp var)
9476 (setq var (assoc var '(("D" calc-angle-mode deg)
9477 ("R" calc-angle-mode rad)
9478 ("F" calc-prefer-frac t)
9479 ("S" calc-symbolic-mode t)))
9480 value (nth 2 var) var (nth 1 var)))
9481 (if (memq var modes)
9482 (setcar (cdr (memq var modes)) value)
9483 (cons var (cons value modes)))
9484 modes)
9485
9486 (defun org-table-eval-formula (&optional arg equation
9487 suppress-align suppress-const
9488 suppress-store)
9489 "Replace the table field value at the cursor by the result of a calculation.
9490
9491 This function makes use of Dave Gillespie's Calc package, in my view the
9492 most exciting program ever written for GNU Emacs. So you need to have Calc
9493 installed in order to use this function.
9494
9495 In a table, this command replaces the value in the current field with the
9496 result of a formula. It also installs the formula as the \"current\" column
9497 formula, by storing it in a special line below the table. When called
9498 with a `C-u' prefix, the current field must ba a named field, and the
9499 formula is installed as valid in only this specific field.
9500
9501 When called, the command first prompts for a formula, which is read in
9502 the minibuffer. Previously entered formulas are available through the
9503 history list, and the last used formula is offered as a default.
9504 These stored formulas are adapted correctly when moving, inserting, or
9505 deleting columns with the corresponding commands.
9506
9507 The formula can be any algebraic expression understood by the Calc package.
9508 For details, see the Org-mode manual.
9509
9510 This function can also be called from Lisp programs and offers
9511 additional arguments: EQUATION can be the formula to apply. If this
9512 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9513 used to speed-up recursive calls by by-passing unnecessary aligns.
9514 SUPPRESS-CONST suppresses the interpretation of constants in the
9515 formula, assuming that this has been done already outside the function.
9516 SUPPRESS-STORE means the formula should not be stored, either because
9517 it is already stored, or because it is a modified equation that should
9518 not overwrite the stored one."
9519 (interactive "P")
9520 (require 'calc)
9521 (org-table-check-inside-data-field)
9522 (org-table-get-specials)
9523 (let* (fields
9524 (ndown (if (integerp arg) arg 1))
9525 (org-table-automatic-realign nil)
9526 (case-fold-search nil)
9527 (down (> ndown 1))
9528 (formula (if (and equation suppress-store)
9529 equation
9530 (org-table-get-formula equation (equal arg '(4)))))
9531 (n0 (org-table-current-column))
9532 (modes (copy-sequence org-calc-default-modes))
9533 n form fmt x ev orig c)
9534 ;; Parse the format string. Since we have a lot of modes, this is
9535 ;; a lot of work. However, I think calc still uses most of the time.
9536 (if (string-match ";" formula)
9537 (let ((tmp (org-split-string formula ";")))
9538 (setq formula (car tmp)
9539 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9540 (nth 1 tmp)))
9541 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9542 (setq c (string-to-char (match-string 1 fmt))
9543 n (string-to-number (or (match-string 1 fmt) "")))
9544 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9545 (setq modes (org-set-calc-mode
9546 'calc-float-format
9547 (list (cdr (assoc c '((?n . float) (?f . fix)
9548 (?s . sci) (?e . eng))))
9549 n))))
9550 (setq fmt (replace-match "" t t fmt)))
9551 (while (string-match "[DRFS]" fmt)
9552 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9553 (setq fmt (replace-match "" t t fmt)))
9554 (unless (string-match "\\S-" fmt)
9555 (setq fmt nil))))
9556 (if (and (not suppress-const) org-table-formula-use-constants)
9557 (setq formula (org-table-formula-substitute-names formula)))
9558 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9559 (while (> ndown 0)
9560 (setq fields (org-split-string
9561 (buffer-substring
9562 (point-at-bol) (point-at-eol)) " *| *"))
9563 (if org-table-formula-numbers-only
9564 (setq fields (mapcar
9565 (lambda (x) (number-to-string (string-to-number x)))
9566 fields)))
9567 (setq ndown (1- ndown))
9568 (setq form (copy-sequence formula))
9569 ;; Insert the references to fields in same row
9570 (while (string-match "\\$\\([0-9]+\\)?" form)
9571 (setq n (if (match-beginning 1)
9572 (string-to-number (match-string 1 form))
9573 n0)
9574 x (nth (1- n) fields))
9575 (unless x (error "Invalid field specifier \"%s\""
9576 (match-string 0 form)))
9577 (if (equal x "") (setq x "0"))
9578 (setq form (replace-match (concat "(" x ")") t t form)))
9579 ;; Insert ranges in current column
9580 (while (string-match "\\&[-I0-9]+" form)
9581 (setq form (replace-match
9582 (save-match-data
9583 (org-table-get-vertical-vector (match-string 0 form)
9584 nil n0))
9585 t t form)))
9586 (setq ev (calc-eval (cons form modes)
9587 (if org-table-formula-numbers-only 'num)))
9588
9589 (when org-table-formula-debug
9590 (with-output-to-temp-buffer "*Help*"
9591 (princ (format "Substitution history of formula
9592 Orig: %s
9593 $xyz-> %s
9594 $1-> %s\n" orig formula form))
9595 (if (listp ev)
9596 (princ (format " %s^\nError: %s"
9597 (make-string (car ev) ?\-) (nth 1 ev)))
9598 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9599 ev (or fmt "NONE")
9600 (if fmt (format fmt (string-to-number ev)) ev)))))
9601 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9602 (unless (and (interactive-p) (not ndown))
9603 (unless (let (inhibit-redisplay)
9604 (y-or-n-p "Debugging Formula. Continue to next? "))
9605 (org-table-align)
9606 (error "Abort"))
9607 (delete-window (get-buffer-window "*Help*"))
9608 (message "")))
9609 (if (listp ev) (setq fmt nil ev "#ERROR"))
9610 (org-table-justify-field-maybe
9611 (if fmt (format fmt (string-to-number ev)) ev))
9612 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9613 (call-interactively 'org-return)
9614 (setq ndown 0)))
9615 (and down (org-table-maybe-recalculate-line))
9616 (or suppress-align (and org-table-may-need-update
9617 (org-table-align)))))
9618
9619 (defun org-table-recalculate (&optional all noalign)
9620 "Recalculate the current table line by applying all stored formulas."
9621 (interactive "P")
9622 (or (memq this-command org-recalc-commands)
9623 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9624 (unless (org-at-table-p) (error "Not at a table"))
9625 (org-table-get-specials)
9626 (let* ((eqlist (sort (org-table-get-stored-formulas)
9627 (lambda (a b) (string< (car a) (car b)))))
9628 (inhibit-redisplay t)
9629 (line-re org-table-dataline-regexp)
9630 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9631 (thiscol (org-table-current-column))
9632 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9633 ;; Insert constants in all formulas
9634 (setq eqlist
9635 (mapcar (lambda (x)
9636 (setcdr x (org-table-formula-substitute-names (cdr x)))
9637 x)
9638 eqlist))
9639 ;; Split the equation list
9640 (while (setq eq (pop eqlist))
9641 (if (<= (string-to-char (car eq)) ?9)
9642 (push eq eqlnum)
9643 (push eq eqlname)))
9644 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9645 (if all
9646 (progn
9647 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9648 (goto-char (setq beg (org-table-begin)))
9649 (if (re-search-forward org-table-calculate-mark-regexp end t)
9650 ;; This is a table with marked lines, only compute selected lines
9651 (setq line-re org-table-recalculate-regexp)
9652 ;; Move forward to the first non-header line
9653 (if (and (re-search-forward org-table-dataline-regexp end t)
9654 (re-search-forward org-table-hline-regexp end t)
9655 (re-search-forward org-table-dataline-regexp end t))
9656 (setq beg (match-beginning 0))
9657 nil))) ;; just leave beg where it is
9658 (setq beg (point-at-bol)
9659 end (move-marker (make-marker) (1+ (point-at-eol)))))
9660 (goto-char beg)
9661 (and all (message "Re-applying formulas to full table..."))
9662 (while (re-search-forward line-re end t)
9663 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9664 ;; Unprotected line, recalculate
9665 (and all (message "Re-applying formulas to full table...(line %d)"
9666 (setq cnt (1+ cnt))))
9667 (setq org-last-recalc-line (org-current-line))
9668 (setq eql eqlnum)
9669 (while (setq entry (pop eql))
9670 (goto-line org-last-recalc-line)
9671 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9672 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9673 (goto-line thisline)
9674 (org-table-goto-column thiscol)
9675 (or noalign (and org-table-may-need-update (org-table-align))
9676 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9677 ;; Now do the names fields
9678 (while (setq eq (pop eqlname))
9679 (setq name (car eq)
9680 a (assoc name org-table-named-field-locations))
9681 (when a
9682 (message "Re-applying formula to named field: %s" name)
9683 (goto-line (nth 1 a))
9684 (org-table-goto-column (nth 2 a))
9685 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9686 ;; back to initial position
9687 (goto-line thisline)
9688 (org-table-goto-column thiscol)
9689 (or noalign (and org-table-may-need-update (org-table-align))
9690 (and all (message "Re-applying formulas...done")))))
9691
9692 (defun org-table-formula-substitute-names (f)
9693 "Replace $const with values in string F."
9694 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9695 ;; First, check for column names
9696 (while (setq start (string-match org-table-column-name-regexp f start))
9697 (setq start (1+ start))
9698 (setq a (assoc (match-string 1 f) org-table-column-names))
9699 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9700 ;; Expand ranges to vectors
9701 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9702 (setq n1 (string-to-number (match-string 1 f))
9703 n2 (string-to-number (match-string 2 f))
9704 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9705 s (concat "[($" (number-to-string (1- nn1)) ")"))
9706 (loop for i from nn1 upto nn2 do
9707 (setq s (concat s ",($" (int-to-string i) ")")))
9708 (setq s (concat s "]"))
9709 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9710 (setq f (replace-match s t t f)))
9711 ;; Parameters and constants
9712 (setq start 0)
9713 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9714 (setq start (1+ start))
9715 (if (setq a (save-match-data
9716 (org-table-get-constant (match-string 1 f))))
9717 (setq f (replace-match (concat "(" a ")") t t f))))
9718 (if org-table-formula-debug
9719 (put-text-property 0 (length f) :orig-formula f1 f))
9720 f))
9721
9722 (defun org-table-get-constant (const)
9723 "Find the value for a parameter or constant in a formula.
9724 Parameters get priority."
9725 (or (cdr (assoc const org-table-local-parameters))
9726 (cdr (assoc const org-table-formula-constants))
9727 (and (fboundp 'constants-get) (constants-get const))
9728 "#UNDEFINED_NAME"))
9729
9730 (defvar org-edit-formulas-map (make-sparse-keymap))
9731 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9732 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9733 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9734
9735 (defvar org-pos)
9736 (defvar org-window-configuration)
9737
9738 (defun org-table-edit-formulas ()
9739 "Edit the formulas of the current table in a separate buffer."
9740 (interactive)
9741 (unless (org-at-table-p)
9742 (error "Not at a table"))
9743 (org-table-get-specials)
9744 (let ((eql (org-table-get-stored-formulas))
9745 (pos (move-marker (make-marker) (point)))
9746 (wc (current-window-configuration))
9747 entry loc s)
9748 (switch-to-buffer-other-window "*Edit Formulas*")
9749 (erase-buffer)
9750 (fundamental-mode)
9751 (set (make-local-variable 'org-pos) pos)
9752 (set (make-local-variable 'org-window-configuration) wc)
9753 (use-local-map org-edit-formulas-map)
9754 (setq s "# Edit formulas and finish with `C-c C-c'.
9755 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9756 # Use `C-c ?' to get information about $name at point.
9757 # To cancel editing, press `C-c C-q'.\n")
9758 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9759 (insert s)
9760 (while (setq entry (pop eql))
9761 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9762 (setq s (format "# Named formula, referring to column %d in line %d\n"
9763 (nth 2 loc) (nth 1 loc)))
9764 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9765 (insert s))
9766 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9767 (remove-text-properties 0 (length s) '(face nil) s)
9768 (insert s))
9769 (goto-char (point-min))
9770 (message "Edit formulas and finish with `C-c C-c'.")))
9771
9772 (defun org-show-variable ()
9773 "Show the location/value of the $ expression at point."
9774 (interactive)
9775 (let (var (pos org-pos) (win (selected-window)) e)
9776 (save-excursion
9777 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9778 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9779 (setq var (match-string 1))
9780 (error "No variable at point")))
9781 (cond
9782 ((setq e (assoc var org-table-named-field-locations))
9783 (switch-to-buffer-other-window (marker-buffer pos))
9784 (goto-line (nth 1 e))
9785 (org-table-goto-column (nth 2 e))
9786 (select-window win)
9787 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9788 ((setq e (assoc var org-table-column-names))
9789 (switch-to-buffer-other-window (marker-buffer pos))
9790 (goto-char pos)
9791 (goto-char (org-table-begin))
9792 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9793 (org-table-end) t)
9794 (progn
9795 (goto-char (match-beginning 1))
9796 (message "Named column (column %s)" (cdr e)))
9797 (error "Column name not found"))
9798 (select-window win))
9799 ((string-match "^[0-9]$" var)
9800 ;; column number
9801 (switch-to-buffer-other-window (marker-buffer pos))
9802 (goto-char pos)
9803 (goto-char (org-table-begin))
9804 (recenter 1)
9805 (if (re-search-forward org-table-dataline-regexp
9806 (org-table-end) t)
9807 (progn
9808 (goto-char (match-beginning 0))
9809 (org-table-goto-column (string-to-number var))
9810 (message "Column %s" var))
9811 (error "Column name not found"))
9812 (select-window win))
9813 ((setq e (assoc var org-table-local-parameters))
9814 (switch-to-buffer-other-window (marker-buffer pos))
9815 (goto-char pos)
9816 (goto-char (org-table-begin))
9817 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9818 (progn
9819 (goto-char (match-beginning 1))
9820 (message "Local parameter."))
9821 (error "Parameter not found"))
9822 (select-window win))
9823 (t
9824 (cond
9825 ((setq e (assoc var org-table-formula-constants))
9826 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9827 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9828 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9829 (t (error "Undefined name $%s" var)))))))
9830
9831 (defun org-finish-edit-formulas (&optional arg)
9832 "Parse the buffer for formula definitions and install them.
9833 With prefix ARG, apply the new formulas to the table."
9834 (interactive "P")
9835 (let ((pos org-pos) eql)
9836 (goto-char (point-min))
9837 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9838 (push (cons (match-string 1) (match-string 2)) eql))
9839 (set-window-configuration org-window-configuration)
9840 (select-window (get-buffer-window (marker-buffer pos)))
9841 (goto-char pos)
9842 (unless (org-at-table-p)
9843 (error "Lost table position - cannot install formulae"))
9844 (org-table-store-formulas eql)
9845 (move-marker pos nil)
9846 (kill-buffer "*Edit Formulas*")
9847 (if arg
9848 (org-table-recalculate 'all)
9849 (message "New formulas installed - press C-u C-c C-c to apply."))))
9850
9851 (defun org-abort-edit-formulas ()
9852 "Abort editing formulas, without installing the changes."
9853 (interactive)
9854 (let ((pos org-pos))
9855 (set-window-configuration org-window-configuration)
9856 (select-window (get-buffer-window (marker-buffer pos)))
9857 (goto-char pos)
9858 (message "Formula editing aborted without installing changes")))
9859
9860 ;;; The orgtbl minor mode
9861
9862 ;; Define a minor mode which can be used in other modes in order to
9863 ;; integrate the org-mode table editor.
9864
9865 ;; This is really a hack, because the org-mode table editor uses several
9866 ;; keys which normally belong to the major mode, for example the TAB and
9867 ;; RET keys. Here is how it works: The minor mode defines all the keys
9868 ;; necessary to operate the table editor, but wraps the commands into a
9869 ;; function which tests if the cursor is currently inside a table. If that
9870 ;; is the case, the table editor command is executed. However, when any of
9871 ;; those keys is used outside a table, the function uses `key-binding' to
9872 ;; look up if the key has an associated command in another currently active
9873 ;; keymap (minor modes, major mode, global), and executes that command.
9874 ;; There might be problems if any of the keys used by the table editor is
9875 ;; otherwise used as a prefix key.
9876
9877 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9878 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9879 ;; addresses this by checking explicitly for both bindings.
9880
9881 ;; The optimized version (see variable `orgtbl-optimized') takes over
9882 ;; all keys which are bound to `self-insert-command' in the *global map*.
9883 ;; Some modes bind other commands to simple characters, for example
9884 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9885 ;; active, this binding is ignored inside tables and replaced with a
9886 ;; modified self-insert.
9887
9888 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9889 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9890 In the optimized version, the table editor takes over all simple keys that
9891 normally just insert a character. In tables, the characters are inserted
9892 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9893 for empty fields). Outside tables, the correct binding of the keys is
9894 restored.
9895
9896 The default for this option is t if the optimized version is also used in
9897 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9898 this variable requires a restart of Emacs to become effective."
9899 :group 'org-table
9900 :type 'boolean)
9901
9902 (defvar orgtbl-mode nil
9903 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9904 table editor in arbitrary modes.")
9905 (make-variable-buffer-local 'orgtbl-mode)
9906
9907 (defvar orgtbl-mode-map (make-keymap)
9908 "Keymap for `orgtbl-mode'.")
9909
9910 ;;;###autoload
9911 (defun turn-on-orgtbl ()
9912 "Unconditionally turn on `orgtbl-mode'."
9913 (orgtbl-mode 1))
9914
9915 ;;;###autoload
9916 (defun orgtbl-mode (&optional arg)
9917 "The `org-mode' table editor as a minor mode for use in other modes."
9918 (interactive)
9919 (if (eq major-mode 'org-mode)
9920 ;; Exit without error, in case some hook functions calls this
9921 ;; by accident in org-mode.
9922 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9923 (setq orgtbl-mode
9924 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9925 (if orgtbl-mode
9926 (progn
9927 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9928 ;; Make sure we are first in minor-mode-map-alist
9929 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9930 (and c (setq minor-mode-map-alist
9931 (cons c (delq c minor-mode-map-alist)))))
9932 (set (make-local-variable (quote org-table-may-need-update)) t)
9933 (org-add-hook 'before-change-functions 'org-before-change-function
9934 nil 'local)
9935 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
9936 auto-fill-inhibit-regexp)
9937 (set (make-local-variable 'auto-fill-inhibit-regexp)
9938 (if auto-fill-inhibit-regexp
9939 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
9940 "[ \t]*|"))
9941 (easy-menu-add orgtbl-mode-menu)
9942 (run-hooks 'orgtbl-mode-hook))
9943 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9944 (remove-hook 'before-change-functions 'org-before-change-function t)
9945 (easy-menu-remove orgtbl-mode-menu)
9946 (force-mode-line-update 'all))))
9947
9948 ;; Install it as a minor mode.
9949 (put 'orgtbl-mode :included t)
9950 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9951 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9952
9953 (defun orgtbl-make-binding (fun n &rest keys)
9954 "Create a function for binding in the table minor mode.
9955 FUN is the command to call inside a table. N is used to create a unique
9956 command name. KEYS are keys that should be checked in for a command
9957 to execute outside of tables."
9958 (eval
9959 (list 'defun
9960 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9961 '(arg)
9962 (concat "In tables, run `" (symbol-name fun) "'.\n"
9963 "Outside of tables, run the binding of `"
9964 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9965 "'.")
9966 '(interactive "p")
9967 (list 'if
9968 '(org-at-table-p)
9969 (list 'call-interactively (list 'quote fun))
9970 (list 'let '(orgtbl-mode)
9971 (list 'call-interactively
9972 (append '(or)
9973 (mapcar (lambda (k)
9974 (list 'key-binding k))
9975 keys)
9976 '('orgtbl-error))))))))
9977
9978 (defun orgtbl-error ()
9979 "Error when there is no default binding for a table key."
9980 (interactive)
9981 (error "This key is has no function outside tables"))
9982
9983 (defun orgtbl-setup ()
9984 "Setup orgtbl keymaps."
9985 (let ((nfunc 0)
9986 (bindings
9987 (list
9988 '([(meta shift left)] org-table-delete-column)
9989 '([(meta left)] org-table-move-column-left)
9990 '([(meta right)] org-table-move-column-right)
9991 '([(meta shift right)] org-table-insert-column)
9992 '([(meta shift up)] org-table-kill-row)
9993 '([(meta shift down)] org-table-insert-row)
9994 '([(meta up)] org-table-move-row-up)
9995 '([(meta down)] org-table-move-row-down)
9996 '("\C-c\C-w" org-table-cut-region)
9997 '("\C-c\M-w" org-table-copy-region)
9998 '("\C-c\C-y" org-table-paste-rectangle)
9999 '("\C-c-" org-table-insert-hline)
10000 ; '([(shift tab)] org-table-previous-field)
10001 '("\C-m" org-table-next-row)
10002 (list (org-key 'S-return) 'org-table-copy-down)
10003 '([(meta return)] org-table-wrap-region)
10004 '("\C-c\C-q" org-table-wrap-region)
10005 '("\C-c?" org-table-current-column)
10006 '("\C-c " org-table-blank-field)
10007 '("\C-c+" org-table-sum)
10008 '("\C-c|" org-table-toggle-vline-visibility)
10009 '("\C-c=" org-table-eval-formula)
10010 '("\C-c'" org-table-edit-formulas)
10011 '("\C-c*" org-table-recalculate)
10012 '("\C-c^" org-table-sort-lines)
10013 '([(control ?#)] org-table-rotate-recalc-marks)))
10014 elt key fun cmd)
10015 (while (setq elt (pop bindings))
10016 (setq nfunc (1+ nfunc))
10017 (setq key (car elt)
10018 fun (nth 1 elt)
10019 cmd (orgtbl-make-binding fun nfunc key))
10020 (define-key orgtbl-mode-map key cmd))
10021 ;; Special treatment needed for TAB and RET
10022 (define-key orgtbl-mode-map [(return)]
10023 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10024 (define-key orgtbl-mode-map "\C-m"
10025 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10026 (define-key orgtbl-mode-map [(tab)]
10027 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10028 (define-key orgtbl-mode-map "\C-i"
10029 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10030 (define-key orgtbl-mode-map "\C-i"
10031 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10032 (define-key orgtbl-mode-map "\C-c\C-c"
10033 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10034 (when orgtbl-optimized
10035 ;; If the user wants maximum table support, we need to hijack
10036 ;; some standard editing functions
10037 (org-remap orgtbl-mode-map
10038 'self-insert-command 'orgtbl-self-insert-command
10039 'delete-char 'orgtbl-delete-char
10040 'delete-backward-char 'orgtbl-delete-backward-char)
10041 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10042 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10043 '("OrgTbl"
10044 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10045 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10046 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10047 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10048 "--"
10049 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10050 ["Copy Field from Above"
10051 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10052 "--"
10053 ("Column"
10054 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10055 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10056 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10057 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10058 ("Row"
10059 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10060 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10061 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10062 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10063 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10064 "--"
10065 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10066 ("Rectangle"
10067 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10068 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10069 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10070 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10071 "--"
10072 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10073 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10074 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10075 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10076 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10077 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10078 ["Sum Column/Rectangle" org-table-sum
10079 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10080 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10081 ["Debug Formulas"
10082 (setq org-table-formula-debug (not org-table-formula-debug))
10083 :style toggle :selected org-table-formula-debug]
10084 ))
10085 t)
10086
10087 (defun orgtbl-tab ()
10088 "Justification and field motion for `orgtbl-mode'."
10089 (interactive)
10090 (org-table-justify-field-maybe)
10091 (org-table-next-field))
10092
10093 (defun orgtbl-ret ()
10094 "Justification and field motion for `orgtbl-mode'."
10095 (interactive)
10096 (org-table-justify-field-maybe)
10097 (org-table-next-row))
10098
10099 (defun orgtbl-self-insert-command (N)
10100 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10101 If the cursor is in a table looking at whitespace, the whitespace is
10102 overwritten, and the table is not marked as requiring realignment."
10103 (interactive "p")
10104 (if (and (org-at-table-p)
10105 (or
10106 (and org-table-auto-blank-field
10107 (member last-command
10108 '(orgtbl-hijacker-command-100
10109 orgtbl-hijacker-command-101
10110 orgtbl-hijacker-command-102
10111 orgtbl-hijacker-command-103
10112 orgtbl-hijacker-command-104
10113 orgtbl-hijacker-command-105))
10114 (org-table-blank-field))
10115 t)
10116 (eq N 1)
10117 (looking-at "[^|\n]* +|"))
10118 (let (org-table-may-need-update)
10119 (goto-char (1- (match-end 0)))
10120 (delete-backward-char 1)
10121 (goto-char (match-beginning 0))
10122 (self-insert-command N))
10123 (setq org-table-may-need-update t)
10124 (let (orgtbl-mode)
10125 (call-interactively (key-binding (vector last-input-event))))))
10126
10127 (defun org-force-self-insert (N)
10128 "Needed to enforce self-insert under remapping."
10129 (interactive "p")
10130 (self-insert-command N))
10131
10132 (defun orgtbl-delete-backward-char (N)
10133 "Like `delete-backward-char', insert whitespace at field end in tables.
10134 When deleting backwards, in tables this function will insert whitespace in
10135 front of the next \"|\" separator, to keep the table aligned. The table will
10136 still be marked for re-alignment, because a narrow field may lead to a
10137 reduced column width."
10138 (interactive "p")
10139 (if (and (org-at-table-p)
10140 (eq N 1)
10141 (string-match "|" (buffer-substring (point-at-bol) (point)))
10142 (looking-at ".*?|"))
10143 (let ((pos (point)))
10144 (backward-delete-char N)
10145 (skip-chars-forward "^|")
10146 (insert " ")
10147 (goto-char (1- pos)))
10148 (delete-backward-char N)))
10149
10150 (defun orgtbl-delete-char (N)
10151 "Like `delete-char', but insert whitespace at field end in tables.
10152 When deleting characters, in tables this function will insert whitespace in
10153 front of the next \"|\" separator, to keep the table aligned. The table
10154 will still be marked for re-alignment, because a narrow field may lead to
10155 a reduced column width."
10156 (interactive "p")
10157 (if (and (org-at-table-p)
10158 (not (bolp))
10159 (not (= (char-after) ?|))
10160 (eq N 1))
10161 (if (looking-at ".*?|")
10162 (let ((pos (point)))
10163 (replace-match (concat
10164 (substring (match-string 0) 1 -1)
10165 " |"))
10166 (goto-char pos)))
10167 (delete-char N)))
10168
10169 ;;; Exporting
10170
10171 (defconst org-level-max 20)
10172
10173 (defun org-export-find-first-heading-line (list)
10174 "Remove all lines from LIST which are before the first headline."
10175 (let ((orig-list list)
10176 (re (concat "^" outline-regexp)))
10177 (while (and list
10178 (not (string-match re (car list))))
10179 (pop list))
10180 (or list orig-list)))
10181
10182 (defun org-skip-comments (lines)
10183 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10184 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10185 (re2 "^\\(\\*+\\)[ \t\n\r]")
10186 rtn line level)
10187 (while (setq line (pop lines))
10188 (cond
10189 ((and (string-match re1 line)
10190 (setq level (- (match-end 1) (match-beginning 1))))
10191 ;; Beginning of a COMMENT subtree. Skip it.
10192 (while (and (setq line (pop lines))
10193 (or (not (string-match re2 line))
10194 (> (- (match-end 1) (match-beginning 1)) level))))
10195 (setq lines (cons line lines)))
10196 ((string-match "^#" line)
10197 ;; an ordinary comment line
10198 )
10199 ((and org-export-table-remove-special-lines
10200 (string-match "^[ \t]*| *[!_^] *|" line))
10201 ;; a special table line that should be removed
10202 )
10203 (t (setq rtn (cons line rtn)))))
10204 (nreverse rtn)))
10205
10206 ;; ASCII
10207
10208 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10209 "Characters for underlining headings in ASCII export.")
10210
10211 (defconst org-html-entities
10212 '(("nbsp")
10213 ("iexcl")
10214 ("cent")
10215 ("pound")
10216 ("curren")
10217 ("yen")
10218 ("brvbar")
10219 ("sect")
10220 ("uml")
10221 ("copy")
10222 ("ordf")
10223 ("laquo")
10224 ("not")
10225 ("shy")
10226 ("reg")
10227 ("macr")
10228 ("deg")
10229 ("plusmn")
10230 ("sup2")
10231 ("sup3")
10232 ("acute")
10233 ("micro")
10234 ("para")
10235 ("middot")
10236 ("odot"."o")
10237 ("star"."*")
10238 ("cedil")
10239 ("sup1")
10240 ("ordm")
10241 ("raquo")
10242 ("frac14")
10243 ("frac12")
10244 ("frac34")
10245 ("iquest")
10246 ("Agrave")
10247 ("Aacute")
10248 ("Acirc")
10249 ("Atilde")
10250 ("Auml")
10251 ("Aring") ("AA"."&Aring;")
10252 ("AElig")
10253 ("Ccedil")
10254 ("Egrave")
10255 ("Eacute")
10256 ("Ecirc")
10257 ("Euml")
10258 ("Igrave")
10259 ("Iacute")
10260 ("Icirc")
10261 ("Iuml")
10262 ("ETH")
10263 ("Ntilde")
10264 ("Ograve")
10265 ("Oacute")
10266 ("Ocirc")
10267 ("Otilde")
10268 ("Ouml")
10269 ("times")
10270 ("Oslash")
10271 ("Ugrave")
10272 ("Uacute")
10273 ("Ucirc")
10274 ("Uuml")
10275 ("Yacute")
10276 ("THORN")
10277 ("szlig")
10278 ("agrave")
10279 ("aacute")
10280 ("acirc")
10281 ("atilde")
10282 ("auml")
10283 ("aring")
10284 ("aelig")
10285 ("ccedil")
10286 ("egrave")
10287 ("eacute")
10288 ("ecirc")
10289 ("euml")
10290 ("igrave")
10291 ("iacute")
10292 ("icirc")
10293 ("iuml")
10294 ("eth")
10295 ("ntilde")
10296 ("ograve")
10297 ("oacute")
10298 ("ocirc")
10299 ("otilde")
10300 ("ouml")
10301 ("divide")
10302 ("oslash")
10303 ("ugrave")
10304 ("uacute")
10305 ("ucirc")
10306 ("uuml")
10307 ("yacute")
10308 ("thorn")
10309 ("yuml")
10310 ("fnof")
10311 ("Alpha")
10312 ("Beta")
10313 ("Gamma")
10314 ("Delta")
10315 ("Epsilon")
10316 ("Zeta")
10317 ("Eta")
10318 ("Theta")
10319 ("Iota")
10320 ("Kappa")
10321 ("Lambda")
10322 ("Mu")
10323 ("Nu")
10324 ("Xi")
10325 ("Omicron")
10326 ("Pi")
10327 ("Rho")
10328 ("Sigma")
10329 ("Tau")
10330 ("Upsilon")
10331 ("Phi")
10332 ("Chi")
10333 ("Psi")
10334 ("Omega")
10335 ("alpha")
10336 ("beta")
10337 ("gamma")
10338 ("delta")
10339 ("epsilon")
10340 ("varepsilon"."&epsilon;")
10341 ("zeta")
10342 ("eta")
10343 ("theta")
10344 ("iota")
10345 ("kappa")
10346 ("lambda")
10347 ("mu")
10348 ("nu")
10349 ("xi")
10350 ("omicron")
10351 ("pi")
10352 ("rho")
10353 ("sigmaf") ("varsigma"."&sigmaf;")
10354 ("sigma")
10355 ("tau")
10356 ("upsilon")
10357 ("phi")
10358 ("chi")
10359 ("psi")
10360 ("omega")
10361 ("thetasym") ("vartheta"."&thetasym;")
10362 ("upsih")
10363 ("piv")
10364 ("bull") ("bullet"."&bull;")
10365 ("hellip") ("dots"."&hellip;")
10366 ("prime")
10367 ("Prime")
10368 ("oline")
10369 ("frasl")
10370 ("weierp")
10371 ("image")
10372 ("real")
10373 ("trade")
10374 ("alefsym")
10375 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
10376 ("uarr") ("uparrow"."&uarr;")
10377 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
10378 ("darr")("downarrow"."&darr;")
10379 ("harr") ("leftrightarrow"."&harr;")
10380 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
10381 ("lArr") ("Leftarrow"."&lArr;")
10382 ("uArr") ("Uparrow"."&uArr;")
10383 ("rArr") ("Rightarrow"."&rArr;")
10384 ("dArr") ("Downarrow"."&dArr;")
10385 ("hArr") ("Leftrightarrow"."&hArr;")
10386 ("forall")
10387 ("part") ("partial"."&part;")
10388 ("exist") ("exists"."&exist;")
10389 ("empty") ("emptyset"."&empty;")
10390 ("nabla")
10391 ("isin") ("in"."&isin;")
10392 ("notin")
10393 ("ni")
10394 ("prod")
10395 ("sum")
10396 ("minus")
10397 ("lowast") ("ast"."&lowast;")
10398 ("radic")
10399 ("prop") ("proptp"."&prop;")
10400 ("infin") ("infty"."&infin;")
10401 ("ang") ("angle"."&ang;")
10402 ("and") ("vee"."&and;")
10403 ("or") ("wedge"."&or;")
10404 ("cap")
10405 ("cup")
10406 ("int")
10407 ("there4")
10408 ("sim")
10409 ("cong") ("simeq"."&cong;")
10410 ("asymp")("approx"."&asymp;")
10411 ("ne") ("neq"."&ne;")
10412 ("equiv")
10413 ("le")
10414 ("ge")
10415 ("sub") ("subset"."&sub;")
10416 ("sup") ("supset"."&sup;")
10417 ("nsub")
10418 ("sube")
10419 ("supe")
10420 ("oplus")
10421 ("otimes")
10422 ("perp")
10423 ("sdot") ("cdot"."&sdot;")
10424 ("lceil")
10425 ("rceil")
10426 ("lfloor")
10427 ("rfloor")
10428 ("lang")
10429 ("rang")
10430 ("loz") ("Diamond"."&loz;")
10431 ("spades") ("spadesuit"."&spades;")
10432 ("clubs") ("clubsuit"."&clubs;")
10433 ("hearts") ("diamondsuit"."&hearts;")
10434 ("diams") ("diamondsuit"."&diams;")
10435 ("quot")
10436 ("amp")
10437 ("lt")
10438 ("gt")
10439 ("OElig")
10440 ("oelig")
10441 ("Scaron")
10442 ("scaron")
10443 ("Yuml")
10444 ("circ")
10445 ("tilde")
10446 ("ensp")
10447 ("emsp")
10448 ("thinsp")
10449 ("zwnj")
10450 ("zwj")
10451 ("lrm")
10452 ("rlm")
10453 ("ndash")
10454 ("mdash")
10455 ("lsquo")
10456 ("rsquo")
10457 ("sbquo")
10458 ("ldquo")
10459 ("rdquo")
10460 ("bdquo")
10461 ("dagger")
10462 ("Dagger")
10463 ("permil")
10464 ("lsaquo")
10465 ("rsaquo")
10466 ("euro")
10467
10468 ("arccos"."arccos")
10469 ("arcsin"."arcsin")
10470 ("arctan"."arctan")
10471 ("arg"."arg")
10472 ("cos"."cos")
10473 ("cosh"."cosh")
10474 ("cot"."cot")
10475 ("coth"."coth")
10476 ("csc"."csc")
10477 ("deg"."deg")
10478 ("det"."det")
10479 ("dim"."dim")
10480 ("exp"."exp")
10481 ("gcd"."gcd")
10482 ("hom"."hom")
10483 ("inf"."inf")
10484 ("ker"."ker")
10485 ("lg"."lg")
10486 ("lim"."lim")
10487 ("liminf"."liminf")
10488 ("limsup"."limsup")
10489 ("ln"."ln")
10490 ("log"."log")
10491 ("max"."max")
10492 ("min"."min")
10493 ("Pr"."Pr")
10494 ("sec"."sec")
10495 ("sin"."sin")
10496 ("sinh"."sinh")
10497 ("sup"."sup")
10498 ("tan"."tan")
10499 ("tanh"."tanh")
10500 )
10501 "Entities for TeX->HTML translation.
10502 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
10503 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
10504 In that case, \"\\ent\" will be translated to \"&other;\".
10505 The list contains HTML entities for Latin-1, Greek and other symbols.
10506 It is supplemented by a number of commonly used TeX macros with appropriate
10507 translations. There is currently no way for users to extend this.")
10508
10509 (defun org-cleaned-string-for-export (string)
10510 "Cleanup a buffer substring so that links can be created safely."
10511 (interactive)
10512 (let* ((cb (current-buffer))
10513 (re-radio (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)"))
10514 rtn)
10515 (save-excursion
10516 (set-buffer (get-buffer-create " org-mode-tmp"))
10517 (erase-buffer)
10518 (insert string)
10519 (org-mode)
10520 ;; Find targets in comments and move them out of comments,
10521 ;; but mark them as targets that should be invisible
10522 (goto-char (point-min))
10523 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
10524 (replace-match "\\1(INVISIBLE)"))
10525 ;; Find matches for radio targets and turn them into links
10526 (goto-char (point-min))
10527 (while (re-search-forward re-radio nil t)
10528 (replace-match "\\1[[\\2]]"))
10529 ;; Find all links that contain a newline and put them into a single line
10530 (goto-char (point-min))
10531 (while (re-search-forward "\\(\\[\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\]\\)" nil t)
10532 (replace-match "\\1 \\2")
10533 (goto-char (match-beginning 0)))
10534 ;; Remove comments
10535 (goto-char (point-min))
10536 (while (re-search-forward "^#.*\n?" nil t)
10537 (replace-match ""))
10538 (setq rtn (buffer-string)))
10539 (kill-buffer " org-mode-tmp")
10540 rtn))
10541
10542 (defun org-solidify-link-text (s &optional alist)
10543 "Take link text and make a safe target out of it."
10544 (save-match-data
10545 (let* ((rtn
10546 (mapconcat
10547 'identity
10548 (org-split-string s "[ \t\r\n]+") "--"))
10549 (a (assoc rtn alist)))
10550 (or (cdr a) rtn))))
10551
10552 (defun org-convert-to-odd-levels ()
10553 "Convert an org-mode file with all levels allowed to one with odd levels.
10554 This will leave level 1 alone, convert level 2 to level 3, level 3 to
10555 level 5 etc."
10556 (interactive)
10557 (when (yes-or-no-p "Are you sure you want to globally change levels? ")
10558 (let ((org-odd-levels-only nil) n)
10559 (save-excursion
10560 (goto-char (point-min))
10561 (while (re-search-forward "^\\*\\*+" nil t)
10562 (setq n (1- (length (match-string 0))))
10563 (while (>= (setq n (1- n)) 0)
10564 (org-demote))
10565 (end-of-line 1))))))
10566
10567 (defun org-tr-level (n)
10568 "Make N odd if required."
10569 (if org-odd-levels-only (1+ (/ n 2)) n))
10570
10571 (defvar org-last-level nil) ; dynamically scoped variable
10572
10573 (defun org-export-as-ascii (arg)
10574 "Export the outline as a pretty ASCII file.
10575 If there is an active region, export only the region.
10576 The prefix ARG specifies how many levels of the outline should become
10577 underlined headlines. The default is 3."
10578 (interactive "P")
10579 (setq-default org-todo-line-regexp org-todo-line-regexp)
10580 (let* ((region
10581 (buffer-substring
10582 (if (org-region-active-p) (region-beginning) (point-min))
10583 (if (org-region-active-p) (region-end) (point-max))))
10584 (lines (org-export-find-first-heading-line
10585 (org-skip-comments
10586 (org-split-string
10587 (org-cleaned-string-for-export region)
10588 "[\r\n]"))))
10589 (org-startup-with-deadline-check nil)
10590 (level 0) line txt
10591 (umax nil)
10592 (case-fold-search nil)
10593 (filename (concat (file-name-sans-extension (buffer-file-name))
10594 ".txt"))
10595 (buffer (find-file-noselect filename))
10596 (levels-open (make-vector org-level-max nil))
10597 (date (format-time-string "%Y/%m/%d" (current-time)))
10598 (time (format-time-string "%X" (current-time)))
10599 (author user-full-name)
10600 (title (buffer-name))
10601 (options nil)
10602 (email user-mail-address)
10603 (language org-export-default-language)
10604 (text nil)
10605 (todo nil)
10606 (lang-words nil))
10607
10608 (setq org-last-level 1)
10609 (org-init-section-numbers)
10610
10611 (find-file-noselect filename)
10612
10613 ;; Search for the export key lines
10614 (org-parse-key-lines)
10615
10616 (setq lang-words (or (assoc language org-export-language-setup)
10617 (assoc "en" org-export-language-setup)))
10618 (if org-export-ascii-show-new-buffer
10619 (switch-to-buffer-other-window buffer)
10620 (set-buffer buffer))
10621 (erase-buffer)
10622 (fundamental-mode)
10623 (if options (org-parse-export-options options))
10624 (setq umax (if arg (prefix-numeric-value arg)
10625 org-export-headline-levels))
10626
10627 ;; File header
10628 (if title (org-insert-centered title ?=))
10629 (insert "\n")
10630 (if (or author email)
10631 (insert (concat (nth 1 lang-words) ": " (or author "")
10632 (if email (concat " <" email ">") "")
10633 "\n")))
10634 (if (and date time)
10635 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10636 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10637
10638 (insert "\n\n")
10639
10640 (if org-export-with-toc
10641 (progn
10642 (insert (nth 3 lang-words) "\n"
10643 (make-string (length (nth 3 lang-words)) ?=) "\n")
10644 (mapcar '(lambda (line)
10645 (if (string-match org-todo-line-regexp
10646 line)
10647 ;; This is a headline
10648 (progn
10649 (setq level (- (match-end 1) (match-beginning 1))
10650 level (org-tr-level level)
10651 txt (match-string 3 line)
10652 todo
10653 (or (and (match-beginning 2)
10654 (not (equal (match-string 2 line)
10655 org-done-string)))
10656 ; TODO, not DONE
10657 (and (= level umax)
10658 (org-search-todo-below
10659 line lines level))))
10660 (setq txt (org-html-expand-for-ascii txt))
10661
10662 (if org-export-with-section-numbers
10663 (setq txt (concat (org-section-number level)
10664 " " txt)))
10665 (if (<= level umax)
10666 (progn
10667 (insert
10668 (make-string (* (1- level) 4) ?\ )
10669 (format (if todo "%s (*)\n" "%s\n") txt))
10670 (setq org-last-level level))
10671 ))))
10672 lines)))
10673
10674 (org-init-section-numbers)
10675 (while (setq line (pop lines))
10676 ;; Remove the quoted HTML tags.
10677 (setq line (org-html-expand-for-ascii line))
10678 ;; Remove targets
10679 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
10680 (setq line (replace-match "" t t line)))
10681 ;; Replace internal links
10682 (while (string-match org-bracket-link-regexp line)
10683 (setq line (replace-match
10684 (if (match-end 3) "[\\3]" "[\\1]")
10685 t nil line)))
10686 (cond
10687 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10688 ;; a Headline
10689 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
10690 txt (match-string 2 line))
10691 (org-ascii-level-start level txt umax))
10692 (t (insert line "\n"))))
10693 (normal-mode)
10694 (save-buffer)
10695 (goto-char (point-min))))
10696
10697 (defun org-search-todo-below (line lines level)
10698 "Search the subtree below LINE for any TODO entries."
10699 (let ((rest (cdr (memq line lines)))
10700 (re org-todo-line-regexp)
10701 line lv todo)
10702 (catch 'exit
10703 (while (setq line (pop rest))
10704 (if (string-match re line)
10705 (progn
10706 (setq lv (- (match-end 1) (match-beginning 1))
10707 todo (and (match-beginning 2)
10708 (not (equal (match-string 2 line)
10709 org-done-string))))
10710 ; TODO, not DONE
10711 (if (<= lv level) (throw 'exit nil))
10712 (if todo (throw 'exit t))))))))
10713
10714 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10715 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10716 (defun org-html-expand-for-ascii (line)
10717 "Handle quoted HTML for ASCII export."
10718 (if org-export-html-expand
10719 (while (string-match "@<[^<>\n]*>" line)
10720 ;; We just remove the tags for now.
10721 (setq line (replace-match "" nil nil line))))
10722 line)
10723
10724 (defun org-insert-centered (s &optional underline)
10725 "Insert the string S centered and underline it with character UNDERLINE."
10726 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
10727 (insert (make-string ind ?\ ) s "\n")
10728 (if underline
10729 (insert (make-string ind ?\ )
10730 (make-string (length s) underline)
10731 "\n"))))
10732
10733 (defun org-ascii-level-start (level title umax)
10734 "Insert a new level in ASCII export."
10735 (let (char)
10736 (if (> level umax)
10737 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10738 (if (or (not (equal (char-before) ?\n))
10739 (not (equal (char-before (1- (point))) ?\n)))
10740 (insert "\n"))
10741 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10742 (if org-export-with-section-numbers
10743 (setq title (concat (org-section-number level) " " title)))
10744 (insert title "\n" (make-string (string-width title) char) "\n"))))
10745
10746 (defun org-export-copy-visible ()
10747 "Copy the visible part of the buffer to another buffer, for printing.
10748 Also removes the first line of the buffer if it specifies a mode,
10749 and all options lines."
10750 (interactive)
10751 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
10752 ".txt"))
10753 (buffer (find-file-noselect filename))
10754 (ore (concat
10755 (org-make-options-regexp
10756 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10757 "STARTUP" "ARCHIVE"
10758 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10759 (if org-noutline-p "\\(\n\\|$\\)" "")))
10760 s e)
10761 (with-current-buffer buffer
10762 (erase-buffer)
10763 (text-mode))
10764 (save-excursion
10765 (setq s (goto-char (point-min)))
10766 (while (not (= (point) (point-max)))
10767 (goto-char (org-find-invisible))
10768 (append-to-buffer buffer s (point))
10769 (setq s (goto-char (org-find-visible)))))
10770 (switch-to-buffer-other-window buffer)
10771 (newline)
10772 (goto-char (point-min))
10773 (if (looking-at ".*-\\*- mode:.*\n")
10774 (replace-match ""))
10775 (while (re-search-forward ore nil t)
10776 (replace-match ""))
10777 (goto-char (point-min))))
10778
10779 (defun org-find-visible ()
10780 (if (featurep 'noutline)
10781 (let ((s (point)))
10782 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10783 (get-char-property s 'invisible)))
10784 s)
10785 (skip-chars-forward "^\n")
10786 (point)))
10787 (defun org-find-invisible ()
10788 (if (featurep 'noutline)
10789 (let ((s (point)))
10790 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10791 (not (get-char-property s 'invisible))))
10792 s)
10793 (skip-chars-forward "^\r")
10794 (point)))
10795
10796 ;; HTML
10797
10798 (defun org-get-current-options ()
10799 "Return a string with current options as keyword options.
10800 Does include HTML export options as well as TODO and CATEGORY stuff."
10801 (format
10802 "#+TITLE: %s
10803 #+AUTHOR: %s
10804 #+EMAIL: %s
10805 #+LANGUAGE: %s
10806 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10807 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10808 #+CATEGORY: %s
10809 #+SEQ_TODO: %s
10810 #+TYP_TODO: %s
10811 #+STARTUP: %s %s
10812 #+ARCHIVE: %s
10813 "
10814 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10815 org-export-headline-levels
10816 org-export-with-section-numbers
10817 org-export-with-toc
10818 org-export-preserve-breaks
10819 org-export-html-expand
10820 org-export-with-fixed-width
10821 org-export-with-tables
10822 org-export-with-sub-superscripts
10823 org-export-with-emphasize
10824 org-export-with-TeX-macros
10825 (file-name-nondirectory (buffer-file-name))
10826 (if (equal org-todo-interpretation 'sequence)
10827 (mapconcat 'identity org-todo-keywords " ")
10828 "TODO FEEDBACK VERIFY DONE")
10829 (if (equal org-todo-interpretation 'type)
10830 (mapconcat 'identity org-todo-keywords " ")
10831 "Me Jason Marie DONE")
10832 (cdr (assoc org-startup-folded
10833 '((nil . "nofold")(t . "fold")(content . "content"))))
10834 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10835 org-archive-location
10836 ))
10837
10838 (defun org-insert-export-options-template ()
10839 "Insert into the buffer a template with information for exporting."
10840 (interactive)
10841 (if (not (bolp)) (newline))
10842 (let ((s (org-get-current-options)))
10843 (and (string-match "#\\+CATEGORY" s)
10844 (setq s (substring s 0 (match-beginning 0))))
10845 (insert s)))
10846
10847 (defun org-toggle-fixed-width-section (arg)
10848 "Toggle the fixed-width export.
10849 If there is no active region, the QUOTE keyword at the current headline is
10850 inserted or removed. When present, it causes the text between this headline
10851 and the next to be exported as fixed-width text, and unmodified.
10852 If there is an active region, this command adds or removes a colon as the
10853 first character of this line. If the first character of a line is a colon,
10854 this line is also exported in fixed-width font."
10855 (interactive "P")
10856 (let* ((cc 0)
10857 (regionp (org-region-active-p))
10858 (beg (if regionp (region-beginning) (point)))
10859 (end (if regionp (region-end)))
10860 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10861 (re "[ \t]*\\(:\\)")
10862 off)
10863 (if regionp
10864 (save-excursion
10865 (goto-char beg)
10866 (setq cc (current-column))
10867 (beginning-of-line 1)
10868 (setq off (looking-at re))
10869 (while (> nlines 0)
10870 (setq nlines (1- nlines))
10871 (beginning-of-line 1)
10872 (cond
10873 (arg
10874 (move-to-column cc t)
10875 (insert ":\n")
10876 (forward-line -1))
10877 ((and off (looking-at re))
10878 (replace-match "" t t nil 1))
10879 ((not off) (move-to-column cc t) (insert ":")))
10880 (forward-line 1)))
10881 (save-excursion
10882 (org-back-to-heading)
10883 (if (looking-at (concat outline-regexp
10884 "\\( +\\<" org-quote-string "\\>\\)"))
10885 (replace-match "" t t nil 1)
10886 (if (looking-at outline-regexp)
10887 (progn
10888 (goto-char (match-end 0))
10889 (insert " " org-quote-string))))))))
10890
10891 (defun org-export-as-html-and-open (arg)
10892 "Export the outline as HTML and immediately open it with a browser.
10893 If there is an active region, export only the region.
10894 The prefix ARG specifies how many levels of the outline should become
10895 headlines. The default is 3. Lower levels will become bulleted lists."
10896 (interactive "P")
10897 (org-export-as-html arg 'hidden)
10898 (org-open-file (buffer-file-name)))
10899
10900 (defun org-export-as-html-batch ()
10901 "Call `org-export-as-html', may be used in batch processing as
10902 emacs --batch
10903 --load=$HOME/lib/emacs/org.el
10904 --eval \"(setq org-export-headline-levels 2)\"
10905 --visit=MyFile --funcall org-export-as-html-batch"
10906 (org-export-as-html org-export-headline-levels 'hidden))
10907
10908 (defun org-export-as-html (arg &optional hidden)
10909 "Export the outline as a pretty HTML file.
10910 If there is an active region, export only the region.
10911 The prefix ARG specifies how many levels of the outline should become
10912 headlines. The default is 3. Lower levels will become bulleted lists."
10913 (interactive "P")
10914 (setq-default org-todo-line-regexp org-todo-line-regexp)
10915 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
10916 (setq-default org-done-string org-done-string)
10917 (let* ((style org-export-html-style)
10918 (region-p (org-region-active-p))
10919 (region
10920 (buffer-substring
10921 (if region-p (region-beginning) (point-min))
10922 (if region-p (region-end) (point-max))))
10923 (all_lines
10924 (org-skip-comments (org-split-string
10925 (org-cleaned-string-for-export region)
10926 "[\r\n]")))
10927 (lines (org-export-find-first-heading-line all_lines))
10928 (level 0) (line "") (origline "") txt todo
10929 (umax nil)
10930 (filename (concat (file-name-sans-extension (buffer-file-name))
10931 ".html"))
10932 (buffer (find-file-noselect filename))
10933 (levels-open (make-vector org-level-max nil))
10934 (date (format-time-string "%Y/%m/%d" (current-time)))
10935 (time (format-time-string "%X" (current-time)))
10936 (author user-full-name)
10937 (title (buffer-name))
10938 (options nil)
10939 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
10940 (inquote nil)
10941 (infixed nil)
10942 (in-local-list nil)
10943 (local-list-num nil)
10944 (local-list-indent nil)
10945 (llt org-plain-list-ordered-item-terminator)
10946 (email user-mail-address)
10947 (language org-export-default-language)
10948 (text nil)
10949 (lang-words nil)
10950 (target-alist nil) tg
10951 (head-count 0) cnt
10952 (start 0)
10953 ;; FIXME: The following returns always nil under XEmacs
10954 (coding-system (and (fboundp 'coding-system-get)
10955 (boundp 'buffer-file-coding-system)
10956 buffer-file-coding-system))
10957 (coding-system-for-write (or coding-system coding-system-for-write))
10958 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
10959 (charset (and coding-system
10960 (coding-system-get coding-system 'mime-charset)))
10961 table-open type
10962 table-buffer table-orig-buffer
10963 ind start-is-num starter
10964 )
10965 (message "Exporting...")
10966
10967 (setq org-last-level 1)
10968 (org-init-section-numbers)
10969
10970 ;; Search for the export key lines
10971 (org-parse-key-lines)
10972 (setq lang-words (or (assoc language org-export-language-setup)
10973 (assoc "en" org-export-language-setup)))
10974
10975 ;; Switch to the output buffer
10976 (if (or hidden (not org-export-html-show-new-buffer))
10977 (set-buffer buffer)
10978 (switch-to-buffer-other-window buffer))
10979 (erase-buffer)
10980 (fundamental-mode)
10981 (let ((case-fold-search nil))
10982 (if options (org-parse-export-options options))
10983 (setq umax (if arg (prefix-numeric-value arg)
10984 org-export-headline-levels))
10985
10986 ;; File header
10987 (insert (format
10988 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
10989 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
10990 <html lang=\"%s\"><head>
10991 <title>%s</title>
10992 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
10993 <meta name=generator content=\"Org-mode\">
10994 <meta name=generated content=\"%s %s\">
10995 <meta name=author content=\"%s\">
10996 %s
10997 </head><body>
10998 "
10999 language (org-html-expand title) (or charset "iso-8859-1")
11000 date time author style))
11001 (if title (insert (concat "<H1 class=\"title\">"
11002 (org-html-expand title) "</H1>\n")))
11003 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11004 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11005 email "&gt;</a>\n")))
11006 (if (or author email) (insert "<br>\n"))
11007 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11008 date " " time "<br>\n")))
11009 (if text (insert (concat "<p>\n" (org-html-expand text))))
11010 (if org-export-with-toc
11011 (progn
11012 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11013 (insert "<ul>\n")
11014 (setq lines
11015 (mapcar '(lambda (line)
11016 (if (string-match org-todo-line-regexp line)
11017 ;; This is a headline
11018 (progn
11019 (setq level (- (match-end 1) (match-beginning 1))
11020 level (org-tr-level level)
11021 txt (save-match-data
11022 (org-html-expand
11023 (match-string 3 line)))
11024 todo
11025 (or (and (match-beginning 2)
11026 (not (equal (match-string 2 line)
11027 org-done-string)))
11028 ; TODO, not DONE
11029 (and (= level umax)
11030 (org-search-todo-below
11031 line lines level))))
11032 (if org-export-with-section-numbers
11033 (setq txt (concat (org-section-number level)
11034 " " txt)))
11035 (if (<= level umax)
11036 (progn
11037 (setq head-count (+ head-count 1))
11038 (if (> level org-last-level)
11039 (progn
11040 (setq cnt (- level org-last-level))
11041 (while (>= (setq cnt (1- cnt)) 0)
11042 (insert "<ul>"))
11043 (insert "\n")))
11044 (if (< level org-last-level)
11045 (progn
11046 (setq cnt (- org-last-level level))
11047 (while (>= (setq cnt (1- cnt)) 0)
11048 (insert "</ul>"))
11049 (insert "\n")))
11050 ;; Check for targets
11051 (while (string-match org-target-regexp line)
11052 (setq tg (match-string 1 line)
11053 line (replace-match
11054 (concat "@<span class=\"target\">" tg "@</span> ")
11055 t t line))
11056 (push (cons (org-solidify-link-text tg)
11057 (format "sec-%d" head-count))
11058 target-alist))
11059 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11060 (setq txt (replace-match "" t t txt)))
11061 (insert
11062 (format
11063 (if todo
11064 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11065 "<li><a href=\"#sec-%d\">%s</a>\n")
11066 head-count txt))
11067
11068 (setq org-last-level level))
11069 )))
11070 line)
11071 lines))
11072 (while (> org-last-level 0)
11073 (setq org-last-level (1- org-last-level))
11074 (insert "</ul>\n"))
11075 ))
11076 (setq head-count 0)
11077 (org-init-section-numbers)
11078
11079 (while (setq line (pop lines) origline line)
11080 (catch 'nextline
11081
11082 ;; end of quote section?
11083 (when (and inquote (string-match "^\\*+" line))
11084 (insert "</pre>\n")
11085 (setq inquote nil))
11086 ;; inside a quote section?
11087 (when inquote
11088 (insert (org-html-protect line) "\n")
11089 (throw 'nextline nil))
11090
11091 ;; verbatim lines
11092 (when (and org-export-with-fixed-width
11093 (string-match "^[ \t]*:\\(.*\\)" line))
11094 (when (not infixed)
11095 (setq infixed t)
11096 (insert "<pre>\n"))
11097 (insert (org-html-protect (match-string 1 line)) "\n")
11098 (when (and lines
11099 (not (string-match "^[ \t]*\\(:.*\\)"
11100 (car lines))))
11101 (setq infixed nil)
11102 (insert "</pre>\n"))
11103 (throw 'nextline nil))
11104
11105
11106 ;; make targets to anchors
11107 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11108 (cond
11109 ((match-end 2)
11110 (setq line (replace-match
11111 (concat "@<a name=\""
11112 (org-solidify-link-text (match-string 1 line))
11113 "\">\\nbsp@</a>")
11114 t t line)))
11115 ((and org-export-with-toc (equal (string-to-char line) ?*))
11116 (setq line (replace-match
11117 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11118 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11119 t t line)))
11120 (t
11121 (setq line (replace-match
11122 (concat "@<a name=\""
11123 (org-solidify-link-text (match-string 1 line))
11124 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11125 t t line)))))
11126 ;; Replace internal links
11127 (while (string-match org-bracket-link-regexp line)
11128 (setq line (replace-match
11129 (concat
11130 "@<a href=\"#"
11131 (org-solidify-link-text (match-string 1 line) target-alist)
11132 "\">"
11133 (match-string (if (match-end 3) 3 1) line)
11134 "@</a>")
11135 t t line)))
11136
11137 ;; Protect the external links
11138 (setq start 0)
11139 (while (string-match org-link-maybe-angles-regexp line start)
11140 (setq start (match-end 0))
11141 (setq line (replace-match
11142 (concat "\000" (match-string 1 line) "\000")
11143 t t line)))
11144
11145 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11146 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11147 (setq line (org-html-expand line))
11148
11149 ;; Format the links
11150 (setq start 0)
11151 (while (string-match org-protected-link-regexp line start)
11152 (setq start (- (match-end 0) 2))
11153 (setq type (match-string 1 line))
11154 (cond
11155 ((member type '("http" "https" "ftp" "mailto" "news"))
11156 ;; standard URL
11157 (setq line (replace-match
11158 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
11159 "<a href=\"\\1:\\2\">\\1:\\2</a>"
11160 nil nil line)))
11161 ((string= type "file")
11162 ;; FILE link
11163 (let* ((filename (match-string 2 line))
11164 (abs-p (file-name-absolute-p filename))
11165 (thefile (if abs-p (expand-file-name filename) filename))
11166 (thefile (save-match-data
11167 (if (string-match ":[0-9]+$" thefile)
11168 (replace-match "" t t thefile)
11169 thefile)))
11170 (file-is-image-p
11171 (save-match-data
11172 (string-match (org-image-file-name-regexp) thefile))))
11173 (setq line (replace-match
11174 (if (and org-export-html-inline-images
11175 file-is-image-p)
11176 (concat "<img src=\"" thefile "\"/>")
11177 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
11178 nil nil line))))
11179
11180 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11181 (setq line (replace-match
11182 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
11183
11184 ;; TODO items
11185 (if (and (string-match org-todo-line-regexp line)
11186 (match-beginning 2))
11187 (if (equal (match-string 2 line) org-done-string)
11188 (setq line (replace-match
11189 "<span class=\"done\">\\2</span>"
11190 nil nil line 2))
11191 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11192 nil nil line 2))))
11193
11194 ;; DEADLINES
11195 (if (string-match org-deadline-line-regexp line)
11196 (progn
11197 (if (save-match-data
11198 (string-match "<a href"
11199 (substring line 0 (match-beginning 0))))
11200 nil ; Don't do the replacement - it is inside a link
11201 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11202 nil nil line 1)))))
11203 (cond
11204 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11205 ;; This is a headline
11206 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11207 txt (match-string 2 line))
11208 (if (<= level umax) (setq head-count (+ head-count 1)))
11209 (when in-local-list
11210 ;; Close any local lists before inserting a new header line
11211 (while local-list-num
11212 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11213 (pop local-list-num))
11214 (setq local-list-indent nil
11215 in-local-list nil))
11216 (org-html-level-start level txt umax
11217 (and org-export-with-toc (<= level umax))
11218 head-count)
11219 ;; QUOTES
11220 (when (string-match quote-re line)
11221 (insert "<pre>")
11222 (setq inquote t)))
11223
11224 ((and org-export-with-tables
11225 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11226 (if (not table-open)
11227 ;; New table starts
11228 (setq table-open t table-buffer nil table-orig-buffer nil))
11229 ;; Accumulate lines
11230 (setq table-buffer (cons line table-buffer)
11231 table-orig-buffer (cons origline table-orig-buffer))
11232 (when (or (not lines)
11233 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11234 (car lines))))
11235 (setq table-open nil
11236 table-buffer (nreverse table-buffer)
11237 table-orig-buffer (nreverse table-orig-buffer))
11238 (insert (org-format-table-html table-buffer table-orig-buffer))))
11239 (t
11240 ;; Normal lines
11241 (when (and (> org-export-plain-list-max-depth 0)
11242 (string-match
11243 (cond
11244 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11245 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11246 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11247 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11248 line))
11249 (setq ind (org-get-string-indentation line)
11250 start-is-num (match-beginning 4)
11251 starter (if (match-beginning 2) (match-string 2 line))
11252 line (substring line (match-beginning 5)))
11253 (unless (string-match "[^ \t]" line)
11254 ;; empty line. Pretend indentation is large.
11255 (setq ind (1+ (or (car local-list-indent) 1))))
11256 (while (and in-local-list
11257 (or (and (= ind (car local-list-indent))
11258 (not starter))
11259 (< ind (car local-list-indent))))
11260 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11261 (pop local-list-num) (pop local-list-indent)
11262 (setq in-local-list local-list-indent))
11263 (cond
11264 ((and starter
11265 (or (not in-local-list)
11266 (> ind (car local-list-indent)))
11267 (< (length local-list-indent)
11268 org-export-plain-list-max-depth))
11269 ;; Start new (level of ) list
11270 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11271 (push start-is-num local-list-num)
11272 (push ind local-list-indent)
11273 (setq in-local-list t))
11274 (starter
11275 ;; continue current list
11276 (insert "<li>\n"))))
11277 ;; Empty lines start a new paragraph. If hand-formatted lists
11278 ;; are not fully interpreted, lines starting with "-", "+", "*"
11279 ;; also start a new paragraph.
11280 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11281 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11282 ))
11283 (if org-export-html-with-timestamp
11284 (insert org-export-html-html-helper-timestamp))
11285 (insert "</body>\n</html>\n")
11286 (normal-mode)
11287 (save-buffer)
11288 (goto-char (point-min)))))
11289
11290 (defun org-format-table-html (lines olines)
11291 "Find out which HTML converter to use and return the HTML code."
11292 (if (string-match "^[ \t]*|" (car lines))
11293 ;; A normal org table
11294 (org-format-org-table-html lines)
11295 ;; Table made by table.el - test for spanning
11296 (let* ((hlines (delq nil (mapcar
11297 (lambda (x)
11298 (if (string-match "^[ \t]*\\+-" x) x
11299 nil))
11300 lines)))
11301 (first (car hlines))
11302 (ll (and (string-match "\\S-+" first)
11303 (match-string 0 first)))
11304 (re (concat "^[ \t]*" (regexp-quote ll)))
11305 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
11306 hlines))))
11307 (if (and (not spanning)
11308 (not org-export-prefer-native-exporter-for-tables))
11309 ;; We can use my own converter with HTML conversions
11310 (org-format-table-table-html lines)
11311 ;; Need to use the code generator in table.el, with the original text.
11312 (org-format-table-table-html-using-table-generate-source olines)))))
11313
11314 (defun org-format-org-table-html (lines)
11315 "Format a table into HTML."
11316 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11317 (setq lines (nreverse lines))
11318 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11319 (setq lines (nreverse lines))
11320 (when org-export-table-remove-special-lines
11321 ;; Check if the table has a marking column. If yes remove the
11322 ;; column and the special lines
11323 (let* ((special
11324 (not
11325 (memq nil
11326 (mapcar
11327 (lambda (x)
11328 (or (string-match "^[ \t]*|-" x)
11329 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
11330 lines)))))
11331 (if special
11332 (setq lines
11333 (delq nil
11334 (mapcar
11335 (lambda (x)
11336 (if (string-match "^[ \t]*| *[!_^] *|" x)
11337 nil ; ignore this line
11338 (and (or (string-match "^[ \t]*|-+\\+" x)
11339 (string-match "^[ \t]*|[^|]*|" x))
11340 (replace-match "|" t t x))))
11341 lines))))))
11342
11343 (let ((head (and org-export-highlight-first-table-line
11344 (delq nil (mapcar
11345 (lambda (x) (string-match "^[ \t]*|-" x))
11346 (cdr lines)))))
11347 line fields html)
11348 (setq html (concat org-export-html-table-tag "\n"))
11349 (while (setq line (pop lines))
11350 (catch 'next-line
11351 (if (string-match "^[ \t]*|-" line)
11352 (progn
11353 (setq head nil) ;; head ends here, first time around
11354 ;; ignore this line
11355 (throw 'next-line t)))
11356 ;; Break the line into fields
11357 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11358 (setq html (concat
11359 html
11360 "<tr>"
11361 (mapconcat (lambda (x)
11362 (if head
11363 (concat "<th>" x "</th>")
11364 (concat "<td>" x "</td>")))
11365 fields "")
11366 "</tr>\n"))))
11367 (setq html (concat html "</table>\n"))
11368 html))
11369
11370 (defun org-fake-empty-table-line (line)
11371 "Replace everything except \"|\" with spaces."
11372 (let ((i (length line))
11373 (newstr (copy-sequence line)))
11374 (while (> i 0)
11375 (setq i (1- i))
11376 (if (not (eq (aref newstr i) ?|))
11377 (aset newstr i ?\ )))
11378 newstr))
11379
11380 (defun org-format-table-table-html (lines)
11381 "Format a table generated by table.el into HTML.
11382 This conversion does *not* use `table-generate-source' from table.el.
11383 This has the advantage that Org-mode's HTML conversions can be used.
11384 But it has the disadvantage, that no cell- or row-spanning is allowed."
11385 (let (line field-buffer
11386 (head org-export-highlight-first-table-line)
11387 fields html empty)
11388 (setq html (concat org-export-html-table-tag "\n"))
11389 (while (setq line (pop lines))
11390 (setq empty "&nbsp")
11391 (catch 'next-line
11392 (if (string-match "^[ \t]*\\+-" line)
11393 (progn
11394 (if field-buffer
11395 (progn
11396 (setq html (concat
11397 html
11398 "<tr>"
11399 (mapconcat
11400 (lambda (x)
11401 (if (equal x "") (setq x empty))
11402 (if head
11403 (concat "<th>" x "</th>\n")
11404 (concat "<td>" x "</td>\n")))
11405 field-buffer "\n")
11406 "</tr>\n"))
11407 (setq head nil)
11408 (setq field-buffer nil)))
11409 ;; Ignore this line
11410 (throw 'next-line t)))
11411 ;; Break the line into fields and store the fields
11412 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11413 (if field-buffer
11414 (setq field-buffer (mapcar
11415 (lambda (x)
11416 (concat x "<br>" (pop fields)))
11417 field-buffer))
11418 (setq field-buffer fields))))
11419 (setq html (concat html "</table>\n"))
11420 html))
11421
11422 (defun org-format-table-table-html-using-table-generate-source (lines)
11423 "Format a table into html, using `table-generate-source' from table.el.
11424 This has the advantage that cell- or row-spanning is allowed.
11425 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
11426 (require 'table)
11427 (with-current-buffer (get-buffer-create " org-tmp1 ")
11428 (erase-buffer)
11429 (insert (mapconcat 'identity lines "\n"))
11430 (goto-char (point-min))
11431 (if (not (re-search-forward "|[^+]" nil t))
11432 (error "Error processing table"))
11433 (table-recognize-table)
11434 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
11435 (table-generate-source 'html " org-tmp2 ")
11436 (set-buffer " org-tmp2 ")
11437 (buffer-substring (point-min) (point-max))))
11438
11439 (defun org-html-protect (s)
11440 ;; convert & to &amp;, < to &lt; and > to &gt;
11441 (let ((start 0))
11442 (while (string-match "&" s start)
11443 (setq s (replace-match "&amp;" t t s)
11444 start (1+ (match-beginning 0))))
11445 (while (string-match "<" s)
11446 (setq s (replace-match "&lt;" t t s)))
11447 (while (string-match ">" s)
11448 (setq s (replace-match "&gt;" t t s))))
11449 s)
11450
11451 (defun org-html-expand (string)
11452 "Prepare STRING for HTML export. Applies all active conversions."
11453 ;; First check if there is a link in the line - if yes, apply conversions
11454 ;; only before the start of the link.
11455 ;; FIXME: This is no longer correct, because links now have an end.
11456 (let* ((m (string-match org-link-regexp string))
11457 (s (if m (substring string 0 m) string))
11458 (r (if m (substring string m) "")))
11459 ;; convert & to &amp;, < to &lt; and > to &gt;
11460 (setq s (org-html-protect s))
11461 (if org-export-html-expand
11462 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
11463 (setq s (replace-match "<\\1>" nil nil s))))
11464 (if org-export-with-emphasize
11465 (setq s (org-export-html-convert-emphasize s)))
11466 (if org-export-with-sub-superscripts
11467 (setq s (org-export-html-convert-sub-super s)))
11468 (if org-export-with-TeX-macros
11469 (let ((start 0) wd ass)
11470 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
11471 (setq wd (match-string 1 s))
11472 (if (setq ass (assoc wd org-html-entities))
11473 (setq s (replace-match (or (cdr ass)
11474 (concat "&" (car ass) ";"))
11475 t t s))
11476 (setq start (+ start (length wd)))))))
11477 (concat s r)))
11478
11479 (defun org-create-multibrace-regexp (left right n)
11480 "Create a regular expression which will match a balanced sexp.
11481 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
11482 as single character strings.
11483 The regexp returned will match the entire expression including the
11484 delimiters. It will also define a single group which contains the
11485 match except for the outermost delimiters. The maximum depth of
11486 stacked delimiters is N. Escaping delimiters is not possible."
11487 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
11488 (or "\\|")
11489 (re nothing)
11490 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
11491 (while (> n 1)
11492 (setq n (1- n)
11493 re (concat re or next)
11494 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
11495 (concat left "\\(" re "\\)" right)))
11496
11497 (defvar org-match-substring-regexp
11498 (concat
11499 "\\([^\\]\\)\\([_^]\\)\\("
11500 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
11501 "\\|"
11502 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
11503 "\\|"
11504 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
11505 "The regular expression matching a sub- or superscript.")
11506
11507 (defun org-export-html-convert-sub-super (string)
11508 "Convert sub- and superscripts in STRING to HTML."
11509 (let (key c)
11510 (while (string-match org-match-substring-regexp string)
11511 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
11512 (setq c (or (match-string 8 string)
11513 (match-string 6 string)
11514 (match-string 5 string)))
11515 (setq string (replace-match
11516 (concat (match-string 1 string)
11517 "<" key ">" c "</" key ">")
11518 t t string)))
11519 (while (string-match "\\\\\\([_^]\\)" string)
11520 (setq string (replace-match (match-string 1 string) t t string))))
11521 string)
11522
11523 (defun org-export-html-convert-emphasize (string)
11524 (while (string-match
11525 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
11526 string)
11527 (setq string (replace-match
11528 (concat "<b>" (match-string 3 string) "</b>")
11529 t t string 2)))
11530 (while (string-match
11531 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
11532 string)
11533 (setq string (replace-match
11534 (concat "<i>" (match-string 3 string) "</i>")
11535 t t string 2)))
11536 (while (string-match
11537 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
11538 string)
11539 (setq string (replace-match
11540 (concat "<u>" (match-string 3 string) "</u>")
11541 t t string 2)))
11542 string)
11543
11544 (defun org-parse-key-lines ()
11545 "Find the special key lines with the information for exporters."
11546 (save-excursion
11547 (goto-char 0)
11548 (let ((re (org-make-options-regexp
11549 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
11550 key)
11551 (while (re-search-forward re nil t)
11552 (setq key (match-string 1))
11553 (cond ((string-equal key "TITLE")
11554 (setq title (match-string 2)))
11555 ((string-equal key "AUTHOR")
11556 (setq author (match-string 2)))
11557 ((string-equal key "EMAIL")
11558 (setq email (match-string 2)))
11559 ((string-equal key "LANGUAGE")
11560 (setq language (match-string 2)))
11561 ((string-equal key "TEXT")
11562 (setq text (concat text "\n" (match-string 2))))
11563 ((string-equal key "OPTIONS")
11564 (setq options (match-string 2))))))))
11565
11566 (defun org-parse-export-options (s)
11567 "Parse the export options line."
11568 (let ((op '(("H" . org-export-headline-levels)
11569 ("num" . org-export-with-section-numbers)
11570 ("toc" . org-export-with-toc)
11571 ("\\n" . org-export-preserve-breaks)
11572 ("@" . org-export-html-expand)
11573 (":" . org-export-with-fixed-width)
11574 ("|" . org-export-with-tables)
11575 ("^" . org-export-with-sub-superscripts)
11576 ("*" . org-export-with-emphasize)
11577 ("TeX" . org-export-with-TeX-macros)))
11578 o)
11579 (while (setq o (pop op))
11580 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
11581 s)
11582 (set (make-local-variable (cdr o))
11583 (car (read-from-string (match-string 1 s))))))))
11584
11585 (defun org-html-level-start (level title umax with-toc head-count)
11586 "Insert a new level in HTML export."
11587 (let ((l (1+ (max level umax))))
11588 (while (<= l org-level-max)
11589 (if (aref levels-open (1- l))
11590 (progn
11591 (org-html-level-close l)
11592 (aset levels-open (1- l) nil)))
11593 (setq l (1+ l)))
11594 (if (> level umax)
11595 (progn
11596 (if (aref levels-open (1- level))
11597 (insert "<li>" title "<p>\n")
11598 (aset levels-open (1- level) t)
11599 (insert "<ul><li>" title "<p>\n")))
11600 (if org-export-with-section-numbers
11601 (setq title (concat (org-section-number level) " " title)))
11602 (setq level (+ level 1))
11603 (if with-toc
11604 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
11605 level head-count title level))
11606 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
11607
11608 (defun org-html-level-close (&rest args)
11609 "Terminate one level in HTML export."
11610 (insert "</ul>"))
11611
11612 ;; Variable holding the vector with section numbers
11613 (defvar org-section-numbers (make-vector org-level-max 0))
11614
11615 (defun org-init-section-numbers ()
11616 "Initialize the vector for the section numbers."
11617 (let* ((level -1)
11618 (numbers (nreverse (org-split-string "" "\\.")))
11619 (depth (1- (length org-section-numbers)))
11620 (i depth) number-string)
11621 (while (>= i 0)
11622 (if (> i level)
11623 (aset org-section-numbers i 0)
11624 (setq number-string (or (car numbers) "0"))
11625 (if (string-match "\\`[A-Z]\\'" number-string)
11626 (aset org-section-numbers i
11627 (- (string-to-char number-string) ?A -1))
11628 (aset org-section-numbers i (string-to-number number-string)))
11629 (pop numbers))
11630 (setq i (1- i)))))
11631
11632 (defun org-section-number (&optional level)
11633 "Return a string with the current section number.
11634 When LEVEL is non-nil, increase section numbers on that level."
11635 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
11636 (when level
11637 (when (> level -1)
11638 (aset org-section-numbers
11639 level (1+ (aref org-section-numbers level))))
11640 (setq idx (1+ level))
11641 (while (<= idx depth)
11642 (if (not (= idx 1))
11643 (aset org-section-numbers idx 0))
11644 (setq idx (1+ idx))))
11645 (setq idx 0)
11646 (while (<= idx depth)
11647 (setq n (aref org-section-numbers idx))
11648 (setq string (concat string (if (not (string= string "")) "." "")
11649 (int-to-string n)))
11650 (setq idx (1+ idx)))
11651 (save-match-data
11652 (if (string-match "\\`\\([@0]\\.\\)+" string)
11653 (setq string (replace-match "" nil nil string)))
11654 (if (string-match "\\(\\.0\\)+\\'" string)
11655 (setq string (replace-match "" nil nil string))))
11656 string))
11657
11658
11659 (defun org-export-icalendar-this-file ()
11660 "Export current file as an iCalendar file.
11661 The iCalendar file will be located in the same directory as the Org-mode
11662 file, but with extension `.ics'."
11663 (interactive)
11664 (org-export-icalendar nil (buffer-file-name)))
11665
11666 ;;;###autoload
11667 (defun org-export-icalendar-all-agenda-files ()
11668 "Export all files in `org-agenda-files' to iCalendar .ics files.
11669 Each iCalendar file will be located in the same directory as the Org-mode
11670 file, but with extension `.ics'."
11671 (interactive)
11672 (apply 'org-export-icalendar nil org-agenda-files))
11673
11674 ;;;###autoload
11675 (defun org-export-icalendar-combine-agenda-files ()
11676 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11677 The file is stored under the name `org-combined-agenda-icalendar-file'."
11678 (interactive)
11679 (apply 'org-export-icalendar t org-agenda-files))
11680
11681 (defun org-export-icalendar (combine &rest files)
11682 "Create iCalendar files for all elements of FILES.
11683 If COMBINE is non-nil, combine all calendar entries into a single large
11684 file and store it under the name `org-combined-agenda-icalendar-file'."
11685 (save-excursion
11686 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11687 (when combine
11688 (setq ical-file org-combined-agenda-icalendar-file
11689 ical-buffer (org-get-agenda-file-buffer ical-file))
11690 (set-buffer ical-buffer) (erase-buffer))
11691 (while (setq file (pop files))
11692 (catch 'nextfile
11693 (org-check-agenda-file file)
11694 (unless combine
11695 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11696 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11697 (set-buffer ical-buffer) (erase-buffer))
11698 (set-buffer (org-get-agenda-file-buffer file))
11699 (setq category (or org-category
11700 (file-name-sans-extension
11701 (file-name-nondirectory (buffer-file-name)))))
11702 (if (symbolp category) (setq category (symbol-name category)))
11703 (let ((standard-output ical-buffer))
11704 (if combine
11705 (and (not started) (setq started t)
11706 (org-start-icalendar-file org-icalendar-combined-name))
11707 (org-start-icalendar-file category))
11708 (org-print-icalendar-entries combine category)
11709 (when (or (and combine (not files)) (not combine))
11710 (org-finish-icalendar-file)
11711 (set-buffer ical-buffer)
11712 (save-buffer)
11713 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11714 (org-release-buffers org-agenda-new-buffers))))
11715
11716 (defvar org-after-save-iCalendar-file-hook nil
11717 "Hook run after an iCalendar file has been saved.
11718 The iCalendar buffer is still current when this hook is run.
11719 A good way to use this is to tell a desktop calenndar application to re-read
11720 the iCalendar file.")
11721
11722 (defun org-print-icalendar-entries (&optional combine category)
11723 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11724 When COMBINE is non nil, add the category to each line."
11725 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11726 (dts (org-ical-ts-to-string
11727 (format-time-string (cdr org-time-stamp-formats) (current-time))
11728 "DTSTART"))
11729 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11730 (save-excursion
11731 (goto-char (point-min))
11732 (while (re-search-forward org-ts-regexp nil t)
11733 (setq pos (match-beginning 0)
11734 ts (match-string 0)
11735 inc t
11736 hd (org-get-heading))
11737 (if (looking-at re2)
11738 (progn
11739 (goto-char (match-end 0))
11740 (setq ts2 (match-string 1) inc nil))
11741 (setq ts2 ts
11742 tmp (buffer-substring (max (point-min)
11743 (- pos org-ds-keyword-length))
11744 pos)
11745 deadlinep (string-match org-deadline-regexp tmp)
11746 scheduledp (string-match org-scheduled-regexp tmp)
11747 ;; donep (org-entry-is-done-p)
11748 ))
11749 (if (or (string-match org-tr-regexp hd)
11750 (string-match org-ts-regexp hd))
11751 (setq hd (replace-match "" t t hd)))
11752 (if combine
11753 (setq hd (concat hd " (category " category ")")))
11754 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11755 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11756 (princ (format "BEGIN:VEVENT
11757 %s
11758 %s
11759 SUMMARY:%s
11760 END:VEVENT\n"
11761 (org-ical-ts-to-string ts "DTSTART")
11762 (org-ical-ts-to-string ts2 "DTEND" inc)
11763 hd)))
11764 (when org-icalendar-include-todo
11765 (goto-char (point-min))
11766 (while (re-search-forward org-todo-line-regexp nil t)
11767 (setq state (match-string 1))
11768 (unless (equal state org-done-string)
11769 (setq hd (match-string 3))
11770 (if (string-match org-priority-regexp hd)
11771 (setq pri (string-to-char (match-string 2 hd))
11772 hd (concat (substring hd 0 (match-beginning 1))
11773 (substring hd (- (match-end 1)))))
11774 (setq pri org-default-priority))
11775 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11776 (- org-lowest-priority ?A))))))
11777
11778 (princ (format "BEGIN:VTODO
11779 %s
11780 SUMMARY:%s
11781 SEQUENCE:1
11782 PRIORITY:%d
11783 END:VTODO\n"
11784 dts hd pri))))))))
11785
11786 (defun org-start-icalendar-file (name)
11787 "Start an iCalendar file by inserting the header."
11788 (let ((user user-full-name)
11789 (name (or name "unknown"))
11790 (timezone (cadr (current-time-zone))))
11791 (princ
11792 (format "BEGIN:VCALENDAR
11793 VERSION:2.0
11794 X-WR-CALNAME:%s
11795 PRODID:-//%s//Emacs with Org-mode//EN
11796 X-WR-TIMEZONE:%s
11797 CALSCALE:GREGORIAN\n" name user timezone))))
11798
11799 (defun org-finish-icalendar-file ()
11800 "Finish an iCalendar file by inserting the END statement."
11801 (princ "END:VCALENDAR\n"))
11802
11803 (defun org-ical-ts-to-string (s keyword &optional inc)
11804 "Take a time string S and convert it to iCalendar format.
11805 KEYWORD is added in front, to make a complete line like DTSTART....
11806 When INC is non-nil, increase the hour by two (if time string contains
11807 a time), or the day by one (if it does not contain a time)."
11808 (let ((t1 (org-parse-time-string s 'nodefault))
11809 t2 fmt have-time time)
11810 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11811 (setq t2 t1 have-time t)
11812 (setq t2 (org-parse-time-string s)))
11813 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11814 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11815 (when inc
11816 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11817 (setq time (encode-time s mi h d m y)))
11818 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11819 (concat keyword (format-time-string fmt time))))
11820
11821
11822 ;;; Key bindings
11823
11824 ;; - Bindings in Org-mode map are currently
11825 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11826 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
11827 ;; e (?) useful from outline-mode
11828 ;; i k @ expendable from outline-mode
11829 ;; 0123456789 % & ()_{} " ` free
11830
11831 ;; Make `C-c C-x' a prefix key
11832 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11833
11834 ;; TAB key with modifiers
11835 (define-key org-mode-map "\C-i" 'org-cycle)
11836 (define-key org-mode-map [(meta tab)] 'org-complete)
11837 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11838 ;; The following line is necessary under Suse GNU/Linux
11839 (unless org-xemacs-p
11840 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11841 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11842
11843 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11844 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11845 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11846 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11847 (define-key org-mode-map [(meta return)] 'org-meta-return)
11848 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11849 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11850
11851 ;; Cursor keys with modifiers
11852 (define-key org-mode-map [(meta left)] 'org-metaleft)
11853 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11854 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11855 (define-key org-mode-map [(meta right)] 'org-metaright)
11856 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11857 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11858 (define-key org-mode-map [(meta up)] 'org-metaup)
11859 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11860 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11861 (define-key org-mode-map [(meta down)] 'org-metadown)
11862 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11863 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11864
11865 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11866 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11867 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11868 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11869 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11870 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11871 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11872 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11873 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11874 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11875 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11876 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11877 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11878 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11879 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11880 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11881
11882 ;; All the other keys
11883 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11884 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11885 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11886 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11887 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11888 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11889 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11890 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11891 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11892 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11893 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11894 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11895 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11896 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11897 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
11898 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
11899 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11900 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11901 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11902 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11903 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11904 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11905 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11906 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11907 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
11908 (define-key org-mode-map "\C-c]" 'org-remove-file)
11909 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
11910 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
11911 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
11912 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11913 (define-key org-mode-map "\C-m" 'org-return)
11914 (define-key org-mode-map "\C-c?" 'org-table-current-column)
11915 (define-key org-mode-map "\C-c " 'org-table-blank-field)
11916 (define-key org-mode-map "\C-c+" 'org-table-sum)
11917 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
11918 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
11919 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
11920 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
11921 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11922 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
11923 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11924 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
11925 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
11926 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
11927 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
11928 ;; OPML support is only an option for the future
11929 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
11930 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
11931 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
11932 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
11933 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
11934 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11935 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
11936 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11937 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
11938 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
11939 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
11940
11941 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11942 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11943 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11944 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11945
11946 (defsubst org-table-p () (org-at-table-p))
11947
11948 (defun org-self-insert-command (N)
11949 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11950 If the cursor is in a table looking at whitespace, the whitespace is
11951 overwritten, and the table is not marked as requiring realignment."
11952 (interactive "p")
11953 (if (and (org-table-p)
11954 (or
11955 (and org-table-auto-blank-field
11956 (member last-command
11957 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11958 (org-table-blank-field))
11959 t)
11960 (eq N 1)
11961 (looking-at "[^|\n]* +|"))
11962 (let (org-table-may-need-update)
11963 (goto-char (1- (match-end 0)))
11964 (delete-backward-char 1)
11965 (goto-char (match-beginning 0))
11966 (self-insert-command N))
11967 (setq org-table-may-need-update t)
11968 (self-insert-command N)))
11969
11970 ;; FIXME:
11971 ;; The following two functions might still be optimized to trigger
11972 ;; re-alignment less frequently.
11973
11974 (defun org-delete-backward-char (N)
11975 "Like `delete-backward-char', insert whitespace at field end in tables.
11976 When deleting backwards, in tables this function will insert whitespace in
11977 front of the next \"|\" separator, to keep the table aligned. The table will
11978 still be marked for re-alignment, because a narrow field may lead to a
11979 reduced column width."
11980 (interactive "p")
11981 (if (and (org-table-p)
11982 (eq N 1)
11983 (string-match "|" (buffer-substring (point-at-bol) (point)))
11984 (looking-at ".*?|"))
11985 (let ((pos (point)))
11986 (backward-delete-char N)
11987 (skip-chars-forward "^|")
11988 (insert " ")
11989 (goto-char (1- pos)))
11990 (backward-delete-char N)))
11991
11992 (defun org-delete-char (N)
11993 "Like `delete-char', but insert whitespace at field end in tables.
11994 When deleting characters, in tables this function will insert whitespace in
11995 front of the next \"|\" separator, to keep the table aligned. The table
11996 will still be marked for re-alignment, because a narrow field may lead to
11997 a reduced column width."
11998 (interactive "p")
11999 (if (and (org-table-p)
12000 (not (bolp))
12001 (not (= (char-after) ?|))
12002 (eq N 1))
12003 (if (looking-at ".*?|")
12004 (let ((pos (point)))
12005 (replace-match (concat
12006 (substring (match-string 0) 1 -1)
12007 " |"))
12008 (goto-char pos)))
12009 (delete-char N)))
12010
12011 ;; How to do this: Measure non-white length of current string
12012 ;; If equal to column width, we should realign.
12013
12014 (defun org-remap (map &rest commands)
12015 "In MAP, remap the functions given in COMMANDS.
12016 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12017 (let (new old)
12018 (while commands
12019 (setq old (pop commands) new (pop commands))
12020 (if (fboundp 'command-remapping)
12021 (define-key map (vector 'remap old) new)
12022 (substitute-key-definition old new map global-map)))))
12023
12024 (when (eq org-enable-table-editor 'optimized)
12025 ;; If the user wants maximum table support, we need to hijack
12026 ;; some standard editing functions
12027 (org-remap org-mode-map
12028 'self-insert-command 'org-self-insert-command
12029 'delete-char 'org-delete-char
12030 'delete-backward-char 'org-delete-backward-char)
12031 (define-key org-mode-map "|" 'org-force-self-insert))
12032
12033 (defun org-shiftcursor-error ()
12034 "Throw an error because Shift-Cursor command was applied in wrong context."
12035 (error "This command is active in special context like tables, headlines or timestamps"))
12036
12037 (defun org-shifttab ()
12038 "Global visibility cycling or move to previous table field.
12039 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12040 See the individual commands for more information."
12041 (interactive)
12042 (cond
12043 ((org-at-table-p) (org-table-previous-field))
12044 (t (org-cycle '(4)))))
12045
12046 (defun org-shiftmetaleft ()
12047 "Promote subtree or delete table column.
12048 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12049 See the individual commands for more information."
12050 (interactive)
12051 (cond
12052 ((org-at-table-p) (org-table-delete-column))
12053 ((org-on-heading-p) (org-promote-subtree))
12054 ((org-at-item-p) (call-interactively 'org-outdent-item))
12055 (t (org-shiftcursor-error))))
12056
12057 (defun org-shiftmetaright ()
12058 "Demote subtree or insert table column.
12059 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12060 See the individual commands for more information."
12061 (interactive)
12062 (cond
12063 ((org-at-table-p) (org-table-insert-column))
12064 ((org-on-heading-p) (org-demote-subtree))
12065 ((org-at-item-p) (call-interactively 'org-indent-item))
12066 (t (org-shiftcursor-error))))
12067
12068 (defun org-shiftmetaup (&optional arg)
12069 "Move subtree up or kill table row.
12070 Calls `org-move-subtree-up' or `org-table-kill-row' or
12071 `org-move-item-up' depending on context. See the individual commands
12072 for more information."
12073 (interactive "P")
12074 (cond
12075 ((org-at-table-p) (org-table-kill-row))
12076 ((org-on-heading-p) (org-move-subtree-up arg))
12077 ((org-at-item-p) (org-move-item-up arg))
12078 (t (org-shiftcursor-error))))
12079 (defun org-shiftmetadown (&optional arg)
12080 "Move subtree down or insert table row.
12081 Calls `org-move-subtree-down' or `org-table-insert-row' or
12082 `org-move-item-down', depending on context. See the individual
12083 commands for more information."
12084 (interactive "P")
12085 (cond
12086 ((org-at-table-p) (org-table-insert-row arg))
12087 ((org-on-heading-p) (org-move-subtree-down arg))
12088 ((org-at-item-p) (org-move-item-down arg))
12089 (t (org-shiftcursor-error))))
12090
12091 (defun org-metaleft (&optional arg)
12092 "Promote heading or move table column to left.
12093 Calls `org-do-promote' or `org-table-move-column', depending on context.
12094 With no specific context, calls the Emacs default `backward-word'.
12095 See the individual commands for more information."
12096 (interactive "P")
12097 (cond
12098 ((org-at-table-p) (org-table-move-column 'left))
12099 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12100 (t (backward-word (prefix-numeric-value arg)))))
12101
12102 (defun org-metaright (&optional arg)
12103 "Demote subtree or move table column to right.
12104 Calls `org-do-demote' or `org-table-move-column', depending on context.
12105 With no specific context, calls the Emacs default `forward-word'.
12106 See the individual commands for more information."
12107 (interactive "P")
12108 (cond
12109 ((org-at-table-p) (org-table-move-column nil))
12110 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12111 (t (forward-word (prefix-numeric-value arg)))))
12112
12113 (defun org-metaup (&optional arg)
12114 "Move subtree up or move table row up.
12115 Calls `org-move-subtree-up' or `org-table-move-row' or
12116 `org-move-item-up', depending on context. See the individual commands
12117 for more information."
12118 (interactive "P")
12119 (cond
12120 ((org-at-table-p) (org-table-move-row 'up))
12121 ((org-on-heading-p) (org-move-subtree-up arg))
12122 ((org-at-item-p) (org-move-item-up arg))
12123 (t (org-shiftcursor-error))))
12124
12125 (defun org-metadown (&optional arg)
12126 "Move subtree down or move table row down.
12127 Calls `org-move-subtree-down' or `org-table-move-row' or
12128 `org-move-item-down', depending on context. See the individual
12129 commands for more information."
12130 (interactive "P")
12131 (cond
12132 ((org-at-table-p) (org-table-move-row nil))
12133 ((org-on-heading-p) (org-move-subtree-down arg))
12134 ((org-at-item-p) (org-move-item-down arg))
12135 (t (org-shiftcursor-error))))
12136
12137 (defun org-shiftup (&optional arg)
12138 "Increase item in timestamp or increase priority of current item.
12139 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12140 See the individual commands for more information."
12141 (interactive "P")
12142 (cond
12143 ((org-at-timestamp-p) (org-timestamp-up arg))
12144 (t (org-priority-up))))
12145
12146 (defun org-shiftdown (&optional arg)
12147 "Decrease item in timestamp or decrease priority of current item.
12148 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12149 See the individual commands for more information."
12150 (interactive "P")
12151 (cond
12152 ((org-at-timestamp-p) (org-timestamp-down arg))
12153 (t (org-priority-down))))
12154
12155 (defun org-shiftright ()
12156 "Next TODO keyword or timestamp one day later, depending on context."
12157 (interactive)
12158 (cond
12159 ((org-at-timestamp-p) (org-timestamp-up-day))
12160 ((org-on-heading-p) (org-todo 'right))
12161 (t (org-shiftcursor-error))))
12162
12163 (defun org-shiftleft ()
12164 "Previous TODO keyword or timestamp one day earlier, depending on context."
12165 (interactive)
12166 (cond
12167 ((org-at-timestamp-p) (org-timestamp-down-day))
12168 ((org-on-heading-p) (org-todo 'left))
12169 (t (org-shiftcursor-error))))
12170
12171 (defun org-copy-special ()
12172 "Copy region in table or copy current subtree.
12173 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12174 See the individual commands for more information."
12175 (interactive)
12176 (call-interactively
12177 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12178
12179 (defun org-cut-special ()
12180 "Cut region in table or cut current subtree.
12181 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12182 See the individual commands for more information."
12183 (interactive)
12184 (call-interactively
12185 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12186
12187 (defun org-paste-special (arg)
12188 "Paste rectangular region into table, or past subtree relative to level.
12189 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12190 See the individual commands for more information."
12191 (interactive "P")
12192 (if (org-at-table-p)
12193 (org-table-paste-rectangle)
12194 (org-paste-subtree arg)))
12195
12196 (defun org-ctrl-c-ctrl-c (&optional arg)
12197 "Call realign table, or recognize a table.el table, or update keywords.
12198 When the cursor is inside a table created by the table.el package,
12199 activate that table. Otherwise, if the cursor is at a normal table
12200 created with org.el, re-align that table. This command works even if
12201 the automatic table editor has been turned off.
12202
12203 If the cursor is in a headline, prompt for tags and insert them into
12204 the current line, aligned to `org-tags-column'. When in a headline and
12205 called with prefix arg, realign all tags in the current buffer.
12206
12207 If the cursor is in one of the special #+KEYWORD lines, this triggers
12208 scanning the buffer for these lines and updating the information.
12209 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
12210 (interactive "P")
12211 (let ((org-enable-table-editor t))
12212 (cond
12213 ((org-on-target-p) (org-update-radio-target-regexp))
12214 ((org-on-heading-p) (org-set-tags arg))
12215 ((org-at-table.el-p)
12216 (require 'table)
12217 (beginning-of-line 1)
12218 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12219 (table-recognize-table))
12220 ((org-at-table-p)
12221 (org-table-maybe-eval-formula)
12222 (if arg
12223 (org-table-recalculate t)
12224 (org-table-maybe-recalculate-line))
12225 (org-table-align))
12226 ((org-at-item-p)
12227 (org-renumber-ordered-list (prefix-numeric-value arg)))
12228 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12229 (cond
12230 ((equal (match-string 1) "TBLFM")
12231 ;; Recalculate the table before this line
12232 (save-excursion
12233 (beginning-of-line 1)
12234 (skip-chars-backward " \r\n\t")
12235 (if (org-at-table-p) (org-table-recalculate t))))
12236 (t
12237 (org-mode-restart))))
12238 ((org-region-active-p)
12239 (org-table-convert-region (region-beginning) (region-end) arg))
12240 ((condition-case nil
12241 (and (region-beginning) (region-end))
12242 (error nil))
12243 (if (y-or-n-p "Convert inactive region to table? ")
12244 (org-table-convert-region (region-beginning) (region-end) arg)
12245 (error "Abort")))
12246 (t (error "C-c C-c can do nothing useful at this location.")))))
12247
12248 (defun org-mode-restart ()
12249 "Restart Org-mode, to scan again for special lines.
12250 Also updates the keyword regular expressions."
12251 (interactive)
12252 (let ((org-inhibit-startup t)) (org-mode))
12253 (message "Org-mode restarted to refresh keyword and special line setup"))
12254
12255 (defun org-return ()
12256 "Goto next table row or insert a newline.
12257 Calls `org-table-next-row' or `newline', depending on context.
12258 See the individual commands for more information."
12259 (interactive)
12260 (cond
12261 ((org-at-table-p)
12262 (org-table-justify-field-maybe)
12263 (org-table-next-row))
12264 (t (newline))))
12265
12266 (defun org-meta-return (&optional arg)
12267 "Insert a new heading or wrap a region in a table.
12268 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12269 See the individual commands for more information."
12270 (interactive "P")
12271 (cond
12272 ((org-at-table-p)
12273 (org-table-wrap-region arg))
12274 (t (org-insert-heading arg))))
12275
12276 ;;; Menu entries
12277
12278 ;; Define the Org-mode menus
12279 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12280 '("Tbl"
12281 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
12282 ["Next Field" org-cycle (org-at-table-p)]
12283 ["Previous Field" org-shifttab (org-at-table-p)]
12284 ["Next Row" org-return (org-at-table-p)]
12285 "--"
12286 ["Blank Field" org-table-blank-field (org-at-table-p)]
12287 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12288 "--"
12289 ("Column"
12290 ["Move Column Left" org-metaleft (org-at-table-p)]
12291 ["Move Column Right" org-metaright (org-at-table-p)]
12292 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12293 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12294 ("Row"
12295 ["Move Row Up" org-metaup (org-at-table-p)]
12296 ["Move Row Down" org-metadown (org-at-table-p)]
12297 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12298 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12299 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12300 "--"
12301 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
12302 ("Rectangle"
12303 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12304 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12305 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12306 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12307 "--"
12308 ("Calculate"
12309 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12310 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12311 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12312 "--"
12313 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12314 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12315 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12316 "--"
12317 ["Sum Column/Rectangle" org-table-sum
12318 (or (org-at-table-p) (org-region-active-p))]
12319 ["Which Column?" org-table-current-column (org-at-table-p)])
12320 ["Debug Formulas"
12321 (setq org-table-formula-debug (not org-table-formula-debug))
12322 :style toggle :selected org-table-formula-debug]
12323 "--"
12324 ["Invisible Vlines" org-table-toggle-vline-visibility
12325 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
12326 "--"
12327 ["Create" org-table-create (and (not (org-at-table-p))
12328 org-enable-table-editor)]
12329 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
12330 ["Import from File" org-table-import (not (org-at-table-p))]
12331 ["Export to File" org-table-export (org-at-table-p)]
12332 "--"
12333 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12334
12335 (easy-menu-define org-org-menu org-mode-map "Org menu"
12336 '("Org"
12337 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
12338 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
12339 ["Sparse Tree" org-occur t]
12340 ["Show All" show-all t]
12341 "--"
12342 ["New Heading" org-insert-heading t]
12343 ("Navigate Headings"
12344 ["Up" outline-up-heading t]
12345 ["Next" outline-next-visible-heading t]
12346 ["Previous" outline-previous-visible-heading t]
12347 ["Next Same Level" outline-forward-same-level t]
12348 ["Previous Same Level" outline-backward-same-level t]
12349 "--"
12350 ["Jump" org-goto t])
12351 ("Edit Structure"
12352 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12353 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12354 "--"
12355 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12356 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12357 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12358 "--"
12359 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12360 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12361 ["Demote Heading" org-metaright (not (org-at-table-p))]
12362 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12363 "--"
12364 ["Archive Subtree" org-archive-subtree t]
12365 "--"
12366 ["Convert file to odd levels" org-convert-to-odd-levels t])
12367 "--"
12368 ("TODO Lists"
12369 ["TODO/DONE/-" org-todo t]
12370 ["Show TODO Tree" org-show-todo-tree t]
12371 ["Global TODO list" org-todo-list t]
12372 "--"
12373 ["Set Priority" org-priority t]
12374 ["Priority Up" org-shiftup t]
12375 ["Priority Down" org-shiftdown t])
12376 ("Dates and Scheduling"
12377 ["Timestamp" org-time-stamp t]
12378 ["Timestamp (inactive)" org-time-stamp-inactive t]
12379 ("Change Date"
12380 ["1 Day Later" org-timestamp-up-day t]
12381 ["1 Day Earlier" org-timestamp-down-day t]
12382 ["1 ... Later" org-shiftup t]
12383 ["1 ... Earlier" org-shiftdown t])
12384 ["Compute Time Range" org-evaluate-time-range t]
12385 ["Schedule Item" org-schedule t]
12386 ["Deadline" org-deadline t]
12387 "--"
12388 ["Goto Calendar" org-goto-calendar t]
12389 ["Date from Calendar" org-date-from-calendar t])
12390 "--"
12391 ["Agenda Command" org-agenda t]
12392 ("File List for Agenda")
12393 ("Special views current file"
12394 ["TODO Tree" org-show-todo-tree t]
12395 ["Check Deadlines" org-check-deadlines t]
12396 ["Timeline" org-timeline t]
12397 ["Tags Tree" org-tags-sparse-tree t])
12398 "--"
12399 ("Hyperlinks"
12400 ["Store Link (Global)" org-store-link t]
12401 ["Insert Link" org-insert-link t]
12402 ["Follow Link" org-open-at-point t])
12403 "--"
12404 ("Export"
12405 ["ASCII" org-export-as-ascii t]
12406 ["Extract Visible Text" org-export-copy-visible t]
12407 ["HTML" org-export-as-html t]
12408 ["HTML and Open" org-export-as-html-and-open t]
12409 ; ["OPML" org-export-as-opml nil]
12410 "--"
12411 ["iCalendar this file" org-export-icalendar-this-file t]
12412 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
12413 :active t :keys "C-c C-x C-i"]
12414 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
12415 "--"
12416 ["Option Template" org-insert-export-options-template t]
12417 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
12418 "--"
12419 ("Documentation"
12420 ["Show Version" org-version t]
12421 ["Info Documentation" org-info t])
12422 ("Customize"
12423 ["Browse Org Group" org-customize t]
12424 "--"
12425 ["Build Full Customize Menu" org-create-customize-menu
12426 (fboundp 'customize-menu-create)])
12427 "--"
12428 ["Refresh setup" org-mode-restart t]
12429 ))
12430
12431 (defun org-info (&optional node)
12432 "Read documentation for Org-mode in the info system.
12433 With optional NODE, go directly to that node."
12434 (interactive)
12435 (require 'info)
12436 (Info-goto-node (format "(org)%s" (or node ""))))
12437
12438 (defun org-install-agenda-files-menu ()
12439 (easy-menu-change
12440 '("Org") "File List for Agenda"
12441 (append
12442 (list
12443 ["Edit File List" (customize-variable 'org-agenda-files) t]
12444 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12445 ["Remove Current File from List" org-remove-file t]
12446 ["Cycle through agenda files" org-cycle-agenda-files t]
12447 "--")
12448 (mapcar 'org-file-menu-entry org-agenda-files))))
12449
12450 ;;; Documentation
12451
12452 (defun org-customize ()
12453 "Call the customize function with org as argument."
12454 (interactive)
12455 (customize-browse 'org))
12456
12457 (defun org-create-customize-menu ()
12458 "Create a full customization menu for Org-mode, insert it into the menu."
12459 (interactive)
12460 (if (fboundp 'customize-menu-create)
12461 (progn
12462 (easy-menu-change
12463 '("Org") "Customize"
12464 `(["Browse Org group" org-customize t]
12465 "--"
12466 ,(customize-menu-create 'org)
12467 ["Set" Custom-set t]
12468 ["Save" Custom-save t]
12469 ["Reset to Current" Custom-reset-current t]
12470 ["Reset to Saved" Custom-reset-saved t]
12471 ["Reset to Standard Settings" Custom-reset-standard t]))
12472 (message "\"Org\"-menu now contains full customization menu"))
12473 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12474
12475 ;;; Miscellaneous stuff
12476
12477 (defun org-move-line-down (arg)
12478 "Move the current line down. With prefix argument, move it past ARG lines."
12479 (interactive "p")
12480 (let ((col (current-column))
12481 beg end pos)
12482 (beginning-of-line 1) (setq beg (point))
12483 (beginning-of-line 2) (setq end (point))
12484 (beginning-of-line (+ 1 arg))
12485 (setq pos (move-marker (make-marker) (point)))
12486 (insert (delete-and-extract-region beg end))
12487 (goto-char pos)
12488 (move-to-column col)))
12489
12490 (defun org-move-line-up (arg)
12491 "Move the current line up. With prefix argument, move it past ARG lines."
12492 (interactive "p")
12493 (let ((col (current-column))
12494 beg end pos)
12495 (beginning-of-line 1) (setq beg (point))
12496 (beginning-of-line 2) (setq end (point))
12497 (beginning-of-line (- arg))
12498 (setq pos (move-marker (make-marker) (point)))
12499 (insert (delete-and-extract-region beg end))
12500 (goto-char pos)
12501 (move-to-column col)))
12502
12503 ;; Paragraph filling stuff.
12504 ;; We want this to be just right, so use the full arsenal.
12505 ;; FIXME: This very likely does not work correctly for XEmacs, because the
12506 ;; filladapt package works slightly differently.
12507
12508 (defun org-set-autofill-regexps ()
12509 (interactive)
12510 ;; In the paragraph separator we include headlines, because filling
12511 ;; text in a line directly attached to a headline would otherwise
12512 ;; fill the headline as well.
12513 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
12514 ;; The paragraph starter includes hand-formatted lists.
12515 (set (make-local-variable 'paragraph-start)
12516 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
12517 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
12518 ;; But only if the user has not turned off tables or fixed-width regions
12519 (set (make-local-variable 'auto-fill-inhibit-regexp)
12520 (concat "\\*\\|#"
12521 (if (or org-enable-table-editor org-enable-fixed-width-editor)
12522 (concat
12523 "\\|[ \t]*["
12524 (if org-enable-table-editor "|" "")
12525 (if org-enable-fixed-width-editor ":" "")
12526 "]"))))
12527 ;; We use our own fill-paragraph function, to make sure that tables
12528 ;; and fixed-width regions are not wrapped. That function will pass
12529 ;; through to `fill-paragraph' when appropriate.
12530 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
12531 ;; Adaptive filling: To get full control, first make sure that
12532 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
12533 (setq adaptive-fill-regexp "\000")
12534 (setq adaptive-fill-function 'org-adaptive-fill-function))
12535
12536 (defun org-fill-paragraph (&optional justify)
12537 "Re-align a table, pass through to fill-paragraph if no table."
12538 (let ((table-p (org-at-table-p))
12539 (table.el-p (org-at-table.el-p)))
12540 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
12541 (table.el-p t) ; skip table.el tables
12542 (table-p (org-table-align) t) ; align org-mode tables
12543 (t nil)))) ; call paragraph-fill
12544
12545 ;; For reference, this is the default value of adaptive-fill-regexp
12546 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
12547
12548 (defun org-adaptive-fill-function ()
12549 "Return a fill prefix for org-mode files.
12550 In particular, this makes sure hanging paragraphs for hand-formatted lists
12551 work correctly."
12552 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
12553 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
12554
12555 ;; Functions needed for Emacs/XEmacs region compatibility
12556
12557 (defun org-add-hook (hook function &optional append local)
12558 "Add-hook, compatible with both Emacsen."
12559 (if (and local org-xemacs-p)
12560 (add-local-hook hook function append)
12561 (add-hook hook function append local)))
12562
12563 (defun org-region-active-p ()
12564 "Is `transient-mark-mode' on and the region active?
12565 Works on both Emacs and XEmacs."
12566 (if org-ignore-region
12567 nil
12568 (if org-xemacs-p
12569 (and zmacs-regions (region-active-p))
12570 (and transient-mark-mode mark-active))))
12571
12572 (defun org-add-to-invisibility-spec (arg)
12573 "Add elements to `buffer-invisibility-spec'.
12574 See documentation for `buffer-invisibility-spec' for the kind of elements
12575 that can be added."
12576 (cond
12577 ((fboundp 'add-to-invisibility-spec)
12578 (add-to-invisibility-spec arg))
12579 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
12580 (setq buffer-invisibility-spec (list arg)))
12581 (t
12582 (setq buffer-invisibility-spec
12583 (cons arg buffer-invisibility-spec)))))
12584
12585 (defun org-remove-from-invisibility-spec (arg)
12586 "Remove elements from `buffer-invisibility-spec'."
12587 (if (fboundp 'remove-from-invisibility-spec)
12588 (remove-from-invisibility-spec arg)
12589 (if (consp buffer-invisibility-spec)
12590 (setq buffer-invisibility-spec
12591 (delete arg buffer-invisibility-spec)))))
12592
12593 (defun org-in-invisibility-spec-p (arg)
12594 "Is ARG a member of `buffer-invisibility-spec'?"
12595 (if (consp buffer-invisibility-spec)
12596 (member arg buffer-invisibility-spec)
12597 nil))
12598
12599 (defun org-image-file-name-regexp ()
12600 "Return regexp matching the file names of images."
12601 (if (fboundp 'image-file-name-regexp)
12602 (image-file-name-regexp)
12603 (let ((image-file-name-extensions
12604 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
12605 "xbm" "xpm" "pbm" "pgm" "ppm")))
12606 (concat "\\."
12607 (regexp-opt (nconc (mapcar 'upcase
12608 image-file-name-extensions)
12609 image-file-name-extensions)
12610 t)
12611 "\\'"))))
12612
12613 ;; Functions needed for compatibility with old outline.el.
12614
12615 ;; Programming for the old outline.el (that uses selective display
12616 ;; instead of `invisible' text properties) is a nightmare, mostly
12617 ;; because regular expressions can no longer be anchored at
12618 ;; beginning/end of line. Therefore a number of function need special
12619 ;; treatment when the old outline.el is being used.
12620
12621 ;; The following functions capture almost the entire compatibility code
12622 ;; between the different versions of outline-mode. The only other
12623 ;; places where this is important are the font-lock-keywords, and in
12624 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
12625
12626 ;; C-a should go to the beginning of a *visible* line, also in the
12627 ;; new outline.el. I guess this should be patched into Emacs?
12628 (defun org-beginning-of-line ()
12629 "Go to the beginning of the current line. If that is invisible, continue
12630 to a visible line beginning. This makes the function of C-a more intuitive."
12631 (interactive)
12632 (beginning-of-line 1)
12633 (if (bobp)
12634 nil
12635 (backward-char 1)
12636 (if (org-invisible-p)
12637 (while (and (not (bobp)) (org-invisible-p))
12638 (backward-char 1)
12639 (beginning-of-line 1))
12640 (forward-char 1))))
12641
12642 (when org-noutline-p
12643 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
12644 ;; FIXME: should I use substitute-key-definition to reach other bindings
12645 ;; of beginning-of-line?
12646
12647 (defun org-invisible-p ()
12648 "Check if point is at a character currently not visible."
12649 (if org-noutline-p
12650 ;; Early versions of noutline don't have `outline-invisible-p'.
12651 (if (fboundp 'outline-invisible-p)
12652 (outline-invisible-p)
12653 (get-char-property (point) 'invisible))
12654 (save-excursion
12655 (skip-chars-backward "^\r\n")
12656 (equal (char-before) ?\r))))
12657
12658 (defun org-invisible-p2 ()
12659 "Check if point is at a character currently not visible."
12660 (save-excursion
12661 (if org-noutline-p
12662 (progn
12663 (if (and (eolp) (not (bobp))) (backward-char 1))
12664 ;; Early versions of noutline don't have `outline-invisible-p'.
12665 (if (fboundp 'outline-invisible-p)
12666 (outline-invisible-p)
12667 (get-char-property (point) 'invisible)))
12668 (skip-chars-backward "^\r\n")
12669 (equal (char-before) ?\r))))
12670
12671 (defun org-back-to-heading (&optional invisible-ok)
12672 "Move to previous heading line, or beg of this line if it's a heading.
12673 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
12674 (if org-noutline-p
12675 (outline-back-to-heading invisible-ok)
12676 (if (and (memq (char-before) '(?\n ?\r))
12677 (looking-at outline-regexp))
12678 t
12679 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
12680 outline-regexp)
12681 nil t)
12682 (if invisible-ok
12683 (progn (goto-char (match-end 1))
12684 (looking-at outline-regexp)))
12685 (error "Before first heading")))))
12686
12687 (defun org-on-heading-p (&optional invisible-ok)
12688 "Return t if point is on a (visible) heading line.
12689 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12690 (if org-noutline-p
12691 (outline-on-heading-p 'invisible-ok)
12692 (save-excursion
12693 (skip-chars-backward "^\n\r")
12694 (and (looking-at outline-regexp)
12695 (or invisible-ok
12696 (bobp)
12697 (equal (char-before) ?\n))))))
12698
12699 (defun org-on-target-p ()
12700 (let ((pos (point)))
12701 (save-excursion
12702 (skip-chars-forward "<")
12703 (and (re-search-backward "<<" nil t)
12704 (or (looking-at org-target-regexp)
12705 (looking-at org-radio-target-regexp))
12706 (<= (match-beginning 0) pos)
12707 (>= (match-end 0) pos)))))
12708
12709 (defun org-up-heading-all (arg)
12710 "Move to the heading line of which the present line is a subheading.
12711 This function considers both visible and invisible heading lines.
12712 With argument, move up ARG levels."
12713 (if org-noutline-p
12714 (if (fboundp 'outline-up-heading-all)
12715 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12716 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12717 (org-back-to-heading t)
12718 (looking-at outline-regexp)
12719 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12720 (error "Cannot move up %d levels" arg)
12721 (re-search-backward
12722 (concat "[\n\r]" (regexp-quote
12723 (make-string (- (match-end 0) (match-beginning 0) arg)
12724 ?*))
12725 "[^*]"))
12726 (forward-char 1))))
12727
12728 (defun org-show-hidden-entry ()
12729 "Show an entry where even the heading is hidden."
12730 (save-excursion
12731 (if (not org-noutline-p)
12732 (progn
12733 (org-back-to-heading t)
12734 (org-flag-heading nil)))
12735 (org-show-entry)))
12736
12737 (defun org-check-occur-regexp (regexp)
12738 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12739 Of course, only for the old outline mode."
12740 (if org-noutline-p
12741 regexp
12742 (if (string-match "^\\^" regexp)
12743 (concat "[\n\r]" (substring regexp 1))
12744 regexp)))
12745
12746 (defun org-flag-heading (flag &optional entry)
12747 "Flag the current heading. FLAG non-nil means make invisible.
12748 When ENTRY is non-nil, show the entire entry."
12749 (save-excursion
12750 (org-back-to-heading t)
12751 (if (not org-noutline-p)
12752 ;; Make the current headline visible
12753 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12754 ;; Check if we should show the entire entry
12755 (if entry
12756 (progn
12757 (org-show-entry)
12758 (save-excursion ;; FIXME: Is this the fix for points in the -|
12759 ;; middle of text? |
12760 (and (outline-next-heading) ;; |
12761 (org-flag-heading nil)))) ; show the next heading _|
12762 (outline-flag-region (max 1 (1- (point)))
12763 (save-excursion (outline-end-of-heading) (point))
12764 (if org-noutline-p
12765 flag
12766 (if flag ?\r ?\n))))))
12767
12768 (defun org-end-of-subtree (&optional invisible-OK)
12769 ;; This is an exact copy of the original function, but it uses
12770 ;; `org-back-to-heading', to make it work also in invisible
12771 ;; trees. And is uses an invisible-OK argument.
12772 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
12773 (org-back-to-heading invisible-OK)
12774 (let ((first t)
12775 (level (funcall outline-level)))
12776 (while (and (not (eobp))
12777 (or first (> (funcall outline-level) level)))
12778 (setq first nil)
12779 (outline-next-heading))
12780 (if (memq (preceding-char) '(?\n ?\^M))
12781 (progn
12782 ;; Go to end of line before heading
12783 (forward-char -1)
12784 (if (memq (preceding-char) '(?\n ?\^M))
12785 ;; leave blank line before heading
12786 (forward-char -1))))))
12787
12788 (defun org-show-subtree ()
12789 "Show everything after this heading at deeper levels."
12790 (outline-flag-region
12791 (point)
12792 (save-excursion
12793 (outline-end-of-subtree) (outline-next-heading) (point))
12794 (if org-noutline-p nil ?\n)))
12795
12796 (defun org-show-entry ()
12797 "Show the body directly following this heading.
12798 Show the heading too, if it is currently invisible."
12799 (interactive)
12800 (save-excursion
12801 (org-back-to-heading t)
12802 (outline-flag-region
12803 (1- (point))
12804 (save-excursion
12805 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12806 (or (match-beginning 1) (point-max)))
12807 (if org-noutline-p nil ?\n))))
12808
12809
12810 (defun org-make-options-regexp (kwds)
12811 "Make a regular expression for keyword lines."
12812 (concat
12813 (if org-noutline-p "^" "[\n\r]")
12814 "#?[ \t]*\\+\\("
12815 (mapconcat 'regexp-quote kwds "\\|")
12816 "\\):[ \t]*"
12817 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12818
12819 ;; Make `bookmark-jump' show the jump location if it was hidden.
12820 (eval-after-load "bookmark"
12821 '(if (boundp 'bookmark-after-jump-hook)
12822 ;; We can use the hook
12823 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12824 ;; Hook not available, use advice
12825 (defadvice bookmark-jump (after org-make-visible activate)
12826 "Make the position visible."
12827 (org-bookmark-jump-unhide))))
12828
12829 (defun org-bookmark-jump-unhide ()
12830 "Unhide the current position, to show the bookmark location."
12831 (and (eq major-mode 'org-mode)
12832 (or (org-invisible-p)
12833 (save-excursion (goto-char (max (point-min) (1- (point))))
12834 (org-invisible-p)))
12835 (org-show-hierarchy-above)))
12836
12837 ;;; Finish up
12838
12839 (provide 'org)
12840
12841 (run-hooks 'org-load-hook)
12842
12843 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12844 ;;; org.el ends here
12845