]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-export-as-html): Fixed bugs in HTML
[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 (debug)
2967 (unless (org-kill-is-subtree-p tree)
2968 (error
2969 (substitute-command-keys
2970 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2971 (let* ((txt (or tree (current-kill 0)))
2972 (^re (concat "^\\(" outline-regexp "\\)"))
2973 (re (concat "\\(" outline-regexp "\\)"))
2974 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2975
2976 (old-level (if (string-match ^re txt)
2977 (- (match-end 0) (match-beginning 0))
2978 -1))
2979 (force-level (cond (level (prefix-numeric-value level))
2980 ((string-match
2981 ^re_ (buffer-substring (point-at-bol) (point)))
2982 (- (match-end 0) (match-beginning 0)))
2983 (t nil)))
2984 (previous-level (save-excursion
2985 (condition-case nil
2986 (progn
2987 (outline-previous-visible-heading 1)
2988 (if (looking-at re)
2989 (- (match-end 0) (match-beginning 0))
2990 1))
2991 (error 1))))
2992 (next-level (save-excursion
2993 (condition-case nil
2994 (progn
2995 (outline-next-visible-heading 1)
2996 (if (looking-at re)
2997 (- (match-end 0) (match-beginning 0))
2998 1))
2999 (error 1))))
3000 (new-level (or force-level (max previous-level next-level)))
3001 (shift (if (or (= old-level -1)
3002 (= new-level -1)
3003 (= old-level new-level))
3004 0
3005 (- new-level old-level)))
3006 (shift1 shift)
3007 (delta (if (> shift 0) -1 1))
3008 (func (if (> shift 0) 'org-demote 'org-promote))
3009 (org-odd-levels-only nil)
3010 beg end)
3011 ;; Remove the forces level indicator
3012 (if force-level
3013 (delete-region (point-at-bol) (point)))
3014 ;; Make sure we start at the beginning of an empty line
3015 (if (not (bolp)) (insert "\n"))
3016 (if (not (looking-at "[ \t]*$"))
3017 (progn (insert "\n") (backward-char 1)))
3018 ;; Paste
3019 (setq beg (point))
3020 (insert txt)
3021 (setq end (point))
3022 (goto-char beg)
3023 ;; Shift if necessary
3024 (if (= shift 0)
3025 (message "Pasted at level %d, without shift" new-level)
3026 (save-restriction
3027 (narrow-to-region beg end)
3028 (while (not (= shift 0))
3029 (org-map-region func (point-min) (point-max))
3030 (setq shift (+ delta shift)))
3031 (goto-char (point-min))
3032 (message "Pasted at level %d, with shift by %d levels"
3033 new-level shift1)))
3034 (if (and (eq org-subtree-clip (current-kill 0))
3035 org-subtree-clip-folded)
3036 ;; The tree was folded before it was killed/copied
3037 (hide-subtree))))
3038
3039 (defun org-kill-is-subtree-p (&optional txt)
3040 "Check if the current kill is an outline subtree, or a set of trees.
3041 Returns nil if kill does not start with a headline, or if the first
3042 headline level is not the largest headline level in the tree.
3043 So this will actually accept several entries of equal levels as well,
3044 which is OK for `org-paste-subtree'.
3045 If optional TXT is given, check this string instead of the current kill."
3046 (let* ((kill (or txt (current-kill 0) ""))
3047 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3048 (- (match-end 0) (match-beginning 0))))
3049 (re (concat "^" outline-regexp))
3050 (start 1))
3051 (if (not start-level)
3052 nil ;; does not even start with a heading
3053 (catch 'exit
3054 (while (setq start (string-match re kill (1+ start)))
3055 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3056 (throw 'exit nil)))
3057 t))))
3058
3059 ;;; Plain list items
3060
3061 (defun org-at-item-p ()
3062 "Is point in a line starting a hand-formatted item?"
3063 (let ((llt org-plain-list-ordered-item-terminator))
3064 (save-excursion
3065 (goto-char (point-at-bol))
3066 (looking-at
3067 (cond
3068 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3069 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3070 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3071 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3072
3073 (defun org-get-indentation ()
3074 "Get the indentation of the current line, interpreting tabs."
3075 (save-excursion
3076 (beginning-of-line 1)
3077 (skip-chars-forward " \t")
3078 (current-column)))
3079
3080 (defun org-beginning-of-item ()
3081 "Go to the beginning of the current hand-formatted item.
3082 If the cursor is not in an item, throw an error."
3083 (let ((pos (point))
3084 (limit (save-excursion (org-back-to-heading)
3085 (beginning-of-line 2) (point)))
3086 ind ind1)
3087 (if (org-at-item-p)
3088 (beginning-of-line 1)
3089 (beginning-of-line 1)
3090 (skip-chars-forward " \t")
3091 (setq ind (current-column))
3092 (if (catch 'exit
3093 (while t
3094 (beginning-of-line 0)
3095 (if (< (point) limit) (throw 'exit nil))
3096 (unless (looking-at " \t]*$")
3097 (skip-chars-forward " \t")
3098 (setq ind1 (current-column))
3099 (if (< ind1 ind)
3100 (throw 'exit (org-at-item-p))))))
3101 nil
3102 (goto-char pos)
3103 (error "Not in an item")))))
3104
3105 (defun org-end-of-item ()
3106 "Go to the end of the current hand-formatted item.
3107 If the cursor is not in an item, throw an error."
3108 (let ((pos (point))
3109 (limit (save-excursion (outline-next-heading) (point)))
3110 (ind (save-excursion
3111 (org-beginning-of-item)
3112 (skip-chars-forward " \t")
3113 (current-column)))
3114 ind1)
3115 (if (catch 'exit
3116 (while t
3117 (beginning-of-line 2)
3118 (if (>= (point) limit) (throw 'exit t))
3119 (unless (looking-at "[ \t]*$")
3120 (skip-chars-forward " \t")
3121 (setq ind1 (current-column))
3122 (if (<= ind1 ind) (throw 'exit t)))))
3123 (beginning-of-line 1)
3124 (goto-char pos)
3125 (error "Not in an item"))))
3126
3127 (defun org-move-item-down (arg)
3128 "Move the plain list item at point down, i.e. swap with following item.
3129 Subitems (items with larger indentation) are considered part of the item,
3130 so this really moves item trees."
3131 (interactive "p")
3132 (let (beg end ind ind1 (pos (point)) txt)
3133 (org-beginning-of-item)
3134 (setq beg (point))
3135 (setq ind (org-get-indentation))
3136 (org-end-of-item)
3137 (setq end (point))
3138 (setq ind1 (org-get-indentation))
3139 (if (and (org-at-item-p) (= ind ind1))
3140 (progn
3141 (org-end-of-item)
3142 (setq txt (buffer-substring beg end))
3143 (save-excursion
3144 (delete-region beg end))
3145 (setq pos (point))
3146 (insert txt)
3147 (goto-char pos)
3148 (org-maybe-renumber-ordered-list))
3149 (goto-char pos)
3150 (error "Cannot move this item further down"))))
3151
3152 (defun org-move-item-up (arg)
3153 "Move the plain list item at point up, i.e. swap with previous item.
3154 Subitems (items with larger indentation) are considered part of the item,
3155 so this really moves item trees."
3156 (interactive "p")
3157 (let (beg end ind ind1 (pos (point)) txt)
3158 (org-beginning-of-item)
3159 (setq beg (point))
3160 (setq ind (org-get-indentation))
3161 (org-end-of-item)
3162 (setq end (point))
3163 (goto-char beg)
3164 (catch 'exit
3165 (while t
3166 (beginning-of-line 0)
3167 (if (looking-at "[ \t]*$")
3168 nil
3169 (if (<= (setq ind1 (org-get-indentation)) ind)
3170 (throw 'exit t)))))
3171 (condition-case nil
3172 (org-beginning-of-item)
3173 (error (goto-char beg)
3174 (error "Cannot move this item further up")))
3175 (setq ind1 (org-get-indentation))
3176 (if (and (org-at-item-p) (= ind ind1))
3177 (progn
3178 (setq txt (buffer-substring beg end))
3179 (save-excursion
3180 (delete-region beg end))
3181 (setq pos (point))
3182 (insert txt)
3183 (goto-char pos)
3184 (org-maybe-renumber-ordered-list))
3185 (goto-char pos)
3186 (error "Cannot move this item further up"))))
3187
3188 (defun org-maybe-renumber-ordered-list ()
3189 "Renumber the ordered list at point if setup allows it.
3190 This tests the user option `org-auto-renumber-ordered-lists' before
3191 doing the renumbering."
3192 (and org-auto-renumber-ordered-lists
3193 (org-at-item-p)
3194 (match-beginning 3)
3195 (org-renumber-ordered-list 1)))
3196
3197 (defun org-get-string-indentation (s)
3198 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3199 (let ((n -1) (i 0) (w tab-width) c)
3200 (catch 'exit
3201 (while (< (setq n (1+ n)) (length s))
3202 (setq c (aref s n))
3203 (cond ((= c ?\ ) (setq i (1+ i)))
3204 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3205 (t (throw 'exit t)))))
3206 i))
3207
3208 (defun org-renumber-ordered-list (arg)
3209 "Renumber an ordered plain list.
3210 Cursor next to be in the first line of an item, the line that starts
3211 with something like \"1.\" or \"2)\"."
3212 (interactive "p")
3213 (unless (and (org-at-item-p)
3214 (match-beginning 3))
3215 (error "This is not an ordered list"))
3216 (let ((line (org-current-line))
3217 (col (current-column))
3218 (ind (org-get-string-indentation
3219 (buffer-substring (point-at-bol) (match-beginning 3))))
3220 ;; (term (substring (match-string 3) -1))
3221 ind1 (n (1- arg)))
3222 ;; find where this list begins
3223 (catch 'exit
3224 (while t
3225 (catch 'next
3226 (beginning-of-line 0)
3227 (if (looking-at "[ \t]*$") (throw 'next t))
3228 (skip-chars-forward " \t") (setq ind1 (current-column))
3229 (if (or (< ind1 ind)
3230 (and (= ind1 ind)
3231 (not (org-at-item-p))))
3232 (throw 'exit t)))))
3233 ;; Walk forward and replace these numbers
3234 (catch 'exit
3235 (while t
3236 (catch 'next
3237 (beginning-of-line 2)
3238 (if (eobp) (throw 'exit nil))
3239 (if (looking-at "[ \t]*$") (throw 'next nil))
3240 (skip-chars-forward " \t") (setq ind1 (current-column))
3241 (if (> ind1 ind) (throw 'next t))
3242 (if (< ind1 ind) (throw 'exit t))
3243 (if (not (org-at-item-p)) (throw 'exit nil))
3244 (if (not (match-beginning 3))
3245 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3246 (delete-region (match-beginning 3) (1- (match-end 3)))
3247 (goto-char (match-beginning 3))
3248 (insert (format "%d" (setq n (1+ n)))))))
3249 (goto-line line)
3250 (move-to-column col)))
3251
3252 (defvar org-last-indent-begin-marker (make-marker))
3253 (defvar org-last-indent-end-marker (make-marker))
3254
3255
3256 (defun org-outdent-item (arg)
3257 "Outdent a local list item."
3258 (interactive "p")
3259 (org-indent-item (- arg)))
3260
3261 (defun org-indent-item (arg)
3262 "Indent a local list item."
3263 (interactive "p")
3264 (unless (org-at-item-p)
3265 (error "Not on an item"))
3266 (let (beg end ind ind1)
3267 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3268 (setq beg org-last-indent-begin-marker
3269 end org-last-indent-end-marker)
3270 (org-beginning-of-item)
3271 (setq beg (move-marker org-last-indent-begin-marker (point)))
3272 (org-end-of-item)
3273 (setq end (move-marker org-last-indent-end-marker (point))))
3274 (goto-char beg)
3275 (skip-chars-forward " \t") (setq ind (current-column))
3276 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3277 (while (< (point) end)
3278 (beginning-of-line 1)
3279 (skip-chars-forward " \t") (setq ind1 (current-column))
3280 (delete-region (point-at-bol) (point))
3281 (indent-to-column (+ ind1 arg))
3282 (beginning-of-line 2))
3283 (goto-char beg)))
3284
3285 ;;; Archiving
3286
3287 (defun org-archive-subtree ()
3288 "Move the current subtree to the archive.
3289 The archive can be a certain top-level heading in the current file, or in
3290 a different file. The tree will be moved to that location, the subtree
3291 heading be marked DONE, and the current time will be added."
3292 (interactive)
3293 ;; Save all relevant TODO keyword-relatex variables
3294 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3295 (tr-org-todo-keywords org-todo-keywords)
3296 (tr-org-todo-interpretation org-todo-interpretation)
3297 (tr-org-done-string org-done-string)
3298 (tr-org-todo-regexp org-todo-regexp)
3299 (tr-org-todo-line-regexp org-todo-line-regexp)
3300 (this-buffer (current-buffer))
3301 file heading buffer level newfile-p)
3302 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3303 (progn
3304 (setq file (format (match-string 1 org-archive-location)
3305 (file-name-nondirectory (buffer-file-name)))
3306 heading (match-string 2 org-archive-location)))
3307 (error "Invalid `org-archive-location'"))
3308 (if (> (length file) 0)
3309 (setq newfile-p (not (file-exists-p file))
3310 buffer (find-file-noselect file))
3311 (setq buffer (current-buffer)))
3312 (unless buffer
3313 (error "Cannot access file \"%s\"" file))
3314 (if (and (> (length heading) 0)
3315 (string-match "^\\*+" heading))
3316 (setq level (match-end 0))
3317 (setq heading nil level 0))
3318 (save-excursion
3319 ;; We first only copy, in case something goes wrong
3320 ;; we need to protect this-command, to avoid kill-region sets it,
3321 ;; which would lead to duplication of subtrees
3322 (let (this-command) (org-copy-subtree))
3323 (set-buffer buffer)
3324 ;; Enforce org-mode for the archive buffer
3325 (if (not (eq major-mode 'org-mode))
3326 ;; Force the mode for future visits.
3327 (let ((org-insert-mode-line-in-empty-file t))
3328 (call-interactively 'org-mode)))
3329 (when newfile-p
3330 (goto-char (point-max))
3331 (insert (format "\nArchived entries from file %s\n\n"
3332 (buffer-file-name this-buffer))))
3333 ;; Force the TODO keywords of the original buffer
3334 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3335 (org-todo-keywords tr-org-todo-keywords)
3336 (org-todo-interpretation tr-org-todo-interpretation)
3337 (org-done-string tr-org-done-string)
3338 (org-todo-regexp tr-org-todo-regexp)
3339 (org-todo-line-regexp tr-org-todo-line-regexp))
3340 (goto-char (point-min))
3341 (if heading
3342 (progn
3343 (if (re-search-forward
3344 (concat "\\(^\\|\r\\)"
3345 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3346 nil t)
3347 (goto-char (match-end 0))
3348 ;; Heading not found, just insert it at the end
3349 (goto-char (point-max))
3350 (or (bolp) (insert "\n"))
3351 (insert "\n" heading "\n")
3352 (end-of-line 0))
3353 ;; Make the heading visible, and the following as well
3354 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3355 (if (re-search-forward
3356 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3357 nil t)
3358 (progn (goto-char (match-beginning 0)) (insert "\n")
3359 (beginning-of-line 0))
3360 (goto-char (point-max)) (insert "\n")))
3361 (goto-char (point-max)) (insert "\n"))
3362 ;; Paste
3363 (org-paste-subtree (1+ level))
3364 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3365 (if org-archive-mark-done
3366 (org-todo (length org-todo-keywords)))
3367 ;; Move cursor to right after the TODO keyword
3368 (when org-archive-stamp-time
3369 (beginning-of-line 1)
3370 (looking-at org-todo-line-regexp)
3371 (goto-char (or (match-end 2) (match-beginning 3)))
3372 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3373 (current-time))
3374 ")"))
3375 ;; Save the buffer, if it is not the same buffer.
3376 (if (not (eq this-buffer buffer)) (save-buffer))))
3377 ;; Here we are back in the original buffer. Everything seems to have
3378 ;; worked. So now cut the tree and finish up.
3379 (let (this-command) (org-cut-subtree))
3380 (if (looking-at "[ \t]*$") (kill-line))
3381 (message "Subtree archived %s"
3382 (if (eq this-buffer buffer)
3383 (concat "under heading: " heading)
3384 (concat "in file: " (abbreviate-file-name file))))))
3385
3386 ;;; Completion
3387
3388 (defun org-complete (&optional arg)
3389 "Perform completion on word at point.
3390 At the beginning of a headline, this completes TODO keywords as given in
3391 `org-todo-keywords'.
3392 If the current word is preceded by a backslash, completes the TeX symbols
3393 that are supported for HTML support.
3394 If the current word is preceded by \"#+\", completes special words for
3395 setting file options.
3396 At all other locations, this simply calls `ispell-complete-word'."
3397 (interactive "P")
3398 (catch 'exit
3399 (let* ((end (point))
3400 (beg1 (save-excursion
3401 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3402 (skip-chars-backward "a-zA-Z_@0-9")
3403 (point)))
3404 (beg (save-excursion
3405 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3406 (skip-chars-backward "a-zA-Z0-9_:$")
3407 (point)))
3408 (camel (equal (char-before beg) ?*))
3409 (tag (equal (char-before beg1) ?:))
3410 (texp (equal (char-before beg) ?\\))
3411 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3412 beg)
3413 "#+"))
3414 (completion-ignore-case opt)
3415 (type nil)
3416 (tbl nil)
3417 (table (cond
3418 (opt
3419 (setq type :opt)
3420 (mapcar (lambda (x)
3421 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3422 (cons (match-string 2 x) (match-string 1 x)))
3423 (org-split-string (org-get-current-options) "\n")))
3424 (texp
3425 (setq type :tex)
3426 org-html-entities)
3427 ((string-match "\\`\\*+[ \t]*\\'"
3428 (buffer-substring (point-at-bol) beg))
3429 (setq type :todo)
3430 (mapcar 'list org-todo-keywords))
3431 (camel
3432 (setq type :camel)
3433 (save-excursion
3434 (goto-char (point-min))
3435 (while (re-search-forward org-todo-line-regexp nil t)
3436 (push (list
3437 (if org-file-link-context-use-camel-case
3438 (org-make-org-heading-camel (match-string 3) t)
3439 (org-make-org-heading-search-string
3440 (match-string 3) t)))
3441 tbl)))
3442 tbl)
3443 (tag (setq type :tag beg beg1)
3444 (org-get-buffer-tags))
3445 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3446 (pattern (buffer-substring-no-properties beg end))
3447 (completion (try-completion pattern table)))
3448 (cond ((eq completion t)
3449 (if (equal type :opt)
3450 (insert (substring (cdr (assoc (upcase pattern) table))
3451 (length pattern)))))
3452 ((null completion)
3453 (message "Can't find completion for \"%s\"" pattern)
3454 (ding))
3455 ((not (string= pattern completion))
3456 (delete-region beg end)
3457 (if (string-match " +$" completion)
3458 (setq completion (replace-match "" t t completion)))
3459 (insert completion)
3460 (if (get-buffer-window "*Completions*")
3461 (delete-window (get-buffer-window "*Completions*")))
3462 (if (assoc completion table)
3463 (if (eq type :todo) (insert " ")
3464 (if (eq type :tag) (insert ":"))))
3465 (if (and (equal type :opt) (assoc completion table))
3466 (message "%s" (substitute-command-keys
3467 "Press \\[org-complete] again to insert example settings"))))
3468 (t
3469 (message "Making completion list...")
3470 (let ((list (sort (all-completions pattern table) 'string<)))
3471 (with-output-to-temp-buffer "*Completions*"
3472 (display-completion-list list)))
3473 (message "Making completion list...%s" "done"))))))
3474
3475 ;;; Comments, TODO and DEADLINE
3476
3477 (defun org-toggle-comment ()
3478 "Change the COMMENT state of an entry."
3479 (interactive)
3480 (save-excursion
3481 (org-back-to-heading)
3482 (if (looking-at (concat outline-regexp
3483 "\\( +\\<" org-comment-string "\\>\\)"))
3484 (replace-match "" t t nil 1)
3485 (if (looking-at outline-regexp)
3486 (progn
3487 (goto-char (match-end 0))
3488 (insert " " org-comment-string))))))
3489
3490 (defvar org-last-todo-state-is-todo nil
3491 "This is non-nil when the last TODO state change led to a TODO state.
3492 If the last change removed the TODO tag or switched to DONE, then
3493 this is nil.")
3494
3495 (defun org-todo (&optional arg)
3496 "Change the TODO state of an item.
3497 The state of an item is given by a keyword at the start of the heading,
3498 like
3499 *** TODO Write paper
3500 *** DONE Call mom
3501
3502 The different keywords are specified in the variable `org-todo-keywords'.
3503 By default the available states are \"TODO\" and \"DONE\".
3504 So for this example: when the item starts with TODO, it is changed to DONE.
3505 When it starts with DONE, the DONE is removed. And when neither TODO nor
3506 DONE are present, add TODO at the beginning of the heading.
3507
3508 With prefix arg, use completion to determine the new state. With numeric
3509 prefix arg, switch to that state."
3510 (interactive "P")
3511 (save-excursion
3512 (org-back-to-heading)
3513 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3514 (or (looking-at (concat " +" org-todo-regexp " *"))
3515 (looking-at " *"))
3516 (let* ((this (match-string 1))
3517 (completion-ignore-case t)
3518 (member (member this org-todo-keywords))
3519 (tail (cdr member))
3520 (state (cond
3521 ((equal arg '(4))
3522 ;; Read a state with completion
3523 (completing-read "State: " (mapcar (lambda(x) (list x))
3524 org-todo-keywords)
3525 nil t))
3526 ((eq arg 'right)
3527 (if this
3528 (if tail (car tail) nil)
3529 (car org-todo-keywords)))
3530 ((eq arg 'left)
3531 (if (equal member org-todo-keywords)
3532 nil
3533 (if this
3534 (nth (- (length org-todo-keywords) (length tail) 2)
3535 org-todo-keywords)
3536 org-done-string)))
3537 (arg
3538 ;; user requests a specific state
3539 (nth (1- (prefix-numeric-value arg))
3540 org-todo-keywords))
3541 ((null member) (car org-todo-keywords))
3542 ((null tail) nil) ;; -> first entry
3543 ((eq org-todo-interpretation 'sequence)
3544 (car tail))
3545 ((memq org-todo-interpretation '(type priority))
3546 (if (eq this-command last-command)
3547 (car tail)
3548 (if (> (length tail) 0) org-done-string nil)))
3549 (t nil)))
3550 (next (if state (concat " " state " ") " ")))
3551 (replace-match next t t)
3552 (setq org-last-todo-state-is-todo
3553 (not (equal state org-done-string)))
3554 (when org-log-done
3555 (if (equal state org-done-string)
3556 (org-log-done)
3557 (if (not this)
3558 (org-log-done t))))
3559 ;; Fixup tag positioning
3560 (and org-auto-align-tags (org-set-tags nil t))
3561 (run-hooks 'org-after-todo-state-change-hook)))
3562 ;; Fixup cursor location if close to the keyword
3563 (if (and (outline-on-heading-p)
3564 (not (bolp))
3565 (save-excursion (beginning-of-line 1)
3566 (looking-at org-todo-line-regexp))
3567 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3568 (progn
3569 (goto-char (or (match-end 2) (match-end 1)))
3570 (just-one-space))))
3571
3572 (defun org-log-done (&optional undone)
3573 "Add a time stamp logging that a TODO entry has been closed.
3574 When UNDONE is non-nil, remove such a time stamp again."
3575 (interactive)
3576 (let (beg end col)
3577 (save-excursion
3578 (org-back-to-heading t)
3579 (setq beg (point))
3580 (looking-at (concat outline-regexp " *"))
3581 (goto-char (match-end 0))
3582 (setq col (current-column))
3583 (outline-next-heading)
3584 (setq end (point))
3585 (goto-char beg)
3586 (when (re-search-forward (concat
3587 "[\r\n]\\([ \t]*"
3588 (regexp-quote org-closed-string)
3589 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3590 (delete-region (match-beginning 1) (match-end 1)))
3591 (unless undone
3592 (org-back-to-heading t)
3593 (skip-chars-forward "^\n\r")
3594 (goto-char (min (1+ (point)) (point-max)))
3595 (when (not (member (char-before) '(?\r ?\n)))
3596 (insert "\n"))
3597 (indent-to col)
3598 (insert org-closed-string " "
3599 (format-time-string
3600 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3601 (current-time))
3602 "\n")))))
3603
3604 (defun org-show-todo-tree (arg)
3605 "Make a compact tree which shows all headlines marked with TODO.
3606 The tree will show the lines where the regexp matches, and all higher
3607 headlines above the match.
3608 With \\[universal-argument] prefix, also show the DONE entries.
3609 With a numeric prefix N, construct a sparse tree for the Nth element
3610 of `org-todo-keywords'."
3611 (interactive "P")
3612 (let ((case-fold-search nil)
3613 (kwd-re
3614 (cond ((null arg) org-not-done-regexp)
3615 ((equal arg '(4)) org-todo-regexp)
3616 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3617 (regexp-quote (nth (1- (prefix-numeric-value arg))
3618 org-todo-keywords)))
3619 (t (error "Invalid prefix argument: %s" arg)))))
3620 (message "%d TODO entries found"
3621 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3622
3623 (defun org-deadline ()
3624 "Insert the DEADLINE: string to make a deadline.
3625 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3626 to modify it to the correct date."
3627 (interactive)
3628 (insert
3629 org-deadline-string " "
3630 (format-time-string (car org-time-stamp-formats)
3631 (org-read-date nil 'to-time)))
3632 (message "%s" (substitute-command-keys
3633 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3634
3635 (defun org-schedule ()
3636 "Insert the SCHEDULED: string to schedule a TODO item.
3637 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3638 to modify it to the correct date."
3639 (interactive)
3640 (insert
3641 org-scheduled-string " "
3642 (format-time-string (car org-time-stamp-formats)
3643 (org-read-date nil 'to-time)))
3644 (message "%s" (substitute-command-keys
3645 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3646
3647
3648 (defun org-occur (regexp &optional callback)
3649 "Make a compact tree which shows all matches of REGEXP.
3650 The tree will show the lines where the regexp matches, and all higher
3651 headlines above the match. It will also show the heading after the match,
3652 to make sure editing the matching entry is easy.
3653 If CALLBACK is non-nil, it is a function which is called to confirm
3654 that the match should indeed be shown."
3655 (interactive "sRegexp: ")
3656 (org-remove-occur-highlights nil nil t)
3657 (setq regexp (org-check-occur-regexp regexp))
3658 (let ((cnt 0))
3659 (save-excursion
3660 (goto-char (point-min))
3661 (hide-sublevels 1)
3662 (while (re-search-forward regexp nil t)
3663 (when (or (not callback)
3664 (save-match-data (funcall callback)))
3665 (setq cnt (1+ cnt))
3666 (org-highlight-new-match (match-beginning 0) (match-end 0))
3667 (org-show-hierarchy-above))))
3668 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
3669 nil 'local)
3670 (run-hooks 'org-occur-hook)
3671 (if (interactive-p)
3672 (message "%d match(es) for regexp %s" cnt regexp))
3673 cnt))
3674
3675 (defun org-show-hierarchy-above ()
3676 "Make sure point and the headings hierarchy above is visible."
3677 (catch 'exit
3678 (if (org-on-heading-p t)
3679 (org-flag-heading nil) ; only show the heading
3680 (and (or (org-invisible-p) (org-invisible-p2))
3681 (org-show-hidden-entry))) ; show entire entry
3682 (save-excursion
3683 (and org-show-following-heading
3684 (outline-next-heading)
3685 (org-flag-heading nil))) ; show the next heading
3686 (when org-show-hierarchy-above
3687 (save-excursion ; show all higher headings
3688 (while (and (condition-case nil
3689 (progn (org-up-heading-all 1) t)
3690 (error nil))
3691 (not (bobp)))
3692 (org-flag-heading nil))))))
3693
3694 ;; Overlay compatibility functions
3695 (defun org-make-overlay (beg end &optional buffer)
3696 (if org-xemacs-p (make-extent beg end buffer) (make-overlay beg end buffer)))
3697 (defun org-delete-overlay (ovl)
3698 (if org-xemacs-p (delete-extent ovl) (delete-overlay ovl)))
3699 (defun org-detatch-overlay (ovl)
3700 (if org-xemacs-p (detach-extent ovl) (delete-overlay ovl)))
3701 (defun org-move-overlay (ovl beg end &optional buffer)
3702 (if org-xemacs-p
3703 (set-extent-endpoints ovl beg end buffer)
3704 (move-overlay ovl beg end buffer)))
3705 (defun org-overlay-put (ovl prop value)
3706 (if org-xemacs-p
3707 (set-extent-property ovl prop value)
3708 (overlay-put ovl prop value)))
3709
3710 (defvar org-occur-highlights nil)
3711 (defun org-highlight-new-match (beg end)
3712 "Highlight from BEG to END and mark the highlight is an occur headline."
3713 (let ((ov (org-make-overlay beg end)))
3714 (org-overlay-put ov 'face 'secondary-selection)
3715 (push ov org-occur-highlights)))
3716
3717 (defun org-remove-occur-highlights (&optional beg end noremove)
3718 "Remove the occur highlights from the buffer.
3719 BEG and END are ignored. If NOREMOVE is nil, remove this function
3720 from the `before-change-functions' in the current buffer."
3721 (interactive)
3722 (mapc 'org-delete-overlay org-occur-highlights)
3723 (setq org-occur-highlights nil)
3724 (unless noremove
3725 (remove-hook 'before-change-functions
3726 'org-remove-occur-highlights 'local)))
3727
3728 ;;; Priorities
3729
3730 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3731 "Regular expression matching the priority indicator.")
3732
3733 (defvar org-remove-priority-next-time nil)
3734
3735 (defun org-priority-up ()
3736 "Increase the priority of the current item."
3737 (interactive)
3738 (org-priority 'up))
3739
3740 (defun org-priority-down ()
3741 "Decrease the priority of the current item."
3742 (interactive)
3743 (org-priority 'down))
3744
3745 (defun org-priority (&optional action)
3746 "Change the priority of an item by ARG.
3747 ACTION can be set, up, or down."
3748 (interactive)
3749 (setq action (or action 'set))
3750 (let (current new news have remove)
3751 (save-excursion
3752 (org-back-to-heading)
3753 (if (looking-at org-priority-regexp)
3754 (setq current (string-to-char (match-string 2))
3755 have t)
3756 (setq current org-default-priority))
3757 (cond
3758 ((eq action 'set)
3759 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3760 (setq new (read-char-exclusive))
3761 (cond ((equal new ?\ ) (setq remove t))
3762 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3763 (error "Priority must be between `%c' and `%c'"
3764 ?A org-lowest-priority))))
3765 ((eq action 'up)
3766 (setq new (1- current)))
3767 ((eq action 'down)
3768 (setq new (1+ current)))
3769 (t (error "Invalid action")))
3770 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3771 (setq news (format "%c" new))
3772 (if have
3773 (if remove
3774 (replace-match "" t t nil 1)
3775 (replace-match news t t nil 2))
3776 (if remove
3777 (error "No priority cookie found in line")
3778 (looking-at org-todo-line-regexp)
3779 (if (match-end 2)
3780 (progn
3781 (goto-char (match-end 2))
3782 (insert " [#" news "]"))
3783 (goto-char (match-beginning 3))
3784 (insert "[#" news "] ")))))
3785 (if remove
3786 (message "Priority removed")
3787 (message "Priority of current item set to %s" news))))
3788
3789
3790 (defun org-get-priority (s)
3791 "Find priority cookie and return priority."
3792 (save-match-data
3793 (if (not (string-match org-priority-regexp s))
3794 (* 1000 (- org-lowest-priority org-default-priority))
3795 (* 1000 (- org-lowest-priority
3796 (string-to-char (match-string 2 s)))))))
3797
3798 ;;; Timestamps
3799
3800 (defvar org-last-changed-timestamp nil)
3801
3802 (defun org-time-stamp (arg)
3803 "Prompt for a date/time and insert a time stamp.
3804 If the user specifies a time like HH:MM, or if this command is called
3805 with a prefix argument, the time stamp will contain date and time.
3806 Otherwise, only the date will be included. All parts of a date not
3807 specified by the user will be filled in from the current date/time.
3808 So if you press just return without typing anything, the time stamp
3809 will represent the current date/time. If there is already a timestamp
3810 at the cursor, it will be modified."
3811 (interactive "P")
3812 (let ((fmt (if arg (cdr org-time-stamp-formats)
3813 (car org-time-stamp-formats)))
3814 (org-time-was-given nil)
3815 time)
3816 (cond
3817 ((and (org-at-timestamp-p)
3818 (eq last-command 'org-time-stamp)
3819 (eq this-command 'org-time-stamp))
3820 (insert "--")
3821 (setq time (let ((this-command this-command))
3822 (org-read-date arg 'totime)))
3823 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3824 (insert (format-time-string fmt time)))
3825 ((org-at-timestamp-p)
3826 (setq time (let ((this-command this-command))
3827 (org-read-date arg 'totime)))
3828 (and (org-at-timestamp-p) (replace-match
3829 (setq org-last-changed-timestamp
3830 (format-time-string fmt time))
3831 t t))
3832 (message "Timestamp updated"))
3833 (t
3834 (setq time (let ((this-command this-command))
3835 (org-read-date arg 'totime)))
3836 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3837 (insert (format-time-string fmt time))))))
3838
3839 (defun org-time-stamp-inactive (&optional arg)
3840 "Insert an inactive time stamp.
3841 An inactive time stamp is enclosed in square brackets instead of angle
3842 brackets. It is inactive in the sense that it does not trigger agenda entries,
3843 does not link to the calendar and cannot be changed with the S-cursor keys.
3844 So these are more for recording a certain time/date."
3845 ;; FIXME: Would it be better not to ask for a date/time here?
3846 (interactive "P")
3847 (let ((fmt (if arg (cdr org-time-stamp-formats)
3848 (car org-time-stamp-formats)))
3849 (org-time-was-given nil)
3850 time)
3851 (setq time (org-read-date arg 'totime))
3852 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3853 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3854 (insert (format-time-string fmt time))))
3855
3856 (defvar org-date-ovl (org-make-overlay 1 1))
3857 (org-overlay-put org-date-ovl 'face 'org-warning)
3858 (org-detatch-overlay org-date-ovl)
3859
3860 ;;; FIXME: Make the function take "Fri" as "next friday"
3861 ;;; because these are mostly being used to record the current time.
3862 (defun org-read-date (&optional with-time to-time)
3863 "Read a date and make things smooth for the user.
3864 The prompt will suggest to enter an ISO date, but you can also enter anything
3865 which will at least partially be understood by `parse-time-string'.
3866 Unrecognized parts of the date will default to the current day, month, year,
3867 hour and minute. For example,
3868 3-2-5 --> 2003-02-05
3869 feb 15 --> currentyear-02-15
3870 sep 12 9 --> 2009-09-12
3871 12:45 --> today 12:45
3872 22 sept 0:34 --> currentyear-09-22 0:34
3873 12 --> currentyear-currentmonth-12
3874 etc.
3875 The function understands only English month and weekday abbreviations,
3876 but this can be configured with the variables `parse-time-months' and
3877 `parse-time-weekdays'.
3878
3879 While prompting, a calendar is popped up - you can also select the
3880 date with the mouse (button 1). The calendar shows a period of three
3881 months. To scroll it to other months, use the keys `>' and `<'.
3882 If you don't like the calendar, turn it off with
3883 \(setq org-popup-calendar-for-date-prompt nil)
3884
3885 With optional argument TO-TIME, the date will immediately be converted
3886 to an internal time.
3887 With an optional argument WITH-TIME, the prompt will suggest to also
3888 insert a time. Note that when WITH-TIME is not set, you can still
3889 enter a time, and this function will inform the calling routine about
3890 this change. The calling routine may then choose to change the format
3891 used to insert the time stamp into the buffer to include the time."
3892 (require 'parse-time)
3893 (let* ((default-time
3894 ;; Default time is either today, or, when entering a range,
3895 ;; the range start.
3896 (if (save-excursion
3897 (re-search-backward
3898 (concat org-ts-regexp "--\\=")
3899 (- (point) 20) t))
3900 (apply
3901 'encode-time
3902 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3903 (parse-time-string (match-string 1))))
3904 (current-time)))
3905 (calendar-move-hook nil)
3906 (view-diary-entries-initially nil)
3907 (timestr (format-time-string
3908 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3909 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3910 ans ans1 ans2
3911 second minute hour day month year tl)
3912
3913 (if org-popup-calendar-for-date-prompt
3914 ;; Also show a calendar for date selection
3915 ;; Copied (with modifications) from planner.el by John Wiegley
3916 (save-excursion
3917 (save-window-excursion
3918 (calendar)
3919 (calendar-forward-day (- (time-to-days default-time)
3920 (calendar-absolute-from-gregorian
3921 (calendar-current-date))))
3922 (org-eval-in-calendar nil)
3923 (let* ((old-map (current-local-map))
3924 (map (copy-keymap calendar-mode-map))
3925 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3926 (define-key map (kbd "RET") 'org-calendar-select)
3927 (define-key map (if org-xemacs-p [button1] [mouse-1])
3928 'org-calendar-select-mouse)
3929 (define-key map (if org-xemacs-p [button2] [mouse-2])
3930 'org-calendar-select-mouse)
3931 (define-key minibuffer-local-map [(meta shift left)]
3932 (lambda () (interactive)
3933 (org-eval-in-calendar '(calendar-backward-month 1))))
3934 (define-key minibuffer-local-map [(meta shift right)]
3935 (lambda () (interactive)
3936 (org-eval-in-calendar '(calendar-forward-month 1))))
3937 (define-key minibuffer-local-map [(shift up)]
3938 (lambda () (interactive)
3939 (org-eval-in-calendar '(calendar-backward-week 1))))
3940 (define-key minibuffer-local-map [(shift down)]
3941 (lambda () (interactive)
3942 (org-eval-in-calendar '(calendar-forward-week 1))))
3943 (define-key minibuffer-local-map [(shift left)]
3944 (lambda () (interactive)
3945 (org-eval-in-calendar '(calendar-backward-day 1))))
3946 (define-key minibuffer-local-map [(shift right)]
3947 (lambda () (interactive)
3948 (org-eval-in-calendar '(calendar-forward-day 1))))
3949 (define-key minibuffer-local-map ">"
3950 (lambda () (interactive)
3951 (org-eval-in-calendar '(scroll-calendar-left 1))))
3952 (define-key minibuffer-local-map "<"
3953 (lambda () (interactive)
3954 (org-eval-in-calendar '(scroll-calendar-right 1))))
3955 (unwind-protect
3956 (progn
3957 (use-local-map map)
3958 (setq ans (read-string prompt "" nil nil))
3959 (if (not (string-match "\\S-" ans)) (setq ans nil))
3960 (setq ans (or ans1 ans ans2)))
3961 (use-local-map old-map)))))
3962 ;; Naked prompt only
3963 (setq ans (read-string prompt "" nil timestr)))
3964 (org-detatch-overlay org-date-ovl)
3965
3966 (if (string-match
3967 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3968 (progn
3969 (setq year (if (match-end 2)
3970 (string-to-number (match-string 2 ans))
3971 (string-to-number (format-time-string "%Y")))
3972 month (string-to-number (match-string 3 ans))
3973 day (string-to-number (match-string 4 ans)))
3974 (if (< year 100) (setq year (+ 2000 year)))
3975 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3976 t t ans))))
3977 (setq tl (parse-time-string ans)
3978 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3979 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3980 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3981 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3982 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3983 second (or (nth 0 tl) 0))
3984 (if (and (boundp 'org-time-was-given)
3985 (nth 2 tl))
3986 (setq org-time-was-given t))
3987 (if (< year 100) (setq year (+ 2000 year)))
3988 (if to-time
3989 (encode-time second minute hour day month year)
3990 (if (or (nth 1 tl) (nth 2 tl))
3991 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3992 (format "%04d-%02d-%02d" year month day)))))
3993
3994 (defun org-eval-in-calendar (form)
3995 "Eval FORM in the calendar window and return to current window.
3996 Also, store the cursor date in variable ans2."
3997 (let ((sw (selected-window)))
3998 (select-window (get-buffer-window "*Calendar*"))
3999 (eval form)
4000 (when (calendar-cursor-to-date)
4001 (let* ((date (calendar-cursor-to-date))
4002 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4003 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4004 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4005 (select-window sw)))
4006
4007 (defun org-calendar-select ()
4008 "Return to `org-read-date' with the date currently selected.
4009 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4010 (interactive)
4011 (when (calendar-cursor-to-date)
4012 (let* ((date (calendar-cursor-to-date))
4013 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4014 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4015 (if (active-minibuffer-window) (exit-minibuffer))))
4016
4017 (defun org-calendar-select-mouse (ev)
4018 "Return to `org-read-date' with the date currently selected.
4019 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4020 (interactive "e")
4021 (mouse-set-point ev)
4022 (when (calendar-cursor-to-date)
4023 (let* ((date (calendar-cursor-to-date))
4024 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4025 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4026 (if (active-minibuffer-window) (exit-minibuffer))))
4027
4028 (defun org-check-deadlines (ndays)
4029 "Check if there are any deadlines due or past due.
4030 A deadline is considered due if it happens within `org-deadline-warning-days'
4031 days from today's date. If the deadline appears in an entry marked DONE,
4032 it is not shown. The prefix arg NDAYS can be used to test that many
4033 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4034 (interactive "P")
4035 (let* ((org-warn-days
4036 (cond
4037 ((equal ndays '(4)) 100000)
4038 (ndays (prefix-numeric-value ndays))
4039 (t org-deadline-warning-days)))
4040 (case-fold-search nil)
4041 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4042 (callback
4043 (lambda ()
4044 (and (let ((d1 (time-to-days (current-time)))
4045 (d2 (time-to-days
4046 (org-time-string-to-time (match-string 1)))))
4047 (< (- d2 d1) org-warn-days))
4048 (not (org-entry-is-done-p))))))
4049 (message "%d deadlines past-due or due within %d days"
4050 (org-occur regexp callback)
4051 org-warn-days)))
4052
4053 (defun org-evaluate-time-range (&optional to-buffer)
4054 "Evaluate a time range by computing the difference between start and end.
4055 Normally the result is just printed in the echo area, but with prefix arg
4056 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4057 If the time range is actually in a table, the result is inserted into the
4058 next column.
4059 For time difference computation, a year is assumed to be exactly 365
4060 days in order to avoid rounding problems."
4061 (interactive "P")
4062 (save-excursion
4063 (unless (org-at-date-range-p)
4064 (goto-char (point-at-bol))
4065 (re-search-forward org-tr-regexp (point-at-eol) t))
4066 (if (not (org-at-date-range-p))
4067 (error "Not at a time-stamp range, and none found in current line")))
4068 (let* ((ts1 (match-string 1))
4069 (ts2 (match-string 2))
4070 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4071 (match-end (match-end 0))
4072 (time1 (org-time-string-to-time ts1))
4073 (time2 (org-time-string-to-time ts2))
4074 (t1 (time-to-seconds time1))
4075 (t2 (time-to-seconds time2))
4076 (diff (abs (- t2 t1)))
4077 (negative (< (- t2 t1) 0))
4078 ;; (ys (floor (* 365 24 60 60)))
4079 (ds (* 24 60 60))
4080 (hs (* 60 60))
4081 (fy "%dy %dd %02d:%02d")
4082 (fy1 "%dy %dd")
4083 (fd "%dd %02d:%02d")
4084 (fd1 "%dd")
4085 (fh "%02d:%02d")
4086 y d h m align)
4087 ;; FIXME: Should I re-introduce years, make year refer to same date?
4088 ;; This would be the only useful way to have years, actually.
4089 (if havetime
4090 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4091 y 0
4092 d (floor (/ diff ds)) diff (mod diff ds)
4093 h (floor (/ diff hs)) diff (mod diff hs)
4094 m (floor (/ diff 60)))
4095 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4096 y 0
4097 d (floor (+ (/ diff ds) 0.5))
4098 h 0 m 0))
4099 (if (not to-buffer)
4100 (message (org-make-tdiff-string y d h m))
4101 (when (org-at-table-p)
4102 (goto-char match-end)
4103 (setq align t)
4104 (and (looking-at " *|") (goto-char (match-end 0))))
4105 (if (looking-at
4106 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4107 (replace-match ""))
4108 (if negative (insert " -"))
4109 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4110 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4111 (insert " " (format fh h m))))
4112 (if align (org-table-align))
4113 (message "Time difference inserted"))))
4114
4115 (defun org-make-tdiff-string (y d h m)
4116 (let ((fmt "")
4117 (l nil))
4118 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4119 l (push y l)))
4120 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4121 l (push d l)))
4122 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4123 l (push h l)))
4124 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4125 l (push m l)))
4126 (apply 'format fmt (nreverse l))))
4127
4128 (defun org-time-string-to-time (s)
4129 (apply 'encode-time (org-parse-time-string s)))
4130
4131 (defun org-parse-time-string (s &optional nodefault)
4132 "Parse the standard Org-mode time string.
4133 This should be a lot faster than the normal `parse-time-string'.
4134 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4135 hour and minute fields will be nil if not given."
4136 (if (string-match org-ts-regexp1 s)
4137 (list 0
4138 (if (or (match-beginning 8) (not nodefault))
4139 (string-to-number (or (match-string 8 s) "0")))
4140 (if (or (match-beginning 7) (not nodefault))
4141 (string-to-number (or (match-string 7 s) "0")))
4142 (string-to-number (match-string 4 s))
4143 (string-to-number (match-string 3 s))
4144 (string-to-number (match-string 2 s))
4145 nil nil nil)
4146 (make-list 9 0)))
4147
4148 (defun org-timestamp-up (&optional arg)
4149 "Increase the date item at the cursor by one.
4150 If the cursor is on the year, change the year. If it is on the month or
4151 the day, change that.
4152 With prefix ARG, change by that many units."
4153 (interactive "p")
4154 (org-timestamp-change (prefix-numeric-value arg)))
4155
4156 (defun org-timestamp-down (&optional arg)
4157 "Decrease the date item at the cursor by one.
4158 If the cursor is on the year, change the year. If it is on the month or
4159 the day, change that.
4160 With prefix ARG, change by that many units."
4161 (interactive "p")
4162 (org-timestamp-change (- (prefix-numeric-value arg))))
4163
4164 (defun org-timestamp-up-day (&optional arg)
4165 "Increase the date in the time stamp by one day.
4166 With prefix ARG, change that many days."
4167 (interactive "p")
4168 (if (and (not (org-at-timestamp-p))
4169 (org-on-heading-p))
4170 (org-todo 'up)
4171 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4172
4173 (defun org-timestamp-down-day (&optional arg)
4174 "Decrease the date in the time stamp by one day.
4175 With prefix ARG, change that many days."
4176 (interactive "p")
4177 (if (and (not (org-at-timestamp-p))
4178 (org-on-heading-p))
4179 (org-todo 'down)
4180 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4181
4182 (defsubst org-pos-in-match-range (pos n)
4183 (and (match-beginning n)
4184 (<= (match-beginning n) pos)
4185 (>= (match-end n) pos)))
4186
4187 (defun org-at-timestamp-p ()
4188 "Determine if the cursor is in or at a timestamp."
4189 (interactive)
4190 (let* ((tsr org-ts-regexp2)
4191 (pos (point))
4192 (ans (or (looking-at tsr)
4193 (save-excursion
4194 (skip-chars-backward "^<\n\r\t")
4195 (if (> (point) 1) (backward-char 1))
4196 (and (looking-at tsr)
4197 (> (- (match-end 0) pos) -1))))))
4198 (and (boundp 'org-ts-what)
4199 (setq org-ts-what
4200 (cond
4201 ((org-pos-in-match-range pos 2) 'year)
4202 ((org-pos-in-match-range pos 3) 'month)
4203 ((org-pos-in-match-range pos 7) 'hour)
4204 ((org-pos-in-match-range pos 8) 'minute)
4205 ((or (org-pos-in-match-range pos 4)
4206 (org-pos-in-match-range pos 5)) 'day)
4207 (t 'day))))
4208 ans))
4209
4210 (defun org-timestamp-change (n &optional what)
4211 "Change the date in the time stamp at point.
4212 The date will be changed by N times WHAT. WHAT can be `day', `month',
4213 `year', `minute', `second'. If WHAT is not given, the cursor position
4214 in the timestamp determines what will be changed."
4215 (let ((fmt (car org-time-stamp-formats))
4216 org-ts-what
4217 (pos (point))
4218 ts time time0)
4219 (if (not (org-at-timestamp-p))
4220 (error "Not at a timestamp"))
4221 (setq org-ts-what (or what org-ts-what))
4222 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4223 (- (match-end 0) (match-beginning 0))))
4224 1)
4225 (cdr org-time-stamp-formats)
4226 (car org-time-stamp-formats)))
4227 (setq ts (match-string 0))
4228 (replace-match "")
4229 (setq time0 (org-parse-time-string ts))
4230 (setq time
4231 (apply 'encode-time
4232 (append
4233 (list (or (car time0) 0))
4234 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4235 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4236 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4237 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4238 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4239 (nthcdr 6 time0))))
4240 (if (eq what 'calendar)
4241 (let ((cal-date
4242 (save-excursion
4243 (save-match-data
4244 (set-buffer "*Calendar*")
4245 (calendar-cursor-to-date)))))
4246 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4247 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4248 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4249 (setcar time0 (or (car time0) 0))
4250 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4251 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4252 (setq time (apply 'encode-time time0))))
4253 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4254 (goto-char pos)
4255 ;; Try to recenter the calendar window, if any
4256 (if (and org-calendar-follow-timestamp-change
4257 (get-buffer-window "*Calendar*" t)
4258 (memq org-ts-what '(day month year)))
4259 (org-recenter-calendar (time-to-days time)))))
4260
4261 (defun org-recenter-calendar (date)
4262 "If the calendar is visible, recenter it to DATE."
4263 (let* ((win (selected-window))
4264 (cwin (get-buffer-window "*Calendar*" t))
4265 (calendar-move-hook nil))
4266 (when cwin
4267 (select-window cwin)
4268 (calendar-goto-date (if (listp date) date
4269 (calendar-gregorian-from-absolute date)))
4270 (select-window win))))
4271
4272 (defun org-goto-calendar (&optional arg)
4273 "Go to the Emacs calendar at the current date.
4274 If there is a time stamp in the current line, go to that date.
4275 A prefix ARG can be used to force the current date."
4276 (interactive "P")
4277 (let ((tsr org-ts-regexp) diff
4278 (calendar-move-hook nil)
4279 (view-diary-entries-initially nil))
4280 (if (or (org-at-timestamp-p)
4281 (save-excursion
4282 (beginning-of-line 1)
4283 (looking-at (concat ".*" tsr))))
4284 (let ((d1 (time-to-days (current-time)))
4285 (d2 (time-to-days
4286 (org-time-string-to-time (match-string 1)))))
4287 (setq diff (- d2 d1))))
4288 (calendar)
4289 (calendar-goto-today)
4290 (if (and diff (not arg)) (calendar-forward-day diff))))
4291
4292 (defun org-date-from-calendar ()
4293 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4294 If there is already a time stamp at the cursor position, update it."
4295 (interactive)
4296 (org-timestamp-change 0 'calendar))
4297
4298 ;;; Agenda, and Diary Integration
4299
4300 ;;; Define the mode
4301
4302 (defvar org-agenda-mode-map (make-sparse-keymap)
4303 "Keymap for `org-agenda-mode'.")
4304
4305 (defvar org-agenda-menu)
4306 (defvar org-agenda-follow-mode nil)
4307 (defvar org-agenda-show-log nil)
4308 (defvar org-agenda-buffer-name "*Org Agenda*")
4309 (defvar org-agenda-redo-command nil)
4310 (defvar org-agenda-mode-hook nil)
4311 (defvar org-agenda-type nil)
4312 (defvar org-agenda-force-single-file nil)
4313
4314 ;;;###autoload
4315 (defun org-agenda-mode ()
4316 "Mode for time-sorted view on action items in Org-mode files.
4317
4318 The following commands are available:
4319
4320 \\{org-agenda-mode-map}"
4321 (interactive)
4322 (kill-all-local-variables)
4323 (setq major-mode 'org-agenda-mode)
4324 (setq mode-name "Org-Agenda")
4325 (use-local-map org-agenda-mode-map)
4326 (easy-menu-add org-agenda-menu)
4327 (if org-startup-truncated (setq truncate-lines t))
4328 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4329 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4330 (unless org-agenda-keep-modes
4331 (setq org-agenda-follow-mode nil
4332 org-agenda-show-log nil))
4333 (easy-menu-change
4334 '("Agenda") "Agenda Files"
4335 (append
4336 (list
4337 (vector
4338 (if (get 'org-agenda-files 'org-restrict)
4339 "Restricted to single file"
4340 "Edit File List")
4341 '(customize-variable 'org-agenda-files)
4342 (not (get 'org-agenda-files 'org-restrict)))
4343 "--")
4344 (mapcar 'org-file-menu-entry (org-agenda-files))))
4345 (org-agenda-set-mode-name)
4346 (apply
4347 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4348 (list 'org-agenda-mode-hook)))
4349
4350 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4351 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4352 (define-key org-agenda-mode-map " " 'org-agenda-show)
4353 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4354 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4355 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4356 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4357 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4358 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4359 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4360 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4361 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4362 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4363 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4364 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4365
4366 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4367 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4368 (while l (define-key org-agenda-mode-map
4369 (int-to-string (pop l)) 'digit-argument)))
4370
4371 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4372 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4373 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4374 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4375 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4376 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4377 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4378 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4379 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4380 (define-key org-agenda-mode-map "n" 'next-line)
4381 (define-key org-agenda-mode-map "p" 'previous-line)
4382 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4383 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4384 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4385 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4386 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4387 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4388 (eval-after-load "calendar"
4389 '(define-key calendar-mode-map org-calendar-to-agenda-key
4390 'org-calendar-goto-agenda))
4391 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4392 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4393 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4394 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4395 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4396 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4397 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4398 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4399 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4400 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4401 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4402 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4403 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4404 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4405 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4406 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4407 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4408 "Local keymap for agenda entries from Org-mode.")
4409
4410 (define-key org-agenda-keymap
4411 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4412 (define-key org-agenda-keymap
4413 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4414 (define-key org-agenda-keymap [follow-link] 'mouse-face)
4415 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4416 '("Agenda"
4417 ("Agenda Files")
4418 "--"
4419 ["Show" org-agenda-show t]
4420 ["Go To (other window)" org-agenda-goto t]
4421 ["Go To (one window)" org-agenda-switch-to t]
4422 ["Follow Mode" org-agenda-follow-mode
4423 :style toggle :selected org-agenda-follow-mode :active t]
4424 "--"
4425 ["Cycle TODO" org-agenda-todo t]
4426 ("Tags"
4427 ["Show all Tags" org-agenda-show-tags t]
4428 ["Set Tags" org-agenda-set-tags t])
4429 ("Reschedule"
4430 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4431 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4432 "--"
4433 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4434 ("Priority"
4435 ["Set Priority" org-agenda-priority t]
4436 ["Increase Priority" org-agenda-priority-up t]
4437 ["Decrease Priority" org-agenda-priority-down t]
4438 ["Show Priority" org-agenda-show-priority t])
4439 "--"
4440 ;; ["New agenda command" org-agenda t]
4441 ["Rebuild buffer" org-agenda-redo t]
4442 "--"
4443 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4444 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4445 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4446 "--"
4447 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4448 :style radio :selected (equal org-agenda-ndays 1)]
4449 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4450 :style radio :selected (equal org-agenda-ndays 7)]
4451 "--"
4452 ["Show Logbook entries" org-agenda-log-mode
4453 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4454 ["Include Diary" org-agenda-toggle-diary
4455 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4456 ["Use Time Grid" org-agenda-toggle-time-grid
4457 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4458 "--"
4459 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4460 ("Calendar Commands"
4461 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4462 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4463 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4464 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4465 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4466 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4467 "--"
4468 ["Quit" org-agenda-quit t]
4469 ["Exit and Release Buffers" org-agenda-exit t]
4470 ))
4471
4472 ;;;###autoload
4473 (defun org-agenda (arg)
4474 "Dispatch agenda commands to collect entries to the agenda buffer.
4475 Prompts for a character to select a command. Any prefix arg will be passed
4476 on to the selected command. The default selections are:
4477
4478 a Call `org-agenda' to display the agenda for the current day or week.
4479 t Call `org-todo-list' to display the global todo list.
4480 T Call `org-todo-list' to display the global todo list, select only
4481 entries with a specific TODO keyword (the user gets a prompt).
4482 m Call `org-tags-view' to display headlines with tags matching
4483 a condition (the user is prompted for the condition).
4484 M Like `m', but select only TODO entries, no ordinary headlines.
4485
4486 More commands can be added by configuring the variable
4487 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4488 searches can be pre-defined in this way.
4489
4490 If the current buffer is in Org-mode and visiting a file, you can also
4491 first press `1' to indicate that the agenda should be temporarily (until the
4492 next use of \\[org-agenda]) restricted to the current file."
4493 (interactive "P")
4494 (catch 'exit
4495 (let ((restrict-ok (and (buffer-file-name) (eq major-mode 'org-mode)))
4496 (custom org-agenda-custom-commands)
4497 c entry key type string)
4498 (put 'org-agenda-files 'org-restrict nil)
4499 (save-window-excursion
4500 (delete-other-windows)
4501 (switch-to-buffer-other-window " *Agenda Commands*")
4502 (erase-buffer)
4503 (insert
4504 "Press key for an agenda command:
4505 --------------------------------
4506 a Agenda for current week or day
4507 t List of all TODO entries T Entries with special TODO kwd
4508 m Match a TAGS query M Like m, but only TODO entries
4509 C Configure your own agenda commands")
4510 (while (setq entry (pop custom))
4511 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4512 (insert (format "\n%-4s%-14s: %s"
4513 key
4514 (cond
4515 ((eq type 'tags) "Tags query")
4516 ((eq type 'todo) "TODO keyword")
4517 ((eq type 'tags-tree) "Tags tree")
4518 ((eq type 'todo-tree) "TODO kwd tree")
4519 ((eq type 'occur-tree) "Occur tree")
4520 (t "???"))
4521 (org-string-props string 'face 'org-link))))
4522 (goto-char (point-min))
4523 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4524 (message "Press key for agenda command%s"
4525 (if restrict-ok ", or [1] to restrict to current file" ""))
4526 (setq c (read-char-exclusive))
4527 (message "")
4528 (when (equal c ?1)
4529 (if restrict-ok
4530 (put 'org-agenda-files 'org-restrict (list (buffer-file-name)))
4531 (error "Cannot restrict agenda to current buffer"))
4532 (message "Press key for agenda command%s"
4533 (if restrict-ok " (restricted to current file)" ""))
4534 (setq c (read-char-exclusive))
4535 (message "")))
4536 (require 'calendar) ; FIXME: can we avoid this for some commands?
4537 ;; For example the todo list should not need it (but does...)
4538 (cond
4539 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4540 ((equal c ?a) (call-interactively 'org-agenda-list))
4541 ((equal c ?t) (call-interactively 'org-todo-list))
4542 ((equal c ?T)
4543 (setq current-prefix-arg (or arg '(4)))
4544 (call-interactively 'org-todo-list))
4545 ((equal c ?m) (call-interactively 'org-tags-view))
4546 ((equal c ?M)
4547 (setq current-prefix-arg (or arg '(4)))
4548 (call-interactively 'org-tags-view))
4549 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4550 (setq type (nth 1 entry) string (nth 2 entry))
4551 (cond
4552 ((eq type 'tags)
4553 (org-tags-view current-prefix-arg string))
4554 ((eq type 'todo)
4555 (org-todo-list string))
4556 ((eq type 'tags-tree)
4557 (org-check-for-org-mode)
4558 (org-tags-sparse-tree current-prefix-arg string))
4559 ((eq type 'todo-tree)
4560 (org-check-for-org-mode)
4561 (org-occur (concat "^" outline-regexp "[ \t]*"
4562 (regexp-quote string) "\\>")))
4563 ((eq type 'occur-tree)
4564 (org-check-for-org-mode)
4565 (org-occur string))
4566 (t (error "Invalid custom agenda command type %s" type))))
4567 (t (error "Invalid key"))))))
4568
4569 (defun org-check-for-org-mode ()
4570 "Make sure current buffer is in org-mode. Error if not."
4571 (or (eq major-mode 'org-mode)
4572 (error "Cannot execute org-mode agenda command on buffer in %s."
4573 major-mode)))
4574
4575 (defun org-fit-agenda-window ()
4576 "Fit the window to the buffer size."
4577 (and org-fit-agenda-window
4578 (fboundp 'fit-window-to-buffer)
4579 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4580 (/ (frame-height) 2))))
4581
4582 (defun org-agenda-files ()
4583 "Get the list of agenda files."
4584 (or (get 'org-agenda-files 'org-restrict)
4585 org-agenda-files))
4586
4587 (defvar org-agenda-markers nil
4588 "List of all currently active markers created by `org-agenda'.")
4589 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4590 "Creation time of the last agenda marker.")
4591
4592 (defun org-agenda-new-marker (&optional pos)
4593 "Return a new agenda marker.
4594 Org-mode keeps a list of these markers and resets them when they are
4595 no longer in use."
4596 (let ((m (copy-marker (or pos (point)))))
4597 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4598 (push m org-agenda-markers)
4599 m))
4600
4601 (defun org-agenda-maybe-reset-markers (&optional force)
4602 "Reset markers created by `org-agenda'. But only if they are old enough."
4603 (if (or force
4604 (> (- (time-to-seconds (current-time))
4605 org-agenda-last-marker-time)
4606 5))
4607 (while org-agenda-markers
4608 (move-marker (pop org-agenda-markers) nil))))
4609
4610 (defvar org-agenda-new-buffers nil
4611 "Buffers created to visit agenda files.")
4612
4613 (defun org-get-agenda-file-buffer (file)
4614 "Get a buffer visiting FILE. If the buffer needs to be created, add
4615 it to the list of buffers which might be released later."
4616 (let ((buf (find-buffer-visiting file)))
4617 (if buf
4618 buf ; just return it
4619 ;; Make a new buffer and remember it
4620 (setq buf (find-file-noselect file))
4621 (if buf (push buf org-agenda-new-buffers))
4622 buf)))
4623
4624 (defun org-release-buffers (blist)
4625 "Release all buffers in list, asking the user for confirmation when needed.
4626 When a buffer is unmodified, it is just killed. When modified, it is saved
4627 \(if the user agrees) and then killed."
4628 (let (buf file)
4629 (while (setq buf (pop blist))
4630 (setq file (buffer-file-name buf))
4631 (when (and (buffer-modified-p buf)
4632 file
4633 (y-or-n-p (format "Save file %s? " file)))
4634 (with-current-buffer buf (save-buffer)))
4635 (kill-buffer buf))))
4636
4637 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4638
4639 (defun org-timeline (&optional include-all keep-modes)
4640 "Show a time-sorted view of the entries in the current org file.
4641 Only entries with a time stamp of today or later will be listed. With
4642 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4643 under the current date.
4644 If the buffer contains an active region, only check the region for
4645 dates."
4646 (interactive "P")
4647 (require 'calendar)
4648 (org-agenda-maybe-reset-markers 'force)
4649 (org-compile-prefix-format org-timeline-prefix-format)
4650 (let* ((dopast t)
4651 (dotodo include-all)
4652 (doclosed org-agenda-show-log)
4653 (org-agenda-keep-modes keep-modes)
4654 (entry (buffer-file-name))
4655 (org-agenda-files (list (buffer-file-name)))
4656 (date (calendar-current-date))
4657 (win (selected-window))
4658 (pos1 (point))
4659 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4660 (end (if (org-region-active-p) (region-end) (point-max)))
4661 (day-numbers (org-get-all-dates beg end 'no-ranges
4662 t doclosed)) ; always include today
4663 (today (time-to-days (current-time)))
4664 (org-respect-restriction t)
4665 (past t)
4666 args
4667 s e rtn d)
4668 (setq org-agenda-redo-command
4669 (list 'progn
4670 (list 'switch-to-buffer-other-window (current-buffer))
4671 (list 'org-timeline (list 'quote include-all) t)))
4672 (if (not dopast)
4673 ;; Remove past dates from the list of dates.
4674 (setq day-numbers (delq nil (mapcar (lambda(x)
4675 (if (>= x today) x nil))
4676 day-numbers))))
4677 (switch-to-buffer-other-window
4678 (get-buffer-create org-agenda-buffer-name))
4679 (setq buffer-read-only nil)
4680 (erase-buffer)
4681 (org-agenda-mode) (setq buffer-read-only nil)
4682 (set (make-local-variable 'org-agenda-type) 'timeline)
4683 (if doclosed (push :closed args))
4684 (push :timestamp args)
4685 (if dotodo (push :todo args))
4686 (while (setq d (pop day-numbers))
4687 (if (and (>= d today)
4688 dopast
4689 past)
4690 (progn
4691 (setq past nil)
4692 (insert (make-string 79 ?-) "\n")))
4693 (setq date (calendar-gregorian-from-absolute d))
4694 (setq s (point))
4695 (setq rtn (apply 'org-agenda-get-day-entries
4696 entry date args))
4697 (if (or rtn (equal d today))
4698 (progn
4699 (insert (calendar-day-name date) " "
4700 (number-to-string (extract-calendar-day date)) " "
4701 (calendar-month-name (extract-calendar-month date)) " "
4702 (number-to-string (extract-calendar-year date)) "\n")
4703 (put-text-property s (1- (point)) 'face
4704 'org-link)
4705 (if (equal d today)
4706 (put-text-property s (1- (point)) 'org-today t))
4707 (insert (org-finalize-agenda-entries rtn) "\n")
4708 (put-text-property s (1- (point)) 'day d))))
4709 (goto-char (point-min))
4710 (setq buffer-read-only t)
4711 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4712 (point-min)))
4713 (when (not org-select-timeline-window)
4714 (select-window win)
4715 (goto-char pos1))))
4716
4717 ;;;###autoload
4718 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4719 "Produce a weekly view from all files in variable `org-agenda-files'.
4720 The view will be for the current week, but from the overview buffer you
4721 will be able to go to other weeks.
4722 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4723 also be shown, under the current date.
4724 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4725 on the days are also shown. See the variable `org-log-done' for how
4726 to turn on logging.
4727 START-DAY defaults to TODAY, or to the most recent match for the weekday
4728 given in `org-agenda-start-on-weekday'.
4729 NDAYS defaults to `org-agenda-ndays'."
4730 (interactive "P")
4731 (org-agenda-maybe-reset-markers 'force)
4732 (org-compile-prefix-format org-agenda-prefix-format)
4733 (require 'calendar)
4734 (let* ((org-agenda-start-on-weekday
4735 (if (or (equal ndays 1)
4736 (and (null ndays) (equal 1 org-agenda-ndays)))
4737 nil org-agenda-start-on-weekday))
4738 (org-agenda-keep-modes keep-modes)
4739 (files (copy-sequence (org-agenda-files)))
4740 (win (selected-window))
4741 (today (time-to-days (current-time)))
4742 (sd (or start-day today))
4743 (start (if (or (null org-agenda-start-on-weekday)
4744 (< org-agenda-ndays 7))
4745 sd
4746 (let* ((nt (calendar-day-of-week
4747 (calendar-gregorian-from-absolute sd)))
4748 (n1 org-agenda-start-on-weekday)
4749 (d (- nt n1)))
4750 (- sd (+ (if (< d 0) 7 0) d)))))
4751 (day-numbers (list start))
4752 (inhibit-redisplay t)
4753 s e rtn rtnall file date d start-pos end-pos todayp nd)
4754 (setq org-agenda-redo-command
4755 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4756 ;; Make the list of days
4757 (setq ndays (or ndays org-agenda-ndays)
4758 nd ndays)
4759 (while (> ndays 1)
4760 (push (1+ (car day-numbers)) day-numbers)
4761 (setq ndays (1- ndays)))
4762 (setq day-numbers (nreverse day-numbers))
4763 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4764 (progn
4765 (delete-other-windows)
4766 (switch-to-buffer-other-window
4767 (get-buffer-create org-agenda-buffer-name))))
4768 (setq buffer-read-only nil)
4769 (erase-buffer)
4770 (org-agenda-mode) (setq buffer-read-only nil)
4771 (set (make-local-variable 'org-agenda-type) 'agenda)
4772 (set (make-local-variable 'starting-day) (car day-numbers))
4773 (set (make-local-variable 'include-all-loc) include-all)
4774 (when (and (or include-all org-agenda-include-all-todo)
4775 (member today day-numbers))
4776 (setq files (org-agenda-files)
4777 rtnall nil)
4778 (while (setq file (pop files))
4779 (catch 'nextfile
4780 (org-check-agenda-file file)
4781 (setq date (calendar-gregorian-from-absolute today)
4782 rtn (org-agenda-get-day-entries
4783 file date :todo))
4784 (setq rtnall (append rtnall rtn))))
4785 (when rtnall
4786 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4787 (add-text-properties (point-min) (1- (point))
4788 (list 'face 'org-link))
4789 (insert (org-finalize-agenda-entries rtnall) "\n")))
4790 (while (setq d (pop day-numbers))
4791 (setq date (calendar-gregorian-from-absolute d)
4792 s (point))
4793 (if (or (setq todayp (= d today))
4794 (and (not start-pos) (= d sd)))
4795 (setq start-pos (point))
4796 (if (and start-pos (not end-pos))
4797 (setq end-pos (point))))
4798 (setq files (org-agenda-files)
4799 rtnall nil)
4800 (while (setq file (pop files))
4801 (catch 'nextfile
4802 (org-check-agenda-file file)
4803 (if org-agenda-show-log
4804 (setq rtn (org-agenda-get-day-entries
4805 file date
4806 :deadline :scheduled :timestamp :closed))
4807 (setq rtn (org-agenda-get-day-entries
4808 file date
4809 :deadline :scheduled :timestamp)))
4810 (setq rtnall (append rtnall rtn))))
4811 (if org-agenda-include-diary
4812 (progn
4813 (require 'diary-lib)
4814 (setq rtn (org-get-entries-from-diary date))
4815 (setq rtnall (append rtnall rtn))))
4816 (if (or rtnall org-agenda-show-all-dates)
4817 (progn
4818 (insert (format "%-9s %2d %s %4d\n"
4819 (calendar-day-name date)
4820 (extract-calendar-day date)
4821 (calendar-month-name (extract-calendar-month date))
4822 (extract-calendar-year date)))
4823 (put-text-property s (1- (point)) 'face
4824 'org-link)
4825 (if rtnall (insert
4826 (org-finalize-agenda-entries
4827 (org-agenda-add-time-grid-maybe
4828 rtnall nd todayp))
4829 "\n"))
4830 (put-text-property s (1- (point)) 'day d))))
4831 (goto-char (point-min))
4832 (setq buffer-read-only t)
4833 (org-fit-agenda-window)
4834 (unless (and (pos-visible-in-window-p (point-min))
4835 (pos-visible-in-window-p (point-max)))
4836 (goto-char (1- (point-max)))
4837 (recenter -1)
4838 (if (not (pos-visible-in-window-p (or start-pos 1)))
4839 (progn
4840 (goto-char (or start-pos 1))
4841 (recenter 1))))
4842 (goto-char (or start-pos 1))
4843 (if (not org-select-agenda-window) (select-window win))
4844 (message "")))
4845
4846 (defvar org-select-this-todo-keyword nil)
4847
4848 ;;;###autoload
4849 (defun org-todo-list (arg &optional keep-modes)
4850 "Show all TODO entries from all agenda file in a single list.
4851 The prefix arg can be used to select a specific TODO keyword and limit
4852 the list to these. When using \\[universal-argument], you will be prompted
4853 for a keyword. A numeric prefix directly selects the Nth keyword in
4854 `org-todo-keywords'."
4855 (interactive "P")
4856 (org-agenda-maybe-reset-markers 'force)
4857 (org-compile-prefix-format org-agenda-prefix-format)
4858 (let* ((org-agenda-keep-modes keep-modes)
4859 (today (time-to-days (current-time)))
4860 (date (calendar-gregorian-from-absolute today))
4861 (win (selected-window))
4862 (kwds org-todo-keywords)
4863 (completion-ignore-case t)
4864 (org-select-this-todo-keyword
4865 (if (stringp arg) arg
4866 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4867 rtn rtnall files file pos)
4868 (when (equal arg '(4))
4869 (setq org-select-this-todo-keyword
4870 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4871 nil t)))
4872 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4873 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4874 (progn
4875 (delete-other-windows)
4876 (switch-to-buffer-other-window
4877 (get-buffer-create org-agenda-buffer-name))))
4878 (setq buffer-read-only nil)
4879 (erase-buffer)
4880 (org-agenda-mode) (setq buffer-read-only nil)
4881 (set (make-local-variable 'org-agenda-type) 'todo)
4882 (set (make-local-variable 'last-arg) arg)
4883 (set (make-local-variable 'org-todo-keywords) kwds)
4884 (set (make-local-variable 'org-agenda-redo-command)
4885 '(org-todo-list (or current-prefix-arg last-arg) t))
4886 (setq files (org-agenda-files)
4887 rtnall nil)
4888 (while (setq file (pop files))
4889 (catch 'nextfile
4890 (org-check-agenda-file file)
4891 (setq rtn (org-agenda-get-day-entries file date :todo))
4892 (setq rtnall (append rtnall rtn))))
4893 (insert "Global list of TODO items of type: ")
4894 (add-text-properties (point-min) (1- (point))
4895 (list 'face 'org-link))
4896 (setq pos (point))
4897 (insert (or org-select-this-todo-keyword "ALL") "\n")
4898 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4899 (setq pos (point))
4900 (insert
4901 "Available with `N r': (0)ALL "
4902 (let ((n 0))
4903 (mapconcat (lambda (x)
4904 (format "(%d)%s" (setq n (1+ n)) x))
4905 org-todo-keywords " "))
4906 "\n")
4907 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4908 (when rtnall
4909 (insert (org-finalize-agenda-entries rtnall) "\n"))
4910 (goto-char (point-min))
4911 (setq buffer-read-only t)
4912 (org-fit-agenda-window)
4913 (if (not org-select-agenda-window) (select-window win))))
4914
4915 (defun org-check-agenda-file (file)
4916 "Make sure FILE exists. If not, ask user what to do."
4917 ;; FIXME: this does not correctly change the menus
4918 ;; Could probably be fixed by explicitly going to the buffer where
4919 ;; the call originated.
4920 (when (not (file-exists-p file))
4921 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4922 file)
4923 (let ((r (downcase (read-char-exclusive))))
4924 (cond
4925 ((equal r ?r)
4926 (org-remove-file file)
4927 (throw 'nextfile t))
4928 (t (error "Abort"))))))
4929
4930 (defun org-agenda-check-type (error &rest types)
4931 "Check if agenda buffer is of allowed type.
4932 If ERROR is non-nil, throw an error, otherwise just return nil."
4933 (if (memq org-agenda-type types)
4934 t
4935 (if error
4936 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
4937 nil)))
4938
4939 (defun org-agenda-quit ()
4940 "Exit agenda by removing the window or the buffer."
4941 (interactive)
4942 (let ((buf (current-buffer)))
4943 (if (not (one-window-p)) (delete-window))
4944 (kill-buffer buf)
4945 (org-agenda-maybe-reset-markers 'force)))
4946
4947 (defun org-agenda-exit ()
4948 "Exit agenda by removing the window or the buffer.
4949 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4950 Org-mode buffers visited directly by the user will not be touched."
4951 (interactive)
4952 (org-release-buffers org-agenda-new-buffers)
4953 (setq org-agenda-new-buffers nil)
4954 (org-agenda-quit))
4955
4956 (defun org-agenda-redo ()
4957 "Rebuild Agenda.
4958 When this is the global TODO list, a prefix argument will be interpreted."
4959 (interactive)
4960 (message "Rebuilding agenda buffer...")
4961 (eval org-agenda-redo-command)
4962 (message "Rebuilding agenda buffer...done"))
4963
4964 (defun org-agenda-goto-today ()
4965 "Go to today."
4966 (interactive)
4967 (org-agenda-check-type t 'timeline 'agenda)
4968 (if (boundp 'starting-day)
4969 (let ((cmd (car org-agenda-redo-command))
4970 (iall (nth 1 org-agenda-redo-command))
4971 (nday (nth 3 org-agenda-redo-command))
4972 (keep (nth 4 org-agenda-redo-command)))
4973 (eval (list cmd iall nil nday keep)))
4974 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4975 (point-min)))))
4976
4977 (defun org-agenda-later (arg)
4978 "Go forward in time by `org-agenda-ndays' days.
4979 With prefix ARG, go forward that many times `org-agenda-ndays'."
4980 (interactive "p")
4981 (org-agenda-check-type t 'agenda)
4982 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4983 (+ starting-day (* arg org-agenda-ndays)) nil t))
4984
4985 (defun org-agenda-earlier (arg)
4986 "Go back in time by `org-agenda-ndays' days.
4987 With prefix ARG, go back that many times `org-agenda-ndays'."
4988 (interactive "p")
4989 (org-agenda-check-type t 'agenda)
4990 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4991 (- starting-day (* arg org-agenda-ndays)) nil t))
4992
4993 (defun org-agenda-week-view ()
4994 "Switch to weekly view for agenda."
4995 (interactive)
4996 (org-agenda-check-type t 'agenda)
4997 (setq org-agenda-ndays 7)
4998 (org-agenda-list include-all-loc
4999 (or (get-text-property (point) 'day)
5000 starting-day)
5001 nil t)
5002 (org-agenda-set-mode-name)
5003 (message "Switched to week view"))
5004
5005 (defun org-agenda-day-view ()
5006 "Switch to daily view for agenda."
5007 (interactive)
5008 (org-agenda-check-type t 'agenda)
5009 (setq org-agenda-ndays 1)
5010 (org-agenda-list include-all-loc
5011 (or (get-text-property (point) 'day)
5012 starting-day)
5013 nil t)
5014 (org-agenda-set-mode-name)
5015 (message "Switched to day view"))
5016
5017 (defun org-agenda-next-date-line (&optional arg)
5018 "Jump to the next line indicating a date in agenda buffer."
5019 (interactive "p")
5020 (org-agenda-check-type t 'agenda 'timeline)
5021 (beginning-of-line 1)
5022 (if (looking-at "^\\S-") (forward-char 1))
5023 (if (not (re-search-forward "^\\S-" nil t arg))
5024 (progn
5025 (backward-char 1)
5026 (error "No next date after this line in this buffer")))
5027 (goto-char (match-beginning 0)))
5028
5029 (defun org-agenda-previous-date-line (&optional arg)
5030 "Jump to the previous line indicating a date in agenda buffer."
5031 (interactive "p")
5032 (org-agenda-check-type t 'agenda 'timeline)
5033 (beginning-of-line 1)
5034 (if (not (re-search-backward "^\\S-" nil t arg))
5035 (error "No previous date before this line in this buffer")))
5036
5037 ;; Initialize the highlight
5038 (defvar org-hl (org-make-overlay 1 1))
5039 (org-overlay-put org-hl 'face 'highlight)
5040
5041 (defun org-highlight (begin end &optional buffer)
5042 "Highlight a region with overlay."
5043 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
5044 org-hl begin end (or buffer (current-buffer))))
5045
5046 (defun org-unhighlight ()
5047 "Detach overlay INDEX."
5048 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
5049
5050
5051 (defun org-agenda-follow-mode ()
5052 "Toggle follow mode in an agenda buffer."
5053 (interactive)
5054 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5055 (org-agenda-set-mode-name)
5056 (message "Follow mode is %s"
5057 (if org-agenda-follow-mode "on" "off")))
5058
5059 (defun org-agenda-log-mode ()
5060 "Toggle log mode in an agenda buffer."
5061 (interactive)
5062 (org-agenda-check-type t 'agenda 'timeline)
5063 (setq org-agenda-show-log (not org-agenda-show-log))
5064 (org-agenda-set-mode-name)
5065 (org-agenda-redo)
5066 (message "Log mode is %s"
5067 (if org-agenda-show-log "on" "off")))
5068
5069 (defun org-agenda-toggle-diary ()
5070 "Toggle diary inclusion in an agenda buffer."
5071 (interactive)
5072 (org-agenda-check-type t 'agenda)
5073 (setq org-agenda-include-diary (not org-agenda-include-diary))
5074 (org-agenda-redo)
5075 (org-agenda-set-mode-name)
5076 (message "Diary inclusion turned %s"
5077 (if org-agenda-include-diary "on" "off")))
5078
5079 (defun org-agenda-toggle-time-grid ()
5080 "Toggle time grid in an agenda buffer."
5081 (interactive)
5082 (org-agenda-check-type t 'agenda)
5083 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5084 (org-agenda-redo)
5085 (org-agenda-set-mode-name)
5086 (message "Time-grid turned %s"
5087 (if org-agenda-use-time-grid "on" "off")))
5088
5089 (defun org-agenda-set-mode-name ()
5090 "Set the mode name to indicate all the small mode settings."
5091 (setq mode-name
5092 (concat "Org-Agenda"
5093 (if (equal org-agenda-ndays 1) " Day" "")
5094 (if (equal org-agenda-ndays 7) " Week" "")
5095 (if org-agenda-follow-mode " Follow" "")
5096 (if org-agenda-include-diary " Diary" "")
5097 (if org-agenda-use-time-grid " Grid" "")
5098 (if org-agenda-show-log " Log" "")))
5099 (force-mode-line-update))
5100
5101 (defun org-agenda-post-command-hook ()
5102 (and (eolp) (not (bolp)) (backward-char 1))
5103 (if (and org-agenda-follow-mode
5104 (get-text-property (point) 'org-marker))
5105 (org-agenda-show)))
5106
5107 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5108
5109 (defun org-get-entries-from-diary (date)
5110 "Get the (Emacs Calendar) diary entries for DATE."
5111 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5112 (diary-display-hook '(fancy-diary-display))
5113 (list-diary-entries-hook
5114 (cons 'org-diary-default-entry list-diary-entries-hook))
5115 (diary-file-name-prefix-function nil) ; turn this feature off
5116 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5117 entries
5118 (org-disable-agenda-to-diary t))
5119 (save-excursion
5120 (save-window-excursion
5121 (list-diary-entries date 1)))
5122 (if (not (get-buffer fancy-diary-buffer))
5123 (setq entries nil)
5124 (with-current-buffer fancy-diary-buffer
5125 (setq buffer-read-only nil)
5126 (if (= (point-max) 1)
5127 ;; No entries
5128 (setq entries nil)
5129 ;; Omit the date and other unnecessary stuff
5130 (org-agenda-cleanup-fancy-diary)
5131 ;; Add prefix to each line and extend the text properties
5132 (if (= (point-max) 1)
5133 (setq entries nil)
5134 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5135 (set-buffer-modified-p nil)
5136 (kill-buffer fancy-diary-buffer)))
5137 (when entries
5138 (setq entries (org-split-string entries "\n"))
5139 (setq entries
5140 (mapcar
5141 (lambda (x)
5142 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5143 ;; Extend the text properties to the beginning of the line
5144 (add-text-properties
5145 0 (length x)
5146 (text-properties-at (1- (length x)) x)
5147 x)
5148 x)
5149 entries)))))
5150
5151 (defun org-agenda-cleanup-fancy-diary ()
5152 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5153 This gets rid of the date, the underline under the date, and
5154 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5155 date. It also removes lines that contain only whitespace."
5156 (goto-char (point-min))
5157 (if (looking-at ".*?:[ \t]*")
5158 (progn
5159 (replace-match "")
5160 (re-search-forward "\n=+$" nil t)
5161 (replace-match "")
5162 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5163 (re-search-forward "\n=+$" nil t)
5164 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5165 (goto-char (point-min))
5166 (while (re-search-forward "^ +\n" nil t)
5167 (replace-match ""))
5168 (goto-char (point-min))
5169 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5170 (replace-match "")))
5171
5172 ;; Make sure entries from the diary have the right text properties.
5173 (eval-after-load "diary-lib"
5174 '(if (boundp 'diary-modify-entry-list-string-function)
5175 ;; We can rely on the hook, nothing to do
5176 nil
5177 ;; Hook not avaiable, must use advice to make this work
5178 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5179 "Make the position visible."
5180 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5181 (stringp string)
5182 (buffer-file-name))
5183 (setq string (org-modify-diary-entry-string string))))))
5184
5185 (defun org-modify-diary-entry-string (string)
5186 "Add text properties to string, allowing org-mode to act on it."
5187 (add-text-properties
5188 0 (length string)
5189 (list 'mouse-face 'highlight
5190 'keymap org-agenda-keymap
5191 'help-echo
5192 (format
5193 "mouse-2 or RET jump to diary file %s"
5194 (abbreviate-file-name (buffer-file-name)))
5195 'org-agenda-diary-link t
5196 'org-marker (org-agenda-new-marker (point-at-bol)))
5197 string)
5198 string)
5199
5200 (defun org-diary-default-entry ()
5201 "Add a dummy entry to the diary.
5202 Needed to avoid empty dates which mess up holiday display."
5203 ;; Catch the error if dealing with the new add-to-diary-alist
5204 (when org-disable-agenda-to-diary
5205 (condition-case nil
5206 (add-to-diary-list original-date "Org-mode dummy" "")
5207 (error
5208 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5209
5210 (defun org-cycle-agenda-files ()
5211 "Cycle through the files in `org-agenda-files'.
5212 If the current buffer visits an agenda file, find the next one in the list.
5213 If the current buffer does not, find the first agenda file."
5214 (interactive)
5215 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5216 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
5217 file)
5218 (unless files (error "No agenda files"))
5219 (catch 'exit
5220 (while (setq file (pop files))
5221 (if (equal (file-truename file) tcf)
5222 (when (car files)
5223 (find-file (car files))
5224 (throw 'exit t))))
5225 (find-file (car org-agenda-files)))))
5226
5227 (defun org-agenda-file-to-end (&optional file)
5228 "Move/add the current file to the end of the agenda file list.
5229 If the file is not present in the list, it is appended to the list. If it is
5230 present, it is moved there."
5231 (interactive)
5232 (org-agenda-file-to-front 'to-end file))
5233
5234 (defun org-agenda-file-to-front (&optional to-end file)
5235 "Move/add the current file to the top of the agenda file list.
5236 If the file is not present in the list, it is added to the front. If it is
5237 present, it is moved there. With optional argument TO-END, add/move to the
5238 end of the list."
5239 (interactive "P")
5240 (let ((file-alist (mapcar (lambda (x)
5241 (cons (file-truename x) x))
5242 org-agenda-files))
5243 (ctf (file-truename (buffer-file-name)))
5244 x had)
5245 (setq x (assoc ctf file-alist) had x)
5246
5247 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
5248 (if to-end
5249 (setq file-alist (append (delq x file-alist) (list x)))
5250 (setq file-alist (cons x (delq x file-alist))))
5251 (setq org-agenda-files (mapcar 'cdr file-alist))
5252 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5253 (customize-save-variable 'org-agenda-files org-agenda-files))
5254 (org-install-agenda-files-menu)
5255 (message "File %s to %s of agenda file list"
5256 (if had "moved" "added") (if to-end "end" "front"))))
5257
5258 (defun org-remove-file (&optional file)
5259 "Remove current file from the list of files in variable `org-agenda-files'.
5260 These are the files which are being checked for agenda entries.
5261 Optional argument FILE means, use this file instead of the current."
5262 (interactive)
5263 (let* ((file (or file (buffer-file-name)))
5264 (true-file (file-truename file))
5265 (afile (abbreviate-file-name file))
5266 (files (delq nil (mapcar
5267 (lambda (x)
5268 (if (equal true-file
5269 (file-truename x))
5270 nil x))
5271 org-agenda-files))))
5272 (if (not (= (length files) (length org-agenda-files)))
5273 (progn
5274 (setq org-agenda-files files)
5275 (customize-save-variable 'org-agenda-files org-agenda-files)
5276 (org-install-agenda-files-menu)
5277 (message "Removed file: %s" afile))
5278 (message "File was not in list: %s" afile))))
5279
5280 (defun org-file-menu-entry (file)
5281 (vector file (list 'find-file file) t))
5282 ;; FIXME: Maybe we removed a buffer visited through the menu from
5283 ;; org-agenda-new-buffers, so that the buffer will not be removed
5284 ;; when exiting the agenda????
5285
5286 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5287 "Return a list of all relevant day numbers from BEG to END buffer positions.
5288 If NO-RANGES is non-nil, include only the start and end dates of a range,
5289 not every single day in the range. If FORCE-TODAY is non-nil, make
5290 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5291 inactive time stamps (those in square brackets) are included."
5292 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5293 dates date day day1 day2 ts1 ts2)
5294 (if force-today
5295 (setq dates (list (time-to-days (current-time)))))
5296 (save-excursion
5297 (goto-char beg)
5298 (while (re-search-forward re end t)
5299 (setq day (time-to-days (org-time-string-to-time
5300 (substring (match-string 1) 0 10))))
5301 (or (memq day dates) (push day dates)))
5302 (unless no-ranges
5303 (goto-char beg)
5304 (while (re-search-forward org-tr-regexp end t)
5305 (setq ts1 (substring (match-string 1) 0 10)
5306 ts2 (substring (match-string 2) 0 10)
5307 day1 (time-to-days (org-time-string-to-time ts1))
5308 day2 (time-to-days (org-time-string-to-time ts2)))
5309 (while (< (setq day1 (1+ day1)) day2)
5310 (or (memq day1 dates) (push day1 dates)))))
5311 (sort dates '<))))
5312
5313 ;;;###autoload
5314 (defun org-diary (&rest args)
5315 "Return diary information from org-files.
5316 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5317 It accesses org files and extracts information from those files to be
5318 listed in the diary. The function accepts arguments specifying what
5319 items should be listed. The following arguments are allowed:
5320
5321 :timestamp List the headlines of items containing a date stamp or
5322 date range matching the selected date. Deadlines will
5323 also be listed, on the expiration day.
5324
5325 :deadline List any deadlines past due, or due within
5326 `org-deadline-warning-days'. The listing occurs only
5327 in the diary for *today*, not at any other date. If
5328 an entry is marked DONE, it is no longer listed.
5329
5330 :scheduled List all items which are scheduled for the given date.
5331 The diary for *today* also contains items which were
5332 scheduled earlier and are not yet marked DONE.
5333
5334 :todo List all TODO items from the org-file. This may be a
5335 long list - so this is not turned on by default.
5336 Like deadlines, these entries only show up in the
5337 diary for *today*, not at any other date.
5338
5339 The call in the diary file should look like this:
5340
5341 &%%(org-diary) ~/path/to/some/orgfile.org
5342
5343 Use a separate line for each org file to check. Or, if you omit the file name,
5344 all files listed in `org-agenda-files' will be checked automatically:
5345
5346 &%%(org-diary)
5347
5348 If you don't give any arguments (as in the example above), the default
5349 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5350 also be written as
5351
5352 &%%(org-diary :deadline :timestamp :scheduled)
5353
5354 The function expects the lisp variables `entry' and `date' to be provided
5355 by the caller, because this is how the calendar works. Don't use this
5356 function from a program - use `org-agenda-get-day-entries' instead."
5357 (org-agenda-maybe-reset-markers)
5358 (org-compile-prefix-format org-agenda-prefix-format)
5359 (setq args (or args '(:deadline :scheduled :timestamp)))
5360 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5361 (list entry)
5362 org-agenda-files))
5363 file rtn results)
5364 ;; If this is called during org-agenda, don't return any entries to
5365 ;; the calendar. Org Agenda will list these entries itself.
5366 (if org-disable-agenda-to-diary (setq files nil))
5367 (while (setq file (pop files))
5368 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5369 (setq results (append results rtn)))
5370 (if results
5371 (concat (org-finalize-agenda-entries results) "\n"))))
5372 (defvar org-category-table nil)
5373 (defun org-get-category-table ()
5374 "Get the table of categories and positions in current buffer."
5375 (let (tbl)
5376 (save-excursion
5377 (goto-char (point-min))
5378 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5379 (push (cons (point) (org-trim (match-string 2))) tbl)))
5380 tbl))
5381 (defun org-get-category (&optional pos)
5382 "Get the category applying to position POS."
5383 (if (not org-category-table)
5384 (cond
5385 ((null org-category)
5386 (setq org-category
5387 (if (buffer-file-name)
5388 (file-name-sans-extension
5389 (file-name-nondirectory (buffer-file-name)))
5390 "???")))
5391 ((symbolp org-category) (symbol-name org-category))
5392 (t org-category))
5393 (let ((tbl org-category-table)
5394 (pos (or pos (point))))
5395 (while (and tbl (> (caar tbl) pos))
5396 (pop tbl))
5397 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5398 org-category-table))))))
5399
5400 (defun org-agenda-get-day-entries (file date &rest args)
5401 "Does the work for `org-diary' and `org-agenda'.
5402 FILE is the path to a file to be checked for entries. DATE is date like
5403 the one returned by `calendar-current-date'. ARGS are symbols indicating
5404 which kind of entries should be extracted. For details about these, see
5405 the documentation of `org-diary'."
5406 (setq args (or args '(:deadline :scheduled :timestamp)))
5407 (let* ((org-startup-with-deadline-check nil)
5408 (org-startup-folded nil)
5409 (buffer (if (file-exists-p file)
5410 (org-get-agenda-file-buffer file)
5411 (error "No such file %s" file)))
5412 arg results rtn)
5413 (if (not buffer)
5414 ;; If file does not exist, make sure an error message ends up in diary
5415 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5416 (with-current-buffer buffer
5417 (unless (eq major-mode 'org-mode)
5418 (error "Agenda file %s is not in `org-mode'" file))
5419 (setq org-category-table (org-get-category-table))
5420 (let ((case-fold-search nil))
5421 (save-excursion
5422 (save-restriction
5423 (if org-respect-restriction
5424 (if (org-region-active-p)
5425 ;; Respect a region to restrict search
5426 (narrow-to-region (region-beginning) (region-end)))
5427 ;; If we work for the calendar or many files,
5428 ;; get rid of any restriction
5429 (widen))
5430 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5431 (while (setq arg (pop args))
5432 (cond
5433 ((and (eq arg :todo)
5434 (equal date (calendar-current-date)))
5435 (setq rtn (org-agenda-get-todos))
5436 (setq results (append results rtn)))
5437 ((eq arg :timestamp)
5438 (setq rtn (org-agenda-get-blocks))
5439 (setq results (append results rtn))
5440 (setq rtn (org-agenda-get-timestamps))
5441 (setq results (append results rtn)))
5442 ((eq arg :scheduled)
5443 (setq rtn (org-agenda-get-scheduled))
5444 (setq results (append results rtn)))
5445 ((eq arg :closed)
5446 (setq rtn (org-agenda-get-closed))
5447 (setq results (append results rtn)))
5448 ((and (eq arg :deadline)
5449 (equal date (calendar-current-date)))
5450 (setq rtn (org-agenda-get-deadlines))
5451 (setq results (append results rtn))))))))
5452 results))))
5453
5454 (defun org-entry-is-done-p ()
5455 "Is the current entry marked DONE?"
5456 (save-excursion
5457 (and (re-search-backward "[\r\n]\\*" nil t)
5458 (looking-at org-nl-done-regexp))))
5459
5460 (defun org-at-date-range-p ()
5461 "Is the cursor inside a date range?"
5462 (interactive)
5463 (save-excursion
5464 (catch 'exit
5465 (let ((pos (point)))
5466 (skip-chars-backward "^<\r\n")
5467 (skip-chars-backward "<")
5468 (and (looking-at org-tr-regexp)
5469 (>= (match-end 0) pos)
5470 (throw 'exit t))
5471 (skip-chars-backward "^<\r\n")
5472 (skip-chars-backward "<")
5473 (and (looking-at org-tr-regexp)
5474 (>= (match-end 0) pos)
5475 (throw 'exit t)))
5476 nil)))
5477
5478 (defun org-agenda-get-todos ()
5479 "Return the TODO information for agenda display."
5480 (let* ((props (list 'face nil
5481 'done-face 'org-done
5482 'mouse-face 'highlight
5483 'keymap org-agenda-keymap
5484 'help-echo
5485 (format "mouse-2 or RET jump to org file %s"
5486 (abbreviate-file-name (buffer-file-name)))))
5487 (regexp (concat "[\n\r]\\*+ *\\("
5488 (if org-select-this-todo-keyword
5489 (concat "\\<\\(" org-select-this-todo-keyword
5490 "\\)\\>")
5491 org-not-done-regexp)
5492 "[^\n\r]*\\)"))
5493 marker priority category tags
5494 ee txt)
5495 (goto-char (point-min))
5496 (while (re-search-forward regexp nil t)
5497 (goto-char (match-beginning 1))
5498 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5499 category (org-get-category)
5500 tags (org-get-tags-at (point))
5501 txt (org-format-agenda-item "" (match-string 1) category tags)
5502 priority
5503 (+ (org-get-priority txt)
5504 (if org-todo-kwd-priority-p
5505 (- org-todo-kwd-max-priority -2
5506 (length
5507 (member (match-string 2) org-todo-keywords)))
5508 1)))
5509 (add-text-properties
5510 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5511 'priority priority 'category category)
5512 props)
5513 txt)
5514 (push txt ee)
5515 (goto-char (match-end 1)))
5516 (nreverse ee)))
5517
5518 (defconst org-agenda-no-heading-message
5519 "No heading for this item in buffer or region.")
5520
5521 (defun org-agenda-get-timestamps ()
5522 "Return the date stamp information for agenda display."
5523 (let* ((props (list 'face nil
5524 'mouse-face 'highlight
5525 'keymap org-agenda-keymap
5526 'help-echo
5527 (format "mouse-2 or RET jump to org file %s"
5528 (abbreviate-file-name (buffer-file-name)))))
5529 (regexp (regexp-quote
5530 (substring
5531 (format-time-string
5532 (car org-time-stamp-formats)
5533 (apply 'encode-time ; DATE bound by calendar
5534 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5535 0 11)))
5536 marker hdmarker deadlinep scheduledp donep tmp priority category
5537 ee txt timestr tags)
5538 (goto-char (point-min))
5539 (while (re-search-forward regexp nil t)
5540 (if (not (save-match-data (org-at-date-range-p)))
5541 (progn
5542 (setq marker (org-agenda-new-marker (match-beginning 0))
5543 category (org-get-category (match-beginning 0))
5544 tmp (buffer-substring (max (point-min)
5545 (- (match-beginning 0)
5546 org-ds-keyword-length))
5547 (match-beginning 0))
5548 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5549 deadlinep (string-match org-deadline-regexp tmp)
5550 scheduledp (string-match org-scheduled-regexp tmp)
5551 donep (org-entry-is-done-p))
5552 (if (string-match ">" timestr)
5553 ;; substring should only run to end of time stamp
5554 (setq timestr (substring timestr 0 (match-end 0))))
5555 (save-excursion
5556 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5557 (progn
5558 (goto-char (match-end 1))
5559 (setq hdmarker (org-agenda-new-marker)
5560 tags (org-get-tags-at))
5561 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5562 (setq txt (org-format-agenda-item
5563 (format "%s%s"
5564 (if deadlinep "Deadline: " "")
5565 (if scheduledp "Scheduled: " ""))
5566 (match-string 1) category tags timestr)))
5567 (setq txt org-agenda-no-heading-message))
5568 (setq priority (org-get-priority txt))
5569 (add-text-properties
5570 0 (length txt) (append (list 'org-marker marker
5571 'org-hd-marker hdmarker) props)
5572 txt)
5573 (if deadlinep
5574 (add-text-properties
5575 0 (length txt)
5576 (list 'face
5577 (if donep 'org-done 'org-warning)
5578 'undone-face 'org-warning
5579 'done-face 'org-done
5580 'category category
5581 'priority (+ 100 priority))
5582 txt)
5583 (if scheduledp
5584 (add-text-properties
5585 0 (length txt)
5586 (list 'face 'org-scheduled-today
5587 'undone-face 'org-scheduled-today
5588 'done-face 'org-done
5589 'category category
5590 priority (+ 99 priority))
5591 txt)
5592 (add-text-properties
5593 0 (length txt)
5594 (list 'priority priority 'category category) txt)))
5595 (push txt ee))
5596 (outline-next-heading))))
5597 (nreverse ee)))
5598
5599 (defun org-agenda-get-closed ()
5600 "Return the logged TODO entries for agenda display."
5601 (let* ((props (list 'mouse-face 'highlight
5602 'keymap org-agenda-keymap
5603 'help-echo
5604 (format "mouse-2 or RET jump to org file %s"
5605 (abbreviate-file-name (buffer-file-name)))))
5606 (regexp (concat
5607 "\\<" org-closed-string " *\\["
5608 (regexp-quote
5609 (substring
5610 (format-time-string
5611 (car org-time-stamp-formats)
5612 (apply 'encode-time ; DATE bound by calendar
5613 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5614 1 11))))
5615 marker hdmarker priority category tags
5616 ee txt timestr)
5617 (goto-char (point-min))
5618 (while (re-search-forward regexp nil t)
5619 (if (not (save-match-data (org-at-date-range-p)))
5620 (progn
5621 (setq marker (org-agenda-new-marker (match-beginning 0))
5622 category (org-get-category (match-beginning 0))
5623 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5624 ;; donep (org-entry-is-done-p)
5625 )
5626 (if (string-match "\\]" timestr)
5627 ;; substring should only run to end of time stamp
5628 (setq timestr (substring timestr 0 (match-end 0))))
5629 (save-excursion
5630 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5631 (progn
5632 (goto-char (match-end 1))
5633 (setq hdmarker (org-agenda-new-marker)
5634 tags (org-get-tags-at))
5635 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5636 (setq txt (org-format-agenda-item
5637 "Closed: "
5638 (match-string 1) category tags timestr)))
5639 (setq txt org-agenda-no-heading-message))
5640 (setq priority 100000)
5641 (add-text-properties
5642 0 (length txt) (append (list 'org-marker marker
5643 'org-hd-marker hdmarker
5644 'face 'org-done
5645 'priority priority
5646 'category category
5647 'undone-face 'org-warning
5648 'done-face 'org-done) props)
5649 txt)
5650 (push txt ee))
5651 (outline-next-heading))))
5652 (nreverse ee)))
5653
5654 (defun org-agenda-get-deadlines ()
5655 "Return the deadline information for agenda display."
5656 (let* ((wdays org-deadline-warning-days)
5657 (props (list 'mouse-face 'highlight
5658 'keymap org-agenda-keymap
5659 'help-echo
5660 (format "mouse-2 or RET jump to org file %s"
5661 (abbreviate-file-name (buffer-file-name)))))
5662 (regexp org-deadline-time-regexp)
5663 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5664 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5665 d2 diff pos pos1 category tags
5666 ee txt head)
5667 (goto-char (point-min))
5668 (while (re-search-forward regexp nil t)
5669 (setq pos (1- (match-beginning 1))
5670 d2 (time-to-days
5671 (org-time-string-to-time (match-string 1)))
5672 diff (- d2 d1))
5673 ;; When to show a deadline in the calendar:
5674 ;; If the expiration is within wdays warning time.
5675 ;; Past-due deadlines are only shown on the current date
5676 (if (and (< diff wdays) todayp (not (= diff 0)))
5677 (save-excursion
5678 (setq category (org-get-category))
5679 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5680 (progn
5681 (goto-char (match-end 0))
5682 (setq pos1 (match-end 1))
5683 (setq tags (org-get-tags-at pos1))
5684 (setq head (buffer-substring-no-properties
5685 (point)
5686 (progn (skip-chars-forward "^\r\n")
5687 (point))))
5688 (if (string-match org-looking-at-done-regexp head)
5689 (setq txt nil)
5690 (setq txt (org-format-agenda-item
5691 (format "In %3d d.: " diff) head category tags))))
5692 (setq txt org-agenda-no-heading-message))
5693 (when txt
5694 (add-text-properties
5695 0 (length txt)
5696 (append
5697 (list 'org-marker (org-agenda-new-marker pos)
5698 'org-hd-marker (org-agenda-new-marker pos1)
5699 'priority (+ (- 10 diff) (org-get-priority txt))
5700 'category category
5701 'face (cond ((<= diff 0) 'org-warning)
5702 ((<= diff 5) 'org-scheduled-previously)
5703 (t nil))
5704 'undone-face (cond
5705 ((<= diff 0) 'org-warning)
5706 ((<= diff 5) 'org-scheduled-previously)
5707 (t nil))
5708 'done-face 'org-done)
5709 props)
5710 txt)
5711 (push txt ee)))))
5712 ee))
5713
5714 (defun org-agenda-get-scheduled ()
5715 "Return the scheduled information for agenda display."
5716 (let* ((props (list 'face 'org-scheduled-previously
5717 'undone-face 'org-scheduled-previously
5718 'done-face 'org-done
5719 'mouse-face 'highlight
5720 'keymap org-agenda-keymap
5721 'help-echo
5722 (format "mouse-2 or RET jump to org file %s"
5723 (abbreviate-file-name (buffer-file-name)))))
5724 (regexp org-scheduled-time-regexp)
5725 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5726 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5727 d2 diff pos pos1 category tags
5728 ee txt head)
5729 (goto-char (point-min))
5730 (while (re-search-forward regexp nil t)
5731 (setq pos (1- (match-beginning 1))
5732 d2 (time-to-days
5733 (org-time-string-to-time (match-string 1)))
5734 diff (- d2 d1))
5735 ;; When to show a scheduled item in the calendar:
5736 ;; If it is on or past the date.
5737 (if (and (< diff 0) todayp)
5738 (save-excursion
5739 (setq category (org-get-category))
5740 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5741 (progn
5742 (goto-char (match-end 0))
5743 (setq pos1 (match-end 1))
5744 (setq tags (org-get-tags-at))
5745 (setq head (buffer-substring-no-properties
5746 (point)
5747 (progn (skip-chars-forward "^\r\n") (point))))
5748 (if (string-match org-looking-at-done-regexp head)
5749 (setq txt nil)
5750 (setq txt (org-format-agenda-item
5751 (format "Sched.%2dx: " (- 1 diff)) head
5752 category tags))))
5753 (setq txt org-agenda-no-heading-message))
5754 (when txt
5755 (add-text-properties
5756 0 (length txt)
5757 (append (list 'org-marker (org-agenda-new-marker pos)
5758 'org-hd-marker (org-agenda-new-marker pos1)
5759 'priority (+ (- 5 diff) (org-get-priority txt))
5760 'category category)
5761 props) txt)
5762 (push txt ee)))))
5763 ee))
5764
5765 (defun org-agenda-get-blocks ()
5766 "Return the date-range information for agenda display."
5767 (let* ((props (list 'face nil
5768 'mouse-face 'highlight
5769 'keymap org-agenda-keymap
5770 'help-echo
5771 (format "mouse-2 or RET jump to org file %s"
5772 (abbreviate-file-name (buffer-file-name)))))
5773 (regexp org-tr-regexp)
5774 (d0 (calendar-absolute-from-gregorian date))
5775 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
5776 (goto-char (point-min))
5777 (while (re-search-forward regexp nil t)
5778 (setq timestr (match-string 0)
5779 s1 (match-string 1)
5780 s2 (match-string 2)
5781 d1 (time-to-days (org-time-string-to-time s1))
5782 d2 (time-to-days (org-time-string-to-time s2)))
5783 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5784 ;; Only allow days between the limits, because the normal
5785 ;; date stamps will catch the limits.
5786 (save-excursion
5787 (setq marker (org-agenda-new-marker (point)))
5788 (setq category (org-get-category))
5789 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5790 (progn
5791 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5792 (goto-char (match-end 1))
5793 (setq tags (org-get-tags-at))
5794 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5795 (setq txt (org-format-agenda-item
5796 (format (if (= d1 d2) "" "(%d/%d): ")
5797 (1+ (- d0 d1)) (1+ (- d2 d1)))
5798 (match-string 1) category tags
5799 (if (= d0 d1) timestr))))
5800 (setq txt org-agenda-no-heading-message))
5801 (add-text-properties
5802 0 (length txt) (append (list 'org-marker marker
5803 'org-hd-marker hdmarker
5804 'priority (org-get-priority txt)
5805 'category category)
5806 props)
5807 txt)
5808 (push txt ee)))
5809 (outline-next-heading))
5810 ;; Sort the entries by expiration date.
5811 (nreverse ee)))
5812
5813 (defconst org-plain-time-of-day-regexp
5814 (concat
5815 "\\(\\<[012]?[0-9]"
5816 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5817 "\\(--?"
5818 "\\(\\<[012]?[0-9]"
5819 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5820 "\\)?")
5821 "Regular expression to match a plain time or time range.
5822 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5823 groups carry important information:
5824 0 the full match
5825 1 the first time, range or not
5826 8 the second time, if it is a range.")
5827
5828 (defconst org-stamp-time-of-day-regexp
5829 (concat
5830 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5831 "\\([012][0-9]:[0-5][0-9]\\)>"
5832 "\\(--?"
5833 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5834 "Regular expression to match a timestamp time or time range.
5835 After a match, the following groups carry important information:
5836 0 the full match
5837 1 date plus weekday, for backreferencing to make sure both times on same day
5838 2 the first time, range or not
5839 4 the second time, if it is a range.")
5840
5841 (defvar org-prefix-has-time nil
5842 "A flag, set by `org-compile-prefix-format'.
5843 The flag is set if the currently compiled format contains a `%t'.")
5844 (defvar org-prefix-has-tag nil
5845 "A flag, set by `org-compile-prefix-format'.
5846 The flag is set if the currently compiled format contains a `%T'.")
5847
5848 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
5849 "Format TXT to be inserted into the agenda buffer.
5850 In particular, it adds the prefix and corresponding text properties. EXTRA
5851 must be a string and replaces the `%s' specifier in the prefix format.
5852 CATEGORY (string, symbol or nil) may be used to overrule the default
5853 category taken from local variable or file name. It will replace the `%c'
5854 specifier in the format. DOTIME, when non-nil, indicates that a
5855 time-of-day should be extracted from TXT for sorting of this entry, and for
5856 the `%t' specifier in the format. When DOTIME is a string, this string is
5857 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5858 only the correctly processes TXT should be returned - this is used by
5859 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
5860 (save-match-data
5861 ;; Diary entries sometimes have extra whitespace at the beginning
5862 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5863 (let* ((category (or category
5864 org-category
5865 (if (buffer-file-name)
5866 (file-name-sans-extension
5867 (file-name-nondirectory (buffer-file-name)))
5868 "")))
5869 (tag (or (nth (1- (length tags)) tags) ""))
5870 time ;; needed for the eval of the prefix format
5871 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5872 (time-of-day (and dotime (org-get-time-of-day ts)))
5873 stamp plain s0 s1 s2 rtn)
5874 (when (and dotime time-of-day org-prefix-has-time)
5875 ;; Extract starting and ending time and move them to prefix
5876 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5877 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5878 (setq s0 (match-string 0 ts)
5879 s1 (match-string (if plain 1 2) ts)
5880 s2 (match-string (if plain 8 4) ts))
5881
5882 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5883 ;; them, we might want to remove them there to avoid duplication.
5884 ;; The user can turn this off with a variable.
5885 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5886 (string-match (concat (regexp-quote s0) " *") txt)
5887 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5888 (= (match-beginning 0) 0)
5889 t))
5890 (setq txt (replace-match "" nil nil txt))))
5891 ;; Normalize the time(s) to 24 hour
5892 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5893 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5894
5895 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
5896 (and org-agenda-remove-tags-when-in-prefix
5897 org-prefix-has-tag))
5898 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
5899 (setq txt (replace-match "" t t txt)))
5900
5901 ;; Create the final string
5902 (if noprefix
5903 (setq rtn txt)
5904 ;; Prepare the variables needed in the eval of the compiled format
5905 (setq time (cond (s2 (concat s1 "-" s2))
5906 (s1 (concat s1 "......"))
5907 (t ""))
5908 extra (or extra "")
5909 category (if (symbolp category) (symbol-name category) category))
5910 ;; Evaluate the compiled format
5911 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5912
5913 ;; And finally add the text properties
5914 (add-text-properties
5915 0 (length rtn) (list 'category (downcase category)
5916 'tags tags
5917 'prefix-length (- (length rtn) (length txt))
5918 'time-of-day time-of-day
5919 'dotime dotime)
5920 rtn)
5921 rtn)))
5922
5923 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5924 (catch 'exit
5925 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5926 ((and todayp (member 'today (car org-agenda-time-grid))))
5927 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5928 ((member 'weekly (car org-agenda-time-grid)))
5929 (t (throw 'exit list)))
5930 (let* ((have (delq nil (mapcar
5931 (lambda (x) (get-text-property 1 'time-of-day x))
5932 list)))
5933 (string (nth 1 org-agenda-time-grid))
5934 (gridtimes (nth 2 org-agenda-time-grid))
5935 (req (car org-agenda-time-grid))
5936 (remove (member 'remove-match req))
5937 new time)
5938 (if (and (member 'require-timed req) (not have))
5939 ;; don't show empty grid
5940 (throw 'exit list))
5941 (while (setq time (pop gridtimes))
5942 (unless (and remove (member time have))
5943 (setq time (int-to-string time))
5944 (push (org-format-agenda-item
5945 nil string "" nil ;; FIXME: put a category for the grid?
5946 (concat (substring time 0 -2) ":" (substring time -2)))
5947 new)
5948 (put-text-property
5949 1 (length (car new)) 'face 'org-time-grid (car new))))
5950 (if (member 'time-up org-agenda-sorting-strategy)
5951 (append new list)
5952 (append list new)))))
5953
5954 (defun org-compile-prefix-format (format)
5955 "Compile the prefix format into a Lisp form that can be evaluated.
5956 The resulting form is returned and stored in the variable
5957 `org-prefix-format-compiled'."
5958 (setq org-prefix-has-time nil org-prefix-has-tag nil)
5959 (let ((start 0) varform vars var (s format)e c f opt)
5960 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5961 s start)
5962 (setq var (cdr (assoc (match-string 4 s)
5963 '(("c" . category) ("t" . time) ("s" . extra)
5964 ("T" . tag))))
5965 c (or (match-string 3 s) "")
5966 opt (match-beginning 1)
5967 start (1+ (match-beginning 0)))
5968 (if (equal var 'time) (setq org-prefix-has-time t))
5969 (if (equal var 'tag) (setq org-prefix-has-tag t))
5970 (setq f (concat "%" (match-string 2 s) "s"))
5971 (if opt
5972 (setq varform
5973 `(if (equal "" ,var)
5974 ""
5975 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5976 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5977 (setq s (replace-match "%s" t nil s))
5978 (push varform vars))
5979 (setq vars (nreverse vars))
5980 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5981
5982 (defun org-get-time-of-day (s &optional string)
5983 "Check string S for a time of day.
5984 If found, return it as a military time number between 0 and 2400.
5985 If not found, return nil.
5986 The optional STRING argument forces conversion into a 5 character wide string
5987 HH:MM."
5988 (save-match-data
5989 (when
5990 (or
5991 (string-match
5992 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5993 (string-match
5994 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5995 (let* ((t0 (+ (* 100
5996 (+ (string-to-number (match-string 1 s))
5997 (if (and (match-beginning 4)
5998 (equal (downcase (match-string 4 s)) "pm"))
5999 12 0)))
6000 (if (match-beginning 3)
6001 (string-to-number (match-string 3 s))
6002 0)))
6003 (t1 (concat " "
6004 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6005 (int-to-string t0))))
6006 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6007
6008 (defun org-finalize-agenda-entries (list)
6009 "Sort and concatenate the agenda items."
6010 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6011
6012 (defsubst org-cmp-priority (a b)
6013 "Compare the priorities of string A and B."
6014 (let ((pa (or (get-text-property 1 'priority a) 0))
6015 (pb (or (get-text-property 1 'priority b) 0)))
6016 (cond ((> pa pb) +1)
6017 ((< pa pb) -1)
6018 (t nil))))
6019
6020 (defsubst org-cmp-category (a b)
6021 "Compare the string values of categories of strings A and B."
6022 (let ((ca (or (get-text-property 1 'category a) ""))
6023 (cb (or (get-text-property 1 'category b) "")))
6024 (cond ((string-lessp ca cb) -1)
6025 ((string-lessp cb ca) +1)
6026 (t nil))))
6027
6028 (defsubst org-cmp-time (a b)
6029 "Compare the time-of-day values of strings A and B."
6030 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6031 (ta (or (get-text-property 1 'time-of-day a) def))
6032 (tb (or (get-text-property 1 'time-of-day b) def)))
6033 (cond ((< ta tb) -1)
6034 ((< tb ta) +1)
6035 (t nil))))
6036
6037 (defun org-entries-lessp (a b)
6038 "Predicate for sorting agenda entries."
6039 ;; The following variables will be used when the form is evaluated.
6040 (let* ((time-up (org-cmp-time a b))
6041 (time-down (if time-up (- time-up) nil))
6042 (priority-up (org-cmp-priority a b))
6043 (priority-down (if priority-up (- priority-up) nil))
6044 (category-up (org-cmp-category a b))
6045 (category-down (if category-up (- category-up) nil))
6046 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
6047 (cdr (assoc
6048 (eval (cons 'or org-agenda-sorting-strategy))
6049 '((-1 . t) (1 . nil) (nil . nil))))))
6050
6051 (defun org-agenda-show-priority ()
6052 "Show the priority of the current item.
6053 This priority is composed of the main priority given with the [#A] cookies,
6054 and by additional input from the age of a schedules or deadline entry."
6055 (interactive)
6056 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6057 (message "Priority is %d" (if pri pri -1000))))
6058
6059 (defun org-agenda-show-tags ()
6060 "Show the tags applicable to the current item."
6061 (interactive)
6062 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6063 (if tags
6064 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6065 (message "No tags associated with this line"))))
6066
6067 (defun org-agenda-goto (&optional highlight)
6068 "Go to the Org-mode file which contains the item at point."
6069 (interactive)
6070 (let* ((marker (or (get-text-property (point) 'org-marker)
6071 (org-agenda-error)))
6072 (buffer (marker-buffer marker))
6073 (pos (marker-position marker)))
6074 (switch-to-buffer-other-window buffer)
6075 (widen)
6076 (goto-char pos)
6077 (when (eq major-mode 'org-mode)
6078 (org-show-hidden-entry)
6079 (save-excursion
6080 (and (outline-next-heading)
6081 (org-flag-heading nil)))) ; show the next heading
6082 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6083
6084 (defun org-agenda-switch-to ()
6085 "Go to the Org-mode file which contains the item at point."
6086 (interactive)
6087 (let* ((marker (or (get-text-property (point) 'org-marker)
6088 (org-agenda-error)))
6089 (buffer (marker-buffer marker))
6090 (pos (marker-position marker)))
6091 (switch-to-buffer buffer)
6092 (delete-other-windows)
6093 (widen)
6094 (goto-char pos)
6095 (when (eq major-mode 'org-mode)
6096 (org-show-hidden-entry)
6097 (save-excursion
6098 (and (outline-next-heading)
6099 (org-flag-heading nil)))))) ; show the next heading
6100
6101 (defun org-agenda-goto-mouse (ev)
6102 "Go to the Org-mode file which contains the item at the mouse click."
6103 (interactive "e")
6104 (mouse-set-point ev)
6105 (org-agenda-goto))
6106
6107 (defun org-agenda-show ()
6108 "Display the Org-mode file which contains the item at point."
6109 (interactive)
6110 (let ((win (selected-window)))
6111 (org-agenda-goto t)
6112 (select-window win)))
6113
6114 (defun org-agenda-recenter (arg)
6115 "Display the Org-mode file which contains the item at point and recenter."
6116 (interactive "P")
6117 (let ((win (selected-window)))
6118 (org-agenda-goto t)
6119 (recenter arg)
6120 (select-window win)))
6121
6122 (defun org-agenda-show-mouse (ev)
6123 "Display the Org-mode file which contains the item at the mouse click."
6124 (interactive "e")
6125 (mouse-set-point ev)
6126 (org-agenda-show))
6127
6128 (defun org-agenda-check-no-diary ()
6129 "Check if the entry is a diary link and abort if yes."
6130 (if (get-text-property (point) 'org-agenda-diary-link)
6131 (org-agenda-error)))
6132
6133 (defun org-agenda-error ()
6134 (error "Command not allowed in this line"))
6135
6136 (defvar org-last-heading-marker (make-marker)
6137 "Marker pointing to the headline that last changed its TODO state
6138 by a remote command from the agenda.")
6139
6140 (defun org-agenda-todo (&optional arg)
6141 "Cycle TODO state of line at point, also in Org-mode file.
6142 This changes the line at point, all other lines in the agenda referring to
6143 the same tree node, and the headline of the tree node in the Org-mode file."
6144 (interactive "P")
6145 (org-agenda-check-no-diary)
6146 (let* ((col (current-column))
6147 (marker (or (get-text-property (point) 'org-marker)
6148 (org-agenda-error)))
6149 (buffer (marker-buffer marker))
6150 (pos (marker-position marker))
6151 (hdmarker (get-text-property (point) 'org-hd-marker))
6152 (buffer-read-only nil)
6153 newhead)
6154 (with-current-buffer buffer
6155 (widen)
6156 (goto-char pos)
6157 (org-show-hidden-entry)
6158 (save-excursion
6159 (and (outline-next-heading)
6160 (org-flag-heading nil))) ; show the next heading
6161 (org-todo arg)
6162 (forward-char 1)
6163 (setq newhead (org-get-heading))
6164 (save-excursion
6165 (org-back-to-heading)
6166 (move-marker org-last-heading-marker (point))))
6167 (beginning-of-line 1)
6168 (save-excursion
6169 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6170 (move-to-column col)))
6171
6172 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6173 "Change all lines in the agenda buffer which match HDMARKER.
6174 The new content of the line will be NEWHEAD (as modified by
6175 `org-format-agenda-item'). HDMARKER is checked with
6176 `equal' against all `org-hd-marker' text properties in the file.
6177 If FIXFACE is non-nil, the face of each item is modified acording to
6178 the new TODO state."
6179 (let* (props m pl undone-face done-face finish new dotime cat tags)
6180 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6181 (save-excursion
6182 (goto-char (point-max))
6183 (beginning-of-line 1)
6184 (while (not finish)
6185 (setq finish (bobp))
6186 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6187 (equal m hdmarker))
6188 (setq props (text-properties-at (point))
6189 dotime (get-text-property (point) 'dotime)
6190 cat (get-text-property (point) 'category)
6191 tags (get-text-property (point) 'tags)
6192 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6193 pl (get-text-property (point) 'prefix-length)
6194 undone-face (get-text-property (point) 'undone-face)
6195 done-face (get-text-property (point) 'done-face))
6196 (move-to-column pl)
6197 (if (looking-at ".*")
6198 (progn
6199 (replace-match new t t)
6200 (beginning-of-line 1)
6201 (add-text-properties (point-at-bol) (point-at-eol) props)
6202 (if fixface
6203 (add-text-properties
6204 (point-at-bol) (point-at-eol)
6205 (list 'face
6206 (if org-last-todo-state-is-todo
6207 undone-face done-face))))
6208 (beginning-of-line 1))
6209 (error "Line update did not work")))
6210 (beginning-of-line 0)))))
6211
6212 (defun org-agenda-priority-up ()
6213 "Increase the priority of line at point, also in Org-mode file."
6214 (interactive)
6215 (org-agenda-priority 'up))
6216
6217 (defun org-agenda-priority-down ()
6218 "Decrease the priority of line at point, also in Org-mode file."
6219 (interactive)
6220 (org-agenda-priority 'down))
6221
6222 (defun org-agenda-priority (&optional force-direction)
6223 "Set the priority of line at point, also in Org-mode file.
6224 This changes the line at point, all other lines in the agenda referring to
6225 the same tree node, and the headline of the tree node in the Org-mode file."
6226 (interactive)
6227 (org-agenda-check-no-diary)
6228 (let* ((marker (or (get-text-property (point) 'org-marker)
6229 (org-agenda-error)))
6230 (buffer (marker-buffer marker))
6231 (pos (marker-position marker))
6232 (hdmarker (get-text-property (point) 'org-hd-marker))
6233 (buffer-read-only nil)
6234 newhead)
6235 (with-current-buffer buffer
6236 (widen)
6237 (goto-char pos)
6238 (org-show-hidden-entry)
6239 (save-excursion
6240 (and (outline-next-heading)
6241 (org-flag-heading nil))) ; show the next heading
6242 (funcall 'org-priority force-direction)
6243 (end-of-line 1)
6244 (setq newhead (org-get-heading)))
6245 (org-agenda-change-all-lines newhead hdmarker)
6246 (beginning-of-line 1)))
6247
6248 (defun org-get-tags-at (&optional pos)
6249 "Get a list of all headline targs applicable at POS.
6250 POS defaults to point. If tags are inherited, the list contains
6251 the targets in the same sequence as the headlines appear, i.e.
6252 the tags of the current headline come last."
6253 (interactive)
6254 (let (tags)
6255 (save-excursion
6256 (goto-char (or pos (point)))
6257 (save-match-data
6258 (org-back-to-heading t)
6259 (condition-case nil
6260 (while t
6261 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6262 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6263 (or org-use-tag-inheritance (error ""))
6264 (org-up-heading-all 1))
6265 (error nil))))
6266 (message "%s" tags)
6267 tags))
6268
6269 (defun org-agenda-set-tags ()
6270 "Set tags for the current headline."
6271 (interactive)
6272 (org-agenda-check-no-diary)
6273 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6274 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6275 (org-agenda-error)))
6276 (buffer (marker-buffer hdmarker))
6277 (pos (marker-position hdmarker))
6278 (buffer-read-only nil)
6279 newhead)
6280 (with-current-buffer buffer
6281 (widen)
6282 (goto-char pos)
6283 (org-show-hidden-entry)
6284 (save-excursion
6285 (and (outline-next-heading)
6286 (org-flag-heading nil))) ; show the next heading
6287 (call-interactively 'org-set-tags)
6288 (end-of-line 1)
6289 (setq newhead (org-get-heading)))
6290 (org-agenda-change-all-lines newhead hdmarker)
6291 (beginning-of-line 1)))
6292
6293 (defun org-agenda-date-later (arg &optional what)
6294 "Change the date of this item to one day later."
6295 (interactive "p")
6296 (org-agenda-check-type t 'agenda 'timeline)
6297 (org-agenda-check-no-diary)
6298 (let* ((marker (or (get-text-property (point) 'org-marker)
6299 (org-agenda-error)))
6300 (buffer (marker-buffer marker))
6301 (pos (marker-position marker)))
6302 (with-current-buffer buffer
6303 (widen)
6304 (goto-char pos)
6305 (if (not (org-at-timestamp-p))
6306 (error "Cannot find time stamp"))
6307 (org-timestamp-change arg (or what 'day))
6308 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6309
6310 (defun org-agenda-date-earlier (arg &optional what)
6311 "Change the date of this item to one day earlier."
6312 (interactive "p")
6313 (org-agenda-date-later (- arg) what))
6314
6315 (defun org-agenda-date-prompt (arg)
6316 "Change the date of this item. Date is prompted for, with default today.
6317 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6318 be used to request time specification in the time stamp."
6319 (interactive "P")
6320 (org-agenda-check-type t 'agenda 'timeline)
6321 (org-agenda-check-no-diary)
6322 (let* ((marker (or (get-text-property (point) 'org-marker)
6323 (org-agenda-error)))
6324 (buffer (marker-buffer marker))
6325 (pos (marker-position marker)))
6326 (with-current-buffer buffer
6327 (widen)
6328 (goto-char pos)
6329 (if (not (org-at-timestamp-p))
6330 (error "Cannot find time stamp"))
6331 (org-time-stamp arg)
6332 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6333
6334 (defun org-get-heading ()
6335 "Return the heading of the current entry, without the stars."
6336 (save-excursion
6337 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6338 ;;FIXME???????? (and (bolp) (end-of-line 1))
6339 (if (and (re-search-backward "[\r\n]\\*" nil t)
6340 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6341 (match-string 1)
6342 "")))
6343
6344 (defun org-agenda-diary-entry ()
6345 "Make a diary entry, like the `i' command from the calendar.
6346 All the standard commands work: block, weekly etc."
6347 (interactive)
6348 (org-agenda-check-type t 'agenda 'timeline)
6349 (require 'diary-lib)
6350 (let* ((char (progn
6351 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6352 (read-char-exclusive)))
6353 (cmd (cdr (assoc char
6354 '((?d . insert-diary-entry)
6355 (?w . insert-weekly-diary-entry)
6356 (?m . insert-monthly-diary-entry)
6357 (?y . insert-yearly-diary-entry)
6358 (?a . insert-anniversary-diary-entry)
6359 (?b . insert-block-diary-entry)
6360 (?c . insert-cyclic-diary-entry)))))
6361 (oldf (symbol-function 'calendar-cursor-to-date))
6362 (point (point))
6363 (mark (or (mark t) (point))))
6364 (unless cmd
6365 (error "No command associated with <%c>" char))
6366 (unless (and (get-text-property point 'day)
6367 (or (not (equal ?b char))
6368 (get-text-property mark 'day)))
6369 (error "Don't know which date to use for diary entry"))
6370 ;; We implement this by hacking the `calendar-cursor-to-date' function
6371 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6372 (let ((calendar-mark-ring
6373 (list (calendar-gregorian-from-absolute
6374 (or (get-text-property mark 'day)
6375 (get-text-property point 'day))))))
6376 (unwind-protect
6377 (progn
6378 (fset 'calendar-cursor-to-date
6379 (lambda (&optional error)
6380 (calendar-gregorian-from-absolute
6381 (get-text-property point 'day))))
6382 (call-interactively cmd))
6383 (fset 'calendar-cursor-to-date oldf)))))
6384
6385
6386 (defun org-agenda-execute-calendar-command (cmd)
6387 "Execute a calendar command from the agenda, with the date associated to
6388 the cursor position."
6389 (org-agenda-check-type t 'agenda 'timeline)
6390 (require 'diary-lib)
6391 (unless (get-text-property (point) 'day)
6392 (error "Don't know which date to use for calendar command"))
6393 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6394 (point (point))
6395 (date (calendar-gregorian-from-absolute
6396 (get-text-property point 'day)))
6397 (displayed-day (extract-calendar-day date))
6398 (displayed-month (extract-calendar-month date))
6399 (displayed-year (extract-calendar-year date)))
6400 (unwind-protect
6401 (progn
6402 (fset 'calendar-cursor-to-date
6403 (lambda (&optional error)
6404 (calendar-gregorian-from-absolute
6405 (get-text-property point 'day))))
6406 (call-interactively cmd))
6407 (fset 'calendar-cursor-to-date oldf))))
6408
6409 (defun org-agenda-phases-of-moon ()
6410 "Display the phases of the moon for the 3 months around the cursor date."
6411 (interactive)
6412 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6413
6414 (defun org-agenda-holidays ()
6415 "Display the holidays for the 3 months around the cursor date."
6416 (interactive)
6417 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6418
6419 (defun org-agenda-sunrise-sunset (arg)
6420 "Display sunrise and sunset for the cursor date.
6421 Latitude and longitude can be specified with the variables
6422 `calendar-latitude' and `calendar-longitude'. When called with prefix
6423 argument, latitude and longitude will be prompted for."
6424 (interactive "P")
6425 (let ((calendar-longitude (if arg nil calendar-longitude))
6426 (calendar-latitude (if arg nil calendar-latitude))
6427 (calendar-location-name
6428 (if arg "the given coordinates" calendar-location-name)))
6429 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6430
6431 (defun org-agenda-goto-calendar ()
6432 "Open the Emacs calendar with the date at the cursor."
6433 (interactive)
6434 (org-agenda-check-type t 'agenda 'timeline)
6435 (let* ((day (or (get-text-property (point) 'day)
6436 (error "Don't know which date to open in calendar")))
6437 (date (calendar-gregorian-from-absolute day))
6438 (calendar-move-hook nil)
6439 (view-diary-entries-initially nil))
6440 (calendar)
6441 (calendar-goto-date date)))
6442
6443 (defun org-calendar-goto-agenda ()
6444 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6445 This is a command that has to be installed in `calendar-mode-map'."
6446 (interactive)
6447 (org-agenda-list nil (calendar-absolute-from-gregorian
6448 (calendar-cursor-to-date))
6449 nil t))
6450
6451 (defun org-agenda-convert-date ()
6452 (interactive)
6453 (org-agenda-check-type t 'agenda 'timeline)
6454 (let ((day (get-text-property (point) 'day))
6455 date s)
6456 (unless day
6457 (error "Don't know which date to convert"))
6458 (setq date (calendar-gregorian-from-absolute day))
6459 (setq s (concat
6460 "Gregorian: " (calendar-date-string date) "\n"
6461 "ISO: " (calendar-iso-date-string date) "\n"
6462 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6463 "Julian: " (calendar-julian-date-string date) "\n"
6464 "Astron. JD: " (calendar-astro-date-string date)
6465 " (Julian date number at noon UTC)\n"
6466 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6467 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6468 "French: " (calendar-french-date-string date) "\n"
6469 "Mayan: " (calendar-mayan-date-string date) "\n"
6470 "Coptic: " (calendar-coptic-date-string date) "\n"
6471 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6472 "Persian: " (calendar-persian-date-string date) "\n"
6473 "Chinese: " (calendar-chinese-date-string date) "\n"))
6474 (with-output-to-temp-buffer "*Dates*"
6475 (princ s))
6476 (if (fboundp 'fit-window-to-buffer)
6477 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6478
6479 ;;; Tags
6480
6481 (defun org-scan-tags (action matcher &optional todo-only)
6482 "Scan headline tags with inheritance and produce output ACTION.
6483 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6484 evaluated, testing if a given set of tags qualifies a headline for
6485 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6486 are included in the output."
6487 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6488 (mapconcat 'regexp-quote
6489 (nreverse (cdr (reverse org-todo-keywords)))
6490 "\\|")
6491 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6492 (props (list 'face nil
6493 'done-face 'org-done
6494 'undone-face nil
6495 'mouse-face 'highlight
6496 'keymap org-agenda-keymap
6497 'help-echo
6498 (format "mouse-2 or RET jump to org file %s"
6499 (abbreviate-file-name (buffer-file-name)))))
6500 lspos
6501 tags tags-list tags-alist (llast 0) rtn level category i txt
6502 todo marker)
6503
6504 (save-excursion
6505 (goto-char (point-min))
6506 (when (eq action 'sparse-tree) (hide-sublevels 1))
6507 (while (re-search-forward re nil t)
6508 (setq todo (if (match-end 1) (match-string 2))
6509 tags (if (match-end 4) (match-string 4)))
6510 (goto-char (setq lspos (1+ (match-beginning 0))))
6511 (setq level (outline-level)
6512 category (org-get-category))
6513 (setq i llast llast level)
6514 ;; remove tag lists from same and sublevels
6515 (while (>= i level)
6516 (when (setq entry (assoc i tags-alist))
6517 (setq tags-alist (delete entry tags-alist)))
6518 (setq i (1- i)))
6519 ;; add the nex tags
6520 (when tags
6521 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6522 tags-alist
6523 (cons (cons level tags) tags-alist)))
6524 ;; compile tags for current headline
6525 (setq tags-list
6526 (if org-use-tag-inheritance
6527 (apply 'append (mapcar 'cdr tags-alist))
6528 tags))
6529 (when (and (or (not todo-only) todo)
6530 (eval matcher))
6531 ;; list this headline
6532 (if (eq action 'sparse-tree)
6533 (progn
6534 (org-show-hierarchy-above))
6535 (setq txt (org-format-agenda-item
6536 ""
6537 (concat
6538 (if org-tags-match-list-sublevels
6539 (make-string (1- level) ?.) "")
6540 (org-get-heading))
6541 category tags-list))
6542 (goto-char lspos)
6543 (setq marker (org-agenda-new-marker))
6544 (add-text-properties
6545 0 (length txt)
6546 (append (list 'org-marker marker 'org-hd-marker marker
6547 'category category)
6548 props)
6549 txt)
6550 (push txt rtn))
6551 ;; if we are to skip sublevels, jump to end of subtree
6552 (point)
6553 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6554 (nreverse rtn)))
6555
6556 (defun org-tags-sparse-tree (&optional arg match)
6557 "Create a sparse tree according to tags search string MATCH.
6558 MATCH can contain positive and negative selection of tags, like
6559 \"+WORK+URGENT-WITHBOSS\"."
6560 (interactive "P")
6561 (let ((org-show-following-heading nil)
6562 (org-show-hierarchy-above nil))
6563 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6564
6565 (defun org-make-tags-matcher (match)
6566 "Create the TAGS matcher form for the tags-selecting string MATCH."
6567 (unless match
6568 ;; Get a new match request, with completion
6569 (setq org-last-tags-completion-table
6570 (or (org-get-buffer-tags)
6571 org-last-tags-completion-table))
6572 (setq match (completing-read
6573 "Tags: " 'org-tags-completion-function nil nil nil
6574 'org-tags-history)))
6575 ;; parse the string and create a lisp form
6576 (let ((match0 match) minus tag mm matcher orterms term orlist)
6577 (setq orterms (org-split-string match "|"))
6578 (while (setq term (pop orterms))
6579 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
6580 (setq minus (and (match-end 1)
6581 (equal (match-string 1 term) "-"))
6582 tag (match-string 2 term)
6583 term (substring term (match-end 0))
6584 mm (list 'member (downcase tag) 'tags-list)
6585 mm (if minus (list 'not mm) mm))
6586 (push mm matcher))
6587 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6588 orlist)
6589 (setq matcher nil))
6590 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6591 ;; Return the string and lisp forms of the matcher
6592 (cons match0 matcher)))
6593
6594 ;;;###autoload
6595 (defun org-tags-view (&optional todo-only match keep-modes)
6596 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
6597 The prefix arg TODO-ONLY limits the search to TODO entries."
6598 (interactive "P")
6599 (org-agenda-maybe-reset-markers 'force)
6600 (org-compile-prefix-format org-agenda-prefix-format)
6601 (let* ((org-agenda-keep-modes keep-modes)
6602 (org-tags-match-list-sublevels
6603 (if todo-only t org-tags-match-list-sublevels))
6604 (win (selected-window))
6605 (completion-ignore-case t)
6606 rtn rtnall files file pos matcher
6607 buffer)
6608 (setq matcher (org-make-tags-matcher match)
6609 match (car matcher) matcher (cdr matcher))
6610 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6611 (progn
6612 (delete-other-windows)
6613 (switch-to-buffer-other-window
6614 (get-buffer-create org-agenda-buffer-name))))
6615 (setq buffer-read-only nil)
6616 (erase-buffer)
6617 (org-agenda-mode) (setq buffer-read-only nil)
6618 (set (make-local-variable 'org-agenda-type) 'tags)
6619 (set (make-local-variable 'org-agenda-redo-command)
6620 (list 'org-tags-view (list 'quote todo-only)
6621 (list 'if 'current-prefix-arg nil match) t))
6622 (setq files (org-agenda-files)
6623 rtnall nil)
6624 (while (setq file (pop files))
6625 (catch 'nextfile
6626 (org-check-agenda-file file)
6627 (setq buffer (if (file-exists-p file)
6628 (org-get-agenda-file-buffer file)
6629 (error "No such file %s" file)))
6630 (if (not buffer)
6631 ;; If file does not exist, merror message to agenda
6632 (setq rtn (list
6633 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6634 rtnall (append rtnall rtn))
6635 (with-current-buffer buffer
6636 (unless (eq major-mode 'org-mode)
6637 (error "Agenda file %s is not in `org-mode'" file))
6638 (save-excursion
6639 (save-restriction
6640 (if org-respect-restriction
6641 (if (org-region-active-p)
6642 ;; Respect a region to restrict search
6643 (narrow-to-region (region-beginning) (region-end)))
6644 ;; If we work for the calendar or many files,
6645 ;; get rid of any restriction
6646 (widen))
6647 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6648 (setq rtnall (append rtnall rtn))))))))
6649 (insert "Headlines with TAGS match: ")
6650 (add-text-properties (point-min) (1- (point))
6651 (list 'face 'org-link))
6652 (setq pos (point))
6653 (insert match "\n")
6654 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6655 (setq pos (point))
6656 (insert "Press `C-u r' to search again with new search string\n")
6657 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6658 (when rtnall
6659 (insert (mapconcat 'identity rtnall "\n")))
6660 (goto-char (point-min))
6661 (setq buffer-read-only t)
6662 (org-fit-agenda-window)
6663 (if (not org-select-agenda-window) (select-window win))))
6664
6665 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6666 (defun org-set-tags (&optional arg just-align)
6667 "Set the tags for the current headline.
6668 With prefix ARG, realign all tags in headings in the current buffer."
6669 (interactive)
6670 (let* (;(inherit (org-get-inherited-tags))
6671 (re (concat "^" outline-regexp))
6672 (col (current-column))
6673 (current (org-get-tags))
6674 tags hd empty invis)
6675 (if arg
6676 (save-excursion
6677 (goto-char (point-min))
6678 (while (re-search-forward re nil t)
6679 (org-set-tags nil t))
6680 (message "All tags realigned to column %d" org-tags-column))
6681 (if just-align
6682 (setq tags current)
6683 (setq org-last-tags-completion-table
6684 (or (org-get-buffer-tags)
6685 org-last-tags-completion-table))
6686 (setq tags
6687 (let ((org-add-colon-after-tag-completion t))
6688 (completing-read "Tags: " 'org-tags-completion-function
6689 nil nil current 'org-tags-history)))
6690 (while (string-match "[-+&]+" tags)
6691 (setq tags (replace-match ":" t t tags))))
6692 ;; FIXME: still optimize this byt not checking when JUST-ALIGN?
6693 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6694 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6695 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
6696 (if (equal current "")
6697 (progn
6698 (end-of-line 1)
6699 (or empty (insert-before-markers " ")))
6700 (beginning-of-line 1)
6701 (setq invis (org-invisible-p))
6702 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6703 (setq hd (match-string 1))
6704 (delete-region (match-beginning 0) (match-end 0))
6705 (insert-before-markers (org-trim hd) (if empty "" " ")))
6706 ;; FIXME: What happens when adding a new tag??? Seems OK!!!
6707 (unless (equal tags "")
6708 (move-to-column (max (current-column)
6709 (if (> org-tags-column 0)
6710 org-tags-column
6711 (- (- org-tags-column) (length tags))))
6712 t)
6713 (insert-before-markers tags)
6714 (if (and (not invis) (org-invisible-p))
6715 (outline-flag-region (point-at-bol) (point) nil)))
6716 (move-to-column col))))
6717
6718 (defun org-tags-completion-function (string predicate &optional flag)
6719 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6720 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6721 (setq s1 (match-string 1 string)
6722 s2 (match-string 2 string))
6723 (setq s1 "" s2 string))
6724 (cond
6725 ((eq flag nil)
6726 ;; try completion
6727 (setq rtn (try-completion s2 ctable))
6728 (if (stringp rtn)
6729 (concat s1 s2 (substring rtn (length s2))
6730 (if (and org-add-colon-after-tag-completion
6731 (assoc rtn ctable))
6732 ":" "")))
6733 )
6734 ((eq flag t)
6735 ;; all-completions
6736 (all-completions s2 ctable)
6737 )
6738 ((eq flag 'lambda)
6739 ;; exact match?
6740 (assoc s2 ctable)))
6741 ))
6742
6743 (defun org-get-tags ()
6744 "Get the TAGS string in the current headline."
6745 (unless (org-on-heading-p)
6746 (error "Not on a heading"))
6747 (save-excursion
6748 (beginning-of-line 1)
6749 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
6750 (match-string 1)
6751 "")))
6752
6753 (defun org-get-buffer-tags ()
6754 "Get a table of all tags used in the buffer, for completion."
6755 (let (tags)
6756 (save-excursion
6757 (goto-char (point-min))
6758 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
6759 (mapc (lambda (x) (add-to-list 'tags x))
6760 (org-split-string (match-string 1) ":"))))
6761 (mapcar 'list tags)))
6762
6763 ;;; Link Stuff
6764
6765 (defun org-find-file-at-mouse (ev)
6766 "Open file link or URL at mouse."
6767 (interactive "e")
6768 (mouse-set-point ev)
6769 (org-open-at-point 'in-emacs))
6770
6771 (defun org-open-at-mouse (ev)
6772 "Open file link or URL at mouse."
6773 (interactive "e")
6774 (mouse-set-point ev)
6775 (org-open-at-point))
6776
6777 (defun org-open-at-point (&optional in-emacs)
6778 "Open link at or after point.
6779 If there is no link at point, this function will search forward up to
6780 the end of the current subtree.
6781 Normally, files will be opened by an appropriate application. If the
6782 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6783 (interactive "P")
6784 (org-remove-occur-highlights nil nil t)
6785 (if (org-at-timestamp-p)
6786 (org-agenda-list nil (time-to-days (org-time-string-to-time
6787 (substring (match-string 1) 0 10)))
6788 1)
6789 (let (type path link line search (pos (point)))
6790 (catch 'match
6791 (save-excursion
6792 (skip-chars-forward "^]\n\r")
6793 (when (and (re-search-backward "\\[\\[" nil t)
6794 (looking-at org-bracket-link-regexp)
6795 (<= (match-beginning 0) pos)
6796 (>= (match-end 0) pos))
6797 (setq link (match-string 1))
6798 (while (string-match " *\n *" link)
6799 (setq link (replace-match " " t t link)))
6800 (if (string-match org-link-regexp link)
6801 (setq type (match-string 1)
6802 path (match-string 2))
6803 (setq type "thisfile"
6804 path link))
6805 (throw 'match t)))
6806
6807 (when (get-text-property (point) 'org-linked-text)
6808 (setq type "thisfile"
6809 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6810 (1+ (point)) (point))
6811 path (buffer-substring
6812 (previous-single-property-change pos 'org-linked-text)
6813 (next-single-property-change pos 'org-linked-text)))
6814 (throw 'match t))
6815
6816 (save-excursion
6817 (skip-chars-backward
6818 (concat (if org-allow-space-in-links "^" "^ ")
6819 org-non-link-chars))
6820 (when (or (looking-at org-link-regexp)
6821 (and (re-search-forward org-link-regexp (point-at-eol) t)
6822 (<= (match-beginning 0) pos)
6823 (>= (match-end 0) pos)))
6824 (setq type (match-string 1)
6825 path (match-string 2))
6826 (throw 'match t)))
6827 (save-excursion
6828 (skip-chars-backward "^ \t\n\r")
6829 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
6830 (setq type "tags"
6831 path (match-string 1))
6832 (while (string-match ":" path)
6833 (setq path (replace-match "+" t t path)))
6834 (throw 'match t)))
6835 (save-excursion
6836 (skip-chars-backward "a-zA-Z_")
6837 (when (and org-activate-camels
6838 (looking-at org-camel-regexp))
6839 (setq type "camel" path (match-string 0))
6840 (if (equal (char-before) ?*)
6841 (setq path (concat "*" path))))
6842 (throw 'match t))
6843 (save-excursion
6844 (when (re-search-forward
6845 org-link-regexp
6846 (save-excursion
6847 (condition-case nil
6848 (progn (outline-end-of-subtree) (max pos (point)))
6849 (error (end-of-line 1) (point))))
6850 t)
6851 (setq type (match-string 1)
6852 path (match-string 2)))))
6853 (unless path
6854 (error "No link found"))
6855 ;; Remove any trailing spaces in path
6856 (if (string-match " +\\'" path)
6857 (setq path (replace-match "" t t path)))
6858
6859 (cond
6860
6861 ((string= type "tags")
6862 (org-tags-view in-emacs path))
6863 ((or (string= type "camel")
6864 (string= type "thisfile"))
6865 (org-mark-ring-push)
6866 (org-link-search
6867 path
6868 (cond ((equal in-emacs '(4)) 'occur)
6869 ((equal in-emacs '(16)) 'org-occur)
6870 (t nil))))
6871
6872 ((string= type "file")
6873 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6874 (setq line (string-to-number (match-string 1 path))
6875 path (substring path 0 (match-beginning 0)))
6876 (if (string-match "::\\(.+\\)\\'" path)
6877 (setq search (match-string 1 path)
6878 path (substring path 0 (match-beginning 0)))))
6879 (org-open-file path in-emacs line search))
6880
6881 ((string= type "news")
6882 (org-follow-gnus-link path))
6883
6884 ((string= type "bbdb")
6885 (org-follow-bbdb-link path))
6886
6887 ((string= type "gnus")
6888 (let (group article)
6889 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6890 (error "Error in Gnus link"))
6891 (setq group (match-string 1 path)
6892 article (match-string 3 path))
6893 (org-follow-gnus-link group article)))
6894
6895 ((string= type "vm")
6896 (let (folder article)
6897 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6898 (error "Error in VM link"))
6899 (setq folder (match-string 1 path)
6900 article (match-string 3 path))
6901 ;; in-emacs is the prefix arg, will be interpreted as read-only
6902 (org-follow-vm-link folder article in-emacs)))
6903
6904 ((string= type "wl")
6905 (let (folder article)
6906 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6907 (error "Error in Wanderlust link"))
6908 (setq folder (match-string 1 path)
6909 article (match-string 3 path))
6910 (org-follow-wl-link folder article)))
6911
6912 ((string= type "mhe")
6913 (let (folder article)
6914 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6915 (error "Error in MHE link"))
6916 (setq folder (match-string 1 path)
6917 article (match-string 3 path))
6918 (org-follow-mhe-link folder article)))
6919
6920 ((string= type "rmail")
6921 (let (folder article)
6922 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6923 (error "Error in RMAIL link"))
6924 (setq folder (match-string 1 path)
6925 article (match-string 3 path))
6926 (org-follow-rmail-link folder article)))
6927
6928 ((string= type "shell")
6929 (let ((cmd path))
6930 (while (string-match "@{" cmd)
6931 (setq cmd (replace-match "<" t t cmd)))
6932 (while (string-match "@}" cmd)
6933 (setq cmd (replace-match ">" t t cmd)))
6934 (if (or (not org-confirm-shell-links)
6935 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6936 (shell-command cmd)
6937 (error "Abort"))))
6938
6939 (t
6940 (browse-url-at-point))))))
6941
6942 (defun org-link-search (s &optional type)
6943 "Search for a link search option.
6944 When S is a CamelCaseWord, search for a target, or for a sentence containing
6945 the words. If S is surrounded by forward slashes, it is interpreted as a
6946 regular expression. In org-mode files, this will create an `org-occur'
6947 sparse tree. In ordinary files, `occur' will be used to list matches.
6948 If the current buffer is in `dired-mode', grep will be used to search
6949 in all files."
6950 (let ((case-fold-search t)
6951 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6952 (pos (point))
6953 (pre "") (post "")
6954 words re0 re1 re2 re3 re4 re5 reall camel)
6955 (cond ((save-excursion
6956 (goto-char (point-min))
6957 (and
6958 (re-search-forward
6959 (concat "<<" (regexp-quote s0) ">>") nil t)
6960 (setq pos (match-beginning 0))))
6961 ;; There is an exact target for this
6962 (goto-char pos))
6963 ((string-match "^/\\(.*\\)/$" s)
6964 ;; A regular expression
6965 (cond
6966 ((eq major-mode 'org-mode)
6967 (org-occur (match-string 1 s)))
6968 ;;((eq major-mode 'dired-mode)
6969 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6970 (t (org-do-occur (match-string 1 s)))))
6971 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
6972 t)
6973 ;; A camel or a normal search string
6974 (when (equal (string-to-char s) ?*)
6975 ;; Anchor on headlines, post may include tags.
6976 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6977 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
6978 s (substring s 1)))
6979 (remove-text-properties
6980 0 (length s)
6981 '(face nil mouse-face nil keymap nil fontified nil) s)
6982 ;; Make a series of regular expressions to find a match
6983 (setq words
6984 (if camel
6985 (org-camel-to-words s)
6986 (org-split-string s "[ \n\r\t]+"))
6987 re0 (concat "<<" (regexp-quote s0) ">>")
6988 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6989 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6990 re1 (concat pre re2 post)
6991 re3 (concat pre re4 post)
6992 re5 (concat pre ".*" re4)
6993 re2 (concat pre re2)
6994 re4 (concat pre re4)
6995 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6996 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6997 re5 "\\)"
6998 ))
6999 (cond
7000 ((eq type 'org-occur) (org-occur reall))
7001 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7002 (t (goto-char (point-min))
7003 (if (or (re-search-forward re0 nil t)
7004 (re-search-forward re1 nil t)
7005 (re-search-forward re2 nil t)
7006 (re-search-forward re3 nil t)
7007 (re-search-forward re4 nil t)
7008 (re-search-forward re5 nil t))
7009 (goto-char (match-beginning 0))
7010 (goto-char pos)
7011 (error "No match")))))
7012 (t
7013 ;; Normal string-search
7014 (goto-char (point-min))
7015 (if (search-forward s nil t)
7016 (goto-char (match-beginning 0))
7017 (error "No match"))))
7018 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7019
7020 (defun org-do-occur (regexp &optional cleanup)
7021 "Call the Emacs command `occur'.
7022 If CLEANUP is non-nil, remove the printout of the regular expression
7023 in the *Occur* buffer. This is useful if the regex is long and not useful
7024 to read."
7025 (occur regexp)
7026 (when cleanup
7027 (let ((cwin (selected-window)) win beg end)
7028 (when (setq win (get-buffer-window "*Occur*"))
7029 (select-window win))
7030 (goto-char (point-min))
7031 (when (re-search-forward "match[a-z]+" nil t)
7032 (setq beg (match-end 0))
7033 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7034 (setq end (1- (match-beginning 0)))))
7035 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7036 (goto-char (point-min))
7037 (select-window cwin))))
7038
7039 (defvar org-mark-ring nil
7040 "Mark ring for positions before jumps in Org-mode.")
7041 (defvar org-mark-ring-last-goto nil
7042 "Last position in the mark ring used to go back.")
7043 ;; Fill and close the ring
7044 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7045 (loop for i from 1 to org-mark-ring-length do
7046 (push (make-marker) org-mark-ring))
7047 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7048 org-mark-ring)
7049
7050 (defun org-mark-ring-push (&optional pos buffer)
7051 "Put the current position or POS into the mark ring and rotate it."
7052 (interactive)
7053 (setq pos (or pos (point)))
7054 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7055 (move-marker (car org-mark-ring)
7056 (or pos (point))
7057 (or buffer (current-buffer)))
7058 (message
7059 (substitute-command-keys
7060 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7061
7062 (defun org-mark-ring-goto (&optional n)
7063 "Jump to the previous position in the mark ring.
7064 With prefix arg N, jump back that many stored positions. When
7065 called several times in succession, walk through the entire ring.
7066 Org-mode commands jumping to a different position in the current file,
7067 or to another Org-mode file, automatically push the old position
7068 onto the ring."
7069 (interactive "p")
7070 (let (p m)
7071 (if (eq last-command this-command)
7072 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7073 (setq p org-mark-ring))
7074 (setq org-mark-ring-last-goto p)
7075 (setq m (car p))
7076 (switch-to-buffer (marker-buffer m))
7077 (goto-char m)
7078 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7079
7080 (defun org-camel-to-words (s)
7081 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7082 (let ((case-fold-search nil)
7083 words)
7084 (while (string-match "[a-z][A-Z]" s)
7085 (push (substring s 0 (1+ (match-beginning 0))) words)
7086 (setq s (substring s (1+ (match-beginning 0)))))
7087 (nreverse (cons s words))))
7088
7089 (defun org-remove-angle-brackets (s)
7090 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7091 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7092 s)
7093 (defun org-add-angle-brackets (s)
7094 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7095 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7096 s)
7097
7098 (defun org-follow-bbdb-link (name)
7099 "Follow a BBDB link to NAME."
7100 (require 'bbdb)
7101 (let ((inhibit-redisplay t)
7102 (bbdb-electric-p nil))
7103 (catch 'exit
7104 ;; Exact match on name
7105 (bbdb-name (concat "\\`" name "\\'") nil)
7106 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7107 ;; Exact match on name
7108 (bbdb-company (concat "\\`" name "\\'") nil)
7109 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7110 ;; Partial match on name
7111 (bbdb-name name nil)
7112 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7113 ;; Partial match on company
7114 (bbdb-company name nil)
7115 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7116 ;; General match including network address and notes
7117 (bbdb name nil)
7118 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7119 (delete-window (get-buffer-window "*BBDB*"))
7120 (error "No matching BBDB record")))))
7121
7122 (defun org-follow-gnus-link (&optional group article)
7123 "Follow a Gnus link to GROUP and ARTICLE."
7124 (require 'gnus)
7125 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7126 (if group (gnus-fetch-group group))
7127 (if article
7128 (or (gnus-summary-goto-article article nil 'force)
7129 (if (fboundp 'gnus-summary-insert-cached-articles)
7130 (progn
7131 (gnus-summary-insert-cached-articles)
7132 (gnus-summary-goto-article article nil 'force))
7133 (message "Message could not be found.")))))
7134
7135 (defun org-follow-vm-link (&optional folder article readonly)
7136 "Follow a VM link to FOLDER and ARTICLE."
7137 (require 'vm)
7138 (setq article (org-add-angle-brackets article))
7139 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7140 ;; ange-ftp or efs or tramp access
7141 (let ((user (or (match-string 1 folder) (user-login-name)))
7142 (host (match-string 2 folder))
7143 (file (match-string 3 folder)))
7144 (cond
7145 ((featurep 'tramp)
7146 ;; use tramp to access the file
7147 (if org-xemacs-p
7148 (setq folder (format "[%s@%s]%s" user host file))
7149 (setq folder (format "/%s@%s:%s" user host file))))
7150 (t
7151 ;; use ange-ftp or efs
7152 (require (if org-xemacs-p 'efs 'ange-ftp))
7153 (setq folder (format "/%s@%s:%s" user host file))))))
7154 (when folder
7155 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7156 (sit-for 0.1)
7157 (when article
7158 (vm-select-folder-buffer)
7159 (widen)
7160 (let ((case-fold-search t))
7161 (goto-char (point-min))
7162 (if (not (re-search-forward
7163 (concat "^" "message-id: *" (regexp-quote article))))
7164 (error "Could not find the specified message in this folder"))
7165 (vm-isearch-update)
7166 (vm-isearch-narrow)
7167 (vm-beginning-of-message)
7168 (vm-summarize)))))
7169
7170 (defun org-follow-wl-link (folder article)
7171 "Follow a Wanderlust link to FOLDER and ARTICLE."
7172 (setq article (org-add-angle-brackets article))
7173 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7174 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7175 (wl-summary-redisplay))
7176
7177 (defun org-follow-rmail-link (folder article)
7178 "Follow an RMAIL link to FOLDER and ARTICLE."
7179 (setq article (org-add-angle-brackets article))
7180 (let (message-number)
7181 (save-excursion
7182 (save-window-excursion
7183 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7184 (setq message-number
7185 (save-restriction
7186 (widen)
7187 (goto-char (point-max))
7188 (if (re-search-backward
7189 (concat "^Message-ID:\\s-+" (regexp-quote
7190 (or article "")))
7191 nil t)
7192 (rmail-what-message))))))
7193 (if message-number
7194 (progn
7195 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7196 (rmail-show-message message-number)
7197 message-number)
7198 (error "Message not found"))))
7199
7200 ;; mh-e integration based on planner-mode
7201 (defun org-mhe-get-message-real-folder ()
7202 "Return the name of the current message real folder, so if you use
7203 sequences, it will now work."
7204 (save-excursion
7205 (let* ((folder
7206 (if (equal major-mode 'mh-folder-mode)
7207 mh-current-folder
7208 ;; Refer to the show buffer
7209 mh-show-folder-buffer))
7210 (end-index
7211 (if (boundp 'mh-index-folder)
7212 (min (length mh-index-folder) (length folder))))
7213 )
7214 ;; a simple test on mh-index-data does not work, because
7215 ;; mh-index-data is always nil in a show buffer.
7216 (if (and (boundp 'mh-index-folder)
7217 (string= mh-index-folder (substring folder 0 end-index)))
7218 (if (equal major-mode 'mh-show-mode)
7219 (save-window-excursion
7220 (when (buffer-live-p (get-buffer folder))
7221 (progn
7222 (pop-to-buffer folder)
7223 (org-mhe-get-message-folder-from-index)
7224 )
7225 ))
7226 (org-mhe-get-message-folder-from-index)
7227 )
7228 folder
7229 )
7230 )))
7231
7232 (defun org-mhe-get-message-folder-from-index ()
7233 "Returns the name of the message folder in a index folder buffer."
7234 (save-excursion
7235 (mh-index-previous-folder)
7236 (if (not (re-search-forward "^\\(+.*\\)$" nil t))
7237 (message "Problem getting folder from index.")
7238 (message (match-string 1)))))
7239
7240 (defun org-mhe-get-message-folder ()
7241 "Return the name of the current message folder. Be careful if you
7242 use sequences."
7243 (save-excursion
7244 (if (equal major-mode 'mh-folder-mode)
7245 mh-current-folder
7246 ;; Refer to the show buffer
7247 mh-show-folder-buffer)))
7248
7249 (defun org-mhe-get-message-num ()
7250 "Return the number of the current message. Be careful if you
7251 use sequences."
7252 (save-excursion
7253 (if (equal major-mode 'mh-folder-mode)
7254 (mh-get-msg-num nil)
7255 ;; Refer to the show buffer
7256 (mh-show-buffer-message-number))))
7257
7258 (defun org-mhe-get-header (header)
7259 "Return a header of the message in folder mode. This will create a
7260 show buffer for the corresponding message. If you have a more clever
7261 idea..."
7262 (let* ((folder (org-mhe-get-message-folder))
7263 (num (org-mhe-get-message-num))
7264 (buffer (get-buffer-create (concat "show-" folder)))
7265 (header-field))
7266 (with-current-buffer buffer
7267 (mh-display-msg num folder)
7268 (if (equal major-mode 'mh-folder-mode)
7269 (mh-header-display)
7270 (mh-show-header-display))
7271 (set-buffer buffer)
7272 (setq header-field (mh-get-header-field header))
7273 (if (equal major-mode 'mh-folder-mode)
7274 (mh-show)
7275 (mh-show-show))
7276 header-field)))
7277
7278 (defun org-follow-mhe-link (folder article)
7279 "Follow an MHE link to FOLDER and ARTICLE."
7280 (setq article (org-add-angle-brackets article))
7281 (require 'mh-e)
7282 (mh-find-path)
7283 (let* ((show-buf (concat "show-" folder)))
7284 (mh-visit-folder folder)
7285 (get-buffer-create show-buf)
7286 (mh-show-msg
7287 (string-to-number
7288 (car (split-string
7289 (with-temp-buffer
7290 (call-process
7291 (expand-file-name "pick" mh-progs)
7292 nil t nil
7293 folder
7294 "--message-id"
7295 article)
7296 (buffer-string))
7297 "\n"))))
7298 (pop-to-buffer show-buf)))
7299
7300 (defun org-open-file (path &optional in-emacs line search)
7301 "Open the file at PATH.
7302 First, this expands any special file name abbreviations. Then the
7303 configuration variable `org-file-apps' is checked if it contains an
7304 entry for this file type, and if yes, the corresponding command is launched.
7305 If no application is found, Emacs simply visits the file.
7306 With optional argument IN-EMACS, Emacs will visit the file.
7307 Optional LINE specifies a line to go to, optional SEARCH a string to
7308 search for. If LINE or SEARCH is given, the file will always be
7309 opened in Emacs.
7310 If the file does not exist, an error is thrown."
7311 (setq in-emacs (or in-emacs line search))
7312 (let* ((file (if (equal path "")
7313 (buffer-file-name)
7314 (convert-standard-filename (org-expand-file-name path))))
7315 (dirp (file-directory-p file))
7316 (dfile (downcase file))
7317 (old-buffer (current-buffer))
7318 (old-pos (point))
7319 (old-mode major-mode)
7320 ext cmd apps)
7321 (if (and (not (file-exists-p file))
7322 (not org-open-non-existing-files))
7323 (error "No such file: %s" file))
7324 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7325 (setq ext (match-string 1 dfile))
7326 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7327 (setq ext (match-string 1 dfile))))
7328 (setq apps (append org-file-apps (org-default-apps)))
7329 (if in-emacs
7330 (setq cmd 'emacs)
7331 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7332 (cdr (assoc ext apps))
7333 (cdr (assoc t apps)))))
7334 (when (eq cmd 'mailcap)
7335 (require 'mailcap)
7336 (mailcap-parse-mailcaps)
7337 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7338 (command (mailcap-mime-info mime-type)))
7339 (if (stringp command)
7340 (setq cmd command)
7341 (setq cmd 'emacs))))
7342 (cond
7343 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7344 (setq cmd (format cmd (concat "\"" file "\"")))
7345 (save-window-excursion
7346 (shell-command (concat cmd " &"))))
7347 ((or (stringp cmd)
7348 (eq cmd 'emacs))
7349 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
7350 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7351 (if line (goto-line line)
7352 (if search (org-link-search search))))
7353 ((consp cmd)
7354 (eval cmd))
7355 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7356 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7357 (or (not (equal old-buffer (current-buffer)))
7358 (not (equal old-pos (point))))
7359 (org-mark-ring-push old-pos old-buffer))))
7360
7361 (defun org-default-apps ()
7362 "Return the default applications for this operating system."
7363 (cond
7364 ((eq system-type 'darwin)
7365 org-file-apps-defaults-macosx)
7366 ((eq system-type 'windows-nt)
7367 org-file-apps-defaults-windowsnt)
7368 (t org-file-apps-defaults-gnu)))
7369
7370 (defun org-expand-file-name (path)
7371 "Replace special path abbreviations and expand the file name."
7372 (expand-file-name path))
7373
7374
7375 (defvar org-insert-link-history nil
7376 "Minibuffer history for links inserted with `org-insert-link'.")
7377
7378 (defvar org-stored-links nil
7379 "Contains the links stored with `org-store-link'.")
7380
7381 ;;;###autoload
7382 (defun org-store-link (arg)
7383 "\\<org-mode-map>Store an org-link to the current location.
7384 This link can later be inserted into an org-buffer with
7385 \\[org-insert-link].
7386 For some link types, a prefix arg is interpreted:
7387 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7388 For file links, arg negates `org-context-in-file-links'."
7389 (interactive "P")
7390 (let (link cpltxt txt (pos (point)))
7391 (cond
7392
7393 ((eq major-mode 'bbdb-mode)
7394 (setq cpltxt (concat
7395 "bbdb:"
7396 (or (bbdb-record-name (bbdb-current-record))
7397 (bbdb-record-company (bbdb-current-record))))
7398 link (org-make-link cpltxt)))
7399
7400 ((eq major-mode 'calendar-mode)
7401 (let ((cd (calendar-cursor-to-date)))
7402 (setq link
7403 (format-time-string
7404 (car org-time-stamp-formats)
7405 (apply 'encode-time
7406 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7407 nil nil nil))))))
7408
7409 ((or (eq major-mode 'vm-summary-mode)
7410 (eq major-mode 'vm-presentation-mode))
7411 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7412 (vm-follow-summary-cursor)
7413 (save-excursion
7414 (vm-select-folder-buffer)
7415 (let* ((message (car vm-message-pointer))
7416 (folder (buffer-file-name))
7417 (subject (vm-su-subject message))
7418 (author (vm-su-full-name message))
7419 (message-id (vm-su-message-id message)))
7420 (setq message-id (org-remove-angle-brackets message-id))
7421 (setq folder (abbreviate-file-name folder))
7422 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7423 folder)
7424 (setq folder (replace-match "" t t folder)))
7425 (setq cpltxt (concat author " on: " subject))
7426 (setq link (concat cpltxt "\n "
7427 (org-make-link
7428 "vm:" folder "#" message-id))))))
7429
7430 ((eq major-mode 'wl-summary-mode)
7431 (let* ((msgnum (wl-summary-message-number))
7432 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7433 msgnum 'message-id))
7434 (wl-message-entity (elmo-msgdb-overview-get-entity
7435 msgnum (wl-summary-buffer-msgdb)))
7436 (author (wl-summary-line-from)) ; FIXME: how to get author name?
7437 (subject "???")) ; FIXME: How to get subject of email?
7438 (setq message-id (org-remove-angle-brackets message-id))
7439 (setq cpltxt (concat author " on: " subject))
7440 (setq link (concat cpltxt "\n "
7441 (org-make-link
7442 "wl:" wl-summary-buffer-folder-name
7443 "#" message-id)))))
7444
7445 ((or (equal major-mode 'mh-folder-mode)
7446 (equal major-mode 'mh-show-mode))
7447 (let ((from-header (org-mhe-get-header "From:"))
7448 (to-header (org-mhe-get-header "To:"))
7449 (subject (org-mhe-get-header "Subject:")))
7450 (setq cpltxt (concat from-header " on: " subject))
7451 (setq link (concat cpltxt "\n "
7452 (org-make-link
7453 "mhe:" (org-mhe-get-message-real-folder) "#"
7454 (org-remove-angle-brackets
7455 (org-mhe-get-header "Message-Id:")))))))
7456
7457 ((eq major-mode 'rmail-mode)
7458 (save-excursion
7459 (save-restriction
7460 (rmail-narrow-to-non-pruned-header)
7461 (let ((folder (buffer-file-name))
7462 (message-id (mail-fetch-field "message-id"))
7463 (author (mail-fetch-field "from"))
7464 (subject (mail-fetch-field "subject")))
7465 (setq message-id (org-remove-angle-brackets message-id))
7466 (setq cpltxt (concat author " on: " subject))
7467 (setq link (concat cpltxt "\n "
7468 (org-make-link
7469 "rmail:" folder "#" message-id)))))))
7470
7471 ((eq major-mode 'gnus-group-mode)
7472 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7473 (gnus-group-group-name)) ; version
7474 ((fboundp 'gnus-group-name)
7475 (gnus-group-name))
7476 (t "???"))))
7477 (setq cpltxt (concat
7478 (if (org-xor arg org-usenet-links-prefer-google)
7479 "http://groups.google.com/groups?group="
7480 "gnus:")
7481 group)
7482 link (org-make-link cpltxt))))
7483
7484 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7485 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7486 (gnus-summary-beginning-of-article)
7487 (let* ((group (car gnus-article-current))
7488 (article (cdr gnus-article-current))
7489 (header (gnus-summary-article-header article))
7490 (author (mail-header-from header))
7491 (message-id (mail-header-id header))
7492 (date (mail-header-date header))
7493 (subject (gnus-summary-subject-string)))
7494 (setq cpltxt (concat author " on: " subject))
7495 (if (org-xor arg org-usenet-links-prefer-google)
7496 (setq link
7497 (concat
7498 cpltxt "\n "
7499 (format "http://groups.google.com/groups?as_umsgid=%s"
7500 (org-fixup-message-id-for-http message-id))))
7501 (setq link (concat cpltxt "\n"
7502 (org-make-link
7503 "gnus:" group
7504 "#" (number-to-string article)))))))
7505
7506 ((eq major-mode 'w3-mode)
7507 (setq cpltxt (url-view-url t)
7508 link (org-make-link cpltxt)))
7509 ((eq major-mode 'w3m-mode)
7510 (setq cpltxt w3m-current-url
7511 link (org-make-link cpltxt)))
7512
7513 ((eq major-mode 'org-mode)
7514 ;; Just link to current headline
7515 (setq cpltxt (concat "file:"
7516 (abbreviate-file-name (buffer-file-name))))
7517 ;; Add a context search string
7518 (when (org-xor org-context-in-file-links arg)
7519 ;; Check if we are on a target
7520 (if (save-excursion
7521 (skip-chars-forward "^>\n\r")
7522 (and (re-search-backward "<<" nil t)
7523 (looking-at "<<\\(.*?\\)>>")
7524 (<= (match-beginning 0) pos)
7525 (>= (match-end 0) pos)))
7526 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7527 (setq txt (cond
7528 ((org-on-heading-p) nil)
7529 ((org-region-active-p)
7530 (buffer-substring (region-beginning) (region-end)))
7531 (t (buffer-substring (point-at-bol) (point-at-eol)))))
7532 (setq cpltxt
7533 (concat cpltxt "::"
7534 (if org-file-link-context-use-camel-case
7535 (org-make-org-heading-camel txt)
7536 (org-make-org-heading-search-string txt))))))
7537 (if (string-match "::\\'" cpltxt)
7538 (setq cpltxt (substring cpltxt 0 -2)))
7539 (setq link (org-make-link cpltxt)))
7540
7541 ((buffer-file-name)
7542 ;; Just link to this file here.
7543 (setq cpltxt (concat "file:"
7544 (abbreviate-file-name (buffer-file-name))))
7545 ;; Add a context string
7546 (when (org-xor org-context-in-file-links arg)
7547 (setq txt (if (org-region-active-p)
7548 (buffer-substring (region-beginning) (region-end))
7549 (buffer-substring (point-at-bol) (point-at-eol))))
7550 (setq cpltxt
7551 (concat cpltxt "::"
7552 (if org-file-link-context-use-camel-case
7553 (org-make-org-heading-camel txt)
7554 (org-make-org-heading-search-string txt)))))
7555 (setq link (org-make-link cpltxt)))
7556
7557 ((interactive-p)
7558 (error "Cannot link to a buffer which is not visiting a file"))
7559
7560 (t (setq link nil)))
7561
7562 (if (and (interactive-p) link)
7563 (progn
7564 (setq org-stored-links
7565 (cons (cons (or cpltxt link) link) org-stored-links))
7566 (message "Stored: %s" (or cpltxt link)))
7567 link)))
7568
7569 (defun org-make-org-heading-search-string (&optional string heading)
7570 "Make search string for STRING or current headline."
7571 (interactive)
7572 (let ((s (or string (org-get-heading))))
7573 (unless (and string (not heading))
7574 ;; We are using a headline, clean up garbage in there.
7575 (if (string-match org-todo-regexp s)
7576 (setq s (replace-match "" t t s)))
7577 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7578 (setq s (replace-match "" t t s)))
7579 (setq s (org-trim s))
7580 (if (string-match (concat "^\\(" org-quote-string "\\|"
7581 org-comment-string "\\)") s)
7582 (setq s (replace-match "" t t s)))
7583 (while (string-match org-ts-regexp s)
7584 (setq s (replace-match "" t t s))))
7585 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7586 (setq s (replace-match " " t t s)))
7587 (or string (setq s (concat "*" s))) ; Add * for headlines
7588 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7589
7590 (defun org-make-org-heading-camel (&optional string heading)
7591 "Make a CamelCase string for STRING or the current headline."
7592 (interactive)
7593 (let ((s (or string (org-get-heading))))
7594 (unless (and string (not heading))
7595 ;; We are using a headline, clean up garbage in there.
7596 (if (string-match org-todo-regexp s)
7597 (setq s (replace-match "" t t s)))
7598 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7599 (setq s (replace-match "" t t s)))
7600 (setq s (org-trim s))
7601 (if (string-match (concat "^\\(" org-quote-string "\\|"
7602 org-comment-string "\\)") s)
7603 (setq s (replace-match "" t t s)))
7604 (while (string-match org-ts-regexp s)
7605 (setq s (replace-match "" t t s))))
7606 (while (string-match "[^a-zA-Z_ \t]+" s)
7607 (setq s (replace-match " " t t s)))
7608 (or string (setq s (concat "*" s))) ; Add * for headlines
7609 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7610
7611 (defun org-make-link (&rest strings)
7612 "Concatenate STRINGS, format resulting string with `org-link-format'."
7613 (format org-link-format (apply 'concat strings)))
7614
7615 (defun org-make-link2 (link &optional description)
7616 "Make a link with brackets."
7617 (concat "[[" link "]"
7618 (if description (concat "[" description "]") "")
7619 "]"))
7620
7621 (defun org-xor (a b)
7622 "Exclusive or."
7623 (if a (not b) b))
7624
7625 (defun org-get-header (header)
7626 "Find a header field in the current buffer."
7627 (save-excursion
7628 (goto-char (point-min))
7629 (let ((case-fold-search t) s)
7630 (cond
7631 ((eq header 'from)
7632 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7633 (setq s (match-string 1)))
7634 (while (string-match "\"" s)
7635 (setq s (replace-match "" t t s)))
7636 (if (string-match "[<(].*" s)
7637 (setq s (replace-match "" t t s))))
7638 ((eq header 'message-id)
7639 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7640 (setq s (match-string 1))))
7641 ((eq header 'subject)
7642 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7643 (setq s (match-string 1)))))
7644 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7645 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7646 s)))
7647
7648
7649 (defun org-fixup-message-id-for-http (s)
7650 "Replace special characters in a message id, so it can be used in an http query."
7651 (while (string-match "<" s)
7652 (setq s (replace-match "%3C" t t s)))
7653 (while (string-match ">" s)
7654 (setq s (replace-match "%3E" t t s)))
7655 (while (string-match "@" s)
7656 (setq s (replace-match "%40" t t s)))
7657 s)
7658
7659 (defun org-insert-link (&optional complete-file)
7660 "Insert a link. At the prompt, enter the link.
7661
7662 Completion can be used to select a link previously stored with
7663 `org-store-link'. When the empty string is entered (i.e. if you just
7664 press RET at the prompt), the link defaults to the most recently
7665 stored link. As SPC triggers completion in the minibuffer, you need to
7666 use M-SPC or C-q SPC to force the insertion of a space character.
7667
7668 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7669 selected using completion. The path to the file will be relative to
7670 the current directory if the file is in the current directory or a
7671 subdirectory. Otherwise, the link will be the absolute path as
7672 completed in the minibuffer (i.e. normally ~/path/to/file).
7673
7674 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7675 is in the current directory or below."
7676 (interactive "P")
7677 (let ((link (if complete-file
7678 (read-file-name "File: ")
7679 (completing-read
7680 "Link: " org-stored-links nil nil nil
7681 org-insert-link-history
7682 (or (car (car org-stored-links))))))
7683 linktxt matched)
7684 (if (or (not link) (equal link ""))
7685 (error "No links available"))
7686 (if complete-file
7687 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7688 (cond
7689 ((equal complete-file '(16))
7690 (insert
7691 (org-make-link
7692 "file:" (abbreviate-file-name (expand-file-name link)))))
7693 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7694 (expand-file-name link))
7695 (insert
7696 (org-make-link
7697 "file:" (match-string 1 (expand-file-name link)))))
7698 (t (insert (org-make-link "file:" link)))))
7699 (setq linktxt (cdr (assoc link org-stored-links)))
7700 (if (not org-keep-stored-link-after-insertion)
7701 (setq org-stored-links (delq (assoc link org-stored-links)
7702 org-stored-links)))
7703 (if (not linktxt) (setq link (org-make-link link)))
7704 (setq link (or linktxt link))
7705 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7706 (let* ((path (match-string 1 link))
7707 (case-fold-search nil)
7708 (search (match-string 2 link)))
7709 (when (save-match-data
7710 (equal (file-truename (buffer-file-name))
7711 (file-truename path)))
7712 ;; We are linking to this same file
7713 (if (and org-file-link-context-use-camel-case
7714 (save-match-data
7715 (string-match (concat "^" org-camel-regexp "$") search)))
7716 (setq link (replace-match search t t link)
7717 matched t)
7718 (setq link (replace-match (concat "[[" search "]]")
7719 t t link)
7720 matched t)))))
7721 (let ((lines (org-split-string link "\n")))
7722 (insert (car lines))
7723 (setq matched (or matched (string-match org-link-regexp (car lines))))
7724 (setq lines (cdr lines))
7725 (while lines
7726 (insert "\n")
7727 (if (save-excursion
7728 (beginning-of-line 0)
7729 (looking-at "[ \t]+\\S-"))
7730 (indent-relative))
7731 (setq matched (or matched
7732 (string-match org-link-regexp (car lines))))
7733 (insert (car lines))
7734 (setq lines (cdr lines))))
7735 (unless matched
7736 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7737
7738 ;;; Hooks for remember.el
7739 ;;;###autoload
7740 (defun org-remember-annotation ()
7741 "Return a link to the current location as an annotation for remember.el.
7742 If you are using Org-mode files as target for data storage with
7743 remember.el, then the annotations should include a link compatible with the
7744 conventions in Org-mode. This function returns such a link."
7745 (org-store-link nil))
7746
7747 (defconst org-remember-help
7748 "Select a destination location for the note.
7749 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7750 RET at beg-of-buf -> Append to file as level 2 headline
7751 RET on headline -> Store as sublevel entry to current headline
7752 <left>/<right> -> before/after current headline, same headings level")
7753
7754 ;;;###autoload
7755 (defun org-remember-handler ()
7756 "Store stuff from remember.el into an org file.
7757 First prompts for an org file. If the user just presses return, the value
7758 of `org-default-notes-file' is used.
7759 Then the command offers the headings tree of the selected file in order to
7760 file the text at a specific location.
7761 You can either immediately press RET to get the note appended to the
7762 file, or you can use vertical cursor motion and visibility cycling (TAB) to
7763 find a better place. Then press RET or <left> or <right> in insert the note.
7764
7765 Key Cursor position Note gets inserted
7766 -----------------------------------------------------------------------------
7767 RET buffer-start as level 2 heading at end of file
7768 RET on headline as sublevel of the heading at cursor
7769 RET no heading at cursor position, level taken from context.
7770 Or use prefix arg to specify level manually.
7771 <left> on headline as same level, before current heading
7772 <right> on headline as same level, after current heading
7773
7774 So the fastest way to store the note is to press RET RET to append it to
7775 the default file. This way your current train of thought is not
7776 interrupted, in accordance with the principles of remember.el. But with
7777 little extra effort, you can push it directly to the correct location.
7778
7779 Before being stored away, the function ensures that the text has a
7780 headline, i.e. a first line that starts with a \"*\". If not, a headline
7781 is constructed from the current date and some additional data.
7782
7783 If the variable `org-adapt-indentation' is non-nil, the entire text is
7784 also indented so that it starts in the same column as the headline
7785 \(i.e. after the stars).
7786
7787 See also the variable `org-reverse-note-order'."
7788 (catch 'quit
7789 (let* ((txt (buffer-substring (point-min) (point-max)))
7790 (fastp current-prefix-arg)
7791 (file (if fastp org-default-notes-file (org-get-org-file)))
7792 (visiting (find-buffer-visiting file))
7793 (org-startup-with-deadline-check nil)
7794 (org-startup-folded nil)
7795 spos level indent reversed)
7796 ;; Modify text so that it becomes a nice subtree which can be inserted
7797 ;; into an org tree.
7798 (let* ((lines (split-string txt "\n"))
7799 (first (car lines))
7800 (lines (cdr lines)))
7801 (if (string-match "^\\*+" first)
7802 ;; Is already a headline
7803 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7804 -1) ?\ ))
7805 ;; We need to add a headline: Use time and first buffer line
7806 (setq lines (cons first lines)
7807 first (concat "* " (current-time-string)
7808 " (" (remember-buffer-desc) ")")
7809 indent " "))
7810 (if org-adapt-indentation
7811 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7812 (setq txt (concat first "\n"
7813 (mapconcat 'identity lines "\n"))))
7814 ;; Find the file
7815 (if (not visiting)
7816 (find-file-noselect file))
7817 (with-current-buffer (get-file-buffer file)
7818 (setq reversed (org-notes-order-reversed-p))
7819 (save-excursion
7820 (save-restriction
7821 (widen)
7822 ;; Ask the User for a location
7823 (setq spos (if fastp 1 (org-get-location
7824 (current-buffer)
7825 org-remember-help)))
7826 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7827 ; not handle this note
7828 (goto-char spos)
7829 (cond ((bobp)
7830 ;; Put it at the start or end, as level 2
7831 (save-restriction
7832 (widen)
7833 (goto-char (if reversed (point-min) (point-max)))
7834 (if (not (bolp)) (newline))
7835 (org-paste-subtree (or current-prefix-arg 2) txt)))
7836 ((and (org-on-heading-p nil) (not current-prefix-arg))
7837 ;; Put it below this entry, at the beg/end of the subtree
7838 (org-back-to-heading)
7839 (setq level (outline-level))
7840 (if reversed
7841 (outline-end-of-heading)
7842 (outline-end-of-subtree))
7843 (if (not (bolp)) (newline))
7844 (beginning-of-line 1)
7845 (org-paste-subtree (1+ level) txt))
7846 (t
7847 ;; Put it right there, with automatic level determined by
7848 ;; org-paste-subtree or from prefix arg
7849 (org-paste-subtree current-prefix-arg txt)))
7850 (when remember-save-after-remembering
7851 (save-buffer)
7852 (if (not visiting) (kill-buffer (current-buffer)))))))))
7853 t) ;; return t to indicate that we took care of this note.
7854
7855 (defun org-get-org-file ()
7856 "Read a filename, with default directory `org-directory'."
7857 (let ((default (or org-default-notes-file remember-data-file)))
7858 (read-file-name (format "File name [%s]: " default)
7859 (file-name-as-directory org-directory)
7860 default)))
7861
7862 (defun org-notes-order-reversed-p ()
7863 "Check if the current file should receive notes in reversed order."
7864 (cond
7865 ((not org-reverse-note-order) nil)
7866 ((eq t org-reverse-note-order) t)
7867 ((not (listp org-reverse-note-order)) nil)
7868 (t (catch 'exit
7869 (let ((all org-reverse-note-order)
7870 entry)
7871 (while (setq entry (pop all))
7872 (if (string-match (car entry) (buffer-file-name))
7873 (throw 'exit (cdr entry))))
7874 nil)))))
7875
7876 ;;; Tables
7877
7878 ;; Watch out: Here we are talking about two different kind of tables.
7879 ;; Most of the code is for the tables created with the Org-mode table editor.
7880 ;; Sometimes, we talk about tables created and edited with the table.el
7881 ;; Emacs package. We call the former org-type tables, and the latter
7882 ;; table.el-type tables.
7883
7884
7885 (defun org-before-change-function (beg end)
7886 "Every change indicates that a table might need an update."
7887 (setq org-table-may-need-update t))
7888
7889 (defconst org-table-line-regexp "^[ \t]*|"
7890 "Detects an org-type table line.")
7891 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7892 "Detects an org-type table line.")
7893 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7894 "Detects a table line marked for automatic recalculation.")
7895 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7896 "Detects a table line marked for automatic recalculation.")
7897 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7898 "Detects a table line marked for automatic recalculation.")
7899 (defconst org-table-hline-regexp "^[ \t]*|-"
7900 "Detects an org-type table hline.")
7901 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7902 "Detects a table-type table hline.")
7903 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7904 "Detects an org-type or table-type table.")
7905 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7906 "Searching from within a table (any type) this finds the first line
7907 outside the table.")
7908 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7909 "Searching from within a table (any type) this finds the first line
7910 outside the table.")
7911
7912 (defun org-table-create-with-table.el ()
7913 "Use the table.el package to insert a new table.
7914 If there is already a table at point, convert between Org-mode tables
7915 and table.el tables."
7916 (interactive)
7917 (require 'table)
7918 (cond
7919 ((org-at-table.el-p)
7920 (if (y-or-n-p "Convert table to Org-mode table? ")
7921 (org-table-convert)))
7922 ((org-at-table-p)
7923 (if (y-or-n-p "Convert table to table.el table? ")
7924 (org-table-convert)))
7925 (t (call-interactively 'table-insert))))
7926
7927 (defun org-table-create (&optional size)
7928 "Query for a size and insert a table skeleton.
7929 SIZE is a string Columns x Rows like for example \"3x2\"."
7930 (interactive "P")
7931 (unless size
7932 (setq size (read-string
7933 (concat "Table size Columns x Rows [e.g. "
7934 org-table-default-size "]: ")
7935 "" nil org-table-default-size)))
7936
7937 (let* ((pos (point))
7938 (indent (make-string (current-column) ?\ ))
7939 (split (org-split-string size " *x *"))
7940 (rows (string-to-number (nth 1 split)))
7941 (columns (string-to-number (car split)))
7942 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7943 "\n")))
7944 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7945 (point-at-bol) (point)))
7946 (beginning-of-line 1)
7947 (newline))
7948 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7949 (dotimes (i rows) (insert line))
7950 (goto-char pos)
7951 (if (> rows 1)
7952 ;; Insert a hline after the first row.
7953 (progn
7954 (end-of-line 1)
7955 (insert "\n|-")
7956 (goto-char pos)))
7957 (org-table-align)))
7958
7959 (defun org-table-convert-region (beg0 end0 nspace)
7960 "Convert region to a table.
7961 The region goes from BEG0 to END0, but these borders will be moved
7962 slightly, to make sure a beginning of line in the first line is included.
7963 When NSPACE is non-nil, it indicates the minimum number of spaces that
7964 separate columns (default: just one space)."
7965 (let* ((beg (min beg0 end0))
7966 (end (max beg0 end0))
7967 (tabsep t)
7968 re)
7969 (goto-char beg)
7970 (beginning-of-line 1)
7971 (setq beg (move-marker (make-marker) (point)))
7972 (goto-char end)
7973 (if (bolp) (backward-char 1) (end-of-line 1))
7974 (setq end (move-marker (make-marker) (point)))
7975 ;; Lets see if this is tab-separated material. If every nonempty line
7976 ;; contains a tab, we will assume that it is tab-separated material
7977 (if nspace
7978 (setq tabsep nil)
7979 (goto-char beg)
7980 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7981 (if nspace (setq tabsep nil))
7982 (if tabsep
7983 (setq re "^\\|\t")
7984 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7985 (max 1 (prefix-numeric-value nspace)))))
7986 (goto-char beg)
7987 (while (re-search-forward re end t)
7988 (replace-match "|" t t))
7989 (goto-char beg)
7990 (insert " ")
7991 (org-table-align)))
7992
7993 (defun org-table-import (file arg)
7994 "Import FILE as a table.
7995 The file is assumed to be tab-separated. Such files can be produced by most
7996 spreadsheet and database applications. If no tabs (at least one per line)
7997 are found, lines will be split on whitespace into fields."
7998 (interactive "f\nP")
7999 (or (bolp) (newline))
8000 (let ((beg (point))
8001 (pm (point-max)))
8002 (insert-file-contents file)
8003 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8004
8005 (defun org-table-export ()
8006 "Export table as a tab-separated file.
8007 Such a file can be imported into a spreadsheet program like Excel."
8008 (interactive)
8009 (let* ((beg (org-table-begin))
8010 (end (org-table-end))
8011 (table (buffer-substring beg end))
8012 (file (read-file-name "Export table to: "))
8013 buf)
8014 (unless (or (not (file-exists-p file))
8015 (y-or-n-p (format "Overwrite file %s? " file)))
8016 (error "Abort"))
8017 (with-current-buffer (find-file-noselect file)
8018 (setq buf (current-buffer))
8019 (erase-buffer)
8020 (fundamental-mode)
8021 (insert table)
8022 (goto-char (point-min))
8023 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8024 (replace-match "" t t)
8025 (end-of-line 1))
8026 (goto-char (point-min))
8027 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8028 (replace-match "" t t)
8029 (goto-char (min (1+ (point)) (point-max))))
8030 (goto-char (point-min))
8031 (while (re-search-forward "^-[-+]*$" nil t)
8032 (replace-match "")
8033 (if (looking-at "\n")
8034 (delete-char 1)))
8035 (goto-char (point-min))
8036 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8037 (replace-match "\t" t t))
8038 (save-buffer))
8039 (kill-buffer buf)))
8040
8041 (defvar org-table-aligned-begin-marker (make-marker)
8042 "Marker at the beginning of the table last aligned.
8043 Used to check if cursor still is in that table, to minimize realignment.")
8044 (defvar org-table-aligned-end-marker (make-marker)
8045 "Marker at the end of the table last aligned.
8046 Used to check if cursor still is in that table, to minimize realignment.")
8047 (defvar org-table-last-alignment nil
8048 "List of flags for flushright alignment, from the last re-alignment.
8049 This is being used to correctly align a single field after TAB or RET.")
8050 ;; FIXME: The following is currently not used.
8051 (defvar org-table-last-column-widths nil
8052 "List of max width of fields in each column.
8053 This is being used to correctly align a single field after TAB or RET.")
8054
8055 (defvar org-last-recalc-line nil)
8056
8057 (defun org-table-align ()
8058 "Align the table at point by aligning all vertical bars."
8059 (interactive)
8060 ;; (message "align") (sit-for 2)
8061 (let* (
8062 ;; Limits of table
8063 (beg (org-table-begin))
8064 (end (org-table-end))
8065 ;; Current cursor position
8066 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8067 (colpos (org-table-current-column))
8068 (winstart (window-start))
8069 text lines (new "") lengths l typenums ty fields maxfields i
8070 column
8071 (indent "") cnt frac
8072 rfmt hfmt
8073 (spaces (if (org-in-invisibility-spec-p '(org-table))
8074 org-table-spaces-around-invisible-separators
8075 org-table-spaces-around-separators))
8076 (sp1 (car spaces))
8077 (sp2 (cdr spaces))
8078 (rfmt1 (concat
8079 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8080 (hfmt1 (concat
8081 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8082 emptystrings)
8083 (untabify beg end)
8084 ;; (message "Aligning table...")
8085 ;; Get the rows
8086 (setq lines (org-split-string
8087 (buffer-substring-no-properties beg end) "\n"))
8088 ;; Store the indentation of the first line
8089 (if (string-match "^ *" (car lines))
8090 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8091 ;; Mark the hlines
8092 (setq lines (mapcar (lambda (l)
8093 (if (string-match "^ *|-" l)
8094 nil
8095 (if (string-match "[ \t]+$" l)
8096 (substring l 0 (match-beginning 0))
8097 l)))
8098 lines))
8099 ;; Get the data fields
8100 (setq fields (mapcar
8101 (lambda (l)
8102 (org-split-string l " *| *"))
8103 (delq nil (copy-sequence lines))))
8104 ;; How many fields in the longest line?
8105 (condition-case nil
8106 (setq maxfields (apply 'max (mapcar 'length fields)))
8107 (error
8108 (kill-region beg end)
8109 (org-table-create org-table-default-size)
8110 (error "Empty table - created default table")))
8111 ;; A list of empty string to fill any short rows on output
8112 (setq emptystrings (make-list maxfields ""))
8113 ;; Get the maximum length of a field and the most common datatype
8114 ;; for each column
8115 (setq i -1)
8116 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8117 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8118 ;; maximum length
8119 (push (apply 'max 1 (mapcar 'string-width column)) lengths)
8120 ;; compute the fraction stepwise, ignoring empty fields
8121 (setq cnt 0 frac 0.0)
8122 (mapcar
8123 (lambda (x)
8124 (if (equal x "")
8125 nil
8126 (setq frac ( / (+ (* frac cnt)
8127 (if (string-match org-table-number-regexp x) 1 0))
8128 (setq cnt (1+ cnt))))))
8129 column)
8130 (push (>= frac org-table-number-fraction) typenums))
8131 (setq lengths (nreverse lengths)
8132 typenums (nreverse typenums))
8133 (setq org-table-last-alignment typenums
8134 org-table-last-column-widths lengths)
8135 ;; Compute the formats needed for output of the table
8136 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8137 (while (setq l (pop lengths))
8138 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8139 (setq rfmt (concat rfmt (format rfmt1 ty l))
8140 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8141 (setq rfmt (concat rfmt "\n")
8142 hfmt (concat (substring hfmt 0 -1) "|\n"))
8143 ;; Produce the new table
8144 ;;(while lines
8145 ;; (setq l (pop lines))
8146 ;; (if l
8147 ;; (setq new (concat new (apply 'format rfmt
8148 ;; (append (pop fields) emptystrings))))
8149 ;; (setq new (concat new hfmt))))
8150 (setq new (mapconcat
8151 (lambda (l)
8152 (if l (apply 'format rfmt
8153 (append (pop fields) emptystrings))
8154 hfmt))
8155 lines ""))
8156 ;; Replace the old one
8157 (delete-region beg end)
8158 (move-marker end nil)
8159 (move-marker org-table-aligned-begin-marker (point))
8160 (insert new)
8161 (move-marker org-table-aligned-end-marker (point))
8162 ;; Try to move to the old location (approximately)
8163 (goto-line linepos)
8164 (set-window-start (selected-window) winstart 'noforce)
8165 (org-table-goto-column colpos)
8166 (setq org-table-may-need-update nil)
8167 (if (org-in-invisibility-spec-p '(org-table))
8168 (org-table-add-invisible-to-vertical-lines))
8169 ))
8170
8171 (defun org-table-begin (&optional table-type)
8172 "Find the beginning of the table and return its position.
8173 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8174 (save-excursion
8175 (if (not (re-search-backward
8176 (if table-type org-table-any-border-regexp
8177 org-table-border-regexp)
8178 nil t))
8179 (error "Can't find beginning of table")
8180 (goto-char (match-beginning 0))
8181 (beginning-of-line 2)
8182 (point))))
8183
8184 (defun org-table-end (&optional table-type)
8185 "Find the end of the table and return its position.
8186 With argument TABLE-TYPE, go to the end of a table.el-type table."
8187 (save-excursion
8188 (if (not (re-search-forward
8189 (if table-type org-table-any-border-regexp
8190 org-table-border-regexp)
8191 nil t))
8192 (goto-char (point-max))
8193 (goto-char (match-beginning 0)))
8194 (point-marker)))
8195
8196 (defun org-table-justify-field-maybe (&optional new)
8197 "Justify the current field, text to left, number to right.
8198 Optional argument NEW may specify text to replace the current field content."
8199 (cond
8200 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8201 ((org-at-table-hline-p)
8202 ;; FIXME: I used to enforce realign here, but I think this is not needed.
8203 ;; (setq org-table-may-need-update t)
8204 )
8205 ((and (not new)
8206 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8207 (current-buffer)))
8208 (< (point) org-table-aligned-begin-marker)
8209 (>= (point) org-table-aligned-end-marker)))
8210 ;; This is not the same table, force a full re-align
8211 (setq org-table-may-need-update t))
8212 (t ;; realign the current field, based on previous full realign
8213 (let* ((pos (point)) s
8214 (col (org-table-current-column))
8215 (num (nth (1- col) org-table-last-alignment))
8216 l f n o e)
8217 (when (> col 0)
8218 (skip-chars-backward "^|\n")
8219 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8220 (progn
8221 (setq s (match-string 1)
8222 o (match-string 0)
8223 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8224 e (not (= (match-beginning 2) (match-end 2))))
8225 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8226 l (if e "|" (setq org-table-may-need-update t) ""))
8227 n (format f s t t))
8228 (if new
8229 (if (<= (length new) l)
8230 (setq n (format f new t t)) ;; FIXME: why t t?????
8231 (setq n (concat new "|") org-table-may-need-update t)))
8232 (or (equal n o)
8233 (let (org-table-may-need-update)
8234 (replace-match n))))
8235 (setq org-table-may-need-update t))
8236 (goto-char pos))))))
8237
8238 (defun org-table-next-field ()
8239 "Go to the next field in the current table, creating new lines as needed.
8240 Before doing so, re-align the table if necessary."
8241 (interactive)
8242 (org-table-maybe-eval-formula)
8243 (org-table-maybe-recalculate-line)
8244 (if (and org-table-automatic-realign
8245 org-table-may-need-update)
8246 (org-table-align))
8247 (let ((end (org-table-end)))
8248 (if (org-at-table-hline-p)
8249 (end-of-line 1))
8250 (condition-case nil
8251 (progn
8252 (re-search-forward "|" end)
8253 (if (looking-at "[ \t]*$")
8254 (re-search-forward "|" end))
8255 (if (and (looking-at "-")
8256 org-table-tab-jumps-over-hlines
8257 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8258 (goto-char (match-beginning 1)))
8259 (if (looking-at "-")
8260 (progn
8261 (beginning-of-line 0)
8262 (org-table-insert-row 'below))
8263 (if (looking-at " ") (forward-char 1))))
8264 (error
8265 (org-table-insert-row 'below)))))
8266
8267 (defun org-table-previous-field ()
8268 "Go to the previous field in the table.
8269 Before doing so, re-align the table if necessary."
8270 (interactive)
8271 (org-table-justify-field-maybe)
8272 (org-table-maybe-recalculate-line)
8273 (if (and org-table-automatic-realign
8274 org-table-may-need-update)
8275 (org-table-align))
8276 (if (org-at-table-hline-p)
8277 (end-of-line 1))
8278 (re-search-backward "|" (org-table-begin))
8279 (re-search-backward "|" (org-table-begin))
8280 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8281 (re-search-backward "|" (org-table-begin)))
8282 (if (looking-at "| ?")
8283 (goto-char (match-end 0))))
8284
8285 (defun org-table-next-row ()
8286 "Go to the next row (same column) in the current table.
8287 Before doing so, re-align the table if necessary."
8288 (interactive)
8289 (org-table-maybe-eval-formula)
8290 (org-table-maybe-recalculate-line)
8291 (if (or (looking-at "[ \t]*$")
8292 (save-excursion (skip-chars-backward " \t") (bolp)))
8293 (newline)
8294 (if (and org-table-automatic-realign
8295 org-table-may-need-update)
8296 (org-table-align))
8297 (let ((col (org-table-current-column)))
8298 (beginning-of-line 2)
8299 (if (or (not (org-at-table-p))
8300 (org-at-table-hline-p))
8301 (progn
8302 (beginning-of-line 0)
8303 (org-table-insert-row 'below)))
8304 (org-table-goto-column col)
8305 (skip-chars-backward "^|\n\r")
8306 (if (looking-at " ") (forward-char 1)))))
8307
8308 (defun org-table-copy-down (n)
8309 "Copy a field down in the current column.
8310 If the field at the cursor is empty, copy into it the content of the nearest
8311 non-empty field above. With argument N, use the Nth non-empty field.
8312 If the current field is not empty, it is copied down to the next row, and
8313 the cursor is moved with it. Therefore, repeating this command causes the
8314 column to be filled row-by-row.
8315 If the variable `org-table-copy-increment' is non-nil and the field is an
8316 integer, it will be incremented while copying."
8317 (interactive "p")
8318 (let* ((colpos (org-table-current-column))
8319 (field (org-table-get-field))
8320 (non-empty (string-match "[^ \t]" field))
8321 (beg (org-table-begin))
8322 txt)
8323 (org-table-check-inside-data-field)
8324 (if non-empty
8325 (progn
8326 (setq txt (org-trim field))
8327 (org-table-next-row)
8328 (org-table-blank-field))
8329 (save-excursion
8330 (setq txt
8331 (catch 'exit
8332 (while (progn (beginning-of-line 1)
8333 (re-search-backward org-table-dataline-regexp
8334 beg t))
8335 (org-table-goto-column colpos t)
8336 (if (and (looking-at
8337 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8338 (= (setq n (1- n)) 0))
8339 (throw 'exit (match-string 1))))))))
8340 (if txt
8341 (progn
8342 (if (and org-table-copy-increment
8343 (string-match "^[0-9]+$" txt))
8344 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8345 (insert txt)
8346 (org-table-maybe-recalculate-line)
8347 (org-table-align))
8348 (error "No non-empty field found"))))
8349
8350 (defun org-table-check-inside-data-field ()
8351 "Is point inside a table data field?
8352 I.e. not on a hline or before the first or after the last column?
8353 This actually throws an error, so it aborts the current command."
8354 (if (or (not (org-at-table-p))
8355 (= (org-table-current-column) 0)
8356 (org-at-table-hline-p)
8357 (looking-at "[ \t]*$"))
8358 (error "Not in table data field")))
8359
8360 (defvar org-table-clip nil
8361 "Clipboard for table regions.")
8362
8363 (defun org-table-blank-field ()
8364 "Blank the current table field or active region."
8365 (interactive)
8366 (org-table-check-inside-data-field)
8367 (if (and (interactive-p) (org-region-active-p))
8368 (let (org-table-clip)
8369 (org-table-cut-region (region-beginning) (region-end)))
8370 (skip-chars-backward "^|")
8371 (backward-char 1)
8372 (if (looking-at "|[^|\n]+")
8373 (let* ((pos (match-beginning 0))
8374 (match (match-string 0))
8375 (len (string-width match)))
8376 (replace-match (concat "|" (make-string (1- len) ?\ )))
8377 (goto-char (+ 2 pos))
8378 (substring match 1)))))
8379
8380 (defun org-table-get-field (&optional n replace)
8381 "Return the value of the field in column N of current row.
8382 N defaults to current field.
8383 If REPLACE is a string, replace field with this value. The return value
8384 is always the old value."
8385 (and n (org-table-goto-column n))
8386 (skip-chars-backward "^|\n")
8387 (backward-char 1)
8388 (if (looking-at "|[^|\r\n]*")
8389 (let* ((pos (match-beginning 0))
8390 (val (buffer-substring (1+ pos) (match-end 0))))
8391 (if replace
8392 (replace-match (concat "|" replace)))
8393 (goto-char (min (point-at-eol) (+ 2 pos)))
8394 val)
8395 (forward-char 1) ""))
8396
8397 (defun org-table-current-column ()
8398 "Find out which column we are in.
8399 When called interactively, column is also displayed in echo area."
8400 (interactive)
8401 (if (interactive-p) (org-table-check-inside-data-field))
8402 (save-excursion
8403 (let ((cnt 0) (pos (point)))
8404 (beginning-of-line 1)
8405 (while (search-forward "|" pos t)
8406 (setq cnt (1+ cnt)))
8407 (if (interactive-p) (message "This is table column %d" cnt))
8408 cnt)))
8409
8410 (defun org-table-goto-column (n &optional on-delim force)
8411 "Move the cursor to the Nth column in the current table line.
8412 With optional argument ON-DELIM, stop with point before the left delimiter
8413 of the field.
8414 If there are less than N fields, just go to after the last delimiter.
8415 However, when FORCE is non-nil, create new columns if necessary."
8416 (interactive "p")
8417 (let ((pos (point-at-eol)))
8418 (beginning-of-line 1)
8419 (when (> n 0)
8420 (while (and (> (setq n (1- n)) -1)
8421 (or (search-forward "|" pos t)
8422 (and force
8423 (progn (end-of-line 1)
8424 (skip-chars-backward "^|")
8425 (insert " | "))))))
8426 ; (backward-char 2) t)))))
8427 (when (and force (not (looking-at ".*|")))
8428 (save-excursion (end-of-line 1) (insert " | ")))
8429 (if on-delim
8430 (backward-char 1)
8431 (if (looking-at " ") (forward-char 1))))))
8432
8433 (defun org-at-table-p (&optional table-type)
8434 "Return t if the cursor is inside an org-type table.
8435 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8436 (if org-enable-table-editor
8437 (save-excursion
8438 (beginning-of-line 1)
8439 (looking-at (if table-type org-table-any-line-regexp
8440 org-table-line-regexp)))
8441 nil))
8442
8443 (defun org-at-table.el-p ()
8444 "Return t if and only if we are at a table.el table."
8445 (and (org-at-table-p 'any)
8446 (save-excursion
8447 (goto-char (org-table-begin 'any))
8448 (looking-at org-table1-hline-regexp))))
8449
8450 (defun org-table-recognize-table.el ()
8451 "If there is a table.el table nearby, recognize it and move into it."
8452 (if org-table-tab-recognizes-table.el
8453 (if (org-at-table.el-p)
8454 (progn
8455 (beginning-of-line 1)
8456 (if (looking-at org-table-dataline-regexp)
8457 nil
8458 (if (looking-at org-table1-hline-regexp)
8459 (progn
8460 (beginning-of-line 2)
8461 (if (looking-at org-table-any-border-regexp)
8462 (beginning-of-line -1)))))
8463 (if (re-search-forward "|" (org-table-end t) t)
8464 (progn
8465 (require 'table)
8466 (if (table--at-cell-p (point))
8467 t
8468 (message "recognizing table.el table...")
8469 (table-recognize-table)
8470 (message "recognizing table.el table...done")))
8471 (error "This should not happen..."))
8472 t)
8473 nil)
8474 nil))
8475
8476 (defun org-at-table-hline-p ()
8477 "Return t if the cursor is inside a hline in a table."
8478 (if org-enable-table-editor
8479 (save-excursion
8480 (beginning-of-line 1)
8481 (looking-at org-table-hline-regexp))
8482 nil))
8483
8484 (defun org-table-insert-column ()
8485 "Insert a new column into the table."
8486 (interactive)
8487 (if (not (org-at-table-p))
8488 (error "Not at a table"))
8489 (org-table-find-dataline)
8490 (let* ((col (max 1 (org-table-current-column)))
8491 (beg (org-table-begin))
8492 (end (org-table-end))
8493 ;; Current cursor position
8494 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8495 (colpos col))
8496 (goto-char beg)
8497 (while (< (point) end)
8498 (if (org-at-table-hline-p)
8499 nil
8500 (org-table-goto-column col t)
8501 (insert "| "))
8502 (beginning-of-line 2))
8503 (move-marker end nil)
8504 (goto-line linepos)
8505 (org-table-goto-column colpos)
8506 (org-table-align)
8507 (org-table-modify-formulas 'insert col)))
8508
8509 (defun org-table-find-dataline ()
8510 "Find a dataline in the current table, which is needed for column commands."
8511 (if (and (org-at-table-p)
8512 (not (org-at-table-hline-p)))
8513 t
8514 (let ((col (current-column))
8515 (end (org-table-end)))
8516 (move-to-column col)
8517 (while (and (< (point) end)
8518 (or (not (= (current-column) col))
8519 (org-at-table-hline-p)))
8520 (beginning-of-line 2)
8521 (move-to-column col))
8522 (if (and (org-at-table-p)
8523 (not (org-at-table-hline-p)))
8524 t
8525 (error
8526 "Please position cursor in a data line for column operations")))))
8527
8528 (defun org-table-delete-column ()
8529 "Delete a column into the table."
8530 (interactive)
8531 (if (not (org-at-table-p))
8532 (error "Not at a table"))
8533 (org-table-find-dataline)
8534 (org-table-check-inside-data-field)
8535 (let* ((col (org-table-current-column))
8536 (beg (org-table-begin))
8537 (end (org-table-end))
8538 ;; Current cursor position
8539 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8540 (colpos col))
8541 (goto-char beg)
8542 (while (< (point) end)
8543 (if (org-at-table-hline-p)
8544 nil
8545 (org-table-goto-column col t)
8546 (and (looking-at "|[^|\n]+|")
8547 (replace-match "|")))
8548 (beginning-of-line 2))
8549 (move-marker end nil)
8550 (goto-line linepos)
8551 (org-table-goto-column colpos)
8552 (org-table-align)
8553 (org-table-modify-formulas 'remove col)))
8554
8555 (defun org-table-move-column-right ()
8556 "Move column to the right."
8557 (interactive)
8558 (org-table-move-column nil))
8559 (defun org-table-move-column-left ()
8560 "Move column to the left."
8561 (interactive)
8562 (org-table-move-column 'left))
8563
8564 (defun org-table-move-column (&optional left)
8565 "Move the current column to the right. With arg LEFT, move to the left."
8566 (interactive "P")
8567 (if (not (org-at-table-p))
8568 (error "Not at a table"))
8569 (org-table-find-dataline)
8570 (org-table-check-inside-data-field)
8571 (let* ((col (org-table-current-column))
8572 (col1 (if left (1- col) col))
8573 (beg (org-table-begin))
8574 (end (org-table-end))
8575 ;; Current cursor position
8576 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8577 (colpos (if left (1- col) (1+ col))))
8578 (if (and left (= col 1))
8579 (error "Cannot move column further left"))
8580 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8581 (error "Cannot move column further right"))
8582 (goto-char beg)
8583 (while (< (point) end)
8584 (if (org-at-table-hline-p)
8585 nil
8586 (org-table-goto-column col1 t)
8587 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8588 (replace-match "|\\2|\\1|")))
8589 (beginning-of-line 2))
8590 (move-marker end nil)
8591 (goto-line linepos)
8592 (org-table-goto-column colpos)
8593 (org-table-align)
8594 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8595
8596 (defun org-table-move-row-down ()
8597 "Move table row down."
8598 (interactive)
8599 (org-table-move-row nil))
8600 (defun org-table-move-row-up ()
8601 "Move table row up."
8602 (interactive)
8603 (org-table-move-row 'up))
8604
8605 (defun org-table-move-row (&optional up)
8606 "Move the current table line down. With arg UP, move it up."
8607 (interactive "P")
8608 (let ((col (current-column))
8609 (pos (point))
8610 (tonew (if up 0 2))
8611 txt)
8612 (beginning-of-line tonew)
8613 (if (not (org-at-table-p))
8614 (progn
8615 (goto-char pos)
8616 (error "Cannot move row further")))
8617 (goto-char pos)
8618 (beginning-of-line 1)
8619 (setq pos (point))
8620 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8621 (delete-region (point) (1+ (point-at-eol)))
8622 (beginning-of-line tonew)
8623 (insert txt)
8624 (beginning-of-line 0)
8625 (move-to-column col)))
8626
8627 (defun org-table-insert-row (&optional arg)
8628 "Insert a new row above the current line into the table.
8629 With prefix ARG, insert below the current line."
8630 (interactive "P")
8631 (if (not (org-at-table-p))
8632 (error "Not at a table"))
8633 (let* ((line
8634 (org-expand-wide-chars
8635 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8636 new)
8637 (if (string-match "^[ \t]*|-" line)
8638 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8639 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8640 ;; Fix the first field if necessary
8641 (setq new (concat new))
8642 (if (string-match "^[ \t]*| *[#$] *|" line)
8643 (setq new (replace-match (match-string 0 line) t t new)))
8644 (beginning-of-line (if arg 2 1))
8645 (let (org-table-may-need-update)
8646 (insert-before-markers new)
8647 (insert-before-markers "\n"))
8648 (beginning-of-line 0)
8649 (re-search-forward "| ?" (point-at-eol) t)
8650 (and org-table-may-need-update (org-table-align))))
8651
8652 (defun org-table-insert-hline (&optional arg)
8653 "Insert a horizontal-line below the current line into the table.
8654 With prefix ARG, insert above the current line."
8655 (interactive "P")
8656 (if (not (org-at-table-p))
8657 (error "Not at a table"))
8658 (let ((line
8659 (org-expand-wide-chars
8660 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8661 (col (current-column))
8662 start)
8663 (if (string-match "^[ \t]*|-" line)
8664 (setq line
8665 (mapcar (lambda (x) (if (member x '(?| ?+))
8666 (prog1 (if start ?+ ?|) (setq start t))
8667 (if start ?- ?\ )))
8668 line))
8669 (setq line
8670 (mapcar (lambda (x) (if (equal x ?|)
8671 (prog1 (if start ?+ ?|) (setq start t))
8672 (if start ?- ?\ )))
8673 line)))
8674 (beginning-of-line (if arg 1 2))
8675 (apply 'insert line)
8676 (if (equal (char-before (point)) ?+)
8677 (progn (backward-delete-char 1) (insert "|")))
8678 (insert "\n")
8679 (beginning-of-line (if arg 1 -1))
8680 (move-to-column col)))
8681
8682 (defun org-expand-wide-chars (s)
8683 "Expand wide characters to spaces."
8684 (let (w a)
8685 (mapconcat
8686 (lambda (x)
8687 (if (> (setq w (string-width (setq a (char-to-string x)))) 1)
8688 (make-string w ?\ )
8689 a))
8690 s "")))
8691
8692 (defun org-table-kill-row ()
8693 "Delete the current row or horizontal line from the table."
8694 (interactive)
8695 (if (not (org-at-table-p))
8696 (error "Not at a table"))
8697 (let ((col (current-column)))
8698 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8699 (if (not (org-at-table-p)) (beginning-of-line 0))
8700 (move-to-column col)))
8701
8702 (defun org-table-sort-lines (beg end numericp)
8703 "Sort table lines in region.
8704 Point and mark define the first and last line to include. Both point and
8705 mark should be in the column that is used for sorting. For example, to
8706 sort according to column 3, put the mark in the first line to sort, in
8707 table column 3. Put point into the last line to be included in the sorting,
8708 also in table column 3. The command will prompt for the sorting method
8709 \(n for numerical, a for alphanumeric)."
8710 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8711 (setq numericp (string-match "[nN]" numericp))
8712 (org-table-align) ;; Just to be safe
8713 (let* (bcol ecol cmp column lns)
8714 (goto-char beg)
8715 (org-table-check-inside-data-field)
8716 (setq column (org-table-current-column)
8717 beg (move-marker (make-marker) (point-at-bol)))
8718 (goto-char end)
8719 (org-table-check-inside-data-field)
8720 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8721 (untabify beg end)
8722 (goto-char beg)
8723 (org-table-goto-column column)
8724 (skip-chars-backward "^|")
8725 (setq bcol (current-column))
8726 (org-table-goto-column (1+ column))
8727 (skip-chars-backward "^|")
8728 (setq ecol (1- (current-column)))
8729 (setq cmp (if numericp
8730 (lambda (a b) (< (car a) (car b)))
8731 (lambda (a b) (string< (car a) (car b)))))
8732 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8733 (split-string (buffer-substring beg end) "\n")))
8734 (if numericp
8735 (setq lns (mapcar (lambda(x)
8736 (cons (string-to-number (car x)) (cdr x)))
8737 lns)))
8738 (delete-region beg end)
8739 (move-marker beg nil)
8740 (move-marker end nil)
8741 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8742 (message "%d lines sorted %s based on column %d"
8743 (length lns)
8744 (if numericp "numerically" "alphabetically") column)))
8745
8746 (defun org-table-cut-region (beg end)
8747 "Copy region in table to the clipboard and blank all relevant fields."
8748 (interactive "r")
8749 (org-table-copy-region beg end 'cut))
8750
8751 (defun org-table-copy-region (beg end &optional cut)
8752 "Copy rectangular region in table to clipboard.
8753 A special clipboard is used which can only be accessed
8754 with `org-table-paste-rectangle'."
8755 (interactive "rP")
8756 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8757 region cols
8758 (rpl (if cut " " nil)))
8759 (goto-char beg)
8760 (org-table-check-inside-data-field)
8761 (setq l01 (count-lines (point-min) (point))
8762 c01 (org-table-current-column))
8763 (goto-char end)
8764 (org-table-check-inside-data-field)
8765 (setq l02 (count-lines (point-min) (point))
8766 c02 (org-table-current-column))
8767 (setq l1 (min l01 l02) l2 (max l01 l02)
8768 c1 (min c01 c02) c2 (max c01 c02))
8769 (catch 'exit
8770 (while t
8771 (catch 'nextline
8772 (if (> l1 l2) (throw 'exit t))
8773 (goto-line l1)
8774 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8775 (setq cols nil ic1 c1 ic2 c2)
8776 (while (< ic1 (1+ ic2))
8777 (push (org-table-get-field ic1 rpl) cols)
8778 (setq ic1 (1+ ic1)))
8779 (push (nreverse cols) region)
8780 (setq l1 (1+ l1)))))
8781 (setq org-table-clip (nreverse region))
8782 (if cut (org-table-align))
8783 org-table-clip))
8784
8785 (defun org-table-paste-rectangle ()
8786 "Paste a rectangular region into a table.
8787 The upper right corner ends up in the current field. All involved fields
8788 will be overwritten. If the rectangle does not fit into the present table,
8789 the table is enlarged as needed. The process ignores horizontal separator
8790 lines."
8791 (interactive)
8792 (unless (and org-table-clip (listp org-table-clip))
8793 (error "First cut/copy a region to paste!"))
8794 (org-table-check-inside-data-field)
8795 (let* ((clip org-table-clip)
8796 (line (count-lines (point-min) (point)))
8797 (col (org-table-current-column))
8798 (org-enable-table-editor t)
8799 (org-table-automatic-realign nil)
8800 c cols field)
8801 (while (setq cols (pop clip))
8802 (while (org-at-table-hline-p) (beginning-of-line 2))
8803 (if (not (org-at-table-p))
8804 (progn (end-of-line 0) (org-table-next-field)))
8805 (setq c col)
8806 (while (setq field (pop cols))
8807 (org-table-goto-column c nil 'force)
8808 (org-table-get-field nil field)
8809 (setq c (1+ c)))
8810 (beginning-of-line 2))
8811 (goto-line line)
8812 (org-table-goto-column col)
8813 (org-table-align)))
8814
8815 (defun org-table-convert ()
8816 "Convert from `org-mode' table to table.el and back.
8817 Obviously, this only works within limits. When an Org-mode table is
8818 converted to table.el, all horizontal separator lines get lost, because
8819 table.el uses these as cell boundaries and has no notion of horizontal lines.
8820 A table.el table can be converted to an Org-mode table only if it does not
8821 do row or column spanning. Multiline cells will become multiple cells.
8822 Beware, Org-mode does not test if the table can be successfully converted - it
8823 blindly applies a recipe that works for simple tables."
8824 (interactive)
8825 (require 'table)
8826 (if (org-at-table.el-p)
8827 ;; convert to Org-mode table
8828 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8829 (end (move-marker (make-marker) (org-table-end t))))
8830 (table-unrecognize-region beg end)
8831 (goto-char beg)
8832 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8833 (replace-match ""))
8834 (goto-char beg))
8835 (if (org-at-table-p)
8836 ;; convert to table.el table
8837 (let ((beg (move-marker (make-marker) (org-table-begin)))
8838 (end (move-marker (make-marker) (org-table-end))))
8839 ;; first, get rid of all horizontal lines
8840 (goto-char beg)
8841 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8842 (replace-match ""))
8843 ;; insert a hline before first
8844 (goto-char beg)
8845 (org-table-insert-hline 'above)
8846 (beginning-of-line -1)
8847 ;; insert a hline after each line
8848 (while (progn (beginning-of-line 3) (< (point) end))
8849 (org-table-insert-hline))
8850 (goto-char beg)
8851 (setq end (move-marker end (org-table-end)))
8852 ;; replace "+" at beginning and ending of hlines
8853 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8854 (replace-match "\\1+-"))
8855 (goto-char beg)
8856 (while (re-search-forward "-|[ \t]*$" end t)
8857 (replace-match "-+"))
8858 (goto-char beg)))))
8859
8860 (defun org-table-wrap-region (arg)
8861 "Wrap several fields in a column like a paragraph.
8862 This is useful if you'd like to spread the contents of a field over several
8863 lines, in order to keep the table compact.
8864
8865 If there is an active region, and both point and mark are in the same column,
8866 the text in the column is wrapped to minimum width for the given number of
8867 lines. Generally, this makes the table more compact. A prefix ARG may be
8868 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8869 formats the selected text to two lines. If the region was longer than two
8870 lines, the remaining lines remain empty. A negative prefix argument reduces
8871 the current number of lines by that amount. The wrapped text is pasted back
8872 into the table. If you formatted it to more lines than it was before, fields
8873 further down in the table get overwritten - so you might need to make space in
8874 the table first.
8875
8876 If there is no region, the current field is split at the cursor position and
8877 the text fragment to the right of the cursor is prepended to the field one
8878 line down.
8879
8880 If there is no region, but you specify a prefix ARG, the current field gets
8881 blank, and the content is appended to the field above."
8882 (interactive "P")
8883 (org-table-check-inside-data-field)
8884 (if (org-region-active-p)
8885 ;; There is a region: fill as a paragraph
8886 (let ((beg (region-beginning))
8887 nlines)
8888 (org-table-cut-region (region-beginning) (region-end))
8889 (if (> (length (car org-table-clip)) 1)
8890 (error "Region must be limited to single column"))
8891 (setq nlines (if arg
8892 (if (< arg 1)
8893 (+ (length org-table-clip) arg)
8894 arg)
8895 (length org-table-clip)))
8896 (setq org-table-clip
8897 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8898 nil nlines)))
8899 (goto-char beg)
8900 (org-table-paste-rectangle))
8901 ;; No region, split the current field at point
8902 (if arg
8903 ;; combine with field above
8904 (let ((s (org-table-blank-field))
8905 (col (org-table-current-column)))
8906 (beginning-of-line 0)
8907 (while (org-at-table-hline-p) (beginning-of-line 0))
8908 (org-table-goto-column col)
8909 (skip-chars-forward "^|")
8910 (skip-chars-backward " ")
8911 (insert " " (org-trim s))
8912 (org-table-align))
8913 ;; split field
8914 (when (looking-at "\\([^|]+\\)+|")
8915 (let ((s (match-string 1)))
8916 (replace-match " |")
8917 (goto-char (match-beginning 0))
8918 (org-table-next-row)
8919 (insert (org-trim s) " ")
8920 (org-table-align))))))
8921
8922 (defun org-trim (s)
8923 "Remove whitespace at beginning and end of string."
8924 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8925 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8926 s)
8927
8928 (defun org-wrap (string &optional width lines)
8929 "Wrap string to either a number of lines, or a width in characters.
8930 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8931 that costs. If there is a word longer than WIDTH, the text is actually
8932 wrapped to the length of that word.
8933 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8934 many lines, whatever width that takes.
8935 The return value is a list of lines, without newlines at the end."
8936 (let* ((words (org-split-string string "[ \t\n]+"))
8937 (maxword (apply 'max (mapcar 'string-width words)))
8938 w ll)
8939 (cond (width
8940 (org-do-wrap words (max maxword width)))
8941 (lines
8942 (setq w maxword)
8943 (setq ll (org-do-wrap words maxword))
8944 (if (<= (length ll) lines)
8945 ll
8946 (setq ll words)
8947 (while (> (length ll) lines)
8948 (setq w (1+ w))
8949 (setq ll (org-do-wrap words w)))
8950 ll))
8951 (t (error "Cannot wrap this")))))
8952
8953
8954 (defun org-do-wrap (words width)
8955 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8956 (let (lines line)
8957 (while words
8958 (setq line (pop words))
8959 (while (and words (< (+ (length line) (length (car words))) width))
8960 (setq line (concat line " " (pop words))))
8961 (setq lines (push line lines)))
8962 (nreverse lines)))
8963
8964 ;; FIXME: I think I can make this more efficient
8965 (defun org-split-string (string &optional separators)
8966 "Splits STRING into substrings at SEPARATORS.
8967 No empty strings are returned if there are matches at the beginning
8968 and end of string."
8969 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8970 (start 0)
8971 notfirst
8972 (list nil))
8973 (while (and (string-match rexp string
8974 (if (and notfirst
8975 (= start (match-beginning 0))
8976 (< start (length string)))
8977 (1+ start) start))
8978 (< (match-beginning 0) (length string)))
8979 (setq notfirst t)
8980 (or (eq (match-beginning 0) 0)
8981 (and (eq (match-beginning 0) (match-end 0))
8982 (eq (match-beginning 0) start))
8983 (setq list
8984 (cons (substring string start (match-beginning 0))
8985 list)))
8986 (setq start (match-end 0)))
8987 (or (eq start (length string))
8988 (setq list
8989 (cons (substring string start)
8990 list)))
8991 (nreverse list)))
8992
8993 (defun org-table-add-invisible-to-vertical-lines ()
8994 "Add an `invisible' property to vertical lines of current table."
8995 (interactive)
8996 (let* ((beg (org-table-begin))
8997 (end (org-table-end))
8998 (end1))
8999 (save-excursion
9000 (goto-char beg)
9001 (while (< (point) end)
9002 (setq end1 (point-at-eol))
9003 (if (looking-at org-table-dataline-regexp)
9004 (while (re-search-forward "|" end1 t)
9005 (add-text-properties (1- (point)) (point)
9006 '(invisible org-table)))
9007 (while (re-search-forward "[+|]" end1 t)
9008 (add-text-properties (1- (point)) (point)
9009 '(invisible org-table))))
9010 (beginning-of-line 2)))))
9011
9012 (defun org-table-toggle-vline-visibility (&optional arg)
9013 "Toggle the visibility of table vertical lines.
9014 The effect is immediate and on all tables in the file.
9015 With prefix ARG, make lines invisible when ARG is positive, make lines
9016 visible when ARG is not positive."
9017 (interactive "P")
9018 (let ((action (cond
9019 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
9020 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
9021 (t (if (org-in-invisibility-spec-p '(org-table))
9022 'off
9023 'on)))))
9024 (if (eq action 'off)
9025 (progn
9026 (org-remove-from-invisibility-spec '(org-table))
9027 (org-table-map-tables 'org-table-align)
9028 (message "Vertical table lines visible")
9029 (if (org-at-table-p)
9030 (org-table-align)))
9031 (org-add-to-invisibility-spec '(org-table))
9032 (org-table-map-tables 'org-table-align)
9033 (message "Vertical table lines invisible"))
9034 (redraw-frame (selected-frame))))
9035
9036 (defun org-table-map-tables (function)
9037 "Apply FUNCTION to the start of all tables in the buffer."
9038 (save-excursion
9039 (save-restriction
9040 (widen)
9041 (goto-char (point-min))
9042 (while (re-search-forward org-table-any-line-regexp nil t)
9043 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9044 (beginning-of-line 1)
9045 (if (looking-at org-table-line-regexp)
9046 (save-excursion (funcall function)))
9047 (re-search-forward org-table-any-border-regexp nil 1)))))
9048
9049 (defun org-table-sum (&optional beg end nlast)
9050 "Sum numbers in region of current table column.
9051 The result will be displayed in the echo area, and will be available
9052 as kill to be inserted with \\[yank].
9053
9054 If there is an active region, it is interpreted as a rectangle and all
9055 numbers in that rectangle will be summed. If there is no active
9056 region and point is located in a table column, sum all numbers in that
9057 column.
9058
9059 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9060 numbers are assumed to be times as well (in decimal hours) and the
9061 numbers are added as such.
9062
9063 If NLAST is a number, only the NLAST fields will actually be summed."
9064 (interactive)
9065 (save-excursion
9066 (let (col (timecnt 0) diff h m s org-table-clip)
9067 (cond
9068 ((and beg end)) ; beg and end given explicitly
9069 ((org-region-active-p)
9070 (setq beg (region-beginning) end (region-end)))
9071 (t
9072 (setq col (org-table-current-column))
9073 (goto-char (org-table-begin))
9074 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9075 (error "No table data"))
9076 (org-table-goto-column col)
9077 ;not needed? (skip-chars-backward "^|")
9078 (setq beg (point))
9079 (goto-char (org-table-end))
9080 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9081 (error "No table data"))
9082 (org-table-goto-column col)
9083 ;not needed? (skip-chars-forward "^|")
9084 (setq end (point))))
9085 (let* ((items (apply 'append (org-table-copy-region beg end)))
9086 (items1 (cond ((not nlast) items)
9087 ((>= nlast (length items)) items)
9088 (t (setq items (reverse items))
9089 (setcdr (nthcdr (1- nlast) items) nil)
9090 (nreverse items))))
9091 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9092 items1)))
9093 (res (apply '+ numbers))
9094 (sres (if (= timecnt 0)
9095 (format "%g" res)
9096 (setq diff (* 3600 res)
9097 h (floor (/ diff 3600)) diff (mod diff 3600)
9098 m (floor (/ diff 60)) diff (mod diff 60)
9099 s diff)
9100 (format "%d:%02d:%02d" h m s))))
9101 (kill-new sres)
9102 (if (interactive-p)
9103 (message "%s"
9104 (substitute-command-keys
9105 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9106 (length numbers) sres))))
9107 sres))))
9108
9109 (defun org-table-get-number-for-summing (s)
9110 (let (n)
9111 (if (string-match "^ *|? *" s)
9112 (setq s (replace-match "" nil nil s)))
9113 (if (string-match " *|? *$" s)
9114 (setq s (replace-match "" nil nil s)))
9115 (setq n (string-to-number s))
9116 (cond
9117 ((and (string-match "0" s)
9118 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9119 ((string-match "\\`[ \t]+\\'" s) nil)
9120 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9121 (let ((h (string-to-number (or (match-string 1 s) "0")))
9122 (m (string-to-number (or (match-string 2 s) "0")))
9123 (s (string-to-number (or (match-string 4 s) "0"))))
9124 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9125 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9126 ((equal n 0) nil)
9127 (t n))))
9128
9129 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9130 "Get a calc vector from a column, accorting to descriptor DESC.
9131 Optional arguments TBEG and COL can give the beginning of the table and
9132 the current column, to avoid unnecessary parsing."
9133 (save-excursion
9134 (or tbeg (setq tbeg (org-table-begin)))
9135 (or col (setq col (org-table-current-column)))
9136 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9137 (cond
9138 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9139 (setq n1 (- (match-end 1) (match-beginning 1)))
9140 (if (match-beginning 3)
9141 (setq n2 (- (match-end 2) (match-beginning 3))))
9142 (setq n (if n2 (max n1 n2) n1))
9143 (setq n1 (if n2 (min n1 n2)))
9144 (setq nn n)
9145 (while (and (> nn 0)
9146 (re-search-backward org-table-hline-regexp tbeg t))
9147 (push (org-current-line) hline-list)
9148 (setq nn (1- nn)))
9149 (setq hline-list (nreverse hline-list))
9150 (goto-line (nth (1- n) hline-list))
9151 (when (re-search-forward org-table-dataline-regexp)
9152 (org-table-goto-column col)
9153 (setq beg (point)))
9154 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9155 (when (re-search-backward org-table-dataline-regexp)
9156 (org-table-goto-column col)
9157 (setq end (point)))
9158 (setq l (apply 'append (org-table-copy-region beg end)))
9159 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9160 (if (equal x "") "0" x))
9161 l ",") "]"))
9162 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9163 (setq n1 (string-to-number (match-string 1 desc))
9164 n2 (string-to-number (match-string 2 desc)))
9165 (beginning-of-line 1)
9166 (save-excursion
9167 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9168 (org-table-goto-column col)
9169 (setq beg (point))))
9170 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9171 (org-table-goto-column col)
9172 (setq end (point)))
9173 (setq l (apply 'append (org-table-copy-region beg end)))
9174 (concat "[" (mapconcat
9175 (lambda (x) (setq x (org-trim x))
9176 (if (equal x "") "0" x))
9177 l ",") "]"))
9178 ((string-match "\\([0-9]+\\)" desc)
9179 (beginning-of-line 1)
9180 (when (re-search-backward org-table-dataline-regexp tbeg t
9181 (string-to-number (match-string 0 desc)))
9182 (org-table-goto-column col)
9183 (org-trim (org-table-get-field))))))))
9184
9185 (defvar org-table-formula-history nil)
9186
9187 (defvar org-table-column-names nil
9188 "Alist with column names, derived from the `!' line.")
9189 (defvar org-table-column-name-regexp nil
9190 "Regular expression matching the current column names.")
9191 (defvar org-table-local-parameters nil
9192 "Alist with parameter names, derived from the `$' line.")
9193 (defvar org-table-named-field-locations nil
9194 "Alist with locations of named fields.")
9195
9196 (defun org-table-get-formula (&optional equation named)
9197 "Read a formula from the minibuffer, offer stored formula as default."
9198 (let* ((name (car (rassoc (list (org-current-line)
9199 (org-table-current-column))
9200 org-table-named-field-locations)))
9201 (scol (if named
9202 (if name name
9203 (error "Not in a named field"))
9204 (int-to-string (org-table-current-column))))
9205 (dummy (and name (not named)
9206 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9207 (error "Abort")))
9208 (org-table-may-need-update nil)
9209 (stored-list (org-table-get-stored-formulas))
9210 (stored (cdr (assoc scol stored-list)))
9211 (eq (cond
9212 ((and stored equation (string-match "^ *=? *$" equation))
9213 stored)
9214 ((stringp equation)
9215 equation)
9216 (t (read-string
9217 (format "%s formula $%s=" (if named "Field" "Column") scol)
9218 (or stored "") 'org-table-formula-history
9219 ;stored
9220 ))))
9221 mustsave)
9222 (when (not (string-match "\\S-" eq))
9223 ;; remove formula
9224 (setq stored-list (delq (assoc scol stored-list) stored-list))
9225 (org-table-store-formulas stored-list)
9226 (error "Formula removed"))
9227 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9228 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9229 (if (and name (not named))
9230 ;; We set the column equation, delete the named one.
9231 (setq stored-list (delq (assoc name stored-list) stored-list)
9232 mustsave t))
9233 (if stored
9234 (setcdr (assoc scol stored-list) eq)
9235 (setq stored-list (cons (cons scol eq) stored-list)))
9236 (if (or mustsave (not (equal stored eq)))
9237 (org-table-store-formulas stored-list))
9238 eq))
9239
9240 (defun org-table-store-formulas (alist)
9241 "Store the list of formulas below the current table."
9242 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9243 (save-excursion
9244 (goto-char (org-table-end))
9245 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9246 (delete-region (point) (match-end 0)))
9247 (insert "#+TBLFM: "
9248 (mapconcat (lambda (x)
9249 (concat "$" (car x) "=" (cdr x)))
9250 alist "::")
9251 "\n")))
9252
9253 (defun org-table-get-stored-formulas ()
9254 "Return an alist with the t=stored formulas directly after current table."
9255 (interactive)
9256 (let (scol eq eq-alist strings string seen)
9257 (save-excursion
9258 (goto-char (org-table-end))
9259 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9260 (setq strings (org-split-string (match-string 2) " *:: *"))
9261 (while (setq string (pop strings))
9262 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9263 (setq scol (match-string 1 string)
9264 eq (match-string 2 string)
9265 eq-alist (cons (cons scol eq) eq-alist))
9266 (if (member scol seen)
9267 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9268 (push scol seen))))))
9269 (nreverse eq-alist)))
9270
9271 (defun org-table-modify-formulas (action &rest columns)
9272 "Modify the formulas stored below the current table.
9273 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9274 expected, for the other actions only a single column number is needed."
9275 (let ((list (org-table-get-stored-formulas))
9276 (nmax (length (org-split-string
9277 (buffer-substring (point-at-bol) (point-at-eol))
9278 "|")))
9279 col col1 col2 scol si sc1 sc2)
9280 (cond
9281 ((null list)) ; No action needed if there are no stored formulas
9282 ((eq action 'remove)
9283 (setq col (car columns)
9284 scol (int-to-string col))
9285 (org-table-replace-in-formulas list scol "INVALID")
9286 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9287 (loop for i from (1+ col) upto nmax by 1 do
9288 (setq si (int-to-string i))
9289 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9290 (if (assoc si list) (setcar (assoc si list)
9291 (int-to-string (1- i))))))
9292 ((eq action 'insert)
9293 (setq col (car columns))
9294 (loop for i from nmax downto col by 1 do
9295 (setq si (int-to-string i))
9296 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9297 (if (assoc si list) (setcar (assoc si list)
9298 (int-to-string (1+ i))))))
9299 ((eq action 'swap)
9300 (setq col1 (car columns) col2 (nth 1 columns)
9301 sc1 (int-to-string col1) sc2 (int-to-string col2))
9302 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
9303 (org-table-replace-in-formulas list sc1 "ZqZ")
9304 (org-table-replace-in-formulas list sc2 sc1)
9305 (org-table-replace-in-formulas list "ZqZ" sc2)
9306 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
9307 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9308 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
9309 (t (error "Invalid action in `org-table-modify-formulas'")))
9310 (if list (org-table-store-formulas list))))
9311
9312 (defun org-table-replace-in-formulas (list s1 s2)
9313 (let (elt re s)
9314 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9315 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
9316 re (concat (regexp-quote s1) "\\>"))
9317 (while (setq elt (pop list))
9318 (setq s (cdr elt))
9319 (while (string-match re s)
9320 (setq s (replace-match s2 t t s)))
9321 (setcdr elt s))))
9322
9323 (defun org-table-get-specials ()
9324 "Get the column names and local parameters for this table."
9325 (save-excursion
9326 (let ((beg (org-table-begin)) (end (org-table-end))
9327 names name fields fields1 field cnt c v line col)
9328 (setq org-table-column-names nil
9329 org-table-local-parameters nil
9330 org-table-named-field-locations nil)
9331 (goto-char beg)
9332 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9333 (setq names (org-split-string (match-string 1) " *| *")
9334 cnt 1)
9335 (while (setq name (pop names))
9336 (setq cnt (1+ cnt))
9337 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9338 (push (cons name (int-to-string cnt)) org-table-column-names))))
9339 (setq org-table-column-names (nreverse org-table-column-names))
9340 (setq org-table-column-name-regexp
9341 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9342 (goto-char beg)
9343 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9344 (setq fields (org-split-string (match-string 1) " *| *"))
9345 (while (setq field (pop fields))
9346 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9347 (push (cons (match-string 1 field) (match-string 2 field))
9348 org-table-local-parameters))))
9349 (goto-char beg)
9350 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9351 (setq c (match-string 1)
9352 fields (org-split-string (match-string 2) " *| *"))
9353 (save-excursion
9354 (beginning-of-line (if (equal c "_") 2 0))
9355 (setq line (org-current-line) col 1)
9356 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9357 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9358 (while (and fields1 (setq field (pop fields)))
9359 (setq v (pop fields1) col (1+ col))
9360 (when (and (stringp field) (stringp v)
9361 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9362 (push (cons field v) org-table-local-parameters)
9363 (push (list field line col) org-table-named-field-locations)))))))
9364
9365 (defun org-this-word ()
9366 ;; Get the current word
9367 (save-excursion
9368 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
9369 (end (progn (skip-chars-forward "^ \t\n") (point))))
9370 (buffer-substring-no-properties beg end))))
9371
9372 (defun org-table-maybe-eval-formula ()
9373 "Check if the current field starts with \"=\" or \":=\".
9374 If yes, store the formula and apply it."
9375 ;; We already know we are in a table. Get field will only return a formula
9376 ;; when appropriate. It might return a separator line, but no problem.
9377 (when org-table-formula-evaluate-inline
9378 (let* ((field (org-trim (or (org-table-get-field) "")))
9379 named eq)
9380 (when (string-match "^:?=\\(.*\\)" field)
9381 (setq named (equal (string-to-char field) ?:)
9382 eq (match-string 1 field))
9383 (if (fboundp 'calc-eval)
9384 (org-table-eval-formula (if named '(4) nil) eq))))))
9385
9386 (defvar org-recalc-commands nil
9387 "List of commands triggering the recalculation of a line.
9388 Will be filled automatically during use.")
9389
9390 (defvar org-recalc-marks
9391 '((" " . "Unmarked: no special line, no automatic recalculation")
9392 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9393 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9394 ("!" . "Column name definition line. Reference in formula as $name.")
9395 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9396 ("_" . "Names for values in row below this one.")
9397 ("^" . "Names for values in row above this one.")))
9398
9399 (defun org-table-rotate-recalc-marks (&optional newchar)
9400 "Rotate the recalculation mark in the first column.
9401 If in any row, the first field is not consistent with a mark,
9402 insert a new column for the markers.
9403 When there is an active region, change all the lines in the region,
9404 after prompting for the marking character.
9405 After each change, a message will be displayed indicating the meaning
9406 of the new mark."
9407 (interactive)
9408 (unless (org-at-table-p) (error "Not at a table"))
9409 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9410 (beg (org-table-begin))
9411 (end (org-table-end))
9412 (l (org-current-line))
9413 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9414 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9415 (have-col
9416 (save-excursion
9417 (goto-char beg)
9418 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9419 (col (org-table-current-column))
9420 (forcenew (car (assoc newchar org-recalc-marks)))
9421 epos new)
9422 (when l1
9423 (message "Change region to what mark? Type # * ! $ or SPC: ")
9424 (setq newchar (char-to-string (read-char-exclusive))
9425 forcenew (car (assoc newchar org-recalc-marks))))
9426 (if (and newchar (not forcenew))
9427 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9428 newchar))
9429 (if l1 (goto-line l1))
9430 (save-excursion
9431 (beginning-of-line 1)
9432 (unless (looking-at org-table-dataline-regexp)
9433 (error "Not at a table data line")))
9434 (unless have-col
9435 (org-table-goto-column 1)
9436 (org-table-insert-column)
9437 (org-table-goto-column (1+ col)))
9438 (setq epos (point-at-eol))
9439 (save-excursion
9440 (beginning-of-line 1)
9441 (org-table-get-field
9442 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9443 (concat " "
9444 (setq new (or forcenew
9445 (cadr (member (match-string 1) marks))))
9446 " ")
9447 " # ")))
9448 (if (and l1 l2)
9449 (progn
9450 (goto-line l1)
9451 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9452 (and (looking-at org-table-dataline-regexp)
9453 (org-table-get-field 1 (concat " " new " "))))
9454 (goto-line l1)))
9455 (if (not (= epos (point-at-eol))) (org-table-align))
9456 (goto-line l)
9457 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9458
9459 (defun org-table-maybe-recalculate-line ()
9460 "Recompute the current line if marked for it, and if we haven't just done it."
9461 (interactive)
9462 (and org-table-allow-automatic-line-recalculation
9463 (not (and (memq last-command org-recalc-commands)
9464 (equal org-last-recalc-line (org-current-line))))
9465 (save-excursion (beginning-of-line 1)
9466 (looking-at org-table-auto-recalculate-regexp))
9467 (fboundp 'calc-eval)
9468 (org-table-recalculate) t))
9469
9470 (defvar org-table-formula-debug nil
9471 "Non-nil means, debug table formulas.
9472 When nil, simply write \"#ERROR\" in corrupted fields.")
9473
9474 (defvar modes)
9475 (defsubst org-set-calc-mode (var &optional value)
9476 (if (stringp var)
9477 (setq var (assoc var '(("D" calc-angle-mode deg)
9478 ("R" calc-angle-mode rad)
9479 ("F" calc-prefer-frac t)
9480 ("S" calc-symbolic-mode t)))
9481 value (nth 2 var) var (nth 1 var)))
9482 (if (memq var modes)
9483 (setcar (cdr (memq var modes)) value)
9484 (cons var (cons value modes)))
9485 modes)
9486
9487 (defun org-table-eval-formula (&optional arg equation
9488 suppress-align suppress-const
9489 suppress-store)
9490 "Replace the table field value at the cursor by the result of a calculation.
9491
9492 This function makes use of Dave Gillespie's Calc package, in my view the
9493 most exciting program ever written for GNU Emacs. So you need to have Calc
9494 installed in order to use this function.
9495
9496 In a table, this command replaces the value in the current field with the
9497 result of a formula. It also installs the formula as the \"current\" column
9498 formula, by storing it in a special line below the table. When called
9499 with a `C-u' prefix, the current field must ba a named field, and the
9500 formula is installed as valid in only this specific field.
9501
9502 When called, the command first prompts for a formula, which is read in
9503 the minibuffer. Previously entered formulas are available through the
9504 history list, and the last used formula is offered as a default.
9505 These stored formulas are adapted correctly when moving, inserting, or
9506 deleting columns with the corresponding commands.
9507
9508 The formula can be any algebraic expression understood by the Calc package.
9509 For details, see the Org-mode manual.
9510
9511 This function can also be called from Lisp programs and offers
9512 additional arguments: EQUATION can be the formula to apply. If this
9513 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9514 used to speed-up recursive calls by by-passing unnecessary aligns.
9515 SUPPRESS-CONST suppresses the interpretation of constants in the
9516 formula, assuming that this has been done already outside the function.
9517 SUPPRESS-STORE means the formula should not be stored, either because
9518 it is already stored, or because it is a modified equation that should
9519 not overwrite the stored one."
9520 (interactive "P")
9521 (require 'calc)
9522 (org-table-check-inside-data-field)
9523 (org-table-get-specials)
9524 (let* (fields
9525 (ndown (if (integerp arg) arg 1))
9526 (org-table-automatic-realign nil)
9527 (case-fold-search nil)
9528 (down (> ndown 1))
9529 (formula (if (and equation suppress-store)
9530 equation
9531 (org-table-get-formula equation (equal arg '(4)))))
9532 (n0 (org-table-current-column))
9533 (modes (copy-sequence org-calc-default-modes))
9534 n form fmt x ev orig c)
9535 ;; Parse the format string. Since we have a lot of modes, this is
9536 ;; a lot of work. However, I think calc still uses most of the time.
9537 (if (string-match ";" formula)
9538 (let ((tmp (org-split-string formula ";")))
9539 (setq formula (car tmp)
9540 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9541 (nth 1 tmp)))
9542 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9543 (setq c (string-to-char (match-string 1 fmt))
9544 n (string-to-number (or (match-string 1 fmt) "")))
9545 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9546 (setq modes (org-set-calc-mode
9547 'calc-float-format
9548 (list (cdr (assoc c '((?n . float) (?f . fix)
9549 (?s . sci) (?e . eng))))
9550 n))))
9551 (setq fmt (replace-match "" t t fmt)))
9552 (while (string-match "[DRFS]" fmt)
9553 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9554 (setq fmt (replace-match "" t t fmt)))
9555 (unless (string-match "\\S-" fmt)
9556 (setq fmt nil))))
9557 (if (and (not suppress-const) org-table-formula-use-constants)
9558 (setq formula (org-table-formula-substitute-names formula)))
9559 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9560 (while (> ndown 0)
9561 (setq fields (org-split-string
9562 (buffer-substring
9563 (point-at-bol) (point-at-eol)) " *| *"))
9564 (if org-table-formula-numbers-only
9565 (setq fields (mapcar
9566 (lambda (x) (number-to-string (string-to-number x)))
9567 fields)))
9568 (setq ndown (1- ndown))
9569 (setq form (copy-sequence formula))
9570 ;; Insert the references to fields in same row
9571 (while (string-match "\\$\\([0-9]+\\)?" form)
9572 (setq n (if (match-beginning 1)
9573 (string-to-number (match-string 1 form))
9574 n0)
9575 x (nth (1- n) fields))
9576 (unless x (error "Invalid field specifier \"%s\""
9577 (match-string 0 form)))
9578 (if (equal x "") (setq x "0"))
9579 (setq form (replace-match (concat "(" x ")") t t form)))
9580 ;; Insert ranges in current column
9581 (while (string-match "\\&[-I0-9]+" form)
9582 (setq form (replace-match
9583 (save-match-data
9584 (org-table-get-vertical-vector (match-string 0 form)
9585 nil n0))
9586 t t form)))
9587 (setq ev (calc-eval (cons form modes)
9588 (if org-table-formula-numbers-only 'num)))
9589
9590 (when org-table-formula-debug
9591 (with-output-to-temp-buffer "*Help*"
9592 (princ (format "Substitution history of formula
9593 Orig: %s
9594 $xyz-> %s
9595 $1-> %s\n" orig formula form))
9596 (if (listp ev)
9597 (princ (format " %s^\nError: %s"
9598 (make-string (car ev) ?\-) (nth 1 ev)))
9599 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9600 ev (or fmt "NONE")
9601 (if fmt (format fmt (string-to-number ev)) ev)))))
9602 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9603 (unless (and (interactive-p) (not ndown))
9604 (unless (let (inhibit-redisplay)
9605 (y-or-n-p "Debugging Formula. Continue to next? "))
9606 (org-table-align)
9607 (error "Abort"))
9608 (delete-window (get-buffer-window "*Help*"))
9609 (message "")))
9610 (if (listp ev) (setq fmt nil ev "#ERROR"))
9611 (org-table-justify-field-maybe
9612 (if fmt (format fmt (string-to-number ev)) ev))
9613 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9614 (call-interactively 'org-return)
9615 (setq ndown 0)))
9616 (and down (org-table-maybe-recalculate-line))
9617 (or suppress-align (and org-table-may-need-update
9618 (org-table-align)))))
9619
9620 (defun org-table-recalculate (&optional all noalign)
9621 "Recalculate the current table line by applying all stored formulas."
9622 (interactive "P")
9623 (or (memq this-command org-recalc-commands)
9624 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9625 (unless (org-at-table-p) (error "Not at a table"))
9626 (org-table-get-specials)
9627 (let* ((eqlist (sort (org-table-get-stored-formulas)
9628 (lambda (a b) (string< (car a) (car b)))))
9629 (inhibit-redisplay t)
9630 (line-re org-table-dataline-regexp)
9631 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9632 (thiscol (org-table-current-column))
9633 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9634 ;; Insert constants in all formulas
9635 (setq eqlist
9636 (mapcar (lambda (x)
9637 (setcdr x (org-table-formula-substitute-names (cdr x)))
9638 x)
9639 eqlist))
9640 ;; Split the equation list
9641 (while (setq eq (pop eqlist))
9642 (if (<= (string-to-char (car eq)) ?9)
9643 (push eq eqlnum)
9644 (push eq eqlname)))
9645 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9646 (if all
9647 (progn
9648 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9649 (goto-char (setq beg (org-table-begin)))
9650 (if (re-search-forward org-table-calculate-mark-regexp end t)
9651 ;; This is a table with marked lines, only compute selected lines
9652 (setq line-re org-table-recalculate-regexp)
9653 ;; Move forward to the first non-header line
9654 (if (and (re-search-forward org-table-dataline-regexp end t)
9655 (re-search-forward org-table-hline-regexp end t)
9656 (re-search-forward org-table-dataline-regexp end t))
9657 (setq beg (match-beginning 0))
9658 nil))) ;; just leave beg where it is
9659 (setq beg (point-at-bol)
9660 end (move-marker (make-marker) (1+ (point-at-eol)))))
9661 (goto-char beg)
9662 (and all (message "Re-applying formulas to full table..."))
9663 (while (re-search-forward line-re end t)
9664 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9665 ;; Unprotected line, recalculate
9666 (and all (message "Re-applying formulas to full table...(line %d)"
9667 (setq cnt (1+ cnt))))
9668 (setq org-last-recalc-line (org-current-line))
9669 (setq eql eqlnum)
9670 (while (setq entry (pop eql))
9671 (goto-line org-last-recalc-line)
9672 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9673 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9674 (goto-line thisline)
9675 (org-table-goto-column thiscol)
9676 (or noalign (and org-table-may-need-update (org-table-align))
9677 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9678 ;; Now do the names fields
9679 (while (setq eq (pop eqlname))
9680 (setq name (car eq)
9681 a (assoc name org-table-named-field-locations))
9682 (when a
9683 (message "Re-applying formula to named field: %s" name)
9684 (goto-line (nth 1 a))
9685 (org-table-goto-column (nth 2 a))
9686 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9687 ;; back to initial position
9688 (goto-line thisline)
9689 (org-table-goto-column thiscol)
9690 (or noalign (and org-table-may-need-update (org-table-align))
9691 (and all (message "Re-applying formulas...done")))))
9692
9693 (defun org-table-formula-substitute-names (f)
9694 "Replace $const with values in string F."
9695 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9696 ;; First, check for column names
9697 (while (setq start (string-match org-table-column-name-regexp f start))
9698 (setq start (1+ start))
9699 (setq a (assoc (match-string 1 f) org-table-column-names))
9700 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9701 ;; Expand ranges to vectors
9702 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9703 (setq n1 (string-to-number (match-string 1 f))
9704 n2 (string-to-number (match-string 2 f))
9705 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9706 s (concat "[($" (number-to-string (1- nn1)) ")"))
9707 (loop for i from nn1 upto nn2 do
9708 (setq s (concat s ",($" (int-to-string i) ")")))
9709 (setq s (concat s "]"))
9710 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9711 (setq f (replace-match s t t f)))
9712 ;; Parameters and constants
9713 (setq start 0)
9714 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9715 (setq start (1+ start))
9716 (if (setq a (save-match-data
9717 (org-table-get-constant (match-string 1 f))))
9718 (setq f (replace-match (concat "(" a ")") t t f))))
9719 (if org-table-formula-debug
9720 (put-text-property 0 (length f) :orig-formula f1 f))
9721 f))
9722
9723 (defun org-table-get-constant (const)
9724 "Find the value for a parameter or constant in a formula.
9725 Parameters get priority."
9726 (or (cdr (assoc const org-table-local-parameters))
9727 (cdr (assoc const org-table-formula-constants))
9728 (and (fboundp 'constants-get) (constants-get const))
9729 "#UNDEFINED_NAME"))
9730
9731 (defvar org-edit-formulas-map (make-sparse-keymap))
9732 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9733 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9734 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9735
9736 (defvar org-pos)
9737 (defvar org-window-configuration)
9738
9739 (defun org-table-edit-formulas ()
9740 "Edit the formulas of the current table in a separate buffer."
9741 (interactive)
9742 (unless (org-at-table-p)
9743 (error "Not at a table"))
9744 (org-table-get-specials)
9745 (let ((eql (org-table-get-stored-formulas))
9746 (pos (move-marker (make-marker) (point)))
9747 (wc (current-window-configuration))
9748 entry loc s)
9749 (switch-to-buffer-other-window "*Edit Formulas*")
9750 (erase-buffer)
9751 (fundamental-mode)
9752 (set (make-local-variable 'org-pos) pos)
9753 (set (make-local-variable 'org-window-configuration) wc)
9754 (use-local-map org-edit-formulas-map)
9755 (setq s "# Edit formulas and finish with `C-c C-c'.
9756 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9757 # Use `C-c ?' to get information about $name at point.
9758 # To cancel editing, press `C-c C-q'.\n")
9759 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9760 (insert s)
9761 (while (setq entry (pop eql))
9762 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9763 (setq s (format "# Named formula, referring to column %d in line %d\n"
9764 (nth 2 loc) (nth 1 loc)))
9765 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9766 (insert s))
9767 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9768 (remove-text-properties 0 (length s) '(face nil) s)
9769 (insert s))
9770 (goto-char (point-min))
9771 (message "Edit formulas and finish with `C-c C-c'.")))
9772
9773 (defun org-show-variable ()
9774 "Show the location/value of the $ expression at point."
9775 (interactive)
9776 (let (var (pos org-pos) (win (selected-window)) e)
9777 (save-excursion
9778 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9779 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9780 (setq var (match-string 1))
9781 (error "No variable at point")))
9782 (cond
9783 ((setq e (assoc var org-table-named-field-locations))
9784 (switch-to-buffer-other-window (marker-buffer pos))
9785 (goto-line (nth 1 e))
9786 (org-table-goto-column (nth 2 e))
9787 (select-window win)
9788 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9789 ((setq e (assoc var org-table-column-names))
9790 (switch-to-buffer-other-window (marker-buffer pos))
9791 (goto-char pos)
9792 (goto-char (org-table-begin))
9793 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9794 (org-table-end) t)
9795 (progn
9796 (goto-char (match-beginning 1))
9797 (message "Named column (column %s)" (cdr e)))
9798 (error "Column name not found"))
9799 (select-window win))
9800 ((string-match "^[0-9]$" var)
9801 ;; column number
9802 (switch-to-buffer-other-window (marker-buffer pos))
9803 (goto-char pos)
9804 (goto-char (org-table-begin))
9805 (recenter 1)
9806 (if (re-search-forward org-table-dataline-regexp
9807 (org-table-end) t)
9808 (progn
9809 (goto-char (match-beginning 0))
9810 (org-table-goto-column (string-to-number var))
9811 (message "Column %s" var))
9812 (error "Column name not found"))
9813 (select-window win))
9814 ((setq e (assoc var org-table-local-parameters))
9815 (switch-to-buffer-other-window (marker-buffer pos))
9816 (goto-char pos)
9817 (goto-char (org-table-begin))
9818 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9819 (progn
9820 (goto-char (match-beginning 1))
9821 (message "Local parameter."))
9822 (error "Parameter not found"))
9823 (select-window win))
9824 (t
9825 (cond
9826 ((setq e (assoc var org-table-formula-constants))
9827 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9828 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9829 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9830 (t (error "Undefined name $%s" var)))))))
9831
9832 (defun org-finish-edit-formulas (&optional arg)
9833 "Parse the buffer for formula definitions and install them.
9834 With prefix ARG, apply the new formulas to the table."
9835 (interactive "P")
9836 (let ((pos org-pos) eql)
9837 (goto-char (point-min))
9838 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9839 (push (cons (match-string 1) (match-string 2)) eql))
9840 (set-window-configuration org-window-configuration)
9841 (select-window (get-buffer-window (marker-buffer pos)))
9842 (goto-char pos)
9843 (unless (org-at-table-p)
9844 (error "Lost table position - cannot install formulae"))
9845 (org-table-store-formulas eql)
9846 (move-marker pos nil)
9847 (kill-buffer "*Edit Formulas*")
9848 (if arg
9849 (org-table-recalculate 'all)
9850 (message "New formulas installed - press C-u C-c C-c to apply."))))
9851
9852 (defun org-abort-edit-formulas ()
9853 "Abort editing formulas, without installing the changes."
9854 (interactive)
9855 (let ((pos org-pos))
9856 (set-window-configuration org-window-configuration)
9857 (select-window (get-buffer-window (marker-buffer pos)))
9858 (goto-char pos)
9859 (message "Formula editing aborted without installing changes")))
9860
9861 ;;; The orgtbl minor mode
9862
9863 ;; Define a minor mode which can be used in other modes in order to
9864 ;; integrate the org-mode table editor.
9865
9866 ;; This is really a hack, because the org-mode table editor uses several
9867 ;; keys which normally belong to the major mode, for example the TAB and
9868 ;; RET keys. Here is how it works: The minor mode defines all the keys
9869 ;; necessary to operate the table editor, but wraps the commands into a
9870 ;; function which tests if the cursor is currently inside a table. If that
9871 ;; is the case, the table editor command is executed. However, when any of
9872 ;; those keys is used outside a table, the function uses `key-binding' to
9873 ;; look up if the key has an associated command in another currently active
9874 ;; keymap (minor modes, major mode, global), and executes that command.
9875 ;; There might be problems if any of the keys used by the table editor is
9876 ;; otherwise used as a prefix key.
9877
9878 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9879 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9880 ;; addresses this by checking explicitly for both bindings.
9881
9882 ;; The optimized version (see variable `orgtbl-optimized') takes over
9883 ;; all keys which are bound to `self-insert-command' in the *global map*.
9884 ;; Some modes bind other commands to simple characters, for example
9885 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9886 ;; active, this binding is ignored inside tables and replaced with a
9887 ;; modified self-insert.
9888
9889 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9890 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9891 In the optimized version, the table editor takes over all simple keys that
9892 normally just insert a character. In tables, the characters are inserted
9893 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9894 for empty fields). Outside tables, the correct binding of the keys is
9895 restored.
9896
9897 The default for this option is t if the optimized version is also used in
9898 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9899 this variable requires a restart of Emacs to become effective."
9900 :group 'org-table
9901 :type 'boolean)
9902
9903 (defvar orgtbl-mode nil
9904 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9905 table editor in arbitrary modes.")
9906 (make-variable-buffer-local 'orgtbl-mode)
9907
9908 (defvar orgtbl-mode-map (make-keymap)
9909 "Keymap for `orgtbl-mode'.")
9910
9911 ;;;###autoload
9912 (defun turn-on-orgtbl ()
9913 "Unconditionally turn on `orgtbl-mode'."
9914 (orgtbl-mode 1))
9915
9916 ;;;###autoload
9917 (defun orgtbl-mode (&optional arg)
9918 "The `org-mode' table editor as a minor mode for use in other modes."
9919 (interactive)
9920 (if (eq major-mode 'org-mode)
9921 ;; Exit without error, in case some hook functions calls this
9922 ;; by accident in org-mode.
9923 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9924 (setq orgtbl-mode
9925 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9926 (if orgtbl-mode
9927 (progn
9928 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9929 ;; Make sure we are first in minor-mode-map-alist
9930 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9931 (and c (setq minor-mode-map-alist
9932 (cons c (delq c minor-mode-map-alist)))))
9933 (set (make-local-variable (quote org-table-may-need-update)) t)
9934 (org-add-hook 'before-change-functions 'org-before-change-function
9935 nil 'local)
9936 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
9937 auto-fill-inhibit-regexp)
9938 (set (make-local-variable 'auto-fill-inhibit-regexp)
9939 (if auto-fill-inhibit-regexp
9940 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
9941 "[ \t]*|"))
9942 (easy-menu-add orgtbl-mode-menu)
9943 (run-hooks 'orgtbl-mode-hook))
9944 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9945 (remove-hook 'before-change-functions 'org-before-change-function t)
9946 (easy-menu-remove orgtbl-mode-menu)
9947 (force-mode-line-update 'all))))
9948
9949 ;; Install it as a minor mode.
9950 (put 'orgtbl-mode :included t)
9951 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9952 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9953
9954 (defun orgtbl-make-binding (fun n &rest keys)
9955 "Create a function for binding in the table minor mode.
9956 FUN is the command to call inside a table. N is used to create a unique
9957 command name. KEYS are keys that should be checked in for a command
9958 to execute outside of tables."
9959 (eval
9960 (list 'defun
9961 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9962 '(arg)
9963 (concat "In tables, run `" (symbol-name fun) "'.\n"
9964 "Outside of tables, run the binding of `"
9965 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9966 "'.")
9967 '(interactive "p")
9968 (list 'if
9969 '(org-at-table-p)
9970 (list 'call-interactively (list 'quote fun))
9971 (list 'let '(orgtbl-mode)
9972 (list 'call-interactively
9973 (append '(or)
9974 (mapcar (lambda (k)
9975 (list 'key-binding k))
9976 keys)
9977 '('orgtbl-error))))))))
9978
9979 (defun orgtbl-error ()
9980 "Error when there is no default binding for a table key."
9981 (interactive)
9982 (error "This key is has no function outside tables"))
9983
9984 (defun orgtbl-setup ()
9985 "Setup orgtbl keymaps."
9986 (let ((nfunc 0)
9987 (bindings
9988 (list
9989 '([(meta shift left)] org-table-delete-column)
9990 '([(meta left)] org-table-move-column-left)
9991 '([(meta right)] org-table-move-column-right)
9992 '([(meta shift right)] org-table-insert-column)
9993 '([(meta shift up)] org-table-kill-row)
9994 '([(meta shift down)] org-table-insert-row)
9995 '([(meta up)] org-table-move-row-up)
9996 '([(meta down)] org-table-move-row-down)
9997 '("\C-c\C-w" org-table-cut-region)
9998 '("\C-c\M-w" org-table-copy-region)
9999 '("\C-c\C-y" org-table-paste-rectangle)
10000 '("\C-c-" org-table-insert-hline)
10001 ; '([(shift tab)] org-table-previous-field)
10002 '("\C-m" org-table-next-row)
10003 (list (org-key 'S-return) 'org-table-copy-down)
10004 '([(meta return)] org-table-wrap-region)
10005 '("\C-c\C-q" org-table-wrap-region)
10006 '("\C-c?" org-table-current-column)
10007 '("\C-c " org-table-blank-field)
10008 '("\C-c+" org-table-sum)
10009 '("\C-c|" org-table-toggle-vline-visibility)
10010 '("\C-c=" org-table-eval-formula)
10011 '("\C-c'" org-table-edit-formulas)
10012 '("\C-c*" org-table-recalculate)
10013 '("\C-c^" org-table-sort-lines)
10014 '([(control ?#)] org-table-rotate-recalc-marks)))
10015 elt key fun cmd)
10016 (while (setq elt (pop bindings))
10017 (setq nfunc (1+ nfunc))
10018 (setq key (car elt)
10019 fun (nth 1 elt)
10020 cmd (orgtbl-make-binding fun nfunc key))
10021 (define-key orgtbl-mode-map key cmd))
10022 ;; Special treatment needed for TAB and RET
10023 (define-key orgtbl-mode-map [(return)]
10024 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10025 (define-key orgtbl-mode-map "\C-m"
10026 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10027 (define-key orgtbl-mode-map [(tab)]
10028 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10029 (define-key orgtbl-mode-map "\C-i"
10030 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10031 (define-key orgtbl-mode-map "\C-i"
10032 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10033 (define-key orgtbl-mode-map "\C-c\C-c"
10034 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10035 (when orgtbl-optimized
10036 ;; If the user wants maximum table support, we need to hijack
10037 ;; some standard editing functions
10038 (org-remap orgtbl-mode-map
10039 'self-insert-command 'orgtbl-self-insert-command
10040 'delete-char 'orgtbl-delete-char
10041 'delete-backward-char 'orgtbl-delete-backward-char)
10042 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10043 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10044 '("OrgTbl"
10045 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10046 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10047 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10048 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10049 "--"
10050 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10051 ["Copy Field from Above"
10052 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10053 "--"
10054 ("Column"
10055 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10056 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10057 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10058 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10059 ("Row"
10060 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10061 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10062 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10063 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10064 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10065 "--"
10066 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10067 ("Rectangle"
10068 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10069 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10070 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10071 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10072 "--"
10073 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10074 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10075 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10076 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10077 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10078 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10079 ["Sum Column/Rectangle" org-table-sum
10080 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10081 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10082 ["Debug Formulas"
10083 (setq org-table-formula-debug (not org-table-formula-debug))
10084 :style toggle :selected org-table-formula-debug]
10085 ))
10086 t)
10087
10088 (defun orgtbl-tab ()
10089 "Justification and field motion for `orgtbl-mode'."
10090 (interactive)
10091 (org-table-justify-field-maybe)
10092 (org-table-next-field))
10093
10094 (defun orgtbl-ret ()
10095 "Justification and field motion for `orgtbl-mode'."
10096 (interactive)
10097 (org-table-justify-field-maybe)
10098 (org-table-next-row))
10099
10100 (defun orgtbl-self-insert-command (N)
10101 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10102 If the cursor is in a table looking at whitespace, the whitespace is
10103 overwritten, and the table is not marked as requiring realignment."
10104 (interactive "p")
10105 (if (and (org-at-table-p)
10106 (or
10107 (and org-table-auto-blank-field
10108 (member last-command
10109 '(orgtbl-hijacker-command-100
10110 orgtbl-hijacker-command-101
10111 orgtbl-hijacker-command-102
10112 orgtbl-hijacker-command-103
10113 orgtbl-hijacker-command-104
10114 orgtbl-hijacker-command-105))
10115 (org-table-blank-field))
10116 t)
10117 (eq N 1)
10118 (looking-at "[^|\n]* +|"))
10119 (let (org-table-may-need-update)
10120 (goto-char (1- (match-end 0)))
10121 (delete-backward-char 1)
10122 (goto-char (match-beginning 0))
10123 (self-insert-command N))
10124 (setq org-table-may-need-update t)
10125 (let (orgtbl-mode)
10126 (call-interactively (key-binding (vector last-input-event))))))
10127
10128 (defun org-force-self-insert (N)
10129 "Needed to enforce self-insert under remapping."
10130 (interactive "p")
10131 (self-insert-command N))
10132
10133 (defun orgtbl-delete-backward-char (N)
10134 "Like `delete-backward-char', insert whitespace at field end in tables.
10135 When deleting backwards, in tables this function will insert whitespace in
10136 front of the next \"|\" separator, to keep the table aligned. The table will
10137 still be marked for re-alignment, because a narrow field may lead to a
10138 reduced column width."
10139 (interactive "p")
10140 (if (and (org-at-table-p)
10141 (eq N 1)
10142 (string-match "|" (buffer-substring (point-at-bol) (point)))
10143 (looking-at ".*?|"))
10144 (let ((pos (point)))
10145 (backward-delete-char N)
10146 (skip-chars-forward "^|")
10147 (insert " ")
10148 (goto-char (1- pos)))
10149 (delete-backward-char N)))
10150
10151 (defun orgtbl-delete-char (N)
10152 "Like `delete-char', but insert whitespace at field end in tables.
10153 When deleting characters, in tables this function will insert whitespace in
10154 front of the next \"|\" separator, to keep the table aligned. The table
10155 will still be marked for re-alignment, because a narrow field may lead to
10156 a reduced column width."
10157 (interactive "p")
10158 (if (and (org-at-table-p)
10159 (not (bolp))
10160 (not (= (char-after) ?|))
10161 (eq N 1))
10162 (if (looking-at ".*?|")
10163 (let ((pos (point)))
10164 (replace-match (concat
10165 (substring (match-string 0) 1 -1)
10166 " |"))
10167 (goto-char pos)))
10168 (delete-char N)))
10169
10170 ;;; Exporting
10171
10172 (defconst org-level-max 20)
10173
10174 (defun org-export-find-first-heading-line (list)
10175 "Remove all lines from LIST which are before the first headline."
10176 (let ((orig-list list)
10177 (re (concat "^" outline-regexp)))
10178 (while (and list
10179 (not (string-match re (car list))))
10180 (pop list))
10181 (or list orig-list)))
10182
10183 (defun org-skip-comments (lines)
10184 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10185 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10186 (re2 "^\\(\\*+\\)[ \t\n\r]")
10187 rtn line level)
10188 (while (setq line (pop lines))
10189 (cond
10190 ((and (string-match re1 line)
10191 (setq level (- (match-end 1) (match-beginning 1))))
10192 ;; Beginning of a COMMENT subtree. Skip it.
10193 (while (and (setq line (pop lines))
10194 (or (not (string-match re2 line))
10195 (> (- (match-end 1) (match-beginning 1)) level))))
10196 (setq lines (cons line lines)))
10197 ((string-match "^#" line)
10198 ;; an ordinary comment line
10199 )
10200 ((and org-export-table-remove-special-lines
10201 (string-match "^[ \t]*| *[!_^] *|" line))
10202 ;; a special table line that should be removed
10203 )
10204 (t (setq rtn (cons line rtn)))))
10205 (nreverse rtn)))
10206
10207 ;; ASCII
10208
10209 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10210 "Characters for underlining headings in ASCII export.")
10211
10212 (defconst org-html-entities
10213 '(("nbsp")
10214 ("iexcl")
10215 ("cent")
10216 ("pound")
10217 ("curren")
10218 ("yen")
10219 ("brvbar")
10220 ("sect")
10221 ("uml")
10222 ("copy")
10223 ("ordf")
10224 ("laquo")
10225 ("not")
10226 ("shy")
10227 ("reg")
10228 ("macr")
10229 ("deg")
10230 ("plusmn")
10231 ("sup2")
10232 ("sup3")
10233 ("acute")
10234 ("micro")
10235 ("para")
10236 ("middot")
10237 ("odot"."o")
10238 ("star"."*")
10239 ("cedil")
10240 ("sup1")
10241 ("ordm")
10242 ("raquo")
10243 ("frac14")
10244 ("frac12")
10245 ("frac34")
10246 ("iquest")
10247 ("Agrave")
10248 ("Aacute")
10249 ("Acirc")
10250 ("Atilde")
10251 ("Auml")
10252 ("Aring") ("AA"."&Aring;")
10253 ("AElig")
10254 ("Ccedil")
10255 ("Egrave")
10256 ("Eacute")
10257 ("Ecirc")
10258 ("Euml")
10259 ("Igrave")
10260 ("Iacute")
10261 ("Icirc")
10262 ("Iuml")
10263 ("ETH")
10264 ("Ntilde")
10265 ("Ograve")
10266 ("Oacute")
10267 ("Ocirc")
10268 ("Otilde")
10269 ("Ouml")
10270 ("times")
10271 ("Oslash")
10272 ("Ugrave")
10273 ("Uacute")
10274 ("Ucirc")
10275 ("Uuml")
10276 ("Yacute")
10277 ("THORN")
10278 ("szlig")
10279 ("agrave")
10280 ("aacute")
10281 ("acirc")
10282 ("atilde")
10283 ("auml")
10284 ("aring")
10285 ("aelig")
10286 ("ccedil")
10287 ("egrave")
10288 ("eacute")
10289 ("ecirc")
10290 ("euml")
10291 ("igrave")
10292 ("iacute")
10293 ("icirc")
10294 ("iuml")
10295 ("eth")
10296 ("ntilde")
10297 ("ograve")
10298 ("oacute")
10299 ("ocirc")
10300 ("otilde")
10301 ("ouml")
10302 ("divide")
10303 ("oslash")
10304 ("ugrave")
10305 ("uacute")
10306 ("ucirc")
10307 ("uuml")
10308 ("yacute")
10309 ("thorn")
10310 ("yuml")
10311 ("fnof")
10312 ("Alpha")
10313 ("Beta")
10314 ("Gamma")
10315 ("Delta")
10316 ("Epsilon")
10317 ("Zeta")
10318 ("Eta")
10319 ("Theta")
10320 ("Iota")
10321 ("Kappa")
10322 ("Lambda")
10323 ("Mu")
10324 ("Nu")
10325 ("Xi")
10326 ("Omicron")
10327 ("Pi")
10328 ("Rho")
10329 ("Sigma")
10330 ("Tau")
10331 ("Upsilon")
10332 ("Phi")
10333 ("Chi")
10334 ("Psi")
10335 ("Omega")
10336 ("alpha")
10337 ("beta")
10338 ("gamma")
10339 ("delta")
10340 ("epsilon")
10341 ("varepsilon"."&epsilon;")
10342 ("zeta")
10343 ("eta")
10344 ("theta")
10345 ("iota")
10346 ("kappa")
10347 ("lambda")
10348 ("mu")
10349 ("nu")
10350 ("xi")
10351 ("omicron")
10352 ("pi")
10353 ("rho")
10354 ("sigmaf") ("varsigma"."&sigmaf;")
10355 ("sigma")
10356 ("tau")
10357 ("upsilon")
10358 ("phi")
10359 ("chi")
10360 ("psi")
10361 ("omega")
10362 ("thetasym") ("vartheta"."&thetasym;")
10363 ("upsih")
10364 ("piv")
10365 ("bull") ("bullet"."&bull;")
10366 ("hellip") ("dots"."&hellip;")
10367 ("prime")
10368 ("Prime")
10369 ("oline")
10370 ("frasl")
10371 ("weierp")
10372 ("image")
10373 ("real")
10374 ("trade")
10375 ("alefsym")
10376 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
10377 ("uarr") ("uparrow"."&uarr;")
10378 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
10379 ("darr")("downarrow"."&darr;")
10380 ("harr") ("leftrightarrow"."&harr;")
10381 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
10382 ("lArr") ("Leftarrow"."&lArr;")
10383 ("uArr") ("Uparrow"."&uArr;")
10384 ("rArr") ("Rightarrow"."&rArr;")
10385 ("dArr") ("Downarrow"."&dArr;")
10386 ("hArr") ("Leftrightarrow"."&hArr;")
10387 ("forall")
10388 ("part") ("partial"."&part;")
10389 ("exist") ("exists"."&exist;")
10390 ("empty") ("emptyset"."&empty;")
10391 ("nabla")
10392 ("isin") ("in"."&isin;")
10393 ("notin")
10394 ("ni")
10395 ("prod")
10396 ("sum")
10397 ("minus")
10398 ("lowast") ("ast"."&lowast;")
10399 ("radic")
10400 ("prop") ("proptp"."&prop;")
10401 ("infin") ("infty"."&infin;")
10402 ("ang") ("angle"."&ang;")
10403 ("and") ("vee"."&and;")
10404 ("or") ("wedge"."&or;")
10405 ("cap")
10406 ("cup")
10407 ("int")
10408 ("there4")
10409 ("sim")
10410 ("cong") ("simeq"."&cong;")
10411 ("asymp")("approx"."&asymp;")
10412 ("ne") ("neq"."&ne;")
10413 ("equiv")
10414 ("le")
10415 ("ge")
10416 ("sub") ("subset"."&sub;")
10417 ("sup") ("supset"."&sup;")
10418 ("nsub")
10419 ("sube")
10420 ("supe")
10421 ("oplus")
10422 ("otimes")
10423 ("perp")
10424 ("sdot") ("cdot"."&sdot;")
10425 ("lceil")
10426 ("rceil")
10427 ("lfloor")
10428 ("rfloor")
10429 ("lang")
10430 ("rang")
10431 ("loz") ("Diamond"."&loz;")
10432 ("spades") ("spadesuit"."&spades;")
10433 ("clubs") ("clubsuit"."&clubs;")
10434 ("hearts") ("diamondsuit"."&hearts;")
10435 ("diams") ("diamondsuit"."&diams;")
10436 ("quot")
10437 ("amp")
10438 ("lt")
10439 ("gt")
10440 ("OElig")
10441 ("oelig")
10442 ("Scaron")
10443 ("scaron")
10444 ("Yuml")
10445 ("circ")
10446 ("tilde")
10447 ("ensp")
10448 ("emsp")
10449 ("thinsp")
10450 ("zwnj")
10451 ("zwj")
10452 ("lrm")
10453 ("rlm")
10454 ("ndash")
10455 ("mdash")
10456 ("lsquo")
10457 ("rsquo")
10458 ("sbquo")
10459 ("ldquo")
10460 ("rdquo")
10461 ("bdquo")
10462 ("dagger")
10463 ("Dagger")
10464 ("permil")
10465 ("lsaquo")
10466 ("rsaquo")
10467 ("euro")
10468
10469 ("arccos"."arccos")
10470 ("arcsin"."arcsin")
10471 ("arctan"."arctan")
10472 ("arg"."arg")
10473 ("cos"."cos")
10474 ("cosh"."cosh")
10475 ("cot"."cot")
10476 ("coth"."coth")
10477 ("csc"."csc")
10478 ("deg"."deg")
10479 ("det"."det")
10480 ("dim"."dim")
10481 ("exp"."exp")
10482 ("gcd"."gcd")
10483 ("hom"."hom")
10484 ("inf"."inf")
10485 ("ker"."ker")
10486 ("lg"."lg")
10487 ("lim"."lim")
10488 ("liminf"."liminf")
10489 ("limsup"."limsup")
10490 ("ln"."ln")
10491 ("log"."log")
10492 ("max"."max")
10493 ("min"."min")
10494 ("Pr"."Pr")
10495 ("sec"."sec")
10496 ("sin"."sin")
10497 ("sinh"."sinh")
10498 ("sup"."sup")
10499 ("tan"."tan")
10500 ("tanh"."tanh")
10501 )
10502 "Entities for TeX->HTML translation.
10503 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
10504 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
10505 In that case, \"\\ent\" will be translated to \"&other;\".
10506 The list contains HTML entities for Latin-1, Greek and other symbols.
10507 It is supplemented by a number of commonly used TeX macros with appropriate
10508 translations. There is currently no way for users to extend this.")
10509
10510 (defun org-cleaned-string-for-export (string)
10511 "Cleanup a buffer substring so that links can be created safely."
10512 (interactive)
10513 (let* ((cb (current-buffer))
10514 (re-radio (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)"))
10515 rtn)
10516 (save-excursion
10517 (set-buffer (get-buffer-create " org-mode-tmp"))
10518 (erase-buffer)
10519 (insert string)
10520 (org-mode)
10521 ;; Find targets in comments and move them out of comments,
10522 ;; but mark them as targets that should be invisible
10523 (goto-char (point-min))
10524 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
10525 (replace-match "\\1(INVISIBLE)"))
10526 ;; Find matches for radio targets and turn them into links
10527 (goto-char (point-min))
10528 (while (re-search-forward re-radio nil t)
10529 (replace-match "\\1[[\\2]]"))
10530 ;; Find all links that contain a newline and put them into a single line
10531 (goto-char (point-min))
10532 (while (re-search-forward "\\(\\[\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\]\\)" nil t)
10533 (replace-match "\\1 \\2")
10534 (goto-char (match-beginning 0)))
10535 ;; Remove comments
10536 (goto-char (point-min))
10537 (while (re-search-forward "^#.*\n?" nil t)
10538 (replace-match ""))
10539 (setq rtn (buffer-string)))
10540 (kill-buffer " org-mode-tmp")
10541 rtn))
10542
10543 (defun org-solidify-link-text (s &optional alist)
10544 "Take link text and make a safe target out of it."
10545 (save-match-data
10546 (let* ((rtn
10547 (mapconcat
10548 'identity
10549 (org-split-string s "[ \t\r\n]+") "--"))
10550 (a (assoc rtn alist)))
10551 (or (cdr a) rtn))))
10552
10553 (defun org-convert-to-odd-levels ()
10554 "Convert an org-mode file with all levels allowed to one with odd levels.
10555 This will leave level 1 alone, convert level 2 to level 3, level 3 to
10556 level 5 etc."
10557 (interactive)
10558 (when (yes-or-no-p "Are you sure you want to globally change levels? ")
10559 (let ((org-odd-levels-only nil) n)
10560 (save-excursion
10561 (goto-char (point-min))
10562 (while (re-search-forward "^\\*\\*+" nil t)
10563 (setq n (1- (length (match-string 0))))
10564 (while (>= (setq n (1- n)) 0)
10565 (org-demote))
10566 (end-of-line 1))))))
10567
10568 (defun org-tr-level (n)
10569 "Make N odd if required."
10570 (if org-odd-levels-only (1+ (/ n 2)) n))
10571
10572 (defvar org-last-level nil) ; dynamically scoped variable
10573
10574 (defun org-export-as-ascii (arg)
10575 "Export the outline as a pretty ASCII file.
10576 If there is an active region, export only the region.
10577 The prefix ARG specifies how many levels of the outline should become
10578 underlined headlines. The default is 3."
10579 (interactive "P")
10580 (setq-default org-todo-line-regexp org-todo-line-regexp)
10581 (let* ((region
10582 (buffer-substring
10583 (if (org-region-active-p) (region-beginning) (point-min))
10584 (if (org-region-active-p) (region-end) (point-max))))
10585 (lines (org-export-find-first-heading-line
10586 (org-skip-comments
10587 (org-split-string
10588 (org-cleaned-string-for-export region)
10589 "[\r\n]"))))
10590 (org-startup-with-deadline-check nil)
10591 (level 0) line txt
10592 (umax nil)
10593 (case-fold-search nil)
10594 (filename (concat (file-name-sans-extension (buffer-file-name))
10595 ".txt"))
10596 (buffer (find-file-noselect filename))
10597 (levels-open (make-vector org-level-max nil))
10598 (date (format-time-string "%Y/%m/%d" (current-time)))
10599 (time (format-time-string "%X" (current-time)))
10600 (author user-full-name)
10601 (title (buffer-name))
10602 (options nil)
10603 (email user-mail-address)
10604 (language org-export-default-language)
10605 (text nil)
10606 (todo nil)
10607 (lang-words nil))
10608
10609 (setq org-last-level 1)
10610 (org-init-section-numbers)
10611
10612 (find-file-noselect filename)
10613
10614 ;; Search for the export key lines
10615 (org-parse-key-lines)
10616
10617 (setq lang-words (or (assoc language org-export-language-setup)
10618 (assoc "en" org-export-language-setup)))
10619 (if org-export-ascii-show-new-buffer
10620 (switch-to-buffer-other-window buffer)
10621 (set-buffer buffer))
10622 (erase-buffer)
10623 (fundamental-mode)
10624 (if options (org-parse-export-options options))
10625 (setq umax (if arg (prefix-numeric-value arg)
10626 org-export-headline-levels))
10627
10628 ;; File header
10629 (if title (org-insert-centered title ?=))
10630 (insert "\n")
10631 (if (or author email)
10632 (insert (concat (nth 1 lang-words) ": " (or author "")
10633 (if email (concat " <" email ">") "")
10634 "\n")))
10635 (if (and date time)
10636 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10637 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10638
10639 (insert "\n\n")
10640
10641 (if org-export-with-toc
10642 (progn
10643 (insert (nth 3 lang-words) "\n"
10644 (make-string (length (nth 3 lang-words)) ?=) "\n")
10645 (mapcar '(lambda (line)
10646 (if (string-match org-todo-line-regexp
10647 line)
10648 ;; This is a headline
10649 (progn
10650 (setq level (- (match-end 1) (match-beginning 1))
10651 level (org-tr-level level)
10652 txt (match-string 3 line)
10653 todo
10654 (or (and (match-beginning 2)
10655 (not (equal (match-string 2 line)
10656 org-done-string)))
10657 ; TODO, not DONE
10658 (and (= level umax)
10659 (org-search-todo-below
10660 line lines level))))
10661 (setq txt (org-html-expand-for-ascii txt))
10662
10663 (if org-export-with-section-numbers
10664 (setq txt (concat (org-section-number level)
10665 " " txt)))
10666 (if (<= level umax)
10667 (progn
10668 (insert
10669 (make-string (* (1- level) 4) ?\ )
10670 (format (if todo "%s (*)\n" "%s\n") txt))
10671 (setq org-last-level level))
10672 ))))
10673 lines)))
10674
10675 (org-init-section-numbers)
10676 (while (setq line (pop lines))
10677 ;; Remove the quoted HTML tags.
10678 (setq line (org-html-expand-for-ascii line))
10679 ;; Remove targets
10680 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
10681 (setq line (replace-match "" t t line)))
10682 ;; Replace internal links
10683 (while (string-match org-bracket-link-regexp line)
10684 (setq line (replace-match
10685 (if (match-end 3) "[\\3]" "[\\1]")
10686 t nil line)))
10687 (cond
10688 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10689 ;; a Headline
10690 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
10691 txt (match-string 2 line))
10692 (org-ascii-level-start level txt umax))
10693 (t (insert line "\n"))))
10694 (normal-mode)
10695 (save-buffer)
10696 (goto-char (point-min))))
10697
10698 (defun org-search-todo-below (line lines level)
10699 "Search the subtree below LINE for any TODO entries."
10700 (let ((rest (cdr (memq line lines)))
10701 (re org-todo-line-regexp)
10702 line lv todo)
10703 (catch 'exit
10704 (while (setq line (pop rest))
10705 (if (string-match re line)
10706 (progn
10707 (setq lv (- (match-end 1) (match-beginning 1))
10708 todo (and (match-beginning 2)
10709 (not (equal (match-string 2 line)
10710 org-done-string))))
10711 ; TODO, not DONE
10712 (if (<= lv level) (throw 'exit nil))
10713 (if todo (throw 'exit t))))))))
10714
10715 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10716 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10717 (defun org-html-expand-for-ascii (line)
10718 "Handle quoted HTML for ASCII export."
10719 (if org-export-html-expand
10720 (while (string-match "@<[^<>\n]*>" line)
10721 ;; We just remove the tags for now.
10722 (setq line (replace-match "" nil nil line))))
10723 line)
10724
10725 (defun org-insert-centered (s &optional underline)
10726 "Insert the string S centered and underline it with character UNDERLINE."
10727 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
10728 (insert (make-string ind ?\ ) s "\n")
10729 (if underline
10730 (insert (make-string ind ?\ )
10731 (make-string (length s) underline)
10732 "\n"))))
10733
10734 (defun org-ascii-level-start (level title umax)
10735 "Insert a new level in ASCII export."
10736 (let (char)
10737 (if (> level umax)
10738 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10739 (if (or (not (equal (char-before) ?\n))
10740 (not (equal (char-before (1- (point))) ?\n)))
10741 (insert "\n"))
10742 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10743 (if org-export-with-section-numbers
10744 (setq title (concat (org-section-number level) " " title)))
10745 (insert title "\n" (make-string (string-width title) char) "\n"))))
10746
10747 (defun org-export-copy-visible ()
10748 "Copy the visible part of the buffer to another buffer, for printing.
10749 Also removes the first line of the buffer if it specifies a mode,
10750 and all options lines."
10751 (interactive)
10752 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
10753 ".txt"))
10754 (buffer (find-file-noselect filename))
10755 (ore (concat
10756 (org-make-options-regexp
10757 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10758 "STARTUP" "ARCHIVE"
10759 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10760 (if org-noutline-p "\\(\n\\|$\\)" "")))
10761 s e)
10762 (with-current-buffer buffer
10763 (erase-buffer)
10764 (text-mode))
10765 (save-excursion
10766 (setq s (goto-char (point-min)))
10767 (while (not (= (point) (point-max)))
10768 (goto-char (org-find-invisible))
10769 (append-to-buffer buffer s (point))
10770 (setq s (goto-char (org-find-visible)))))
10771 (switch-to-buffer-other-window buffer)
10772 (newline)
10773 (goto-char (point-min))
10774 (if (looking-at ".*-\\*- mode:.*\n")
10775 (replace-match ""))
10776 (while (re-search-forward ore nil t)
10777 (replace-match ""))
10778 (goto-char (point-min))))
10779
10780 (defun org-find-visible ()
10781 (if (featurep 'noutline)
10782 (let ((s (point)))
10783 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10784 (get-char-property s 'invisible)))
10785 s)
10786 (skip-chars-forward "^\n")
10787 (point)))
10788 (defun org-find-invisible ()
10789 (if (featurep 'noutline)
10790 (let ((s (point)))
10791 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10792 (not (get-char-property s 'invisible))))
10793 s)
10794 (skip-chars-forward "^\r")
10795 (point)))
10796
10797 ;; HTML
10798
10799 (defun org-get-current-options ()
10800 "Return a string with current options as keyword options.
10801 Does include HTML export options as well as TODO and CATEGORY stuff."
10802 (format
10803 "#+TITLE: %s
10804 #+AUTHOR: %s
10805 #+EMAIL: %s
10806 #+LANGUAGE: %s
10807 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10808 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10809 #+CATEGORY: %s
10810 #+SEQ_TODO: %s
10811 #+TYP_TODO: %s
10812 #+STARTUP: %s %s
10813 #+ARCHIVE: %s
10814 "
10815 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10816 org-export-headline-levels
10817 org-export-with-section-numbers
10818 org-export-with-toc
10819 org-export-preserve-breaks
10820 org-export-html-expand
10821 org-export-with-fixed-width
10822 org-export-with-tables
10823 org-export-with-sub-superscripts
10824 org-export-with-emphasize
10825 org-export-with-TeX-macros
10826 (file-name-nondirectory (buffer-file-name))
10827 (if (equal org-todo-interpretation 'sequence)
10828 (mapconcat 'identity org-todo-keywords " ")
10829 "TODO FEEDBACK VERIFY DONE")
10830 (if (equal org-todo-interpretation 'type)
10831 (mapconcat 'identity org-todo-keywords " ")
10832 "Me Jason Marie DONE")
10833 (cdr (assoc org-startup-folded
10834 '((nil . "nofold")(t . "fold")(content . "content"))))
10835 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10836 org-archive-location
10837 ))
10838
10839 (defun org-insert-export-options-template ()
10840 "Insert into the buffer a template with information for exporting."
10841 (interactive)
10842 (if (not (bolp)) (newline))
10843 (let ((s (org-get-current-options)))
10844 (and (string-match "#\\+CATEGORY" s)
10845 (setq s (substring s 0 (match-beginning 0))))
10846 (insert s)))
10847
10848 (defun org-toggle-fixed-width-section (arg)
10849 "Toggle the fixed-width export.
10850 If there is no active region, the QUOTE keyword at the current headline is
10851 inserted or removed. When present, it causes the text between this headline
10852 and the next to be exported as fixed-width text, and unmodified.
10853 If there is an active region, this command adds or removes a colon as the
10854 first character of this line. If the first character of a line is a colon,
10855 this line is also exported in fixed-width font."
10856 (interactive "P")
10857 (let* ((cc 0)
10858 (regionp (org-region-active-p))
10859 (beg (if regionp (region-beginning) (point)))
10860 (end (if regionp (region-end)))
10861 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10862 (re "[ \t]*\\(:\\)")
10863 off)
10864 (if regionp
10865 (save-excursion
10866 (goto-char beg)
10867 (setq cc (current-column))
10868 (beginning-of-line 1)
10869 (setq off (looking-at re))
10870 (while (> nlines 0)
10871 (setq nlines (1- nlines))
10872 (beginning-of-line 1)
10873 (cond
10874 (arg
10875 (move-to-column cc t)
10876 (insert ":\n")
10877 (forward-line -1))
10878 ((and off (looking-at re))
10879 (replace-match "" t t nil 1))
10880 ((not off) (move-to-column cc t) (insert ":")))
10881 (forward-line 1)))
10882 (save-excursion
10883 (org-back-to-heading)
10884 (if (looking-at (concat outline-regexp
10885 "\\( +\\<" org-quote-string "\\>\\)"))
10886 (replace-match "" t t nil 1)
10887 (if (looking-at outline-regexp)
10888 (progn
10889 (goto-char (match-end 0))
10890 (insert " " org-quote-string))))))))
10891
10892 (defun org-export-as-html-and-open (arg)
10893 "Export the outline as HTML and immediately open it with a browser.
10894 If there is an active region, export only the region.
10895 The prefix ARG specifies how many levels of the outline should become
10896 headlines. The default is 3. Lower levels will become bulleted lists."
10897 (interactive "P")
10898 (org-export-as-html arg 'hidden)
10899 (org-open-file (buffer-file-name)))
10900
10901 (defun org-export-as-html-batch ()
10902 "Call `org-export-as-html', may be used in batch processing as
10903 emacs --batch
10904 --load=$HOME/lib/emacs/org.el
10905 --eval \"(setq org-export-headline-levels 2)\"
10906 --visit=MyFile --funcall org-export-as-html-batch"
10907 (org-export-as-html org-export-headline-levels 'hidden))
10908
10909 (defun org-export-as-html (arg &optional hidden)
10910 "Export the outline as a pretty HTML file.
10911 If there is an active region, export only the region.
10912 The prefix ARG specifies how many levels of the outline should become
10913 headlines. The default is 3. Lower levels will become bulleted lists."
10914 (interactive "P")
10915 (setq-default org-todo-line-regexp org-todo-line-regexp)
10916 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
10917 (setq-default org-done-string org-done-string)
10918 (let* ((style org-export-html-style)
10919 (region-p (org-region-active-p))
10920 (region
10921 (buffer-substring
10922 (if region-p (region-beginning) (point-min))
10923 (if region-p (region-end) (point-max))))
10924 (all_lines
10925 (org-skip-comments (org-split-string
10926 (org-cleaned-string-for-export region)
10927 "[\r\n]")))
10928 (lines (org-export-find-first-heading-line all_lines))
10929 (level 0) (line "") (origline "") txt todo
10930 (umax nil)
10931 (filename (concat (file-name-sans-extension (buffer-file-name))
10932 ".html"))
10933 (buffer (find-file-noselect filename))
10934 (levels-open (make-vector org-level-max nil))
10935 (date (format-time-string "%Y/%m/%d" (current-time)))
10936 (time (format-time-string "%X" (current-time)))
10937 (author user-full-name)
10938 (title (buffer-name))
10939 (options nil)
10940 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
10941 (inquote nil)
10942 (infixed nil)
10943 (in-local-list nil)
10944 (local-list-num nil)
10945 (local-list-indent nil)
10946 (llt org-plain-list-ordered-item-terminator)
10947 (email user-mail-address)
10948 (language org-export-default-language)
10949 (text nil)
10950 (lang-words nil)
10951 (target-alist nil) tg
10952 (head-count 0) cnt
10953 (start 0)
10954 ;; FIXME: The following returns always nil under XEmacs
10955 (coding-system (and (fboundp 'coding-system-get)
10956 (boundp 'buffer-file-coding-system)
10957 buffer-file-coding-system))
10958 (coding-system-for-write (or coding-system coding-system-for-write))
10959 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
10960 (charset (and coding-system
10961 (coding-system-get coding-system 'mime-charset)))
10962 table-open type
10963 table-buffer table-orig-buffer
10964 ind start-is-num starter
10965 )
10966 (message "Exporting...")
10967
10968 (setq org-last-level 1)
10969 (org-init-section-numbers)
10970
10971 ;; Search for the export key lines
10972 (org-parse-key-lines)
10973 (setq lang-words (or (assoc language org-export-language-setup)
10974 (assoc "en" org-export-language-setup)))
10975
10976 ;; Switch to the output buffer
10977 (if (or hidden (not org-export-html-show-new-buffer))
10978 (set-buffer buffer)
10979 (switch-to-buffer-other-window buffer))
10980 (erase-buffer)
10981 (fundamental-mode)
10982 (let ((case-fold-search nil))
10983 (if options (org-parse-export-options options))
10984 (setq umax (if arg (prefix-numeric-value arg)
10985 org-export-headline-levels))
10986
10987 ;; File header
10988 (insert (format
10989 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
10990 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
10991 <html lang=\"%s\"><head>
10992 <title>%s</title>
10993 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
10994 <meta name=generator content=\"Org-mode\">
10995 <meta name=generated content=\"%s %s\">
10996 <meta name=author content=\"%s\">
10997 %s
10998 </head><body>
10999 "
11000 language (org-html-expand title) (or charset "iso-8859-1")
11001 date time author style))
11002 (if title (insert (concat "<H1 class=\"title\">"
11003 (org-html-expand title) "</H1>\n")))
11004 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11005 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11006 email "&gt;</a>\n")))
11007 (if (or author email) (insert "<br>\n"))
11008 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11009 date " " time "<br>\n")))
11010 (if text (insert (concat "<p>\n" (org-html-expand text))))
11011 (if org-export-with-toc
11012 (progn
11013 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11014 (insert "<ul>\n")
11015 (setq lines
11016 (mapcar '(lambda (line)
11017 (if (string-match org-todo-line-regexp line)
11018 ;; This is a headline
11019 (progn
11020 (setq level (- (match-end 1) (match-beginning 1))
11021 level (org-tr-level level)
11022 txt (save-match-data
11023 (org-html-expand
11024 (match-string 3 line)))
11025 todo
11026 (or (and (match-beginning 2)
11027 (not (equal (match-string 2 line)
11028 org-done-string)))
11029 ; TODO, not DONE
11030 (and (= level umax)
11031 (org-search-todo-below
11032 line lines level))))
11033 (if org-export-with-section-numbers
11034 (setq txt (concat (org-section-number level)
11035 " " txt)))
11036 (if (<= level umax)
11037 (progn
11038 (setq head-count (+ head-count 1))
11039 (if (> level org-last-level)
11040 (progn
11041 (setq cnt (- level org-last-level))
11042 (while (>= (setq cnt (1- cnt)) 0)
11043 (insert "<ul>"))
11044 (insert "\n")))
11045 (if (< level org-last-level)
11046 (progn
11047 (setq cnt (- org-last-level level))
11048 (while (>= (setq cnt (1- cnt)) 0)
11049 (insert "</ul>"))
11050 (insert "\n")))
11051 ;; Check for targets
11052 (while (string-match org-target-regexp line)
11053 (setq tg (match-string 1 line)
11054 line (replace-match
11055 (concat "@<span class=\"target\">" tg "@</span> ")
11056 t t line))
11057 (push (cons (org-solidify-link-text tg)
11058 (format "sec-%d" head-count))
11059 target-alist))
11060 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11061 (setq txt (replace-match "" t t txt)))
11062 (insert
11063 (format
11064 (if todo
11065 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11066 "<li><a href=\"#sec-%d\">%s</a>\n")
11067 head-count txt))
11068
11069 (setq org-last-level level))
11070 )))
11071 line)
11072 lines))
11073 (while (> org-last-level 0)
11074 (setq org-last-level (1- org-last-level))
11075 (insert "</ul>\n"))
11076 ))
11077 (setq head-count 0)
11078 (org-init-section-numbers)
11079
11080 (while (setq line (pop lines) origline line)
11081 (catch 'nextline
11082
11083 ;; end of quote section?
11084 (when (and inquote (string-match "^\\*+" line))
11085 (insert "</pre>\n")
11086 (setq inquote nil))
11087 ;; inside a quote section?
11088 (when inquote
11089 (insert (org-html-protect line) "\n")
11090 (throw 'nextline nil))
11091
11092 ;; verbatim lines
11093 (when (and org-export-with-fixed-width
11094 (string-match "^[ \t]*:\\(.*\\)" line))
11095 (when (not infixed)
11096 (setq infixed t)
11097 (insert "<pre>\n"))
11098 (insert (org-html-protect (match-string 1 line)) "\n")
11099 (when (and lines
11100 (not (string-match "^[ \t]*\\(:.*\\)"
11101 (car lines))))
11102 (setq infixed nil)
11103 (insert "</pre>\n"))
11104 (throw 'nextline nil))
11105
11106
11107 ;; make targets to anchors
11108 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11109 (cond
11110 ((match-end 2)
11111 (setq line (replace-match
11112 (concat "@<a name=\""
11113 (org-solidify-link-text (match-string 1 line))
11114 "\">\\nbsp@</a>")
11115 t t line)))
11116 ((and org-export-with-toc (equal (string-to-char line) ?*))
11117 (setq line (replace-match
11118 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11119 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11120 t t line)))
11121 (t
11122 (setq line (replace-match
11123 (concat "@<a name=\""
11124 (org-solidify-link-text (match-string 1 line))
11125 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11126 t t line)))))
11127 ;; Replace internal links
11128 (while (string-match org-bracket-link-regexp line)
11129 (setq line (replace-match
11130 (concat
11131 "@<a href=\"#"
11132 (org-solidify-link-text (match-string 1 line) target-alist)
11133 "\">"
11134 (match-string (if (match-end 3) 3 1) line)
11135 "@</a>")
11136 t t line)))
11137
11138 ;; Protect the external links
11139 (setq start 0)
11140 (while (string-match org-link-maybe-angles-regexp line start)
11141 (setq start (match-end 0))
11142 (setq line (replace-match
11143 (concat "\000" (match-string 1 line) "\000")
11144 t t line)))
11145
11146 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11147 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11148 (setq line (org-html-expand line))
11149
11150 ;; Format the links
11151 (setq start 0)
11152 (while (string-match org-protected-link-regexp line start)
11153 (setq start (- (match-end 0) 2))
11154 (setq type (match-string 1 line))
11155 (cond
11156 ((member type '("http" "https" "ftp" "mailto" "news"))
11157 ;; standard URL
11158 (setq line (replace-match
11159 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
11160 "<a href=\"\\1:\\2\">\\1:\\2</a>"
11161 nil nil line)))
11162 ((string= type "file")
11163 ;; FILE link
11164 (let* ((filename (match-string 2 line))
11165 (abs-p (file-name-absolute-p filename))
11166 (thefile (if abs-p (expand-file-name filename) filename))
11167 (thefile (save-match-data
11168 (if (string-match ":[0-9]+$" thefile)
11169 (replace-match "" t t thefile)
11170 thefile)))
11171 (file-is-image-p
11172 (save-match-data
11173 (string-match (org-image-file-name-regexp) thefile))))
11174 (setq line (replace-match
11175 (if (and org-export-html-inline-images
11176 file-is-image-p)
11177 (concat "<img src=\"" thefile "\"/>")
11178 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
11179 nil nil line))))
11180
11181 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11182 (setq line (replace-match
11183 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
11184
11185 ;; TODO items
11186 (if (and (string-match org-todo-line-regexp line)
11187 (match-beginning 2))
11188 (if (equal (match-string 2 line) org-done-string)
11189 (setq line (replace-match
11190 "<span class=\"done\">\\2</span>"
11191 nil nil line 2))
11192 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11193 nil nil line 2))))
11194
11195 ;; DEADLINES
11196 (if (string-match org-deadline-line-regexp line)
11197 (progn
11198 (if (save-match-data
11199 (string-match "<a href"
11200 (substring line 0 (match-beginning 0))))
11201 nil ; Don't do the replacement - it is inside a link
11202 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11203 nil nil line 1)))))
11204 (cond
11205 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11206 ;; This is a headline
11207 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11208 txt (match-string 2 line))
11209 (if (<= level umax) (setq head-count (+ head-count 1)))
11210 (when in-local-list
11211 ;; Close any local lists before inserting a new header line
11212 (while local-list-num
11213 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11214 (pop local-list-num))
11215 (setq local-list-indent nil
11216 in-local-list nil))
11217 (org-html-level-start level txt umax
11218 (and org-export-with-toc (<= level umax))
11219 head-count)
11220 ;; QUOTES
11221 (when (string-match quote-re line)
11222 (insert "<pre>")
11223 (setq inquote t)))
11224
11225 ((and org-export-with-tables
11226 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11227 (if (not table-open)
11228 ;; New table starts
11229 (setq table-open t table-buffer nil table-orig-buffer nil))
11230 ;; Accumulate lines
11231 (setq table-buffer (cons line table-buffer)
11232 table-orig-buffer (cons origline table-orig-buffer))
11233 (when (or (not lines)
11234 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11235 (car lines))))
11236 (setq table-open nil
11237 table-buffer (nreverse table-buffer)
11238 table-orig-buffer (nreverse table-orig-buffer))
11239 (insert (org-format-table-html table-buffer table-orig-buffer))))
11240 (t
11241 ;; Normal lines
11242 (when (and (> org-export-plain-list-max-depth 0)
11243 (string-match
11244 (cond
11245 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11246 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11247 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11248 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11249 line))
11250 (setq ind (org-get-string-indentation line)
11251 start-is-num (match-beginning 4)
11252 starter (if (match-beginning 2) (match-string 2 line))
11253 line (substring line (match-beginning 5)))
11254 (unless (string-match "[^ \t]" line)
11255 ;; empty line. Pretend indentation is large.
11256 (setq ind (1+ (or (car local-list-indent) 1))))
11257 (while (and in-local-list
11258 (or (and (= ind (car local-list-indent))
11259 (not starter))
11260 (< ind (car local-list-indent))))
11261 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11262 (pop local-list-num) (pop local-list-indent)
11263 (setq in-local-list local-list-indent))
11264 (cond
11265 ((and starter
11266 (or (not in-local-list)
11267 (> ind (car local-list-indent)))
11268 (< (length local-list-indent)
11269 org-export-plain-list-max-depth))
11270 ;; Start new (level of ) list
11271 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11272 (push start-is-num local-list-num)
11273 (push ind local-list-indent)
11274 (setq in-local-list t))
11275 (starter
11276 ;; continue current list
11277 (insert "<li>\n"))))
11278 ;; Empty lines start a new paragraph. If hand-formatted lists
11279 ;; are not fully interpreted, lines starting with "-", "+", "*"
11280 ;; also start a new paragraph.
11281 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11282 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11283 ))
11284 (if org-export-html-with-timestamp
11285 (insert org-export-html-html-helper-timestamp))
11286 (insert "</body>\n</html>\n")
11287 (normal-mode)
11288 (save-buffer)
11289 (goto-char (point-min)))))
11290
11291 (defun org-format-table-html (lines olines)
11292 "Find out which HTML converter to use and return the HTML code."
11293 (if (string-match "^[ \t]*|" (car lines))
11294 ;; A normal org table
11295 (org-format-org-table-html lines)
11296 ;; Table made by table.el - test for spanning
11297 (let* ((hlines (delq nil (mapcar
11298 (lambda (x)
11299 (if (string-match "^[ \t]*\\+-" x) x
11300 nil))
11301 lines)))
11302 (first (car hlines))
11303 (ll (and (string-match "\\S-+" first)
11304 (match-string 0 first)))
11305 (re (concat "^[ \t]*" (regexp-quote ll)))
11306 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
11307 hlines))))
11308 (if (and (not spanning)
11309 (not org-export-prefer-native-exporter-for-tables))
11310 ;; We can use my own converter with HTML conversions
11311 (org-format-table-table-html lines)
11312 ;; Need to use the code generator in table.el, with the original text.
11313 (org-format-table-table-html-using-table-generate-source olines)))))
11314
11315 (defun org-format-org-table-html (lines)
11316 "Format a table into HTML."
11317 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11318 (setq lines (nreverse lines))
11319 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11320 (setq lines (nreverse lines))
11321 (when org-export-table-remove-special-lines
11322 ;; Check if the table has a marking column. If yes remove the
11323 ;; column and the special lines
11324 (let* ((special
11325 (not
11326 (memq nil
11327 (mapcar
11328 (lambda (x)
11329 (or (string-match "^[ \t]*|-" x)
11330 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
11331 lines)))))
11332 (if special
11333 (setq lines
11334 (delq nil
11335 (mapcar
11336 (lambda (x)
11337 (if (string-match "^[ \t]*| *[!_^] *|" x)
11338 nil ; ignore this line
11339 (and (or (string-match "^[ \t]*|-+\\+" x)
11340 (string-match "^[ \t]*|[^|]*|" x))
11341 (replace-match "|" t t x))))
11342 lines))))))
11343
11344 (let ((head (and org-export-highlight-first-table-line
11345 (delq nil (mapcar
11346 (lambda (x) (string-match "^[ \t]*|-" x))
11347 (cdr lines)))))
11348 line fields html)
11349 (setq html (concat org-export-html-table-tag "\n"))
11350 (while (setq line (pop lines))
11351 (catch 'next-line
11352 (if (string-match "^[ \t]*|-" line)
11353 (progn
11354 (setq head nil) ;; head ends here, first time around
11355 ;; ignore this line
11356 (throw 'next-line t)))
11357 ;; Break the line into fields
11358 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11359 (setq html (concat
11360 html
11361 "<tr>"
11362 (mapconcat (lambda (x)
11363 (if head
11364 (concat "<th>" x "</th>")
11365 (concat "<td>" x "</td>")))
11366 fields "")
11367 "</tr>\n"))))
11368 (setq html (concat html "</table>\n"))
11369 html))
11370
11371 (defun org-fake-empty-table-line (line)
11372 "Replace everything except \"|\" with spaces."
11373 (let ((i (length line))
11374 (newstr (copy-sequence line)))
11375 (while (> i 0)
11376 (setq i (1- i))
11377 (if (not (eq (aref newstr i) ?|))
11378 (aset newstr i ?\ )))
11379 newstr))
11380
11381 (defun org-format-table-table-html (lines)
11382 "Format a table generated by table.el into HTML.
11383 This conversion does *not* use `table-generate-source' from table.el.
11384 This has the advantage that Org-mode's HTML conversions can be used.
11385 But it has the disadvantage, that no cell- or row-spanning is allowed."
11386 (let (line field-buffer
11387 (head org-export-highlight-first-table-line)
11388 fields html empty)
11389 (setq html (concat org-export-html-table-tag "\n"))
11390 (while (setq line (pop lines))
11391 (setq empty "&nbsp")
11392 (catch 'next-line
11393 (if (string-match "^[ \t]*\\+-" line)
11394 (progn
11395 (if field-buffer
11396 (progn
11397 (setq html (concat
11398 html
11399 "<tr>"
11400 (mapconcat
11401 (lambda (x)
11402 (if (equal x "") (setq x empty))
11403 (if head
11404 (concat "<th>" x "</th>\n")
11405 (concat "<td>" x "</td>\n")))
11406 field-buffer "\n")
11407 "</tr>\n"))
11408 (setq head nil)
11409 (setq field-buffer nil)))
11410 ;; Ignore this line
11411 (throw 'next-line t)))
11412 ;; Break the line into fields and store the fields
11413 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11414 (if field-buffer
11415 (setq field-buffer (mapcar
11416 (lambda (x)
11417 (concat x "<br>" (pop fields)))
11418 field-buffer))
11419 (setq field-buffer fields))))
11420 (setq html (concat html "</table>\n"))
11421 html))
11422
11423 (defun org-format-table-table-html-using-table-generate-source (lines)
11424 "Format a table into html, using `table-generate-source' from table.el.
11425 This has the advantage that cell- or row-spanning is allowed.
11426 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
11427 (require 'table)
11428 (with-current-buffer (get-buffer-create " org-tmp1 ")
11429 (erase-buffer)
11430 (insert (mapconcat 'identity lines "\n"))
11431 (goto-char (point-min))
11432 (if (not (re-search-forward "|[^+]" nil t))
11433 (error "Error processing table"))
11434 (table-recognize-table)
11435 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
11436 (table-generate-source 'html " org-tmp2 ")
11437 (set-buffer " org-tmp2 ")
11438 (buffer-substring (point-min) (point-max))))
11439
11440 (defun org-html-protect (s)
11441 ;; convert & to &amp;, < to &lt; and > to &gt;
11442 (let ((start 0))
11443 (while (string-match "&" s start)
11444 (setq s (replace-match "&amp;" t t s)
11445 start (1+ (match-beginning 0))))
11446 (while (string-match "<" s)
11447 (setq s (replace-match "&lt;" t t s)))
11448 (while (string-match ">" s)
11449 (setq s (replace-match "&gt;" t t s))))
11450 s)
11451
11452 (defun org-html-expand (string)
11453 "Prepare STRING for HTML export. Applies all active conversions."
11454 ;; First check if there is a link in the line - if yes, apply conversions
11455 ;; only before the start of the link.
11456 ;; FIXME: This is no longer correct, because links now have an end.
11457 (let* ((m (string-match org-link-regexp string))
11458 (s (if m (substring string 0 m) string))
11459 (r (if m (substring string m) "")))
11460 ;; convert & to &amp;, < to &lt; and > to &gt;
11461 (setq s (org-html-protect s))
11462 (if org-export-html-expand
11463 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
11464 (setq s (replace-match "<\\1>" nil nil s))))
11465 (if org-export-with-emphasize
11466 (setq s (org-export-html-convert-emphasize s)))
11467 (if org-export-with-sub-superscripts
11468 (setq s (org-export-html-convert-sub-super s)))
11469 (if org-export-with-TeX-macros
11470 (let ((start 0) wd ass)
11471 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
11472 (setq wd (match-string 1 s))
11473 (if (setq ass (assoc wd org-html-entities))
11474 (setq s (replace-match (or (cdr ass)
11475 (concat "&" (car ass) ";"))
11476 t t s))
11477 (setq start (+ start (length wd)))))))
11478 (concat s r)))
11479
11480 (defun org-create-multibrace-regexp (left right n)
11481 "Create a regular expression which will match a balanced sexp.
11482 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
11483 as single character strings.
11484 The regexp returned will match the entire expression including the
11485 delimiters. It will also define a single group which contains the
11486 match except for the outermost delimiters. The maximum depth of
11487 stacked delimiters is N. Escaping delimiters is not possible."
11488 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
11489 (or "\\|")
11490 (re nothing)
11491 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
11492 (while (> n 1)
11493 (setq n (1- n)
11494 re (concat re or next)
11495 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
11496 (concat left "\\(" re "\\)" right)))
11497
11498 (defvar org-match-substring-regexp
11499 (concat
11500 "\\([^\\]\\)\\([_^]\\)\\("
11501 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
11502 "\\|"
11503 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
11504 "\\|"
11505 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
11506 "The regular expression matching a sub- or superscript.")
11507
11508 (defun org-export-html-convert-sub-super (string)
11509 "Convert sub- and superscripts in STRING to HTML."
11510 (let (key c)
11511 (while (string-match org-match-substring-regexp string)
11512 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
11513 (setq c (or (match-string 8 string)
11514 (match-string 6 string)
11515 (match-string 5 string)))
11516 (setq string (replace-match
11517 (concat (match-string 1 string)
11518 "<" key ">" c "</" key ">")
11519 t t string)))
11520 (while (string-match "\\\\\\([_^]\\)" string)
11521 (setq string (replace-match (match-string 1 string) t t string))))
11522 string)
11523
11524 (defun org-export-html-convert-emphasize (string)
11525 (while (string-match
11526 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
11527 string)
11528 (setq string (replace-match
11529 (concat "<b>" (match-string 3 string) "</b>")
11530 t t string 2)))
11531 (while (string-match
11532 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
11533 string)
11534 (setq string (replace-match
11535 (concat "<i>" (match-string 3 string) "</i>")
11536 t t string 2)))
11537 (while (string-match
11538 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
11539 string)
11540 (setq string (replace-match
11541 (concat "<u>" (match-string 3 string) "</u>")
11542 t t string 2)))
11543 string)
11544
11545 (defun org-parse-key-lines ()
11546 "Find the special key lines with the information for exporters."
11547 (save-excursion
11548 (goto-char 0)
11549 (let ((re (org-make-options-regexp
11550 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
11551 key)
11552 (while (re-search-forward re nil t)
11553 (setq key (match-string 1))
11554 (cond ((string-equal key "TITLE")
11555 (setq title (match-string 2)))
11556 ((string-equal key "AUTHOR")
11557 (setq author (match-string 2)))
11558 ((string-equal key "EMAIL")
11559 (setq email (match-string 2)))
11560 ((string-equal key "LANGUAGE")
11561 (setq language (match-string 2)))
11562 ((string-equal key "TEXT")
11563 (setq text (concat text "\n" (match-string 2))))
11564 ((string-equal key "OPTIONS")
11565 (setq options (match-string 2))))))))
11566
11567 (defun org-parse-export-options (s)
11568 "Parse the export options line."
11569 (let ((op '(("H" . org-export-headline-levels)
11570 ("num" . org-export-with-section-numbers)
11571 ("toc" . org-export-with-toc)
11572 ("\\n" . org-export-preserve-breaks)
11573 ("@" . org-export-html-expand)
11574 (":" . org-export-with-fixed-width)
11575 ("|" . org-export-with-tables)
11576 ("^" . org-export-with-sub-superscripts)
11577 ("*" . org-export-with-emphasize)
11578 ("TeX" . org-export-with-TeX-macros)))
11579 o)
11580 (while (setq o (pop op))
11581 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
11582 s)
11583 (set (make-local-variable (cdr o))
11584 (car (read-from-string (match-string 1 s))))))))
11585
11586 (defun org-html-level-start (level title umax with-toc head-count)
11587 "Insert a new level in HTML export."
11588 (let ((l (1+ (max level umax))))
11589 (while (<= l org-level-max)
11590 (if (aref levels-open (1- l))
11591 (progn
11592 (org-html-level-close l)
11593 (aset levels-open (1- l) nil)))
11594 (setq l (1+ l)))
11595 (if (> level umax)
11596 (progn
11597 (if (aref levels-open (1- level))
11598 (insert "<li>" title "<p>\n")
11599 (aset levels-open (1- level) t)
11600 (insert "<ul><li>" title "<p>\n")))
11601 (if org-export-with-section-numbers
11602 (setq title (concat (org-section-number level) " " title)))
11603 (setq level (+ level 1))
11604 (if with-toc
11605 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
11606 level head-count title level))
11607 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
11608
11609 (defun org-html-level-close (&rest args)
11610 "Terminate one level in HTML export."
11611 (insert "</ul>"))
11612
11613 ;; Variable holding the vector with section numbers
11614 (defvar org-section-numbers (make-vector org-level-max 0))
11615
11616 (defun org-init-section-numbers ()
11617 "Initialize the vector for the section numbers."
11618 (let* ((level -1)
11619 (numbers (nreverse (org-split-string "" "\\.")))
11620 (depth (1- (length org-section-numbers)))
11621 (i depth) number-string)
11622 (while (>= i 0)
11623 (if (> i level)
11624 (aset org-section-numbers i 0)
11625 (setq number-string (or (car numbers) "0"))
11626 (if (string-match "\\`[A-Z]\\'" number-string)
11627 (aset org-section-numbers i
11628 (- (string-to-char number-string) ?A -1))
11629 (aset org-section-numbers i (string-to-number number-string)))
11630 (pop numbers))
11631 (setq i (1- i)))))
11632
11633 (defun org-section-number (&optional level)
11634 "Return a string with the current section number.
11635 When LEVEL is non-nil, increase section numbers on that level."
11636 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
11637 (when level
11638 (when (> level -1)
11639 (aset org-section-numbers
11640 level (1+ (aref org-section-numbers level))))
11641 (setq idx (1+ level))
11642 (while (<= idx depth)
11643 (if (not (= idx 1))
11644 (aset org-section-numbers idx 0))
11645 (setq idx (1+ idx))))
11646 (setq idx 0)
11647 (while (<= idx depth)
11648 (setq n (aref org-section-numbers idx))
11649 (setq string (concat string (if (not (string= string "")) "." "")
11650 (int-to-string n)))
11651 (setq idx (1+ idx)))
11652 (save-match-data
11653 (if (string-match "\\`\\([@0]\\.\\)+" string)
11654 (setq string (replace-match "" nil nil string)))
11655 (if (string-match "\\(\\.0\\)+\\'" string)
11656 (setq string (replace-match "" nil nil string))))
11657 string))
11658
11659
11660 (defun org-export-icalendar-this-file ()
11661 "Export current file as an iCalendar file.
11662 The iCalendar file will be located in the same directory as the Org-mode
11663 file, but with extension `.ics'."
11664 (interactive)
11665 (org-export-icalendar nil (buffer-file-name)))
11666
11667 ;;;###autoload
11668 (defun org-export-icalendar-all-agenda-files ()
11669 "Export all files in `org-agenda-files' to iCalendar .ics files.
11670 Each iCalendar file will be located in the same directory as the Org-mode
11671 file, but with extension `.ics'."
11672 (interactive)
11673 (apply 'org-export-icalendar nil org-agenda-files))
11674
11675 ;;;###autoload
11676 (defun org-export-icalendar-combine-agenda-files ()
11677 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11678 The file is stored under the name `org-combined-agenda-icalendar-file'."
11679 (interactive)
11680 (apply 'org-export-icalendar t org-agenda-files))
11681
11682 (defun org-export-icalendar (combine &rest files)
11683 "Create iCalendar files for all elements of FILES.
11684 If COMBINE is non-nil, combine all calendar entries into a single large
11685 file and store it under the name `org-combined-agenda-icalendar-file'."
11686 (save-excursion
11687 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11688 (when combine
11689 (setq ical-file org-combined-agenda-icalendar-file
11690 ical-buffer (org-get-agenda-file-buffer ical-file))
11691 (set-buffer ical-buffer) (erase-buffer))
11692 (while (setq file (pop files))
11693 (catch 'nextfile
11694 (org-check-agenda-file file)
11695 (unless combine
11696 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11697 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11698 (set-buffer ical-buffer) (erase-buffer))
11699 (set-buffer (org-get-agenda-file-buffer file))
11700 (setq category (or org-category
11701 (file-name-sans-extension
11702 (file-name-nondirectory (buffer-file-name)))))
11703 (if (symbolp category) (setq category (symbol-name category)))
11704 (let ((standard-output ical-buffer))
11705 (if combine
11706 (and (not started) (setq started t)
11707 (org-start-icalendar-file org-icalendar-combined-name))
11708 (org-start-icalendar-file category))
11709 (org-print-icalendar-entries combine category)
11710 (when (or (and combine (not files)) (not combine))
11711 (org-finish-icalendar-file)
11712 (set-buffer ical-buffer)
11713 (save-buffer)
11714 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11715 (org-release-buffers org-agenda-new-buffers))))
11716
11717 (defvar org-after-save-iCalendar-file-hook nil
11718 "Hook run after an iCalendar file has been saved.
11719 The iCalendar buffer is still current when this hook is run.
11720 A good way to use this is to tell a desktop calenndar application to re-read
11721 the iCalendar file.")
11722
11723 (defun org-print-icalendar-entries (&optional combine category)
11724 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11725 When COMBINE is non nil, add the category to each line."
11726 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11727 (dts (org-ical-ts-to-string
11728 (format-time-string (cdr org-time-stamp-formats) (current-time))
11729 "DTSTART"))
11730 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11731 (save-excursion
11732 (goto-char (point-min))
11733 (while (re-search-forward org-ts-regexp nil t)
11734 (setq pos (match-beginning 0)
11735 ts (match-string 0)
11736 inc t
11737 hd (org-get-heading))
11738 (if (looking-at re2)
11739 (progn
11740 (goto-char (match-end 0))
11741 (setq ts2 (match-string 1) inc nil))
11742 (setq ts2 ts
11743 tmp (buffer-substring (max (point-min)
11744 (- pos org-ds-keyword-length))
11745 pos)
11746 deadlinep (string-match org-deadline-regexp tmp)
11747 scheduledp (string-match org-scheduled-regexp tmp)
11748 ;; donep (org-entry-is-done-p)
11749 ))
11750 (if (or (string-match org-tr-regexp hd)
11751 (string-match org-ts-regexp hd))
11752 (setq hd (replace-match "" t t hd)))
11753 (if combine
11754 (setq hd (concat hd " (category " category ")")))
11755 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11756 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11757 (princ (format "BEGIN:VEVENT
11758 %s
11759 %s
11760 SUMMARY:%s
11761 END:VEVENT\n"
11762 (org-ical-ts-to-string ts "DTSTART")
11763 (org-ical-ts-to-string ts2 "DTEND" inc)
11764 hd)))
11765 (when org-icalendar-include-todo
11766 (goto-char (point-min))
11767 (while (re-search-forward org-todo-line-regexp nil t)
11768 (setq state (match-string 1))
11769 (unless (equal state org-done-string)
11770 (setq hd (match-string 3))
11771 (if (string-match org-priority-regexp hd)
11772 (setq pri (string-to-char (match-string 2 hd))
11773 hd (concat (substring hd 0 (match-beginning 1))
11774 (substring hd (- (match-end 1)))))
11775 (setq pri org-default-priority))
11776 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11777 (- org-lowest-priority ?A))))))
11778
11779 (princ (format "BEGIN:VTODO
11780 %s
11781 SUMMARY:%s
11782 SEQUENCE:1
11783 PRIORITY:%d
11784 END:VTODO\n"
11785 dts hd pri))))))))
11786
11787 (defun org-start-icalendar-file (name)
11788 "Start an iCalendar file by inserting the header."
11789 (let ((user user-full-name)
11790 (name (or name "unknown"))
11791 (timezone (cadr (current-time-zone))))
11792 (princ
11793 (format "BEGIN:VCALENDAR
11794 VERSION:2.0
11795 X-WR-CALNAME:%s
11796 PRODID:-//%s//Emacs with Org-mode//EN
11797 X-WR-TIMEZONE:%s
11798 CALSCALE:GREGORIAN\n" name user timezone))))
11799
11800 (defun org-finish-icalendar-file ()
11801 "Finish an iCalendar file by inserting the END statement."
11802 (princ "END:VCALENDAR\n"))
11803
11804 (defun org-ical-ts-to-string (s keyword &optional inc)
11805 "Take a time string S and convert it to iCalendar format.
11806 KEYWORD is added in front, to make a complete line like DTSTART....
11807 When INC is non-nil, increase the hour by two (if time string contains
11808 a time), or the day by one (if it does not contain a time)."
11809 (let ((t1 (org-parse-time-string s 'nodefault))
11810 t2 fmt have-time time)
11811 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11812 (setq t2 t1 have-time t)
11813 (setq t2 (org-parse-time-string s)))
11814 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11815 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11816 (when inc
11817 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11818 (setq time (encode-time s mi h d m y)))
11819 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11820 (concat keyword (format-time-string fmt time))))
11821
11822
11823 ;;; Key bindings
11824
11825 ;; - Bindings in Org-mode map are currently
11826 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11827 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
11828 ;; e (?) useful from outline-mode
11829 ;; i k @ expendable from outline-mode
11830 ;; 0123456789 % & ()_{} " ` free
11831
11832 ;; Make `C-c C-x' a prefix key
11833 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11834
11835 ;; TAB key with modifiers
11836 (define-key org-mode-map "\C-i" 'org-cycle)
11837 (define-key org-mode-map [(meta tab)] 'org-complete)
11838 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11839 ;; The following line is necessary under Suse GNU/Linux
11840 (unless org-xemacs-p
11841 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11842 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11843
11844 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11845 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11846 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11847 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11848 (define-key org-mode-map [(meta return)] 'org-meta-return)
11849 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11850 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11851
11852 ;; Cursor keys with modifiers
11853 (define-key org-mode-map [(meta left)] 'org-metaleft)
11854 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11855 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11856 (define-key org-mode-map [(meta right)] 'org-metaright)
11857 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11858 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11859 (define-key org-mode-map [(meta up)] 'org-metaup)
11860 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11861 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11862 (define-key org-mode-map [(meta down)] 'org-metadown)
11863 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11864 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11865
11866 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11867 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11868 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11869 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11870 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11871 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11872 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11873 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11874 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11875 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11876 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11877 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11878 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11879 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11880 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11881 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11882
11883 ;; All the other keys
11884 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11885 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11886 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11887 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11888 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11889 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11890 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11891 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11892 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11893 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11894 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11895 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11896 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11897 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11898 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
11899 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
11900 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11901 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11902 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11903 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11904 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11905 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11906 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11907 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11908 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
11909 (define-key org-mode-map "\C-c]" 'org-remove-file)
11910 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
11911 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
11912 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
11913 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11914 (define-key org-mode-map "\C-m" 'org-return)
11915 (define-key org-mode-map "\C-c?" 'org-table-current-column)
11916 (define-key org-mode-map "\C-c " 'org-table-blank-field)
11917 (define-key org-mode-map "\C-c+" 'org-table-sum)
11918 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
11919 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
11920 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
11921 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
11922 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11923 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
11924 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11925 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
11926 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
11927 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
11928 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
11929 ;; OPML support is only an option for the future
11930 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
11931 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
11932 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
11933 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
11934 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
11935 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11936 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
11937 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11938 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
11939 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
11940 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
11941
11942 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11943 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11944 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11945 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11946
11947 (defsubst org-table-p () (org-at-table-p))
11948
11949 (defun org-self-insert-command (N)
11950 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11951 If the cursor is in a table looking at whitespace, the whitespace is
11952 overwritten, and the table is not marked as requiring realignment."
11953 (interactive "p")
11954 (if (and (org-table-p)
11955 (or
11956 (and org-table-auto-blank-field
11957 (member last-command
11958 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11959 (org-table-blank-field))
11960 t)
11961 (eq N 1)
11962 (looking-at "[^|\n]* +|"))
11963 (let (org-table-may-need-update)
11964 (goto-char (1- (match-end 0)))
11965 (delete-backward-char 1)
11966 (goto-char (match-beginning 0))
11967 (self-insert-command N))
11968 (setq org-table-may-need-update t)
11969 (self-insert-command N)))
11970
11971 ;; FIXME:
11972 ;; The following two functions might still be optimized to trigger
11973 ;; re-alignment less frequently.
11974
11975 (defun org-delete-backward-char (N)
11976 "Like `delete-backward-char', insert whitespace at field end in tables.
11977 When deleting backwards, in tables this function will insert whitespace in
11978 front of the next \"|\" separator, to keep the table aligned. The table will
11979 still be marked for re-alignment, because a narrow field may lead to a
11980 reduced column width."
11981 (interactive "p")
11982 (if (and (org-table-p)
11983 (eq N 1)
11984 (string-match "|" (buffer-substring (point-at-bol) (point)))
11985 (looking-at ".*?|"))
11986 (let ((pos (point)))
11987 (backward-delete-char N)
11988 (skip-chars-forward "^|")
11989 (insert " ")
11990 (goto-char (1- pos)))
11991 (backward-delete-char N)))
11992
11993 (defun org-delete-char (N)
11994 "Like `delete-char', but insert whitespace at field end in tables.
11995 When deleting characters, in tables this function will insert whitespace in
11996 front of the next \"|\" separator, to keep the table aligned. The table
11997 will still be marked for re-alignment, because a narrow field may lead to
11998 a reduced column width."
11999 (interactive "p")
12000 (if (and (org-table-p)
12001 (not (bolp))
12002 (not (= (char-after) ?|))
12003 (eq N 1))
12004 (if (looking-at ".*?|")
12005 (let ((pos (point)))
12006 (replace-match (concat
12007 (substring (match-string 0) 1 -1)
12008 " |"))
12009 (goto-char pos)))
12010 (delete-char N)))
12011
12012 ;; How to do this: Measure non-white length of current string
12013 ;; If equal to column width, we should realign.
12014
12015 (defun org-remap (map &rest commands)
12016 "In MAP, remap the functions given in COMMANDS.
12017 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12018 (let (new old)
12019 (while commands
12020 (setq old (pop commands) new (pop commands))
12021 (if (fboundp 'command-remapping)
12022 (define-key map (vector 'remap old) new)
12023 (substitute-key-definition old new map global-map)))))
12024
12025 (when (eq org-enable-table-editor 'optimized)
12026 ;; If the user wants maximum table support, we need to hijack
12027 ;; some standard editing functions
12028 (org-remap org-mode-map
12029 'self-insert-command 'org-self-insert-command
12030 'delete-char 'org-delete-char
12031 'delete-backward-char 'org-delete-backward-char)
12032 (define-key org-mode-map "|" 'org-force-self-insert))
12033
12034 (defun org-shiftcursor-error ()
12035 "Throw an error because Shift-Cursor command was applied in wrong context."
12036 (error "This command is active in special context like tables, headlines or timestamps"))
12037
12038 (defun org-shifttab ()
12039 "Global visibility cycling or move to previous table field.
12040 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12041 See the individual commands for more information."
12042 (interactive)
12043 (cond
12044 ((org-at-table-p) (org-table-previous-field))
12045 (t (org-cycle '(4)))))
12046
12047 (defun org-shiftmetaleft ()
12048 "Promote subtree or delete table column.
12049 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12050 See the individual commands for more information."
12051 (interactive)
12052 (cond
12053 ((org-at-table-p) (org-table-delete-column))
12054 ((org-on-heading-p) (org-promote-subtree))
12055 ((org-at-item-p) (call-interactively 'org-outdent-item))
12056 (t (org-shiftcursor-error))))
12057
12058 (defun org-shiftmetaright ()
12059 "Demote subtree or insert table column.
12060 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12061 See the individual commands for more information."
12062 (interactive)
12063 (cond
12064 ((org-at-table-p) (org-table-insert-column))
12065 ((org-on-heading-p) (org-demote-subtree))
12066 ((org-at-item-p) (call-interactively 'org-indent-item))
12067 (t (org-shiftcursor-error))))
12068
12069 (defun org-shiftmetaup (&optional arg)
12070 "Move subtree up or kill table row.
12071 Calls `org-move-subtree-up' or `org-table-kill-row' or
12072 `org-move-item-up' depending on context. See the individual commands
12073 for more information."
12074 (interactive "P")
12075 (cond
12076 ((org-at-table-p) (org-table-kill-row))
12077 ((org-on-heading-p) (org-move-subtree-up arg))
12078 ((org-at-item-p) (org-move-item-up arg))
12079 (t (org-shiftcursor-error))))
12080 (defun org-shiftmetadown (&optional arg)
12081 "Move subtree down or insert table row.
12082 Calls `org-move-subtree-down' or `org-table-insert-row' or
12083 `org-move-item-down', depending on context. See the individual
12084 commands for more information."
12085 (interactive "P")
12086 (cond
12087 ((org-at-table-p) (org-table-insert-row arg))
12088 ((org-on-heading-p) (org-move-subtree-down arg))
12089 ((org-at-item-p) (org-move-item-down arg))
12090 (t (org-shiftcursor-error))))
12091
12092 (defun org-metaleft (&optional arg)
12093 "Promote heading or move table column to left.
12094 Calls `org-do-promote' or `org-table-move-column', depending on context.
12095 With no specific context, calls the Emacs default `backward-word'.
12096 See the individual commands for more information."
12097 (interactive "P")
12098 (cond
12099 ((org-at-table-p) (org-table-move-column 'left))
12100 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12101 (t (backward-word (prefix-numeric-value arg)))))
12102
12103 (defun org-metaright (&optional arg)
12104 "Demote subtree or move table column to right.
12105 Calls `org-do-demote' or `org-table-move-column', depending on context.
12106 With no specific context, calls the Emacs default `forward-word'.
12107 See the individual commands for more information."
12108 (interactive "P")
12109 (cond
12110 ((org-at-table-p) (org-table-move-column nil))
12111 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12112 (t (forward-word (prefix-numeric-value arg)))))
12113
12114 (defun org-metaup (&optional arg)
12115 "Move subtree up or move table row up.
12116 Calls `org-move-subtree-up' or `org-table-move-row' or
12117 `org-move-item-up', depending on context. See the individual commands
12118 for more information."
12119 (interactive "P")
12120 (cond
12121 ((org-at-table-p) (org-table-move-row 'up))
12122 ((org-on-heading-p) (org-move-subtree-up arg))
12123 ((org-at-item-p) (org-move-item-up arg))
12124 (t (org-shiftcursor-error))))
12125
12126 (defun org-metadown (&optional arg)
12127 "Move subtree down or move table row down.
12128 Calls `org-move-subtree-down' or `org-table-move-row' or
12129 `org-move-item-down', depending on context. See the individual
12130 commands for more information."
12131 (interactive "P")
12132 (cond
12133 ((org-at-table-p) (org-table-move-row nil))
12134 ((org-on-heading-p) (org-move-subtree-down arg))
12135 ((org-at-item-p) (org-move-item-down arg))
12136 (t (org-shiftcursor-error))))
12137
12138 (defun org-shiftup (&optional arg)
12139 "Increase item in timestamp or increase priority of current item.
12140 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12141 See the individual commands for more information."
12142 (interactive "P")
12143 (cond
12144 ((org-at-timestamp-p) (org-timestamp-up arg))
12145 (t (org-priority-up))))
12146
12147 (defun org-shiftdown (&optional arg)
12148 "Decrease item in timestamp or decrease priority of current item.
12149 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12150 See the individual commands for more information."
12151 (interactive "P")
12152 (cond
12153 ((org-at-timestamp-p) (org-timestamp-down arg))
12154 (t (org-priority-down))))
12155
12156 (defun org-shiftright ()
12157 "Next TODO keyword or timestamp one day later, depending on context."
12158 (interactive)
12159 (cond
12160 ((org-at-timestamp-p) (org-timestamp-up-day))
12161 ((org-on-heading-p) (org-todo 'right))
12162 (t (org-shiftcursor-error))))
12163
12164 (defun org-shiftleft ()
12165 "Previous TODO keyword or timestamp one day earlier, depending on context."
12166 (interactive)
12167 (cond
12168 ((org-at-timestamp-p) (org-timestamp-down-day))
12169 ((org-on-heading-p) (org-todo 'left))
12170 (t (org-shiftcursor-error))))
12171
12172 (defun org-copy-special ()
12173 "Copy region in table or copy current subtree.
12174 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12175 See the individual commands for more information."
12176 (interactive)
12177 (call-interactively
12178 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12179
12180 (defun org-cut-special ()
12181 "Cut region in table or cut current subtree.
12182 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12183 See the individual commands for more information."
12184 (interactive)
12185 (call-interactively
12186 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12187
12188 (defun org-paste-special (arg)
12189 "Paste rectangular region into table, or past subtree relative to level.
12190 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12191 See the individual commands for more information."
12192 (interactive "P")
12193 (if (org-at-table-p)
12194 (org-table-paste-rectangle)
12195 (org-paste-subtree arg)))
12196
12197 (defun org-ctrl-c-ctrl-c (&optional arg)
12198 "Call realign table, or recognize a table.el table, or update keywords.
12199 When the cursor is inside a table created by the table.el package,
12200 activate that table. Otherwise, if the cursor is at a normal table
12201 created with org.el, re-align that table. This command works even if
12202 the automatic table editor has been turned off.
12203
12204 If the cursor is in a headline, prompt for tags and insert them into
12205 the current line, aligned to `org-tags-column'. When in a headline and
12206 called with prefix arg, realign all tags in the current buffer.
12207
12208 If the cursor is in one of the special #+KEYWORD lines, this triggers
12209 scanning the buffer for these lines and updating the information.
12210 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
12211 (interactive "P")
12212 (let ((org-enable-table-editor t))
12213 (cond
12214 ((org-on-target-p) (org-update-radio-target-regexp))
12215 ((org-on-heading-p) (org-set-tags arg))
12216 ((org-at-table.el-p)
12217 (require 'table)
12218 (beginning-of-line 1)
12219 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12220 (table-recognize-table))
12221 ((org-at-table-p)
12222 (org-table-maybe-eval-formula)
12223 (if arg
12224 (org-table-recalculate t)
12225 (org-table-maybe-recalculate-line))
12226 (org-table-align))
12227 ((org-at-item-p)
12228 (org-renumber-ordered-list (prefix-numeric-value arg)))
12229 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12230 (cond
12231 ((equal (match-string 1) "TBLFM")
12232 ;; Recalculate the table before this line
12233 (save-excursion
12234 (beginning-of-line 1)
12235 (skip-chars-backward " \r\n\t")
12236 (if (org-at-table-p) (org-table-recalculate t))))
12237 (t
12238 (org-mode-restart))))
12239 ((org-region-active-p)
12240 (org-table-convert-region (region-beginning) (region-end) arg))
12241 ((condition-case nil
12242 (and (region-beginning) (region-end))
12243 (error nil))
12244 (if (y-or-n-p "Convert inactive region to table? ")
12245 (org-table-convert-region (region-beginning) (region-end) arg)
12246 (error "Abort")))
12247 (t (error "C-c C-c can do nothing useful at this location.")))))
12248
12249 (defun org-mode-restart ()
12250 "Restart Org-mode, to scan again for special lines.
12251 Also updates the keyword regular expressions."
12252 (interactive)
12253 (let ((org-inhibit-startup t)) (org-mode))
12254 (message "Org-mode restarted to refresh keyword and special line setup"))
12255
12256 (defun org-return ()
12257 "Goto next table row or insert a newline.
12258 Calls `org-table-next-row' or `newline', depending on context.
12259 See the individual commands for more information."
12260 (interactive)
12261 (cond
12262 ((org-at-table-p)
12263 (org-table-justify-field-maybe)
12264 (org-table-next-row))
12265 (t (newline))))
12266
12267 (defun org-meta-return (&optional arg)
12268 "Insert a new heading or wrap a region in a table.
12269 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12270 See the individual commands for more information."
12271 (interactive "P")
12272 (cond
12273 ((org-at-table-p)
12274 (org-table-wrap-region arg))
12275 (t (org-insert-heading arg))))
12276
12277 ;;; Menu entries
12278
12279 ;; Define the Org-mode menus
12280 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12281 '("Tbl"
12282 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
12283 ["Next Field" org-cycle (org-at-table-p)]
12284 ["Previous Field" org-shifttab (org-at-table-p)]
12285 ["Next Row" org-return (org-at-table-p)]
12286 "--"
12287 ["Blank Field" org-table-blank-field (org-at-table-p)]
12288 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12289 "--"
12290 ("Column"
12291 ["Move Column Left" org-metaleft (org-at-table-p)]
12292 ["Move Column Right" org-metaright (org-at-table-p)]
12293 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12294 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12295 ("Row"
12296 ["Move Row Up" org-metaup (org-at-table-p)]
12297 ["Move Row Down" org-metadown (org-at-table-p)]
12298 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12299 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12300 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12301 "--"
12302 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
12303 ("Rectangle"
12304 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12305 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12306 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12307 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12308 "--"
12309 ("Calculate"
12310 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12311 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12312 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12313 "--"
12314 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12315 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12316 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12317 "--"
12318 ["Sum Column/Rectangle" org-table-sum
12319 (or (org-at-table-p) (org-region-active-p))]
12320 ["Which Column?" org-table-current-column (org-at-table-p)])
12321 ["Debug Formulas"
12322 (setq org-table-formula-debug (not org-table-formula-debug))
12323 :style toggle :selected org-table-formula-debug]
12324 "--"
12325 ["Invisible Vlines" org-table-toggle-vline-visibility
12326 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
12327 "--"
12328 ["Create" org-table-create (and (not (org-at-table-p))
12329 org-enable-table-editor)]
12330 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
12331 ["Import from File" org-table-import (not (org-at-table-p))]
12332 ["Export to File" org-table-export (org-at-table-p)]
12333 "--"
12334 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12335
12336 (easy-menu-define org-org-menu org-mode-map "Org menu"
12337 '("Org"
12338 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
12339 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
12340 ["Sparse Tree" org-occur t]
12341 ["Show All" show-all t]
12342 "--"
12343 ["New Heading" org-insert-heading t]
12344 ("Navigate Headings"
12345 ["Up" outline-up-heading t]
12346 ["Next" outline-next-visible-heading t]
12347 ["Previous" outline-previous-visible-heading t]
12348 ["Next Same Level" outline-forward-same-level t]
12349 ["Previous Same Level" outline-backward-same-level t]
12350 "--"
12351 ["Jump" org-goto t])
12352 ("Edit Structure"
12353 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12354 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12355 "--"
12356 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12357 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12358 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12359 "--"
12360 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12361 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12362 ["Demote Heading" org-metaright (not (org-at-table-p))]
12363 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12364 "--"
12365 ["Archive Subtree" org-archive-subtree t]
12366 "--"
12367 ["Convert file to odd levels" org-convert-to-odd-levels t])
12368 "--"
12369 ("TODO Lists"
12370 ["TODO/DONE/-" org-todo t]
12371 ["Show TODO Tree" org-show-todo-tree t]
12372 ["Global TODO list" org-todo-list t]
12373 "--"
12374 ["Set Priority" org-priority t]
12375 ["Priority Up" org-shiftup t]
12376 ["Priority Down" org-shiftdown t])
12377 ("Dates and Scheduling"
12378 ["Timestamp" org-time-stamp t]
12379 ["Timestamp (inactive)" org-time-stamp-inactive t]
12380 ("Change Date"
12381 ["1 Day Later" org-timestamp-up-day t]
12382 ["1 Day Earlier" org-timestamp-down-day t]
12383 ["1 ... Later" org-shiftup t]
12384 ["1 ... Earlier" org-shiftdown t])
12385 ["Compute Time Range" org-evaluate-time-range t]
12386 ["Schedule Item" org-schedule t]
12387 ["Deadline" org-deadline t]
12388 "--"
12389 ["Goto Calendar" org-goto-calendar t]
12390 ["Date from Calendar" org-date-from-calendar t])
12391 "--"
12392 ["Agenda Command" org-agenda t]
12393 ("File List for Agenda")
12394 ("Special views current file"
12395 ["TODO Tree" org-show-todo-tree t]
12396 ["Check Deadlines" org-check-deadlines t]
12397 ["Timeline" org-timeline t]
12398 ["Tags Tree" org-tags-sparse-tree t])
12399 "--"
12400 ("Hyperlinks"
12401 ["Store Link (Global)" org-store-link t]
12402 ["Insert Link" org-insert-link t]
12403 ["Follow Link" org-open-at-point t])
12404 "--"
12405 ("Export"
12406 ["ASCII" org-export-as-ascii t]
12407 ["Extract Visible Text" org-export-copy-visible t]
12408 ["HTML" org-export-as-html t]
12409 ["HTML and Open" org-export-as-html-and-open t]
12410 ; ["OPML" org-export-as-opml nil]
12411 "--"
12412 ["iCalendar this file" org-export-icalendar-this-file t]
12413 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
12414 :active t :keys "C-c C-x C-i"]
12415 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
12416 "--"
12417 ["Option Template" org-insert-export-options-template t]
12418 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
12419 "--"
12420 ("Documentation"
12421 ["Show Version" org-version t]
12422 ["Info Documentation" org-info t])
12423 ("Customize"
12424 ["Browse Org Group" org-customize t]
12425 "--"
12426 ["Build Full Customize Menu" org-create-customize-menu
12427 (fboundp 'customize-menu-create)])
12428 "--"
12429 ["Refresh setup" org-mode-restart t]
12430 ))
12431
12432 (defun org-info (&optional node)
12433 "Read documentation for Org-mode in the info system.
12434 With optional NODE, go directly to that node."
12435 (interactive)
12436 (require 'info)
12437 (Info-goto-node (format "(org)%s" (or node ""))))
12438
12439 (defun org-install-agenda-files-menu ()
12440 (easy-menu-change
12441 '("Org") "File List for Agenda"
12442 (append
12443 (list
12444 ["Edit File List" (customize-variable 'org-agenda-files) t]
12445 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12446 ["Remove Current File from List" org-remove-file t]
12447 ["Cycle through agenda files" org-cycle-agenda-files t]
12448 "--")
12449 (mapcar 'org-file-menu-entry org-agenda-files))))
12450
12451 ;;; Documentation
12452
12453 (defun org-customize ()
12454 "Call the customize function with org as argument."
12455 (interactive)
12456 (customize-browse 'org))
12457
12458 (defun org-create-customize-menu ()
12459 "Create a full customization menu for Org-mode, insert it into the menu."
12460 (interactive)
12461 (if (fboundp 'customize-menu-create)
12462 (progn
12463 (easy-menu-change
12464 '("Org") "Customize"
12465 `(["Browse Org group" org-customize t]
12466 "--"
12467 ,(customize-menu-create 'org)
12468 ["Set" Custom-set t]
12469 ["Save" Custom-save t]
12470 ["Reset to Current" Custom-reset-current t]
12471 ["Reset to Saved" Custom-reset-saved t]
12472 ["Reset to Standard Settings" Custom-reset-standard t]))
12473 (message "\"Org\"-menu now contains full customization menu"))
12474 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12475
12476 ;;; Miscellaneous stuff
12477
12478 (defun org-move-line-down (arg)
12479 "Move the current line down. With prefix argument, move it past ARG lines."
12480 (interactive "p")
12481 (let ((col (current-column))
12482 beg end pos)
12483 (beginning-of-line 1) (setq beg (point))
12484 (beginning-of-line 2) (setq end (point))
12485 (beginning-of-line (+ 1 arg))
12486 (setq pos (move-marker (make-marker) (point)))
12487 (insert (delete-and-extract-region beg end))
12488 (goto-char pos)
12489 (move-to-column col)))
12490
12491 (defun org-move-line-up (arg)
12492 "Move the current line up. With prefix argument, move it past ARG lines."
12493 (interactive "p")
12494 (let ((col (current-column))
12495 beg end pos)
12496 (beginning-of-line 1) (setq beg (point))
12497 (beginning-of-line 2) (setq end (point))
12498 (beginning-of-line (- arg))
12499 (setq pos (move-marker (make-marker) (point)))
12500 (insert (delete-and-extract-region beg end))
12501 (goto-char pos)
12502 (move-to-column col)))
12503
12504 ;; Paragraph filling stuff.
12505 ;; We want this to be just right, so use the full arsenal.
12506 ;; FIXME: This very likely does not work correctly for XEmacs, because the
12507 ;; filladapt package works slightly differently.
12508
12509 (defun org-set-autofill-regexps ()
12510 (interactive)
12511 ;; In the paragraph separator we include headlines, because filling
12512 ;; text in a line directly attached to a headline would otherwise
12513 ;; fill the headline as well.
12514 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
12515 ;; The paragraph starter includes hand-formatted lists.
12516 (set (make-local-variable 'paragraph-start)
12517 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
12518 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
12519 ;; But only if the user has not turned off tables or fixed-width regions
12520 (set (make-local-variable 'auto-fill-inhibit-regexp)
12521 (concat "\\*\\|#"
12522 (if (or org-enable-table-editor org-enable-fixed-width-editor)
12523 (concat
12524 "\\|[ \t]*["
12525 (if org-enable-table-editor "|" "")
12526 (if org-enable-fixed-width-editor ":" "")
12527 "]"))))
12528 ;; We use our own fill-paragraph function, to make sure that tables
12529 ;; and fixed-width regions are not wrapped. That function will pass
12530 ;; through to `fill-paragraph' when appropriate.
12531 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
12532 ;; Adaptive filling: To get full control, first make sure that
12533 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
12534 (setq adaptive-fill-regexp "\000")
12535 (setq adaptive-fill-function 'org-adaptive-fill-function))
12536
12537 (defun org-fill-paragraph (&optional justify)
12538 "Re-align a table, pass through to fill-paragraph if no table."
12539 (let ((table-p (org-at-table-p))
12540 (table.el-p (org-at-table.el-p)))
12541 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
12542 (table.el-p t) ; skip table.el tables
12543 (table-p (org-table-align) t) ; align org-mode tables
12544 (t nil)))) ; call paragraph-fill
12545
12546 ;; For reference, this is the default value of adaptive-fill-regexp
12547 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
12548
12549 (defun org-adaptive-fill-function ()
12550 "Return a fill prefix for org-mode files.
12551 In particular, this makes sure hanging paragraphs for hand-formatted lists
12552 work correctly."
12553 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
12554 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
12555
12556 ;; Functions needed for Emacs/XEmacs region compatibility
12557
12558 (defun org-add-hook (hook function &optional append local)
12559 "Add-hook, compatible with both Emacsen."
12560 (if (and local org-xemacs-p)
12561 (add-local-hook hook function append)
12562 (add-hook hook function append local)))
12563
12564 (defun org-region-active-p ()
12565 "Is `transient-mark-mode' on and the region active?
12566 Works on both Emacs and XEmacs."
12567 (if org-ignore-region
12568 nil
12569 (if org-xemacs-p
12570 (and zmacs-regions (region-active-p))
12571 (and transient-mark-mode mark-active))))
12572
12573 (defun org-add-to-invisibility-spec (arg)
12574 "Add elements to `buffer-invisibility-spec'.
12575 See documentation for `buffer-invisibility-spec' for the kind of elements
12576 that can be added."
12577 (cond
12578 ((fboundp 'add-to-invisibility-spec)
12579 (add-to-invisibility-spec arg))
12580 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
12581 (setq buffer-invisibility-spec (list arg)))
12582 (t
12583 (setq buffer-invisibility-spec
12584 (cons arg buffer-invisibility-spec)))))
12585
12586 (defun org-remove-from-invisibility-spec (arg)
12587 "Remove elements from `buffer-invisibility-spec'."
12588 (if (fboundp 'remove-from-invisibility-spec)
12589 (remove-from-invisibility-spec arg)
12590 (if (consp buffer-invisibility-spec)
12591 (setq buffer-invisibility-spec
12592 (delete arg buffer-invisibility-spec)))))
12593
12594 (defun org-in-invisibility-spec-p (arg)
12595 "Is ARG a member of `buffer-invisibility-spec'?"
12596 (if (consp buffer-invisibility-spec)
12597 (member arg buffer-invisibility-spec)
12598 nil))
12599
12600 (defun org-image-file-name-regexp ()
12601 "Return regexp matching the file names of images."
12602 (if (fboundp 'image-file-name-regexp)
12603 (image-file-name-regexp)
12604 (let ((image-file-name-extensions
12605 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
12606 "xbm" "xpm" "pbm" "pgm" "ppm")))
12607 (concat "\\."
12608 (regexp-opt (nconc (mapcar 'upcase
12609 image-file-name-extensions)
12610 image-file-name-extensions)
12611 t)
12612 "\\'"))))
12613
12614 ;; Functions needed for compatibility with old outline.el.
12615
12616 ;; Programming for the old outline.el (that uses selective display
12617 ;; instead of `invisible' text properties) is a nightmare, mostly
12618 ;; because regular expressions can no longer be anchored at
12619 ;; beginning/end of line. Therefore a number of function need special
12620 ;; treatment when the old outline.el is being used.
12621
12622 ;; The following functions capture almost the entire compatibility code
12623 ;; between the different versions of outline-mode. The only other
12624 ;; places where this is important are the font-lock-keywords, and in
12625 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
12626
12627 ;; C-a should go to the beginning of a *visible* line, also in the
12628 ;; new outline.el. I guess this should be patched into Emacs?
12629 (defun org-beginning-of-line ()
12630 "Go to the beginning of the current line. If that is invisible, continue
12631 to a visible line beginning. This makes the function of C-a more intuitive."
12632 (interactive)
12633 (beginning-of-line 1)
12634 (if (bobp)
12635 nil
12636 (backward-char 1)
12637 (if (org-invisible-p)
12638 (while (and (not (bobp)) (org-invisible-p))
12639 (backward-char 1)
12640 (beginning-of-line 1))
12641 (forward-char 1))))
12642
12643 (when org-noutline-p
12644 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
12645 ;; FIXME: should I use substitute-key-definition to reach other bindings
12646 ;; of beginning-of-line?
12647
12648 (defun org-invisible-p ()
12649 "Check if point is at a character currently not visible."
12650 (if org-noutline-p
12651 ;; Early versions of noutline don't have `outline-invisible-p'.
12652 (if (fboundp 'outline-invisible-p)
12653 (outline-invisible-p)
12654 (get-char-property (point) 'invisible))
12655 (save-excursion
12656 (skip-chars-backward "^\r\n")
12657 (equal (char-before) ?\r))))
12658
12659 (defun org-invisible-p2 ()
12660 "Check if point is at a character currently not visible."
12661 (save-excursion
12662 (if org-noutline-p
12663 (progn
12664 (if (and (eolp) (not (bobp))) (backward-char 1))
12665 ;; Early versions of noutline don't have `outline-invisible-p'.
12666 (if (fboundp 'outline-invisible-p)
12667 (outline-invisible-p)
12668 (get-char-property (point) 'invisible)))
12669 (skip-chars-backward "^\r\n")
12670 (equal (char-before) ?\r))))
12671
12672 (defun org-back-to-heading (&optional invisible-ok)
12673 "Move to previous heading line, or beg of this line if it's a heading.
12674 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
12675 (if org-noutline-p
12676 (outline-back-to-heading invisible-ok)
12677 (if (and (memq (char-before) '(?\n ?\r))
12678 (looking-at outline-regexp))
12679 t
12680 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
12681 outline-regexp)
12682 nil t)
12683 (if invisible-ok
12684 (progn (goto-char (match-end 1))
12685 (looking-at outline-regexp)))
12686 (error "Before first heading")))))
12687
12688 (defun org-on-heading-p (&optional invisible-ok)
12689 "Return t if point is on a (visible) heading line.
12690 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12691 (if org-noutline-p
12692 (outline-on-heading-p 'invisible-ok)
12693 (save-excursion
12694 (skip-chars-backward "^\n\r")
12695 (and (looking-at outline-regexp)
12696 (or invisible-ok
12697 (bobp)
12698 (equal (char-before) ?\n))))))
12699
12700 (defun org-on-target-p ()
12701 (let ((pos (point)))
12702 (save-excursion
12703 (skip-chars-forward "<")
12704 (and (re-search-backward "<<" nil t)
12705 (or (looking-at org-target-regexp)
12706 (looking-at org-radio-target-regexp))
12707 (<= (match-beginning 0) pos)
12708 (>= (match-end 0) pos)))))
12709
12710 (defun org-up-heading-all (arg)
12711 "Move to the heading line of which the present line is a subheading.
12712 This function considers both visible and invisible heading lines.
12713 With argument, move up ARG levels."
12714 (if org-noutline-p
12715 (if (fboundp 'outline-up-heading-all)
12716 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12717 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12718 (org-back-to-heading t)
12719 (looking-at outline-regexp)
12720 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12721 (error "Cannot move up %d levels" arg)
12722 (re-search-backward
12723 (concat "[\n\r]" (regexp-quote
12724 (make-string (- (match-end 0) (match-beginning 0) arg)
12725 ?*))
12726 "[^*]"))
12727 (forward-char 1))))
12728
12729 (defun org-show-hidden-entry ()
12730 "Show an entry where even the heading is hidden."
12731 (save-excursion
12732 (if (not org-noutline-p)
12733 (progn
12734 (org-back-to-heading t)
12735 (org-flag-heading nil)))
12736 (org-show-entry)))
12737
12738 (defun org-check-occur-regexp (regexp)
12739 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12740 Of course, only for the old outline mode."
12741 (if org-noutline-p
12742 regexp
12743 (if (string-match "^\\^" regexp)
12744 (concat "[\n\r]" (substring regexp 1))
12745 regexp)))
12746
12747 (defun org-flag-heading (flag &optional entry)
12748 "Flag the current heading. FLAG non-nil means make invisible.
12749 When ENTRY is non-nil, show the entire entry."
12750 (save-excursion
12751 (org-back-to-heading t)
12752 (if (not org-noutline-p)
12753 ;; Make the current headline visible
12754 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12755 ;; Check if we should show the entire entry
12756 (if entry
12757 (progn
12758 (org-show-entry)
12759 (save-excursion ;; FIXME: Is this the fix for points in the -|
12760 ;; middle of text? |
12761 (and (outline-next-heading) ;; |
12762 (org-flag-heading nil)))) ; show the next heading _|
12763 (outline-flag-region (max 1 (1- (point)))
12764 (save-excursion (outline-end-of-heading) (point))
12765 (if org-noutline-p
12766 flag
12767 (if flag ?\r ?\n))))))
12768
12769 (defun org-end-of-subtree (&optional invisible-OK)
12770 ;; This is an exact copy of the original function, but it uses
12771 ;; `org-back-to-heading', to make it work also in invisible
12772 ;; trees. And is uses an invisible-OK argument.
12773 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
12774 (org-back-to-heading invisible-OK)
12775 (let ((first t)
12776 (level (funcall outline-level)))
12777 (while (and (not (eobp))
12778 (or first (> (funcall outline-level) level)))
12779 (setq first nil)
12780 (outline-next-heading))
12781 (if (memq (preceding-char) '(?\n ?\^M))
12782 (progn
12783 ;; Go to end of line before heading
12784 (forward-char -1)
12785 (if (memq (preceding-char) '(?\n ?\^M))
12786 ;; leave blank line before heading
12787 (forward-char -1))))))
12788
12789 (defun org-show-subtree ()
12790 "Show everything after this heading at deeper levels."
12791 (outline-flag-region
12792 (point)
12793 (save-excursion
12794 (outline-end-of-subtree) (outline-next-heading) (point))
12795 (if org-noutline-p nil ?\n)))
12796
12797 (defun org-show-entry ()
12798 "Show the body directly following this heading.
12799 Show the heading too, if it is currently invisible."
12800 (interactive)
12801 (save-excursion
12802 (org-back-to-heading t)
12803 (outline-flag-region
12804 (1- (point))
12805 (save-excursion
12806 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12807 (or (match-beginning 1) (point-max)))
12808 (if org-noutline-p nil ?\n))))
12809
12810
12811 (defun org-make-options-regexp (kwds)
12812 "Make a regular expression for keyword lines."
12813 (concat
12814 (if org-noutline-p "^" "[\n\r]")
12815 "#?[ \t]*\\+\\("
12816 (mapconcat 'regexp-quote kwds "\\|")
12817 "\\):[ \t]*"
12818 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12819
12820 ;; Make `bookmark-jump' show the jump location if it was hidden.
12821 (eval-after-load "bookmark"
12822 '(if (boundp 'bookmark-after-jump-hook)
12823 ;; We can use the hook
12824 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12825 ;; Hook not available, use advice
12826 (defadvice bookmark-jump (after org-make-visible activate)
12827 "Make the position visible."
12828 (org-bookmark-jump-unhide))))
12829
12830 (defun org-bookmark-jump-unhide ()
12831 "Unhide the current position, to show the bookmark location."
12832 (and (eq major-mode 'org-mode)
12833 (or (org-invisible-p)
12834 (save-excursion (goto-char (max (point-min) (1- (point))))
12835 (org-invisible-p)))
12836 (org-show-hierarchy-above)))
12837
12838 ;;; Finish up
12839
12840 (provide 'org)
12841
12842 (run-hooks 'org-load-hook)
12843
12844 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12845 ;;; org.el ends here
12846