]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
Move defvars out of eval-when-compile. Use
[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.08
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.08
85 ;;
86 ;;
87 ;; Version 4.07
88 ;; - Bug fixes.
89 ;; - Leading stars in headlines can be hidden, so make the outline look
90 ;; cleaner.
91 ;; - Mouse-1 can be used to follow links.
92 ;;
93 ;; Version 4.06
94 ;; - HTML exporter treats targeted internal links.
95 ;; - Bug fixes.
96 ;;
97 ;; Version 4.05
98 ;; - Changes to internal link system (thanks to David Wainberg for ideas).
99 ;; - in-file links: [[Search String]] instead of <file:::Search String>
100 ;; - automatic links to "radio targets".
101 ;; - CamelCase not longer active by default, configure org-activate-camels
102 ;; if you want to turn it back on.
103 ;; - After following a link, `C-c &' jumps back to it.
104 ;; - MH-E link support (thanks to Thomas Baumann).
105 ;; - Special table lines are no longer exported.
106 ;; - Bug fixes and minor improvements.
107 ;;
108 ;; Version 4.04
109 ;; - Cleanup tags display in agenda.
110 ;; - Bug fixes.
111 ;;
112 ;; Version 4.03
113 ;; - Table alignment fixed for use with wide characters.
114 ;; - `C-c -' leaves cursor in current table line.
115 ;; - The current TAG can be incorporated into the agenda prefix.
116 ;; See option `org-agenda-prefix-format' for details.
117 ;;
118 ;; Version 4.02
119 ;; - Minor bug fixes and improvements around tag searches.
120 ;; - XEmacs compatibility fixes.
121 ;;
122 ;; Version 4.01
123 ;; - Tags can also be set remotely from agenda buffer.
124 ;; - Boolean logic for tag searches.
125 ;; - Additional agenda commands can be configured through the variable
126 ;; `org-agenda-custom-commands'.
127 ;; - Minor bug fixes.
128 ;;
129 ;;; Code:
130
131 (eval-when-compile (require 'cl) (require 'calendar))
132 (require 'outline)
133 (require 'time-date)
134 (require 'easymenu)
135
136 (defvar calc-embedded-close-formula)
137 (defvar calc-embedded-open-formula)
138 (defvar font-lock-unfontify-region-function)
139
140 ;;; Customization variables
141
142 (defvar org-version "4.08"
143 "The version number of the file org.el.")
144 (defun org-version ()
145 (interactive)
146 (message "Org-mode version %s" org-version))
147
148 ;; The following two constants are for compatibility with different Emacs
149 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
150 ;; The compatibility code in org.el is based on these two constants.
151 (defconst org-xemacs-p (featurep 'xemacs)
152 "Are we running XEmacs?")
153 (defconst org-noutline-p (featurep 'noutline)
154 "Are we using the new outline mode?")
155
156 (defgroup org nil
157 "Outline-based notes management and organizer."
158 :tag "Org"
159 :group 'outlines
160 :group 'hypermedia
161 :group 'calendar)
162
163 (defgroup org-startup nil
164 "Options concerning startup of Org-mode."
165 :tag "Org Startup"
166 :group 'org)
167
168 (defcustom org-CUA-compatible nil
169 "Non-nil means use alternative key bindings for S-<cursor movement>.
170 Org-mode used S-<cursor movement> for changing timestamps and priorities.
171 S-<cursor movement> is also used for example by `CUA-mode' to select text.
172 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
173 alternative bindings. Setting this variable to t will replace the following
174 keys both in Org-mode and in the Org-agenda buffer.
175
176 S-RET -> C-S-RET
177 S-up -> M-p
178 S-down -> M-n
179 S-left -> M--
180 S-right -> M-+
181
182 If you do not like the alternative keys, take a look at the variable
183 `org-disputed-keys'.
184
185 This option is only relevant at load-time of Org-mode. Changing it requires
186 a restart of Emacs to become effective."
187 :group 'org-startup
188 :type 'boolean)
189
190 (defvar org-disputed-keys
191 '((S-up [(shift up)] [(meta ?p)])
192 (S-down [(shift down)] [(meta ?n)])
193 (S-left [(shift left)] [(meta ?-)])
194 (S-right [(shift right)] [(meta ?+)])
195 (S-return [(shift return)] [(control shift return)]))
196 "Keys for which Org-mode and other modes compete.
197 This is an alist, cars are symbols for lookup, 1st element is the default key,
198 second element will be used when `org-CUA-compatible' is t.")
199
200 (defun org-key (key)
201 "Select a key according to `org-CUA-compatible'."
202 (nth (if org-CUA-compatible 2 1)
203 (or (assq key org-disputed-keys)
204 (error "Invalid Key %s in `org-key'" key))))
205
206 (defcustom org-startup-folded t
207 "Non-nil means, entering Org-mode will switch to OVERVIEW.
208 This can also be configured on a per-file basis by adding one of
209 the following lines anywhere in the buffer:
210
211 #+STARTUP: fold
212 #+STARTUP: nofold
213 #+STARTUP: content"
214 :group 'org-startup
215 :type '(choice
216 (const :tag "nofold: show all" nil)
217 (const :tag "fold: overview" t)
218 (const :tag "content: all headlines" content)))
219
220 (defcustom org-startup-truncated t
221 "Non-nil means, entering Org-mode will set `truncate-lines'.
222 This is useful since some lines containing links can be very long and
223 uninteresting. Also tables look terrible when wrapped."
224 :group 'org-startup
225 :type 'boolean)
226
227 (defcustom org-startup-with-deadline-check nil
228 "Non-nil means, entering Org-mode will run the deadline check.
229 This means, if you start editing an org file, you will get an
230 immediate reminder of any due deadlines.
231 This can also be configured on a per-file basis by adding one of
232 the following lines anywhere in the buffer:
233
234 #+STARTUP: dlcheck
235 #+STARTUP: nodlcheck"
236 :group 'org-startup
237 :type 'boolean)
238
239 (defcustom org-insert-mode-line-in-empty-file nil
240 "Non-nil means insert the first line setting Org-mode in empty files.
241 When the function `org-mode' is called interactively in an empty file, this
242 normally means that the file name does not automatically trigger Org-mode.
243 To ensure that the file will always be in Org-mode in the future, a
244 line enforcing Org-mode will be inserted into the buffer, if this option
245 has been set."
246 :group 'org-startup
247 :type 'boolean)
248
249 (defgroup org-keywords nil
250 "Options concerning TODO items in Org-mode."
251 :tag "Org Keywords"
252 :group 'org)
253
254 (defcustom org-todo-keywords '("TODO" "DONE")
255 "List of TODO entry keywords.
256 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
257 considered to mean that the entry is \"done\". All the other mean that
258 action is required, and will make the entry show up in todo lists, diaries
259 etc.
260 The command \\[org-todo] cycles an entry through these states, and an
261 additional state where no keyword is present. For details about this
262 cycling, see also the variable `org-todo-interpretation'
263 Changes become only effective after restarting Emacs."
264 :group 'org-keywords
265 :type '(repeat (string :tag "Keyword")))
266
267 (defcustom org-todo-interpretation 'sequence
268 "Controls how TODO keywords are interpreted.
269 \\<org-mode-map>Possible values are `sequence' and `type'.
270 This variable is only relevant if `org-todo-keywords' contains more than two
271 states. There are two ways how these keywords can be used:
272
273 - As a sequence in the process of working on a TODO item, for example
274 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
275 org-todo-interpretation 'sequence)
276
277 - As different types of TODO items, for example
278 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
279 org-todo-interpretation 'type)
280
281 When the states are interpreted as a sequence, \\[org-todo] always cycles
282 to the next state, in order to walk through all different states. So with
283 \\[org-todo], you turn an empty entry into the state TODO. When you started
284 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
285 later to VERIFY and finally to DONE.
286
287 When the states are interpreted as types, \\[org-todo] still cycles through
288 when it is called several times in direct succession, in order to initially
289 select the type. However, if not called immediately after a previous
290 \\[org-todo], it switches from each type directly to DONE. So with the
291 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
292 RELAXED. If you later return to this entry and press \\[org-todo] again,
293 RELAXED will not be changed REMIND, but directly to DONE.
294
295 You can create a large number of types. To initially select a
296 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
297 type with completion. Of course, you can also type the keyword
298 directly into the buffer. M-TAB completes TODO keywords at the
299 beginning of a headline."
300 :group 'org-keywords
301 :type '(choice (const sequence)
302 (const type)))
303
304 (defcustom org-default-priority ?B
305 "The default priority of TODO items.
306 This is the priority an item get if no explicit priority is given."
307 :group 'org-keywords
308 :type 'character)
309
310 (defcustom org-lowest-priority ?C
311 "The lowest priority of TODO items. A character like ?A, ?B etc."
312 :group 'org-keywords
313 :type 'character)
314
315 (defcustom org-deadline-string "DEADLINE:"
316 "String to mark deadline entries.
317 A deadline is this string, followed by a time stamp. Should be a word,
318 terminated by a colon. You can insert a schedule keyword and
319 a timestamp with \\[org-deadline].
320 Changes become only effective after restarting Emacs."
321 :group 'org-keywords
322 :type 'string)
323
324 (defcustom org-scheduled-string "SCHEDULED:"
325 "String to mark scheduled TODO entries.
326 A schedule is this string, followed by a time stamp. Should be a word,
327 terminated by a colon. You can insert a schedule keyword and
328 a timestamp with \\[org-schedule].
329 Changes become only effective after restarting Emacs."
330 :group 'org-keywords
331 :type 'string)
332
333 (defcustom org-closed-string "CLOSED:"
334 "String used as the prefix for timestamps logging closing a TODO entry."
335 :group 'org-keywords
336 :type 'string)
337
338 (defcustom org-comment-string "COMMENT"
339 "Entries starting with this keyword will never be exported.
340 An entry can be toggled between COMMENT and normal with
341 \\[org-toggle-comment].
342 Changes become only effective after restarting Emacs."
343 :group 'org-keywords
344 :type 'string)
345
346 (defcustom org-quote-string "QUOTE"
347 "Entries starting with this keyword will be exported in fixed-width font.
348 Quoting applies only to the text in the entry following the headline, and does
349 not extend beyond the next headline, even if that is lower level.
350 An entry can be toggled between QUOTE and normal with
351 \\[org-toggle-fixed-width-section]."
352 :group 'org-keywords
353 :type 'string)
354
355 (defcustom org-after-todo-state-change-hook nil
356 "Hook which is run after the state of a TODO item was changed.
357 The new state (a string with a TODO keyword, or nil) is available in the
358 Lisp variable `state'."
359 :group 'org-keywords
360 :type 'hook)
361
362 ;; Variables for pre-computed regular expressions, all buffer local
363 (defvar org-todo-kwd-priority-p nil
364 "Do TODO items have priorities?")
365 (make-variable-buffer-local 'org-todo-kwd-priority-p)
366 (defvar org-todo-kwd-max-priority nil
367 "Maximum priority of TODO items.")
368 (make-variable-buffer-local 'org-todo-kwd-max-priority)
369 (defvar org-ds-keyword-length 12
370 "Maximum length of the Deadline and SCHEDULED keywords.")
371 (make-variable-buffer-local 'org-ds-keyword-length)
372 (defvar org-done-string nil
373 "The last string in `org-todo-keywords', indicating an item is DONE.")
374 (make-variable-buffer-local 'org-done-string)
375 (defvar org-todo-regexp nil
376 "Matches any of the TODO state keywords.")
377 (make-variable-buffer-local 'org-todo-regexp)
378 (defvar org-not-done-regexp nil
379 "Matches any of the TODO state keywords except the last one.")
380 (make-variable-buffer-local 'org-not-done-regexp)
381 (defvar org-todo-line-regexp nil
382 "Matches a headline and puts TODO state into group 2 if present.")
383 (make-variable-buffer-local 'org-todo-line-regexp)
384 (defvar org-nl-done-regexp nil
385 "Matches newline followed by a headline with the DONE keyword.")
386 (make-variable-buffer-local 'org-nl-done-regexp)
387 (defvar org-looking-at-done-regexp nil
388 "Matches the DONE keyword a point.")
389 (make-variable-buffer-local 'org-looking-at-done-regexp)
390 (defvar org-deadline-regexp nil
391 "Matches the DEADLINE keyword.")
392 (make-variable-buffer-local 'org-deadline-regexp)
393 (defvar org-deadline-time-regexp nil
394 "Matches the DEADLINE keyword together with a time stamp.")
395 (make-variable-buffer-local 'org-deadline-time-regexp)
396 (defvar org-deadline-line-regexp nil
397 "Matches the DEADLINE keyword and the rest of the line.")
398 (make-variable-buffer-local 'org-deadline-line-regexp)
399 (defvar org-scheduled-regexp nil
400 "Matches the SCHEDULED keyword.")
401 (make-variable-buffer-local 'org-scheduled-regexp)
402 (defvar org-scheduled-time-regexp nil
403 "Matches the SCHEDULED keyword together with a time stamp.")
404 (make-variable-buffer-local 'org-scheduled-time-regexp)
405
406 (defvar org-category nil
407 "Variable used by org files to set a category for agenda display.
408 Such files should use a file variable to set it, for example
409
410 -*- mode: org; org-category: \"ELisp\"
411
412 or contain a special line
413
414 #+CATEGORY: ELisp
415
416 If the file does not specify a category, then file's base name
417 is used instead.")
418 (make-variable-buffer-local 'org-category)
419
420 (defgroup org-time nil
421 "Options concerning time stamps and deadlines in Org-mode."
422 :tag "Org Time"
423 :group 'org)
424
425 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
426 "Formats for `format-time-string' which are used for time stamps.
427 It is not recommended to change this constant.")
428
429
430 (defcustom org-deadline-warning-days 30
431 "No. of days before expiration during which a deadline becomes active.
432 This variable governs the display in the org file."
433 :group 'org-time
434 :type 'number)
435
436 (defcustom org-popup-calendar-for-date-prompt t
437 "Non-nil means, pop up a calendar when prompting for a date.
438 In the calendar, the date can be selected with mouse-1. However, the
439 minibuffer will also be active, and you can simply enter the date as well.
440 When nil, only the minibuffer will be available."
441 :group 'org-time
442 :type 'number)
443
444 (defcustom org-calendar-follow-timestamp-change t
445 "Non-nil means, make the calendar window follow timestamp changes.
446 When a timestamp is modified and the calendar window is visible, it will be
447 moved to the new date."
448 :group 'org-time
449 :type 'boolean)
450
451 (defcustom org-log-done nil
452 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
453 When the state of an entry is changed from nothing to TODO, remove a previous
454 closing date."
455 :group 'org-time
456 :type 'boolean)
457
458 (defgroup org-agenda nil
459 "Options concerning agenda display Org-mode."
460 :tag "Org Agenda"
461 :group 'org)
462
463 (defcustom org-agenda-files nil
464 "A list of org files for agenda/diary display.
465 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
466 \\[org-remove-file]. You can also use customize to edit the list."
467 :group 'org-agenda
468 :type '(repeat file))
469
470 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
471 "Custom commands for the agenda.
472 These commands will be offered on the splash screen displayed by the
473 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
474
475 key The key (a single char as a string) to be associated with the command.
476 type The command type, any of the following symbols:
477 todo Entries with a specific TODO keyword, in all agenda files.
478 tags Tags match in all agenda files.
479 todo-tree Sparse tree of specific TODO keyword in *current* file.
480 tags-tree Sparse tree with all tags matches in *current* file.
481 occur-tree Occur sparse tree for current file.
482 match What to search for:
483 - a single keyword for TODO keyword searches
484 - a tags match expression for tags searches
485 - a regular expression for occur searches"
486 :group 'org-agenda
487 :type '(repeat
488 (list (string :tag "Key")
489 (choice :tag "Type"
490 (const :tag "Tags search in all agenda files" tags)
491 (const :tag "TODO keyword search in all agenda files" todo)
492 (const :tag "Tags sparse tree in current buffer" tags-tree)
493 (const :tag "TODO keyword tree in current buffer" todo-tree)
494 (const :tag "Occur tree in current buffer" occur-tree))
495 (string :tag "Match"))))
496
497 (defcustom org-select-timeline-window t
498 "Non-nil means, after creating a timeline, move cursor into Timeline window.
499 When nil, cursor will remain in the current window."
500 :group 'org-agenda
501 :type 'boolean)
502
503 (defcustom org-select-agenda-window t
504 "Non-nil means, after creating an agenda, move cursor into Agenda window.
505 When nil, cursor will remain in the current window."
506 :group 'org-agenda
507 :type 'boolean)
508
509 (defcustom org-fit-agenda-window t
510 "Non-nil means, change window size of agenda to fit content."
511 :group 'org-agenda
512 :type 'boolean)
513
514 (defcustom org-agenda-show-all-dates t
515 "Non-nil means, `org-agenda' shows every day in the selected range.
516 When nil, only the days which actually have entries are shown."
517 :group 'org-agenda
518 :type 'boolean)
519
520 ;; FIXME: First day of month works only for current month because it would
521 ;; require a variable ndays treatment.
522 (defcustom org-agenda-start-on-weekday 1
523 "Non-nil means, start the overview always on the specified weekday.
524 0 Denotes Sunday, 1 denotes Monday etc.
525 When nil, always start on the current day."
526 :group 'org-agenda
527 :type '(choice (const :tag "Today" nil)
528 (const :tag "First day of month" t)
529 (number :tag "Weekday No.")))
530
531 (defcustom org-agenda-ndays 7
532 "Number of days to include in overview display."
533 :group 'org-agenda
534 :type 'number)
535
536 (defcustom org-agenda-include-all-todo t
537 "Non-nil means, the agenda will always contain all TODO entries.
538 When nil, date-less entries will only be shown if `org-agenda' is called
539 with a prefix argument.
540 When non-nil, the TODO entries will be listed at the top of the agenda, before
541 the entries for specific days."
542 :group 'org-agenda
543 :type 'boolean)
544
545 (defcustom org-agenda-include-diary nil
546 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
547 :group 'org-agenda
548 :type 'boolean)
549
550 (defcustom org-calendar-to-agenda-key [?c]
551 "The key to be installed in `calendar-mode-map' for switching to the agenda.
552 The command `org-calendar-goto-agenda' will be bound to this key. The
553 default is the character `c' because then `c' can be used to switch back and
554 forth between agenda and calendar."
555 :group 'org-agenda
556 :type 'sexp)
557
558 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
559 "Sorting structure for the agenda items of a single day.
560 This is a list of symbols which will be used in sequence to determine
561 if an entry should be listed before another entry. The following
562 symbols are recognized:
563
564 time-up Put entries with time-of-day indications first, early first
565 time-down Put entries with time-of-day indications first, late first
566 category-keep Keep the default order of categories, corresponding to the
567 sequence in `org-agenda-files'.
568 category-up Sort alphabetically by category, A-Z.
569 category-down Sort alphabetically by category, Z-A.
570 priority-up Sort numerically by priority, high priority last.
571 priority-down Sort numerically by priority, high priority first.
572
573 The different possibilities will be tried in sequence, and testing stops
574 if one comparison returns a \"not-equal\". For example, the default
575 '(time-up category-keep priority-down)
576 means: Pull out all entries having a specified time of day and sort them,
577 in order to make a time schedule for the current day the first thing in the
578 agenda listing for the day. Of the entries without a time indication, keep
579 the grouped in categories, don't sort the categories, but keep them in
580 the sequence given in `org-agenda-files'. Within each category sort by
581 priority.
582
583 Leaving out `category-keep' would mean that items will be sorted across
584 categories by priority."
585 :group 'org-agenda
586 :type '(repeat
587 (choice
588 (const time-up)
589 (const time-down)
590 (const category-keep)
591 (const category-up)
592 (const category-down)
593 (const priority-up)
594 (const priority-down))))
595
596 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
597 "Format specification for the prefix of items in the agenda buffer.
598 This format works similar to a printf format, with the following meaning:
599
600 %c the category of the item, \"Diary\" for entries from the diary, or
601 as given by the CATEGORY keyword or derived from the file name.
602 %T the first tag of the item.
603 %t the time-of-day specification if one applies to the entry, in the
604 format HH:MM
605 %s Scheduling/Deadline information, a short string
606
607 All specifiers work basically like the standard `%s' of printf, but may
608 contain two additional characters: A question mark just after the `%' and
609 a whitespace/punctuation character just before the final letter.
610
611 If the first character after `%' is a question mark, the entire field
612 will only be included if the corresponding value applies to the
613 current entry. This is useful for fields which should have fixed
614 width when present, but zero width when absent. For example,
615 \"%?-12t\" will result in a 12 character time field if a time of the
616 day is specified, but will completely disappear in entries which do
617 not contain a time.
618
619 If there is punctuation or whitespace character just before the final
620 format letter, this character will be appended to the field value if
621 the value is not empty. For example, the format \"%-12:c\" leads to
622 \"Diary: \" if the category is \"Diary\". If the category were be
623 empty, no additional colon would be interted.
624
625 The default value of this option is \" %-12:c%?-12t% s\", meaning:
626 - Indent the line with two space characters
627 - Give the category in a 12 chars wide field, padded with whitespace on
628 the right (because of `-'). Append a colon if there is a category
629 (because of `:').
630 - If there is a time-of-day, put it into a 12 chars wide field. If no
631 time, don't put in an empty field, just skip it (because of '?').
632 - Finally, put the scheduling information and append a whitespace.
633
634 As another example, if you don't want the time-of-day of entries in
635 the prefix, you could use:
636
637 (setq org-agenda-prefix-format \" %-11:c% s\")
638
639 See also the variables `org-agenda-remove-times-when-in-prefix' and
640 `org-agenda-remove-tags-when-in-prefix'."
641 :type 'string
642 :group 'org-agenda)
643
644 (defcustom org-timeline-prefix-format " % s"
645 "Like `org-agenda-prefix-format', but for the timeline of a single file."
646 :type 'string
647 :group 'org-agenda)
648
649 (defvar org-prefix-format-compiled nil
650 "The compiled version of the most recently used prefix format.
651 Depending on which command was used last, this may be the compiled version
652 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
653
654 (defcustom org-agenda-use-time-grid t
655 "Non-nil means, show a time grid in the agenda schedule.
656 A time grid is a set of lines for specific times (like every two hours between
657 8:00 and 20:00). The items scheduled for a day at specific times are
658 sorted in between these lines.
659 For details about when the grid will be shown, and what it will look like, see
660 the variable `org-agenda-time-grid'."
661 :group 'org-agenda
662 :type 'boolean)
663
664 (defcustom org-agenda-time-grid
665 '((daily today require-timed)
666 "----------------"
667 (800 1000 1200 1400 1600 1800 2000))
668
669 "The settings for time grid for agenda display.
670 This is a list of three items. The first item is again a list. It contains
671 symbols specifying conditions when the grid should be displayed:
672
673 daily if the agenda shows a single day
674 weekly if the agenda shows an entire week
675 today show grid on current date, independent of daily/weekly display
676 require-timed show grid only if at least on item has a time specification
677
678 The second item is a string which will be places behing the grid time.
679
680 The third item is a list of integers, indicating the times that should have
681 a grid line."
682 :group 'org-agenda
683 :type
684 '(list
685 (set :greedy t :tag "Grid Display Options"
686 (const :tag "Show grid in single day agenda display" daily)
687 (const :tag "Show grid in weekly agenda display" weekly)
688 (const :tag "Always show grid for today" today)
689 (const :tag "Show grid only if any timed entries are present"
690 require-timed)
691 (const :tag "Skip grid times already present in an entry"
692 remove-match))
693 (string :tag "Grid String")
694 (repeat :tag "Grid Times" (integer :tag "Time"))))
695
696 (defcustom org-agenda-remove-times-when-in-prefix t
697 "Non-nil means, remove duplicate time specifications in agenda items.
698 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
699 time-of-day specification in a headline or diary entry is extracted and
700 placed into the prefix. If this option is non-nil, the original specification
701 \(a timestamp or -range, or just a plain time(range) specification like
702 11:30-4pm) will be removed for agenda display. This makes the agenda less
703 cluttered.
704 The option can be t or nil. It may also be the symbol `beg', indicating
705 that the time should only be removed what it is located at the beginning of
706 the headline/diary entry."
707 :group 'org-agenda
708 :type '(choice
709 (const :tag "Always" t)
710 (const :tag "Never" nil)
711 (const :tag "When at beginning of entry" beg)))
712
713 (defcustom org-sort-agenda-notime-is-late t
714 "Non-nil means, items without time are considered late.
715 This is only relevant for sorting. When t, items which have no explicit
716 time like 15:30 will be considered as 24:01, i.e. later than any items which
717 do have a time. When nil, the default time is before 0:00. You can use this
718 option to decide if the schedule for today should come before or after timeless
719 agenda entries."
720 :group 'org-agenda
721 :type 'boolean)
722
723 (defcustom org-agenda-remove-tags-when-in-prefix nil
724 "Non-nil means, the tags from copy of headline in agenda.
725 When this is the symbol `prefix', only remove tags when
726 `org-agenda-prefix-format' contains a `%T' specifier."
727 :group 'org-agenda
728 :type '(choice
729 (const :tag "Always" t)
730 (const :tag "Never" nil)
731 (const :tag "When prefix format contains %T" prefix)))
732
733 (defgroup org-structure nil
734 "Options concerning structure editing in Org-mode."
735 :tag "Org Structure"
736 :group 'org)
737
738 (defcustom org-cycle-include-plain-lists nil
739 "Non-nil means, include plain lists into visibility cycling.
740 This means that during cycling, plain list items will *temporarily* be
741 interpreted as outline headlines with a level given by 1000+i where i is the
742 indentation of the bullet. In all other operations, plain list items are
743 not seen as headlines. For example, you cannot assign a TODO keyword to
744 such an item."
745 :group 'org-structure
746 :type 'boolean)
747
748 (defcustom org-cycle-emulate-tab t
749 "Where should `org-cycle' emulate TAB.
750 nil Never
751 white Only in completely white lines
752 t Everywhere except in headlines"
753 :group 'org-structure
754 :type '(choice (const :tag "Never" nil)
755 (const :tag "Only in completely white lines" white)
756 (const :tag "Everywhere except in headlines" t)
757 ))
758
759 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
760 "Hook that is run after `org-cycle' has changed the buffer visibility.
761 The function(s) in this hook must accept a single argument which indicates
762 the new state that was set by the most recent `org-cycle' command. The
763 argument is a symbol. After a global state change, it can have the values
764 `overview', `content', or `all'. After a local state change, it can have
765 the values `folded', `children', or `subtree'."
766 :group 'org-structure
767 :type 'hook)
768
769 (defcustom org-highlight-sparse-tree-matches t
770 "Non-nil means, highlight all matches that define a sparse tree.
771 The highlights will automatically disappear the next time the buffer is
772 changed by an edit command."
773 :group 'org-structure
774 :type 'boolean)
775
776 (defcustom org-show-hierarchy-above t
777 "Non-nil means, show full hierarchy when showing a spot in the tree.
778 Turning this off makes sparse trees more compact, but also less clear."
779 :group 'org-structure
780 :type 'boolean)
781
782 (defcustom org-show-following-heading t
783 "Non-nil means, show heading following match in `org-occur'.
784 When doing an `org-occur' it is useful to show the headline which
785 follows the match, even if they do not match the regexp. This makes it
786 easier to edit directly inside the sparse tree. However, if you use
787 `org-occur' mainly as an overview, the following headlines are
788 unnecessary clutter."
789 :group 'org-structure
790 :type 'boolean)
791
792 (defcustom org-occur-hook '(org-first-headline-recenter)
793 "Hook that is run after `org-occur' has constructed a sparse tree.
794 This can be used to recenter the window to show as much of the structure
795 as possible."
796 :group 'org-structure
797 :type 'hook)
798
799 (defcustom org-level-color-stars-only nil
800 "Non-nil means fontify only the stars in each headline.
801 When nil, the entire headline is fontified.
802 Changing it requires restart of `font-lock-mode' to become effective."
803 :group 'org-structure
804 :type 'boolean)
805
806 (defcustom org-hide-leading-stars nil
807 "Non-nil means, hide the first N-1 stars in a headline.
808 This works by using the face `org-hide' for these stars. This
809 face is white for a light background, and black for a dark
810 background. You may have to customize the face `org-hide' to
811 make this work.
812 Changing it requires restart of `font-lock-mode' to become effective."
813 :group 'org-structure
814 :type 'boolean)
815
816 (defcustom org-odd-levels-only nil
817 "Non-nil means, skip even levels and only use odd levels for the outline.
818 This has the effect that two stars are being added/taken away in
819 promotion/demotion commands. It also influences how levels are
820 handled by the exporters.
821 Changing it requires restart of `font-lock-mode' to become effective
822 for fontification."
823 :group 'org-structure
824 :type 'boolean)
825
826 (defcustom org-adapt-indentation t
827 "Non-nil means, adapt indentation when promoting and demoting.
828 When this is set and the *entire* text in an entry is indented, the
829 indentation is increased by one space in a demotion command, and
830 decreased by one in a promotion command. If any line in the entry
831 body starts at column 0, indentation is not changed at all."
832 :group 'org-structure
833 :type 'boolean)
834
835 (defcustom org-plain-list-ordered-item-terminator t
836 "The character that makes a line with leading number an ordered list item.
837 Valid values are ?. and ?\). To get both terminators, use t. While
838 ?. may look nicer, it creates the danger that a line with leading
839 number may be incorrectly interpreted as an item. ?\) therefore is
840 the safe choice."
841 :group 'org-structure
842 :type '(choice (const :tag "dot like in \"2.\"" ?.)
843 (const :tag "paren like in \"2)\"" ?\))
844 (const :tab "both" t)))
845
846 (defcustom org-auto-renumber-ordered-lists t
847 "Non-nil means, automatically renumber ordered plain lists.
848 Renumbering happens when the sequence have been changed with
849 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
850 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
851 :group 'org-structure
852 :type 'boolean)
853
854 (defcustom org-enable-fixed-width-editor t
855 "Non-nil means, lines starting with \":\" are treated as fixed-width.
856 This currently only means, they are never auto-wrapped.
857 When nil, such lines will be treated like ordinary lines.
858 See also the QUOTE keyword."
859 :group 'org-structure
860 :type 'boolean)
861
862 (defcustom org-archive-location "%s_archive::"
863 "The location where subtrees should be archived.
864 This string consists of two parts, separated by a double-colon.
865
866 The first part is a file name - when omitted, archiving happens in the same
867 file. %s will be replaced by the current file name (without directory part).
868 Archiving to a different file is useful to keep archived entries from
869 contributing to the Org-mode Agenda.
870
871 The part after the double colon is a headline. The archived entries will be
872 filed under that headline. When omitted, the subtrees are simply filed away
873 at the end of the file, as top-level entries.
874
875 Here are a few examples:
876 \"%s_archive::\"
877 If the current file is Projects.org, archive in file
878 Projects.org_archive, as top-level trees. This is the default.
879
880 \"::* Archived Tasks\"
881 Archive in the current file, under the top-level headline
882 \"* Archived Tasks\".
883
884 \"~/org/archive.org::\"
885 Archive in file ~/org/archive.org (absolute path), as top-level trees.
886
887 \"basement::** Finished Tasks\"
888 Archive in file ./basement (relative path), as level 3 trees
889 below the level 2 heading \"** Finished Tasks\".
890
891 You may set this option on a per-file basis by adding to the buffer a
892 line like
893
894 #+ARCHIVE: basement::** Finished Tasks"
895 :group 'org-structure
896 :type 'string)
897
898 (defcustom org-archive-mark-done t
899 "Non-nil means, mark archived entries as DONE."
900 :group 'org-structure
901 :type 'boolean)
902
903 (defcustom org-archive-stamp-time t
904 "Non-nil means, add a time stamp to archived entries.
905 The time stamp will be added directly after the TODO state keyword in the
906 first line, so it is probably best to use this in combinations with
907 `org-archive-mark-done'."
908 :group 'org-structure
909 :type 'boolean)
910
911 (defgroup org-tags nil
912 "Options concerning startup of Org-mode."
913 :tag "Org Tags"
914 :group 'org)
915
916 (defcustom org-tags-column 48
917 "The column to which tags should be indented in a headline.
918 If this number is positive, it specifies the column. If it is negative,
919 it means that the tags should be flushright to that column. For example,
920 -79 works well for a normal 80 character screen."
921 :group 'org-tags
922 :type 'integer)
923
924 (defcustom org-auto-align-tags t
925 "Non-nil means, realign tags after pro/demotion of TODO state change.
926 These operations change the length of a headline and therefore shift
927 the tags around. With this options turned on, after each such operation
928 the tags are again aligned to `org-tags-column'."
929 :group 'org-tags
930 :type 'boolean)
931
932 (defcustom org-use-tag-inheritance t
933 "Non-nil means, tags in levels apply also for sublevels.
934 When nil, only the tags directly given in a specific line apply there.
935 If you turn off this option, you very likely want to turn on the
936 companion option `org-tags-match-list-sublevels'."
937 :group 'org-tags
938 :type 'boolean)
939
940 (defcustom org-tags-match-list-sublevels nil
941 "Non-nil means list also sublevels of headlines matching tag search.
942 Because of tag inheritance (see variable `org-use-tag-inheritance'),
943 the sublevels of a headline matching a tag search often also match
944 the same search. Listing all of them can create very long lists.
945 Setting this variable to nil causes subtrees to be skipped.
946 This option is off by default, because inheritance in on. If you turn
947 inheritance off, you very likely want to turn this option on.
948
949 As a special case, if the tag search is restricted to TODO items, the
950 value of this variable is ignored and sublevels are always checked, to
951 make sure all corresponding TODO items find their way into the list."
952 :group 'org-tags
953 :type 'boolean)
954
955 (defvar org-tags-history nil
956 "History of minibuffer reads for tags.")
957 (defvar org-last-tags-completion-table nil
958 "The last used completion table for tags.")
959
960 (defgroup org-link nil
961 "Options concerning links in Org-mode."
962 :tag "Org Link"
963 :group 'org)
964
965 (defcustom org-tab-follows-link nil
966 "Non-nil means, on links TAB will follow the link.
967 Needs to be set before org.el is loaded."
968 :group 'org-link
969 :type 'boolean)
970
971 (defcustom org-return-follows-link nil
972 "Non-nil means, on links RET will follow the link.
973 Needs to be set before org.el is loaded."
974 :group 'org-link
975 :type 'boolean)
976
977 (defcustom org-mark-ring-length 4
978 "Number of different positions to be recorded in the ring
979 Changing this requires a restart of Emacs to work correctly."
980 :group 'org-link
981 :type 'interger)
982
983 (defcustom org-link-format "<%s>"
984 "Default format for linkes in the buffer.
985 This is a format string for printf, %s will be replaced by the link text.
986 If you want to make sure that your link is always properly terminated,
987 include angle brackets into this format, like \"<%s>\". Some people also
988 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
989 :group 'org-link
990 :type '(choice
991 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
992 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
993 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
994 (string :tag "Other" :value "<%s>")))
995
996 (defcustom org-allow-space-in-links t
997 "Non-nil means, file names in links may contain space characters.
998 When nil, it becomes possible to put several links into a line.
999 Note that in tables, a link never extends accross fields, so in a table
1000 it is always possible to put several links into a line.
1001 Changing this variable requires a restart of Emacs of become effective."
1002 :group 'org-link
1003 :type 'boolean)
1004
1005 (defcustom org-radio-targets t
1006 "Non-nil means activate text matching a link target.
1007 Radio targets are strings in triple angular brackets, like <<<My Target>>>.
1008 When this option is set, any occurrence of \"my target\" in normal text
1009 becomes a link."
1010 :group 'org-link
1011 :type 'boolean)
1012
1013 (defcustom org-activate-camels nil
1014 "Non-nil means, treat words in CamelCase as in-file links.
1015 Changing this requires restart of Emacs to become effective."
1016 :group 'org-link
1017 :type 'boolean)
1018
1019 (defcustom org-context-in-file-links t
1020 "Non-nil means, file links from `org-store-link' contain context.
1021 A search string will be added to the file name with :: as separator and
1022 used to find the context when the link is activated by the command
1023 `org-open-at-point'.
1024 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1025 negates this setting for the duration of the command."
1026 :group 'org-link
1027 :type 'boolean)
1028
1029 (defcustom org-file-link-context-use-camel-case nil
1030 "Non-nil means, use CamelCase to store a search context in a file link.
1031 When nil, the search string simply consists of the words of the string."
1032 :group 'org-link
1033 :type 'boolean)
1034
1035 (defcustom org-keep-stored-link-after-insertion nil
1036 "Non-nil means, keep link in list for entire session.
1037
1038 The command `org-store-link' adds a link pointing to the current
1039 location to an internal list. These links accumulate during a session.
1040 The command `org-insert-link' can be used to insert links into any
1041 Org-mode file (offering completion for all stored links). When this
1042 option is nil, every link which has been inserted once using \\[org-insert-link]
1043 will be removed from the list, to make completing the unused links
1044 more efficient."
1045 :group 'org-link
1046 :type 'boolean)
1047
1048 (defcustom org-link-frame-setup
1049 '((vm . vm-visit-folder-other-frame)
1050 (gnus . gnus-other-frame)
1051 (file . find-file-other-window))
1052 "Setup the frame configuration for following links.
1053 When following a link with Emacs, it may often be useful to display
1054 this link in another window or frame. This variable can be used to
1055 set this up for the different types of links.
1056 For VM, use any of
1057 `vm-visit-folder'
1058 `vm-visit-folder-other-frame'
1059 For Gnus, use any of
1060 `gnus'
1061 `gnus-other-frame'
1062 For FILE, use any of
1063 `find-file'
1064 `find-file-other-window'
1065 `find-file-other-frame'
1066 For the calendar, use the variable `calendar-setup'.
1067 For BBDB, it is currently only possible to display the matches in
1068 another window."
1069 :group 'org-link
1070 :type '(list
1071 (cons (const vm)
1072 (choice
1073 (const vm-visit-folder)
1074 (const vm-visit-folder-other-window)
1075 (const vm-visit-folder-other-frame)))
1076 (cons (const gnus)
1077 (choice
1078 (const gnus)
1079 (const gnus-other-frame)))
1080 (cons (const file)
1081 (choice
1082 (const find-file)
1083 (const find-file-other-window)
1084 (const find-file-other-frame)))))
1085
1086 (defcustom org-usenet-links-prefer-google nil
1087 "Non-nil means, `org-store-link' will create web links to Google groups.
1088 When nil, Gnus will be used for such links.
1089 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1090 negates this setting for the duration of the command."
1091 :group 'org-link
1092 :type 'boolean)
1093
1094 (defcustom org-open-non-existing-files nil
1095 "Non-nil means, `org-open-file' will open non-existing file.
1096 When nil, an error will be generated."
1097 :group 'org-link
1098 :type 'boolean)
1099
1100 (defcustom org-confirm-shell-links t
1101 "Non-nil means, ask for confirmation before executing shell links.
1102 The default is true, to keep new users from shooting into their own foot."
1103 :group 'org-link
1104 :type 'boolean)
1105
1106 (defconst org-file-apps-defaults-gnu
1107 '((t . mailcap))
1108 "Default file applications on a UNIX or GNU/Linux system.
1109 See `org-file-apps'.")
1110
1111 (defconst org-file-apps-defaults-macosx
1112 '((t . "open %s")
1113 ("ps" . "gv %s")
1114 ("ps.gz" . "gv %s")
1115 ("eps" . "gv %s")
1116 ("eps.gz" . "gv %s")
1117 ("dvi" . "xdvi %s")
1118 ("fig" . "xfig %s"))
1119 "Default file applications on a MacOS X system.
1120 The system \"open\" is known as a default, but we use X11 applications
1121 for some files for which the OS does not have a good default.
1122 See `org-file-apps'.")
1123
1124 (defconst org-file-apps-defaults-windowsnt
1125 '((t . (w32-shell-execute "open" file)))
1126 "Default file applications on a Windows NT system.
1127 The system \"open\" is used for most files.
1128 See `org-file-apps'.")
1129
1130 (defcustom org-file-apps
1131 '(
1132 ("txt" . emacs)
1133 ("tex" . emacs)
1134 ("ltx" . emacs)
1135 ("org" . emacs)
1136 ("el" . emacs)
1137 )
1138 "External applications for opening `file:path' items in a document.
1139 Org-mode uses system defaults for different file types, but
1140 you can use this variable to set the application for a given file
1141 extension. The entries in this list are cons cells with a file extension
1142 and the corresponding command. Possible values for the command are:
1143 `emacs' The file will be visited by the current Emacs process.
1144 `default' Use the default application for this file type.
1145 string A command to be executed by a shell; %s will be replaced
1146 by the path to the file.
1147 sexp A Lisp form which will be evaluated. The file path will
1148 be available in the Lisp variable `file'.
1149 For more examples, see the system specific constants
1150 `org-file-apps-defaults-macosx'
1151 `org-file-apps-defaults-windowsnt'
1152 `org-file-apps-defaults-gnu'."
1153 :group 'org-link
1154 :type '(repeat
1155 (cons (choice :value ""
1156 (string :tag "Extension")
1157 (const :tag "Default for unrecognized files" t)
1158 (const :tag "Links to a directory" directory))
1159 (choice :value ""
1160 (const :tag "Visit with Emacs" emacs)
1161 (const :tag "Use system default" default)
1162 (string :tag "Command")
1163 (sexp :tag "Lisp form")))))
1164
1165 (defcustom org-mhe-search-all-folders nil
1166 "Non-nil means, that the search for the mh-message will be extended to
1167 all folders if the message cannot be found in the folder given in the link.
1168 Searching all folders is very effective with one of the search engines
1169 supported by MH-E, but will be slow with pick."
1170 :group 'org-link
1171 :type 'boolean)
1172
1173 (defgroup org-remember nil
1174 "Options concerning interaction with remember.el."
1175 :tag "Org Remember"
1176 :group 'org)
1177
1178 (defcustom org-directory "~/org"
1179 "Directory with org files.
1180 This directory will be used as default to prompt for org files.
1181 Used by the hooks for remember.el."
1182 :group 'org-remember
1183 :type 'directory)
1184
1185 (defcustom org-default-notes-file "~/.notes"
1186 "Default target for storing notes.
1187 Used by the hooks for remember.el. This can be a string, or nil to mean
1188 the value of `remember-data-file'."
1189 :group 'org-remember
1190 :type '(choice
1191 (const :tag "Default from remember-data-file" nil)
1192 file))
1193
1194 (defcustom org-reverse-note-order nil
1195 "Non-nil means, store new notes at the beginning of a file or entry.
1196 When nil, new notes will be filed to the end of a file or entry."
1197 :group 'org-remember
1198 :type '(choice
1199 (const :tag "Reverse always" t)
1200 (const :tag "Reverse never" nil)
1201 (repeat :tag "By file name regexp"
1202 (cons regexp boolean))))
1203
1204 (defgroup org-table nil
1205 "Options concerning tables in Org-mode."
1206 :tag "Org Table"
1207 :group 'org)
1208
1209 (defcustom org-enable-table-editor 'optimized
1210 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1211 When nil, such lines will be treated like ordinary lines.
1212
1213 When equal to the symbol `optimized', the table editor will be optimized to
1214 do the following:
1215 - Use automatic overwrite mode in front of whitespace in table fields.
1216 This make the structure of the table stay in tact as long as the edited
1217 field does not exceed the column width.
1218 - Minimize the number of realigns. Normally, the table is aligned each time
1219 TAB or RET are pressed to move to another field. With optimization this
1220 happens only if changes to a field might have changed the column width.
1221 Optimization requires replacing the functions `self-insert-command',
1222 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1223 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1224 very good at guessing when a re-align will be necessary, but you can always
1225 force one with \\[org-ctrl-c-ctrl-c].
1226
1227 If you would like to use the optimized version in Org-mode, but the
1228 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1229
1230 This variable can be used to turn on and off the table editor during a session,
1231 but in order to toggle optimization, a restart is required.
1232
1233 See also the variable `org-table-auto-blank-field'."
1234 :group 'org-table
1235 :type '(choice
1236 (const :tag "off" nil)
1237 (const :tag "on" t)
1238 (const :tag "on, optimized" optimized)))
1239
1240 ;; FIXME: We could have a third option which makes it jump only over the first
1241 ;; hline in a table.
1242 (defcustom org-table-tab-jumps-over-hlines t
1243 "Non-nil means, tab in the last column of a table with jump over a hline.
1244 If a horizontal separator line is following the current line,
1245 `org-table-next-field' can either create a new row before that line, or jump
1246 over the line. When this option is nil, a new line will be created before
1247 this line."
1248 :group 'org-table
1249 :type 'boolean)
1250
1251 (defcustom org-table-auto-blank-field t
1252 "Non-nil means, automatically blank table field when starting to type into it.
1253 This only happens when typing immediately after a field motion
1254 command (TAB, S-TAB or RET).
1255 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1256 :group 'org-table
1257 :type 'boolean)
1258
1259 (defcustom org-table-default-size "5x2"
1260 "The default size for newly created tables, Columns x Rows."
1261 :group 'org-table
1262 :type 'string)
1263
1264 (defcustom org-table-automatic-realign t
1265 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1266 When nil, aligning is only done with \\[org-table-align], or after column
1267 removal/insertion."
1268 :group 'org-table
1269 :type 'boolean)
1270
1271 (defcustom org-table-spaces-around-separators '(1 . 1)
1272 "The number of spaces to be placed before and after separators."
1273 :group 'org-table
1274 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1275
1276 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1277 "The number of spaces to be placed before and after separators.
1278 This option applies when the column separators have been made invisible."
1279 :group 'org-table
1280 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1281
1282 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1283 "Regular expression for recognizing numbers in table columns.
1284 If a table column contains mostly numbers, it will be aligned to the
1285 right. If not, it will be aligned to the left.
1286
1287 The default value of this option is a regular expression which allows
1288 anything which looks remotely like a number as used in scientific
1289 context. For example, all of the following will be considered a
1290 number:
1291 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1292
1293 Other options offered by the customize interface are more restrictive."
1294 :group 'org-table
1295 :type '(choice
1296 (const :tag "Positive Integers"
1297 "^[0-9]+$")
1298 (const :tag "Integers"
1299 "^[-+]?[0-9]+$")
1300 (const :tag "Floating Point Numbers"
1301 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1302 (const :tag "Floating Point Number or Integer"
1303 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1304 (const :tag "Exponential, Floating point, Integer"
1305 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1306 (const :tag "Very General Number-Like"
1307 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1308 (string :tag "Regexp:")))
1309
1310 (defcustom org-table-number-fraction 0.5
1311 "Fraction of numbers in a column required to make the column align right.
1312 In a column all non-white fields are considered. If at least this
1313 fraction of fields is matched by `org-table-number-fraction',
1314 alignment to the right border applies."
1315 :group 'org-table
1316 :type 'number)
1317
1318 (defcustom org-export-highlight-first-table-line t
1319 "Non-nil means, highlight the first table line.
1320 In HTML export, this means use <th> instead of <td>.
1321 In tables created with table.el, this applies to the first table line.
1322 In Org-mode tables, all lines before the first horizontal separator
1323 line will be formatted with <th> tags."
1324 :group 'org-table
1325 :type 'boolean)
1326
1327 (defcustom org-table-tab-recognizes-table.el t
1328 "Non-nil means, TAB will automatically notice a table.el table.
1329 When it sees such a table, it moves point into it and - if necessary -
1330 calls `table-recognize-table'."
1331 :group 'org-table
1332 :type 'boolean)
1333
1334 (defgroup org-table-calculation nil
1335 "Options concerning tables in Org-mode."
1336 :tag "Org Table Calculation"
1337 :group 'org)
1338
1339 (defcustom org-table-copy-increment t
1340 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1341 :group 'org-table-calculation
1342 :type 'boolean)
1343
1344 (defcustom org-calc-default-modes
1345 '(calc-internal-prec 12
1346 calc-float-format (float 5)
1347 calc-angle-mode deg
1348 calc-prefer-frac nil
1349 calc-symbolic-mode nil
1350 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1351 calc-display-working-message t
1352 )
1353 "List with Calc mode settings for use in calc-eval for table formulas.
1354 The list must contain alternating symbols (Calc modes variables and values).
1355 Don't remove any of the default settings, just change the values. Org-mode
1356 relies on the variables to be present in the list."
1357 :group 'org-table-calculation
1358 :type 'plist)
1359
1360 (defcustom org-table-formula-evaluate-inline t
1361 "Non-nil means, TAB and RET evaluate a formula in current table field.
1362 If the current field starts with an equal sign, it is assumed to be a formula
1363 which should be evaluated as described in the manual and in the documentation
1364 string of the command `org-table-eval-formula'. This feature requires the
1365 Emacs calc package.
1366 When this variable is nil, formula calculation is only available through
1367 the command \\[org-table-eval-formula]."
1368 :group 'org-table-calculation
1369 :type 'boolean)
1370
1371
1372 (defcustom org-table-formula-use-constants t
1373 "Non-nil means, interpret constants in formulas in tables.
1374 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1375 by the value given in `org-table-formula-constants', or by a value obtained
1376 from the `constants.el' package."
1377 :group 'org-table-calculation
1378 :type 'boolean)
1379
1380 (defcustom org-table-formula-constants nil
1381 "Alist with constant names and values, for use in table formulas.
1382 The car of each element is a name of a constant, without the `$' before it.
1383 The cdr is the value as a string. For example, if you'd like to use the
1384 speed of light in a formula, you would configure
1385
1386 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1387
1388 and then use it in an equation like `$1*$c'."
1389 :group 'org-table-calculation
1390 :type '(repeat
1391 (cons (string :tag "name")
1392 (string :tag "value"))))
1393
1394 (defcustom org-table-formula-numbers-only nil
1395 "Non-nil means, calculate only with numbers in table formulas.
1396 Then all input fields will be converted to a number, and the result
1397 must also be a number. When nil, calc's full potential is available
1398 in table calculations, including symbolics etc."
1399 :group 'org-table-calculation
1400 :type 'boolean)
1401
1402 (defcustom org-table-allow-automatic-line-recalculation t
1403 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1404 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1405 :group 'org-table-calculation
1406 :type 'boolean)
1407
1408 (defgroup org-export nil
1409 "Options for exporting org-listings."
1410 :tag "Org Export"
1411 :group 'org)
1412
1413 (defcustom org-export-language-setup
1414 '(("en" "Author" "Date" "Table of Contents")
1415 ("da" "Ophavsmand" "Dato" "Indhold")
1416 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1417 ("es" "Autor" "Fecha" "\xccndice")
1418 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1419 ("it" "Autore" "Data" "Indice")
1420 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1421 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1422 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1423 "Terms used in export text, translated to different languages.
1424 Use the variable `org-export-default-language' to set the language,
1425 or use the +OPTION lines for a per-file setting."
1426 :group 'org-export
1427 :type '(repeat
1428 (list
1429 (string :tag "HTML language tag")
1430 (string :tag "Author")
1431 (string :tag "Date")
1432 (string :tag "Table of Contents"))))
1433
1434 (defcustom org-export-default-language "en"
1435 "The default language of HTML export, as a string.
1436 This should have an association in `org-export-language-setup'."
1437 :group 'org-export
1438 :type 'string)
1439
1440 (defcustom org-export-html-style
1441 "<style type=\"text/css\">
1442 html {
1443 font-family: Times, serif;
1444 font-size: 12pt;
1445 }
1446 .title { text-align: center; }
1447 .todo, .deadline { color: red; }
1448 .done { color: green; }
1449 .target { background-color: lavender; }
1450 pre {
1451 border: 1pt solid #AEBDCC;
1452 background-color: #F3F5F7;
1453 padding: 5pt;
1454 font-family: courier, monospace;
1455 }
1456 table { border-collapse: collapse; }
1457 td, th {
1458 vertical-align: top;
1459 border: 1pt solid #ADB9CC;
1460 }
1461 </style>"
1462 "The default style specification for exported HTML files.
1463 Since there are different ways of setting style information, this variable
1464 needs to contain the full HTML structure to provide a style, including the
1465 surrounding HTML tags. The style specifications should include definitions
1466 for new classes todo, done, title, and deadline. For example, legal values
1467 would be:
1468
1469 <style type=\"text/css\">
1470 p { font-weight: normal; color: gray; }
1471 h1 { color: black; }
1472 .title { text-align: center; }
1473 .todo, .deadline { color: red; }
1474 .done { color: green; }
1475 </style>
1476
1477 or, if you want to keep the style in a file,
1478
1479 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1480
1481 As the value of this option simply gets inserted into the HTML <head> header,
1482 you can \"misuse\" it to add arbitrary text to the header."
1483 :group 'org-export
1484 :type 'string)
1485
1486 (defcustom org-export-headline-levels 3
1487 "The last level which is still exported as a headline.
1488 Inferior levels will produce itemize lists when exported.
1489 Note that a numeric prefix argument to an exporter function overrides
1490 this setting.
1491
1492 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1493 :group 'org-export
1494 :type 'number)
1495
1496 (defcustom org-export-with-section-numbers t
1497 "Non-nil means, add section numbers to headlines when exporting.
1498
1499 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1500 :group 'org-export
1501 :type 'boolean)
1502
1503 (defcustom org-export-with-toc t
1504 "Non-nil means, create a table of contents in exported files.
1505 The TOC contains headlines with levels up to`org-export-headline-levels'.
1506
1507 Headlines which contain any TODO items will be marked with \"(*)\" in
1508 ASCII export, and with red color in HTML output.
1509
1510 In HTML output, the TOC will be clickable.
1511
1512 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1513 :group 'org-export
1514 :type 'boolean)
1515
1516 (defcustom org-export-plain-list-max-depth 20
1517 "Maximum depth of hand-formatted lists in HTML export.
1518
1519 Org-mode parses hand-formatted enumeration and bullet lists and
1520 transforms them to HTML open export. Different indentation of the
1521 bullet or number indicates different list nesting levels. To avoid
1522 confusion, only a single level is allowed by default. When this is
1523 larger than 1, deeper indentation leads to deeper list nesting. For
1524 example, the default value of 3 allows the following list to be
1525 formatted correctly in HTML:
1526
1527 * Fruit
1528 - Apple
1529 - Banana
1530 1. from Africa
1531 2. from South America
1532 - Pineapple
1533 * Bread
1534 * Dairy products"
1535 :group 'org-export
1536 :type 'integer)
1537
1538 (defcustom org-export-preserve-breaks nil
1539 "Non-nil means, preserve all line breaks when exporting.
1540 Normally, in HTML output paragraphs will be reformatted. In ASCII
1541 export, line breaks will always be preserved, regardless of this variable.
1542
1543 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1544 :group 'org-export
1545 :type 'boolean)
1546
1547 (defcustom org-export-html-inline-images t
1548 "Non-nil means, inline images into exported HTML pages.
1549 The link will still be to the original location of the image file.
1550 So if you are moving the page, lets say to your public HTML site,
1551 you will have to move the image and maybe change the link."
1552 :group 'org-export
1553 :type 'boolean)
1554
1555 (defcustom org-export-html-expand t
1556 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1557 When nil, these tags will be exported as plain text and therefore
1558 not be interpreted by a browser.
1559
1560 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1561 :group 'org-export
1562 :type 'boolean)
1563
1564 (defcustom org-export-with-fixed-width t
1565 "Non-nil means, lines starting with \":\" will be in fixed width font.
1566 This can be used to have pre-formatted text, fragments of code etc. For
1567 example:
1568 : ;; Some Lisp examples
1569 : (while (defc cnt)
1570 : (ding))
1571 will be looking just like this in also HTML. In ASCII export, this option
1572 has no effect.
1573
1574 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1575 :group 'org-export
1576 :type 'boolean)
1577
1578 (defcustom org-export-with-tables t
1579 "If non-nil, lines starting with \"|\" define a table.
1580 For example:
1581
1582 | Name | Address | Birthday |
1583 |-------------+----------+-----------|
1584 | Arthur Dent | England | 29.2.2100 |
1585
1586 In ASCII export, this option has no effect.
1587
1588 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1589 :group 'org-export
1590 :type 'boolean)
1591
1592 (defcustom org-export-table-remove-special-lines t
1593 "Remove special lines and marking characters in calculating tables.
1594 This removes the special marking character column from tables that are set
1595 up for spreadsheet calculations. It also removes the entire lines
1596 marked with `!', `_', or `^'. The lines with `$' are kept, because
1597 the values of constants may be useful to have."
1598 :group 'org-export
1599 :type 'boolean)
1600
1601 (defcustom org-export-prefer-native-exporter-for-tables nil
1602 "Non-nil means, always export tables created with table.el natively.
1603 Natively means, use the HTML code generator in table.el.
1604 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1605 the table does not use row- or column-spanning). This has the
1606 advantage, that the automatic HTML conversions for math symbols and
1607 sub/superscripts can be applied. Org-mode's HTML generator is also
1608 much faster."
1609 :group 'org-export
1610 :type 'boolean)
1611
1612 (defcustom org-export-html-table-tag
1613 "<table border=1 cellspacing=0 cellpadding=6>"
1614 "The HTML tag used to start a table.
1615 This must be a <table> tag, but you may change the options like
1616 borders and spacing."
1617 :group 'org-export
1618 :type 'string)
1619
1620 (defcustom org-export-with-emphasize t
1621 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1622 If the export target supports emphasizing text, the word will be
1623 typeset in bold, italic, or underlined, respectively. Works only for
1624 single words, but you can say: I *really* *mean* *this*.
1625 In ASCII export, this option has no effect.
1626
1627 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1628 :group 'org-export
1629 :type 'boolean)
1630
1631 (defcustom org-match-sexp-depth 3
1632 "Number of stacked braces for sub/superscript matching.
1633 This has to be set before loading org.el to be effective."
1634 :group 'org-export
1635 :type 'integer)
1636
1637 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1638 (defcustom org-export-with-sub-superscripts t
1639 "Non-nil means, interpret \"_\" and \"^\" for export.
1640 When this option is turned on, you can use TeX-like syntax for sub- and
1641 superscripts. Several characters after \"_\" or \"^\" will be
1642 considered as a single item - so grouping with {} is normally not
1643 needed. For example, the following things will be parsed as single
1644 sub- or superscripts.
1645
1646 10^24 or 10^tau several digits will be considered 1 item.
1647 10^-12 or 10^-tau a leading sign with digits or a word
1648 x^2-y^3 will be read as x^2 - y^3, because items are
1649 terminated by almost any nonword/nondigit char.
1650 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1651
1652 Still, ambiguity is possible - so when in doubt use {} to enclose the
1653 sub/superscript.
1654 In ASCII export, this option has no effect.
1655
1656 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1657 :group 'org-export
1658 :type 'boolean)
1659
1660 (defcustom org-export-with-TeX-macros t
1661 "Non-nil means, interpret simple TeX-like macros when exporting.
1662 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1663 No only real TeX macros will work here, but the standard HTML entities
1664 for math can be used as macro names as well. For a list of supported
1665 names in HTML export, see the constant `org-html-entities'.
1666 In ASCII export, this option has no effect.
1667
1668 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1669 :group 'org-export
1670 :type 'boolean)
1671
1672 (defcustom org-export-html-with-timestamp nil
1673 "If non-nil, write `org-export-html-html-helper-timestamp'
1674 into the exported HTML text. Otherwise, the buffer will just be saved
1675 to a file."
1676 :group 'org-export
1677 :type 'boolean)
1678
1679 (defcustom org-export-html-html-helper-timestamp
1680 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1681 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1682 :group 'org-export
1683 :type 'string)
1684
1685 (defcustom org-export-ascii-show-new-buffer t
1686 "Non-nil means, popup buffer containing the exported ASCII text.
1687 Otherwise the buffer will just be saved to a file and stay hidden."
1688 :group 'org-export
1689 :type 'boolean)
1690
1691 (defcustom org-export-html-show-new-buffer nil
1692 "Non-nil means, popup buffer containing the exported html text.
1693 Otherwise, the buffer will just be saved to a file and stay hidden."
1694 :group 'org-export
1695 :type 'boolean)
1696
1697 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1698 "The file name for the iCalendar file covering all agenda files.
1699 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1700 :group 'org-export
1701 :type 'file)
1702
1703 (defcustom org-icalendar-include-todo nil
1704 "Non-nil means, export to iCalendar files should also cover TODO items."
1705 :group 'org-export
1706 :type 'boolean)
1707
1708 (defcustom org-icalendar-combined-name "OrgMode"
1709 "Calendar name for the combined iCalendar representing all agenda files."
1710 :group 'org-export
1711 :type 'string)
1712
1713 (defgroup org-faces nil
1714 "Faces for highlighting in Org-mode."
1715 :tag "Org Faces"
1716 :group 'org)
1717
1718 (defface org-hide
1719 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1720 (((class color) (background light)) (:foreground "white"))
1721 (((class color) (background dark)) (:foreground "black"))
1722 ; (((class color) (background light)) (:foreground "grey90"))
1723 ; (((class color) (background dark)) (:foreground "grey10"))
1724 (t (:inverse-video nil)))
1725 "Face used for level 1 headlines."
1726 :group 'org-faces)
1727
1728 (defface org-level-1 ;; font-lock-function-name-face
1729 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1730 (((class color) (background light)) (:foreground "Blue"))
1731 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1732 (t (:inverse-video t :bold t)))
1733 "Face used for level 1 headlines."
1734 :group 'org-faces)
1735
1736 (defface org-level-2 ;; font-lock-variable-name-face
1737 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1738 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1739 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1740 (t (:bold t :italic t)))
1741 "Face used for level 2 headlines."
1742 :group 'org-faces)
1743
1744 (defface org-level-3 ;; font-lock-keyword-face
1745 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1746 (((class color) (background light)) (:foreground "Purple"))
1747 (((class color) (background dark)) (:foreground "Cyan"))
1748 (t (:bold t)))
1749 "Face used for level 3 headlines."
1750 :group 'org-faces)
1751
1752 (defface org-level-4 ;; font-lock-comment-face
1753 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1754 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1755 (((class color) (background light)) (:foreground "Firebrick"))
1756 (((class color) (background dark)) (:foreground "chocolate1"))
1757 (t (:bold t :italic t)))
1758 "Face used for level 4 headlines."
1759 :group 'org-faces)
1760
1761 (defface org-level-5 ;; font-lock-type-face
1762 '((((type tty) (class color)) (:foreground "green"))
1763 (((class color) (background light)) (:foreground "ForestGreen"))
1764 (((class color) (background dark)) (:foreground "PaleGreen"))
1765 (t (:bold t :underline t)))
1766 "Face used for level 5 headlines."
1767 :group 'org-faces)
1768
1769 (defface org-level-6 ;; font-lock-constant-face
1770 '((((type tty) (class color)) (:foreground "magenta"))
1771 (((class color) (background light)) (:foreground "CadetBlue"))
1772 (((class color) (background dark)) (:foreground "Aquamarine"))
1773 (t (:bold t :underline t)))
1774 "Face used for level 6 headlines."
1775 :group 'org-faces)
1776
1777 (defface org-level-7 ;; font-lock-builtin-face
1778 '((((type tty) (class color)) (:foreground "blue" :weight light))
1779 (((class color) (background light)) (:foreground "Orchid"))
1780 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1781 (t (:bold t)))
1782 "Face used for level 7 headlines."
1783 :group 'org-faces)
1784
1785 (defface org-level-8 ;; font-lock-string-face
1786 '((((type tty) (class color)) (:foreground "green"))
1787 (((class color) (background light)) (:foreground "RosyBrown"))
1788 (((class color) (background dark)) (:foreground "LightSalmon"))
1789 (t (:italic t)))
1790 "Face used for level 8 headlines."
1791 :group 'org-faces)
1792
1793 (defface org-special-keyword ;; font-lock-string-face
1794 '((((type tty) (class color)) (:foreground "green"))
1795 (((class color) (background light)) (:foreground "RosyBrown"))
1796 (((class color) (background dark)) (:foreground "LightSalmon"))
1797 (t (:italic t)))
1798 "Face used for special keywords."
1799 :group 'org-faces)
1800
1801 (defface org-warning ;; font-lock-warning-face
1802 '((((type tty) (class color)) (:foreground "red"))
1803 (((class color) (background light)) (:foreground "Red" :bold t))
1804 (((class color) (background dark)) (:foreground "Red1" :bold t))
1805 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1806 (t (:inverse-video t :bold t)))
1807 "Face for deadlines and TODO keywords."
1808 :group 'org-faces)
1809
1810 (defcustom org-fontify-done-headline nil
1811 "Non-nil means, change the face of a headline if it is marked DONE.
1812 Normally, only the TODO/DONE keyword indicates the state of a headline.
1813 When this is non-nil, the headline after the keyword is set to the
1814 `org-headline-done' as an additional indication."
1815 :group 'org-faces
1816 :type 'boolean)
1817
1818 (defface org-headline-done ;; font-lock-string-face
1819 '((((type tty) (class color)) (:foreground "green"))
1820 (((class color) (background light)) (:foreground "RosyBrown"))
1821 (((class color) (background dark)) (:foreground "LightSalmon"))
1822 (t (:italic t)))
1823 "Face used to indicate that a headline is DONE. See also the variable
1824 `org-fontify-done-headline'."
1825 :group 'org-faces)
1826
1827 ;; Inheritance does not yet work for xemacs. So we just copy...
1828
1829 (defface org-deadline-announce
1830 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1831 (((class color) (background light)) (:foreground "Blue"))
1832 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1833 (t (:inverse-video t :bold t)))
1834 "Face for upcoming deadlines."
1835 :group 'org-faces)
1836
1837 (defface org-scheduled-today
1838 '((((type tty) (class color)) (:foreground "green"))
1839 (((class color) (background light)) (:foreground "DarkGreen"))
1840 (((class color) (background dark)) (:foreground "PaleGreen"))
1841 (t (:bold t :underline t)))
1842 "Face for items scheduled for a certain day."
1843 :group 'org-faces)
1844
1845 (defface org-scheduled-previously
1846 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1847 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1848 (((class color) (background light)) (:foreground "Firebrick"))
1849 (((class color) (background dark)) (:foreground "chocolate1"))
1850 (t (:bold t :italic t)))
1851 "Face for items scheduled previously, and not yet done."
1852 :group 'org-faces)
1853
1854 (defface org-formula
1855 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1856 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1857 (((class color) (background light)) (:foreground "Firebrick"))
1858 (((class color) (background dark)) (:foreground "chocolate1"))
1859 (t (:bold t :italic t)))
1860 "Face for formulas."
1861 :group 'org-faces)
1862
1863 (defface org-link
1864 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1865 (((class color) (background light)) (:foreground "Purple"))
1866 (((class color) (background dark)) (:foreground "Cyan"))
1867 (t (:bold t)))
1868 "Face for links."
1869 :group 'org-faces)
1870
1871 (defface org-tag
1872 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1873 (((class color) (background light)) (:foreground "Purple" :weight bold))
1874 (((class color) (background dark)) (:foreground "Cyan" :weight bold))
1875 (t (:bold t)))
1876 "Face for links."
1877 :group 'org-faces)
1878
1879 (defface org-done ;; font-lock-type-face
1880 '((((type tty) (class color)) (:foreground "green"))
1881 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1882 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1883 (t (:bold t :underline t)))
1884 "Face used for DONE."
1885 :group 'org-faces)
1886
1887 (defface org-table ;; font-lock-function-name-face
1888 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1889 (((class color) (background light)) (:foreground "Blue"))
1890 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1891 (t (:inverse-video t :bold t)))
1892 "Face used for tables."
1893 :group 'org-faces)
1894
1895 (defface org-time-grid ;; font-lock-variable-name-face
1896 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1897 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1898 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1899 (t (:bold t :italic t)))
1900 "Face used for time grids."
1901 :group 'org-faces)
1902
1903 (defvar org-level-faces
1904 '(org-level-1 org-level-2 org-level-3 org-level-4
1905 org-level-5 org-level-6 org-level-7 org-level-8
1906 ))
1907 (defvar org-n-levels (length org-level-faces))
1908
1909 (defun org-set-regexps-and-options ()
1910 "Precompute regular expressions for current buffer."
1911 (when (eq major-mode 'org-mode)
1912 (let ((re (org-make-options-regexp
1913 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1914 "STARTUP" "ARCHIVE")))
1915 (splitre "[ \t]+")
1916 kwds int key value cat arch)
1917 (save-excursion
1918 (save-restriction
1919 (widen)
1920 (goto-char (point-min))
1921 (while (re-search-forward re nil t)
1922 (setq key (match-string 1) value (match-string 2))
1923 (cond
1924 ((equal key "CATEGORY")
1925 (if (string-match "[ \t]+$" value)
1926 (setq value (replace-match "" t t value)))
1927 (setq cat (intern value)))
1928 ((equal key "SEQ_TODO")
1929 (setq int 'sequence
1930 kwds (append kwds (org-split-string value splitre))))
1931 ((equal key "PRI_TODO")
1932 (setq int 'priority
1933 kwds (append kwds (org-split-string value splitre))))
1934 ((equal key "TYP_TODO")
1935 (setq int 'type
1936 kwds (append kwds (org-split-string value splitre))))
1937 ((equal key "STARTUP")
1938 (let ((opts (org-split-string value splitre))
1939 (set '(("fold" org-startup-folded t)
1940 ("nofold" org-startup-folded nil)
1941 ("content" org-startup-folded content)
1942 ("dlcheck" org-startup-with-deadline-check t)
1943 ("nodlcheck" org-startup-with-deadline-check nil)))
1944 l var val)
1945 (while (setq l (assoc (pop opts) set))
1946 (setq var (nth 1 l) val (nth 2 l))
1947 (set (make-local-variable var) val))))
1948 ((equal key "ARCHIVE")
1949 (string-match " *$" value)
1950 (setq arch (replace-match "" t t value))
1951 (remove-text-properties 0 (length arch)
1952 '(face t fontified t) arch)))
1953 )))
1954 (and cat (set (make-local-variable 'org-category) cat))
1955 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1956 (and arch (set (make-local-variable 'org-archive-location) arch))
1957 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1958 ;; Compute the regular expressions and other local variables
1959 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1960 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1961 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1962 (length org-scheduled-string)))
1963 org-done-string
1964 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1965 org-todo-regexp
1966 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1967 "\\|") "\\)\\>")
1968 org-not-done-regexp
1969 (concat "\\<\\("
1970 (mapconcat 'regexp-quote
1971 (nreverse (cdr (reverse org-todo-keywords)))
1972 "\\|")
1973 "\\)\\>")
1974 org-todo-line-regexp
1975 (concat "^\\(\\*+\\)[ \t]*\\("
1976 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1977 "\\)? *\\(.*\\)")
1978 org-nl-done-regexp
1979 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1980 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1981 org-deadline-regexp (concat "\\<" org-deadline-string)
1982 org-deadline-time-regexp
1983 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1984 org-deadline-line-regexp
1985 (concat "\\<\\(" org-deadline-string "\\).*")
1986 org-scheduled-regexp
1987 (concat "\\<" org-scheduled-string)
1988 org-scheduled-time-regexp
1989 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1990 (org-set-font-lock-defaults)))
1991
1992 ;; Tell the compiler about dynamically scoped variables,
1993 ;; and variables from other packages
1994 (defvar zmacs-regions)
1995 (defvar original-date)
1996 (defvar org-transient-mark-mode)
1997 (defvar org-old-auto-fill-inhibit-regexp)
1998 (defvar orgtbl-mode-menu)
1999 (defvar org-html-entities)
2000 (defvar org-goto-start-pos)
2001 (defvar org-cursor-color)
2002 (defvar org-time-was-given)
2003 (defvar org-ts-what)
2004 (defvar mark-active)
2005 (defvar timecnt)
2006 (defvar levels-open)
2007 (defvar title)
2008 (defvar author)
2009 (defvar email)
2010 (defvar text)
2011 (defvar entry)
2012 (defvar date)
2013 (defvar language)
2014 (defvar options)
2015 (defvar ans1)
2016 (defvar ans2)
2017 (defvar starting-day)
2018 (defvar include-all-loc)
2019 (defvar vm-message-pointer)
2020 (defvar vm-folder-directory)
2021 (defvar wl-summary-buffer-elmo-folder)
2022 (defvar wl-summary-buffer-folder-name)
2023 (defvar gnus-group-name)
2024 (defvar gnus-article-current)
2025 (defvar w3m-current-url)
2026 (defvar mh-progs)
2027 (defvar mh-current-folder)
2028 (defvar mh-show-folder-buffer)
2029 (defvar mh-index-folder)
2030 (defvar mh-searcher)
2031 (defvar org-selected-point)
2032 (defvar calendar-mode-map)
2033 (defvar remember-save-after-remembering)
2034 (defvar remember-data-file)
2035 (defvar last-arg)
2036
2037 ;;; Define the mode
2038
2039 (defvar org-mode-map (copy-keymap outline-mode-map)
2040 "Keymap for Org-mode.")
2041
2042 (defvar org-struct-menu)
2043 (defvar org-org-menu)
2044 (defvar org-tbl-menu)
2045
2046 ;; We use a before-change function to check if a table might need
2047 ;; an update.
2048 (defvar org-table-may-need-update t
2049 "Indicates that a table might need an update.
2050 This variable is set by `org-before-change-function'.
2051 `org-table-align' sets it back to nil.")
2052 (defvar org-mode-hook nil)
2053 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2054 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2055
2056
2057 ;;;###autoload
2058 (define-derived-mode org-mode outline-mode "Org"
2059 "Outline-based notes management and organizer, alias
2060 \"Carsten's outline-mode for keeping track of everything.\"
2061
2062 Org-mode develops organizational tasks around a NOTES file which
2063 contains information about projects as plain text. Org-mode is
2064 implemented on top of outline-mode, which is ideal to keep the content
2065 of large files well structured. It supports ToDo items, deadlines and
2066 time stamps, which magically appear in the diary listing of the Emacs
2067 calendar. Tables are easily created with a built-in table editor.
2068 Plain text URL-like links connect to websites, emails (VM), Usenet
2069 messages (Gnus), BBDB entries, and any files related to the project.
2070 For printing and sharing of notes, an Org-mode file (or a part of it)
2071 can be exported as a structured ASCII or HTML file.
2072
2073 The following commands are available:
2074
2075 \\{org-mode-map}"
2076 (easy-menu-add org-org-menu)
2077 (easy-menu-add org-tbl-menu)
2078 (org-install-agenda-files-menu)
2079 (setq outline-regexp "\\*+")
2080 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2081 (setq outline-level 'org-outline-level)
2082 (if org-startup-truncated (setq truncate-lines t))
2083 (org-set-regexps-and-options)
2084 (set (make-local-variable 'font-lock-unfontify-region-function)
2085 'org-unfontify-region)
2086 ;; Activate before-change-function
2087 (set (make-local-variable 'org-table-may-need-update) t)
2088 (org-add-hook 'before-change-functions 'org-before-change-function nil
2089 'local)
2090 ;; Paragraphs and auto-filling
2091 (org-set-autofill-regexps)
2092 (org-update-radio-target-regexp)
2093 ;; Settings for Calc embedded mode
2094 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2095 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2096 (if (and org-insert-mode-line-in-empty-file
2097 (interactive-p)
2098 (= (point-min) (point-max)))
2099 (insert " -*- mode: org -*-\n\n"))
2100
2101 ;; Get rid of Outline menus, they are not needed
2102 ;; Need to do this here because define-derived-mode sets up
2103 ;; the keymap so late.
2104 (if org-xemacs-p
2105 (progn
2106 (delete-menu-item '("Headings"))
2107 (delete-menu-item '("Show"))
2108 (delete-menu-item '("Hide"))
2109 (set-menubar-dirty-flag))
2110 (define-key org-mode-map [menu-bar headings] 'undefined)
2111 (define-key org-mode-map [menu-bar hide] 'undefined)
2112 (define-key org-mode-map [menu-bar show] 'undefined))
2113
2114 (unless org-inhibit-startup
2115 (if org-startup-with-deadline-check
2116 (call-interactively 'org-check-deadlines)
2117 (cond
2118 ((eq org-startup-folded t)
2119 (org-cycle '(4)))
2120 ((eq org-startup-folded 'content)
2121 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2122 (org-cycle '(4)) (org-cycle '(4))))))))
2123
2124 (defsubst org-current-line (&optional pos)
2125 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2126
2127
2128 ;; FIXME: Do we need to copy?
2129 (defun org-string-props (string &rest properties)
2130 "Add PROPERTIES to string."
2131 (add-text-properties 0 (length string) properties string)
2132 string)
2133
2134 ;;; Font-Lock stuff
2135
2136 (defvar org-mouse-map (make-sparse-keymap))
2137 (define-key org-mouse-map
2138 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2139 (define-key org-mouse-map
2140 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2141 (define-key org-mouse-map [follow-link] 'mouse-face)
2142 (when org-tab-follows-link
2143 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2144 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2145 (when org-return-follows-link
2146 (define-key org-mouse-map [(return)] 'org-open-at-point)
2147 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2148
2149 (require 'font-lock)
2150
2151 (defconst org-non-link-chars "\t\n\r|<>\000")
2152 (defconst org-link-regexp
2153 (if org-allow-space-in-links
2154 (concat
2155 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2156 (concat
2157 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2158 )
2159 "Regular expression for matching links.")
2160 (defconst org-link-maybe-angles-regexp
2161 (concat "<?\\(" org-link-regexp "\\)>?")
2162 "Matches a link and optionally surrounding angle brackets.")
2163 (defconst org-protected-link-regexp
2164 (concat "\000" org-link-regexp "\000")
2165 "Matches a link and optionally surrounding angle brackets.")
2166
2167 (defconst org-bracket-link-regexp
2168 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2169 "Matches a link in double brackets.")
2170
2171 (defconst org-ts-lengths
2172 (cons (length (format-time-string (car org-time-stamp-formats)))
2173 (length (format-time-string (cdr org-time-stamp-formats))))
2174 "This holds the lengths of the two different time formats.")
2175 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2176 "Regular expression for fast time stamp matching.")
2177 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2178 "Regular expression for fast time stamp matching.")
2179 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2180 "Regular expression matching time strings for analysis.")
2181 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2182 "Regular expression matching time stamps, with groups.")
2183 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2184 "Regular expression matching a time stamp range.")
2185 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2186 org-ts-regexp "\\)?")
2187 "Regular expression matching a time stamp or time stamp range.")
2188
2189 (defun org-activate-links (limit)
2190 "Run through the buffer and add overlays to links."
2191 (if (re-search-forward org-link-regexp limit t)
2192 (progn
2193 (add-text-properties (match-beginning 0) (match-end 0)
2194 (list 'mouse-face 'highlight
2195 'keymap org-mouse-map))
2196 t)))
2197
2198 (defun org-activate-links2 (limit)
2199 "Run through the buffer and add overlays to links."
2200 (if (re-search-forward org-bracket-link-regexp limit t)
2201 (progn
2202 (add-text-properties (match-beginning 0) (match-end 0)
2203 (list 'mouse-face 'highlight
2204 'keymap org-mouse-map))
2205 t)))
2206
2207 (defun org-activate-dates (limit)
2208 "Run through the buffer and add overlays to dates."
2209 (if (re-search-forward org-tsr-regexp limit t)
2210 (progn
2211 (add-text-properties (match-beginning 0) (match-end 0)
2212 (list 'mouse-face 'highlight
2213 'keymap org-mouse-map))
2214 t)))
2215
2216 (defvar org-target-link-regexp nil
2217 "Regular expression matching radio targets in plain text.")
2218 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2219 "Regular expression matching a link target.")
2220 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2221 "Regular expression matching a link target.")
2222
2223 (defun org-activate-target-links (limit)
2224 "Run through the buffer and add overlays to target matches."
2225 (when (and org-radio-targets org-target-link-regexp)
2226 (let ((case-fold-search t))
2227 (if (re-search-forward org-target-link-regexp limit t)
2228 (progn
2229 (add-text-properties (match-beginning 0) (match-end 0)
2230 (list 'mouse-face 'highlight
2231 'keymap org-mouse-map
2232 'org-linked-text t))
2233 t)))))
2234
2235 (defun org-update-radio-target-regexp ()
2236 "Find all radio targets in this file and update the regular expression."
2237 (interactive)
2238 (when org-radio-targets
2239 (setq org-target-link-regexp
2240 (org-make-target-link-regexp (org-all-targets 'radio)))
2241 (font-lock-mode -1)
2242 (font-lock-mode 1)))
2243
2244 (defun org-all-targets (&optional radio)
2245 "Return a list of all targets in this file.
2246 With optional argument RADIO, only find radio targets."
2247 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2248 rtn)
2249 (save-excursion
2250 (goto-char (point-min))
2251 (while (re-search-forward re nil t)
2252 (add-to-list 'rtn (downcase
2253 (if (fboundp 'match-string-no-properties)
2254 (match-string-no-properties 1)
2255 (match-string 1)))))
2256 rtn)))
2257
2258 (defun org-make-target-link-regexp (targets)
2259 "Make regular expression matching all strings in TARGETS.
2260 The regular expression finds the targets also if there is a line break
2261 between words."
2262 (and targets
2263 (concat
2264 "\\<\\("
2265 (mapconcat
2266 (lambda (x)
2267 (while (string-match " +" x)
2268 (setq x (replace-match "\\s-+" t t x)))
2269 x)
2270 targets
2271 "\\|")
2272 "\\)\\>")))
2273
2274 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2275 "Matches CamelCase words, possibly with a star before it.")
2276
2277 (defun org-activate-camels (limit)
2278 "Run through the buffer and add overlays to dates."
2279 (if org-activate-camels
2280 (if (re-search-forward org-camel-regexp limit t)
2281 (progn
2282 (add-text-properties (match-beginning 0) (match-end 0)
2283 (list 'mouse-face 'highlight
2284 'keymap org-mouse-map))
2285 t))))
2286
2287 (defun org-activate-tags (limit)
2288 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2289 (progn
2290 (add-text-properties (match-beginning 1) (match-end 1)
2291 (list 'mouse-face 'highlight
2292 'keymap org-mouse-map))
2293 t)))
2294
2295 (defun org-font-lock-level ()
2296 (save-excursion
2297 (org-back-to-heading t)
2298 (- (match-end 0) (match-beginning 0))))
2299
2300 (defun org-outline-level ()
2301 (save-excursion
2302 (looking-at outline-regexp)
2303 (if (match-beginning 1)
2304 (+ (org-get-string-indentation (match-string 1)) 1000)
2305 (- (match-end 0) (match-beginning 0)))))
2306
2307 (defvar org-font-lock-keywords nil)
2308
2309 (defun org-set-font-lock-defaults ()
2310 (let ((org-font-lock-extra-keywords
2311 (list
2312 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2313 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2314 '(org-activate-links (0 'org-link t))
2315 '(org-activate-links2 (0 'org-link t))
2316 '(org-activate-target-links (0 'org-link t))
2317 '(org-activate-dates (0 'org-link t))
2318 '(org-activate-camels (0 'org-link t))
2319 '(org-activate-tags (1 'org-tag t))
2320 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2321 '(1 'org-warning t))
2322 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2323 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2324 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2325 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2326 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2327 ;; (3 'bold))
2328 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2329 ;; (3 'italic))
2330 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2331 ;; (3 'underline))
2332 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2333 "\\|" org-quote-string "\\)\\>")
2334 '(1 'org-special-keyword t))
2335 '("^#.*" (0 'font-lock-comment-face t))
2336 (if org-fontify-done-headline
2337 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2338 '(1 'org-done t) '(2 'org-headline-done t))
2339 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2340 '(1 'org-done t)))
2341 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2342 (1 'org-table t))
2343 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2344 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2345 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2346 )))
2347
2348 ;; Now set the full font-lock-keywords
2349 (set (make-local-variable 'org-font-lock-keywords)
2350 org-font-lock-extra-keywords)
2351 (set (make-local-variable 'font-lock-defaults)
2352 '(org-font-lock-keywords t nil nil backward-paragraph))
2353 (kill-local-variable 'font-lock-keywords) nil))
2354
2355 (defvar org-m nil)
2356 (defvar org-l nil)
2357 (defvar org-f nil)
2358 (defun org-get-level-face (n)
2359 "Get the right face for match N in font-lock matching of healdines."
2360 (setq org-l (- (match-end 2) (match-beginning 1)))
2361 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2362 (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2363 (cond
2364 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2365 ((eq n 2) org-f)
2366 (t (if org-level-color-stars-only nil org-f))))
2367
2368 (defun org-unfontify-region (beg end &optional maybe_loudly)
2369 "Remove fontification and activation overlays from links."
2370 (font-lock-default-unfontify-region beg end)
2371 (let* ((buffer-undo-list t)
2372 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2373 (inhibit-modification-hooks t)
2374 deactivate-mark buffer-file-name buffer-file-truename)
2375 (remove-text-properties beg end
2376 '(mouse-face nil keymap nil org-linked-text nil))))
2377
2378 ;;; Visibility cycling
2379
2380 (defvar org-cycle-global-status nil)
2381 (defvar org-cycle-subtree-status nil)
2382 (defun org-cycle (&optional arg)
2383 "Visibility cycling for Org-mode.
2384
2385 - When this function is called with a prefix argument, rotate the entire
2386 buffer through 3 states (global cycling)
2387 1. OVERVIEW: Show only top-level headlines.
2388 2. CONTENTS: Show all headlines of all levels, but no body text.
2389 3. SHOW ALL: Show everything.
2390
2391 - When point is at the beginning of a headline, rotate the subtree started
2392 by this line through 3 different states (local cycling)
2393 1. FOLDED: Only the main headline is shown.
2394 2. CHILDREN: The main headline and the direct children are shown.
2395 From this state, you can move to one of the children
2396 and zoom in further.
2397 3. SUBTREE: Show the entire subtree, including body text.
2398
2399 - When there is a numeric prefix, go up to a heading with level ARG, do
2400 a `show-subtree' and return to the previous cursor position. If ARG
2401 is negative, go up that many levels.
2402
2403 - When point is not at the beginning of a headline, execute
2404 `indent-relative', like TAB normally does. See the option
2405 `org-cycle-emulate-tab' for details.
2406
2407 - Special case: if point is the the beginning of the buffer and there is
2408 no headline in line 1, this function will act as if called with prefix arg."
2409 (interactive "P")
2410
2411 (if (or (and (bobp) (not (looking-at outline-regexp)))
2412 (equal arg '(4)))
2413 ;; special case: use global cycling
2414 (setq arg t))
2415
2416 (let ((outline-regexp
2417 (if org-cycle-include-plain-lists
2418 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2419 outline-regexp)))
2420
2421 (cond
2422
2423 ((org-at-table-p 'any)
2424 ;; Enter the table or move to the next field in the table
2425 (or (org-table-recognize-table.el)
2426 (progn
2427 (org-table-justify-field-maybe)
2428 (org-table-next-field))))
2429
2430 ((eq arg t) ;; Global cycling
2431
2432 (cond
2433 ((and (eq last-command this-command)
2434 (eq org-cycle-global-status 'overview))
2435 ;; We just created the overview - now do table of contents
2436 ;; This can be slow in very large buffers, so indicate action
2437 (message "CONTENTS...")
2438 (save-excursion
2439 ;; Visit all headings and show their offspring
2440 (goto-char (point-max))
2441 (catch 'exit
2442 (while (and (progn (condition-case nil
2443 (outline-previous-visible-heading 1)
2444 (error (goto-char (point-min))))
2445 t)
2446 (looking-at outline-regexp))
2447 (show-branches)
2448 (if (bobp) (throw 'exit nil))))
2449 (message "CONTENTS...done"))
2450 (setq org-cycle-global-status 'contents)
2451 (run-hook-with-args 'org-cycle-hook 'contents))
2452
2453 ((and (eq last-command this-command)
2454 (eq org-cycle-global-status 'contents))
2455 ;; We just showed the table of contents - now show everything
2456 (show-all)
2457 (message "SHOW ALL")
2458 (setq org-cycle-global-status 'all)
2459 (run-hook-with-args 'org-cycle-hook 'all))
2460
2461 (t
2462 ;; Default action: go to overview
2463 (hide-sublevels 1)
2464 (message "OVERVIEW")
2465 (setq org-cycle-global-status 'overview)
2466 (run-hook-with-args 'org-cycle-hook 'overview))))
2467
2468 ((integerp arg)
2469 ;; Show-subtree, ARG levels up from here.
2470 (save-excursion
2471 (org-back-to-heading)
2472 (outline-up-heading (if (< arg 0) (- arg)
2473 (- (funcall outline-level) arg)))
2474 (org-show-subtree)))
2475
2476 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2477 ;; At a heading: rotate between three different views
2478 (org-back-to-heading)
2479 (let ((goal-column 0) eoh eol eos)
2480 ;; First, some boundaries
2481 (save-excursion
2482 (org-back-to-heading)
2483 (save-excursion
2484 (beginning-of-line 2)
2485 (while (and (not (eobp)) ;; this is like `next-line'
2486 (get-char-property (1- (point)) 'invisible))
2487 (beginning-of-line 2)) (setq eol (point)))
2488 (outline-end-of-heading) (setq eoh (point))
2489 (org-end-of-subtree t) (setq eos (point))
2490 (outline-next-heading))
2491 ;; Find out what to do next and set `this-command'
2492 (cond
2493 ((= eos eoh)
2494 ;; Nothing is hidden behind this heading
2495 (message "EMPTY ENTRY")
2496 (setq org-cycle-subtree-status nil))
2497 ((>= eol eos)
2498 ;; Entire subtree is hidden in one line: open it
2499 (org-show-entry)
2500 (show-children)
2501 (message "CHILDREN")
2502 (setq org-cycle-subtree-status 'children)
2503 (run-hook-with-args 'org-cycle-hook 'children))
2504 ((and (eq last-command this-command)
2505 (eq org-cycle-subtree-status 'children))
2506 ;; We just showed the children, now show everything.
2507 (org-show-subtree)
2508 (message "SUBTREE")
2509 (setq org-cycle-subtree-status 'subtree)
2510 (run-hook-with-args 'org-cycle-hook 'subtree))
2511 (t
2512 ;; Default action: hide the subtree.
2513 (hide-subtree)
2514 (message "FOLDED")
2515 (setq org-cycle-subtree-status 'folded)
2516 (run-hook-with-args 'org-cycle-hook 'folded)))))
2517
2518 ;; TAB emulation
2519 (buffer-read-only (org-back-to-heading))
2520 ((if (and (eq org-cycle-emulate-tab 'white)
2521 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2522 t
2523 (eq org-cycle-emulate-tab t))
2524 (if (and (looking-at "[ \n\r\t]")
2525 (string-match "^[ \t]*$" (buffer-substring
2526 (point-at-bol) (point))))
2527 (progn
2528 (beginning-of-line 1)
2529 (and (looking-at "[ \t]+") (replace-match ""))))
2530 (indent-relative))
2531
2532 (t (save-excursion
2533 (org-back-to-heading)
2534 (org-cycle))))))
2535
2536 (defun org-optimize-window-after-visibility-change (state)
2537 "Adjust the window after a change in outline visibility.
2538 This function is the default value of the hook `org-cycle-hook'."
2539 (cond
2540 ((eq state 'overview) (org-first-headline-recenter 1))
2541 ((eq state 'content) nil)
2542 ((eq state 'all) nil)
2543 ((eq state 'folded) nil)
2544 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2545 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2546
2547 (defun org-subtree-end-visible-p ()
2548 "Is the end of the current subtree visible?"
2549 (pos-visible-in-window-p
2550 (save-excursion (org-end-of-subtree t) (point))))
2551
2552 (defun org-first-headline-recenter (&optional N)
2553 "Move cursor to the first headline and recenter the headline.
2554 Optional argument N means, put the headline into the Nth line of the window."
2555 (goto-char (point-min))
2556 (when (re-search-forward (concat "^" outline-regexp) nil t)
2557 (beginning-of-line)
2558 (recenter (prefix-numeric-value N))))
2559
2560 (defvar org-goto-window-configuration nil)
2561 (defvar org-goto-marker nil)
2562 (defvar org-goto-map (make-sparse-keymap))
2563 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2564 (while (setq cmd (pop cmds))
2565 (substitute-key-definition cmd cmd org-goto-map global-map)))
2566 (define-key org-goto-map "\C-m" 'org-goto-ret)
2567 (define-key org-goto-map [(left)] 'org-goto-left)
2568 (define-key org-goto-map [(right)] 'org-goto-right)
2569 (define-key org-goto-map [(?q)] 'org-goto-quit)
2570 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2571 (define-key org-goto-map "\C-i" 'org-cycle)
2572 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2573 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2574 (define-key org-goto-map "n" 'outline-next-visible-heading)
2575 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2576 (define-key org-goto-map "f" 'outline-forward-same-level)
2577 (define-key org-goto-map "b" 'outline-backward-same-level)
2578 (define-key org-goto-map "u" 'outline-up-heading)
2579 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2580 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2581 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2582 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2583 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2584 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2585 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2586
2587 (defconst org-goto-help
2588 "Select a location to jump to, press RET
2589 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2590
2591 (defun org-goto ()
2592 "Go to a different location of the document, keeping current visibility.
2593
2594 When you want to go to a different location in a document, the fastest way
2595 is often to fold the entire buffer and then dive into the tree. This
2596 method has the disadvantage, that the previous location will be folded,
2597 which may not be what you want.
2598
2599 This command works around this by showing a copy of the current buffer in
2600 overview mode. You can dive into the tree in that copy, to find the
2601 location you want to reach. When pressing RET, the command returns to the
2602 original buffer in which the visibility is still unchanged. It then jumps
2603 to the new location, making it and the headline hierarchy above it visible."
2604 (interactive)
2605 (let* ((org-goto-start-pos (point))
2606 (selected-point
2607 (org-get-location (current-buffer) org-goto-help)))
2608 (if selected-point
2609 (progn
2610 (org-mark-ring-push org-goto-start-pos)
2611 (goto-char selected-point)
2612 (if (or (org-invisible-p) (org-invisible-p2))
2613 (org-show-hierarchy-above)))
2614 (error "Quit"))))
2615
2616 (defun org-get-location (buf help)
2617 "Let the user select a location in the Org-mode buffer BUF.
2618 This function uses a recursive edit. It returns the selected position
2619 or nil."
2620 (let (org-selected-point)
2621 (save-excursion
2622 (save-window-excursion
2623 (delete-other-windows)
2624 (switch-to-buffer (get-buffer-create "*org-goto*"))
2625 (with-output-to-temp-buffer "*Help*"
2626 (princ help))
2627 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2628 (setq buffer-read-only nil)
2629 (erase-buffer)
2630 (insert-buffer-substring buf)
2631 (let ((org-startup-truncated t)
2632 (org-startup-folded t)
2633 (org-startup-with-deadline-check nil))
2634 (org-mode))
2635 (setq buffer-read-only t)
2636 (if (boundp 'org-goto-start-pos)
2637 (goto-char org-goto-start-pos)
2638 (goto-char (point-min)))
2639 (org-beginning-of-line)
2640 (message "Select location and press RET")
2641 ;; now we make sure that during selection, ony very few keys work
2642 ;; and that it is impossible to switch to another window.
2643 (let ((gm (current-global-map))
2644 (overriding-local-map org-goto-map))
2645 (unwind-protect
2646 (progn
2647 (use-global-map org-goto-map)
2648 (recursive-edit))
2649 (use-global-map gm)))))
2650 (kill-buffer "*org-goto*")
2651 org-selected-point))
2652
2653 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2654 (defun org-goto-ret (&optional arg)
2655 "Finish `org-goto' by going to the new location."
2656 (interactive "P")
2657 (setq org-selected-point (point)
2658 current-prefix-arg arg)
2659 (throw 'exit nil))
2660
2661 (defun org-goto-left ()
2662 "Finish `org-goto' by going to the new location."
2663 (interactive)
2664 (if (org-on-heading-p)
2665 (progn
2666 (beginning-of-line 1)
2667 (setq org-selected-point (point)
2668 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2669 (throw 'exit nil))
2670 (error "Not on a heading")))
2671
2672 (defun org-goto-right ()
2673 "Finish `org-goto' by going to the new location."
2674 (interactive)
2675 (if (org-on-heading-p)
2676 (progn
2677 (outline-end-of-subtree)
2678 (or (eobp) (forward-char 1))
2679 (setq org-selected-point (point)
2680 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2681 (throw 'exit nil))
2682 (error "Not on a heading")))
2683
2684 (defun org-goto-quit ()
2685 "Finish `org-goto' without cursor motion."
2686 (interactive)
2687 (setq org-selected-point nil)
2688 (throw 'exit nil))
2689
2690 ;;; Promotion, Demotion, Inserting new headlines
2691
2692 (defvar org-ignore-region nil
2693 "To temporarily disable the active region.")
2694
2695 (defun org-insert-heading (&optional force-heading)
2696 "Insert a new heading or item with same depth at point."
2697 (interactive "P")
2698 (when (or force-heading (not (org-insert-item)))
2699 (let* ((head (save-excursion
2700 (condition-case nil
2701 (org-back-to-heading)
2702 (error (outline-next-heading)))
2703 (prog1 (match-string 0)
2704 (funcall outline-level)))))
2705 (unless (bolp) (newline))
2706 (insert head)
2707 (unless (eolp)
2708 (save-excursion (newline-and-indent)))
2709 (unless (equal (char-before) ?\ )
2710 (insert " "))
2711 (run-hooks 'org-insert-heading-hook))))
2712
2713 (defun org-insert-item ()
2714 "Insert a new item at the current level.
2715 Return t when things worked, nil when we are not in an item."
2716 (when (save-excursion
2717 (condition-case nil
2718 (progn
2719 (org-beginning-of-item)
2720 (org-at-item-p)
2721 t)
2722 (error nil)))
2723 (unless (bolp) (newline))
2724 (insert (match-string 0))
2725 (org-maybe-renumber-ordered-list)
2726 t))
2727
2728 (defun org-insert-todo-heading (arg)
2729 "Insert a new heading with the same level and TODO state as current heading.
2730 If the heading has no TODO state, or if the state is DONE, use the first
2731 state (TODO by default). Also with prefix arg, force first state."
2732 (interactive "P")
2733 (org-insert-heading)
2734 (save-excursion
2735 (org-back-to-heading)
2736 (outline-previous-heading)
2737 (looking-at org-todo-line-regexp))
2738 (if (or arg
2739 (not (match-beginning 2))
2740 (equal (match-string 2) org-done-string))
2741 (insert (car org-todo-keywords) " ")
2742 (insert (match-string 2) " ")))
2743
2744 (defun org-promote-subtree ()
2745 "Promote the entire subtree.
2746 See also `org-promote'."
2747 (interactive)
2748 (save-excursion
2749 (org-map-tree 'org-promote)))
2750
2751 (defun org-demote-subtree ()
2752 "Demote the entire subtree. See `org-demote'.
2753 See also `org-promote'."
2754 (interactive)
2755 (save-excursion
2756 (org-map-tree 'org-demote)))
2757
2758 (defun org-do-promote ()
2759 "Promote the current heading higher up the tree.
2760 If the region is active in `transient-mark-mode', promote all headings
2761 in the region."
2762 (interactive)
2763 (save-excursion
2764 (if (org-region-active-p)
2765 (org-map-region 'org-promote (region-beginning) (region-end))
2766 (org-promote)))
2767 (org-fix-position-after-promote))
2768
2769 (defun org-do-demote ()
2770 "Demote the current heading lower down the tree.
2771 If the region is active in `transient-mark-mode', demote all headings
2772 in the region."
2773 (interactive)
2774 (save-excursion
2775 (if (org-region-active-p)
2776 (org-map-region 'org-demote (region-beginning) (region-end))
2777 (org-demote)))
2778 (org-fix-position-after-promote))
2779
2780 (defun org-fix-position-after-promote ()
2781 "Make sure that after pro/demotion cursor position is right."
2782 (and (equal (char-after) ?\ )
2783 (equal (char-before) ?*)
2784 (forward-char 1)))
2785
2786 (defun org-get-legal-level (level change)
2787 "Rectify a level change under the influence of `org-odd-levels-only'
2788 LEVEL is a current level, CHANGE is by how much the level should be
2789 modified. Even if CHANGE is nil, LEVEL may be returned modified because
2790 even level numbers will become the next higher odd number."
2791 (if org-odd-levels-only
2792 (cond ((not change) (1+ (* 2 (/ level 2))))
2793 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
2794 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
2795 (max 1 (+ level change))))
2796
2797 (defun org-promote ()
2798 "Promote the current heading higher up the tree.
2799 If the region is active in `transient-mark-mode', promote all headings
2800 in the region."
2801 (org-back-to-heading t)
2802 (let* ((level (save-match-data (funcall outline-level)))
2803 (up-head (make-string (org-get-legal-level level -1) ?*))
2804 (diff (abs (- level (length up-head)))))
2805 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2806 (replace-match up-head nil t)
2807 ;; Fixup tag positioning
2808 (and org-auto-align-tags (org-set-tags nil t))
2809 (if org-adapt-indentation
2810 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
2811 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
2812
2813 (defun org-demote ()
2814 "Demote the current heading lower down the tree.
2815 If the region is active in `transient-mark-mode', demote all headings
2816 in the region."
2817 (org-back-to-heading t)
2818 (let* ((level (save-match-data (funcall outline-level)))
2819 (down-head (make-string (org-get-legal-level level 1) ?*))
2820 (diff (abs (- level (length down-head)))))
2821 (replace-match down-head nil t)
2822 ;; Fixup tag positioning
2823 (and org-auto-align-tags (org-set-tags nil t))
2824 (if org-adapt-indentation
2825 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
2826
2827 (defun org-map-tree (fun)
2828 "Call FUN for every heading underneath the current one."
2829 (org-back-to-heading)
2830 (let ((level (funcall outline-level)))
2831 (save-excursion
2832 (funcall fun)
2833 (while (and (progn
2834 (outline-next-heading)
2835 (> (funcall outline-level) level))
2836 (not (eobp)))
2837 (funcall fun)))))
2838
2839 (defun org-map-region (fun beg end)
2840 "Call FUN for every heading between BEG and END."
2841 (let ((org-ignore-region t))
2842 (save-excursion
2843 (setq end (copy-marker end))
2844 (goto-char beg)
2845 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2846 (< (point) end))
2847 (funcall fun))
2848 (while (and (progn
2849 (outline-next-heading)
2850 (< (point) end))
2851 (not (eobp)))
2852 (funcall fun)))))
2853
2854 (defun org-fixup-indentation (from to prohibit)
2855 "Change the indentation in the current entry by re-replacing FROM with TO.
2856 However, if the regexp PROHIBIT matches at all, don't do anything.
2857 This is being used to change indentation along with the length of the
2858 heading marker. But if there are any lines which are not indented, nothing
2859 is changed at all."
2860 (save-excursion
2861 (let ((end (save-excursion (outline-next-heading)
2862 (point-marker))))
2863 (unless (save-excursion (re-search-forward prohibit end t))
2864 (while (re-search-forward from end t)
2865 (replace-match to)
2866 (beginning-of-line 2)))
2867 (move-marker end nil))))
2868
2869 ;;; Vertical tree motion, cutting and pasting of subtrees
2870
2871 (defun org-move-subtree-up (&optional arg)
2872 "Move the current subtree up past ARG headlines of the same level."
2873 (interactive "p")
2874 (org-move-subtree-down (- (prefix-numeric-value arg))))
2875
2876 (defun org-move-subtree-down (&optional arg)
2877 "Move the current subtree down past ARG headlines of the same level."
2878 (interactive "p")
2879 (setq arg (prefix-numeric-value arg))
2880 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2881 'outline-get-last-sibling))
2882 (ins-point (make-marker))
2883 (cnt (abs arg))
2884 beg end txt folded)
2885 ;; Select the tree
2886 (org-back-to-heading)
2887 (setq beg (point))
2888 (save-match-data
2889 (save-excursion (outline-end-of-heading)
2890 (setq folded (org-invisible-p)))
2891 (outline-end-of-subtree))
2892 (outline-next-heading)
2893 (setq end (point))
2894 ;; Find insertion point, with error handling
2895 (goto-char beg)
2896 (while (> cnt 0)
2897 (or (and (funcall movfunc) (looking-at outline-regexp))
2898 (progn (goto-char beg)
2899 (error "Cannot move past superior level or buffer limit")))
2900 (setq cnt (1- cnt)))
2901 (if (> arg 0)
2902 ;; Moving forward - still need to move over subtree
2903 (progn (outline-end-of-subtree)
2904 (outline-next-heading)
2905 (if (not (or (looking-at (concat "^" outline-regexp))
2906 (bolp)))
2907 (newline))))
2908 (move-marker ins-point (point))
2909 (setq txt (buffer-substring beg end))
2910 (delete-region beg end)
2911 (insert txt)
2912 (goto-char ins-point)
2913 (if folded (hide-subtree))
2914 (move-marker ins-point nil)))
2915
2916 (defvar org-subtree-clip ""
2917 "Clipboard for cut and paste of subtrees.
2918 This is actually only a copy of the kill, because we use the normal kill
2919 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2920
2921 (defvar org-subtree-clip-folded nil
2922 "Was the last copied subtree folded?
2923 This is used to fold the tree back after pasting.")
2924
2925 (defun org-cut-subtree ()
2926 "Cut the current subtree into the clipboard.
2927 This is a short-hand for marking the subtree and then cutting it."
2928 (interactive)
2929 (org-copy-subtree 'cut))
2930
2931 (defun org-copy-subtree (&optional cut)
2932 "Cut the current subtree into the clipboard.
2933 This is a short-hand for marking the subtree and then copying it.
2934 If CUT is non nil, actually cut the subtree."
2935 (interactive)
2936 (let (beg end folded)
2937 (org-back-to-heading)
2938 (setq beg (point))
2939 (save-match-data
2940 (save-excursion (outline-end-of-heading)
2941 (setq folded (org-invisible-p)))
2942 (outline-end-of-subtree))
2943 (if (equal (char-after) ?\n) (forward-char 1))
2944 (setq end (point))
2945 (goto-char beg)
2946 (when (> end beg)
2947 (setq org-subtree-clip-folded folded)
2948 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2949 (setq org-subtree-clip (current-kill 0))
2950 (message "%s: Subtree with %d characters"
2951 (if cut "Cut" "Copied")
2952 (length org-subtree-clip)))))
2953
2954 ;; FIXME: this needs to be adapted for the odd-level-only stuff.
2955 (defun org-paste-subtree (&optional level tree)
2956 "Paste the clipboard as a subtree, with modification of headline level.
2957 The entire subtree is promoted or demoted in order to match a new headline
2958 level. By default, the new level is derived from the visible headings
2959 before and after the insertion point, and taken to be the inferior headline
2960 level of the two. So if the previous visible heading is level 3 and the
2961 next is level 4 (or vice versa), level 4 will be used for insertion.
2962 This makes sure that the subtree remains an independent subtree and does
2963 not swallow low level entries.
2964
2965 You can also force a different level, either by using a numeric prefix
2966 argument, or by inserting the heading marker by hand. For example, if the
2967 cursor is after \"*****\", then the tree will be shifted to level 5.
2968
2969 If you want to insert the tree as is, just use \\[yank].
2970
2971 If optional TREE is given, use this text instead of the kill ring."
2972 (interactive "P")
2973 (unless (org-kill-is-subtree-p tree)
2974 (error
2975 (substitute-command-keys
2976 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2977 (let* ((txt (or tree (current-kill 0)))
2978 (^re (concat "^\\(" outline-regexp "\\)"))
2979 (re (concat "\\(" outline-regexp "\\)"))
2980 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2981
2982 (old-level (if (string-match ^re txt)
2983 (- (match-end 0) (match-beginning 0))
2984 -1))
2985 (force-level (cond (level (prefix-numeric-value level))
2986 ((string-match
2987 ^re_ (buffer-substring (point-at-bol) (point)))
2988 (- (match-end 0) (match-beginning 0)))
2989 (t nil)))
2990 (previous-level (save-excursion
2991 (condition-case nil
2992 (progn
2993 (outline-previous-visible-heading 1)
2994 (if (looking-at re)
2995 (- (match-end 0) (match-beginning 0))
2996 1))
2997 (error 1))))
2998 (next-level (save-excursion
2999 (condition-case nil
3000 (progn
3001 (outline-next-visible-heading 1)
3002 (if (looking-at re)
3003 (- (match-end 0) (match-beginning 0))
3004 1))
3005 (error 1))))
3006 (new-level (or force-level (max previous-level next-level)))
3007 (shift (if (or (= old-level -1)
3008 (= new-level -1)
3009 (= old-level new-level))
3010 0
3011 (- new-level old-level)))
3012 (shift1 shift)
3013 (delta (if (> shift 0) -1 1))
3014 (func (if (> shift 0) 'org-demote 'org-promote))
3015 (org-odd-levels-only nil)
3016 beg end)
3017 ;; Remove the forces level indicator
3018 (if force-level
3019 (delete-region (point-at-bol) (point)))
3020 ;; Make sure we start at the beginning of an empty line
3021 (if (not (bolp)) (insert "\n"))
3022 (if (not (looking-at "[ \t]*$"))
3023 (progn (insert "\n") (backward-char 1)))
3024 ;; Paste
3025 (setq beg (point))
3026 (insert txt)
3027 (setq end (point))
3028 (goto-char beg)
3029 ;; Shift if necessary
3030 (if (= shift 0)
3031 (message "Pasted at level %d, without shift" new-level)
3032 (save-restriction
3033 (narrow-to-region beg end)
3034 (while (not (= shift 0))
3035 (org-map-region func (point-min) (point-max))
3036 (setq shift (+ delta shift)))
3037 (goto-char (point-min))
3038 (message "Pasted at level %d, with shift by %d levels"
3039 new-level shift1)))
3040 (if (and (eq org-subtree-clip (current-kill 0))
3041 org-subtree-clip-folded)
3042 ;; The tree was folded before it was killed/copied
3043 (hide-subtree))))
3044
3045 (defun org-kill-is-subtree-p (&optional txt)
3046 "Check if the current kill is an outline subtree, or a set of trees.
3047 Returns nil if kill does not start with a headline, or if the first
3048 headline level is not the largest headline level in the tree.
3049 So this will actually accept several entries of equal levels as well,
3050 which is OK for `org-paste-subtree'.
3051 If optional TXT is given, check this string instead of the current kill."
3052 (let* ((kill (or txt (current-kill 0) ""))
3053 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3054 (- (match-end 0) (match-beginning 0))))
3055 (re (concat "^" outline-regexp))
3056 (start 1))
3057 (if (not start-level)
3058 nil ;; does not even start with a heading
3059 (catch 'exit
3060 (while (setq start (string-match re kill (1+ start)))
3061 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3062 (throw 'exit nil)))
3063 t))))
3064
3065 ;;; Plain list items
3066
3067 (defun org-at-item-p ()
3068 "Is point in a line starting a hand-formatted item?"
3069 (let ((llt org-plain-list-ordered-item-terminator))
3070 (save-excursion
3071 (goto-char (point-at-bol))
3072 (looking-at
3073 (cond
3074 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3075 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3076 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3077 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3078
3079 (defun org-get-indentation ()
3080 "Get the indentation of the current line, interpreting tabs."
3081 (save-excursion
3082 (beginning-of-line 1)
3083 (skip-chars-forward " \t")
3084 (current-column)))
3085
3086 (defun org-beginning-of-item ()
3087 "Go to the beginning of the current hand-formatted item.
3088 If the cursor is not in an item, throw an error."
3089 (let ((pos (point))
3090 (limit (save-excursion (org-back-to-heading)
3091 (beginning-of-line 2) (point)))
3092 ind ind1)
3093 (if (org-at-item-p)
3094 (beginning-of-line 1)
3095 (beginning-of-line 1)
3096 (skip-chars-forward " \t")
3097 (setq ind (current-column))
3098 (if (catch 'exit
3099 (while t
3100 (beginning-of-line 0)
3101 (if (< (point) limit) (throw 'exit nil))
3102 (unless (looking-at " \t]*$")
3103 (skip-chars-forward " \t")
3104 (setq ind1 (current-column))
3105 (if (< ind1 ind)
3106 (throw 'exit (org-at-item-p))))))
3107 nil
3108 (goto-char pos)
3109 (error "Not in an item")))))
3110
3111 (defun org-end-of-item ()
3112 "Go to the end of the current hand-formatted item.
3113 If the cursor is not in an item, throw an error."
3114 (let ((pos (point))
3115 (limit (save-excursion (outline-next-heading) (point)))
3116 (ind (save-excursion
3117 (org-beginning-of-item)
3118 (skip-chars-forward " \t")
3119 (current-column)))
3120 ind1)
3121 (if (catch 'exit
3122 (while t
3123 (beginning-of-line 2)
3124 (if (>= (point) limit) (throw 'exit t))
3125 (unless (looking-at "[ \t]*$")
3126 (skip-chars-forward " \t")
3127 (setq ind1 (current-column))
3128 (if (<= ind1 ind) (throw 'exit t)))))
3129 (beginning-of-line 1)
3130 (goto-char pos)
3131 (error "Not in an item"))))
3132
3133 (defun org-move-item-down (arg)
3134 "Move the plain list item at point down, i.e. swap with following item.
3135 Subitems (items with larger indentation) are considered part of the item,
3136 so this really moves item trees."
3137 (interactive "p")
3138 (let (beg end ind ind1 (pos (point)) txt)
3139 (org-beginning-of-item)
3140 (setq beg (point))
3141 (setq ind (org-get-indentation))
3142 (org-end-of-item)
3143 (setq end (point))
3144 (setq ind1 (org-get-indentation))
3145 (if (and (org-at-item-p) (= ind ind1))
3146 (progn
3147 (org-end-of-item)
3148 (setq txt (buffer-substring beg end))
3149 (save-excursion
3150 (delete-region beg end))
3151 (setq pos (point))
3152 (insert txt)
3153 (goto-char pos)
3154 (org-maybe-renumber-ordered-list))
3155 (goto-char pos)
3156 (error "Cannot move this item further down"))))
3157
3158 (defun org-move-item-up (arg)
3159 "Move the plain list item at point up, i.e. swap with previous item.
3160 Subitems (items with larger indentation) are considered part of the item,
3161 so this really moves item trees."
3162 (interactive "p")
3163 (let (beg end ind ind1 (pos (point)) txt)
3164 (org-beginning-of-item)
3165 (setq beg (point))
3166 (setq ind (org-get-indentation))
3167 (org-end-of-item)
3168 (setq end (point))
3169 (goto-char beg)
3170 (catch 'exit
3171 (while t
3172 (beginning-of-line 0)
3173 (if (looking-at "[ \t]*$")
3174 nil
3175 (if (<= (setq ind1 (org-get-indentation)) ind)
3176 (throw 'exit t)))))
3177 (condition-case nil
3178 (org-beginning-of-item)
3179 (error (goto-char beg)
3180 (error "Cannot move this item further up")))
3181 (setq ind1 (org-get-indentation))
3182 (if (and (org-at-item-p) (= ind ind1))
3183 (progn
3184 (setq txt (buffer-substring beg end))
3185 (save-excursion
3186 (delete-region beg end))
3187 (setq pos (point))
3188 (insert txt)
3189 (goto-char pos)
3190 (org-maybe-renumber-ordered-list))
3191 (goto-char pos)
3192 (error "Cannot move this item further up"))))
3193
3194 (defun org-maybe-renumber-ordered-list ()
3195 "Renumber the ordered list at point if setup allows it.
3196 This tests the user option `org-auto-renumber-ordered-lists' before
3197 doing the renumbering."
3198 (and org-auto-renumber-ordered-lists
3199 (org-at-item-p)
3200 (match-beginning 3)
3201 (org-renumber-ordered-list 1)))
3202
3203 (defun org-get-string-indentation (s)
3204 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3205 (let ((n -1) (i 0) (w tab-width) c)
3206 (catch 'exit
3207 (while (< (setq n (1+ n)) (length s))
3208 (setq c (aref s n))
3209 (cond ((= c ?\ ) (setq i (1+ i)))
3210 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3211 (t (throw 'exit t)))))
3212 i))
3213
3214 (defun org-renumber-ordered-list (arg)
3215 "Renumber an ordered plain list.
3216 Cursor next to be in the first line of an item, the line that starts
3217 with something like \"1.\" or \"2)\"."
3218 (interactive "p")
3219 (unless (and (org-at-item-p)
3220 (match-beginning 3))
3221 (error "This is not an ordered list"))
3222 (let ((line (org-current-line))
3223 (col (current-column))
3224 (ind (org-get-string-indentation
3225 (buffer-substring (point-at-bol) (match-beginning 3))))
3226 ;; (term (substring (match-string 3) -1))
3227 ind1 (n (1- arg)))
3228 ;; find where this list begins
3229 (catch 'exit
3230 (while t
3231 (catch 'next
3232 (beginning-of-line 0)
3233 (if (looking-at "[ \t]*$") (throw 'next t))
3234 (skip-chars-forward " \t") (setq ind1 (current-column))
3235 (if (or (< ind1 ind)
3236 (and (= ind1 ind)
3237 (not (org-at-item-p))))
3238 (throw 'exit t)))))
3239 ;; Walk forward and replace these numbers
3240 (catch 'exit
3241 (while t
3242 (catch 'next
3243 (beginning-of-line 2)
3244 (if (eobp) (throw 'exit nil))
3245 (if (looking-at "[ \t]*$") (throw 'next nil))
3246 (skip-chars-forward " \t") (setq ind1 (current-column))
3247 (if (> ind1 ind) (throw 'next t))
3248 (if (< ind1 ind) (throw 'exit t))
3249 (if (not (org-at-item-p)) (throw 'exit nil))
3250 (if (not (match-beginning 3))
3251 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3252 (delete-region (match-beginning 3) (1- (match-end 3)))
3253 (goto-char (match-beginning 3))
3254 (insert (format "%d" (setq n (1+ n)))))))
3255 (goto-line line)
3256 (move-to-column col)))
3257
3258 (defvar org-last-indent-begin-marker (make-marker))
3259 (defvar org-last-indent-end-marker (make-marker))
3260
3261
3262 (defun org-outdent-item (arg)
3263 "Outdent a local list item."
3264 (interactive "p")
3265 (org-indent-item (- arg)))
3266
3267 (defun org-indent-item (arg)
3268 "Indent a local list item."
3269 (interactive "p")
3270 (unless (org-at-item-p)
3271 (error "Not on an item"))
3272 (let (beg end ind ind1)
3273 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3274 (setq beg org-last-indent-begin-marker
3275 end org-last-indent-end-marker)
3276 (org-beginning-of-item)
3277 (setq beg (move-marker org-last-indent-begin-marker (point)))
3278 (org-end-of-item)
3279 (setq end (move-marker org-last-indent-end-marker (point))))
3280 (goto-char beg)
3281 (skip-chars-forward " \t") (setq ind (current-column))
3282 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3283 (while (< (point) end)
3284 (beginning-of-line 1)
3285 (skip-chars-forward " \t") (setq ind1 (current-column))
3286 (delete-region (point-at-bol) (point))
3287 (indent-to-column (+ ind1 arg))
3288 (beginning-of-line 2))
3289 (goto-char beg)))
3290
3291 ;;; Archiving
3292
3293 (defun org-archive-subtree ()
3294 "Move the current subtree to the archive.
3295 The archive can be a certain top-level heading in the current file, or in
3296 a different file. The tree will be moved to that location, the subtree
3297 heading be marked DONE, and the current time will be added."
3298 (interactive)
3299 ;; Save all relevant TODO keyword-relatex variables
3300 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3301 (tr-org-todo-keywords org-todo-keywords)
3302 (tr-org-todo-interpretation org-todo-interpretation)
3303 (tr-org-done-string org-done-string)
3304 (tr-org-todo-regexp org-todo-regexp)
3305 (tr-org-todo-line-regexp org-todo-line-regexp)
3306 (this-buffer (current-buffer))
3307 file heading buffer level newfile-p)
3308 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3309 (progn
3310 (setq file (format (match-string 1 org-archive-location)
3311 (file-name-nondirectory buffer-file-name))
3312 heading (match-string 2 org-archive-location)))
3313 (error "Invalid `org-archive-location'"))
3314 (if (> (length file) 0)
3315 (setq newfile-p (not (file-exists-p file))
3316 buffer (find-file-noselect file))
3317 (setq buffer (current-buffer)))
3318 (unless buffer
3319 (error "Cannot access file \"%s\"" file))
3320 (if (and (> (length heading) 0)
3321 (string-match "^\\*+" heading))
3322 (setq level (match-end 0))
3323 (setq heading nil level 0))
3324 (save-excursion
3325 ;; We first only copy, in case something goes wrong
3326 ;; we need to protect this-command, to avoid kill-region sets it,
3327 ;; which would lead to duplication of subtrees
3328 (let (this-command) (org-copy-subtree))
3329 (set-buffer buffer)
3330 ;; Enforce org-mode for the archive buffer
3331 (if (not (eq major-mode 'org-mode))
3332 ;; Force the mode for future visits.
3333 (let ((org-insert-mode-line-in-empty-file t))
3334 (call-interactively 'org-mode)))
3335 (when newfile-p
3336 (goto-char (point-max))
3337 (insert (format "\nArchived entries from file %s\n\n"
3338 (buffer-file-name this-buffer))))
3339 ;; Force the TODO keywords of the original buffer
3340 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3341 (org-todo-keywords tr-org-todo-keywords)
3342 (org-todo-interpretation tr-org-todo-interpretation)
3343 (org-done-string tr-org-done-string)
3344 (org-todo-regexp tr-org-todo-regexp)
3345 (org-todo-line-regexp tr-org-todo-line-regexp))
3346 (goto-char (point-min))
3347 (if heading
3348 (progn
3349 (if (re-search-forward
3350 (concat "\\(^\\|\r\\)"
3351 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3352 nil t)
3353 (goto-char (match-end 0))
3354 ;; Heading not found, just insert it at the end
3355 (goto-char (point-max))
3356 (or (bolp) (insert "\n"))
3357 (insert "\n" heading "\n")
3358 (end-of-line 0))
3359 ;; Make the heading visible, and the following as well
3360 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3361 (if (re-search-forward
3362 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3363 nil t)
3364 (progn (goto-char (match-beginning 0)) (insert "\n")
3365 (beginning-of-line 0))
3366 (goto-char (point-max)) (insert "\n")))
3367 (goto-char (point-max)) (insert "\n"))
3368 ;; Paste
3369 (org-paste-subtree (1+ level))
3370 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3371 (if org-archive-mark-done
3372 (org-todo (length org-todo-keywords)))
3373 ;; Move cursor to right after the TODO keyword
3374 (when org-archive-stamp-time
3375 (beginning-of-line 1)
3376 (looking-at org-todo-line-regexp)
3377 (goto-char (or (match-end 2) (match-beginning 3)))
3378 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3379 (current-time))
3380 ")"))
3381 ;; Save the buffer, if it is not the same buffer.
3382 (if (not (eq this-buffer buffer)) (save-buffer))))
3383 ;; Here we are back in the original buffer. Everything seems to have
3384 ;; worked. So now cut the tree and finish up.
3385 (let (this-command) (org-cut-subtree))
3386 (if (looking-at "[ \t]*$") (kill-line))
3387 (message "Subtree archived %s"
3388 (if (eq this-buffer buffer)
3389 (concat "under heading: " heading)
3390 (concat "in file: " (abbreviate-file-name file))))))
3391
3392 ;;; Completion
3393
3394 (defun org-complete (&optional arg)
3395 "Perform completion on word at point.
3396 At the beginning of a headline, this completes TODO keywords as given in
3397 `org-todo-keywords'.
3398 If the current word is preceded by a backslash, completes the TeX symbols
3399 that are supported for HTML support.
3400 If the current word is preceded by \"#+\", completes special words for
3401 setting file options.
3402 At all other locations, this simply calls `ispell-complete-word'."
3403 (interactive "P")
3404 (catch 'exit
3405 (let* ((end (point))
3406 (beg1 (save-excursion
3407 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3408 (skip-chars-backward "a-zA-Z_@0-9")
3409 (point)))
3410 (beg (save-excursion
3411 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3412 (skip-chars-backward "a-zA-Z0-9_:$")
3413 (point)))
3414 (camel (equal (char-before beg) ?*))
3415 (tag (equal (char-before beg1) ?:))
3416 (texp (equal (char-before beg) ?\\))
3417 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3418 beg)
3419 "#+"))
3420 (completion-ignore-case opt)
3421 (type nil)
3422 (tbl nil)
3423 (table (cond
3424 (opt
3425 (setq type :opt)
3426 (mapcar (lambda (x)
3427 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3428 (cons (match-string 2 x) (match-string 1 x)))
3429 (org-split-string (org-get-current-options) "\n")))
3430 (texp
3431 (setq type :tex)
3432 org-html-entities)
3433 ((string-match "\\`\\*+[ \t]*\\'"
3434 (buffer-substring (point-at-bol) beg))
3435 (setq type :todo)
3436 (mapcar 'list org-todo-keywords))
3437 (camel
3438 (setq type :camel)
3439 (save-excursion
3440 (goto-char (point-min))
3441 (while (re-search-forward org-todo-line-regexp nil t)
3442 (push (list
3443 (if org-file-link-context-use-camel-case
3444 (org-make-org-heading-camel (match-string 3) t)
3445 (org-make-org-heading-search-string
3446 (match-string 3) t)))
3447 tbl)))
3448 tbl)
3449 (tag (setq type :tag beg beg1)
3450 (org-get-buffer-tags))
3451 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3452 (pattern (buffer-substring-no-properties beg end))
3453 (completion (try-completion pattern table)))
3454 (cond ((eq completion t)
3455 (if (equal type :opt)
3456 (insert (substring (cdr (assoc (upcase pattern) table))
3457 (length pattern)))))
3458 ((null completion)
3459 (message "Can't find completion for \"%s\"" pattern)
3460 (ding))
3461 ((not (string= pattern completion))
3462 (delete-region beg end)
3463 (if (string-match " +$" completion)
3464 (setq completion (replace-match "" t t completion)))
3465 (insert completion)
3466 (if (get-buffer-window "*Completions*")
3467 (delete-window (get-buffer-window "*Completions*")))
3468 (if (assoc completion table)
3469 (if (eq type :todo) (insert " ")
3470 (if (eq type :tag) (insert ":"))))
3471 (if (and (equal type :opt) (assoc completion table))
3472 (message "%s" (substitute-command-keys
3473 "Press \\[org-complete] again to insert example settings"))))
3474 (t
3475 (message "Making completion list...")
3476 (let ((list (sort (all-completions pattern table) 'string<)))
3477 (with-output-to-temp-buffer "*Completions*"
3478 (condition-case nil
3479 ;; Protection needed for XEmacs and emacs 21
3480 (display-completion-list list pattern)
3481 (error (display-completion-list list)))))
3482 (message "Making completion list...%s" "done"))))))
3483
3484 ;;; Comments, TODO and DEADLINE
3485
3486 (defun org-toggle-comment ()
3487 "Change the COMMENT state of an entry."
3488 (interactive)
3489 (save-excursion
3490 (org-back-to-heading)
3491 (if (looking-at (concat outline-regexp
3492 "\\( +\\<" org-comment-string "\\>\\)"))
3493 (replace-match "" t t nil 1)
3494 (if (looking-at outline-regexp)
3495 (progn
3496 (goto-char (match-end 0))
3497 (insert " " org-comment-string))))))
3498
3499 (defvar org-last-todo-state-is-todo nil
3500 "This is non-nil when the last TODO state change led to a TODO state.
3501 If the last change removed the TODO tag or switched to DONE, then
3502 this is nil.")
3503
3504 (defun org-todo (&optional arg)
3505 "Change the TODO state of an item.
3506 The state of an item is given by a keyword at the start of the heading,
3507 like
3508 *** TODO Write paper
3509 *** DONE Call mom
3510
3511 The different keywords are specified in the variable `org-todo-keywords'.
3512 By default the available states are \"TODO\" and \"DONE\".
3513 So for this example: when the item starts with TODO, it is changed to DONE.
3514 When it starts with DONE, the DONE is removed. And when neither TODO nor
3515 DONE are present, add TODO at the beginning of the heading.
3516
3517 With prefix arg, use completion to determine the new state. With numeric
3518 prefix arg, switch to that state."
3519 (interactive "P")
3520 (save-excursion
3521 (org-back-to-heading)
3522 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3523 (or (looking-at (concat " +" org-todo-regexp " *"))
3524 (looking-at " *"))
3525 (let* ((this (match-string 1))
3526 (completion-ignore-case t)
3527 (member (member this org-todo-keywords))
3528 (tail (cdr member))
3529 (state (cond
3530 ((equal arg '(4))
3531 ;; Read a state with completion
3532 (completing-read "State: " (mapcar (lambda(x) (list x))
3533 org-todo-keywords)
3534 nil t))
3535 ((eq arg 'right)
3536 (if this
3537 (if tail (car tail) nil)
3538 (car org-todo-keywords)))
3539 ((eq arg 'left)
3540 (if (equal member org-todo-keywords)
3541 nil
3542 (if this
3543 (nth (- (length org-todo-keywords) (length tail) 2)
3544 org-todo-keywords)
3545 org-done-string)))
3546 (arg
3547 ;; user requests a specific state
3548 (nth (1- (prefix-numeric-value arg))
3549 org-todo-keywords))
3550 ((null member) (car org-todo-keywords))
3551 ((null tail) nil) ;; -> first entry
3552 ((eq org-todo-interpretation 'sequence)
3553 (car tail))
3554 ((memq org-todo-interpretation '(type priority))
3555 (if (eq this-command last-command)
3556 (car tail)
3557 (if (> (length tail) 0) org-done-string nil)))
3558 (t nil)))
3559 (next (if state (concat " " state " ") " ")))
3560 (replace-match next t t)
3561 (setq org-last-todo-state-is-todo
3562 (not (equal state org-done-string)))
3563 (when org-log-done
3564 (if (equal state org-done-string)
3565 (org-log-done)
3566 (if (not this)
3567 (org-log-done t))))
3568 ;; Fixup tag positioning
3569 (and org-auto-align-tags (org-set-tags nil t))
3570 (run-hooks 'org-after-todo-state-change-hook)))
3571 ;; Fixup cursor location if close to the keyword
3572 (if (and (outline-on-heading-p)
3573 (not (bolp))
3574 (save-excursion (beginning-of-line 1)
3575 (looking-at org-todo-line-regexp))
3576 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3577 (progn
3578 (goto-char (or (match-end 2) (match-end 1)))
3579 (just-one-space))))
3580
3581 (defun org-log-done (&optional undone)
3582 "Add a time stamp logging that a TODO entry has been closed.
3583 When UNDONE is non-nil, remove such a time stamp again."
3584 (interactive)
3585 (let (beg end col)
3586 (save-excursion
3587 (org-back-to-heading t)
3588 (setq beg (point))
3589 (looking-at (concat outline-regexp " *"))
3590 (goto-char (match-end 0))
3591 (setq col (current-column))
3592 (outline-next-heading)
3593 (setq end (point))
3594 (goto-char beg)
3595 (when (re-search-forward (concat
3596 "[\r\n]\\([ \t]*"
3597 (regexp-quote org-closed-string)
3598 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3599 (delete-region (match-beginning 1) (match-end 1)))
3600 (unless undone
3601 (org-back-to-heading t)
3602 (skip-chars-forward "^\n\r")
3603 (goto-char (min (1+ (point)) (point-max)))
3604 (when (not (member (char-before) '(?\r ?\n)))
3605 (insert "\n"))
3606 (indent-to col)
3607 (insert org-closed-string " "
3608 (format-time-string
3609 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3610 (current-time))
3611 "\n")))))
3612
3613 (defun org-show-todo-tree (arg)
3614 "Make a compact tree which shows all headlines marked with TODO.
3615 The tree will show the lines where the regexp matches, and all higher
3616 headlines above the match.
3617 With \\[universal-argument] prefix, also show the DONE entries.
3618 With a numeric prefix N, construct a sparse tree for the Nth element
3619 of `org-todo-keywords'."
3620 (interactive "P")
3621 (let ((case-fold-search nil)
3622 (kwd-re
3623 (cond ((null arg) org-not-done-regexp)
3624 ((equal arg '(4)) org-todo-regexp)
3625 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3626 (regexp-quote (nth (1- (prefix-numeric-value arg))
3627 org-todo-keywords)))
3628 (t (error "Invalid prefix argument: %s" arg)))))
3629 (message "%d TODO entries found"
3630 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3631
3632 (defun org-deadline ()
3633 "Insert the DEADLINE: string to make a deadline.
3634 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3635 to modify it to the correct date."
3636 (interactive)
3637 (insert
3638 org-deadline-string " "
3639 (format-time-string (car org-time-stamp-formats)
3640 (org-read-date nil 'to-time)))
3641 (message "%s" (substitute-command-keys
3642 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3643
3644 (defun org-schedule ()
3645 "Insert the SCHEDULED: string to schedule a TODO item.
3646 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3647 to modify it to the correct date."
3648 (interactive)
3649 (insert
3650 org-scheduled-string " "
3651 (format-time-string (car org-time-stamp-formats)
3652 (org-read-date nil 'to-time)))
3653 (message "%s" (substitute-command-keys
3654 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3655
3656
3657 (defun org-occur (regexp &optional callback)
3658 "Make a compact tree which shows all matches of REGEXP.
3659 The tree will show the lines where the regexp matches, and all higher
3660 headlines above the match. It will also show the heading after the match,
3661 to make sure editing the matching entry is easy.
3662 If CALLBACK is non-nil, it is a function which is called to confirm
3663 that the match should indeed be shown."
3664 (interactive "sRegexp: ")
3665 (org-remove-occur-highlights nil nil t)
3666 (setq regexp (org-check-occur-regexp regexp))
3667 (let ((cnt 0))
3668 (save-excursion
3669 (goto-char (point-min))
3670 (hide-sublevels 1)
3671 (while (re-search-forward regexp nil t)
3672 (when (or (not callback)
3673 (save-match-data (funcall callback)))
3674 (setq cnt (1+ cnt))
3675 (org-highlight-new-match (match-beginning 0) (match-end 0))
3676 (org-show-hierarchy-above))))
3677 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
3678 nil 'local)
3679 (run-hooks 'org-occur-hook)
3680 (if (interactive-p)
3681 (message "%d match(es) for regexp %s" cnt regexp))
3682 cnt))
3683
3684 (defun org-show-hierarchy-above ()
3685 "Make sure point and the headings hierarchy above is visible."
3686 (catch 'exit
3687 (if (org-on-heading-p t)
3688 (org-flag-heading nil) ; only show the heading
3689 (and (or (org-invisible-p) (org-invisible-p2))
3690 (org-show-hidden-entry))) ; show entire entry
3691 (save-excursion
3692 (and org-show-following-heading
3693 (outline-next-heading)
3694 (org-flag-heading nil))) ; show the next heading
3695 (when org-show-hierarchy-above
3696 (save-excursion ; show all higher headings
3697 (while (and (condition-case nil
3698 (progn (org-up-heading-all 1) t)
3699 (error nil))
3700 (not (bobp)))
3701 (org-flag-heading nil))))))
3702
3703 ;; Overlay compatibility functions
3704 (defun org-make-overlay (beg end &optional buffer)
3705 (if org-xemacs-p (make-extent beg end buffer) (make-overlay beg end buffer)))
3706 (defun org-delete-overlay (ovl)
3707 (if org-xemacs-p (delete-extent ovl) (delete-overlay ovl)))
3708 (defun org-detatch-overlay (ovl)
3709 (if org-xemacs-p (detach-extent ovl) (delete-overlay ovl)))
3710 (defun org-move-overlay (ovl beg end &optional buffer)
3711 (if org-xemacs-p
3712 (set-extent-endpoints ovl beg end buffer)
3713 (move-overlay ovl beg end buffer)))
3714 (defun org-overlay-put (ovl prop value)
3715 (if org-xemacs-p
3716 (set-extent-property ovl prop value)
3717 (overlay-put ovl prop value)))
3718
3719 (defvar org-occur-highlights nil)
3720 (defun org-highlight-new-match (beg end)
3721 "Highlight from BEG to END and mark the highlight is an occur headline."
3722 (let ((ov (org-make-overlay beg end)))
3723 (org-overlay-put ov 'face 'secondary-selection)
3724 (push ov org-occur-highlights)))
3725
3726 (defun org-remove-occur-highlights (&optional beg end noremove)
3727 "Remove the occur highlights from the buffer.
3728 BEG and END are ignored. If NOREMOVE is nil, remove this function
3729 from the `before-change-functions' in the current buffer."
3730 (interactive)
3731 (mapc 'org-delete-overlay org-occur-highlights)
3732 (setq org-occur-highlights nil)
3733 (unless noremove
3734 (remove-hook 'before-change-functions
3735 'org-remove-occur-highlights 'local)))
3736
3737 ;;; Priorities
3738
3739 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3740 "Regular expression matching the priority indicator.")
3741
3742 (defvar org-remove-priority-next-time nil)
3743
3744 (defun org-priority-up ()
3745 "Increase the priority of the current item."
3746 (interactive)
3747 (org-priority 'up))
3748
3749 (defun org-priority-down ()
3750 "Decrease the priority of the current item."
3751 (interactive)
3752 (org-priority 'down))
3753
3754 (defun org-priority (&optional action)
3755 "Change the priority of an item by ARG.
3756 ACTION can be set, up, or down."
3757 (interactive)
3758 (setq action (or action 'set))
3759 (let (current new news have remove)
3760 (save-excursion
3761 (org-back-to-heading)
3762 (if (looking-at org-priority-regexp)
3763 (setq current (string-to-char (match-string 2))
3764 have t)
3765 (setq current org-default-priority))
3766 (cond
3767 ((eq action 'set)
3768 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3769 (setq new (read-char-exclusive))
3770 (cond ((equal new ?\ ) (setq remove t))
3771 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3772 (error "Priority must be between `%c' and `%c'"
3773 ?A org-lowest-priority))))
3774 ((eq action 'up)
3775 (setq new (1- current)))
3776 ((eq action 'down)
3777 (setq new (1+ current)))
3778 (t (error "Invalid action")))
3779 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3780 (setq news (format "%c" new))
3781 (if have
3782 (if remove
3783 (replace-match "" t t nil 1)
3784 (replace-match news t t nil 2))
3785 (if remove
3786 (error "No priority cookie found in line")
3787 (looking-at org-todo-line-regexp)
3788 (if (match-end 2)
3789 (progn
3790 (goto-char (match-end 2))
3791 (insert " [#" news "]"))
3792 (goto-char (match-beginning 3))
3793 (insert "[#" news "] ")))))
3794 (if remove
3795 (message "Priority removed")
3796 (message "Priority of current item set to %s" news))))
3797
3798
3799 (defun org-get-priority (s)
3800 "Find priority cookie and return priority."
3801 (save-match-data
3802 (if (not (string-match org-priority-regexp s))
3803 (* 1000 (- org-lowest-priority org-default-priority))
3804 (* 1000 (- org-lowest-priority
3805 (string-to-char (match-string 2 s)))))))
3806
3807 ;;; Timestamps
3808
3809 (defvar org-last-changed-timestamp nil)
3810
3811 (defun org-time-stamp (arg)
3812 "Prompt for a date/time and insert a time stamp.
3813 If the user specifies a time like HH:MM, or if this command is called
3814 with a prefix argument, the time stamp will contain date and time.
3815 Otherwise, only the date will be included. All parts of a date not
3816 specified by the user will be filled in from the current date/time.
3817 So if you press just return without typing anything, the time stamp
3818 will represent the current date/time. If there is already a timestamp
3819 at the cursor, it will be modified."
3820 (interactive "P")
3821 (let ((fmt (if arg (cdr org-time-stamp-formats)
3822 (car org-time-stamp-formats)))
3823 (org-time-was-given nil)
3824 time)
3825 (cond
3826 ((and (org-at-timestamp-p)
3827 (eq last-command 'org-time-stamp)
3828 (eq this-command 'org-time-stamp))
3829 (insert "--")
3830 (setq time (let ((this-command this-command))
3831 (org-read-date arg 'totime)))
3832 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3833 (insert (format-time-string fmt time)))
3834 ((org-at-timestamp-p)
3835 (setq time (let ((this-command this-command))
3836 (org-read-date arg 'totime)))
3837 (and (org-at-timestamp-p) (replace-match
3838 (setq org-last-changed-timestamp
3839 (format-time-string fmt time))
3840 t t))
3841 (message "Timestamp updated"))
3842 (t
3843 (setq time (let ((this-command this-command))
3844 (org-read-date arg 'totime)))
3845 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3846 (insert (format-time-string fmt time))))))
3847
3848 (defun org-time-stamp-inactive (&optional arg)
3849 "Insert an inactive time stamp.
3850 An inactive time stamp is enclosed in square brackets instead of angle
3851 brackets. It is inactive in the sense that it does not trigger agenda entries,
3852 does not link to the calendar and cannot be changed with the S-cursor keys.
3853 So these are more for recording a certain time/date."
3854 ;; FIXME: Would it be better not to ask for a date/time here?
3855 (interactive "P")
3856 (let ((fmt (if arg (cdr org-time-stamp-formats)
3857 (car org-time-stamp-formats)))
3858 (org-time-was-given nil)
3859 time)
3860 (setq time (org-read-date arg 'totime))
3861 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3862 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3863 (insert (format-time-string fmt time))))
3864
3865 (defvar org-date-ovl (org-make-overlay 1 1))
3866 (org-overlay-put org-date-ovl 'face 'org-warning)
3867 (org-detatch-overlay org-date-ovl)
3868
3869 ;;; FIXME: Make the function take "Fri" as "next friday"
3870 ;;; because these are mostly being used to record the current time.
3871 (defun org-read-date (&optional with-time to-time)
3872 "Read a date and make things smooth for the user.
3873 The prompt will suggest to enter an ISO date, but you can also enter anything
3874 which will at least partially be understood by `parse-time-string'.
3875 Unrecognized parts of the date will default to the current day, month, year,
3876 hour and minute. For example,
3877 3-2-5 --> 2003-02-05
3878 feb 15 --> currentyear-02-15
3879 sep 12 9 --> 2009-09-12
3880 12:45 --> today 12:45
3881 22 sept 0:34 --> currentyear-09-22 0:34
3882 12 --> currentyear-currentmonth-12
3883 etc.
3884 The function understands only English month and weekday abbreviations,
3885 but this can be configured with the variables `parse-time-months' and
3886 `parse-time-weekdays'.
3887
3888 While prompting, a calendar is popped up - you can also select the
3889 date with the mouse (button 1). The calendar shows a period of three
3890 months. To scroll it to other months, use the keys `>' and `<'.
3891 If you don't like the calendar, turn it off with
3892 \(setq org-popup-calendar-for-date-prompt nil)
3893
3894 With optional argument TO-TIME, the date will immediately be converted
3895 to an internal time.
3896 With an optional argument WITH-TIME, the prompt will suggest to also
3897 insert a time. Note that when WITH-TIME is not set, you can still
3898 enter a time, and this function will inform the calling routine about
3899 this change. The calling routine may then choose to change the format
3900 used to insert the time stamp into the buffer to include the time."
3901 (require 'parse-time)
3902 (let* ((default-time
3903 ;; Default time is either today, or, when entering a range,
3904 ;; the range start.
3905 (if (save-excursion
3906 (re-search-backward
3907 (concat org-ts-regexp "--\\=")
3908 (- (point) 20) t))
3909 (apply
3910 'encode-time
3911 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3912 (parse-time-string (match-string 1))))
3913 (current-time)))
3914 (calendar-move-hook nil)
3915 (view-diary-entries-initially nil)
3916 (timestr (format-time-string
3917 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3918 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3919 ans ans1 ans2
3920 second minute hour day month year tl)
3921
3922 (if org-popup-calendar-for-date-prompt
3923 ;; Also show a calendar for date selection
3924 ;; Copied (with modifications) from planner.el by John Wiegley
3925 (save-excursion
3926 (save-window-excursion
3927 (calendar)
3928 (calendar-forward-day (- (time-to-days default-time)
3929 (calendar-absolute-from-gregorian
3930 (calendar-current-date))))
3931 (org-eval-in-calendar nil)
3932 (let* ((old-map (current-local-map))
3933 (map (copy-keymap calendar-mode-map))
3934 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3935 (define-key map (kbd "RET") 'org-calendar-select)
3936 (define-key map (if org-xemacs-p [button1] [mouse-1])
3937 'org-calendar-select-mouse)
3938 (define-key map (if org-xemacs-p [button2] [mouse-2])
3939 'org-calendar-select-mouse)
3940 (define-key minibuffer-local-map [(meta shift left)]
3941 (lambda () (interactive)
3942 (org-eval-in-calendar '(calendar-backward-month 1))))
3943 (define-key minibuffer-local-map [(meta shift right)]
3944 (lambda () (interactive)
3945 (org-eval-in-calendar '(calendar-forward-month 1))))
3946 (define-key minibuffer-local-map [(shift up)]
3947 (lambda () (interactive)
3948 (org-eval-in-calendar '(calendar-backward-week 1))))
3949 (define-key minibuffer-local-map [(shift down)]
3950 (lambda () (interactive)
3951 (org-eval-in-calendar '(calendar-forward-week 1))))
3952 (define-key minibuffer-local-map [(shift left)]
3953 (lambda () (interactive)
3954 (org-eval-in-calendar '(calendar-backward-day 1))))
3955 (define-key minibuffer-local-map [(shift right)]
3956 (lambda () (interactive)
3957 (org-eval-in-calendar '(calendar-forward-day 1))))
3958 (define-key minibuffer-local-map ">"
3959 (lambda () (interactive)
3960 (org-eval-in-calendar '(scroll-calendar-left 1))))
3961 (define-key minibuffer-local-map "<"
3962 (lambda () (interactive)
3963 (org-eval-in-calendar '(scroll-calendar-right 1))))
3964 (unwind-protect
3965 (progn
3966 (use-local-map map)
3967 (setq ans (read-string prompt "" nil nil))
3968 (if (not (string-match "\\S-" ans)) (setq ans nil))
3969 (setq ans (or ans1 ans ans2)))
3970 (use-local-map old-map)))))
3971 ;; Naked prompt only
3972 (setq ans (read-string prompt "" nil timestr)))
3973 (org-detatch-overlay org-date-ovl)
3974
3975 (if (string-match
3976 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3977 (progn
3978 (setq year (if (match-end 2)
3979 (string-to-number (match-string 2 ans))
3980 (string-to-number (format-time-string "%Y")))
3981 month (string-to-number (match-string 3 ans))
3982 day (string-to-number (match-string 4 ans)))
3983 (if (< year 100) (setq year (+ 2000 year)))
3984 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3985 t t ans))))
3986 (setq tl (parse-time-string ans)
3987 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3988 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3989 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3990 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3991 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3992 second (or (nth 0 tl) 0))
3993 (if (and (boundp 'org-time-was-given)
3994 (nth 2 tl))
3995 (setq org-time-was-given t))
3996 (if (< year 100) (setq year (+ 2000 year)))
3997 (if to-time
3998 (encode-time second minute hour day month year)
3999 (if (or (nth 1 tl) (nth 2 tl))
4000 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4001 (format "%04d-%02d-%02d" year month day)))))
4002
4003 (defun org-eval-in-calendar (form)
4004 "Eval FORM in the calendar window and return to current window.
4005 Also, store the cursor date in variable ans2."
4006 (let ((sw (selected-window)))
4007 (select-window (get-buffer-window "*Calendar*"))
4008 (eval form)
4009 (when (calendar-cursor-to-date)
4010 (let* ((date (calendar-cursor-to-date))
4011 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4012 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4013 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4014 (select-window sw)))
4015
4016 (defun org-calendar-select ()
4017 "Return to `org-read-date' with the date currently selected.
4018 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4019 (interactive)
4020 (when (calendar-cursor-to-date)
4021 (let* ((date (calendar-cursor-to-date))
4022 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4023 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4024 (if (active-minibuffer-window) (exit-minibuffer))))
4025
4026 (defun org-calendar-select-mouse (ev)
4027 "Return to `org-read-date' with the date currently selected.
4028 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4029 (interactive "e")
4030 (mouse-set-point ev)
4031 (when (calendar-cursor-to-date)
4032 (let* ((date (calendar-cursor-to-date))
4033 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4034 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4035 (if (active-minibuffer-window) (exit-minibuffer))))
4036
4037 (defun org-check-deadlines (ndays)
4038 "Check if there are any deadlines due or past due.
4039 A deadline is considered due if it happens within `org-deadline-warning-days'
4040 days from today's date. If the deadline appears in an entry marked DONE,
4041 it is not shown. The prefix arg NDAYS can be used to test that many
4042 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4043 (interactive "P")
4044 (let* ((org-warn-days
4045 (cond
4046 ((equal ndays '(4)) 100000)
4047 (ndays (prefix-numeric-value ndays))
4048 (t org-deadline-warning-days)))
4049 (case-fold-search nil)
4050 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4051 (callback
4052 (lambda ()
4053 (and (let ((d1 (time-to-days (current-time)))
4054 (d2 (time-to-days
4055 (org-time-string-to-time (match-string 1)))))
4056 (< (- d2 d1) org-warn-days))
4057 (not (org-entry-is-done-p))))))
4058 (message "%d deadlines past-due or due within %d days"
4059 (org-occur regexp callback)
4060 org-warn-days)))
4061
4062 (defun org-evaluate-time-range (&optional to-buffer)
4063 "Evaluate a time range by computing the difference between start and end.
4064 Normally the result is just printed in the echo area, but with prefix arg
4065 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4066 If the time range is actually in a table, the result is inserted into the
4067 next column.
4068 For time difference computation, a year is assumed to be exactly 365
4069 days in order to avoid rounding problems."
4070 (interactive "P")
4071 (save-excursion
4072 (unless (org-at-date-range-p)
4073 (goto-char (point-at-bol))
4074 (re-search-forward org-tr-regexp (point-at-eol) t))
4075 (if (not (org-at-date-range-p))
4076 (error "Not at a time-stamp range, and none found in current line")))
4077 (let* ((ts1 (match-string 1))
4078 (ts2 (match-string 2))
4079 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4080 (match-end (match-end 0))
4081 (time1 (org-time-string-to-time ts1))
4082 (time2 (org-time-string-to-time ts2))
4083 (t1 (time-to-seconds time1))
4084 (t2 (time-to-seconds time2))
4085 (diff (abs (- t2 t1)))
4086 (negative (< (- t2 t1) 0))
4087 ;; (ys (floor (* 365 24 60 60)))
4088 (ds (* 24 60 60))
4089 (hs (* 60 60))
4090 (fy "%dy %dd %02d:%02d")
4091 (fy1 "%dy %dd")
4092 (fd "%dd %02d:%02d")
4093 (fd1 "%dd")
4094 (fh "%02d:%02d")
4095 y d h m align)
4096 ;; FIXME: Should I re-introduce years, make year refer to same date?
4097 ;; This would be the only useful way to have years, actually.
4098 (if havetime
4099 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4100 y 0
4101 d (floor (/ diff ds)) diff (mod diff ds)
4102 h (floor (/ diff hs)) diff (mod diff hs)
4103 m (floor (/ diff 60)))
4104 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4105 y 0
4106 d (floor (+ (/ diff ds) 0.5))
4107 h 0 m 0))
4108 (if (not to-buffer)
4109 (message (org-make-tdiff-string y d h m))
4110 (when (org-at-table-p)
4111 (goto-char match-end)
4112 (setq align t)
4113 (and (looking-at " *|") (goto-char (match-end 0))))
4114 (if (looking-at
4115 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4116 (replace-match ""))
4117 (if negative (insert " -"))
4118 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4119 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4120 (insert " " (format fh h m))))
4121 (if align (org-table-align))
4122 (message "Time difference inserted"))))
4123
4124 (defun org-make-tdiff-string (y d h m)
4125 (let ((fmt "")
4126 (l nil))
4127 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4128 l (push y l)))
4129 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4130 l (push d l)))
4131 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4132 l (push h l)))
4133 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4134 l (push m l)))
4135 (apply 'format fmt (nreverse l))))
4136
4137 (defun org-time-string-to-time (s)
4138 (apply 'encode-time (org-parse-time-string s)))
4139
4140 (defun org-parse-time-string (s &optional nodefault)
4141 "Parse the standard Org-mode time string.
4142 This should be a lot faster than the normal `parse-time-string'.
4143 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4144 hour and minute fields will be nil if not given."
4145 (if (string-match org-ts-regexp1 s)
4146 (list 0
4147 (if (or (match-beginning 8) (not nodefault))
4148 (string-to-number (or (match-string 8 s) "0")))
4149 (if (or (match-beginning 7) (not nodefault))
4150 (string-to-number (or (match-string 7 s) "0")))
4151 (string-to-number (match-string 4 s))
4152 (string-to-number (match-string 3 s))
4153 (string-to-number (match-string 2 s))
4154 nil nil nil)
4155 (make-list 9 0)))
4156
4157 (defun org-timestamp-up (&optional arg)
4158 "Increase the date item at the cursor by one.
4159 If the cursor is on the year, change the year. If it is on the month or
4160 the day, change that.
4161 With prefix ARG, change by that many units."
4162 (interactive "p")
4163 (org-timestamp-change (prefix-numeric-value arg)))
4164
4165 (defun org-timestamp-down (&optional arg)
4166 "Decrease the date item at the cursor by one.
4167 If the cursor is on the year, change the year. If it is on the month or
4168 the day, change that.
4169 With prefix ARG, change by that many units."
4170 (interactive "p")
4171 (org-timestamp-change (- (prefix-numeric-value arg))))
4172
4173 (defun org-timestamp-up-day (&optional arg)
4174 "Increase 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 'up)
4180 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4181
4182 (defun org-timestamp-down-day (&optional arg)
4183 "Decrease the date in the time stamp by one day.
4184 With prefix ARG, change that many days."
4185 (interactive "p")
4186 (if (and (not (org-at-timestamp-p))
4187 (org-on-heading-p))
4188 (org-todo 'down)
4189 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4190
4191 (defsubst org-pos-in-match-range (pos n)
4192 (and (match-beginning n)
4193 (<= (match-beginning n) pos)
4194 (>= (match-end n) pos)))
4195
4196 (defun org-at-timestamp-p ()
4197 "Determine if the cursor is in or at a timestamp."
4198 (interactive)
4199 (let* ((tsr org-ts-regexp2)
4200 (pos (point))
4201 (ans (or (looking-at tsr)
4202 (save-excursion
4203 (skip-chars-backward "^<\n\r\t")
4204 (if (> (point) 1) (backward-char 1))
4205 (and (looking-at tsr)
4206 (> (- (match-end 0) pos) -1))))))
4207 (and (boundp 'org-ts-what)
4208 (setq org-ts-what
4209 (cond
4210 ((org-pos-in-match-range pos 2) 'year)
4211 ((org-pos-in-match-range pos 3) 'month)
4212 ((org-pos-in-match-range pos 7) 'hour)
4213 ((org-pos-in-match-range pos 8) 'minute)
4214 ((or (org-pos-in-match-range pos 4)
4215 (org-pos-in-match-range pos 5)) 'day)
4216 (t 'day))))
4217 ans))
4218
4219 (defun org-timestamp-change (n &optional what)
4220 "Change the date in the time stamp at point.
4221 The date will be changed by N times WHAT. WHAT can be `day', `month',
4222 `year', `minute', `second'. If WHAT is not given, the cursor position
4223 in the timestamp determines what will be changed."
4224 (let ((fmt (car org-time-stamp-formats))
4225 org-ts-what
4226 (pos (point))
4227 ts time time0)
4228 (if (not (org-at-timestamp-p))
4229 (error "Not at a timestamp"))
4230 (setq org-ts-what (or what org-ts-what))
4231 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4232 (- (match-end 0) (match-beginning 0))))
4233 1)
4234 (cdr org-time-stamp-formats)
4235 (car org-time-stamp-formats)))
4236 (setq ts (match-string 0))
4237 (replace-match "")
4238 (setq time0 (org-parse-time-string ts))
4239 (setq time
4240 (apply 'encode-time
4241 (append
4242 (list (or (car time0) 0))
4243 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4244 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4245 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4246 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4247 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4248 (nthcdr 6 time0))))
4249 (if (eq what 'calendar)
4250 (let ((cal-date
4251 (save-excursion
4252 (save-match-data
4253 (set-buffer "*Calendar*")
4254 (calendar-cursor-to-date)))))
4255 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4256 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4257 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4258 (setcar time0 (or (car time0) 0))
4259 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4260 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4261 (setq time (apply 'encode-time time0))))
4262 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4263 (goto-char pos)
4264 ;; Try to recenter the calendar window, if any
4265 (if (and org-calendar-follow-timestamp-change
4266 (get-buffer-window "*Calendar*" t)
4267 (memq org-ts-what '(day month year)))
4268 (org-recenter-calendar (time-to-days time)))))
4269
4270 (defun org-recenter-calendar (date)
4271 "If the calendar is visible, recenter it to DATE."
4272 (let* ((win (selected-window))
4273 (cwin (get-buffer-window "*Calendar*" t))
4274 (calendar-move-hook nil))
4275 (when cwin
4276 (select-window cwin)
4277 (calendar-goto-date (if (listp date) date
4278 (calendar-gregorian-from-absolute date)))
4279 (select-window win))))
4280
4281 (defun org-goto-calendar (&optional arg)
4282 "Go to the Emacs calendar at the current date.
4283 If there is a time stamp in the current line, go to that date.
4284 A prefix ARG can be used to force the current date."
4285 (interactive "P")
4286 (let ((tsr org-ts-regexp) diff
4287 (calendar-move-hook nil)
4288 (view-diary-entries-initially nil))
4289 (if (or (org-at-timestamp-p)
4290 (save-excursion
4291 (beginning-of-line 1)
4292 (looking-at (concat ".*" tsr))))
4293 (let ((d1 (time-to-days (current-time)))
4294 (d2 (time-to-days
4295 (org-time-string-to-time (match-string 1)))))
4296 (setq diff (- d2 d1))))
4297 (calendar)
4298 (calendar-goto-today)
4299 (if (and diff (not arg)) (calendar-forward-day diff))))
4300
4301 (defun org-date-from-calendar ()
4302 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4303 If there is already a time stamp at the cursor position, update it."
4304 (interactive)
4305 (org-timestamp-change 0 'calendar))
4306
4307 ;;; Agenda, and Diary Integration
4308
4309 ;;; Define the mode
4310
4311 (defvar org-agenda-mode-map (make-sparse-keymap)
4312 "Keymap for `org-agenda-mode'.")
4313
4314 (defvar org-agenda-menu)
4315 (defvar org-agenda-follow-mode nil)
4316 (defvar org-agenda-show-log nil)
4317 (defvar org-agenda-buffer-name "*Org Agenda*")
4318 (defvar org-agenda-redo-command nil)
4319 (defvar org-agenda-mode-hook nil)
4320 (defvar org-agenda-type nil)
4321 (defvar org-agenda-force-single-file nil)
4322
4323 ;;;###autoload
4324 (defun org-agenda-mode ()
4325 "Mode for time-sorted view on action items in Org-mode files.
4326
4327 The following commands are available:
4328
4329 \\{org-agenda-mode-map}"
4330 (interactive)
4331 (kill-all-local-variables)
4332 (setq major-mode 'org-agenda-mode)
4333 (setq mode-name "Org-Agenda")
4334 (use-local-map org-agenda-mode-map)
4335 (easy-menu-add org-agenda-menu)
4336 (if org-startup-truncated (setq truncate-lines t))
4337 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4338 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4339 (unless org-agenda-keep-modes
4340 (setq org-agenda-follow-mode nil
4341 org-agenda-show-log nil))
4342 (easy-menu-change
4343 '("Agenda") "Agenda Files"
4344 (append
4345 (list
4346 (vector
4347 (if (get 'org-agenda-files 'org-restrict)
4348 "Restricted to single file"
4349 "Edit File List")
4350 '(customize-variable 'org-agenda-files)
4351 (not (get 'org-agenda-files 'org-restrict)))
4352 "--")
4353 (mapcar 'org-file-menu-entry (org-agenda-files))))
4354 (org-agenda-set-mode-name)
4355 (apply
4356 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4357 (list 'org-agenda-mode-hook)))
4358
4359 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4360 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4361 (define-key org-agenda-mode-map " " 'org-agenda-show)
4362 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4363 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4364 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4365 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4366 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4367 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4368 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4369 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4370 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4371 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4372 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4373 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4374
4375 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4376 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4377 (while l (define-key org-agenda-mode-map
4378 (int-to-string (pop l)) 'digit-argument)))
4379
4380 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4381 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4382 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4383 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4384 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4385 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4386 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4387 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4388 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4389 (define-key org-agenda-mode-map "n" 'next-line)
4390 (define-key org-agenda-mode-map "p" 'previous-line)
4391 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4392 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4393 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4394 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4395 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4396 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4397 (eval-after-load "calendar"
4398 '(define-key calendar-mode-map org-calendar-to-agenda-key
4399 'org-calendar-goto-agenda))
4400 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4401 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4402 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4403 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4404 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4405 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4406 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4407 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4408 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4409 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4410 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4411 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4412 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4413 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4414 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4415 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4416 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4417 "Local keymap for agenda entries from Org-mode.")
4418
4419 (define-key org-agenda-keymap
4420 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4421 (define-key org-agenda-keymap
4422 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4423 (define-key org-agenda-keymap [follow-link] 'mouse-face)
4424 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4425 '("Agenda"
4426 ("Agenda Files")
4427 "--"
4428 ["Show" org-agenda-show t]
4429 ["Go To (other window)" org-agenda-goto t]
4430 ["Go To (one window)" org-agenda-switch-to t]
4431 ["Follow Mode" org-agenda-follow-mode
4432 :style toggle :selected org-agenda-follow-mode :active t]
4433 "--"
4434 ["Cycle TODO" org-agenda-todo t]
4435 ("Tags"
4436 ["Show all Tags" org-agenda-show-tags t]
4437 ["Set Tags" org-agenda-set-tags t])
4438 ("Reschedule"
4439 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4440 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4441 "--"
4442 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4443 ("Priority"
4444 ["Set Priority" org-agenda-priority t]
4445 ["Increase Priority" org-agenda-priority-up t]
4446 ["Decrease Priority" org-agenda-priority-down t]
4447 ["Show Priority" org-agenda-show-priority t])
4448 "--"
4449 ;; ["New agenda command" org-agenda t]
4450 ["Rebuild buffer" org-agenda-redo t]
4451 "--"
4452 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4453 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4454 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4455 "--"
4456 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4457 :style radio :selected (equal org-agenda-ndays 1)]
4458 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4459 :style radio :selected (equal org-agenda-ndays 7)]
4460 "--"
4461 ["Show Logbook entries" org-agenda-log-mode
4462 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4463 ["Include Diary" org-agenda-toggle-diary
4464 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4465 ["Use Time Grid" org-agenda-toggle-time-grid
4466 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4467 "--"
4468 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4469 ("Calendar Commands"
4470 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4471 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4472 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4473 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4474 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4475 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4476 "--"
4477 ["Quit" org-agenda-quit t]
4478 ["Exit and Release Buffers" org-agenda-exit t]
4479 ))
4480
4481 ;;;###autoload
4482 (defun org-agenda (arg)
4483 "Dispatch agenda commands to collect entries to the agenda buffer.
4484 Prompts for a character to select a command. Any prefix arg will be passed
4485 on to the selected command. The default selections are:
4486
4487 a Call `org-agenda' to display the agenda for the current day or week.
4488 t Call `org-todo-list' to display the global todo list.
4489 T Call `org-todo-list' to display the global todo list, select only
4490 entries with a specific TODO keyword (the user gets a prompt).
4491 m Call `org-tags-view' to display headlines with tags matching
4492 a condition (the user is prompted for the condition).
4493 M Like `m', but select only TODO entries, no ordinary headlines.
4494
4495 More commands can be added by configuring the variable
4496 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4497 searches can be pre-defined in this way.
4498
4499 If the current buffer is in Org-mode and visiting a file, you can also
4500 first press `1' to indicate that the agenda should be temporarily (until the
4501 next use of \\[org-agenda]) restricted to the current file."
4502 (interactive "P")
4503 (catch 'exit
4504 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4505 (custom org-agenda-custom-commands)
4506 c entry key type string)
4507 (put 'org-agenda-files 'org-restrict nil)
4508 (save-window-excursion
4509 (delete-other-windows)
4510 (switch-to-buffer-other-window " *Agenda Commands*")
4511 (erase-buffer)
4512 (insert
4513 "Press key for an agenda command:
4514 --------------------------------
4515 a Agenda for current week or day
4516 t List of all TODO entries T Entries with special TODO kwd
4517 m Match a TAGS query M Like m, but only TODO entries
4518 C Configure your own agenda commands")
4519 (while (setq entry (pop custom))
4520 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4521 (insert (format "\n%-4s%-14s: %s"
4522 key
4523 (cond
4524 ((eq type 'tags) "Tags query")
4525 ((eq type 'todo) "TODO keyword")
4526 ((eq type 'tags-tree) "Tags tree")
4527 ((eq type 'todo-tree) "TODO kwd tree")
4528 ((eq type 'occur-tree) "Occur tree")
4529 (t "???"))
4530 (org-string-props string 'face 'org-link))))
4531 (goto-char (point-min))
4532 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4533 (message "Press key for agenda command%s"
4534 (if restrict-ok ", or [1] to restrict to current file" ""))
4535 (setq c (read-char-exclusive))
4536 (message "")
4537 (when (equal c ?1)
4538 (if restrict-ok
4539 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
4540 (error "Cannot restrict agenda to current buffer"))
4541 (message "Press key for agenda command%s"
4542 (if restrict-ok " (restricted to current file)" ""))
4543 (setq c (read-char-exclusive))
4544 (message "")))
4545 (require 'calendar) ; FIXME: can we avoid this for some commands?
4546 ;; For example the todo list should not need it (but does...)
4547 (cond
4548 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4549 ((equal c ?a) (call-interactively 'org-agenda-list))
4550 ((equal c ?t) (call-interactively 'org-todo-list))
4551 ((equal c ?T)
4552 (setq current-prefix-arg (or arg '(4)))
4553 (call-interactively 'org-todo-list))
4554 ((equal c ?m) (call-interactively 'org-tags-view))
4555 ((equal c ?M)
4556 (setq current-prefix-arg (or arg '(4)))
4557 (call-interactively 'org-tags-view))
4558 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4559 (setq type (nth 1 entry) string (nth 2 entry))
4560 (cond
4561 ((eq type 'tags)
4562 (org-tags-view current-prefix-arg string))
4563 ((eq type 'todo)
4564 (org-todo-list string))
4565 ((eq type 'tags-tree)
4566 (org-check-for-org-mode)
4567 (org-tags-sparse-tree current-prefix-arg string))
4568 ((eq type 'todo-tree)
4569 (org-check-for-org-mode)
4570 (org-occur (concat "^" outline-regexp "[ \t]*"
4571 (regexp-quote string) "\\>")))
4572 ((eq type 'occur-tree)
4573 (org-check-for-org-mode)
4574 (org-occur string))
4575 (t (error "Invalid custom agenda command type %s" type))))
4576 (t (error "Invalid key"))))))
4577
4578 (defun org-check-for-org-mode ()
4579 "Make sure current buffer is in org-mode. Error if not."
4580 (or (eq major-mode 'org-mode)
4581 (error "Cannot execute org-mode agenda command on buffer in %s."
4582 major-mode)))
4583
4584 (defun org-fit-agenda-window ()
4585 "Fit the window to the buffer size."
4586 (and org-fit-agenda-window
4587 (fboundp 'fit-window-to-buffer)
4588 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4589 (/ (frame-height) 2))))
4590
4591 (defun org-agenda-files ()
4592 "Get the list of agenda files."
4593 (or (get 'org-agenda-files 'org-restrict)
4594 org-agenda-files))
4595
4596 (defvar org-agenda-markers nil
4597 "List of all currently active markers created by `org-agenda'.")
4598 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4599 "Creation time of the last agenda marker.")
4600
4601 (defun org-agenda-new-marker (&optional pos)
4602 "Return a new agenda marker.
4603 Org-mode keeps a list of these markers and resets them when they are
4604 no longer in use."
4605 (let ((m (copy-marker (or pos (point)))))
4606 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4607 (push m org-agenda-markers)
4608 m))
4609
4610 (defun org-agenda-maybe-reset-markers (&optional force)
4611 "Reset markers created by `org-agenda'. But only if they are old enough."
4612 (if (or force
4613 (> (- (time-to-seconds (current-time))
4614 org-agenda-last-marker-time)
4615 5))
4616 (while org-agenda-markers
4617 (move-marker (pop org-agenda-markers) nil))))
4618
4619 (defvar org-agenda-new-buffers nil
4620 "Buffers created to visit agenda files.")
4621
4622 (defun org-get-agenda-file-buffer (file)
4623 "Get a buffer visiting FILE. If the buffer needs to be created, add
4624 it to the list of buffers which might be released later."
4625 (let ((buf (find-buffer-visiting file)))
4626 (if buf
4627 buf ; just return it
4628 ;; Make a new buffer and remember it
4629 (setq buf (find-file-noselect file))
4630 (if buf (push buf org-agenda-new-buffers))
4631 buf)))
4632
4633 (defun org-release-buffers (blist)
4634 "Release all buffers in list, asking the user for confirmation when needed.
4635 When a buffer is unmodified, it is just killed. When modified, it is saved
4636 \(if the user agrees) and then killed."
4637 (let (buf file)
4638 (while (setq buf (pop blist))
4639 (setq file (buffer-file-name buf))
4640 (when (and (buffer-modified-p buf)
4641 file
4642 (y-or-n-p (format "Save file %s? " file)))
4643 (with-current-buffer buf (save-buffer)))
4644 (kill-buffer buf))))
4645
4646 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4647
4648 (defun org-timeline (&optional include-all keep-modes)
4649 "Show a time-sorted view of the entries in the current org file.
4650 Only entries with a time stamp of today or later will be listed. With
4651 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4652 under the current date.
4653 If the buffer contains an active region, only check the region for
4654 dates."
4655 (interactive "P")
4656 (require 'calendar)
4657 (org-agenda-maybe-reset-markers 'force)
4658 (org-compile-prefix-format org-timeline-prefix-format)
4659 (let* ((dopast t)
4660 (dotodo include-all)
4661 (doclosed org-agenda-show-log)
4662 (org-agenda-keep-modes keep-modes)
4663 (entry buffer-file-name)
4664 (org-agenda-files (list buffer-file-name))
4665 (date (calendar-current-date))
4666 (win (selected-window))
4667 (pos1 (point))
4668 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4669 (end (if (org-region-active-p) (region-end) (point-max)))
4670 (day-numbers (org-get-all-dates beg end 'no-ranges
4671 t doclosed)) ; always include today
4672 (today (time-to-days (current-time)))
4673 (org-respect-restriction t)
4674 (past t)
4675 args
4676 s e rtn d)
4677 (setq org-agenda-redo-command
4678 (list 'progn
4679 (list 'switch-to-buffer-other-window (current-buffer))
4680 (list 'org-timeline (list 'quote include-all) t)))
4681 (if (not dopast)
4682 ;; Remove past dates from the list of dates.
4683 (setq day-numbers (delq nil (mapcar (lambda(x)
4684 (if (>= x today) x nil))
4685 day-numbers))))
4686 (switch-to-buffer-other-window
4687 (get-buffer-create org-agenda-buffer-name))
4688 (setq buffer-read-only nil)
4689 (erase-buffer)
4690 (org-agenda-mode) (setq buffer-read-only nil)
4691 (set (make-local-variable 'org-agenda-type) 'timeline)
4692 (if doclosed (push :closed args))
4693 (push :timestamp args)
4694 (if dotodo (push :todo args))
4695 (while (setq d (pop day-numbers))
4696 (if (and (>= d today)
4697 dopast
4698 past)
4699 (progn
4700 (setq past nil)
4701 (insert (make-string 79 ?-) "\n")))
4702 (setq date (calendar-gregorian-from-absolute d))
4703 (setq s (point))
4704 (setq rtn (apply 'org-agenda-get-day-entries
4705 entry date args))
4706 (if (or rtn (equal d today))
4707 (progn
4708 (insert (calendar-day-name date) " "
4709 (number-to-string (extract-calendar-day date)) " "
4710 (calendar-month-name (extract-calendar-month date)) " "
4711 (number-to-string (extract-calendar-year date)) "\n")
4712 (put-text-property s (1- (point)) 'face
4713 'org-link)
4714 (if (equal d today)
4715 (put-text-property s (1- (point)) 'org-today t))
4716 (insert (org-finalize-agenda-entries rtn) "\n")
4717 (put-text-property s (1- (point)) 'day d))))
4718 (goto-char (point-min))
4719 (setq buffer-read-only t)
4720 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4721 (point-min)))
4722 (when (not org-select-timeline-window)
4723 (select-window win)
4724 (goto-char pos1))))
4725
4726 ;;;###autoload
4727 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4728 "Produce a weekly view from all files in variable `org-agenda-files'.
4729 The view will be for the current week, but from the overview buffer you
4730 will be able to go to other weeks.
4731 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4732 also be shown, under the current date.
4733 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4734 on the days are also shown. See the variable `org-log-done' for how
4735 to turn on logging.
4736 START-DAY defaults to TODAY, or to the most recent match for the weekday
4737 given in `org-agenda-start-on-weekday'.
4738 NDAYS defaults to `org-agenda-ndays'."
4739 (interactive "P")
4740 (org-agenda-maybe-reset-markers 'force)
4741 (org-compile-prefix-format org-agenda-prefix-format)
4742 (require 'calendar)
4743 (let* ((org-agenda-start-on-weekday
4744 (if (or (equal ndays 1)
4745 (and (null ndays) (equal 1 org-agenda-ndays)))
4746 nil org-agenda-start-on-weekday))
4747 (org-agenda-keep-modes keep-modes)
4748 (files (copy-sequence (org-agenda-files)))
4749 (win (selected-window))
4750 (today (time-to-days (current-time)))
4751 (sd (or start-day today))
4752 (start (if (or (null org-agenda-start-on-weekday)
4753 (< org-agenda-ndays 7))
4754 sd
4755 (let* ((nt (calendar-day-of-week
4756 (calendar-gregorian-from-absolute sd)))
4757 (n1 org-agenda-start-on-weekday)
4758 (d (- nt n1)))
4759 (- sd (+ (if (< d 0) 7 0) d)))))
4760 (day-numbers (list start))
4761 (inhibit-redisplay t)
4762 s e rtn rtnall file date d start-pos end-pos todayp nd)
4763 (setq org-agenda-redo-command
4764 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4765 ;; Make the list of days
4766 (setq ndays (or ndays org-agenda-ndays)
4767 nd ndays)
4768 (while (> ndays 1)
4769 (push (1+ (car day-numbers)) day-numbers)
4770 (setq ndays (1- ndays)))
4771 (setq day-numbers (nreverse day-numbers))
4772 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4773 (progn
4774 (delete-other-windows)
4775 (switch-to-buffer-other-window
4776 (get-buffer-create org-agenda-buffer-name))))
4777 (setq buffer-read-only nil)
4778 (erase-buffer)
4779 (org-agenda-mode) (setq buffer-read-only nil)
4780 (set (make-local-variable 'org-agenda-type) 'agenda)
4781 (set (make-local-variable 'starting-day) (car day-numbers))
4782 (set (make-local-variable 'include-all-loc) include-all)
4783 (when (and (or include-all org-agenda-include-all-todo)
4784 (member today day-numbers))
4785 (setq files (org-agenda-files)
4786 rtnall nil)
4787 (while (setq file (pop files))
4788 (catch 'nextfile
4789 (org-check-agenda-file file)
4790 (setq date (calendar-gregorian-from-absolute today)
4791 rtn (org-agenda-get-day-entries
4792 file date :todo))
4793 (setq rtnall (append rtnall rtn))))
4794 (when rtnall
4795 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4796 (add-text-properties (point-min) (1- (point))
4797 (list 'face 'org-link))
4798 (insert (org-finalize-agenda-entries rtnall) "\n")))
4799 (while (setq d (pop day-numbers))
4800 (setq date (calendar-gregorian-from-absolute d)
4801 s (point))
4802 (if (or (setq todayp (= d today))
4803 (and (not start-pos) (= d sd)))
4804 (setq start-pos (point))
4805 (if (and start-pos (not end-pos))
4806 (setq end-pos (point))))
4807 (setq files (org-agenda-files)
4808 rtnall nil)
4809 (while (setq file (pop files))
4810 (catch 'nextfile
4811 (org-check-agenda-file file)
4812 (if org-agenda-show-log
4813 (setq rtn (org-agenda-get-day-entries
4814 file date
4815 :deadline :scheduled :timestamp :closed))
4816 (setq rtn (org-agenda-get-day-entries
4817 file date
4818 :deadline :scheduled :timestamp)))
4819 (setq rtnall (append rtnall rtn))))
4820 (if org-agenda-include-diary
4821 (progn
4822 (require 'diary-lib)
4823 (setq rtn (org-get-entries-from-diary date))
4824 (setq rtnall (append rtnall rtn))))
4825 (if (or rtnall org-agenda-show-all-dates)
4826 (progn
4827 (insert (format "%-9s %2d %s %4d\n"
4828 (calendar-day-name date)
4829 (extract-calendar-day date)
4830 (calendar-month-name (extract-calendar-month date))
4831 (extract-calendar-year date)))
4832 (put-text-property s (1- (point)) 'face
4833 'org-link)
4834 (if rtnall (insert
4835 (org-finalize-agenda-entries
4836 (org-agenda-add-time-grid-maybe
4837 rtnall nd todayp))
4838 "\n"))
4839 (put-text-property s (1- (point)) 'day d))))
4840 (goto-char (point-min))
4841 (setq buffer-read-only t)
4842 (org-fit-agenda-window)
4843 (unless (and (pos-visible-in-window-p (point-min))
4844 (pos-visible-in-window-p (point-max)))
4845 (goto-char (1- (point-max)))
4846 (recenter -1)
4847 (if (not (pos-visible-in-window-p (or start-pos 1)))
4848 (progn
4849 (goto-char (or start-pos 1))
4850 (recenter 1))))
4851 (goto-char (or start-pos 1))
4852 (if (not org-select-agenda-window) (select-window win))
4853 (message "")))
4854
4855 (defvar org-select-this-todo-keyword nil)
4856
4857 ;;;###autoload
4858 (defun org-todo-list (arg &optional keep-modes)
4859 "Show all TODO entries from all agenda file in a single list.
4860 The prefix arg can be used to select a specific TODO keyword and limit
4861 the list to these. When using \\[universal-argument], you will be prompted
4862 for a keyword. A numeric prefix directly selects the Nth keyword in
4863 `org-todo-keywords'."
4864 (interactive "P")
4865 (org-agenda-maybe-reset-markers 'force)
4866 (org-compile-prefix-format org-agenda-prefix-format)
4867 (let* ((org-agenda-keep-modes keep-modes)
4868 (today (time-to-days (current-time)))
4869 (date (calendar-gregorian-from-absolute today))
4870 (win (selected-window))
4871 (kwds org-todo-keywords)
4872 (completion-ignore-case t)
4873 (org-select-this-todo-keyword
4874 (if (stringp arg) arg
4875 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4876 rtn rtnall files file pos)
4877 (when (equal arg '(4))
4878 (setq org-select-this-todo-keyword
4879 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4880 nil t)))
4881 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4882 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4883 (progn
4884 (delete-other-windows)
4885 (switch-to-buffer-other-window
4886 (get-buffer-create org-agenda-buffer-name))))
4887 (setq buffer-read-only nil)
4888 (erase-buffer)
4889 (org-agenda-mode) (setq buffer-read-only nil)
4890 (set (make-local-variable 'org-agenda-type) 'todo)
4891 (set (make-local-variable 'last-arg) arg)
4892 (set (make-local-variable 'org-todo-keywords) kwds)
4893 (set (make-local-variable 'org-agenda-redo-command)
4894 '(org-todo-list (or current-prefix-arg last-arg) t))
4895 (setq files (org-agenda-files)
4896 rtnall nil)
4897 (while (setq file (pop files))
4898 (catch 'nextfile
4899 (org-check-agenda-file file)
4900 (setq rtn (org-agenda-get-day-entries file date :todo))
4901 (setq rtnall (append rtnall rtn))))
4902 (insert "Global list of TODO items of type: ")
4903 (add-text-properties (point-min) (1- (point))
4904 (list 'face 'org-link))
4905 (setq pos (point))
4906 (insert (or org-select-this-todo-keyword "ALL") "\n")
4907 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4908 (setq pos (point))
4909 (insert
4910 "Available with `N r': (0)ALL "
4911 (let ((n 0))
4912 (mapconcat (lambda (x)
4913 (format "(%d)%s" (setq n (1+ n)) x))
4914 org-todo-keywords " "))
4915 "\n")
4916 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4917 (when rtnall
4918 (insert (org-finalize-agenda-entries rtnall) "\n"))
4919 (goto-char (point-min))
4920 (setq buffer-read-only t)
4921 (org-fit-agenda-window)
4922 (if (not org-select-agenda-window) (select-window win))))
4923
4924 (defun org-check-agenda-file (file)
4925 "Make sure FILE exists. If not, ask user what to do."
4926 ;; FIXME: this does not correctly change the menus
4927 ;; Could probably be fixed by explicitly going to the buffer where
4928 ;; the call originated.
4929 (when (not (file-exists-p file))
4930 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4931 file)
4932 (let ((r (downcase (read-char-exclusive))))
4933 (cond
4934 ((equal r ?r)
4935 (org-remove-file file)
4936 (throw 'nextfile t))
4937 (t (error "Abort"))))))
4938
4939 (defun org-agenda-check-type (error &rest types)
4940 "Check if agenda buffer is of allowed type.
4941 If ERROR is non-nil, throw an error, otherwise just return nil."
4942 (if (memq org-agenda-type types)
4943 t
4944 (if error
4945 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
4946 nil)))
4947
4948 (defun org-agenda-quit ()
4949 "Exit agenda by removing the window or the buffer."
4950 (interactive)
4951 (let ((buf (current-buffer)))
4952 (if (not (one-window-p)) (delete-window))
4953 (kill-buffer buf)
4954 (org-agenda-maybe-reset-markers 'force)))
4955
4956 (defun org-agenda-exit ()
4957 "Exit agenda by removing the window or the buffer.
4958 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4959 Org-mode buffers visited directly by the user will not be touched."
4960 (interactive)
4961 (org-release-buffers org-agenda-new-buffers)
4962 (setq org-agenda-new-buffers nil)
4963 (org-agenda-quit))
4964
4965 (defun org-agenda-redo ()
4966 "Rebuild Agenda.
4967 When this is the global TODO list, a prefix argument will be interpreted."
4968 (interactive)
4969 (message "Rebuilding agenda buffer...")
4970 (eval org-agenda-redo-command)
4971 (message "Rebuilding agenda buffer...done"))
4972
4973 (defun org-agenda-goto-today ()
4974 "Go to today."
4975 (interactive)
4976 (org-agenda-check-type t 'timeline 'agenda)
4977 (if (boundp 'starting-day)
4978 (let ((cmd (car org-agenda-redo-command))
4979 (iall (nth 1 org-agenda-redo-command))
4980 (nday (nth 3 org-agenda-redo-command))
4981 (keep (nth 4 org-agenda-redo-command)))
4982 (eval (list cmd iall nil nday keep)))
4983 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4984 (point-min)))))
4985
4986 (defun org-agenda-later (arg)
4987 "Go forward in time by `org-agenda-ndays' days.
4988 With prefix ARG, go forward that many times `org-agenda-ndays'."
4989 (interactive "p")
4990 (org-agenda-check-type t 'agenda)
4991 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4992 (+ starting-day (* arg org-agenda-ndays)) nil t))
4993
4994 (defun org-agenda-earlier (arg)
4995 "Go back in time by `org-agenda-ndays' days.
4996 With prefix ARG, go back that many times `org-agenda-ndays'."
4997 (interactive "p")
4998 (org-agenda-check-type t 'agenda)
4999 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5000 (- starting-day (* arg org-agenda-ndays)) nil t))
5001
5002 (defun org-agenda-week-view ()
5003 "Switch to weekly view for agenda."
5004 (interactive)
5005 (org-agenda-check-type t 'agenda)
5006 (setq org-agenda-ndays 7)
5007 (org-agenda-list include-all-loc
5008 (or (get-text-property (point) 'day)
5009 starting-day)
5010 nil t)
5011 (org-agenda-set-mode-name)
5012 (message "Switched to week view"))
5013
5014 (defun org-agenda-day-view ()
5015 "Switch to daily view for agenda."
5016 (interactive)
5017 (org-agenda-check-type t 'agenda)
5018 (setq org-agenda-ndays 1)
5019 (org-agenda-list include-all-loc
5020 (or (get-text-property (point) 'day)
5021 starting-day)
5022 nil t)
5023 (org-agenda-set-mode-name)
5024 (message "Switched to day view"))
5025
5026 (defun org-agenda-next-date-line (&optional arg)
5027 "Jump to the next line indicating a date in agenda buffer."
5028 (interactive "p")
5029 (org-agenda-check-type t 'agenda 'timeline)
5030 (beginning-of-line 1)
5031 (if (looking-at "^\\S-") (forward-char 1))
5032 (if (not (re-search-forward "^\\S-" nil t arg))
5033 (progn
5034 (backward-char 1)
5035 (error "No next date after this line in this buffer")))
5036 (goto-char (match-beginning 0)))
5037
5038 (defun org-agenda-previous-date-line (&optional arg)
5039 "Jump to the previous line indicating a date in agenda buffer."
5040 (interactive "p")
5041 (org-agenda-check-type t 'agenda 'timeline)
5042 (beginning-of-line 1)
5043 (if (not (re-search-backward "^\\S-" nil t arg))
5044 (error "No previous date before this line in this buffer")))
5045
5046 ;; Initialize the highlight
5047 (defvar org-hl (org-make-overlay 1 1))
5048 (org-overlay-put org-hl 'face 'highlight)
5049
5050 (defun org-highlight (begin end &optional buffer)
5051 "Highlight a region with overlay."
5052 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
5053 org-hl begin end (or buffer (current-buffer))))
5054
5055 (defun org-unhighlight ()
5056 "Detach overlay INDEX."
5057 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
5058
5059
5060 (defun org-agenda-follow-mode ()
5061 "Toggle follow mode in an agenda buffer."
5062 (interactive)
5063 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5064 (org-agenda-set-mode-name)
5065 (message "Follow mode is %s"
5066 (if org-agenda-follow-mode "on" "off")))
5067
5068 (defun org-agenda-log-mode ()
5069 "Toggle log mode in an agenda buffer."
5070 (interactive)
5071 (org-agenda-check-type t 'agenda 'timeline)
5072 (setq org-agenda-show-log (not org-agenda-show-log))
5073 (org-agenda-set-mode-name)
5074 (org-agenda-redo)
5075 (message "Log mode is %s"
5076 (if org-agenda-show-log "on" "off")))
5077
5078 (defun org-agenda-toggle-diary ()
5079 "Toggle diary inclusion in an agenda buffer."
5080 (interactive)
5081 (org-agenda-check-type t 'agenda)
5082 (setq org-agenda-include-diary (not org-agenda-include-diary))
5083 (org-agenda-redo)
5084 (org-agenda-set-mode-name)
5085 (message "Diary inclusion turned %s"
5086 (if org-agenda-include-diary "on" "off")))
5087
5088 (defun org-agenda-toggle-time-grid ()
5089 "Toggle time grid in an agenda buffer."
5090 (interactive)
5091 (org-agenda-check-type t 'agenda)
5092 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5093 (org-agenda-redo)
5094 (org-agenda-set-mode-name)
5095 (message "Time-grid turned %s"
5096 (if org-agenda-use-time-grid "on" "off")))
5097
5098 (defun org-agenda-set-mode-name ()
5099 "Set the mode name to indicate all the small mode settings."
5100 (setq mode-name
5101 (concat "Org-Agenda"
5102 (if (equal org-agenda-ndays 1) " Day" "")
5103 (if (equal org-agenda-ndays 7) " Week" "")
5104 (if org-agenda-follow-mode " Follow" "")
5105 (if org-agenda-include-diary " Diary" "")
5106 (if org-agenda-use-time-grid " Grid" "")
5107 (if org-agenda-show-log " Log" "")))
5108 (force-mode-line-update))
5109
5110 (defun org-agenda-post-command-hook ()
5111 (and (eolp) (not (bolp)) (backward-char 1))
5112 (if (and org-agenda-follow-mode
5113 (get-text-property (point) 'org-marker))
5114 (org-agenda-show)))
5115
5116 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5117
5118 (defun org-get-entries-from-diary (date)
5119 "Get the (Emacs Calendar) diary entries for DATE."
5120 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5121 (diary-display-hook '(fancy-diary-display))
5122 (list-diary-entries-hook
5123 (cons 'org-diary-default-entry list-diary-entries-hook))
5124 (diary-file-name-prefix-function nil) ; turn this feature off
5125 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5126 entries
5127 (org-disable-agenda-to-diary t))
5128 (save-excursion
5129 (save-window-excursion
5130 (list-diary-entries date 1)))
5131 (if (not (get-buffer fancy-diary-buffer))
5132 (setq entries nil)
5133 (with-current-buffer fancy-diary-buffer
5134 (setq buffer-read-only nil)
5135 (if (= (point-max) 1)
5136 ;; No entries
5137 (setq entries nil)
5138 ;; Omit the date and other unnecessary stuff
5139 (org-agenda-cleanup-fancy-diary)
5140 ;; Add prefix to each line and extend the text properties
5141 (if (= (point-max) 1)
5142 (setq entries nil)
5143 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5144 (set-buffer-modified-p nil)
5145 (kill-buffer fancy-diary-buffer)))
5146 (when entries
5147 (setq entries (org-split-string entries "\n"))
5148 (setq entries
5149 (mapcar
5150 (lambda (x)
5151 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5152 ;; Extend the text properties to the beginning of the line
5153 (add-text-properties
5154 0 (length x)
5155 (text-properties-at (1- (length x)) x)
5156 x)
5157 x)
5158 entries)))))
5159
5160 (defun org-agenda-cleanup-fancy-diary ()
5161 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5162 This gets rid of the date, the underline under the date, and
5163 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5164 date. It also removes lines that contain only whitespace."
5165 (goto-char (point-min))
5166 (if (looking-at ".*?:[ \t]*")
5167 (progn
5168 (replace-match "")
5169 (re-search-forward "\n=+$" nil t)
5170 (replace-match "")
5171 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5172 (re-search-forward "\n=+$" nil t)
5173 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5174 (goto-char (point-min))
5175 (while (re-search-forward "^ +\n" nil t)
5176 (replace-match ""))
5177 (goto-char (point-min))
5178 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5179 (replace-match "")))
5180
5181 ;; Make sure entries from the diary have the right text properties.
5182 (eval-after-load "diary-lib"
5183 '(if (boundp 'diary-modify-entry-list-string-function)
5184 ;; We can rely on the hook, nothing to do
5185 nil
5186 ;; Hook not avaiable, must use advice to make this work
5187 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5188 "Make the position visible."
5189 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5190 (stringp string)
5191 buffer-file-name)
5192 (setq string (org-modify-diary-entry-string string))))))
5193
5194 (defun org-modify-diary-entry-string (string)
5195 "Add text properties to string, allowing org-mode to act on it."
5196 (add-text-properties
5197 0 (length string)
5198 (list 'mouse-face 'highlight
5199 'keymap org-agenda-keymap
5200 'help-echo
5201 (format
5202 "mouse-2 or RET jump to diary file %s"
5203 (abbreviate-file-name buffer-file-name))
5204 'org-agenda-diary-link t
5205 'org-marker (org-agenda-new-marker (point-at-bol)))
5206 string)
5207 string)
5208
5209 (defun org-diary-default-entry ()
5210 "Add a dummy entry to the diary.
5211 Needed to avoid empty dates which mess up holiday display."
5212 ;; Catch the error if dealing with the new add-to-diary-alist
5213 (when org-disable-agenda-to-diary
5214 (condition-case nil
5215 (add-to-diary-list original-date "Org-mode dummy" "")
5216 (error
5217 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5218
5219 (defun org-cycle-agenda-files ()
5220 "Cycle through the files in `org-agenda-files'.
5221 If the current buffer visits an agenda file, find the next one in the list.
5222 If the current buffer does not, find the first agenda file."
5223 (interactive)
5224 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5225 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5226 file)
5227 (unless files (error "No agenda files"))
5228 (catch 'exit
5229 (while (setq file (pop files))
5230 (if (equal (file-truename file) tcf)
5231 (when (car files)
5232 (find-file (car files))
5233 (throw 'exit t))))
5234 (find-file (car org-agenda-files)))))
5235
5236 (defun org-agenda-file-to-end ()
5237 "Move/add the current file to the end of the agenda file list.
5238 If the file is not present in the list, it is appended to the list. If it is
5239 present, it is moved there."
5240 (interactive)
5241 (org-agenda-file-to-front 'to-end))
5242
5243 (defun org-agenda-file-to-front (&optional to-end)
5244 "Move/add the current file to the top of the agenda file list.
5245 If the file is not present in the list, it is added to the front. If it is
5246 present, it is moved there. With optional argument TO-END, add/move to the
5247 end of the list."
5248 (interactive "P")
5249 (let ((file-alist (mapcar (lambda (x)
5250 (cons (file-truename x) x))
5251 org-agenda-files))
5252 (ctf (file-truename buffer-file-name))
5253 x had)
5254 (setq x (assoc ctf file-alist) had x)
5255
5256 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5257 (if to-end
5258 (setq file-alist (append (delq x file-alist) (list x)))
5259 (setq file-alist (cons x (delq x file-alist))))
5260 (setq org-agenda-files (mapcar 'cdr file-alist))
5261 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5262 (customize-save-variable 'org-agenda-files org-agenda-files))
5263 (org-install-agenda-files-menu)
5264 (message "File %s to %s of agenda file list"
5265 (if had "moved" "added") (if to-end "end" "front"))))
5266
5267 (defun org-remove-file (&optional file)
5268 "Remove current file from the list of files in variable `org-agenda-files'.
5269 These are the files which are being checked for agenda entries.
5270 Optional argument FILE means, use this file instead of the current."
5271 (interactive)
5272 (let* ((file (or file buffer-file-name))
5273 (true-file (file-truename file))
5274 (afile (abbreviate-file-name file))
5275 (files (delq nil (mapcar
5276 (lambda (x)
5277 (if (equal true-file
5278 (file-truename x))
5279 nil x))
5280 org-agenda-files))))
5281 (if (not (= (length files) (length org-agenda-files)))
5282 (progn
5283 (setq org-agenda-files files)
5284 (customize-save-variable 'org-agenda-files org-agenda-files)
5285 (org-install-agenda-files-menu)
5286 (message "Removed file: %s" afile))
5287 (message "File was not in list: %s" afile))))
5288
5289 (defun org-file-menu-entry (file)
5290 (vector file (list 'find-file file) t))
5291 ;; FIXME: Maybe we removed a buffer visited through the menu from
5292 ;; org-agenda-new-buffers, so that the buffer will not be removed
5293 ;; when exiting the agenda????
5294
5295 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5296 "Return a list of all relevant day numbers from BEG to END buffer positions.
5297 If NO-RANGES is non-nil, include only the start and end dates of a range,
5298 not every single day in the range. If FORCE-TODAY is non-nil, make
5299 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5300 inactive time stamps (those in square brackets) are included."
5301 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5302 dates date day day1 day2 ts1 ts2)
5303 (if force-today
5304 (setq dates (list (time-to-days (current-time)))))
5305 (save-excursion
5306 (goto-char beg)
5307 (while (re-search-forward re end t)
5308 (setq day (time-to-days (org-time-string-to-time
5309 (substring (match-string 1) 0 10))))
5310 (or (memq day dates) (push day dates)))
5311 (unless no-ranges
5312 (goto-char beg)
5313 (while (re-search-forward org-tr-regexp end t)
5314 (setq ts1 (substring (match-string 1) 0 10)
5315 ts2 (substring (match-string 2) 0 10)
5316 day1 (time-to-days (org-time-string-to-time ts1))
5317 day2 (time-to-days (org-time-string-to-time ts2)))
5318 (while (< (setq day1 (1+ day1)) day2)
5319 (or (memq day1 dates) (push day1 dates)))))
5320 (sort dates '<))))
5321
5322 ;;;###autoload
5323 (defun org-diary (&rest args)
5324 "Return diary information from org-files.
5325 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5326 It accesses org files and extracts information from those files to be
5327 listed in the diary. The function accepts arguments specifying what
5328 items should be listed. The following arguments are allowed:
5329
5330 :timestamp List the headlines of items containing a date stamp or
5331 date range matching the selected date. Deadlines will
5332 also be listed, on the expiration day.
5333
5334 :deadline List any deadlines past due, or due within
5335 `org-deadline-warning-days'. The listing occurs only
5336 in the diary for *today*, not at any other date. If
5337 an entry is marked DONE, it is no longer listed.
5338
5339 :scheduled List all items which are scheduled for the given date.
5340 The diary for *today* also contains items which were
5341 scheduled earlier and are not yet marked DONE.
5342
5343 :todo List all TODO items from the org-file. This may be a
5344 long list - so this is not turned on by default.
5345 Like deadlines, these entries only show up in the
5346 diary for *today*, not at any other date.
5347
5348 The call in the diary file should look like this:
5349
5350 &%%(org-diary) ~/path/to/some/orgfile.org
5351
5352 Use a separate line for each org file to check. Or, if you omit the file name,
5353 all files listed in `org-agenda-files' will be checked automatically:
5354
5355 &%%(org-diary)
5356
5357 If you don't give any arguments (as in the example above), the default
5358 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5359 also be written as
5360
5361 &%%(org-diary :deadline :timestamp :scheduled)
5362
5363 The function expects the lisp variables `entry' and `date' to be provided
5364 by the caller, because this is how the calendar works. Don't use this
5365 function from a program - use `org-agenda-get-day-entries' instead."
5366 (org-agenda-maybe-reset-markers)
5367 (org-compile-prefix-format org-agenda-prefix-format)
5368 (setq args (or args '(:deadline :scheduled :timestamp)))
5369 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5370 (list entry)
5371 org-agenda-files))
5372 file rtn results)
5373 ;; If this is called during org-agenda, don't return any entries to
5374 ;; the calendar. Org Agenda will list these entries itself.
5375 (if org-disable-agenda-to-diary (setq files nil))
5376 (while (setq file (pop files))
5377 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5378 (setq results (append results rtn)))
5379 (if results
5380 (concat (org-finalize-agenda-entries results) "\n"))))
5381 (defvar org-category-table nil)
5382 (defun org-get-category-table ()
5383 "Get the table of categories and positions in current buffer."
5384 (let (tbl)
5385 (save-excursion
5386 (goto-char (point-min))
5387 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5388 (push (cons (point) (org-trim (match-string 2))) tbl)))
5389 tbl))
5390 (defun org-get-category (&optional pos)
5391 "Get the category applying to position POS."
5392 (if (not org-category-table)
5393 (cond
5394 ((null org-category)
5395 (setq org-category
5396 (if buffer-file-name
5397 (file-name-sans-extension
5398 (file-name-nondirectory buffer-file-name))
5399 "???")))
5400 ((symbolp org-category) (symbol-name org-category))
5401 (t org-category))
5402 (let ((tbl org-category-table)
5403 (pos (or pos (point))))
5404 (while (and tbl (> (caar tbl) pos))
5405 (pop tbl))
5406 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5407 org-category-table))))))
5408
5409 (defun org-agenda-get-day-entries (file date &rest args)
5410 "Does the work for `org-diary' and `org-agenda'.
5411 FILE is the path to a file to be checked for entries. DATE is date like
5412 the one returned by `calendar-current-date'. ARGS are symbols indicating
5413 which kind of entries should be extracted. For details about these, see
5414 the documentation of `org-diary'."
5415 (setq args (or args '(:deadline :scheduled :timestamp)))
5416 (let* ((org-startup-with-deadline-check nil)
5417 (org-startup-folded nil)
5418 (buffer (if (file-exists-p file)
5419 (org-get-agenda-file-buffer file)
5420 (error "No such file %s" file)))
5421 arg results rtn)
5422 (if (not buffer)
5423 ;; If file does not exist, make sure an error message ends up in diary
5424 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5425 (with-current-buffer buffer
5426 (unless (eq major-mode 'org-mode)
5427 (error "Agenda file %s is not in `org-mode'" file))
5428 (setq org-category-table (org-get-category-table))
5429 (let ((case-fold-search nil))
5430 (save-excursion
5431 (save-restriction
5432 (if org-respect-restriction
5433 (if (org-region-active-p)
5434 ;; Respect a region to restrict search
5435 (narrow-to-region (region-beginning) (region-end)))
5436 ;; If we work for the calendar or many files,
5437 ;; get rid of any restriction
5438 (widen))
5439 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5440 (while (setq arg (pop args))
5441 (cond
5442 ((and (eq arg :todo)
5443 (equal date (calendar-current-date)))
5444 (setq rtn (org-agenda-get-todos))
5445 (setq results (append results rtn)))
5446 ((eq arg :timestamp)
5447 (setq rtn (org-agenda-get-blocks))
5448 (setq results (append results rtn))
5449 (setq rtn (org-agenda-get-timestamps))
5450 (setq results (append results rtn)))
5451 ((eq arg :scheduled)
5452 (setq rtn (org-agenda-get-scheduled))
5453 (setq results (append results rtn)))
5454 ((eq arg :closed)
5455 (setq rtn (org-agenda-get-closed))
5456 (setq results (append results rtn)))
5457 ((and (eq arg :deadline)
5458 (equal date (calendar-current-date)))
5459 (setq rtn (org-agenda-get-deadlines))
5460 (setq results (append results rtn))))))))
5461 results))))
5462
5463 (defun org-entry-is-done-p ()
5464 "Is the current entry marked DONE?"
5465 (save-excursion
5466 (and (re-search-backward "[\r\n]\\*" nil t)
5467 (looking-at org-nl-done-regexp))))
5468
5469 (defun org-at-date-range-p ()
5470 "Is the cursor inside a date range?"
5471 (interactive)
5472 (save-excursion
5473 (catch 'exit
5474 (let ((pos (point)))
5475 (skip-chars-backward "^<\r\n")
5476 (skip-chars-backward "<")
5477 (and (looking-at org-tr-regexp)
5478 (>= (match-end 0) pos)
5479 (throw 'exit t))
5480 (skip-chars-backward "^<\r\n")
5481 (skip-chars-backward "<")
5482 (and (looking-at org-tr-regexp)
5483 (>= (match-end 0) pos)
5484 (throw 'exit t)))
5485 nil)))
5486
5487 (defun org-agenda-get-todos ()
5488 "Return the TODO information for agenda display."
5489 (let* ((props (list 'face nil
5490 'done-face 'org-done
5491 'mouse-face 'highlight
5492 'keymap org-agenda-keymap
5493 'help-echo
5494 (format "mouse-2 or RET jump to org file %s"
5495 (abbreviate-file-name buffer-file-name))))
5496 (regexp (concat "[\n\r]\\*+ *\\("
5497 (if org-select-this-todo-keyword
5498 (concat "\\<\\(" org-select-this-todo-keyword
5499 "\\)\\>")
5500 org-not-done-regexp)
5501 "[^\n\r]*\\)"))
5502 marker priority category tags
5503 ee txt)
5504 (goto-char (point-min))
5505 (while (re-search-forward regexp nil t)
5506 (goto-char (match-beginning 1))
5507 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5508 category (org-get-category)
5509 tags (org-get-tags-at (point))
5510 txt (org-format-agenda-item "" (match-string 1) category tags)
5511 priority
5512 (+ (org-get-priority txt)
5513 (if org-todo-kwd-priority-p
5514 (- org-todo-kwd-max-priority -2
5515 (length
5516 (member (match-string 2) org-todo-keywords)))
5517 1)))
5518 (add-text-properties
5519 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5520 'priority priority 'category category)
5521 props)
5522 txt)
5523 (push txt ee)
5524 (goto-char (match-end 1)))
5525 (nreverse ee)))
5526
5527 (defconst org-agenda-no-heading-message
5528 "No heading for this item in buffer or region.")
5529
5530 (defun org-agenda-get-timestamps ()
5531 "Return the date stamp information for agenda display."
5532 (let* ((props (list 'face nil
5533 'mouse-face 'highlight
5534 'keymap org-agenda-keymap
5535 'help-echo
5536 (format "mouse-2 or RET jump to org file %s"
5537 (abbreviate-file-name buffer-file-name))))
5538 (regexp (regexp-quote
5539 (substring
5540 (format-time-string
5541 (car org-time-stamp-formats)
5542 (apply 'encode-time ; DATE bound by calendar
5543 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5544 0 11)))
5545 marker hdmarker deadlinep scheduledp donep tmp priority category
5546 ee txt timestr tags)
5547 (goto-char (point-min))
5548 (while (re-search-forward regexp nil t)
5549 (if (not (save-match-data (org-at-date-range-p)))
5550 (progn
5551 (setq marker (org-agenda-new-marker (match-beginning 0))
5552 category (org-get-category (match-beginning 0))
5553 tmp (buffer-substring (max (point-min)
5554 (- (match-beginning 0)
5555 org-ds-keyword-length))
5556 (match-beginning 0))
5557 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5558 deadlinep (string-match org-deadline-regexp tmp)
5559 scheduledp (string-match org-scheduled-regexp tmp)
5560 donep (org-entry-is-done-p))
5561 (if (string-match ">" timestr)
5562 ;; substring should only run to end of time stamp
5563 (setq timestr (substring timestr 0 (match-end 0))))
5564 (save-excursion
5565 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5566 (progn
5567 (goto-char (match-end 1))
5568 (setq hdmarker (org-agenda-new-marker)
5569 tags (org-get-tags-at))
5570 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5571 (setq txt (org-format-agenda-item
5572 (format "%s%s"
5573 (if deadlinep "Deadline: " "")
5574 (if scheduledp "Scheduled: " ""))
5575 (match-string 1) category tags timestr)))
5576 (setq txt org-agenda-no-heading-message))
5577 (setq priority (org-get-priority txt))
5578 (add-text-properties
5579 0 (length txt) (append (list 'org-marker marker
5580 'org-hd-marker hdmarker) props)
5581 txt)
5582 (if deadlinep
5583 (add-text-properties
5584 0 (length txt)
5585 (list 'face
5586 (if donep 'org-done 'org-warning)
5587 'undone-face 'org-warning
5588 'done-face 'org-done
5589 'category category
5590 'priority (+ 100 priority))
5591 txt)
5592 (if scheduledp
5593 (add-text-properties
5594 0 (length txt)
5595 (list 'face 'org-scheduled-today
5596 'undone-face 'org-scheduled-today
5597 'done-face 'org-done
5598 'category category
5599 priority (+ 99 priority))
5600 txt)
5601 (add-text-properties
5602 0 (length txt)
5603 (list 'priority priority 'category category) txt)))
5604 (push txt ee))
5605 (outline-next-heading))))
5606 (nreverse ee)))
5607
5608 (defun org-agenda-get-closed ()
5609 "Return the logged TODO entries for agenda display."
5610 (let* ((props (list 'mouse-face 'highlight
5611 'keymap org-agenda-keymap
5612 'help-echo
5613 (format "mouse-2 or RET jump to org file %s"
5614 (abbreviate-file-name buffer-file-name))))
5615 (regexp (concat
5616 "\\<" org-closed-string " *\\["
5617 (regexp-quote
5618 (substring
5619 (format-time-string
5620 (car org-time-stamp-formats)
5621 (apply 'encode-time ; DATE bound by calendar
5622 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5623 1 11))))
5624 marker hdmarker priority category tags
5625 ee txt timestr)
5626 (goto-char (point-min))
5627 (while (re-search-forward regexp nil t)
5628 (if (not (save-match-data (org-at-date-range-p)))
5629 (progn
5630 (setq marker (org-agenda-new-marker (match-beginning 0))
5631 category (org-get-category (match-beginning 0))
5632 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5633 ;; donep (org-entry-is-done-p)
5634 )
5635 (if (string-match "\\]" timestr)
5636 ;; substring should only run to end of time stamp
5637 (setq timestr (substring timestr 0 (match-end 0))))
5638 (save-excursion
5639 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5640 (progn
5641 (goto-char (match-end 1))
5642 (setq hdmarker (org-agenda-new-marker)
5643 tags (org-get-tags-at))
5644 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5645 (setq txt (org-format-agenda-item
5646 "Closed: "
5647 (match-string 1) category tags timestr)))
5648 (setq txt org-agenda-no-heading-message))
5649 (setq priority 100000)
5650 (add-text-properties
5651 0 (length txt) (append (list 'org-marker marker
5652 'org-hd-marker hdmarker
5653 'face 'org-done
5654 'priority priority
5655 'category category
5656 'undone-face 'org-warning
5657 'done-face 'org-done) props)
5658 txt)
5659 (push txt ee))
5660 (outline-next-heading))))
5661 (nreverse ee)))
5662
5663 (defun org-agenda-get-deadlines ()
5664 "Return the deadline information for agenda display."
5665 (let* ((wdays org-deadline-warning-days)
5666 (props (list 'mouse-face 'highlight
5667 'keymap org-agenda-keymap
5668 'help-echo
5669 (format "mouse-2 or RET jump to org file %s"
5670 (abbreviate-file-name buffer-file-name))))
5671 (regexp org-deadline-time-regexp)
5672 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5673 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5674 d2 diff pos pos1 category tags
5675 ee txt head)
5676 (goto-char (point-min))
5677 (while (re-search-forward regexp nil t)
5678 (setq pos (1- (match-beginning 1))
5679 d2 (time-to-days
5680 (org-time-string-to-time (match-string 1)))
5681 diff (- d2 d1))
5682 ;; When to show a deadline in the calendar:
5683 ;; If the expiration is within wdays warning time.
5684 ;; Past-due deadlines are only shown on the current date
5685 (if (and (< diff wdays) todayp (not (= diff 0)))
5686 (save-excursion
5687 (setq category (org-get-category))
5688 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5689 (progn
5690 (goto-char (match-end 0))
5691 (setq pos1 (match-end 1))
5692 (setq tags (org-get-tags-at pos1))
5693 (setq head (buffer-substring-no-properties
5694 (point)
5695 (progn (skip-chars-forward "^\r\n")
5696 (point))))
5697 (if (string-match org-looking-at-done-regexp head)
5698 (setq txt nil)
5699 (setq txt (org-format-agenda-item
5700 (format "In %3d d.: " diff) head category tags))))
5701 (setq txt org-agenda-no-heading-message))
5702 (when txt
5703 (add-text-properties
5704 0 (length txt)
5705 (append
5706 (list 'org-marker (org-agenda-new-marker pos)
5707 'org-hd-marker (org-agenda-new-marker pos1)
5708 'priority (+ (- 10 diff) (org-get-priority txt))
5709 'category category
5710 'face (cond ((<= diff 0) 'org-warning)
5711 ((<= diff 5) 'org-scheduled-previously)
5712 (t nil))
5713 'undone-face (cond
5714 ((<= diff 0) 'org-warning)
5715 ((<= diff 5) 'org-scheduled-previously)
5716 (t nil))
5717 'done-face 'org-done)
5718 props)
5719 txt)
5720 (push txt ee)))))
5721 ee))
5722
5723 (defun org-agenda-get-scheduled ()
5724 "Return the scheduled information for agenda display."
5725 (let* ((props (list 'face 'org-scheduled-previously
5726 'undone-face 'org-scheduled-previously
5727 'done-face 'org-done
5728 'mouse-face 'highlight
5729 'keymap org-agenda-keymap
5730 'help-echo
5731 (format "mouse-2 or RET jump to org file %s"
5732 (abbreviate-file-name buffer-file-name))))
5733 (regexp org-scheduled-time-regexp)
5734 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5735 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5736 d2 diff pos pos1 category tags
5737 ee txt head)
5738 (goto-char (point-min))
5739 (while (re-search-forward regexp nil t)
5740 (setq pos (1- (match-beginning 1))
5741 d2 (time-to-days
5742 (org-time-string-to-time (match-string 1)))
5743 diff (- d2 d1))
5744 ;; When to show a scheduled item in the calendar:
5745 ;; If it is on or past the date.
5746 (if (and (< diff 0) todayp)
5747 (save-excursion
5748 (setq category (org-get-category))
5749 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5750 (progn
5751 (goto-char (match-end 0))
5752 (setq pos1 (match-end 1))
5753 (setq tags (org-get-tags-at))
5754 (setq head (buffer-substring-no-properties
5755 (point)
5756 (progn (skip-chars-forward "^\r\n") (point))))
5757 (if (string-match org-looking-at-done-regexp head)
5758 (setq txt nil)
5759 (setq txt (org-format-agenda-item
5760 (format "Sched.%2dx: " (- 1 diff)) head
5761 category tags))))
5762 (setq txt org-agenda-no-heading-message))
5763 (when txt
5764 (add-text-properties
5765 0 (length txt)
5766 (append (list 'org-marker (org-agenda-new-marker pos)
5767 'org-hd-marker (org-agenda-new-marker pos1)
5768 'priority (+ (- 5 diff) (org-get-priority txt))
5769 'category category)
5770 props) txt)
5771 (push txt ee)))))
5772 ee))
5773
5774 (defun org-agenda-get-blocks ()
5775 "Return the date-range information for agenda display."
5776 (let* ((props (list 'face nil
5777 'mouse-face 'highlight
5778 'keymap org-agenda-keymap
5779 'help-echo
5780 (format "mouse-2 or RET jump to org file %s"
5781 (abbreviate-file-name buffer-file-name))))
5782 (regexp org-tr-regexp)
5783 (d0 (calendar-absolute-from-gregorian date))
5784 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
5785 (goto-char (point-min))
5786 (while (re-search-forward regexp nil t)
5787 (setq timestr (match-string 0)
5788 s1 (match-string 1)
5789 s2 (match-string 2)
5790 d1 (time-to-days (org-time-string-to-time s1))
5791 d2 (time-to-days (org-time-string-to-time s2)))
5792 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5793 ;; Only allow days between the limits, because the normal
5794 ;; date stamps will catch the limits.
5795 (save-excursion
5796 (setq marker (org-agenda-new-marker (point)))
5797 (setq category (org-get-category))
5798 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5799 (progn
5800 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5801 (goto-char (match-end 1))
5802 (setq tags (org-get-tags-at))
5803 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5804 (setq txt (org-format-agenda-item
5805 (format (if (= d1 d2) "" "(%d/%d): ")
5806 (1+ (- d0 d1)) (1+ (- d2 d1)))
5807 (match-string 1) category tags
5808 (if (= d0 d1) timestr))))
5809 (setq txt org-agenda-no-heading-message))
5810 (add-text-properties
5811 0 (length txt) (append (list 'org-marker marker
5812 'org-hd-marker hdmarker
5813 'priority (org-get-priority txt)
5814 'category category)
5815 props)
5816 txt)
5817 (push txt ee)))
5818 (outline-next-heading))
5819 ;; Sort the entries by expiration date.
5820 (nreverse ee)))
5821
5822 (defconst org-plain-time-of-day-regexp
5823 (concat
5824 "\\(\\<[012]?[0-9]"
5825 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5826 "\\(--?"
5827 "\\(\\<[012]?[0-9]"
5828 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5829 "\\)?")
5830 "Regular expression to match a plain time or time range.
5831 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5832 groups carry important information:
5833 0 the full match
5834 1 the first time, range or not
5835 8 the second time, if it is a range.")
5836
5837 (defconst org-stamp-time-of-day-regexp
5838 (concat
5839 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5840 "\\([012][0-9]:[0-5][0-9]\\)>"
5841 "\\(--?"
5842 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5843 "Regular expression to match a timestamp time or time range.
5844 After a match, the following groups carry important information:
5845 0 the full match
5846 1 date plus weekday, for backreferencing to make sure both times on same day
5847 2 the first time, range or not
5848 4 the second time, if it is a range.")
5849
5850 (defvar org-prefix-has-time nil
5851 "A flag, set by `org-compile-prefix-format'.
5852 The flag is set if the currently compiled format contains a `%t'.")
5853 (defvar org-prefix-has-tag nil
5854 "A flag, set by `org-compile-prefix-format'.
5855 The flag is set if the currently compiled format contains a `%T'.")
5856
5857 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
5858 "Format TXT to be inserted into the agenda buffer.
5859 In particular, it adds the prefix and corresponding text properties. EXTRA
5860 must be a string and replaces the `%s' specifier in the prefix format.
5861 CATEGORY (string, symbol or nil) may be used to overrule the default
5862 category taken from local variable or file name. It will replace the `%c'
5863 specifier in the format. DOTIME, when non-nil, indicates that a
5864 time-of-day should be extracted from TXT for sorting of this entry, and for
5865 the `%t' specifier in the format. When DOTIME is a string, this string is
5866 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5867 only the correctly processes TXT should be returned - this is used by
5868 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
5869 (save-match-data
5870 ;; Diary entries sometimes have extra whitespace at the beginning
5871 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5872 (let* ((category (or category
5873 org-category
5874 (if buffer-file-name
5875 (file-name-sans-extension
5876 (file-name-nondirectory buffer-file-name))
5877 "")))
5878 (tag (or (nth (1- (or (length tags) 0)) tags) ""))
5879 time ;; needed for the eval of the prefix format
5880 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5881 (time-of-day (and dotime (org-get-time-of-day ts)))
5882 stamp plain s0 s1 s2 rtn)
5883 (when (and dotime time-of-day org-prefix-has-time)
5884 ;; Extract starting and ending time and move them to prefix
5885 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5886 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5887 (setq s0 (match-string 0 ts)
5888 s1 (match-string (if plain 1 2) ts)
5889 s2 (match-string (if plain 8 4) ts))
5890
5891 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5892 ;; them, we might want to remove them there to avoid duplication.
5893 ;; The user can turn this off with a variable.
5894 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5895 (string-match (concat (regexp-quote s0) " *") txt)
5896 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5897 (= (match-beginning 0) 0)
5898 t))
5899 (setq txt (replace-match "" nil nil txt))))
5900 ;; Normalize the time(s) to 24 hour
5901 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5902 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5903
5904 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
5905 (and org-agenda-remove-tags-when-in-prefix
5906 org-prefix-has-tag))
5907 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
5908 (setq txt (replace-match "" t t txt)))
5909
5910 ;; Create the final string
5911 (if noprefix
5912 (setq rtn txt)
5913 ;; Prepare the variables needed in the eval of the compiled format
5914 (setq time (cond (s2 (concat s1 "-" s2))
5915 (s1 (concat s1 "......"))
5916 (t ""))
5917 extra (or extra "")
5918 category (if (symbolp category) (symbol-name category) category))
5919 ;; Evaluate the compiled format
5920 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5921
5922 ;; And finally add the text properties
5923 (add-text-properties
5924 0 (length rtn) (list 'category (downcase category)
5925 'tags tags
5926 'prefix-length (- (length rtn) (length txt))
5927 'time-of-day time-of-day
5928 'dotime dotime)
5929 rtn)
5930 rtn)))
5931
5932 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5933 (catch 'exit
5934 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5935 ((and todayp (member 'today (car org-agenda-time-grid))))
5936 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5937 ((member 'weekly (car org-agenda-time-grid)))
5938 (t (throw 'exit list)))
5939 (let* ((have (delq nil (mapcar
5940 (lambda (x) (get-text-property 1 'time-of-day x))
5941 list)))
5942 (string (nth 1 org-agenda-time-grid))
5943 (gridtimes (nth 2 org-agenda-time-grid))
5944 (req (car org-agenda-time-grid))
5945 (remove (member 'remove-match req))
5946 new time)
5947 (if (and (member 'require-timed req) (not have))
5948 ;; don't show empty grid
5949 (throw 'exit list))
5950 (while (setq time (pop gridtimes))
5951 (unless (and remove (member time have))
5952 (setq time (int-to-string time))
5953 (push (org-format-agenda-item
5954 nil string "" nil ;; FIXME: put a category for the grid?
5955 (concat (substring time 0 -2) ":" (substring time -2)))
5956 new)
5957 (put-text-property
5958 1 (length (car new)) 'face 'org-time-grid (car new))))
5959 (if (member 'time-up org-agenda-sorting-strategy)
5960 (append new list)
5961 (append list new)))))
5962
5963 (defun org-compile-prefix-format (format)
5964 "Compile the prefix format into a Lisp form that can be evaluated.
5965 The resulting form is returned and stored in the variable
5966 `org-prefix-format-compiled'."
5967 (setq org-prefix-has-time nil org-prefix-has-tag nil)
5968 (let ((start 0) varform vars var (s format)e c f opt)
5969 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5970 s start)
5971 (setq var (cdr (assoc (match-string 4 s)
5972 '(("c" . category) ("t" . time) ("s" . extra)
5973 ("T" . tag))))
5974 c (or (match-string 3 s) "")
5975 opt (match-beginning 1)
5976 start (1+ (match-beginning 0)))
5977 (if (equal var 'time) (setq org-prefix-has-time t))
5978 (if (equal var 'tag) (setq org-prefix-has-tag t))
5979 (setq f (concat "%" (match-string 2 s) "s"))
5980 (if opt
5981 (setq varform
5982 `(if (equal "" ,var)
5983 ""
5984 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5985 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5986 (setq s (replace-match "%s" t nil s))
5987 (push varform vars))
5988 (setq vars (nreverse vars))
5989 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5990
5991 (defun org-get-time-of-day (s &optional string)
5992 "Check string S for a time of day.
5993 If found, return it as a military time number between 0 and 2400.
5994 If not found, return nil.
5995 The optional STRING argument forces conversion into a 5 character wide string
5996 HH:MM."
5997 (save-match-data
5998 (when
5999 (or
6000 (string-match
6001 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6002 (string-match
6003 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6004 (let* ((t0 (+ (* 100
6005 (+ (string-to-number (match-string 1 s))
6006 (if (and (match-beginning 4)
6007 (equal (downcase (match-string 4 s)) "pm"))
6008 12 0)))
6009 (if (match-beginning 3)
6010 (string-to-number (match-string 3 s))
6011 0)))
6012 (t1 (concat " "
6013 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6014 (int-to-string t0))))
6015 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6016
6017 (defun org-finalize-agenda-entries (list)
6018 "Sort and concatenate the agenda items."
6019 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6020
6021 (defsubst org-cmp-priority (a b)
6022 "Compare the priorities of string A and B."
6023 (let ((pa (or (get-text-property 1 'priority a) 0))
6024 (pb (or (get-text-property 1 'priority b) 0)))
6025 (cond ((> pa pb) +1)
6026 ((< pa pb) -1)
6027 (t nil))))
6028
6029 (defsubst org-cmp-category (a b)
6030 "Compare the string values of categories of strings A and B."
6031 (let ((ca (or (get-text-property 1 'category a) ""))
6032 (cb (or (get-text-property 1 'category b) "")))
6033 (cond ((string-lessp ca cb) -1)
6034 ((string-lessp cb ca) +1)
6035 (t nil))))
6036
6037 (defsubst org-cmp-time (a b)
6038 "Compare the time-of-day values of strings A and B."
6039 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6040 (ta (or (get-text-property 1 'time-of-day a) def))
6041 (tb (or (get-text-property 1 'time-of-day b) def)))
6042 (cond ((< ta tb) -1)
6043 ((< tb ta) +1)
6044 (t nil))))
6045
6046 (defun org-entries-lessp (a b)
6047 "Predicate for sorting agenda entries."
6048 ;; The following variables will be used when the form is evaluated.
6049 (let* ((time-up (org-cmp-time a b))
6050 (time-down (if time-up (- time-up) nil))
6051 (priority-up (org-cmp-priority a b))
6052 (priority-down (if priority-up (- priority-up) nil))
6053 (category-up (org-cmp-category a b))
6054 (category-down (if category-up (- category-up) nil))
6055 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
6056 (cdr (assoc
6057 (eval (cons 'or org-agenda-sorting-strategy))
6058 '((-1 . t) (1 . nil) (nil . nil))))))
6059
6060 (defun org-agenda-show-priority ()
6061 "Show the priority of the current item.
6062 This priority is composed of the main priority given with the [#A] cookies,
6063 and by additional input from the age of a schedules or deadline entry."
6064 (interactive)
6065 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6066 (message "Priority is %d" (if pri pri -1000))))
6067
6068 (defun org-agenda-show-tags ()
6069 "Show the tags applicable to the current item."
6070 (interactive)
6071 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6072 (if tags
6073 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6074 (message "No tags associated with this line"))))
6075
6076 (defun org-agenda-goto (&optional highlight)
6077 "Go to the Org-mode file which contains the item at point."
6078 (interactive)
6079 (let* ((marker (or (get-text-property (point) 'org-marker)
6080 (org-agenda-error)))
6081 (buffer (marker-buffer marker))
6082 (pos (marker-position marker)))
6083 (switch-to-buffer-other-window buffer)
6084 (widen)
6085 (goto-char pos)
6086 (when (eq major-mode 'org-mode)
6087 (org-show-hidden-entry)
6088 (save-excursion
6089 (and (outline-next-heading)
6090 (org-flag-heading nil)))) ; show the next heading
6091 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6092
6093 (defun org-agenda-switch-to ()
6094 "Go to the Org-mode file which contains the item at point."
6095 (interactive)
6096 (let* ((marker (or (get-text-property (point) 'org-marker)
6097 (org-agenda-error)))
6098 (buffer (marker-buffer marker))
6099 (pos (marker-position marker)))
6100 (switch-to-buffer buffer)
6101 (delete-other-windows)
6102 (widen)
6103 (goto-char pos)
6104 (when (eq major-mode 'org-mode)
6105 (org-show-hidden-entry)
6106 (save-excursion
6107 (and (outline-next-heading)
6108 (org-flag-heading nil)))))) ; show the next heading
6109
6110 (defun org-agenda-goto-mouse (ev)
6111 "Go to the Org-mode file which contains the item at the mouse click."
6112 (interactive "e")
6113 (mouse-set-point ev)
6114 (org-agenda-goto))
6115
6116 (defun org-agenda-show ()
6117 "Display the Org-mode file which contains the item at point."
6118 (interactive)
6119 (let ((win (selected-window)))
6120 (org-agenda-goto t)
6121 (select-window win)))
6122
6123 (defun org-agenda-recenter (arg)
6124 "Display the Org-mode file which contains the item at point and recenter."
6125 (interactive "P")
6126 (let ((win (selected-window)))
6127 (org-agenda-goto t)
6128 (recenter arg)
6129 (select-window win)))
6130
6131 (defun org-agenda-show-mouse (ev)
6132 "Display the Org-mode file which contains the item at the mouse click."
6133 (interactive "e")
6134 (mouse-set-point ev)
6135 (org-agenda-show))
6136
6137 (defun org-agenda-check-no-diary ()
6138 "Check if the entry is a diary link and abort if yes."
6139 (if (get-text-property (point) 'org-agenda-diary-link)
6140 (org-agenda-error)))
6141
6142 (defun org-agenda-error ()
6143 (error "Command not allowed in this line"))
6144
6145 (defvar org-last-heading-marker (make-marker)
6146 "Marker pointing to the headline that last changed its TODO state
6147 by a remote command from the agenda.")
6148
6149 (defun org-agenda-todo (&optional arg)
6150 "Cycle TODO state of line at point, also in Org-mode file.
6151 This changes the line at point, all other lines in the agenda referring to
6152 the same tree node, and the headline of the tree node in the Org-mode file."
6153 (interactive "P")
6154 (org-agenda-check-no-diary)
6155 (let* ((col (current-column))
6156 (marker (or (get-text-property (point) 'org-marker)
6157 (org-agenda-error)))
6158 (buffer (marker-buffer marker))
6159 (pos (marker-position marker))
6160 (hdmarker (get-text-property (point) 'org-hd-marker))
6161 (buffer-read-only nil)
6162 newhead)
6163 (with-current-buffer buffer
6164 (widen)
6165 (goto-char pos)
6166 (org-show-hidden-entry)
6167 (save-excursion
6168 (and (outline-next-heading)
6169 (org-flag-heading nil))) ; show the next heading
6170 (org-todo arg)
6171 (forward-char 1)
6172 (setq newhead (org-get-heading))
6173 (save-excursion
6174 (org-back-to-heading)
6175 (move-marker org-last-heading-marker (point))))
6176 (beginning-of-line 1)
6177 (save-excursion
6178 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6179 (move-to-column col)))
6180
6181 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6182 "Change all lines in the agenda buffer which match HDMARKER.
6183 The new content of the line will be NEWHEAD (as modified by
6184 `org-format-agenda-item'). HDMARKER is checked with
6185 `equal' against all `org-hd-marker' text properties in the file.
6186 If FIXFACE is non-nil, the face of each item is modified acording to
6187 the new TODO state."
6188 (let* (props m pl undone-face done-face finish new dotime cat tags)
6189 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6190 (save-excursion
6191 (goto-char (point-max))
6192 (beginning-of-line 1)
6193 (while (not finish)
6194 (setq finish (bobp))
6195 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6196 (equal m hdmarker))
6197 (setq props (text-properties-at (point))
6198 dotime (get-text-property (point) 'dotime)
6199 cat (get-text-property (point) 'category)
6200 tags (get-text-property (point) 'tags)
6201 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6202 pl (get-text-property (point) 'prefix-length)
6203 undone-face (get-text-property (point) 'undone-face)
6204 done-face (get-text-property (point) 'done-face))
6205 (move-to-column pl)
6206 (if (looking-at ".*")
6207 (progn
6208 (replace-match new t t)
6209 (beginning-of-line 1)
6210 (add-text-properties (point-at-bol) (point-at-eol) props)
6211 (if fixface
6212 (add-text-properties
6213 (point-at-bol) (point-at-eol)
6214 (list 'face
6215 (if org-last-todo-state-is-todo
6216 undone-face done-face))))
6217 (beginning-of-line 1))
6218 (error "Line update did not work")))
6219 (beginning-of-line 0)))))
6220
6221 (defun org-agenda-priority-up ()
6222 "Increase the priority of line at point, also in Org-mode file."
6223 (interactive)
6224 (org-agenda-priority 'up))
6225
6226 (defun org-agenda-priority-down ()
6227 "Decrease the priority of line at point, also in Org-mode file."
6228 (interactive)
6229 (org-agenda-priority 'down))
6230
6231 (defun org-agenda-priority (&optional force-direction)
6232 "Set the priority of line at point, also in Org-mode file.
6233 This changes the line at point, all other lines in the agenda referring to
6234 the same tree node, and the headline of the tree node in the Org-mode file."
6235 (interactive)
6236 (org-agenda-check-no-diary)
6237 (let* ((marker (or (get-text-property (point) 'org-marker)
6238 (org-agenda-error)))
6239 (buffer (marker-buffer marker))
6240 (pos (marker-position marker))
6241 (hdmarker (get-text-property (point) 'org-hd-marker))
6242 (buffer-read-only nil)
6243 newhead)
6244 (with-current-buffer buffer
6245 (widen)
6246 (goto-char pos)
6247 (org-show-hidden-entry)
6248 (save-excursion
6249 (and (outline-next-heading)
6250 (org-flag-heading nil))) ; show the next heading
6251 (funcall 'org-priority force-direction)
6252 (end-of-line 1)
6253 (setq newhead (org-get-heading)))
6254 (org-agenda-change-all-lines newhead hdmarker)
6255 (beginning-of-line 1)))
6256
6257 (defun org-get-tags-at (&optional pos)
6258 "Get a list of all headline targs applicable at POS.
6259 POS defaults to point. If tags are inherited, the list contains
6260 the targets in the same sequence as the headlines appear, i.e.
6261 the tags of the current headline come last."
6262 (interactive)
6263 (let (tags)
6264 (save-excursion
6265 (goto-char (or pos (point)))
6266 (save-match-data
6267 (org-back-to-heading t)
6268 (condition-case nil
6269 (while t
6270 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6271 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6272 (or org-use-tag-inheritance (error ""))
6273 (org-up-heading-all 1))
6274 (error nil))))
6275 (message "%s" tags)
6276 tags))
6277
6278 (defun org-agenda-set-tags ()
6279 "Set tags for the current headline."
6280 (interactive)
6281 (org-agenda-check-no-diary)
6282 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6283 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6284 (org-agenda-error)))
6285 (buffer (marker-buffer hdmarker))
6286 (pos (marker-position hdmarker))
6287 (buffer-read-only nil)
6288 newhead)
6289 (with-current-buffer buffer
6290 (widen)
6291 (goto-char pos)
6292 (org-show-hidden-entry)
6293 (save-excursion
6294 (and (outline-next-heading)
6295 (org-flag-heading nil))) ; show the next heading
6296 (call-interactively 'org-set-tags)
6297 (end-of-line 1)
6298 (setq newhead (org-get-heading)))
6299 (org-agenda-change-all-lines newhead hdmarker)
6300 (beginning-of-line 1)))
6301
6302 (defun org-agenda-date-later (arg &optional what)
6303 "Change the date of this item to one day later."
6304 (interactive "p")
6305 (org-agenda-check-type t 'agenda 'timeline)
6306 (org-agenda-check-no-diary)
6307 (let* ((marker (or (get-text-property (point) 'org-marker)
6308 (org-agenda-error)))
6309 (buffer (marker-buffer marker))
6310 (pos (marker-position marker)))
6311 (with-current-buffer buffer
6312 (widen)
6313 (goto-char pos)
6314 (if (not (org-at-timestamp-p))
6315 (error "Cannot find time stamp"))
6316 (org-timestamp-change arg (or what 'day))
6317 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6318
6319 (defun org-agenda-date-earlier (arg &optional what)
6320 "Change the date of this item to one day earlier."
6321 (interactive "p")
6322 (org-agenda-date-later (- arg) what))
6323
6324 (defun org-agenda-date-prompt (arg)
6325 "Change the date of this item. Date is prompted for, with default today.
6326 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6327 be used to request time specification in the time stamp."
6328 (interactive "P")
6329 (org-agenda-check-type t 'agenda 'timeline)
6330 (org-agenda-check-no-diary)
6331 (let* ((marker (or (get-text-property (point) 'org-marker)
6332 (org-agenda-error)))
6333 (buffer (marker-buffer marker))
6334 (pos (marker-position marker)))
6335 (with-current-buffer buffer
6336 (widen)
6337 (goto-char pos)
6338 (if (not (org-at-timestamp-p))
6339 (error "Cannot find time stamp"))
6340 (org-time-stamp arg)
6341 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6342
6343 (defun org-get-heading ()
6344 "Return the heading of the current entry, without the stars."
6345 (save-excursion
6346 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6347 ;;FIXME???????? (and (bolp) (end-of-line 1))
6348 (if (and (re-search-backward "[\r\n]\\*" nil t)
6349 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6350 (match-string 1)
6351 "")))
6352
6353 (defun org-agenda-diary-entry ()
6354 "Make a diary entry, like the `i' command from the calendar.
6355 All the standard commands work: block, weekly etc."
6356 (interactive)
6357 (org-agenda-check-type t 'agenda 'timeline)
6358 (require 'diary-lib)
6359 (let* ((char (progn
6360 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6361 (read-char-exclusive)))
6362 (cmd (cdr (assoc char
6363 '((?d . insert-diary-entry)
6364 (?w . insert-weekly-diary-entry)
6365 (?m . insert-monthly-diary-entry)
6366 (?y . insert-yearly-diary-entry)
6367 (?a . insert-anniversary-diary-entry)
6368 (?b . insert-block-diary-entry)
6369 (?c . insert-cyclic-diary-entry)))))
6370 (oldf (symbol-function 'calendar-cursor-to-date))
6371 (point (point))
6372 (mark (or (mark t) (point))))
6373 (unless cmd
6374 (error "No command associated with <%c>" char))
6375 (unless (and (get-text-property point 'day)
6376 (or (not (equal ?b char))
6377 (get-text-property mark 'day)))
6378 (error "Don't know which date to use for diary entry"))
6379 ;; We implement this by hacking the `calendar-cursor-to-date' function
6380 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6381 (let ((calendar-mark-ring
6382 (list (calendar-gregorian-from-absolute
6383 (or (get-text-property mark 'day)
6384 (get-text-property point 'day))))))
6385 (unwind-protect
6386 (progn
6387 (fset 'calendar-cursor-to-date
6388 (lambda (&optional error)
6389 (calendar-gregorian-from-absolute
6390 (get-text-property point 'day))))
6391 (call-interactively cmd))
6392 (fset 'calendar-cursor-to-date oldf)))))
6393
6394
6395 (defun org-agenda-execute-calendar-command (cmd)
6396 "Execute a calendar command from the agenda, with the date associated to
6397 the cursor position."
6398 (org-agenda-check-type t 'agenda 'timeline)
6399 (require 'diary-lib)
6400 (unless (get-text-property (point) 'day)
6401 (error "Don't know which date to use for calendar command"))
6402 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6403 (point (point))
6404 (date (calendar-gregorian-from-absolute
6405 (get-text-property point 'day)))
6406 (displayed-day (extract-calendar-day date))
6407 (displayed-month (extract-calendar-month date))
6408 (displayed-year (extract-calendar-year date)))
6409 (unwind-protect
6410 (progn
6411 (fset 'calendar-cursor-to-date
6412 (lambda (&optional error)
6413 (calendar-gregorian-from-absolute
6414 (get-text-property point 'day))))
6415 (call-interactively cmd))
6416 (fset 'calendar-cursor-to-date oldf))))
6417
6418 (defun org-agenda-phases-of-moon ()
6419 "Display the phases of the moon for the 3 months around the cursor date."
6420 (interactive)
6421 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6422
6423 (defun org-agenda-holidays ()
6424 "Display the holidays for the 3 months around the cursor date."
6425 (interactive)
6426 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6427
6428 (defun org-agenda-sunrise-sunset (arg)
6429 "Display sunrise and sunset for the cursor date.
6430 Latitude and longitude can be specified with the variables
6431 `calendar-latitude' and `calendar-longitude'. When called with prefix
6432 argument, latitude and longitude will be prompted for."
6433 (interactive "P")
6434 (let ((calendar-longitude (if arg nil calendar-longitude))
6435 (calendar-latitude (if arg nil calendar-latitude))
6436 (calendar-location-name
6437 (if arg "the given coordinates" calendar-location-name)))
6438 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6439
6440 (defun org-agenda-goto-calendar ()
6441 "Open the Emacs calendar with the date at the cursor."
6442 (interactive)
6443 (org-agenda-check-type t 'agenda 'timeline)
6444 (let* ((day (or (get-text-property (point) 'day)
6445 (error "Don't know which date to open in calendar")))
6446 (date (calendar-gregorian-from-absolute day))
6447 (calendar-move-hook nil)
6448 (view-diary-entries-initially nil))
6449 (calendar)
6450 (calendar-goto-date date)))
6451
6452 (defun org-calendar-goto-agenda ()
6453 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6454 This is a command that has to be installed in `calendar-mode-map'."
6455 (interactive)
6456 (org-agenda-list nil (calendar-absolute-from-gregorian
6457 (calendar-cursor-to-date))
6458 nil t))
6459
6460 (defun org-agenda-convert-date ()
6461 (interactive)
6462 (org-agenda-check-type t 'agenda 'timeline)
6463 (let ((day (get-text-property (point) 'day))
6464 date s)
6465 (unless day
6466 (error "Don't know which date to convert"))
6467 (setq date (calendar-gregorian-from-absolute day))
6468 (setq s (concat
6469 "Gregorian: " (calendar-date-string date) "\n"
6470 "ISO: " (calendar-iso-date-string date) "\n"
6471 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6472 "Julian: " (calendar-julian-date-string date) "\n"
6473 "Astron. JD: " (calendar-astro-date-string date)
6474 " (Julian date number at noon UTC)\n"
6475 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6476 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6477 "French: " (calendar-french-date-string date) "\n"
6478 "Mayan: " (calendar-mayan-date-string date) "\n"
6479 "Coptic: " (calendar-coptic-date-string date) "\n"
6480 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6481 "Persian: " (calendar-persian-date-string date) "\n"
6482 "Chinese: " (calendar-chinese-date-string date) "\n"))
6483 (with-output-to-temp-buffer "*Dates*"
6484 (princ s))
6485 (if (fboundp 'fit-window-to-buffer)
6486 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6487
6488 ;;; Tags
6489
6490 (defun org-scan-tags (action matcher &optional todo-only)
6491 "Scan headline tags with inheritance and produce output ACTION.
6492 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6493 evaluated, testing if a given set of tags qualifies a headline for
6494 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6495 are included in the output."
6496 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6497 (mapconcat 'regexp-quote
6498 (nreverse (cdr (reverse org-todo-keywords)))
6499 "\\|")
6500 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6501 (props (list 'face nil
6502 'done-face 'org-done
6503 'undone-face nil
6504 'mouse-face 'highlight
6505 'keymap org-agenda-keymap
6506 'help-echo
6507 (format "mouse-2 or RET jump to org file %s"
6508 (abbreviate-file-name buffer-file-name))))
6509 lspos
6510 tags tags-list tags-alist (llast 0) rtn level category i txt
6511 todo marker)
6512
6513 (save-excursion
6514 (goto-char (point-min))
6515 (when (eq action 'sparse-tree) (hide-sublevels 1))
6516 (while (re-search-forward re nil t)
6517 (setq todo (if (match-end 1) (match-string 2))
6518 tags (if (match-end 4) (match-string 4)))
6519 (goto-char (setq lspos (1+ (match-beginning 0))))
6520 (setq level (funcall outline-level)
6521 category (org-get-category))
6522 (setq i llast llast level)
6523 ;; remove tag lists from same and sublevels
6524 (while (>= i level)
6525 (when (setq entry (assoc i tags-alist))
6526 (setq tags-alist (delete entry tags-alist)))
6527 (setq i (1- i)))
6528 ;; add the nex tags
6529 (when tags
6530 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6531 tags-alist
6532 (cons (cons level tags) tags-alist)))
6533 ;; compile tags for current headline
6534 (setq tags-list
6535 (if org-use-tag-inheritance
6536 (apply 'append (mapcar 'cdr tags-alist))
6537 tags))
6538 (when (and (or (not todo-only) todo)
6539 (eval matcher))
6540 ;; list this headline
6541 (if (eq action 'sparse-tree)
6542 (progn
6543 (org-show-hierarchy-above))
6544 (setq txt (org-format-agenda-item
6545 ""
6546 (concat
6547 (if org-tags-match-list-sublevels
6548 (make-string (1- level) ?.) "")
6549 (org-get-heading))
6550 category tags-list))
6551 (goto-char lspos)
6552 (setq marker (org-agenda-new-marker))
6553 (add-text-properties
6554 0 (length txt)
6555 (append (list 'org-marker marker 'org-hd-marker marker
6556 'category category)
6557 props)
6558 txt)
6559 (push txt rtn))
6560 ;; if we are to skip sublevels, jump to end of subtree
6561 (point)
6562 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6563 (nreverse rtn)))
6564
6565 (defun org-tags-sparse-tree (&optional arg match)
6566 "Create a sparse tree according to tags search string MATCH.
6567 MATCH can contain positive and negative selection of tags, like
6568 \"+WORK+URGENT-WITHBOSS\"."
6569 (interactive "P")
6570 (let ((org-show-following-heading nil)
6571 (org-show-hierarchy-above nil))
6572 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6573
6574 (defun org-make-tags-matcher (match)
6575 "Create the TAGS matcher form for the tags-selecting string MATCH."
6576 (unless match
6577 ;; Get a new match request, with completion
6578 (setq org-last-tags-completion-table
6579 (or (org-get-buffer-tags)
6580 org-last-tags-completion-table))
6581 (setq match (completing-read
6582 "Tags: " 'org-tags-completion-function nil nil nil
6583 'org-tags-history)))
6584 ;; parse the string and create a lisp form
6585 (let ((match0 match) minus tag mm matcher orterms term orlist)
6586 (setq orterms (org-split-string match "|"))
6587 (while (setq term (pop orterms))
6588 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
6589 (setq minus (and (match-end 1)
6590 (equal (match-string 1 term) "-"))
6591 tag (match-string 2 term)
6592 term (substring term (match-end 0))
6593 mm (list 'member (downcase tag) 'tags-list)
6594 mm (if minus (list 'not mm) mm))
6595 (push mm matcher))
6596 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6597 orlist)
6598 (setq matcher nil))
6599 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6600 ;; Return the string and lisp forms of the matcher
6601 (cons match0 matcher)))
6602
6603 ;;;###autoload
6604 (defun org-tags-view (&optional todo-only match keep-modes)
6605 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
6606 The prefix arg TODO-ONLY limits the search to TODO entries."
6607 (interactive "P")
6608 (org-agenda-maybe-reset-markers 'force)
6609 (org-compile-prefix-format org-agenda-prefix-format)
6610 (let* ((org-agenda-keep-modes keep-modes)
6611 (org-tags-match-list-sublevels
6612 (if todo-only t org-tags-match-list-sublevels))
6613 (win (selected-window))
6614 (completion-ignore-case t)
6615 rtn rtnall files file pos matcher
6616 buffer)
6617 (setq matcher (org-make-tags-matcher match)
6618 match (car matcher) matcher (cdr matcher))
6619 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6620 (progn
6621 (delete-other-windows)
6622 (switch-to-buffer-other-window
6623 (get-buffer-create org-agenda-buffer-name))))
6624 (setq buffer-read-only nil)
6625 (erase-buffer)
6626 (org-agenda-mode) (setq buffer-read-only nil)
6627 (set (make-local-variable 'org-agenda-type) 'tags)
6628 (set (make-local-variable 'org-agenda-redo-command)
6629 (list 'org-tags-view (list 'quote todo-only)
6630 (list 'if 'current-prefix-arg nil match) t))
6631 (setq files (org-agenda-files)
6632 rtnall nil)
6633 (while (setq file (pop files))
6634 (catch 'nextfile
6635 (org-check-agenda-file file)
6636 (setq buffer (if (file-exists-p file)
6637 (org-get-agenda-file-buffer file)
6638 (error "No such file %s" file)))
6639 (if (not buffer)
6640 ;; If file does not exist, merror message to agenda
6641 (setq rtn (list
6642 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6643 rtnall (append rtnall rtn))
6644 (with-current-buffer buffer
6645 (unless (eq major-mode 'org-mode)
6646 (error "Agenda file %s is not in `org-mode'" file))
6647 (save-excursion
6648 (save-restriction
6649 (if org-respect-restriction
6650 (if (org-region-active-p)
6651 ;; Respect a region to restrict search
6652 (narrow-to-region (region-beginning) (region-end)))
6653 ;; If we work for the calendar or many files,
6654 ;; get rid of any restriction
6655 (widen))
6656 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6657 (setq rtnall (append rtnall rtn))))))))
6658 (insert "Headlines with TAGS match: ")
6659 (add-text-properties (point-min) (1- (point))
6660 (list 'face 'org-link))
6661 (setq pos (point))
6662 (insert match "\n")
6663 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6664 (setq pos (point))
6665 (insert "Press `C-u r' to search again with new search string\n")
6666 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6667 (when rtnall
6668 (insert (mapconcat 'identity rtnall "\n")))
6669 (goto-char (point-min))
6670 (setq buffer-read-only t)
6671 (org-fit-agenda-window)
6672 (if (not org-select-agenda-window) (select-window win))))
6673
6674 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6675 (defun org-set-tags (&optional arg just-align)
6676 "Set the tags for the current headline.
6677 With prefix ARG, realign all tags in headings in the current buffer."
6678 (interactive)
6679 (let* (;(inherit (org-get-inherited-tags))
6680 (re (concat "^" outline-regexp))
6681 (col (current-column))
6682 (current (org-get-tags))
6683 tags hd empty invis)
6684 (if arg
6685 (save-excursion
6686 (goto-char (point-min))
6687 (while (re-search-forward re nil t)
6688 (org-set-tags nil t))
6689 (message "All tags realigned to column %d" org-tags-column))
6690 (if just-align
6691 (setq tags current)
6692 (setq org-last-tags-completion-table
6693 (or (org-get-buffer-tags)
6694 org-last-tags-completion-table))
6695 (setq tags
6696 (let ((org-add-colon-after-tag-completion t))
6697 (completing-read "Tags: " 'org-tags-completion-function
6698 nil nil current 'org-tags-history)))
6699 (while (string-match "[-+&]+" tags)
6700 (setq tags (replace-match ":" t t tags))))
6701 ;; FIXME: still optimize this byt not checking when JUST-ALIGN?
6702 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6703 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6704 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
6705 (if (equal current "")
6706 (progn
6707 (end-of-line 1)
6708 (or empty (insert-before-markers " ")))
6709 (beginning-of-line 1)
6710 (setq invis (org-invisible-p))
6711 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6712 (setq hd (match-string 1))
6713 (delete-region (match-beginning 0) (match-end 0))
6714 (insert-before-markers (org-trim hd) (if empty "" " ")))
6715 ;; FIXME: What happens when adding a new tag??? Seems OK!!!
6716 (unless (equal tags "")
6717 (move-to-column (max (current-column)
6718 (if (> org-tags-column 0)
6719 org-tags-column
6720 (- (- org-tags-column) (length tags))))
6721 t)
6722 (insert-before-markers tags)
6723 (if (and (not invis) (org-invisible-p))
6724 (outline-flag-region (point-at-bol) (point) nil)))
6725 (move-to-column col))))
6726
6727 (defun org-tags-completion-function (string predicate &optional flag)
6728 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6729 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6730 (setq s1 (match-string 1 string)
6731 s2 (match-string 2 string))
6732 (setq s1 "" s2 string))
6733 (cond
6734 ((eq flag nil)
6735 ;; try completion
6736 (setq rtn (try-completion s2 ctable))
6737 (if (stringp rtn)
6738 (concat s1 s2 (substring rtn (length s2))
6739 (if (and org-add-colon-after-tag-completion
6740 (assoc rtn ctable))
6741 ":" "")))
6742 )
6743 ((eq flag t)
6744 ;; all-completions
6745 (all-completions s2 ctable)
6746 )
6747 ((eq flag 'lambda)
6748 ;; exact match?
6749 (assoc s2 ctable)))
6750 ))
6751
6752 (defun org-get-tags ()
6753 "Get the TAGS string in the current headline."
6754 (unless (org-on-heading-p)
6755 (error "Not on a heading"))
6756 (save-excursion
6757 (beginning-of-line 1)
6758 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
6759 (match-string 1)
6760 "")))
6761
6762 (defun org-get-buffer-tags ()
6763 "Get a table of all tags used in the buffer, for completion."
6764 (let (tags)
6765 (save-excursion
6766 (goto-char (point-min))
6767 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
6768 (mapc (lambda (x) (add-to-list 'tags x))
6769 (org-split-string (match-string 1) ":"))))
6770 (mapcar 'list tags)))
6771
6772 ;;; Link Stuff
6773
6774 (defun org-find-file-at-mouse (ev)
6775 "Open file link or URL at mouse."
6776 (interactive "e")
6777 (mouse-set-point ev)
6778 (org-open-at-point 'in-emacs))
6779
6780 (defun org-open-at-mouse (ev)
6781 "Open file link or URL at mouse."
6782 (interactive "e")
6783 (mouse-set-point ev)
6784 (org-open-at-point))
6785
6786 (defun org-open-at-point (&optional in-emacs)
6787 "Open link at or after point.
6788 If there is no link at point, this function will search forward up to
6789 the end of the current subtree.
6790 Normally, files will be opened by an appropriate application. If the
6791 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6792 (interactive "P")
6793 (org-remove-occur-highlights nil nil t)
6794 (if (org-at-timestamp-p)
6795 (org-agenda-list nil (time-to-days (org-time-string-to-time
6796 (substring (match-string 1) 0 10)))
6797 1)
6798 (let (type path link line search (pos (point)))
6799 (catch 'match
6800 (save-excursion
6801 (skip-chars-forward "^]\n\r")
6802 (when (and (re-search-backward "\\[\\[" nil t)
6803 (looking-at org-bracket-link-regexp)
6804 (<= (match-beginning 0) pos)
6805 (>= (match-end 0) pos))
6806 (setq link (match-string 1))
6807 (while (string-match " *\n *" link)
6808 (setq link (replace-match " " t t link)))
6809 (if (string-match org-link-regexp link)
6810 (setq type (match-string 1)
6811 path (match-string 2))
6812 (setq type "thisfile"
6813 path link))
6814 (throw 'match t)))
6815
6816 (when (get-text-property (point) 'org-linked-text)
6817 (setq type "thisfile"
6818 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6819 (1+ (point)) (point))
6820 path (buffer-substring
6821 (previous-single-property-change pos 'org-linked-text)
6822 (next-single-property-change pos 'org-linked-text)))
6823 (throw 'match t))
6824
6825 (save-excursion
6826 (skip-chars-backward
6827 (concat (if org-allow-space-in-links "^" "^ ")
6828 org-non-link-chars))
6829 (when (or (looking-at org-link-regexp)
6830 (and (re-search-forward org-link-regexp (point-at-eol) t)
6831 (<= (match-beginning 0) pos)
6832 (>= (match-end 0) pos)))
6833 (setq type (match-string 1)
6834 path (match-string 2))
6835 (throw 'match t)))
6836 (save-excursion
6837 (skip-chars-backward "^ \t\n\r")
6838 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
6839 (setq type "tags"
6840 path (match-string 1))
6841 (while (string-match ":" path)
6842 (setq path (replace-match "+" t t path)))
6843 (throw 'match t)))
6844 (save-excursion
6845 (skip-chars-backward "a-zA-Z_")
6846 (when (and org-activate-camels
6847 (looking-at org-camel-regexp))
6848 (setq type "camel" path (match-string 0))
6849 (if (equal (char-before) ?*)
6850 (setq path (concat "*" path))))
6851 (throw 'match t))
6852 (save-excursion
6853 (when (re-search-forward
6854 org-link-regexp
6855 (save-excursion
6856 (condition-case nil
6857 (progn (outline-end-of-subtree) (max pos (point)))
6858 (error (end-of-line 1) (point))))
6859 t)
6860 (setq type (match-string 1)
6861 path (match-string 2)))))
6862 (unless path
6863 (error "No link found"))
6864 ;; Remove any trailing spaces in path
6865 (if (string-match " +\\'" path)
6866 (setq path (replace-match "" t t path)))
6867
6868 (cond
6869
6870 ((string= type "tags")
6871 (org-tags-view in-emacs path))
6872 ((or (string= type "camel")
6873 (string= type "thisfile"))
6874 (org-mark-ring-push)
6875 (org-link-search
6876 path
6877 (cond ((equal in-emacs '(4)) 'occur)
6878 ((equal in-emacs '(16)) 'org-occur)
6879 (t nil))))
6880
6881 ((string= type "file")
6882 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6883 (setq line (string-to-number (match-string 1 path))
6884 path (substring path 0 (match-beginning 0)))
6885 (if (string-match "::\\(.+\\)\\'" path)
6886 (setq search (match-string 1 path)
6887 path (substring path 0 (match-beginning 0)))))
6888 (org-open-file path in-emacs line search))
6889
6890 ((string= type "news")
6891 (org-follow-gnus-link path))
6892
6893 ((string= type "bbdb")
6894 (org-follow-bbdb-link path))
6895
6896 ((string= type "gnus")
6897 (let (group article)
6898 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6899 (error "Error in Gnus link"))
6900 (setq group (match-string 1 path)
6901 article (match-string 3 path))
6902 (org-follow-gnus-link group article)))
6903
6904 ((string= type "vm")
6905 (let (folder article)
6906 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6907 (error "Error in VM link"))
6908 (setq folder (match-string 1 path)
6909 article (match-string 3 path))
6910 ;; in-emacs is the prefix arg, will be interpreted as read-only
6911 (org-follow-vm-link folder article in-emacs)))
6912
6913 ((string= type "wl")
6914 (let (folder article)
6915 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6916 (error "Error in Wanderlust link"))
6917 (setq folder (match-string 1 path)
6918 article (match-string 3 path))
6919 (org-follow-wl-link folder article)))
6920
6921 ((string= type "mhe")
6922 (let (folder article)
6923 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6924 (error "Error in MHE link"))
6925 (setq folder (match-string 1 path)
6926 article (match-string 3 path))
6927 (org-follow-mhe-link folder article)))
6928
6929 ((string= type "rmail")
6930 (let (folder article)
6931 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6932 (error "Error in RMAIL link"))
6933 (setq folder (match-string 1 path)
6934 article (match-string 3 path))
6935 (org-follow-rmail-link folder article)))
6936
6937 ((string= type "shell")
6938 (let ((cmd path))
6939 (while (string-match "@{" cmd)
6940 (setq cmd (replace-match "<" t t cmd)))
6941 (while (string-match "@}" cmd)
6942 (setq cmd (replace-match ">" t t cmd)))
6943 (if (or (not org-confirm-shell-links)
6944 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6945 (shell-command cmd)
6946 (error "Abort"))))
6947
6948 (t
6949 (browse-url-at-point))))))
6950
6951 (defun org-link-search (s &optional type)
6952 "Search for a link search option.
6953 When S is a CamelCaseWord, search for a target, or for a sentence containing
6954 the words. If S is surrounded by forward slashes, it is interpreted as a
6955 regular expression. In org-mode files, this will create an `org-occur'
6956 sparse tree. In ordinary files, `occur' will be used to list matches.
6957 If the current buffer is in `dired-mode', grep will be used to search
6958 in all files."
6959 (let ((case-fold-search t)
6960 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6961 (pos (point))
6962 (pre "") (post "")
6963 words re0 re1 re2 re3 re4 re5 reall camel)
6964 (cond ((save-excursion
6965 (goto-char (point-min))
6966 (and
6967 (re-search-forward
6968 (concat "<<" (regexp-quote s0) ">>") nil t)
6969 (setq pos (match-beginning 0))))
6970 ;; There is an exact target for this
6971 (goto-char pos))
6972 ((string-match "^/\\(.*\\)/$" s)
6973 ;; A regular expression
6974 (cond
6975 ((eq major-mode 'org-mode)
6976 (org-occur (match-string 1 s)))
6977 ;;((eq major-mode 'dired-mode)
6978 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6979 (t (org-do-occur (match-string 1 s)))))
6980 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
6981 t)
6982 ;; A camel or a normal search string
6983 (when (equal (string-to-char s) ?*)
6984 ;; Anchor on headlines, post may include tags.
6985 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6986 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
6987 s (substring s 1)))
6988 (remove-text-properties
6989 0 (length s)
6990 '(face nil mouse-face nil keymap nil fontified nil) s)
6991 ;; Make a series of regular expressions to find a match
6992 (setq words
6993 (if camel
6994 (org-camel-to-words s)
6995 (org-split-string s "[ \n\r\t]+"))
6996 re0 (concat "<<" (regexp-quote s0) ">>")
6997 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6998 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6999 re1 (concat pre re2 post)
7000 re3 (concat pre re4 post)
7001 re5 (concat pre ".*" re4)
7002 re2 (concat pre re2)
7003 re4 (concat pre re4)
7004 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7005 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7006 re5 "\\)"
7007 ))
7008 (cond
7009 ((eq type 'org-occur) (org-occur reall))
7010 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7011 (t (goto-char (point-min))
7012 (if (or (re-search-forward re0 nil t)
7013 (re-search-forward re1 nil t)
7014 (re-search-forward re2 nil t)
7015 (re-search-forward re3 nil t)
7016 (re-search-forward re4 nil t)
7017 (re-search-forward re5 nil t))
7018 (goto-char (match-beginning 0))
7019 (goto-char pos)
7020 (error "No match")))))
7021 (t
7022 ;; Normal string-search
7023 (goto-char (point-min))
7024 (if (search-forward s nil t)
7025 (goto-char (match-beginning 0))
7026 (error "No match"))))
7027 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7028
7029 (defun org-do-occur (regexp &optional cleanup)
7030 "Call the Emacs command `occur'.
7031 If CLEANUP is non-nil, remove the printout of the regular expression
7032 in the *Occur* buffer. This is useful if the regex is long and not useful
7033 to read."
7034 (occur regexp)
7035 (when cleanup
7036 (let ((cwin (selected-window)) win beg end)
7037 (when (setq win (get-buffer-window "*Occur*"))
7038 (select-window win))
7039 (goto-char (point-min))
7040 (when (re-search-forward "match[a-z]+" nil t)
7041 (setq beg (match-end 0))
7042 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7043 (setq end (1- (match-beginning 0)))))
7044 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7045 (goto-char (point-min))
7046 (select-window cwin))))
7047
7048 (defvar org-mark-ring nil
7049 "Mark ring for positions before jumps in Org-mode.")
7050 (defvar org-mark-ring-last-goto nil
7051 "Last position in the mark ring used to go back.")
7052 ;; Fill and close the ring
7053 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7054 (loop for i from 1 to org-mark-ring-length do
7055 (push (make-marker) org-mark-ring))
7056 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7057 org-mark-ring)
7058
7059 (defun org-mark-ring-push (&optional pos buffer)
7060 "Put the current position or POS into the mark ring and rotate it."
7061 (interactive)
7062 (setq pos (or pos (point)))
7063 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7064 (move-marker (car org-mark-ring)
7065 (or pos (point))
7066 (or buffer (current-buffer)))
7067 (message
7068 (substitute-command-keys
7069 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7070
7071 (defun org-mark-ring-goto (&optional n)
7072 "Jump to the previous position in the mark ring.
7073 With prefix arg N, jump back that many stored positions. When
7074 called several times in succession, walk through the entire ring.
7075 Org-mode commands jumping to a different position in the current file,
7076 or to another Org-mode file, automatically push the old position
7077 onto the ring."
7078 (interactive "p")
7079 (let (p m)
7080 (if (eq last-command this-command)
7081 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7082 (setq p org-mark-ring))
7083 (setq org-mark-ring-last-goto p)
7084 (setq m (car p))
7085 (switch-to-buffer (marker-buffer m))
7086 (goto-char m)
7087 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7088
7089 (defun org-camel-to-words (s)
7090 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7091 (let ((case-fold-search nil)
7092 words)
7093 (while (string-match "[a-z][A-Z]" s)
7094 (push (substring s 0 (1+ (match-beginning 0))) words)
7095 (setq s (substring s (1+ (match-beginning 0)))))
7096 (nreverse (cons s words))))
7097
7098 (defun org-remove-angle-brackets (s)
7099 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7100 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7101 s)
7102 (defun org-add-angle-brackets (s)
7103 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7104 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7105 s)
7106
7107 (defun org-follow-bbdb-link (name)
7108 "Follow a BBDB link to NAME."
7109 (require 'bbdb)
7110 (let ((inhibit-redisplay t)
7111 (bbdb-electric-p nil))
7112 (catch 'exit
7113 ;; Exact match on name
7114 (bbdb-name (concat "\\`" name "\\'") nil)
7115 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7116 ;; Exact match on name
7117 (bbdb-company (concat "\\`" name "\\'") nil)
7118 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7119 ;; Partial match on name
7120 (bbdb-name name nil)
7121 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7122 ;; Partial match on company
7123 (bbdb-company name nil)
7124 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7125 ;; General match including network address and notes
7126 (bbdb name nil)
7127 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7128 (delete-window (get-buffer-window "*BBDB*"))
7129 (error "No matching BBDB record")))))
7130
7131 (defun org-follow-gnus-link (&optional group article)
7132 "Follow a Gnus link to GROUP and ARTICLE."
7133 (require 'gnus)
7134 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7135 (if group (gnus-fetch-group group))
7136 (if article
7137 (or (gnus-summary-goto-article article nil 'force)
7138 (if (fboundp 'gnus-summary-insert-cached-articles)
7139 (progn
7140 (gnus-summary-insert-cached-articles)
7141 (gnus-summary-goto-article article nil 'force))
7142 (message "Message could not be found.")))))
7143
7144 (defun org-follow-vm-link (&optional folder article readonly)
7145 "Follow a VM link to FOLDER and ARTICLE."
7146 (require 'vm)
7147 (setq article (org-add-angle-brackets article))
7148 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7149 ;; ange-ftp or efs or tramp access
7150 (let ((user (or (match-string 1 folder) (user-login-name)))
7151 (host (match-string 2 folder))
7152 (file (match-string 3 folder)))
7153 (cond
7154 ((featurep 'tramp)
7155 ;; use tramp to access the file
7156 (if org-xemacs-p
7157 (setq folder (format "[%s@%s]%s" user host file))
7158 (setq folder (format "/%s@%s:%s" user host file))))
7159 (t
7160 ;; use ange-ftp or efs
7161 (require (if org-xemacs-p 'efs 'ange-ftp))
7162 (setq folder (format "/%s@%s:%s" user host file))))))
7163 (when folder
7164 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7165 (sit-for 0.1)
7166 (when article
7167 (vm-select-folder-buffer)
7168 (widen)
7169 (let ((case-fold-search t))
7170 (goto-char (point-min))
7171 (if (not (re-search-forward
7172 (concat "^" "message-id: *" (regexp-quote article))))
7173 (error "Could not find the specified message in this folder"))
7174 (vm-isearch-update)
7175 (vm-isearch-narrow)
7176 (vm-beginning-of-message)
7177 (vm-summarize)))))
7178
7179 (defun org-follow-wl-link (folder article)
7180 "Follow a Wanderlust link to FOLDER and ARTICLE."
7181 (setq article (org-add-angle-brackets article))
7182 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7183 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7184 (wl-summary-redisplay))
7185
7186 (defun org-follow-rmail-link (folder article)
7187 "Follow an RMAIL link to FOLDER and ARTICLE."
7188 (setq article (org-add-angle-brackets article))
7189 (let (message-number)
7190 (save-excursion
7191 (save-window-excursion
7192 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7193 (setq message-number
7194 (save-restriction
7195 (widen)
7196 (goto-char (point-max))
7197 (if (re-search-backward
7198 (concat "^Message-ID:\\s-+" (regexp-quote
7199 (or article "")))
7200 nil t)
7201 (rmail-what-message))))))
7202 (if message-number
7203 (progn
7204 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7205 (rmail-show-message message-number)
7206 message-number)
7207 (error "Message not found"))))
7208
7209 ;; mh-e integration based on planner-mode
7210 (defun org-mhe-get-message-real-folder ()
7211 "Return the name of the current message real folder, so if you use
7212 sequences, it will now work."
7213 (save-excursion
7214 (let* ((folder
7215 (if (equal major-mode 'mh-folder-mode)
7216 mh-current-folder
7217 ;; Refer to the show buffer
7218 mh-show-folder-buffer))
7219 (end-index
7220 (if (boundp 'mh-index-folder)
7221 (min (length mh-index-folder) (length folder))))
7222 )
7223 ;; a simple test on mh-index-data does not work, because
7224 ;; mh-index-data is always nil in a show buffer.
7225 (if (and (boundp 'mh-index-folder)
7226 (string= mh-index-folder (substring folder 0 end-index)))
7227 (if (equal major-mode 'mh-show-mode)
7228 (save-window-excursion
7229 (when (buffer-live-p (get-buffer folder))
7230 (progn
7231 (pop-to-buffer folder)
7232 (org-mhe-get-message-folder-from-index)
7233 )
7234 ))
7235 (org-mhe-get-message-folder-from-index)
7236 )
7237 folder
7238 )
7239 )))
7240
7241 (defun org-mhe-get-message-folder-from-index ()
7242 "Returns the name of the message folder in a index folder buffer."
7243 (save-excursion
7244 (mh-index-previous-folder)
7245 (re-search-forward "^\\(+.*\\)$" nil t)
7246 (message (match-string 1))))
7247
7248 (defun org-mhe-get-message-folder ()
7249 "Return the name of the current message folder. Be careful if you
7250 use sequences."
7251 (save-excursion
7252 (if (equal major-mode 'mh-folder-mode)
7253 mh-current-folder
7254 ;; Refer to the show buffer
7255 mh-show-folder-buffer)))
7256
7257 (defun org-mhe-get-message-num ()
7258 "Return the number of the current message. Be careful if you
7259 use sequences."
7260 (save-excursion
7261 (if (equal major-mode 'mh-folder-mode)
7262 (mh-get-msg-num nil)
7263 ;; Refer to the show buffer
7264 (mh-show-buffer-message-number))))
7265
7266 (defun org-mhe-get-header (header)
7267 "Return a header of the message in folder mode. This will create a
7268 show buffer for the corresponding message. If you have a more clever
7269 idea..."
7270 (let* ((folder (org-mhe-get-message-folder))
7271 (num (org-mhe-get-message-num))
7272 (buffer (get-buffer-create (concat "show-" folder)))
7273 (header-field))
7274 (with-current-buffer buffer
7275 (mh-display-msg num folder)
7276 (if (equal major-mode 'mh-folder-mode)
7277 (mh-header-display)
7278 (mh-show-header-display))
7279 (set-buffer buffer)
7280 (setq header-field (mh-get-header-field header))
7281 (if (equal major-mode 'mh-folder-mode)
7282 (mh-show)
7283 (mh-show-show))
7284 header-field)))
7285
7286 (defun org-follow-mhe-link (folder article)
7287 "Follow an MHE link to FOLDER and ARTICLE."
7288 (setq article (org-add-angle-brackets article))
7289 (require 'mh-e)
7290 (require 'mh-search)
7291 (mh-find-path)
7292 (mh-search-choose)
7293 (if (equal mh-searcher 'pick)
7294 (progn
7295 (mh-search folder (list "--message-id" article))
7296 (when (and org-mhe-search-all-folders
7297 (not (org-mhe-get-message-real-folder)))
7298 (kill-this-buffer)
7299 (mh-search "+" (list "--message-id" article))))
7300 (mh-search "+" article))
7301 (if (org-mhe-get-message-real-folder)
7302 (mh-show-msg 1)
7303 (kill-this-buffer)
7304 (error "Message not found")))
7305
7306 (defun org-open-file (path &optional in-emacs line search)
7307 "Open the file at PATH.
7308 First, this expands any special file name abbreviations. Then the
7309 configuration variable `org-file-apps' is checked if it contains an
7310 entry for this file type, and if yes, the corresponding command is launched.
7311 If no application is found, Emacs simply visits the file.
7312 With optional argument IN-EMACS, Emacs will visit the file.
7313 Optional LINE specifies a line to go to, optional SEARCH a string to
7314 search for. If LINE or SEARCH is given, the file will always be
7315 opened in Emacs.
7316 If the file does not exist, an error is thrown."
7317 (setq in-emacs (or in-emacs line search))
7318 (let* ((file (if (equal path "")
7319 buffer-file-name
7320 (convert-standard-filename (org-expand-file-name path))))
7321 (dirp (file-directory-p file))
7322 (dfile (downcase file))
7323 (old-buffer (current-buffer))
7324 (old-pos (point))
7325 (old-mode major-mode)
7326 ext cmd apps)
7327 (if (and (not (file-exists-p file))
7328 (not org-open-non-existing-files))
7329 (error "No such file: %s" file))
7330 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7331 (setq ext (match-string 1 dfile))
7332 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7333 (setq ext (match-string 1 dfile))))
7334 (setq apps (append org-file-apps (org-default-apps)))
7335 (if in-emacs
7336 (setq cmd 'emacs)
7337 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7338 (cdr (assoc ext apps))
7339 (cdr (assoc t apps)))))
7340 (when (eq cmd 'mailcap)
7341 (require 'mailcap)
7342 (mailcap-parse-mailcaps)
7343 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7344 (command (mailcap-mime-info mime-type)))
7345 (if (stringp command)
7346 (setq cmd command)
7347 (setq cmd 'emacs))))
7348 (cond
7349 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7350 (setq cmd (format cmd (concat "\"" file "\"")))
7351 (save-window-excursion
7352 (shell-command (concat cmd " &"))))
7353 ((or (stringp cmd)
7354 (eq cmd 'emacs))
7355 (unless (equal (file-truename file) (file-truename buffer-file-name))
7356 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7357 (if line (goto-line line)
7358 (if search (org-link-search search))))
7359 ((consp cmd)
7360 (eval cmd))
7361 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7362 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7363 (or (not (equal old-buffer (current-buffer)))
7364 (not (equal old-pos (point))))
7365 (org-mark-ring-push old-pos old-buffer))))
7366
7367 (defun org-default-apps ()
7368 "Return the default applications for this operating system."
7369 (cond
7370 ((eq system-type 'darwin)
7371 org-file-apps-defaults-macosx)
7372 ((eq system-type 'windows-nt)
7373 org-file-apps-defaults-windowsnt)
7374 (t org-file-apps-defaults-gnu)))
7375
7376 (defun org-expand-file-name (path)
7377 "Replace special path abbreviations and expand the file name."
7378 (expand-file-name path))
7379
7380
7381 (defvar org-insert-link-history nil
7382 "Minibuffer history for links inserted with `org-insert-link'.")
7383
7384 (defvar org-stored-links nil
7385 "Contains the links stored with `org-store-link'.")
7386
7387 ;;;###autoload
7388 (defun org-store-link (arg)
7389 "\\<org-mode-map>Store an org-link to the current location.
7390 This link can later be inserted into an org-buffer with
7391 \\[org-insert-link].
7392 For some link types, a prefix arg is interpreted:
7393 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7394 For file links, arg negates `org-context-in-file-links'."
7395 (interactive "P")
7396 (let (link cpltxt txt (pos (point)))
7397 (cond
7398
7399 ((eq major-mode 'bbdb-mode)
7400 (setq cpltxt (concat
7401 "bbdb:"
7402 (or (bbdb-record-name (bbdb-current-record))
7403 (bbdb-record-company (bbdb-current-record))))
7404 link (org-make-link cpltxt)))
7405
7406 ((eq major-mode 'calendar-mode)
7407 (let ((cd (calendar-cursor-to-date)))
7408 (setq link
7409 (format-time-string
7410 (car org-time-stamp-formats)
7411 (apply 'encode-time
7412 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7413 nil nil nil))))))
7414
7415 ((or (eq major-mode 'vm-summary-mode)
7416 (eq major-mode 'vm-presentation-mode))
7417 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7418 (vm-follow-summary-cursor)
7419 (save-excursion
7420 (vm-select-folder-buffer)
7421 (let* ((message (car vm-message-pointer))
7422 (folder buffer-file-name)
7423 (subject (vm-su-subject message))
7424 (author (vm-su-full-name message))
7425 (message-id (vm-su-message-id message)))
7426 (setq message-id (org-remove-angle-brackets message-id))
7427 (setq folder (abbreviate-file-name folder))
7428 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7429 folder)
7430 (setq folder (replace-match "" t t folder)))
7431 (setq cpltxt (concat author " on: " subject))
7432 (setq link (concat cpltxt "\n "
7433 (org-make-link
7434 "vm:" folder "#" message-id))))))
7435
7436 ((eq major-mode 'wl-summary-mode)
7437 (let* ((msgnum (wl-summary-message-number))
7438 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7439 msgnum 'message-id))
7440 (wl-message-entity (elmo-msgdb-overview-get-entity
7441 msgnum (wl-summary-buffer-msgdb)))
7442 (author (wl-summary-line-from)) ; FIXME: how to get author name?
7443 (subject "???")) ; FIXME: How to get subject of email?
7444 (setq message-id (org-remove-angle-brackets message-id))
7445 (setq cpltxt (concat author " on: " subject))
7446 (setq link (concat cpltxt "\n "
7447 (org-make-link
7448 "wl:" wl-summary-buffer-folder-name
7449 "#" message-id)))))
7450
7451 ((or (equal major-mode 'mh-folder-mode)
7452 (equal major-mode 'mh-show-mode))
7453 (let ((from-header (org-mhe-get-header "From:"))
7454 (to-header (org-mhe-get-header "To:"))
7455 (subject (org-mhe-get-header "Subject:")))
7456 (setq cpltxt (concat from-header " on: " subject))
7457 (setq link (concat cpltxt "\n "
7458 (org-make-link
7459 "mhe:" (org-mhe-get-message-real-folder) "#"
7460 (org-remove-angle-brackets
7461 (org-mhe-get-header "Message-Id:")))))))
7462
7463 ((eq major-mode 'rmail-mode)
7464 (save-excursion
7465 (save-restriction
7466 (rmail-narrow-to-non-pruned-header)
7467 (let ((folder buffer-file-name)
7468 (message-id (mail-fetch-field "message-id"))
7469 (author (mail-fetch-field "from"))
7470 (subject (mail-fetch-field "subject")))
7471 (setq message-id (org-remove-angle-brackets message-id))
7472 (setq cpltxt (concat author " on: " subject))
7473 (setq link (concat cpltxt "\n "
7474 (org-make-link
7475 "rmail:" folder "#" message-id)))))))
7476
7477 ((eq major-mode 'gnus-group-mode)
7478 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7479 (gnus-group-group-name)) ; version
7480 ((fboundp 'gnus-group-name)
7481 (gnus-group-name))
7482 (t "???"))))
7483 (setq cpltxt (concat
7484 (if (org-xor arg org-usenet-links-prefer-google)
7485 "http://groups.google.com/groups?group="
7486 "gnus:")
7487 group)
7488 link (org-make-link cpltxt))))
7489
7490 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7491 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7492 (gnus-summary-beginning-of-article)
7493 (let* ((group (car gnus-article-current))
7494 (article (cdr gnus-article-current))
7495 (header (gnus-summary-article-header article))
7496 (author (mail-header-from header))
7497 (message-id (mail-header-id header))
7498 (date (mail-header-date header))
7499 (subject (gnus-summary-subject-string)))
7500 (setq cpltxt (concat author " on: " subject))
7501 (if (org-xor arg org-usenet-links-prefer-google)
7502 (setq link
7503 (concat
7504 cpltxt "\n "
7505 (format "http://groups.google.com/groups?as_umsgid=%s"
7506 (org-fixup-message-id-for-http message-id))))
7507 (setq link (concat cpltxt "\n"
7508 (org-make-link
7509 "gnus:" group
7510 "#" (number-to-string article)))))))
7511
7512 ((eq major-mode 'w3-mode)
7513 (setq cpltxt (url-view-url t)
7514 link (org-make-link cpltxt)))
7515 ((eq major-mode 'w3m-mode)
7516 (setq cpltxt w3m-current-url
7517 link (org-make-link cpltxt)))
7518
7519 ((eq major-mode 'org-mode)
7520 ;; Just link to current headline
7521 (setq cpltxt (concat "file:"
7522 (abbreviate-file-name buffer-file-name)))
7523 ;; Add a context search string
7524 (when (org-xor org-context-in-file-links arg)
7525 ;; Check if we are on a target
7526 (if (save-excursion
7527 (skip-chars-forward "^>\n\r")
7528 (and (re-search-backward "<<" nil t)
7529 (looking-at "<<\\(.*?\\)>>")
7530 (<= (match-beginning 0) pos)
7531 (>= (match-end 0) pos)))
7532 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7533 (setq txt (cond
7534 ((org-on-heading-p) nil)
7535 ((org-region-active-p)
7536 (buffer-substring (region-beginning) (region-end)))
7537 (t (buffer-substring (point-at-bol) (point-at-eol)))))
7538 (setq cpltxt
7539 (concat cpltxt "::"
7540 (if org-file-link-context-use-camel-case
7541 (org-make-org-heading-camel txt)
7542 (org-make-org-heading-search-string txt))))))
7543 (if (string-match "::\\'" cpltxt)
7544 (setq cpltxt (substring cpltxt 0 -2)))
7545 (setq link (org-make-link cpltxt)))
7546
7547 (buffer-file-name
7548 ;; Just link to this file here.
7549 (setq cpltxt (concat "file:"
7550 (abbreviate-file-name buffer-file-name)))
7551 ;; Add a context string
7552 (when (org-xor org-context-in-file-links arg)
7553 (setq txt (if (org-region-active-p)
7554 (buffer-substring (region-beginning) (region-end))
7555 (buffer-substring (point-at-bol) (point-at-eol))))
7556 (setq cpltxt
7557 (concat cpltxt "::"
7558 (if org-file-link-context-use-camel-case
7559 (org-make-org-heading-camel txt)
7560 (org-make-org-heading-search-string txt)))))
7561 (setq link (org-make-link cpltxt)))
7562
7563 ((interactive-p)
7564 (error "Cannot link to a buffer which is not visiting a file"))
7565
7566 (t (setq link nil)))
7567
7568 (if (and (interactive-p) link)
7569 (progn
7570 (setq org-stored-links
7571 (cons (cons (or cpltxt link) link) org-stored-links))
7572 (message "Stored: %s" (or cpltxt link)))
7573 link)))
7574
7575 (defun org-make-org-heading-search-string (&optional string heading)
7576 "Make search string for STRING or current headline."
7577 (interactive)
7578 (let ((s (or string (org-get-heading))))
7579 (unless (and string (not heading))
7580 ;; We are using a headline, clean up garbage in there.
7581 (if (string-match org-todo-regexp s)
7582 (setq s (replace-match "" t t s)))
7583 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7584 (setq s (replace-match "" t t s)))
7585 (setq s (org-trim s))
7586 (if (string-match (concat "^\\(" org-quote-string "\\|"
7587 org-comment-string "\\)") s)
7588 (setq s (replace-match "" t t s)))
7589 (while (string-match org-ts-regexp s)
7590 (setq s (replace-match "" t t s))))
7591 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7592 (setq s (replace-match " " t t s)))
7593 (or string (setq s (concat "*" s))) ; Add * for headlines
7594 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7595
7596 (defun org-make-org-heading-camel (&optional string heading)
7597 "Make a CamelCase string for STRING or the current headline."
7598 (interactive)
7599 (let ((s (or string (org-get-heading))))
7600 (unless (and string (not heading))
7601 ;; We are using a headline, clean up garbage in there.
7602 (if (string-match org-todo-regexp s)
7603 (setq s (replace-match "" t t s)))
7604 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7605 (setq s (replace-match "" t t s)))
7606 (setq s (org-trim s))
7607 (if (string-match (concat "^\\(" org-quote-string "\\|"
7608 org-comment-string "\\)") s)
7609 (setq s (replace-match "" t t s)))
7610 (while (string-match org-ts-regexp s)
7611 (setq s (replace-match "" t t s))))
7612 (while (string-match "[^a-zA-Z_ \t]+" s)
7613 (setq s (replace-match " " t t s)))
7614 (or string (setq s (concat "*" s))) ; Add * for headlines
7615 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7616
7617 (defun org-make-link (&rest strings)
7618 "Concatenate STRINGS, format resulting string with `org-link-format'."
7619 (format org-link-format (apply 'concat strings)))
7620
7621 (defun org-make-link2 (link &optional description)
7622 "Make a link with brackets."
7623 (concat "[[" link "]"
7624 (if description (concat "[" description "]") "")
7625 "]"))
7626
7627 (defun org-xor (a b)
7628 "Exclusive or."
7629 (if a (not b) b))
7630
7631 (defun org-get-header (header)
7632 "Find a header field in the current buffer."
7633 (save-excursion
7634 (goto-char (point-min))
7635 (let ((case-fold-search t) s)
7636 (cond
7637 ((eq header 'from)
7638 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7639 (setq s (match-string 1)))
7640 (while (string-match "\"" s)
7641 (setq s (replace-match "" t t s)))
7642 (if (string-match "[<(].*" s)
7643 (setq s (replace-match "" t t s))))
7644 ((eq header 'message-id)
7645 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7646 (setq s (match-string 1))))
7647 ((eq header 'subject)
7648 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7649 (setq s (match-string 1)))))
7650 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7651 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7652 s)))
7653
7654
7655 (defun org-fixup-message-id-for-http (s)
7656 "Replace special characters in a message id, so it can be used in an http query."
7657 (while (string-match "<" s)
7658 (setq s (replace-match "%3C" t t s)))
7659 (while (string-match ">" s)
7660 (setq s (replace-match "%3E" t t s)))
7661 (while (string-match "@" s)
7662 (setq s (replace-match "%40" t t s)))
7663 s)
7664
7665 (defun org-insert-link (&optional complete-file)
7666 "Insert a link. At the prompt, enter the link.
7667
7668 Completion can be used to select a link previously stored with
7669 `org-store-link'. When the empty string is entered (i.e. if you just
7670 press RET at the prompt), the link defaults to the most recently
7671 stored link. As SPC triggers completion in the minibuffer, you need to
7672 use M-SPC or C-q SPC to force the insertion of a space character.
7673
7674 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7675 selected using completion. The path to the file will be relative to
7676 the current directory if the file is in the current directory or a
7677 subdirectory. Otherwise, the link will be the absolute path as
7678 completed in the minibuffer (i.e. normally ~/path/to/file).
7679
7680 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7681 is in the current directory or below."
7682 (interactive "P")
7683 (let ((link (if complete-file
7684 (read-file-name "File: ")
7685 (completing-read
7686 "Link: " org-stored-links nil nil nil
7687 org-insert-link-history
7688 (or (car (car org-stored-links))))))
7689 linktxt matched)
7690 (if (or (not link) (equal link ""))
7691 (error "No links available"))
7692 (if complete-file
7693 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7694 (cond
7695 ((equal complete-file '(16))
7696 (insert
7697 (org-make-link
7698 "file:" (abbreviate-file-name (expand-file-name link)))))
7699 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7700 (expand-file-name link))
7701 (insert
7702 (org-make-link
7703 "file:" (match-string 1 (expand-file-name link)))))
7704 (t (insert (org-make-link "file:" link)))))
7705 (setq linktxt (cdr (assoc link org-stored-links)))
7706 (if (not org-keep-stored-link-after-insertion)
7707 (setq org-stored-links (delq (assoc link org-stored-links)
7708 org-stored-links)))
7709 (if (not linktxt) (setq link (org-make-link link)))
7710 (setq link (or linktxt link))
7711 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7712 (let* ((path (match-string 1 link))
7713 (case-fold-search nil)
7714 (search (match-string 2 link)))
7715 (when (save-match-data
7716 (equal (file-truename buffer-file-name)
7717 (file-truename path)))
7718 ;; We are linking to this same file
7719 (if (and org-file-link-context-use-camel-case
7720 (save-match-data
7721 (string-match (concat "^" org-camel-regexp "$") search)))
7722 (setq link (replace-match search t t link)
7723 matched t)
7724 (setq link (replace-match (concat "[[" search "]]")
7725 t t link)
7726 matched t)))))
7727 (let ((lines (org-split-string link "\n")))
7728 (insert (car lines))
7729 (setq matched (or matched (string-match org-link-regexp (car lines))))
7730 (setq lines (cdr lines))
7731 (while lines
7732 (insert "\n")
7733 (if (save-excursion
7734 (beginning-of-line 0)
7735 (looking-at "[ \t]+\\S-"))
7736 (indent-relative))
7737 (setq matched (or matched
7738 (string-match org-link-regexp (car lines))))
7739 (insert (car lines))
7740 (setq lines (cdr lines))))
7741 (unless matched
7742 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7743
7744 ;;; Hooks for remember.el
7745 ;;;###autoload
7746 (defun org-remember-annotation ()
7747 "Return a link to the current location as an annotation for remember.el.
7748 If you are using Org-mode files as target for data storage with
7749 remember.el, then the annotations should include a link compatible with the
7750 conventions in Org-mode. This function returns such a link."
7751 (org-store-link nil))
7752
7753 (defconst org-remember-help
7754 "Select a destination location for the note.
7755 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7756 RET at beg-of-buf -> Append to file as level 2 headline
7757 RET on headline -> Store as sublevel entry to current headline
7758 <left>/<right> -> before/after current headline, same headings level")
7759
7760 ;;;###autoload
7761 (defun org-remember-handler ()
7762 "Store stuff from remember.el into an org file.
7763 First prompts for an org file. If the user just presses return, the value
7764 of `org-default-notes-file' is used.
7765 Then the command offers the headings tree of the selected file in order to
7766 file the text at a specific location.
7767 You can either immediately press RET to get the note appended to the
7768 file, or you can use vertical cursor motion and visibility cycling (TAB) to
7769 find a better place. Then press RET or <left> or <right> in insert the note.
7770
7771 Key Cursor position Note gets inserted
7772 -----------------------------------------------------------------------------
7773 RET buffer-start as level 2 heading at end of file
7774 RET on headline as sublevel of the heading at cursor
7775 RET no heading at cursor position, level taken from context.
7776 Or use prefix arg to specify level manually.
7777 <left> on headline as same level, before current heading
7778 <right> on headline as same level, after current heading
7779
7780 So the fastest way to store the note is to press RET RET to append it to
7781 the default file. This way your current train of thought is not
7782 interrupted, in accordance with the principles of remember.el. But with
7783 little extra effort, you can push it directly to the correct location.
7784
7785 Before being stored away, the function ensures that the text has a
7786 headline, i.e. a first line that starts with a \"*\". If not, a headline
7787 is constructed from the current date and some additional data.
7788
7789 If the variable `org-adapt-indentation' is non-nil, the entire text is
7790 also indented so that it starts in the same column as the headline
7791 \(i.e. after the stars).
7792
7793 See also the variable `org-reverse-note-order'."
7794 (catch 'quit
7795 (let* ((txt (buffer-substring (point-min) (point-max)))
7796 (fastp current-prefix-arg)
7797 (file (if fastp org-default-notes-file (org-get-org-file)))
7798 (visiting (find-buffer-visiting file))
7799 (org-startup-with-deadline-check nil)
7800 (org-startup-folded nil)
7801 spos level indent reversed)
7802 ;; Modify text so that it becomes a nice subtree which can be inserted
7803 ;; into an org tree.
7804 (let* ((lines (split-string txt "\n"))
7805 (first (car lines))
7806 (lines (cdr lines)))
7807 (if (string-match "^\\*+" first)
7808 ;; Is already a headline
7809 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7810 -1) ?\ ))
7811 ;; We need to add a headline: Use time and first buffer line
7812 (setq lines (cons first lines)
7813 first (concat "* " (current-time-string)
7814 " (" (remember-buffer-desc) ")")
7815 indent " "))
7816 (if org-adapt-indentation
7817 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7818 (setq txt (concat first "\n"
7819 (mapconcat 'identity lines "\n"))))
7820 ;; Find the file
7821 (if (not visiting)
7822 (find-file-noselect file))
7823 (with-current-buffer (get-file-buffer file)
7824 (setq reversed (org-notes-order-reversed-p))
7825 (save-excursion
7826 (save-restriction
7827 (widen)
7828 ;; Ask the User for a location
7829 (setq spos (if fastp 1 (org-get-location
7830 (current-buffer)
7831 org-remember-help)))
7832 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7833 ; not handle this note
7834 (goto-char spos)
7835 (cond ((bobp)
7836 ;; Put it at the start or end, as level 2
7837 (save-restriction
7838 (widen)
7839 (goto-char (if reversed (point-min) (point-max)))
7840 (if (not (bolp)) (newline))
7841 (org-paste-subtree (or current-prefix-arg 2) txt)))
7842 ((and (org-on-heading-p nil) (not current-prefix-arg))
7843 ;; Put it below this entry, at the beg/end of the subtree
7844 (org-back-to-heading)
7845 (setq level (funcall outline-level))
7846 (if reversed
7847 (outline-end-of-heading)
7848 (outline-end-of-subtree))
7849 (if (not (bolp)) (newline))
7850 (beginning-of-line 1)
7851 (org-paste-subtree (1+ level) txt))
7852 (t
7853 ;; Put it right there, with automatic level determined by
7854 ;; org-paste-subtree or from prefix arg
7855 (org-paste-subtree current-prefix-arg txt)))
7856 (when remember-save-after-remembering
7857 (save-buffer)
7858 (if (not visiting) (kill-buffer (current-buffer)))))))))
7859 t) ;; return t to indicate that we took care of this note.
7860
7861 (defun org-get-org-file ()
7862 "Read a filename, with default directory `org-directory'."
7863 (let ((default (or org-default-notes-file remember-data-file)))
7864 (read-file-name (format "File name [%s]: " default)
7865 (file-name-as-directory org-directory)
7866 default)))
7867
7868 (defun org-notes-order-reversed-p ()
7869 "Check if the current file should receive notes in reversed order."
7870 (cond
7871 ((not org-reverse-note-order) nil)
7872 ((eq t org-reverse-note-order) t)
7873 ((not (listp org-reverse-note-order)) nil)
7874 (t (catch 'exit
7875 (let ((all org-reverse-note-order)
7876 entry)
7877 (while (setq entry (pop all))
7878 (if (string-match (car entry) buffer-file-name)
7879 (throw 'exit (cdr entry))))
7880 nil)))))
7881
7882 ;;; Tables
7883
7884 ;; Watch out: Here we are talking about two different kind of tables.
7885 ;; Most of the code is for the tables created with the Org-mode table editor.
7886 ;; Sometimes, we talk about tables created and edited with the table.el
7887 ;; Emacs package. We call the former org-type tables, and the latter
7888 ;; table.el-type tables.
7889
7890
7891 (defun org-before-change-function (beg end)
7892 "Every change indicates that a table might need an update."
7893 (setq org-table-may-need-update t))
7894
7895 (defconst org-table-line-regexp "^[ \t]*|"
7896 "Detects an org-type table line.")
7897 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7898 "Detects an org-type table line.")
7899 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7900 "Detects a table line marked for automatic recalculation.")
7901 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7902 "Detects a table line marked for automatic recalculation.")
7903 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7904 "Detects a table line marked for automatic recalculation.")
7905 (defconst org-table-hline-regexp "^[ \t]*|-"
7906 "Detects an org-type table hline.")
7907 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7908 "Detects a table-type table hline.")
7909 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7910 "Detects an org-type or table-type table.")
7911 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7912 "Searching from within a table (any type) this finds the first line
7913 outside the table.")
7914 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7915 "Searching from within a table (any type) this finds the first line
7916 outside the table.")
7917
7918 (defun org-table-create-with-table.el ()
7919 "Use the table.el package to insert a new table.
7920 If there is already a table at point, convert between Org-mode tables
7921 and table.el tables."
7922 (interactive)
7923 (require 'table)
7924 (cond
7925 ((org-at-table.el-p)
7926 (if (y-or-n-p "Convert table to Org-mode table? ")
7927 (org-table-convert)))
7928 ((org-at-table-p)
7929 (if (y-or-n-p "Convert table to table.el table? ")
7930 (org-table-convert)))
7931 (t (call-interactively 'table-insert))))
7932
7933 (defun org-table-create (&optional size)
7934 "Query for a size and insert a table skeleton.
7935 SIZE is a string Columns x Rows like for example \"3x2\"."
7936 (interactive "P")
7937 (unless size
7938 (setq size (read-string
7939 (concat "Table size Columns x Rows [e.g. "
7940 org-table-default-size "]: ")
7941 "" nil org-table-default-size)))
7942
7943 (let* ((pos (point))
7944 (indent (make-string (current-column) ?\ ))
7945 (split (org-split-string size " *x *"))
7946 (rows (string-to-number (nth 1 split)))
7947 (columns (string-to-number (car split)))
7948 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7949 "\n")))
7950 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7951 (point-at-bol) (point)))
7952 (beginning-of-line 1)
7953 (newline))
7954 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7955 (dotimes (i rows) (insert line))
7956 (goto-char pos)
7957 (if (> rows 1)
7958 ;; Insert a hline after the first row.
7959 (progn
7960 (end-of-line 1)
7961 (insert "\n|-")
7962 (goto-char pos)))
7963 (org-table-align)))
7964
7965 (defun org-table-convert-region (beg0 end0 nspace)
7966 "Convert region to a table.
7967 The region goes from BEG0 to END0, but these borders will be moved
7968 slightly, to make sure a beginning of line in the first line is included.
7969 When NSPACE is non-nil, it indicates the minimum number of spaces that
7970 separate columns (default: just one space)."
7971 (let* ((beg (min beg0 end0))
7972 (end (max beg0 end0))
7973 (tabsep t)
7974 re)
7975 (goto-char beg)
7976 (beginning-of-line 1)
7977 (setq beg (move-marker (make-marker) (point)))
7978 (goto-char end)
7979 (if (bolp) (backward-char 1) (end-of-line 1))
7980 (setq end (move-marker (make-marker) (point)))
7981 ;; Lets see if this is tab-separated material. If every nonempty line
7982 ;; contains a tab, we will assume that it is tab-separated material
7983 (if nspace
7984 (setq tabsep nil)
7985 (goto-char beg)
7986 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7987 (if nspace (setq tabsep nil))
7988 (if tabsep
7989 (setq re "^\\|\t")
7990 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7991 (max 1 (prefix-numeric-value nspace)))))
7992 (goto-char beg)
7993 (while (re-search-forward re end t)
7994 (replace-match "|" t t))
7995 (goto-char beg)
7996 (insert " ")
7997 (org-table-align)))
7998
7999 (defun org-table-import (file arg)
8000 "Import FILE as a table.
8001 The file is assumed to be tab-separated. Such files can be produced by most
8002 spreadsheet and database applications. If no tabs (at least one per line)
8003 are found, lines will be split on whitespace into fields."
8004 (interactive "f\nP")
8005 (or (bolp) (newline))
8006 (let ((beg (point))
8007 (pm (point-max)))
8008 (insert-file-contents file)
8009 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8010
8011 (defun org-table-export ()
8012 "Export table as a tab-separated file.
8013 Such a file can be imported into a spreadsheet program like Excel."
8014 (interactive)
8015 (let* ((beg (org-table-begin))
8016 (end (org-table-end))
8017 (table (buffer-substring beg end))
8018 (file (read-file-name "Export table to: "))
8019 buf)
8020 (unless (or (not (file-exists-p file))
8021 (y-or-n-p (format "Overwrite file %s? " file)))
8022 (error "Abort"))
8023 (with-current-buffer (find-file-noselect file)
8024 (setq buf (current-buffer))
8025 (erase-buffer)
8026 (fundamental-mode)
8027 (insert table)
8028 (goto-char (point-min))
8029 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8030 (replace-match "" t t)
8031 (end-of-line 1))
8032 (goto-char (point-min))
8033 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8034 (replace-match "" t t)
8035 (goto-char (min (1+ (point)) (point-max))))
8036 (goto-char (point-min))
8037 (while (re-search-forward "^-[-+]*$" nil t)
8038 (replace-match "")
8039 (if (looking-at "\n")
8040 (delete-char 1)))
8041 (goto-char (point-min))
8042 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8043 (replace-match "\t" t t))
8044 (save-buffer))
8045 (kill-buffer buf)))
8046
8047 (defvar org-table-aligned-begin-marker (make-marker)
8048 "Marker at the beginning of the table last aligned.
8049 Used to check if cursor still is in that table, to minimize realignment.")
8050 (defvar org-table-aligned-end-marker (make-marker)
8051 "Marker at the end of the table last aligned.
8052 Used to check if cursor still is in that table, to minimize realignment.")
8053 (defvar org-table-last-alignment nil
8054 "List of flags for flushright alignment, from the last re-alignment.
8055 This is being used to correctly align a single field after TAB or RET.")
8056 ;; FIXME: The following is currently not used.
8057 (defvar org-table-last-column-widths nil
8058 "List of max width of fields in each column.
8059 This is being used to correctly align a single field after TAB or RET.")
8060
8061 (defvar org-last-recalc-line nil)
8062
8063 (defun org-table-align ()
8064 "Align the table at point by aligning all vertical bars."
8065 (interactive)
8066 ;; (message "align") (sit-for 2)
8067 (let* (
8068 ;; Limits of table
8069 (beg (org-table-begin))
8070 (end (org-table-end))
8071 ;; Current cursor position
8072 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8073 (colpos (org-table-current-column))
8074 (winstart (window-start))
8075 text lines (new "") lengths l typenums ty fields maxfields i
8076 column
8077 (indent "") cnt frac
8078 rfmt hfmt
8079 (spaces (if (org-in-invisibility-spec-p '(org-table))
8080 org-table-spaces-around-invisible-separators
8081 org-table-spaces-around-separators))
8082 (sp1 (car spaces))
8083 (sp2 (cdr spaces))
8084 (rfmt1 (concat
8085 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8086 (hfmt1 (concat
8087 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8088 emptystrings)
8089 (untabify beg end)
8090 ;; (message "Aligning table...")
8091 ;; Get the rows
8092 (setq lines (org-split-string
8093 (buffer-substring-no-properties beg end) "\n"))
8094 ;; Store the indentation of the first line
8095 (if (string-match "^ *" (car lines))
8096 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8097 ;; Mark the hlines
8098 (setq lines (mapcar (lambda (l)
8099 (if (string-match "^ *|-" l)
8100 nil
8101 (if (string-match "[ \t]+$" l)
8102 (substring l 0 (match-beginning 0))
8103 l)))
8104 lines))
8105 ;; Get the data fields
8106 (setq fields (mapcar
8107 (lambda (l)
8108 (org-split-string l " *| *"))
8109 (delq nil (copy-sequence lines))))
8110 ;; How many fields in the longest line?
8111 (condition-case nil
8112 (setq maxfields (apply 'max (mapcar 'length fields)))
8113 (error
8114 (kill-region beg end)
8115 (org-table-create org-table-default-size)
8116 (error "Empty table - created default table")))
8117 ;; A list of empty string to fill any short rows on output
8118 (setq emptystrings (make-list maxfields ""))
8119 ;; Get the maximum length of a field and the most common datatype
8120 ;; for each column
8121 (setq i -1)
8122 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8123 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8124 ;; maximum length
8125 (push (apply 'max 1 (mapcar 'string-width column)) lengths)
8126 ;; compute the fraction stepwise, ignoring empty fields
8127 (setq cnt 0 frac 0.0)
8128 (mapcar
8129 (lambda (x)
8130 (if (equal x "")
8131 nil
8132 (setq frac ( / (+ (* frac cnt)
8133 (if (string-match org-table-number-regexp x) 1 0))
8134 (setq cnt (1+ cnt))))))
8135 column)
8136 (push (>= frac org-table-number-fraction) typenums))
8137 (setq lengths (nreverse lengths)
8138 typenums (nreverse typenums))
8139 (setq org-table-last-alignment typenums
8140 org-table-last-column-widths lengths)
8141 ;; Compute the formats needed for output of the table
8142 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8143 (while (setq l (pop lengths))
8144 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8145 (setq rfmt (concat rfmt (format rfmt1 ty l))
8146 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8147 (setq rfmt (concat rfmt "\n")
8148 hfmt (concat (substring hfmt 0 -1) "|\n"))
8149 ;; Produce the new table
8150 ;;(while lines
8151 ;; (setq l (pop lines))
8152 ;; (if l
8153 ;; (setq new (concat new (apply 'format rfmt
8154 ;; (append (pop fields) emptystrings))))
8155 ;; (setq new (concat new hfmt))))
8156 (setq new (mapconcat
8157 (lambda (l)
8158 (if l (apply 'format rfmt
8159 (append (pop fields) emptystrings))
8160 hfmt))
8161 lines ""))
8162 ;; Replace the old one
8163 (delete-region beg end)
8164 (move-marker end nil)
8165 (move-marker org-table-aligned-begin-marker (point))
8166 (insert new)
8167 (move-marker org-table-aligned-end-marker (point))
8168 ;; Try to move to the old location (approximately)
8169 (goto-line linepos)
8170 (set-window-start (selected-window) winstart 'noforce)
8171 (org-table-goto-column colpos)
8172 (setq org-table-may-need-update nil)
8173 (if (org-in-invisibility-spec-p '(org-table))
8174 (org-table-add-invisible-to-vertical-lines))
8175 ))
8176
8177 (defun org-table-begin (&optional table-type)
8178 "Find the beginning of the table and return its position.
8179 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8180 (save-excursion
8181 (if (not (re-search-backward
8182 (if table-type org-table-any-border-regexp
8183 org-table-border-regexp)
8184 nil t))
8185 (error "Can't find beginning of table")
8186 (goto-char (match-beginning 0))
8187 (beginning-of-line 2)
8188 (point))))
8189
8190 (defun org-table-end (&optional table-type)
8191 "Find the end of the table and return its position.
8192 With argument TABLE-TYPE, go to the end of a table.el-type table."
8193 (save-excursion
8194 (if (not (re-search-forward
8195 (if table-type org-table-any-border-regexp
8196 org-table-border-regexp)
8197 nil t))
8198 (goto-char (point-max))
8199 (goto-char (match-beginning 0)))
8200 (point-marker)))
8201
8202 (defun org-table-justify-field-maybe (&optional new)
8203 "Justify the current field, text to left, number to right.
8204 Optional argument NEW may specify text to replace the current field content."
8205 (cond
8206 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8207 ((org-at-table-hline-p)
8208 ;; FIXME: I used to enforce realign here, but I think this is not needed.
8209 ;; (setq org-table-may-need-update t)
8210 )
8211 ((and (not new)
8212 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8213 (current-buffer)))
8214 (< (point) org-table-aligned-begin-marker)
8215 (>= (point) org-table-aligned-end-marker)))
8216 ;; This is not the same table, force a full re-align
8217 (setq org-table-may-need-update t))
8218 (t ;; realign the current field, based on previous full realign
8219 (let* ((pos (point)) s
8220 (col (org-table-current-column))
8221 (num (nth (1- col) org-table-last-alignment))
8222 l f n o e)
8223 (when (> col 0)
8224 (skip-chars-backward "^|\n")
8225 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8226 (progn
8227 (setq s (match-string 1)
8228 o (match-string 0)
8229 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8230 e (not (= (match-beginning 2) (match-end 2))))
8231 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8232 l (if e "|" (setq org-table-may-need-update t) ""))
8233 n (format f s t t))
8234 (if new
8235 (if (<= (length new) l)
8236 (setq n (format f new t t)) ;; FIXME: why t t?????
8237 (setq n (concat new "|") org-table-may-need-update t)))
8238 (or (equal n o)
8239 (let (org-table-may-need-update)
8240 (replace-match n))))
8241 (setq org-table-may-need-update t))
8242 (goto-char pos))))))
8243
8244 (defun org-table-next-field ()
8245 "Go to the next field in the current table, creating new lines as needed.
8246 Before doing so, re-align the table if necessary."
8247 (interactive)
8248 (org-table-maybe-eval-formula)
8249 (org-table-maybe-recalculate-line)
8250 (if (and org-table-automatic-realign
8251 org-table-may-need-update)
8252 (org-table-align))
8253 (let ((end (org-table-end)))
8254 (if (org-at-table-hline-p)
8255 (end-of-line 1))
8256 (condition-case nil
8257 (progn
8258 (re-search-forward "|" end)
8259 (if (looking-at "[ \t]*$")
8260 (re-search-forward "|" end))
8261 (if (and (looking-at "-")
8262 org-table-tab-jumps-over-hlines
8263 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8264 (goto-char (match-beginning 1)))
8265 (if (looking-at "-")
8266 (progn
8267 (beginning-of-line 0)
8268 (org-table-insert-row 'below))
8269 (if (looking-at " ") (forward-char 1))))
8270 (error
8271 (org-table-insert-row 'below)))))
8272
8273 (defun org-table-previous-field ()
8274 "Go to the previous field in the table.
8275 Before doing so, re-align the table if necessary."
8276 (interactive)
8277 (org-table-justify-field-maybe)
8278 (org-table-maybe-recalculate-line)
8279 (if (and org-table-automatic-realign
8280 org-table-may-need-update)
8281 (org-table-align))
8282 (if (org-at-table-hline-p)
8283 (end-of-line 1))
8284 (re-search-backward "|" (org-table-begin))
8285 (re-search-backward "|" (org-table-begin))
8286 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8287 (re-search-backward "|" (org-table-begin)))
8288 (if (looking-at "| ?")
8289 (goto-char (match-end 0))))
8290
8291 (defun org-table-next-row ()
8292 "Go to the next row (same column) in the current table.
8293 Before doing so, re-align the table if necessary."
8294 (interactive)
8295 (org-table-maybe-eval-formula)
8296 (org-table-maybe-recalculate-line)
8297 (if (or (looking-at "[ \t]*$")
8298 (save-excursion (skip-chars-backward " \t") (bolp)))
8299 (newline)
8300 (if (and org-table-automatic-realign
8301 org-table-may-need-update)
8302 (org-table-align))
8303 (let ((col (org-table-current-column)))
8304 (beginning-of-line 2)
8305 (if (or (not (org-at-table-p))
8306 (org-at-table-hline-p))
8307 (progn
8308 (beginning-of-line 0)
8309 (org-table-insert-row 'below)))
8310 (org-table-goto-column col)
8311 (skip-chars-backward "^|\n\r")
8312 (if (looking-at " ") (forward-char 1)))))
8313
8314 (defun org-table-copy-down (n)
8315 "Copy a field down in the current column.
8316 If the field at the cursor is empty, copy into it the content of the nearest
8317 non-empty field above. With argument N, use the Nth non-empty field.
8318 If the current field is not empty, it is copied down to the next row, and
8319 the cursor is moved with it. Therefore, repeating this command causes the
8320 column to be filled row-by-row.
8321 If the variable `org-table-copy-increment' is non-nil and the field is an
8322 integer, it will be incremented while copying."
8323 (interactive "p")
8324 (let* ((colpos (org-table-current-column))
8325 (field (org-table-get-field))
8326 (non-empty (string-match "[^ \t]" field))
8327 (beg (org-table-begin))
8328 txt)
8329 (org-table-check-inside-data-field)
8330 (if non-empty
8331 (progn
8332 (setq txt (org-trim field))
8333 (org-table-next-row)
8334 (org-table-blank-field))
8335 (save-excursion
8336 (setq txt
8337 (catch 'exit
8338 (while (progn (beginning-of-line 1)
8339 (re-search-backward org-table-dataline-regexp
8340 beg t))
8341 (org-table-goto-column colpos t)
8342 (if (and (looking-at
8343 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8344 (= (setq n (1- n)) 0))
8345 (throw 'exit (match-string 1))))))))
8346 (if txt
8347 (progn
8348 (if (and org-table-copy-increment
8349 (string-match "^[0-9]+$" txt))
8350 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8351 (insert txt)
8352 (org-table-maybe-recalculate-line)
8353 (org-table-align))
8354 (error "No non-empty field found"))))
8355
8356 (defun org-table-check-inside-data-field ()
8357 "Is point inside a table data field?
8358 I.e. not on a hline or before the first or after the last column?
8359 This actually throws an error, so it aborts the current command."
8360 (if (or (not (org-at-table-p))
8361 (= (org-table-current-column) 0)
8362 (org-at-table-hline-p)
8363 (looking-at "[ \t]*$"))
8364 (error "Not in table data field")))
8365
8366 (defvar org-table-clip nil
8367 "Clipboard for table regions.")
8368
8369 (defun org-table-blank-field ()
8370 "Blank the current table field or active region."
8371 (interactive)
8372 (org-table-check-inside-data-field)
8373 (if (and (interactive-p) (org-region-active-p))
8374 (let (org-table-clip)
8375 (org-table-cut-region (region-beginning) (region-end)))
8376 (skip-chars-backward "^|")
8377 (backward-char 1)
8378 (if (looking-at "|[^|\n]+")
8379 (let* ((pos (match-beginning 0))
8380 (match (match-string 0))
8381 (len (string-width match)))
8382 (replace-match (concat "|" (make-string (1- len) ?\ )))
8383 (goto-char (+ 2 pos))
8384 (substring match 1)))))
8385
8386 (defun org-table-get-field (&optional n replace)
8387 "Return the value of the field in column N of current row.
8388 N defaults to current field.
8389 If REPLACE is a string, replace field with this value. The return value
8390 is always the old value."
8391 (and n (org-table-goto-column n))
8392 (skip-chars-backward "^|\n")
8393 (backward-char 1)
8394 (if (looking-at "|[^|\r\n]*")
8395 (let* ((pos (match-beginning 0))
8396 (val (buffer-substring (1+ pos) (match-end 0))))
8397 (if replace
8398 (replace-match (concat "|" replace)))
8399 (goto-char (min (point-at-eol) (+ 2 pos)))
8400 val)
8401 (forward-char 1) ""))
8402
8403 (defun org-table-current-column ()
8404 "Find out which column we are in.
8405 When called interactively, column is also displayed in echo area."
8406 (interactive)
8407 (if (interactive-p) (org-table-check-inside-data-field))
8408 (save-excursion
8409 (let ((cnt 0) (pos (point)))
8410 (beginning-of-line 1)
8411 (while (search-forward "|" pos t)
8412 (setq cnt (1+ cnt)))
8413 (if (interactive-p) (message "This is table column %d" cnt))
8414 cnt)))
8415
8416 (defun org-table-goto-column (n &optional on-delim force)
8417 "Move the cursor to the Nth column in the current table line.
8418 With optional argument ON-DELIM, stop with point before the left delimiter
8419 of the field.
8420 If there are less than N fields, just go to after the last delimiter.
8421 However, when FORCE is non-nil, create new columns if necessary."
8422 (interactive "p")
8423 (let ((pos (point-at-eol)))
8424 (beginning-of-line 1)
8425 (when (> n 0)
8426 (while (and (> (setq n (1- n)) -1)
8427 (or (search-forward "|" pos t)
8428 (and force
8429 (progn (end-of-line 1)
8430 (skip-chars-backward "^|")
8431 (insert " | "))))))
8432 ; (backward-char 2) t)))))
8433 (when (and force (not (looking-at ".*|")))
8434 (save-excursion (end-of-line 1) (insert " | ")))
8435 (if on-delim
8436 (backward-char 1)
8437 (if (looking-at " ") (forward-char 1))))))
8438
8439 (defun org-at-table-p (&optional table-type)
8440 "Return t if the cursor is inside an org-type table.
8441 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8442 (if org-enable-table-editor
8443 (save-excursion
8444 (beginning-of-line 1)
8445 (looking-at (if table-type org-table-any-line-regexp
8446 org-table-line-regexp)))
8447 nil))
8448
8449 (defun org-at-table.el-p ()
8450 "Return t if and only if we are at a table.el table."
8451 (and (org-at-table-p 'any)
8452 (save-excursion
8453 (goto-char (org-table-begin 'any))
8454 (looking-at org-table1-hline-regexp))))
8455
8456 (defun org-table-recognize-table.el ()
8457 "If there is a table.el table nearby, recognize it and move into it."
8458 (if org-table-tab-recognizes-table.el
8459 (if (org-at-table.el-p)
8460 (progn
8461 (beginning-of-line 1)
8462 (if (looking-at org-table-dataline-regexp)
8463 nil
8464 (if (looking-at org-table1-hline-regexp)
8465 (progn
8466 (beginning-of-line 2)
8467 (if (looking-at org-table-any-border-regexp)
8468 (beginning-of-line -1)))))
8469 (if (re-search-forward "|" (org-table-end t) t)
8470 (progn
8471 (require 'table)
8472 (if (table--at-cell-p (point))
8473 t
8474 (message "recognizing table.el table...")
8475 (table-recognize-table)
8476 (message "recognizing table.el table...done")))
8477 (error "This should not happen..."))
8478 t)
8479 nil)
8480 nil))
8481
8482 (defun org-at-table-hline-p ()
8483 "Return t if the cursor is inside a hline in a table."
8484 (if org-enable-table-editor
8485 (save-excursion
8486 (beginning-of-line 1)
8487 (looking-at org-table-hline-regexp))
8488 nil))
8489
8490 (defun org-table-insert-column ()
8491 "Insert a new column into the table."
8492 (interactive)
8493 (if (not (org-at-table-p))
8494 (error "Not at a table"))
8495 (org-table-find-dataline)
8496 (let* ((col (max 1 (org-table-current-column)))
8497 (beg (org-table-begin))
8498 (end (org-table-end))
8499 ;; Current cursor position
8500 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8501 (colpos col))
8502 (goto-char beg)
8503 (while (< (point) end)
8504 (if (org-at-table-hline-p)
8505 nil
8506 (org-table-goto-column col t)
8507 (insert "| "))
8508 (beginning-of-line 2))
8509 (move-marker end nil)
8510 (goto-line linepos)
8511 (org-table-goto-column colpos)
8512 (org-table-align)
8513 (org-table-modify-formulas 'insert col)))
8514
8515 (defun org-table-find-dataline ()
8516 "Find a dataline in the current table, which is needed for column commands."
8517 (if (and (org-at-table-p)
8518 (not (org-at-table-hline-p)))
8519 t
8520 (let ((col (current-column))
8521 (end (org-table-end)))
8522 (move-to-column col)
8523 (while (and (< (point) end)
8524 (or (not (= (current-column) col))
8525 (org-at-table-hline-p)))
8526 (beginning-of-line 2)
8527 (move-to-column col))
8528 (if (and (org-at-table-p)
8529 (not (org-at-table-hline-p)))
8530 t
8531 (error
8532 "Please position cursor in a data line for column operations")))))
8533
8534 (defun org-table-delete-column ()
8535 "Delete a column into the table."
8536 (interactive)
8537 (if (not (org-at-table-p))
8538 (error "Not at a table"))
8539 (org-table-find-dataline)
8540 (org-table-check-inside-data-field)
8541 (let* ((col (org-table-current-column))
8542 (beg (org-table-begin))
8543 (end (org-table-end))
8544 ;; Current cursor position
8545 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8546 (colpos col))
8547 (goto-char beg)
8548 (while (< (point) end)
8549 (if (org-at-table-hline-p)
8550 nil
8551 (org-table-goto-column col t)
8552 (and (looking-at "|[^|\n]+|")
8553 (replace-match "|")))
8554 (beginning-of-line 2))
8555 (move-marker end nil)
8556 (goto-line linepos)
8557 (org-table-goto-column colpos)
8558 (org-table-align)
8559 (org-table-modify-formulas 'remove col)))
8560
8561 (defun org-table-move-column-right ()
8562 "Move column to the right."
8563 (interactive)
8564 (org-table-move-column nil))
8565 (defun org-table-move-column-left ()
8566 "Move column to the left."
8567 (interactive)
8568 (org-table-move-column 'left))
8569
8570 (defun org-table-move-column (&optional left)
8571 "Move the current column to the right. With arg LEFT, move to the left."
8572 (interactive "P")
8573 (if (not (org-at-table-p))
8574 (error "Not at a table"))
8575 (org-table-find-dataline)
8576 (org-table-check-inside-data-field)
8577 (let* ((col (org-table-current-column))
8578 (col1 (if left (1- col) col))
8579 (beg (org-table-begin))
8580 (end (org-table-end))
8581 ;; Current cursor position
8582 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8583 (colpos (if left (1- col) (1+ col))))
8584 (if (and left (= col 1))
8585 (error "Cannot move column further left"))
8586 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8587 (error "Cannot move column further right"))
8588 (goto-char beg)
8589 (while (< (point) end)
8590 (if (org-at-table-hline-p)
8591 nil
8592 (org-table-goto-column col1 t)
8593 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8594 (replace-match "|\\2|\\1|")))
8595 (beginning-of-line 2))
8596 (move-marker end nil)
8597 (goto-line linepos)
8598 (org-table-goto-column colpos)
8599 (org-table-align)
8600 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8601
8602 (defun org-table-move-row-down ()
8603 "Move table row down."
8604 (interactive)
8605 (org-table-move-row nil))
8606 (defun org-table-move-row-up ()
8607 "Move table row up."
8608 (interactive)
8609 (org-table-move-row 'up))
8610
8611 (defun org-table-move-row (&optional up)
8612 "Move the current table line down. With arg UP, move it up."
8613 (interactive "P")
8614 (let ((col (current-column))
8615 (pos (point))
8616 (tonew (if up 0 2))
8617 txt)
8618 (beginning-of-line tonew)
8619 (if (not (org-at-table-p))
8620 (progn
8621 (goto-char pos)
8622 (error "Cannot move row further")))
8623 (goto-char pos)
8624 (beginning-of-line 1)
8625 (setq pos (point))
8626 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8627 (delete-region (point) (1+ (point-at-eol)))
8628 (beginning-of-line tonew)
8629 (insert txt)
8630 (beginning-of-line 0)
8631 (move-to-column col)))
8632
8633 (defun org-table-insert-row (&optional arg)
8634 "Insert a new row above the current line into the table.
8635 With prefix ARG, insert below the current line."
8636 (interactive "P")
8637 (if (not (org-at-table-p))
8638 (error "Not at a table"))
8639 (let* ((line
8640 (org-expand-wide-chars
8641 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8642 new)
8643 (if (string-match "^[ \t]*|-" line)
8644 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8645 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8646 ;; Fix the first field if necessary
8647 (setq new (concat new))
8648 (if (string-match "^[ \t]*| *[#$] *|" line)
8649 (setq new (replace-match (match-string 0 line) t t new)))
8650 (beginning-of-line (if arg 2 1))
8651 (let (org-table-may-need-update)
8652 (insert-before-markers new)
8653 (insert-before-markers "\n"))
8654 (beginning-of-line 0)
8655 (re-search-forward "| ?" (point-at-eol) t)
8656 (and org-table-may-need-update (org-table-align))))
8657
8658 (defun org-table-insert-hline (&optional arg)
8659 "Insert a horizontal-line below the current line into the table.
8660 With prefix ARG, insert above the current line."
8661 (interactive "P")
8662 (if (not (org-at-table-p))
8663 (error "Not at a table"))
8664 (let ((line
8665 (org-expand-wide-chars
8666 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8667 (col (current-column))
8668 start)
8669 (if (string-match "^[ \t]*|-" line)
8670 (setq line
8671 (mapcar (lambda (x) (if (member x '(?| ?+))
8672 (prog1 (if start ?+ ?|) (setq start t))
8673 (if start ?- ?\ )))
8674 line))
8675 (setq line
8676 (mapcar (lambda (x) (if (equal x ?|)
8677 (prog1 (if start ?+ ?|) (setq start t))
8678 (if start ?- ?\ )))
8679 line)))
8680 (beginning-of-line (if arg 1 2))
8681 (apply 'insert line)
8682 (if (equal (char-before (point)) ?+)
8683 (progn (backward-delete-char 1) (insert "|")))
8684 (insert "\n")
8685 (beginning-of-line (if arg 1 -1))
8686 (move-to-column col)))
8687
8688 (defun org-expand-wide-chars (s)
8689 "Expand wide characters to spaces."
8690 (let (w a)
8691 (mapconcat
8692 (lambda (x)
8693 (if (> (setq w (string-width (setq a (char-to-string x)))) 1)
8694 (make-string w ?\ )
8695 a))
8696 s "")))
8697
8698 (defun org-table-kill-row ()
8699 "Delete the current row or horizontal line from the table."
8700 (interactive)
8701 (if (not (org-at-table-p))
8702 (error "Not at a table"))
8703 (let ((col (current-column)))
8704 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8705 (if (not (org-at-table-p)) (beginning-of-line 0))
8706 (move-to-column col)))
8707
8708 (defun org-table-sort-lines (beg end numericp)
8709 "Sort table lines in region.
8710 Point and mark define the first and last line to include. Both point and
8711 mark should be in the column that is used for sorting. For example, to
8712 sort according to column 3, put the mark in the first line to sort, in
8713 table column 3. Put point into the last line to be included in the sorting,
8714 also in table column 3. The command will prompt for the sorting method
8715 \(n for numerical, a for alphanumeric)."
8716 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8717 (setq numericp (string-match "[nN]" numericp))
8718 (org-table-align) ;; Just to be safe
8719 (let* (bcol ecol cmp column lns)
8720 (goto-char beg)
8721 (org-table-check-inside-data-field)
8722 (setq column (org-table-current-column)
8723 beg (move-marker (make-marker) (point-at-bol)))
8724 (goto-char end)
8725 (org-table-check-inside-data-field)
8726 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8727 (untabify beg end)
8728 (goto-char beg)
8729 (org-table-goto-column column)
8730 (skip-chars-backward "^|")
8731 (setq bcol (current-column))
8732 (org-table-goto-column (1+ column))
8733 (skip-chars-backward "^|")
8734 (setq ecol (1- (current-column)))
8735 (setq cmp (if numericp
8736 (lambda (a b) (< (car a) (car b)))
8737 (lambda (a b) (string< (car a) (car b)))))
8738 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8739 (split-string (buffer-substring beg end) "\n")))
8740 (if numericp
8741 (setq lns (mapcar (lambda(x)
8742 (cons (string-to-number (car x)) (cdr x)))
8743 lns)))
8744 (delete-region beg end)
8745 (move-marker beg nil)
8746 (move-marker end nil)
8747 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8748 (message "%d lines sorted %s based on column %d"
8749 (length lns)
8750 (if numericp "numerically" "alphabetically") column)))
8751
8752 (defun org-table-cut-region (beg end)
8753 "Copy region in table to the clipboard and blank all relevant fields."
8754 (interactive "r")
8755 (org-table-copy-region beg end 'cut))
8756
8757 (defun org-table-copy-region (beg end &optional cut)
8758 "Copy rectangular region in table to clipboard.
8759 A special clipboard is used which can only be accessed
8760 with `org-table-paste-rectangle'."
8761 (interactive "rP")
8762 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8763 region cols
8764 (rpl (if cut " " nil)))
8765 (goto-char beg)
8766 (org-table-check-inside-data-field)
8767 (setq l01 (count-lines (point-min) (point))
8768 c01 (org-table-current-column))
8769 (goto-char end)
8770 (org-table-check-inside-data-field)
8771 (setq l02 (count-lines (point-min) (point))
8772 c02 (org-table-current-column))
8773 (setq l1 (min l01 l02) l2 (max l01 l02)
8774 c1 (min c01 c02) c2 (max c01 c02))
8775 (catch 'exit
8776 (while t
8777 (catch 'nextline
8778 (if (> l1 l2) (throw 'exit t))
8779 (goto-line l1)
8780 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8781 (setq cols nil ic1 c1 ic2 c2)
8782 (while (< ic1 (1+ ic2))
8783 (push (org-table-get-field ic1 rpl) cols)
8784 (setq ic1 (1+ ic1)))
8785 (push (nreverse cols) region)
8786 (setq l1 (1+ l1)))))
8787 (setq org-table-clip (nreverse region))
8788 (if cut (org-table-align))
8789 org-table-clip))
8790
8791 (defun org-table-paste-rectangle ()
8792 "Paste a rectangular region into a table.
8793 The upper right corner ends up in the current field. All involved fields
8794 will be overwritten. If the rectangle does not fit into the present table,
8795 the table is enlarged as needed. The process ignores horizontal separator
8796 lines."
8797 (interactive)
8798 (unless (and org-table-clip (listp org-table-clip))
8799 (error "First cut/copy a region to paste!"))
8800 (org-table-check-inside-data-field)
8801 (let* ((clip org-table-clip)
8802 (line (count-lines (point-min) (point)))
8803 (col (org-table-current-column))
8804 (org-enable-table-editor t)
8805 (org-table-automatic-realign nil)
8806 c cols field)
8807 (while (setq cols (pop clip))
8808 (while (org-at-table-hline-p) (beginning-of-line 2))
8809 (if (not (org-at-table-p))
8810 (progn (end-of-line 0) (org-table-next-field)))
8811 (setq c col)
8812 (while (setq field (pop cols))
8813 (org-table-goto-column c nil 'force)
8814 (org-table-get-field nil field)
8815 (setq c (1+ c)))
8816 (beginning-of-line 2))
8817 (goto-line line)
8818 (org-table-goto-column col)
8819 (org-table-align)))
8820
8821 (defun org-table-convert ()
8822 "Convert from `org-mode' table to table.el and back.
8823 Obviously, this only works within limits. When an Org-mode table is
8824 converted to table.el, all horizontal separator lines get lost, because
8825 table.el uses these as cell boundaries and has no notion of horizontal lines.
8826 A table.el table can be converted to an Org-mode table only if it does not
8827 do row or column spanning. Multiline cells will become multiple cells.
8828 Beware, Org-mode does not test if the table can be successfully converted - it
8829 blindly applies a recipe that works for simple tables."
8830 (interactive)
8831 (require 'table)
8832 (if (org-at-table.el-p)
8833 ;; convert to Org-mode table
8834 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8835 (end (move-marker (make-marker) (org-table-end t))))
8836 (table-unrecognize-region beg end)
8837 (goto-char beg)
8838 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8839 (replace-match ""))
8840 (goto-char beg))
8841 (if (org-at-table-p)
8842 ;; convert to table.el table
8843 (let ((beg (move-marker (make-marker) (org-table-begin)))
8844 (end (move-marker (make-marker) (org-table-end))))
8845 ;; first, get rid of all horizontal lines
8846 (goto-char beg)
8847 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8848 (replace-match ""))
8849 ;; insert a hline before first
8850 (goto-char beg)
8851 (org-table-insert-hline 'above)
8852 (beginning-of-line -1)
8853 ;; insert a hline after each line
8854 (while (progn (beginning-of-line 3) (< (point) end))
8855 (org-table-insert-hline))
8856 (goto-char beg)
8857 (setq end (move-marker end (org-table-end)))
8858 ;; replace "+" at beginning and ending of hlines
8859 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8860 (replace-match "\\1+-"))
8861 (goto-char beg)
8862 (while (re-search-forward "-|[ \t]*$" end t)
8863 (replace-match "-+"))
8864 (goto-char beg)))))
8865
8866 (defun org-table-wrap-region (arg)
8867 "Wrap several fields in a column like a paragraph.
8868 This is useful if you'd like to spread the contents of a field over several
8869 lines, in order to keep the table compact.
8870
8871 If there is an active region, and both point and mark are in the same column,
8872 the text in the column is wrapped to minimum width for the given number of
8873 lines. Generally, this makes the table more compact. A prefix ARG may be
8874 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8875 formats the selected text to two lines. If the region was longer than two
8876 lines, the remaining lines remain empty. A negative prefix argument reduces
8877 the current number of lines by that amount. The wrapped text is pasted back
8878 into the table. If you formatted it to more lines than it was before, fields
8879 further down in the table get overwritten - so you might need to make space in
8880 the table first.
8881
8882 If there is no region, the current field is split at the cursor position and
8883 the text fragment to the right of the cursor is prepended to the field one
8884 line down.
8885
8886 If there is no region, but you specify a prefix ARG, the current field gets
8887 blank, and the content is appended to the field above."
8888 (interactive "P")
8889 (org-table-check-inside-data-field)
8890 (if (org-region-active-p)
8891 ;; There is a region: fill as a paragraph
8892 (let ((beg (region-beginning))
8893 nlines)
8894 (org-table-cut-region (region-beginning) (region-end))
8895 (if (> (length (car org-table-clip)) 1)
8896 (error "Region must be limited to single column"))
8897 (setq nlines (if arg
8898 (if (< arg 1)
8899 (+ (length org-table-clip) arg)
8900 arg)
8901 (length org-table-clip)))
8902 (setq org-table-clip
8903 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8904 nil nlines)))
8905 (goto-char beg)
8906 (org-table-paste-rectangle))
8907 ;; No region, split the current field at point
8908 (if arg
8909 ;; combine with field above
8910 (let ((s (org-table-blank-field))
8911 (col (org-table-current-column)))
8912 (beginning-of-line 0)
8913 (while (org-at-table-hline-p) (beginning-of-line 0))
8914 (org-table-goto-column col)
8915 (skip-chars-forward "^|")
8916 (skip-chars-backward " ")
8917 (insert " " (org-trim s))
8918 (org-table-align))
8919 ;; split field
8920 (when (looking-at "\\([^|]+\\)+|")
8921 (let ((s (match-string 1)))
8922 (replace-match " |")
8923 (goto-char (match-beginning 0))
8924 (org-table-next-row)
8925 (insert (org-trim s) " ")
8926 (org-table-align))))))
8927
8928 (defun org-trim (s)
8929 "Remove whitespace at beginning and end of string."
8930 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8931 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8932 s)
8933
8934 (defun org-wrap (string &optional width lines)
8935 "Wrap string to either a number of lines, or a width in characters.
8936 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8937 that costs. If there is a word longer than WIDTH, the text is actually
8938 wrapped to the length of that word.
8939 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8940 many lines, whatever width that takes.
8941 The return value is a list of lines, without newlines at the end."
8942 (let* ((words (org-split-string string "[ \t\n]+"))
8943 (maxword (apply 'max (mapcar 'string-width words)))
8944 w ll)
8945 (cond (width
8946 (org-do-wrap words (max maxword width)))
8947 (lines
8948 (setq w maxword)
8949 (setq ll (org-do-wrap words maxword))
8950 (if (<= (length ll) lines)
8951 ll
8952 (setq ll words)
8953 (while (> (length ll) lines)
8954 (setq w (1+ w))
8955 (setq ll (org-do-wrap words w)))
8956 ll))
8957 (t (error "Cannot wrap this")))))
8958
8959
8960 (defun org-do-wrap (words width)
8961 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8962 (let (lines line)
8963 (while words
8964 (setq line (pop words))
8965 (while (and words (< (+ (length line) (length (car words))) width))
8966 (setq line (concat line " " (pop words))))
8967 (setq lines (push line lines)))
8968 (nreverse lines)))
8969
8970 ;; FIXME: I think I can make this more efficient
8971 (defun org-split-string (string &optional separators)
8972 "Splits STRING into substrings at SEPARATORS.
8973 No empty strings are returned if there are matches at the beginning
8974 and end of string."
8975 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8976 (start 0)
8977 notfirst
8978 (list nil))
8979 (while (and (string-match rexp string
8980 (if (and notfirst
8981 (= start (match-beginning 0))
8982 (< start (length string)))
8983 (1+ start) start))
8984 (< (match-beginning 0) (length string)))
8985 (setq notfirst t)
8986 (or (eq (match-beginning 0) 0)
8987 (and (eq (match-beginning 0) (match-end 0))
8988 (eq (match-beginning 0) start))
8989 (setq list
8990 (cons (substring string start (match-beginning 0))
8991 list)))
8992 (setq start (match-end 0)))
8993 (or (eq start (length string))
8994 (setq list
8995 (cons (substring string start)
8996 list)))
8997 (nreverse list)))
8998
8999 (defun org-table-add-invisible-to-vertical-lines ()
9000 "Add an `invisible' property to vertical lines of current table."
9001 (interactive)
9002 (let* ((beg (org-table-begin))
9003 (end (org-table-end))
9004 (end1))
9005 (save-excursion
9006 (goto-char beg)
9007 (while (< (point) end)
9008 (setq end1 (point-at-eol))
9009 (if (looking-at org-table-dataline-regexp)
9010 (while (re-search-forward "|" end1 t)
9011 (add-text-properties (1- (point)) (point)
9012 '(invisible org-table)))
9013 (while (re-search-forward "[+|]" end1 t)
9014 (add-text-properties (1- (point)) (point)
9015 '(invisible org-table))))
9016 (beginning-of-line 2)))))
9017
9018 (defun org-table-toggle-vline-visibility (&optional arg)
9019 "Toggle the visibility of table vertical lines.
9020 The effect is immediate and on all tables in the file.
9021 With prefix ARG, make lines invisible when ARG is positive, make lines
9022 visible when ARG is not positive."
9023 (interactive "P")
9024 (let ((action (cond
9025 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
9026 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
9027 (t (if (org-in-invisibility-spec-p '(org-table))
9028 'off
9029 'on)))))
9030 (if (eq action 'off)
9031 (progn
9032 (org-remove-from-invisibility-spec '(org-table))
9033 (org-table-map-tables 'org-table-align)
9034 (message "Vertical table lines visible")
9035 (if (org-at-table-p)
9036 (org-table-align)))
9037 (org-add-to-invisibility-spec '(org-table))
9038 (org-table-map-tables 'org-table-align)
9039 (message "Vertical table lines invisible"))
9040 (redraw-frame (selected-frame))))
9041
9042 (defun org-table-map-tables (function)
9043 "Apply FUNCTION to the start of all tables in the buffer."
9044 (save-excursion
9045 (save-restriction
9046 (widen)
9047 (goto-char (point-min))
9048 (while (re-search-forward org-table-any-line-regexp nil t)
9049 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9050 (beginning-of-line 1)
9051 (if (looking-at org-table-line-regexp)
9052 (save-excursion (funcall function)))
9053 (re-search-forward org-table-any-border-regexp nil 1)))))
9054
9055 (defun org-table-sum (&optional beg end nlast)
9056 "Sum numbers in region of current table column.
9057 The result will be displayed in the echo area, and will be available
9058 as kill to be inserted with \\[yank].
9059
9060 If there is an active region, it is interpreted as a rectangle and all
9061 numbers in that rectangle will be summed. If there is no active
9062 region and point is located in a table column, sum all numbers in that
9063 column.
9064
9065 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9066 numbers are assumed to be times as well (in decimal hours) and the
9067 numbers are added as such.
9068
9069 If NLAST is a number, only the NLAST fields will actually be summed."
9070 (interactive)
9071 (save-excursion
9072 (let (col (timecnt 0) diff h m s org-table-clip)
9073 (cond
9074 ((and beg end)) ; beg and end given explicitly
9075 ((org-region-active-p)
9076 (setq beg (region-beginning) end (region-end)))
9077 (t
9078 (setq col (org-table-current-column))
9079 (goto-char (org-table-begin))
9080 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9081 (error "No table data"))
9082 (org-table-goto-column col)
9083 ;not needed? (skip-chars-backward "^|")
9084 (setq beg (point))
9085 (goto-char (org-table-end))
9086 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9087 (error "No table data"))
9088 (org-table-goto-column col)
9089 ;not needed? (skip-chars-forward "^|")
9090 (setq end (point))))
9091 (let* ((items (apply 'append (org-table-copy-region beg end)))
9092 (items1 (cond ((not nlast) items)
9093 ((>= nlast (length items)) items)
9094 (t (setq items (reverse items))
9095 (setcdr (nthcdr (1- nlast) items) nil)
9096 (nreverse items))))
9097 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9098 items1)))
9099 (res (apply '+ numbers))
9100 (sres (if (= timecnt 0)
9101 (format "%g" res)
9102 (setq diff (* 3600 res)
9103 h (floor (/ diff 3600)) diff (mod diff 3600)
9104 m (floor (/ diff 60)) diff (mod diff 60)
9105 s diff)
9106 (format "%d:%02d:%02d" h m s))))
9107 (kill-new sres)
9108 (if (interactive-p)
9109 (message "%s"
9110 (substitute-command-keys
9111 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9112 (length numbers) sres))))
9113 sres))))
9114
9115 (defun org-table-get-number-for-summing (s)
9116 (let (n)
9117 (if (string-match "^ *|? *" s)
9118 (setq s (replace-match "" nil nil s)))
9119 (if (string-match " *|? *$" s)
9120 (setq s (replace-match "" nil nil s)))
9121 (setq n (string-to-number s))
9122 (cond
9123 ((and (string-match "0" s)
9124 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9125 ((string-match "\\`[ \t]+\\'" s) nil)
9126 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9127 (let ((h (string-to-number (or (match-string 1 s) "0")))
9128 (m (string-to-number (or (match-string 2 s) "0")))
9129 (s (string-to-number (or (match-string 4 s) "0"))))
9130 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9131 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9132 ((equal n 0) nil)
9133 (t n))))
9134
9135 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9136 "Get a calc vector from a column, accorting to descriptor DESC.
9137 Optional arguments TBEG and COL can give the beginning of the table and
9138 the current column, to avoid unnecessary parsing."
9139 (save-excursion
9140 (or tbeg (setq tbeg (org-table-begin)))
9141 (or col (setq col (org-table-current-column)))
9142 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9143 (cond
9144 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9145 (setq n1 (- (match-end 1) (match-beginning 1)))
9146 (if (match-beginning 3)
9147 (setq n2 (- (match-end 2) (match-beginning 3))))
9148 (setq n (if n2 (max n1 n2) n1))
9149 (setq n1 (if n2 (min n1 n2)))
9150 (setq nn n)
9151 (while (and (> nn 0)
9152 (re-search-backward org-table-hline-regexp tbeg t))
9153 (push (org-current-line) hline-list)
9154 (setq nn (1- nn)))
9155 (setq hline-list (nreverse hline-list))
9156 (goto-line (nth (1- n) hline-list))
9157 (when (re-search-forward org-table-dataline-regexp)
9158 (org-table-goto-column col)
9159 (setq beg (point)))
9160 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9161 (when (re-search-backward org-table-dataline-regexp)
9162 (org-table-goto-column col)
9163 (setq end (point)))
9164 (setq l (apply 'append (org-table-copy-region beg end)))
9165 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9166 (if (equal x "") "0" x))
9167 l ",") "]"))
9168 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9169 (setq n1 (string-to-number (match-string 1 desc))
9170 n2 (string-to-number (match-string 2 desc)))
9171 (beginning-of-line 1)
9172 (save-excursion
9173 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9174 (org-table-goto-column col)
9175 (setq beg (point))))
9176 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9177 (org-table-goto-column col)
9178 (setq end (point)))
9179 (setq l (apply 'append (org-table-copy-region beg end)))
9180 (concat "[" (mapconcat
9181 (lambda (x) (setq x (org-trim x))
9182 (if (equal x "") "0" x))
9183 l ",") "]"))
9184 ((string-match "\\([0-9]+\\)" desc)
9185 (beginning-of-line 1)
9186 (when (re-search-backward org-table-dataline-regexp tbeg t
9187 (string-to-number (match-string 0 desc)))
9188 (org-table-goto-column col)
9189 (org-trim (org-table-get-field))))))))
9190
9191 (defvar org-table-formula-history nil)
9192
9193 (defvar org-table-column-names nil
9194 "Alist with column names, derived from the `!' line.")
9195 (defvar org-table-column-name-regexp nil
9196 "Regular expression matching the current column names.")
9197 (defvar org-table-local-parameters nil
9198 "Alist with parameter names, derived from the `$' line.")
9199 (defvar org-table-named-field-locations nil
9200 "Alist with locations of named fields.")
9201
9202 (defun org-table-get-formula (&optional equation named)
9203 "Read a formula from the minibuffer, offer stored formula as default."
9204 (let* ((name (car (rassoc (list (org-current-line)
9205 (org-table-current-column))
9206 org-table-named-field-locations)))
9207 (scol (if named
9208 (if name name
9209 (error "Not in a named field"))
9210 (int-to-string (org-table-current-column))))
9211 (dummy (and name (not named)
9212 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9213 (error "Abort")))
9214 (org-table-may-need-update nil)
9215 (stored-list (org-table-get-stored-formulas))
9216 (stored (cdr (assoc scol stored-list)))
9217 (eq (cond
9218 ((and stored equation (string-match "^ *=? *$" equation))
9219 stored)
9220 ((stringp equation)
9221 equation)
9222 (t (read-string
9223 (format "%s formula $%s=" (if named "Field" "Column") scol)
9224 (or stored "") 'org-table-formula-history
9225 ;stored
9226 ))))
9227 mustsave)
9228 (when (not (string-match "\\S-" eq))
9229 ;; remove formula
9230 (setq stored-list (delq (assoc scol stored-list) stored-list))
9231 (org-table-store-formulas stored-list)
9232 (error "Formula removed"))
9233 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9234 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9235 (if (and name (not named))
9236 ;; We set the column equation, delete the named one.
9237 (setq stored-list (delq (assoc name stored-list) stored-list)
9238 mustsave t))
9239 (if stored
9240 (setcdr (assoc scol stored-list) eq)
9241 (setq stored-list (cons (cons scol eq) stored-list)))
9242 (if (or mustsave (not (equal stored eq)))
9243 (org-table-store-formulas stored-list))
9244 eq))
9245
9246 (defun org-table-store-formulas (alist)
9247 "Store the list of formulas below the current table."
9248 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9249 (save-excursion
9250 (goto-char (org-table-end))
9251 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9252 (delete-region (point) (match-end 0)))
9253 (insert "#+TBLFM: "
9254 (mapconcat (lambda (x)
9255 (concat "$" (car x) "=" (cdr x)))
9256 alist "::")
9257 "\n")))
9258
9259 (defun org-table-get-stored-formulas ()
9260 "Return an alist with the t=stored formulas directly after current table."
9261 (interactive)
9262 (let (scol eq eq-alist strings string seen)
9263 (save-excursion
9264 (goto-char (org-table-end))
9265 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9266 (setq strings (org-split-string (match-string 2) " *:: *"))
9267 (while (setq string (pop strings))
9268 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9269 (setq scol (match-string 1 string)
9270 eq (match-string 2 string)
9271 eq-alist (cons (cons scol eq) eq-alist))
9272 (if (member scol seen)
9273 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9274 (push scol seen))))))
9275 (nreverse eq-alist)))
9276
9277 (defun org-table-modify-formulas (action &rest columns)
9278 "Modify the formulas stored below the current table.
9279 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9280 expected, for the other actions only a single column number is needed."
9281 (let ((list (org-table-get-stored-formulas))
9282 (nmax (length (org-split-string
9283 (buffer-substring (point-at-bol) (point-at-eol))
9284 "|")))
9285 col col1 col2 scol si sc1 sc2)
9286 (cond
9287 ((null list)) ; No action needed if there are no stored formulas
9288 ((eq action 'remove)
9289 (setq col (car columns)
9290 scol (int-to-string col))
9291 (org-table-replace-in-formulas list scol "INVALID")
9292 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9293 (loop for i from (1+ col) upto nmax by 1 do
9294 (setq si (int-to-string i))
9295 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9296 (if (assoc si list) (setcar (assoc si list)
9297 (int-to-string (1- i))))))
9298 ((eq action 'insert)
9299 (setq col (car columns))
9300 (loop for i from nmax downto col by 1 do
9301 (setq si (int-to-string i))
9302 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9303 (if (assoc si list) (setcar (assoc si list)
9304 (int-to-string (1+ i))))))
9305 ((eq action 'swap)
9306 (setq col1 (car columns) col2 (nth 1 columns)
9307 sc1 (int-to-string col1) sc2 (int-to-string col2))
9308 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
9309 (org-table-replace-in-formulas list sc1 "ZqZ")
9310 (org-table-replace-in-formulas list sc2 sc1)
9311 (org-table-replace-in-formulas list "ZqZ" sc2)
9312 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
9313 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9314 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
9315 (t (error "Invalid action in `org-table-modify-formulas'")))
9316 (if list (org-table-store-formulas list))))
9317
9318 (defun org-table-replace-in-formulas (list s1 s2)
9319 (let (elt re s)
9320 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9321 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
9322 re (concat (regexp-quote s1) "\\>"))
9323 (while (setq elt (pop list))
9324 (setq s (cdr elt))
9325 (while (string-match re s)
9326 (setq s (replace-match s2 t t s)))
9327 (setcdr elt s))))
9328
9329 (defun org-table-get-specials ()
9330 "Get the column names and local parameters for this table."
9331 (save-excursion
9332 (let ((beg (org-table-begin)) (end (org-table-end))
9333 names name fields fields1 field cnt c v line col)
9334 (setq org-table-column-names nil
9335 org-table-local-parameters nil
9336 org-table-named-field-locations nil)
9337 (goto-char beg)
9338 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9339 (setq names (org-split-string (match-string 1) " *| *")
9340 cnt 1)
9341 (while (setq name (pop names))
9342 (setq cnt (1+ cnt))
9343 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9344 (push (cons name (int-to-string cnt)) org-table-column-names))))
9345 (setq org-table-column-names (nreverse org-table-column-names))
9346 (setq org-table-column-name-regexp
9347 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9348 (goto-char beg)
9349 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9350 (setq fields (org-split-string (match-string 1) " *| *"))
9351 (while (setq field (pop fields))
9352 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9353 (push (cons (match-string 1 field) (match-string 2 field))
9354 org-table-local-parameters))))
9355 (goto-char beg)
9356 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9357 (setq c (match-string 1)
9358 fields (org-split-string (match-string 2) " *| *"))
9359 (save-excursion
9360 (beginning-of-line (if (equal c "_") 2 0))
9361 (setq line (org-current-line) col 1)
9362 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9363 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9364 (while (and fields1 (setq field (pop fields)))
9365 (setq v (pop fields1) col (1+ col))
9366 (when (and (stringp field) (stringp v)
9367 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9368 (push (cons field v) org-table-local-parameters)
9369 (push (list field line col) org-table-named-field-locations)))))))
9370
9371 (defun org-this-word ()
9372 ;; Get the current word
9373 (save-excursion
9374 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
9375 (end (progn (skip-chars-forward "^ \t\n") (point))))
9376 (buffer-substring-no-properties beg end))))
9377
9378 (defun org-table-maybe-eval-formula ()
9379 "Check if the current field starts with \"=\" or \":=\".
9380 If yes, store the formula and apply it."
9381 ;; We already know we are in a table. Get field will only return a formula
9382 ;; when appropriate. It might return a separator line, but no problem.
9383 (when org-table-formula-evaluate-inline
9384 (let* ((field (org-trim (or (org-table-get-field) "")))
9385 named eq)
9386 (when (string-match "^:?=\\(.*\\)" field)
9387 (setq named (equal (string-to-char field) ?:)
9388 eq (match-string 1 field))
9389 (if (fboundp 'calc-eval)
9390 (org-table-eval-formula (if named '(4) nil) eq))))))
9391
9392 (defvar org-recalc-commands nil
9393 "List of commands triggering the recalculation of a line.
9394 Will be filled automatically during use.")
9395
9396 (defvar org-recalc-marks
9397 '((" " . "Unmarked: no special line, no automatic recalculation")
9398 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9399 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9400 ("!" . "Column name definition line. Reference in formula as $name.")
9401 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9402 ("_" . "Names for values in row below this one.")
9403 ("^" . "Names for values in row above this one.")))
9404
9405 (defun org-table-rotate-recalc-marks (&optional newchar)
9406 "Rotate the recalculation mark in the first column.
9407 If in any row, the first field is not consistent with a mark,
9408 insert a new column for the markers.
9409 When there is an active region, change all the lines in the region,
9410 after prompting for the marking character.
9411 After each change, a message will be displayed indicating the meaning
9412 of the new mark."
9413 (interactive)
9414 (unless (org-at-table-p) (error "Not at a table"))
9415 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9416 (beg (org-table-begin))
9417 (end (org-table-end))
9418 (l (org-current-line))
9419 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9420 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9421 (have-col
9422 (save-excursion
9423 (goto-char beg)
9424 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9425 (col (org-table-current-column))
9426 (forcenew (car (assoc newchar org-recalc-marks)))
9427 epos new)
9428 (when l1
9429 (message "Change region to what mark? Type # * ! $ or SPC: ")
9430 (setq newchar (char-to-string (read-char-exclusive))
9431 forcenew (car (assoc newchar org-recalc-marks))))
9432 (if (and newchar (not forcenew))
9433 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9434 newchar))
9435 (if l1 (goto-line l1))
9436 (save-excursion
9437 (beginning-of-line 1)
9438 (unless (looking-at org-table-dataline-regexp)
9439 (error "Not at a table data line")))
9440 (unless have-col
9441 (org-table-goto-column 1)
9442 (org-table-insert-column)
9443 (org-table-goto-column (1+ col)))
9444 (setq epos (point-at-eol))
9445 (save-excursion
9446 (beginning-of-line 1)
9447 (org-table-get-field
9448 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9449 (concat " "
9450 (setq new (or forcenew
9451 (cadr (member (match-string 1) marks))))
9452 " ")
9453 " # ")))
9454 (if (and l1 l2)
9455 (progn
9456 (goto-line l1)
9457 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9458 (and (looking-at org-table-dataline-regexp)
9459 (org-table-get-field 1 (concat " " new " "))))
9460 (goto-line l1)))
9461 (if (not (= epos (point-at-eol))) (org-table-align))
9462 (goto-line l)
9463 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9464
9465 (defun org-table-maybe-recalculate-line ()
9466 "Recompute the current line if marked for it, and if we haven't just done it."
9467 (interactive)
9468 (and org-table-allow-automatic-line-recalculation
9469 (not (and (memq last-command org-recalc-commands)
9470 (equal org-last-recalc-line (org-current-line))))
9471 (save-excursion (beginning-of-line 1)
9472 (looking-at org-table-auto-recalculate-regexp))
9473 (fboundp 'calc-eval)
9474 (org-table-recalculate) t))
9475
9476 (defvar org-table-formula-debug nil
9477 "Non-nil means, debug table formulas.
9478 When nil, simply write \"#ERROR\" in corrupted fields.")
9479
9480 (defvar modes)
9481 (defsubst org-set-calc-mode (var &optional value)
9482 (if (stringp var)
9483 (setq var (assoc var '(("D" calc-angle-mode deg)
9484 ("R" calc-angle-mode rad)
9485 ("F" calc-prefer-frac t)
9486 ("S" calc-symbolic-mode t)))
9487 value (nth 2 var) var (nth 1 var)))
9488 (if (memq var modes)
9489 (setcar (cdr (memq var modes)) value)
9490 (cons var (cons value modes)))
9491 modes)
9492
9493 (defun org-table-eval-formula (&optional arg equation
9494 suppress-align suppress-const
9495 suppress-store)
9496 "Replace the table field value at the cursor by the result of a calculation.
9497
9498 This function makes use of Dave Gillespie's Calc package, in my view the
9499 most exciting program ever written for GNU Emacs. So you need to have Calc
9500 installed in order to use this function.
9501
9502 In a table, this command replaces the value in the current field with the
9503 result of a formula. It also installs the formula as the \"current\" column
9504 formula, by storing it in a special line below the table. When called
9505 with a `C-u' prefix, the current field must ba a named field, and the
9506 formula is installed as valid in only this specific field.
9507
9508 When called, the command first prompts for a formula, which is read in
9509 the minibuffer. Previously entered formulas are available through the
9510 history list, and the last used formula is offered as a default.
9511 These stored formulas are adapted correctly when moving, inserting, or
9512 deleting columns with the corresponding commands.
9513
9514 The formula can be any algebraic expression understood by the Calc package.
9515 For details, see the Org-mode manual.
9516
9517 This function can also be called from Lisp programs and offers
9518 additional arguments: EQUATION can be the formula to apply. If this
9519 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9520 used to speed-up recursive calls by by-passing unnecessary aligns.
9521 SUPPRESS-CONST suppresses the interpretation of constants in the
9522 formula, assuming that this has been done already outside the function.
9523 SUPPRESS-STORE means the formula should not be stored, either because
9524 it is already stored, or because it is a modified equation that should
9525 not overwrite the stored one."
9526 (interactive "P")
9527 (require 'calc)
9528 (org-table-check-inside-data-field)
9529 (org-table-get-specials)
9530 (let* (fields
9531 (ndown (if (integerp arg) arg 1))
9532 (org-table-automatic-realign nil)
9533 (case-fold-search nil)
9534 (down (> ndown 1))
9535 (formula (if (and equation suppress-store)
9536 equation
9537 (org-table-get-formula equation (equal arg '(4)))))
9538 (n0 (org-table-current-column))
9539 (modes (copy-sequence org-calc-default-modes))
9540 n form fmt x ev orig c)
9541 ;; Parse the format string. Since we have a lot of modes, this is
9542 ;; a lot of work. However, I think calc still uses most of the time.
9543 (if (string-match ";" formula)
9544 (let ((tmp (org-split-string formula ";")))
9545 (setq formula (car tmp)
9546 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9547 (nth 1 tmp)))
9548 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9549 (setq c (string-to-char (match-string 1 fmt))
9550 n (string-to-number (or (match-string 1 fmt) "")))
9551 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9552 (setq modes (org-set-calc-mode
9553 'calc-float-format
9554 (list (cdr (assoc c '((?n . float) (?f . fix)
9555 (?s . sci) (?e . eng))))
9556 n))))
9557 (setq fmt (replace-match "" t t fmt)))
9558 (while (string-match "[DRFS]" fmt)
9559 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9560 (setq fmt (replace-match "" t t fmt)))
9561 (unless (string-match "\\S-" fmt)
9562 (setq fmt nil))))
9563 (if (and (not suppress-const) org-table-formula-use-constants)
9564 (setq formula (org-table-formula-substitute-names formula)))
9565 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9566 (while (> ndown 0)
9567 (setq fields (org-split-string
9568 (buffer-substring
9569 (point-at-bol) (point-at-eol)) " *| *"))
9570 (if org-table-formula-numbers-only
9571 (setq fields (mapcar
9572 (lambda (x) (number-to-string (string-to-number x)))
9573 fields)))
9574 (setq ndown (1- ndown))
9575 (setq form (copy-sequence formula))
9576 ;; Insert the references to fields in same row
9577 (while (string-match "\\$\\([0-9]+\\)?" form)
9578 (setq n (if (match-beginning 1)
9579 (string-to-number (match-string 1 form))
9580 n0)
9581 x (nth (1- n) fields))
9582 (unless x (error "Invalid field specifier \"%s\""
9583 (match-string 0 form)))
9584 (if (equal x "") (setq x "0"))
9585 (setq form (replace-match (concat "(" x ")") t t form)))
9586 ;; Insert ranges in current column
9587 (while (string-match "\\&[-I0-9]+" form)
9588 (setq form (replace-match
9589 (save-match-data
9590 (org-table-get-vertical-vector (match-string 0 form)
9591 nil n0))
9592 t t form)))
9593 (setq ev (calc-eval (cons form modes)
9594 (if org-table-formula-numbers-only 'num)))
9595
9596 (when org-table-formula-debug
9597 (with-output-to-temp-buffer "*Help*"
9598 (princ (format "Substitution history of formula
9599 Orig: %s
9600 $xyz-> %s
9601 $1-> %s\n" orig formula form))
9602 (if (listp ev)
9603 (princ (format " %s^\nError: %s"
9604 (make-string (car ev) ?\-) (nth 1 ev)))
9605 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9606 ev (or fmt "NONE")
9607 (if fmt (format fmt (string-to-number ev)) ev)))))
9608 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9609 (unless (and (interactive-p) (not ndown))
9610 (unless (let (inhibit-redisplay)
9611 (y-or-n-p "Debugging Formula. Continue to next? "))
9612 (org-table-align)
9613 (error "Abort"))
9614 (delete-window (get-buffer-window "*Help*"))
9615 (message "")))
9616 (if (listp ev) (setq fmt nil ev "#ERROR"))
9617 (org-table-justify-field-maybe
9618 (if fmt (format fmt (string-to-number ev)) ev))
9619 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9620 (call-interactively 'org-return)
9621 (setq ndown 0)))
9622 (and down (org-table-maybe-recalculate-line))
9623 (or suppress-align (and org-table-may-need-update
9624 (org-table-align)))))
9625
9626 (defun org-table-recalculate (&optional all noalign)
9627 "Recalculate the current table line by applying all stored formulas."
9628 (interactive "P")
9629 (or (memq this-command org-recalc-commands)
9630 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9631 (unless (org-at-table-p) (error "Not at a table"))
9632 (org-table-get-specials)
9633 (let* ((eqlist (sort (org-table-get-stored-formulas)
9634 (lambda (a b) (string< (car a) (car b)))))
9635 (inhibit-redisplay t)
9636 (line-re org-table-dataline-regexp)
9637 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9638 (thiscol (org-table-current-column))
9639 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9640 ;; Insert constants in all formulas
9641 (setq eqlist
9642 (mapcar (lambda (x)
9643 (setcdr x (org-table-formula-substitute-names (cdr x)))
9644 x)
9645 eqlist))
9646 ;; Split the equation list
9647 (while (setq eq (pop eqlist))
9648 (if (<= (string-to-char (car eq)) ?9)
9649 (push eq eqlnum)
9650 (push eq eqlname)))
9651 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9652 (if all
9653 (progn
9654 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9655 (goto-char (setq beg (org-table-begin)))
9656 (if (re-search-forward org-table-calculate-mark-regexp end t)
9657 ;; This is a table with marked lines, only compute selected lines
9658 (setq line-re org-table-recalculate-regexp)
9659 ;; Move forward to the first non-header line
9660 (if (and (re-search-forward org-table-dataline-regexp end t)
9661 (re-search-forward org-table-hline-regexp end t)
9662 (re-search-forward org-table-dataline-regexp end t))
9663 (setq beg (match-beginning 0))
9664 nil))) ;; just leave beg where it is
9665 (setq beg (point-at-bol)
9666 end (move-marker (make-marker) (1+ (point-at-eol)))))
9667 (goto-char beg)
9668 (and all (message "Re-applying formulas to full table..."))
9669 (while (re-search-forward line-re end t)
9670 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9671 ;; Unprotected line, recalculate
9672 (and all (message "Re-applying formulas to full table...(line %d)"
9673 (setq cnt (1+ cnt))))
9674 (setq org-last-recalc-line (org-current-line))
9675 (setq eql eqlnum)
9676 (while (setq entry (pop eql))
9677 (goto-line org-last-recalc-line)
9678 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9679 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9680 (goto-line thisline)
9681 (org-table-goto-column thiscol)
9682 (or noalign (and org-table-may-need-update (org-table-align))
9683 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9684 ;; Now do the names fields
9685 (while (setq eq (pop eqlname))
9686 (setq name (car eq)
9687 a (assoc name org-table-named-field-locations))
9688 (when a
9689 (message "Re-applying formula to named field: %s" name)
9690 (goto-line (nth 1 a))
9691 (org-table-goto-column (nth 2 a))
9692 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9693 ;; back to initial position
9694 (goto-line thisline)
9695 (org-table-goto-column thiscol)
9696 (or noalign (and org-table-may-need-update (org-table-align))
9697 (and all (message "Re-applying formulas...done")))))
9698
9699 (defun org-table-formula-substitute-names (f)
9700 "Replace $const with values in string F."
9701 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9702 ;; First, check for column names
9703 (while (setq start (string-match org-table-column-name-regexp f start))
9704 (setq start (1+ start))
9705 (setq a (assoc (match-string 1 f) org-table-column-names))
9706 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9707 ;; Expand ranges to vectors
9708 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9709 (setq n1 (string-to-number (match-string 1 f))
9710 n2 (string-to-number (match-string 2 f))
9711 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9712 s (concat "[($" (number-to-string (1- nn1)) ")"))
9713 (loop for i from nn1 upto nn2 do
9714 (setq s (concat s ",($" (int-to-string i) ")")))
9715 (setq s (concat s "]"))
9716 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9717 (setq f (replace-match s t t f)))
9718 ;; Parameters and constants
9719 (setq start 0)
9720 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9721 (setq start (1+ start))
9722 (if (setq a (save-match-data
9723 (org-table-get-constant (match-string 1 f))))
9724 (setq f (replace-match (concat "(" a ")") t t f))))
9725 (if org-table-formula-debug
9726 (put-text-property 0 (length f) :orig-formula f1 f))
9727 f))
9728
9729 (defun org-table-get-constant (const)
9730 "Find the value for a parameter or constant in a formula.
9731 Parameters get priority."
9732 (or (cdr (assoc const org-table-local-parameters))
9733 (cdr (assoc const org-table-formula-constants))
9734 (and (fboundp 'constants-get) (constants-get const))
9735 "#UNDEFINED_NAME"))
9736
9737 (defvar org-edit-formulas-map (make-sparse-keymap))
9738 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9739 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9740 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9741
9742 (defvar org-pos)
9743 (defvar org-window-configuration)
9744
9745 (defun org-table-edit-formulas ()
9746 "Edit the formulas of the current table in a separate buffer."
9747 (interactive)
9748 (unless (org-at-table-p)
9749 (error "Not at a table"))
9750 (org-table-get-specials)
9751 (let ((eql (org-table-get-stored-formulas))
9752 (pos (move-marker (make-marker) (point)))
9753 (wc (current-window-configuration))
9754 entry loc s)
9755 (switch-to-buffer-other-window "*Edit Formulas*")
9756 (erase-buffer)
9757 (fundamental-mode)
9758 (set (make-local-variable 'org-pos) pos)
9759 (set (make-local-variable 'org-window-configuration) wc)
9760 (use-local-map org-edit-formulas-map)
9761 (setq s "# Edit formulas and finish with `C-c C-c'.
9762 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9763 # Use `C-c ?' to get information about $name at point.
9764 # To cancel editing, press `C-c C-q'.\n")
9765 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9766 (insert s)
9767 (while (setq entry (pop eql))
9768 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9769 (setq s (format "# Named formula, referring to column %d in line %d\n"
9770 (nth 2 loc) (nth 1 loc)))
9771 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9772 (insert s))
9773 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9774 (remove-text-properties 0 (length s) '(face nil) s)
9775 (insert s))
9776 (goto-char (point-min))
9777 (message "Edit formulas and finish with `C-c C-c'.")))
9778
9779 (defun org-show-variable ()
9780 "Show the location/value of the $ expression at point."
9781 (interactive)
9782 (let (var (pos org-pos) (win (selected-window)) e)
9783 (save-excursion
9784 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9785 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9786 (setq var (match-string 1))
9787 (error "No variable at point")))
9788 (cond
9789 ((setq e (assoc var org-table-named-field-locations))
9790 (switch-to-buffer-other-window (marker-buffer pos))
9791 (goto-line (nth 1 e))
9792 (org-table-goto-column (nth 2 e))
9793 (select-window win)
9794 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9795 ((setq e (assoc var org-table-column-names))
9796 (switch-to-buffer-other-window (marker-buffer pos))
9797 (goto-char pos)
9798 (goto-char (org-table-begin))
9799 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9800 (org-table-end) t)
9801 (progn
9802 (goto-char (match-beginning 1))
9803 (message "Named column (column %s)" (cdr e)))
9804 (error "Column name not found"))
9805 (select-window win))
9806 ((string-match "^[0-9]$" var)
9807 ;; column number
9808 (switch-to-buffer-other-window (marker-buffer pos))
9809 (goto-char pos)
9810 (goto-char (org-table-begin))
9811 (recenter 1)
9812 (if (re-search-forward org-table-dataline-regexp
9813 (org-table-end) t)
9814 (progn
9815 (goto-char (match-beginning 0))
9816 (org-table-goto-column (string-to-number var))
9817 (message "Column %s" var))
9818 (error "Column name not found"))
9819 (select-window win))
9820 ((setq e (assoc var org-table-local-parameters))
9821 (switch-to-buffer-other-window (marker-buffer pos))
9822 (goto-char pos)
9823 (goto-char (org-table-begin))
9824 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9825 (progn
9826 (goto-char (match-beginning 1))
9827 (message "Local parameter."))
9828 (error "Parameter not found"))
9829 (select-window win))
9830 (t
9831 (cond
9832 ((setq e (assoc var org-table-formula-constants))
9833 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9834 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9835 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9836 (t (error "Undefined name $%s" var)))))))
9837
9838 (defun org-finish-edit-formulas (&optional arg)
9839 "Parse the buffer for formula definitions and install them.
9840 With prefix ARG, apply the new formulas to the table."
9841 (interactive "P")
9842 (let ((pos org-pos) eql)
9843 (goto-char (point-min))
9844 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9845 (push (cons (match-string 1) (match-string 2)) eql))
9846 (set-window-configuration org-window-configuration)
9847 (select-window (get-buffer-window (marker-buffer pos)))
9848 (goto-char pos)
9849 (unless (org-at-table-p)
9850 (error "Lost table position - cannot install formulae"))
9851 (org-table-store-formulas eql)
9852 (move-marker pos nil)
9853 (kill-buffer "*Edit Formulas*")
9854 (if arg
9855 (org-table-recalculate 'all)
9856 (message "New formulas installed - press C-u C-c C-c to apply."))))
9857
9858 (defun org-abort-edit-formulas ()
9859 "Abort editing formulas, without installing the changes."
9860 (interactive)
9861 (let ((pos org-pos))
9862 (set-window-configuration org-window-configuration)
9863 (select-window (get-buffer-window (marker-buffer pos)))
9864 (goto-char pos)
9865 (message "Formula editing aborted without installing changes")))
9866
9867 ;;; The orgtbl minor mode
9868
9869 ;; Define a minor mode which can be used in other modes in order to
9870 ;; integrate the org-mode table editor.
9871
9872 ;; This is really a hack, because the org-mode table editor uses several
9873 ;; keys which normally belong to the major mode, for example the TAB and
9874 ;; RET keys. Here is how it works: The minor mode defines all the keys
9875 ;; necessary to operate the table editor, but wraps the commands into a
9876 ;; function which tests if the cursor is currently inside a table. If that
9877 ;; is the case, the table editor command is executed. However, when any of
9878 ;; those keys is used outside a table, the function uses `key-binding' to
9879 ;; look up if the key has an associated command in another currently active
9880 ;; keymap (minor modes, major mode, global), and executes that command.
9881 ;; There might be problems if any of the keys used by the table editor is
9882 ;; otherwise used as a prefix key.
9883
9884 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9885 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9886 ;; addresses this by checking explicitly for both bindings.
9887
9888 ;; The optimized version (see variable `orgtbl-optimized') takes over
9889 ;; all keys which are bound to `self-insert-command' in the *global map*.
9890 ;; Some modes bind other commands to simple characters, for example
9891 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9892 ;; active, this binding is ignored inside tables and replaced with a
9893 ;; modified self-insert.
9894
9895 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9896 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9897 In the optimized version, the table editor takes over all simple keys that
9898 normally just insert a character. In tables, the characters are inserted
9899 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9900 for empty fields). Outside tables, the correct binding of the keys is
9901 restored.
9902
9903 The default for this option is t if the optimized version is also used in
9904 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9905 this variable requires a restart of Emacs to become effective."
9906 :group 'org-table
9907 :type 'boolean)
9908
9909 (defvar orgtbl-mode nil
9910 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9911 table editor in arbitrary modes.")
9912 (make-variable-buffer-local 'orgtbl-mode)
9913
9914 (defvar orgtbl-mode-map (make-keymap)
9915 "Keymap for `orgtbl-mode'.")
9916
9917 ;;;###autoload
9918 (defun turn-on-orgtbl ()
9919 "Unconditionally turn on `orgtbl-mode'."
9920 (orgtbl-mode 1))
9921
9922 ;;;###autoload
9923 (defun orgtbl-mode (&optional arg)
9924 "The `org-mode' table editor as a minor mode for use in other modes."
9925 (interactive)
9926 (if (eq major-mode 'org-mode)
9927 ;; Exit without error, in case some hook functions calls this
9928 ;; by accident in org-mode.
9929 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9930 (setq orgtbl-mode
9931 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9932 (if orgtbl-mode
9933 (progn
9934 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9935 ;; Make sure we are first in minor-mode-map-alist
9936 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9937 (and c (setq minor-mode-map-alist
9938 (cons c (delq c minor-mode-map-alist)))))
9939 (set (make-local-variable (quote org-table-may-need-update)) t)
9940 (org-add-hook 'before-change-functions 'org-before-change-function
9941 nil 'local)
9942 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
9943 auto-fill-inhibit-regexp)
9944 (set (make-local-variable 'auto-fill-inhibit-regexp)
9945 (if auto-fill-inhibit-regexp
9946 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
9947 "[ \t]*|"))
9948 (easy-menu-add orgtbl-mode-menu)
9949 (run-hooks 'orgtbl-mode-hook))
9950 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9951 (remove-hook 'before-change-functions 'org-before-change-function t)
9952 (easy-menu-remove orgtbl-mode-menu)
9953 (force-mode-line-update 'all))))
9954
9955 ;; Install it as a minor mode.
9956 (put 'orgtbl-mode :included t)
9957 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9958 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9959
9960 (defun orgtbl-make-binding (fun n &rest keys)
9961 "Create a function for binding in the table minor mode.
9962 FUN is the command to call inside a table. N is used to create a unique
9963 command name. KEYS are keys that should be checked in for a command
9964 to execute outside of tables."
9965 (eval
9966 (list 'defun
9967 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9968 '(arg)
9969 (concat "In tables, run `" (symbol-name fun) "'.\n"
9970 "Outside of tables, run the binding of `"
9971 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9972 "'.")
9973 '(interactive "p")
9974 (list 'if
9975 '(org-at-table-p)
9976 (list 'call-interactively (list 'quote fun))
9977 (list 'let '(orgtbl-mode)
9978 (list 'call-interactively
9979 (append '(or)
9980 (mapcar (lambda (k)
9981 (list 'key-binding k))
9982 keys)
9983 '('orgtbl-error))))))))
9984
9985 (defun orgtbl-error ()
9986 "Error when there is no default binding for a table key."
9987 (interactive)
9988 (error "This key is has no function outside tables"))
9989
9990 (defun orgtbl-setup ()
9991 "Setup orgtbl keymaps."
9992 (let ((nfunc 0)
9993 (bindings
9994 (list
9995 '([(meta shift left)] org-table-delete-column)
9996 '([(meta left)] org-table-move-column-left)
9997 '([(meta right)] org-table-move-column-right)
9998 '([(meta shift right)] org-table-insert-column)
9999 '([(meta shift up)] org-table-kill-row)
10000 '([(meta shift down)] org-table-insert-row)
10001 '([(meta up)] org-table-move-row-up)
10002 '([(meta down)] org-table-move-row-down)
10003 '("\C-c\C-w" org-table-cut-region)
10004 '("\C-c\M-w" org-table-copy-region)
10005 '("\C-c\C-y" org-table-paste-rectangle)
10006 '("\C-c-" org-table-insert-hline)
10007 ; '([(shift tab)] org-table-previous-field)
10008 '("\C-m" org-table-next-row)
10009 (list (org-key 'S-return) 'org-table-copy-down)
10010 '([(meta return)] org-table-wrap-region)
10011 '("\C-c\C-q" org-table-wrap-region)
10012 '("\C-c?" org-table-current-column)
10013 '("\C-c " org-table-blank-field)
10014 '("\C-c+" org-table-sum)
10015 '("\C-c|" org-table-toggle-vline-visibility)
10016 '("\C-c=" org-table-eval-formula)
10017 '("\C-c'" org-table-edit-formulas)
10018 '("\C-c*" org-table-recalculate)
10019 '("\C-c^" org-table-sort-lines)
10020 '([(control ?#)] org-table-rotate-recalc-marks)))
10021 elt key fun cmd)
10022 (while (setq elt (pop bindings))
10023 (setq nfunc (1+ nfunc))
10024 (setq key (car elt)
10025 fun (nth 1 elt)
10026 cmd (orgtbl-make-binding fun nfunc key))
10027 (define-key orgtbl-mode-map key cmd))
10028 ;; Special treatment needed for TAB and RET
10029 (define-key orgtbl-mode-map [(return)]
10030 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10031 (define-key orgtbl-mode-map "\C-m"
10032 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10033 (define-key orgtbl-mode-map [(tab)]
10034 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10035 (define-key orgtbl-mode-map "\C-i"
10036 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10037 (define-key orgtbl-mode-map "\C-i"
10038 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10039 (define-key orgtbl-mode-map "\C-c\C-c"
10040 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10041 (when orgtbl-optimized
10042 ;; If the user wants maximum table support, we need to hijack
10043 ;; some standard editing functions
10044 (org-remap orgtbl-mode-map
10045 'self-insert-command 'orgtbl-self-insert-command
10046 'delete-char 'orgtbl-delete-char
10047 'delete-backward-char 'orgtbl-delete-backward-char)
10048 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10049 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10050 '("OrgTbl"
10051 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10052 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10053 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10054 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10055 "--"
10056 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10057 ["Copy Field from Above"
10058 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10059 "--"
10060 ("Column"
10061 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10062 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10063 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10064 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10065 ("Row"
10066 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10067 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10068 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10069 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10070 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10071 "--"
10072 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10073 ("Rectangle"
10074 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10075 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10076 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10077 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10078 "--"
10079 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10080 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10081 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10082 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10083 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10084 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10085 ["Sum Column/Rectangle" org-table-sum
10086 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10087 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10088 ["Debug Formulas"
10089 (setq org-table-formula-debug (not org-table-formula-debug))
10090 :style toggle :selected org-table-formula-debug]
10091 ))
10092 t)
10093
10094 (defun orgtbl-tab ()
10095 "Justification and field motion for `orgtbl-mode'."
10096 (interactive)
10097 (org-table-justify-field-maybe)
10098 (org-table-next-field))
10099
10100 (defun orgtbl-ret ()
10101 "Justification and field motion for `orgtbl-mode'."
10102 (interactive)
10103 (org-table-justify-field-maybe)
10104 (org-table-next-row))
10105
10106 (defun orgtbl-self-insert-command (N)
10107 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10108 If the cursor is in a table looking at whitespace, the whitespace is
10109 overwritten, and the table is not marked as requiring realignment."
10110 (interactive "p")
10111 (if (and (org-at-table-p)
10112 (or
10113 (and org-table-auto-blank-field
10114 (member last-command
10115 '(orgtbl-hijacker-command-100
10116 orgtbl-hijacker-command-101
10117 orgtbl-hijacker-command-102
10118 orgtbl-hijacker-command-103
10119 orgtbl-hijacker-command-104
10120 orgtbl-hijacker-command-105))
10121 (org-table-blank-field))
10122 t)
10123 (eq N 1)
10124 (looking-at "[^|\n]* +|"))
10125 (let (org-table-may-need-update)
10126 (goto-char (1- (match-end 0)))
10127 (delete-backward-char 1)
10128 (goto-char (match-beginning 0))
10129 (self-insert-command N))
10130 (setq org-table-may-need-update t)
10131 (let (orgtbl-mode)
10132 (call-interactively (key-binding (vector last-input-event))))))
10133
10134 (defun org-force-self-insert (N)
10135 "Needed to enforce self-insert under remapping."
10136 (interactive "p")
10137 (self-insert-command N))
10138
10139 (defun orgtbl-delete-backward-char (N)
10140 "Like `delete-backward-char', insert whitespace at field end in tables.
10141 When deleting backwards, in tables this function will insert whitespace in
10142 front of the next \"|\" separator, to keep the table aligned. The table will
10143 still be marked for re-alignment, because a narrow field may lead to a
10144 reduced column width."
10145 (interactive "p")
10146 (if (and (org-at-table-p)
10147 (eq N 1)
10148 (string-match "|" (buffer-substring (point-at-bol) (point)))
10149 (looking-at ".*?|"))
10150 (let ((pos (point)))
10151 (backward-delete-char N)
10152 (skip-chars-forward "^|")
10153 (insert " ")
10154 (goto-char (1- pos)))
10155 (delete-backward-char N)))
10156
10157 (defun orgtbl-delete-char (N)
10158 "Like `delete-char', but insert whitespace at field end in tables.
10159 When deleting characters, in tables this function will insert whitespace in
10160 front of the next \"|\" separator, to keep the table aligned. The table
10161 will still be marked for re-alignment, because a narrow field may lead to
10162 a reduced column width."
10163 (interactive "p")
10164 (if (and (org-at-table-p)
10165 (not (bolp))
10166 (not (= (char-after) ?|))
10167 (eq N 1))
10168 (if (looking-at ".*?|")
10169 (let ((pos (point)))
10170 (replace-match (concat
10171 (substring (match-string 0) 1 -1)
10172 " |"))
10173 (goto-char pos)))
10174 (delete-char N)))
10175
10176 ;;; Exporting
10177
10178 (defconst org-level-max 20)
10179
10180 (defun org-export-find-first-heading-line (list)
10181 "Remove all lines from LIST which are before the first headline."
10182 (let ((orig-list list)
10183 (re (concat "^" outline-regexp)))
10184 (while (and list
10185 (not (string-match re (car list))))
10186 (pop list))
10187 (or list orig-list)))
10188
10189 (defun org-skip-comments (lines)
10190 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10191 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10192 (re2 "^\\(\\*+\\)[ \t\n\r]")
10193 rtn line level)
10194 (while (setq line (pop lines))
10195 (cond
10196 ((and (string-match re1 line)
10197 (setq level (- (match-end 1) (match-beginning 1))))
10198 ;; Beginning of a COMMENT subtree. Skip it.
10199 (while (and (setq line (pop lines))
10200 (or (not (string-match re2 line))
10201 (> (- (match-end 1) (match-beginning 1)) level))))
10202 (setq lines (cons line lines)))
10203 ((string-match "^#" line)
10204 ;; an ordinary comment line
10205 )
10206 ((and org-export-table-remove-special-lines
10207 (string-match "^[ \t]*| *[!_^] *|" line))
10208 ;; a special table line that should be removed
10209 )
10210 (t (setq rtn (cons line rtn)))))
10211 (nreverse rtn)))
10212
10213 ;; ASCII
10214
10215 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10216 "Characters for underlining headings in ASCII export.")
10217
10218 (defconst org-html-entities
10219 '(("nbsp")
10220 ("iexcl")
10221 ("cent")
10222 ("pound")
10223 ("curren")
10224 ("yen")
10225 ("brvbar")
10226 ("sect")
10227 ("uml")
10228 ("copy")
10229 ("ordf")
10230 ("laquo")
10231 ("not")
10232 ("shy")
10233 ("reg")
10234 ("macr")
10235 ("deg")
10236 ("plusmn")
10237 ("sup2")
10238 ("sup3")
10239 ("acute")
10240 ("micro")
10241 ("para")
10242 ("middot")
10243 ("odot"."o")
10244 ("star"."*")
10245 ("cedil")
10246 ("sup1")
10247 ("ordm")
10248 ("raquo")
10249 ("frac14")
10250 ("frac12")
10251 ("frac34")
10252 ("iquest")
10253 ("Agrave")
10254 ("Aacute")
10255 ("Acirc")
10256 ("Atilde")
10257 ("Auml")
10258 ("Aring") ("AA"."&Aring;")
10259 ("AElig")
10260 ("Ccedil")
10261 ("Egrave")
10262 ("Eacute")
10263 ("Ecirc")
10264 ("Euml")
10265 ("Igrave")
10266 ("Iacute")
10267 ("Icirc")
10268 ("Iuml")
10269 ("ETH")
10270 ("Ntilde")
10271 ("Ograve")
10272 ("Oacute")
10273 ("Ocirc")
10274 ("Otilde")
10275 ("Ouml")
10276 ("times")
10277 ("Oslash")
10278 ("Ugrave")
10279 ("Uacute")
10280 ("Ucirc")
10281 ("Uuml")
10282 ("Yacute")
10283 ("THORN")
10284 ("szlig")
10285 ("agrave")
10286 ("aacute")
10287 ("acirc")
10288 ("atilde")
10289 ("auml")
10290 ("aring")
10291 ("aelig")
10292 ("ccedil")
10293 ("egrave")
10294 ("eacute")
10295 ("ecirc")
10296 ("euml")
10297 ("igrave")
10298 ("iacute")
10299 ("icirc")
10300 ("iuml")
10301 ("eth")
10302 ("ntilde")
10303 ("ograve")
10304 ("oacute")
10305 ("ocirc")
10306 ("otilde")
10307 ("ouml")
10308 ("divide")
10309 ("oslash")
10310 ("ugrave")
10311 ("uacute")
10312 ("ucirc")
10313 ("uuml")
10314 ("yacute")
10315 ("thorn")
10316 ("yuml")
10317 ("fnof")
10318 ("Alpha")
10319 ("Beta")
10320 ("Gamma")
10321 ("Delta")
10322 ("Epsilon")
10323 ("Zeta")
10324 ("Eta")
10325 ("Theta")
10326 ("Iota")
10327 ("Kappa")
10328 ("Lambda")
10329 ("Mu")
10330 ("Nu")
10331 ("Xi")
10332 ("Omicron")
10333 ("Pi")
10334 ("Rho")
10335 ("Sigma")
10336 ("Tau")
10337 ("Upsilon")
10338 ("Phi")
10339 ("Chi")
10340 ("Psi")
10341 ("Omega")
10342 ("alpha")
10343 ("beta")
10344 ("gamma")
10345 ("delta")
10346 ("epsilon")
10347 ("varepsilon"."&epsilon;")
10348 ("zeta")
10349 ("eta")
10350 ("theta")
10351 ("iota")
10352 ("kappa")
10353 ("lambda")
10354 ("mu")
10355 ("nu")
10356 ("xi")
10357 ("omicron")
10358 ("pi")
10359 ("rho")
10360 ("sigmaf") ("varsigma"."&sigmaf;")
10361 ("sigma")
10362 ("tau")
10363 ("upsilon")
10364 ("phi")
10365 ("chi")
10366 ("psi")
10367 ("omega")
10368 ("thetasym") ("vartheta"."&thetasym;")
10369 ("upsih")
10370 ("piv")
10371 ("bull") ("bullet"."&bull;")
10372 ("hellip") ("dots"."&hellip;")
10373 ("prime")
10374 ("Prime")
10375 ("oline")
10376 ("frasl")
10377 ("weierp")
10378 ("image")
10379 ("real")
10380 ("trade")
10381 ("alefsym")
10382 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
10383 ("uarr") ("uparrow"."&uarr;")
10384 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
10385 ("darr")("downarrow"."&darr;")
10386 ("harr") ("leftrightarrow"."&harr;")
10387 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
10388 ("lArr") ("Leftarrow"."&lArr;")
10389 ("uArr") ("Uparrow"."&uArr;")
10390 ("rArr") ("Rightarrow"."&rArr;")
10391 ("dArr") ("Downarrow"."&dArr;")
10392 ("hArr") ("Leftrightarrow"."&hArr;")
10393 ("forall")
10394 ("part") ("partial"."&part;")
10395 ("exist") ("exists"."&exist;")
10396 ("empty") ("emptyset"."&empty;")
10397 ("nabla")
10398 ("isin") ("in"."&isin;")
10399 ("notin")
10400 ("ni")
10401 ("prod")
10402 ("sum")
10403 ("minus")
10404 ("lowast") ("ast"."&lowast;")
10405 ("radic")
10406 ("prop") ("proptp"."&prop;")
10407 ("infin") ("infty"."&infin;")
10408 ("ang") ("angle"."&ang;")
10409 ("and") ("vee"."&and;")
10410 ("or") ("wedge"."&or;")
10411 ("cap")
10412 ("cup")
10413 ("int")
10414 ("there4")
10415 ("sim")
10416 ("cong") ("simeq"."&cong;")
10417 ("asymp")("approx"."&asymp;")
10418 ("ne") ("neq"."&ne;")
10419 ("equiv")
10420 ("le")
10421 ("ge")
10422 ("sub") ("subset"."&sub;")
10423 ("sup") ("supset"."&sup;")
10424 ("nsub")
10425 ("sube")
10426 ("supe")
10427 ("oplus")
10428 ("otimes")
10429 ("perp")
10430 ("sdot") ("cdot"."&sdot;")
10431 ("lceil")
10432 ("rceil")
10433 ("lfloor")
10434 ("rfloor")
10435 ("lang")
10436 ("rang")
10437 ("loz") ("Diamond"."&loz;")
10438 ("spades") ("spadesuit"."&spades;")
10439 ("clubs") ("clubsuit"."&clubs;")
10440 ("hearts") ("diamondsuit"."&hearts;")
10441 ("diams") ("diamondsuit"."&diams;")
10442 ("quot")
10443 ("amp")
10444 ("lt")
10445 ("gt")
10446 ("OElig")
10447 ("oelig")
10448 ("Scaron")
10449 ("scaron")
10450 ("Yuml")
10451 ("circ")
10452 ("tilde")
10453 ("ensp")
10454 ("emsp")
10455 ("thinsp")
10456 ("zwnj")
10457 ("zwj")
10458 ("lrm")
10459 ("rlm")
10460 ("ndash")
10461 ("mdash")
10462 ("lsquo")
10463 ("rsquo")
10464 ("sbquo")
10465 ("ldquo")
10466 ("rdquo")
10467 ("bdquo")
10468 ("dagger")
10469 ("Dagger")
10470 ("permil")
10471 ("lsaquo")
10472 ("rsaquo")
10473 ("euro")
10474
10475 ("arccos"."arccos")
10476 ("arcsin"."arcsin")
10477 ("arctan"."arctan")
10478 ("arg"."arg")
10479 ("cos"."cos")
10480 ("cosh"."cosh")
10481 ("cot"."cot")
10482 ("coth"."coth")
10483 ("csc"."csc")
10484 ("deg"."deg")
10485 ("det"."det")
10486 ("dim"."dim")
10487 ("exp"."exp")
10488 ("gcd"."gcd")
10489 ("hom"."hom")
10490 ("inf"."inf")
10491 ("ker"."ker")
10492 ("lg"."lg")
10493 ("lim"."lim")
10494 ("liminf"."liminf")
10495 ("limsup"."limsup")
10496 ("ln"."ln")
10497 ("log"."log")
10498 ("max"."max")
10499 ("min"."min")
10500 ("Pr"."Pr")
10501 ("sec"."sec")
10502 ("sin"."sin")
10503 ("sinh"."sinh")
10504 ("sup"."sup")
10505 ("tan"."tan")
10506 ("tanh"."tanh")
10507 )
10508 "Entities for TeX->HTML translation.
10509 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
10510 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
10511 In that case, \"\\ent\" will be translated to \"&other;\".
10512 The list contains HTML entities for Latin-1, Greek and other symbols.
10513 It is supplemented by a number of commonly used TeX macros with appropriate
10514 translations. There is currently no way for users to extend this.")
10515
10516 (defun org-cleaned-string-for-export (string)
10517 "Cleanup a buffer substring so that links can be created safely."
10518 (interactive)
10519 (let* ((cb (current-buffer))
10520 (re-radio (and org-target-link-regexp
10521 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
10522 rtn)
10523 (save-excursion
10524 (set-buffer (get-buffer-create " org-mode-tmp"))
10525 (erase-buffer)
10526 (insert string)
10527 (org-mode)
10528 ;; Find targets in comments and move them out of comments,
10529 ;; but mark them as targets that should be invisible
10530 (goto-char (point-min))
10531 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
10532 (replace-match "\\1(INVISIBLE)"))
10533 ;; Find matches for radio targets and turn them into links
10534 (goto-char (point-min))
10535 (when re-radio
10536 (while (re-search-forward re-radio nil t)
10537 (replace-match "\\1[[\\2]]")))
10538 ;; Find all links that contain a newline and put them into a single line
10539 (goto-char (point-min))
10540 (while (re-search-forward "\\(\\[\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\]\\)" nil t)
10541 (replace-match "\\1 \\2")
10542 (goto-char (match-beginning 0)))
10543 ;; Remove comments
10544 (goto-char (point-min))
10545 (while (re-search-forward "^#.*\n?" nil t)
10546 (replace-match ""))
10547 (setq rtn (buffer-string)))
10548 (kill-buffer " org-mode-tmp")
10549 rtn))
10550
10551 (defun org-solidify-link-text (s &optional alist)
10552 "Take link text and make a safe target out of it."
10553 (save-match-data
10554 (let* ((rtn
10555 (mapconcat
10556 'identity
10557 (org-split-string s "[ \t\r\n]+") "--"))
10558 (a (assoc rtn alist)))
10559 (or (cdr a) rtn))))
10560
10561 (defun org-convert-to-odd-levels ()
10562 "Convert an org-mode file with all levels allowed to one with odd levels.
10563 This will leave level 1 alone, convert level 2 to level 3, level 3 to
10564 level 5 etc."
10565 (interactive)
10566 (when (yes-or-no-p "Are you sure you want to globally change levels? ")
10567 (let ((org-odd-levels-only nil) n)
10568 (save-excursion
10569 (goto-char (point-min))
10570 (while (re-search-forward "^\\*\\*+" nil t)
10571 (setq n (1- (length (match-string 0))))
10572 (while (>= (setq n (1- n)) 0)
10573 (org-demote))
10574 (end-of-line 1))))))
10575
10576 (defun org-tr-level (n)
10577 "Make N odd if required."
10578 (if org-odd-levels-only (1+ (/ n 2)) n))
10579
10580 (defvar org-last-level nil) ; dynamically scoped variable
10581
10582 (defun org-export-as-ascii (arg)
10583 "Export the outline as a pretty ASCII file.
10584 If there is an active region, export only the region.
10585 The prefix ARG specifies how many levels of the outline should become
10586 underlined headlines. The default is 3."
10587 (interactive "P")
10588 (setq-default org-todo-line-regexp org-todo-line-regexp)
10589 (let* ((region
10590 (buffer-substring
10591 (if (org-region-active-p) (region-beginning) (point-min))
10592 (if (org-region-active-p) (region-end) (point-max))))
10593 (lines (org-export-find-first-heading-line
10594 (org-skip-comments
10595 (org-split-string
10596 (org-cleaned-string-for-export region)
10597 "[\r\n]"))))
10598 (org-startup-with-deadline-check nil)
10599 (level 0) line txt
10600 (umax nil)
10601 (case-fold-search nil)
10602 (filename (concat (file-name-sans-extension buffer-file-name)
10603 ".txt"))
10604 (buffer (find-file-noselect filename))
10605 (levels-open (make-vector org-level-max nil))
10606 (date (format-time-string "%Y/%m/%d" (current-time)))
10607 (time (format-time-string "%X" (current-time)))
10608 (author user-full-name)
10609 (title (buffer-name))
10610 (options nil)
10611 (email user-mail-address)
10612 (language org-export-default-language)
10613 (text nil)
10614 (todo nil)
10615 (lang-words nil))
10616
10617 (setq org-last-level 1)
10618 (org-init-section-numbers)
10619
10620 (find-file-noselect filename)
10621
10622 ;; Search for the export key lines
10623 (org-parse-key-lines)
10624
10625 (setq lang-words (or (assoc language org-export-language-setup)
10626 (assoc "en" org-export-language-setup)))
10627 (if org-export-ascii-show-new-buffer
10628 (switch-to-buffer-other-window buffer)
10629 (set-buffer buffer))
10630 (erase-buffer)
10631 (fundamental-mode)
10632 (if options (org-parse-export-options options))
10633 (setq umax (if arg (prefix-numeric-value arg)
10634 org-export-headline-levels))
10635
10636 ;; File header
10637 (if title (org-insert-centered title ?=))
10638 (insert "\n")
10639 (if (or author email)
10640 (insert (concat (nth 1 lang-words) ": " (or author "")
10641 (if email (concat " <" email ">") "")
10642 "\n")))
10643 (if (and date time)
10644 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10645 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10646
10647 (insert "\n\n")
10648
10649 (if org-export-with-toc
10650 (progn
10651 (insert (nth 3 lang-words) "\n"
10652 (make-string (length (nth 3 lang-words)) ?=) "\n")
10653 (mapcar '(lambda (line)
10654 (if (string-match org-todo-line-regexp
10655 line)
10656 ;; This is a headline
10657 (progn
10658 (setq level (- (match-end 1) (match-beginning 1))
10659 level (org-tr-level level)
10660 txt (match-string 3 line)
10661 todo
10662 (or (and (match-beginning 2)
10663 (not (equal (match-string 2 line)
10664 org-done-string)))
10665 ; TODO, not DONE
10666 (and (= level umax)
10667 (org-search-todo-below
10668 line lines level))))
10669 (setq txt (org-html-expand-for-ascii txt))
10670
10671 (if org-export-with-section-numbers
10672 (setq txt (concat (org-section-number level)
10673 " " txt)))
10674 (if (<= level umax)
10675 (progn
10676 (insert
10677 (make-string (* (1- level) 4) ?\ )
10678 (format (if todo "%s (*)\n" "%s\n") txt))
10679 (setq org-last-level level))
10680 ))))
10681 lines)))
10682
10683 (org-init-section-numbers)
10684 (while (setq line (pop lines))
10685 ;; Remove the quoted HTML tags.
10686 (setq line (org-html-expand-for-ascii line))
10687 ;; Remove targets
10688 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
10689 (setq line (replace-match "" t t line)))
10690 ;; Replace internal links
10691 (while (string-match org-bracket-link-regexp line)
10692 (setq line (replace-match
10693 (if (match-end 3) "[\\3]" "[\\1]")
10694 t nil line)))
10695 (cond
10696 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10697 ;; a Headline
10698 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
10699 txt (match-string 2 line))
10700 (org-ascii-level-start level txt umax))
10701 (t (insert line "\n"))))
10702 (normal-mode)
10703 (save-buffer)
10704 (goto-char (point-min))))
10705
10706 (defun org-search-todo-below (line lines level)
10707 "Search the subtree below LINE for any TODO entries."
10708 (let ((rest (cdr (memq line lines)))
10709 (re org-todo-line-regexp)
10710 line lv todo)
10711 (catch 'exit
10712 (while (setq line (pop rest))
10713 (if (string-match re line)
10714 (progn
10715 (setq lv (- (match-end 1) (match-beginning 1))
10716 todo (and (match-beginning 2)
10717 (not (equal (match-string 2 line)
10718 org-done-string))))
10719 ; TODO, not DONE
10720 (if (<= lv level) (throw 'exit nil))
10721 (if todo (throw 'exit t))))))))
10722
10723 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10724 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10725 (defun org-html-expand-for-ascii (line)
10726 "Handle quoted HTML for ASCII export."
10727 (if org-export-html-expand
10728 (while (string-match "@<[^<>\n]*>" line)
10729 ;; We just remove the tags for now.
10730 (setq line (replace-match "" nil nil line))))
10731 line)
10732
10733 (defun org-insert-centered (s &optional underline)
10734 "Insert the string S centered and underline it with character UNDERLINE."
10735 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
10736 (insert (make-string ind ?\ ) s "\n")
10737 (if underline
10738 (insert (make-string ind ?\ )
10739 (make-string (length s) underline)
10740 "\n"))))
10741
10742 (defun org-ascii-level-start (level title umax)
10743 "Insert a new level in ASCII export."
10744 (let (char)
10745 (if (> level umax)
10746 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10747 (if (or (not (equal (char-before) ?\n))
10748 (not (equal (char-before (1- (point))) ?\n)))
10749 (insert "\n"))
10750 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10751 (if org-export-with-section-numbers
10752 (setq title (concat (org-section-number level) " " title)))
10753 (insert title "\n" (make-string (string-width title) char) "\n"))))
10754
10755 (defun org-export-copy-visible ()
10756 "Copy the visible part of the buffer to another buffer, for printing.
10757 Also removes the first line of the buffer if it specifies a mode,
10758 and all options lines."
10759 (interactive)
10760 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
10761 ".txt"))
10762 (buffer (find-file-noselect filename))
10763 (ore (concat
10764 (org-make-options-regexp
10765 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10766 "STARTUP" "ARCHIVE"
10767 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10768 (if org-noutline-p "\\(\n\\|$\\)" "")))
10769 s e)
10770 (with-current-buffer buffer
10771 (erase-buffer)
10772 (text-mode))
10773 (save-excursion
10774 (setq s (goto-char (point-min)))
10775 (while (not (= (point) (point-max)))
10776 (goto-char (org-find-invisible))
10777 (append-to-buffer buffer s (point))
10778 (setq s (goto-char (org-find-visible)))))
10779 (switch-to-buffer-other-window buffer)
10780 (newline)
10781 (goto-char (point-min))
10782 (if (looking-at ".*-\\*- mode:.*\n")
10783 (replace-match ""))
10784 (while (re-search-forward ore nil t)
10785 (replace-match ""))
10786 (goto-char (point-min))))
10787
10788 (defun org-find-visible ()
10789 (if (featurep 'noutline)
10790 (let ((s (point)))
10791 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10792 (get-char-property s 'invisible)))
10793 s)
10794 (skip-chars-forward "^\n")
10795 (point)))
10796 (defun org-find-invisible ()
10797 (if (featurep 'noutline)
10798 (let ((s (point)))
10799 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10800 (not (get-char-property s 'invisible))))
10801 s)
10802 (skip-chars-forward "^\r")
10803 (point)))
10804
10805 ;; HTML
10806
10807 (defun org-get-current-options ()
10808 "Return a string with current options as keyword options.
10809 Does include HTML export options as well as TODO and CATEGORY stuff."
10810 (format
10811 "#+TITLE: %s
10812 #+AUTHOR: %s
10813 #+EMAIL: %s
10814 #+LANGUAGE: %s
10815 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10816 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10817 #+CATEGORY: %s
10818 #+SEQ_TODO: %s
10819 #+TYP_TODO: %s
10820 #+STARTUP: %s %s
10821 #+ARCHIVE: %s
10822 "
10823 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10824 org-export-headline-levels
10825 org-export-with-section-numbers
10826 org-export-with-toc
10827 org-export-preserve-breaks
10828 org-export-html-expand
10829 org-export-with-fixed-width
10830 org-export-with-tables
10831 org-export-with-sub-superscripts
10832 org-export-with-emphasize
10833 org-export-with-TeX-macros
10834 (file-name-nondirectory buffer-file-name)
10835 (if (equal org-todo-interpretation 'sequence)
10836 (mapconcat 'identity org-todo-keywords " ")
10837 "TODO FEEDBACK VERIFY DONE")
10838 (if (equal org-todo-interpretation 'type)
10839 (mapconcat 'identity org-todo-keywords " ")
10840 "Me Jason Marie DONE")
10841 (cdr (assoc org-startup-folded
10842 '((nil . "nofold")(t . "fold")(content . "content"))))
10843 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10844 org-archive-location
10845 ))
10846
10847 (defun org-insert-export-options-template ()
10848 "Insert into the buffer a template with information for exporting."
10849 (interactive)
10850 (if (not (bolp)) (newline))
10851 (let ((s (org-get-current-options)))
10852 (and (string-match "#\\+CATEGORY" s)
10853 (setq s (substring s 0 (match-beginning 0))))
10854 (insert s)))
10855
10856 (defun org-toggle-fixed-width-section (arg)
10857 "Toggle the fixed-width export.
10858 If there is no active region, the QUOTE keyword at the current headline is
10859 inserted or removed. When present, it causes the text between this headline
10860 and the next to be exported as fixed-width text, and unmodified.
10861 If there is an active region, this command adds or removes a colon as the
10862 first character of this line. If the first character of a line is a colon,
10863 this line is also exported in fixed-width font."
10864 (interactive "P")
10865 (let* ((cc 0)
10866 (regionp (org-region-active-p))
10867 (beg (if regionp (region-beginning) (point)))
10868 (end (if regionp (region-end)))
10869 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10870 (re "[ \t]*\\(:\\)")
10871 off)
10872 (if regionp
10873 (save-excursion
10874 (goto-char beg)
10875 (setq cc (current-column))
10876 (beginning-of-line 1)
10877 (setq off (looking-at re))
10878 (while (> nlines 0)
10879 (setq nlines (1- nlines))
10880 (beginning-of-line 1)
10881 (cond
10882 (arg
10883 (move-to-column cc t)
10884 (insert ":\n")
10885 (forward-line -1))
10886 ((and off (looking-at re))
10887 (replace-match "" t t nil 1))
10888 ((not off) (move-to-column cc t) (insert ":")))
10889 (forward-line 1)))
10890 (save-excursion
10891 (org-back-to-heading)
10892 (if (looking-at (concat outline-regexp
10893 "\\( +\\<" org-quote-string "\\>\\)"))
10894 (replace-match "" t t nil 1)
10895 (if (looking-at outline-regexp)
10896 (progn
10897 (goto-char (match-end 0))
10898 (insert " " org-quote-string))))))))
10899
10900 (defun org-export-as-html-and-open (arg)
10901 "Export the outline as HTML and immediately open it with a browser.
10902 If there is an active region, export only the region.
10903 The prefix ARG specifies how many levels of the outline should become
10904 headlines. The default is 3. Lower levels will become bulleted lists."
10905 (interactive "P")
10906 (org-export-as-html arg 'hidden)
10907 (org-open-file buffer-file-name))
10908
10909 (defun org-export-as-html-batch ()
10910 "Call `org-export-as-html', may be used in batch processing as
10911 emacs --batch
10912 --load=$HOME/lib/emacs/org.el
10913 --eval \"(setq org-export-headline-levels 2)\"
10914 --visit=MyFile --funcall org-export-as-html-batch"
10915 (org-export-as-html org-export-headline-levels 'hidden))
10916
10917 (defun org-export-as-html (arg &optional hidden)
10918 "Export the outline as a pretty HTML file.
10919 If there is an active region, export only the region.
10920 The prefix ARG specifies how many levels of the outline should become
10921 headlines. The default is 3. Lower levels will become bulleted lists."
10922 (interactive "P")
10923 (setq-default org-todo-line-regexp org-todo-line-regexp)
10924 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
10925 (setq-default org-done-string org-done-string)
10926 (let* ((style org-export-html-style)
10927 (region-p (org-region-active-p))
10928 (region
10929 (buffer-substring
10930 (if region-p (region-beginning) (point-min))
10931 (if region-p (region-end) (point-max))))
10932 (all_lines
10933 (org-skip-comments (org-split-string
10934 (org-cleaned-string-for-export region)
10935 "[\r\n]")))
10936 (lines (org-export-find-first-heading-line all_lines))
10937 (level 0) (line "") (origline "") txt todo
10938 (umax nil)
10939 (filename (concat (file-name-sans-extension buffer-file-name)
10940 ".html"))
10941 (buffer (find-file-noselect filename))
10942 (levels-open (make-vector org-level-max nil))
10943 (date (format-time-string "%Y/%m/%d" (current-time)))
10944 (time (format-time-string "%X" (current-time)))
10945 (author user-full-name)
10946 (title (buffer-name))
10947 (options nil)
10948 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
10949 (inquote nil)
10950 (infixed nil)
10951 (in-local-list nil)
10952 (local-list-num nil)
10953 (local-list-indent nil)
10954 (llt org-plain-list-ordered-item-terminator)
10955 (email user-mail-address)
10956 (language org-export-default-language)
10957 (text nil)
10958 (lang-words nil)
10959 (target-alist nil) tg
10960 (head-count 0) cnt
10961 (start 0)
10962 ;; FIXME: The following returns always nil under XEmacs
10963 (coding-system (and (fboundp 'coding-system-get)
10964 (boundp 'buffer-file-coding-system)
10965 buffer-file-coding-system))
10966 (coding-system-for-write (or coding-system coding-system-for-write))
10967 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
10968 (charset (and coding-system
10969 (coding-system-get coding-system 'mime-charset)))
10970 table-open type
10971 table-buffer table-orig-buffer
10972 ind start-is-num starter
10973 )
10974 (message "Exporting...")
10975
10976 (setq org-last-level 1)
10977 (org-init-section-numbers)
10978
10979 ;; Search for the export key lines
10980 (org-parse-key-lines)
10981 (setq lang-words (or (assoc language org-export-language-setup)
10982 (assoc "en" org-export-language-setup)))
10983
10984 ;; Switch to the output buffer
10985 (if (or hidden (not org-export-html-show-new-buffer))
10986 (set-buffer buffer)
10987 (switch-to-buffer-other-window buffer))
10988 (erase-buffer)
10989 (fundamental-mode)
10990 (let ((case-fold-search nil))
10991 (if options (org-parse-export-options options))
10992 (setq umax (if arg (prefix-numeric-value arg)
10993 org-export-headline-levels))
10994
10995 ;; File header
10996 (insert (format
10997 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
10998 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
10999 <html lang=\"%s\"><head>
11000 <title>%s</title>
11001 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
11002 <meta name=generator content=\"Org-mode\">
11003 <meta name=generated content=\"%s %s\">
11004 <meta name=author content=\"%s\">
11005 %s
11006 </head><body>
11007 "
11008 language (org-html-expand title) (or charset "iso-8859-1")
11009 date time author style))
11010 (if title (insert (concat "<H1 class=\"title\">"
11011 (org-html-expand title) "</H1>\n")))
11012 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11013 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11014 email "&gt;</a>\n")))
11015 (if (or author email) (insert "<br>\n"))
11016 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11017 date " " time "<br>\n")))
11018 (if text (insert (concat "<p>\n" (org-html-expand text))))
11019 (if org-export-with-toc
11020 (progn
11021 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11022 (insert "<ul>\n")
11023 (setq lines
11024 (mapcar '(lambda (line)
11025 (if (string-match org-todo-line-regexp line)
11026 ;; This is a headline
11027 (progn
11028 (setq level (- (match-end 1) (match-beginning 1))
11029 level (org-tr-level level)
11030 txt (save-match-data
11031 (org-html-expand
11032 (match-string 3 line)))
11033 todo
11034 (or (and (match-beginning 2)
11035 (not (equal (match-string 2 line)
11036 org-done-string)))
11037 ; TODO, not DONE
11038 (and (= level umax)
11039 (org-search-todo-below
11040 line lines level))))
11041 (if org-export-with-section-numbers
11042 (setq txt (concat (org-section-number level)
11043 " " txt)))
11044 (if (<= level umax)
11045 (progn
11046 (setq head-count (+ head-count 1))
11047 (if (> level org-last-level)
11048 (progn
11049 (setq cnt (- level org-last-level))
11050 (while (>= (setq cnt (1- cnt)) 0)
11051 (insert "<ul>"))
11052 (insert "\n")))
11053 (if (< level org-last-level)
11054 (progn
11055 (setq cnt (- org-last-level level))
11056 (while (>= (setq cnt (1- cnt)) 0)
11057 (insert "</ul>"))
11058 (insert "\n")))
11059 ;; Check for targets
11060 (while (string-match org-target-regexp line)
11061 (setq tg (match-string 1 line)
11062 line (replace-match
11063 (concat "@<span class=\"target\">" tg "@</span> ")
11064 t t line))
11065 (push (cons (org-solidify-link-text tg)
11066 (format "sec-%d" head-count))
11067 target-alist))
11068 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11069 (setq txt (replace-match "" t t txt)))
11070 (insert
11071 (format
11072 (if todo
11073 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11074 "<li><a href=\"#sec-%d\">%s</a>\n")
11075 head-count txt))
11076
11077 (setq org-last-level level))
11078 )))
11079 line)
11080 lines))
11081 (while (> org-last-level 0)
11082 (setq org-last-level (1- org-last-level))
11083 (insert "</ul>\n"))
11084 ))
11085 (setq head-count 0)
11086 (org-init-section-numbers)
11087
11088 (while (setq line (pop lines) origline line)
11089 (catch 'nextline
11090
11091 ;; end of quote section?
11092 (when (and inquote (string-match "^\\*+" line))
11093 (insert "</pre>\n")
11094 (setq inquote nil))
11095 ;; inside a quote section?
11096 (when inquote
11097 (insert (org-html-protect line) "\n")
11098 (throw 'nextline nil))
11099
11100 ;; verbatim lines
11101 (when (and org-export-with-fixed-width
11102 (string-match "^[ \t]*:\\(.*\\)" line))
11103 (when (not infixed)
11104 (setq infixed t)
11105 (insert "<pre>\n"))
11106 (insert (org-html-protect (match-string 1 line)) "\n")
11107 (when (and lines
11108 (not (string-match "^[ \t]*\\(:.*\\)"
11109 (car lines))))
11110 (setq infixed nil)
11111 (insert "</pre>\n"))
11112 (throw 'nextline nil))
11113
11114
11115 ;; make targets to anchors
11116 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11117 (cond
11118 ((match-end 2)
11119 (setq line (replace-match
11120 (concat "@<a name=\""
11121 (org-solidify-link-text (match-string 1 line))
11122 "\">\\nbsp@</a>")
11123 t t line)))
11124 ((and org-export-with-toc (equal (string-to-char line) ?*))
11125 (setq line (replace-match
11126 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11127 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11128 t t line)))
11129 (t
11130 (setq line (replace-match
11131 (concat "@<a name=\""
11132 (org-solidify-link-text (match-string 1 line))
11133 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11134 t t line)))))
11135 ;; Replace internal links
11136 (while (string-match org-bracket-link-regexp line)
11137 (setq line (replace-match
11138 (concat
11139 "@<a href=\"#"
11140 (org-solidify-link-text (match-string 1 line) target-alist)
11141 "\">"
11142 (match-string (if (match-end 3) 3 1) line)
11143 "@</a>")
11144 t t line)))
11145
11146 ;; Protect the external links
11147 (setq start 0)
11148 (while (string-match org-link-maybe-angles-regexp line start)
11149 (setq start (match-end 0))
11150 (setq line (replace-match
11151 (concat "\000" (match-string 1 line) "\000")
11152 t t line)))
11153
11154 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11155 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11156 (setq line (org-html-expand line))
11157
11158 ;; Format the links
11159 (setq start 0)
11160 (while (string-match org-protected-link-regexp line start)
11161 (setq start (- (match-end 0) 2))
11162 (setq type (match-string 1 line))
11163 (cond
11164 ((member type '("http" "https" "ftp" "mailto" "news"))
11165 ;; standard URL
11166 (setq line (replace-match
11167 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
11168 "<a href=\"\\1:\\2\">\\1:\\2</a>"
11169 nil nil line)))
11170 ((string= type "file")
11171 ;; FILE link
11172 (let* ((filename (match-string 2 line))
11173 (abs-p (file-name-absolute-p filename))
11174 (thefile (if abs-p (expand-file-name filename) filename))
11175 (thefile (save-match-data
11176 (if (string-match ":[0-9]+$" thefile)
11177 (replace-match "" t t thefile)
11178 thefile)))
11179 (file-is-image-p
11180 (save-match-data
11181 (string-match (org-image-file-name-regexp) thefile))))
11182 (setq line (replace-match
11183 (if (and org-export-html-inline-images
11184 file-is-image-p)
11185 (concat "<img src=\"" thefile "\"/>")
11186 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
11187 nil nil line))))
11188
11189 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11190 (setq line (replace-match
11191 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
11192
11193 ;; TODO items
11194 (if (and (string-match org-todo-line-regexp line)
11195 (match-beginning 2))
11196 (if (equal (match-string 2 line) org-done-string)
11197 (setq line (replace-match
11198 "<span class=\"done\">\\2</span>"
11199 nil nil line 2))
11200 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11201 nil nil line 2))))
11202
11203 ;; DEADLINES
11204 (if (string-match org-deadline-line-regexp line)
11205 (progn
11206 (if (save-match-data
11207 (string-match "<a href"
11208 (substring line 0 (match-beginning 0))))
11209 nil ; Don't do the replacement - it is inside a link
11210 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11211 nil nil line 1)))))
11212 (cond
11213 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11214 ;; This is a headline
11215 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11216 txt (match-string 2 line))
11217 (if (<= level umax) (setq head-count (+ head-count 1)))
11218 (when in-local-list
11219 ;; Close any local lists before inserting a new header line
11220 (while local-list-num
11221 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11222 (pop local-list-num))
11223 (setq local-list-indent nil
11224 in-local-list nil))
11225 (org-html-level-start level txt umax
11226 (and org-export-with-toc (<= level umax))
11227 head-count)
11228 ;; QUOTES
11229 (when (string-match quote-re line)
11230 (insert "<pre>")
11231 (setq inquote t)))
11232
11233 ((and org-export-with-tables
11234 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11235 (if (not table-open)
11236 ;; New table starts
11237 (setq table-open t table-buffer nil table-orig-buffer nil))
11238 ;; Accumulate lines
11239 (setq table-buffer (cons line table-buffer)
11240 table-orig-buffer (cons origline table-orig-buffer))
11241 (when (or (not lines)
11242 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11243 (car lines))))
11244 (setq table-open nil
11245 table-buffer (nreverse table-buffer)
11246 table-orig-buffer (nreverse table-orig-buffer))
11247 (insert (org-format-table-html table-buffer table-orig-buffer))))
11248 (t
11249 ;; Normal lines
11250 (when (and (> org-export-plain-list-max-depth 0)
11251 (string-match
11252 (cond
11253 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11254 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11255 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11256 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11257 line))
11258 (setq ind (org-get-string-indentation line)
11259 start-is-num (match-beginning 4)
11260 starter (if (match-beginning 2) (match-string 2 line))
11261 line (substring line (match-beginning 5)))
11262 (unless (string-match "[^ \t]" line)
11263 ;; empty line. Pretend indentation is large.
11264 (setq ind (1+ (or (car local-list-indent) 1))))
11265 (while (and in-local-list
11266 (or (and (= ind (car local-list-indent))
11267 (not starter))
11268 (< ind (car local-list-indent))))
11269 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11270 (pop local-list-num) (pop local-list-indent)
11271 (setq in-local-list local-list-indent))
11272 (cond
11273 ((and starter
11274 (or (not in-local-list)
11275 (> ind (car local-list-indent)))
11276 (< (length local-list-indent)
11277 org-export-plain-list-max-depth))
11278 ;; Start new (level of ) list
11279 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11280 (push start-is-num local-list-num)
11281 (push ind local-list-indent)
11282 (setq in-local-list t))
11283 (starter
11284 ;; continue current list
11285 (insert "<li>\n"))))
11286 ;; Empty lines start a new paragraph. If hand-formatted lists
11287 ;; are not fully interpreted, lines starting with "-", "+", "*"
11288 ;; also start a new paragraph.
11289 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11290 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11291 ))
11292 (if org-export-html-with-timestamp
11293 (insert org-export-html-html-helper-timestamp))
11294 (insert "</body>\n</html>\n")
11295 (normal-mode)
11296 (save-buffer)
11297 (goto-char (point-min)))))
11298
11299 (defun org-format-table-html (lines olines)
11300 "Find out which HTML converter to use and return the HTML code."
11301 (if (string-match "^[ \t]*|" (car lines))
11302 ;; A normal org table
11303 (org-format-org-table-html lines)
11304 ;; Table made by table.el - test for spanning
11305 (let* ((hlines (delq nil (mapcar
11306 (lambda (x)
11307 (if (string-match "^[ \t]*\\+-" x) x
11308 nil))
11309 lines)))
11310 (first (car hlines))
11311 (ll (and (string-match "\\S-+" first)
11312 (match-string 0 first)))
11313 (re (concat "^[ \t]*" (regexp-quote ll)))
11314 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
11315 hlines))))
11316 (if (and (not spanning)
11317 (not org-export-prefer-native-exporter-for-tables))
11318 ;; We can use my own converter with HTML conversions
11319 (org-format-table-table-html lines)
11320 ;; Need to use the code generator in table.el, with the original text.
11321 (org-format-table-table-html-using-table-generate-source olines)))))
11322
11323 (defun org-format-org-table-html (lines)
11324 "Format a table into HTML."
11325 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11326 (setq lines (nreverse lines))
11327 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11328 (setq lines (nreverse lines))
11329 (when org-export-table-remove-special-lines
11330 ;; Check if the table has a marking column. If yes remove the
11331 ;; column and the special lines
11332 (let* ((special
11333 (not
11334 (memq nil
11335 (mapcar
11336 (lambda (x)
11337 (or (string-match "^[ \t]*|-" x)
11338 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
11339 lines)))))
11340 (if special
11341 (setq lines
11342 (delq nil
11343 (mapcar
11344 (lambda (x)
11345 (if (string-match "^[ \t]*| *[!_^] *|" x)
11346 nil ; ignore this line
11347 (and (or (string-match "^[ \t]*|-+\\+" x)
11348 (string-match "^[ \t]*|[^|]*|" x))
11349 (replace-match "|" t t x))))
11350 lines))))))
11351
11352 (let ((head (and org-export-highlight-first-table-line
11353 (delq nil (mapcar
11354 (lambda (x) (string-match "^[ \t]*|-" x))
11355 (cdr lines)))))
11356 line fields html)
11357 (setq html (concat org-export-html-table-tag "\n"))
11358 (while (setq line (pop lines))
11359 (catch 'next-line
11360 (if (string-match "^[ \t]*|-" line)
11361 (progn
11362 (setq head nil) ;; head ends here, first time around
11363 ;; ignore this line
11364 (throw 'next-line t)))
11365 ;; Break the line into fields
11366 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11367 (setq html (concat
11368 html
11369 "<tr>"
11370 (mapconcat (lambda (x)
11371 (if head
11372 (concat "<th>" x "</th>")
11373 (concat "<td>" x "</td>")))
11374 fields "")
11375 "</tr>\n"))))
11376 (setq html (concat html "</table>\n"))
11377 html))
11378
11379 (defun org-fake-empty-table-line (line)
11380 "Replace everything except \"|\" with spaces."
11381 (let ((i (length line))
11382 (newstr (copy-sequence line)))
11383 (while (> i 0)
11384 (setq i (1- i))
11385 (if (not (eq (aref newstr i) ?|))
11386 (aset newstr i ?\ )))
11387 newstr))
11388
11389 (defun org-format-table-table-html (lines)
11390 "Format a table generated by table.el into HTML.
11391 This conversion does *not* use `table-generate-source' from table.el.
11392 This has the advantage that Org-mode's HTML conversions can be used.
11393 But it has the disadvantage, that no cell- or row-spanning is allowed."
11394 (let (line field-buffer
11395 (head org-export-highlight-first-table-line)
11396 fields html empty)
11397 (setq html (concat org-export-html-table-tag "\n"))
11398 (while (setq line (pop lines))
11399 (setq empty "&nbsp")
11400 (catch 'next-line
11401 (if (string-match "^[ \t]*\\+-" line)
11402 (progn
11403 (if field-buffer
11404 (progn
11405 (setq html (concat
11406 html
11407 "<tr>"
11408 (mapconcat
11409 (lambda (x)
11410 (if (equal x "") (setq x empty))
11411 (if head
11412 (concat "<th>" x "</th>\n")
11413 (concat "<td>" x "</td>\n")))
11414 field-buffer "\n")
11415 "</tr>\n"))
11416 (setq head nil)
11417 (setq field-buffer nil)))
11418 ;; Ignore this line
11419 (throw 'next-line t)))
11420 ;; Break the line into fields and store the fields
11421 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11422 (if field-buffer
11423 (setq field-buffer (mapcar
11424 (lambda (x)
11425 (concat x "<br>" (pop fields)))
11426 field-buffer))
11427 (setq field-buffer fields))))
11428 (setq html (concat html "</table>\n"))
11429 html))
11430
11431 (defun org-format-table-table-html-using-table-generate-source (lines)
11432 "Format a table into html, using `table-generate-source' from table.el.
11433 This has the advantage that cell- or row-spanning is allowed.
11434 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
11435 (require 'table)
11436 (with-current-buffer (get-buffer-create " org-tmp1 ")
11437 (erase-buffer)
11438 (insert (mapconcat 'identity lines "\n"))
11439 (goto-char (point-min))
11440 (if (not (re-search-forward "|[^+]" nil t))
11441 (error "Error processing table"))
11442 (table-recognize-table)
11443 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
11444 (table-generate-source 'html " org-tmp2 ")
11445 (set-buffer " org-tmp2 ")
11446 (buffer-substring (point-min) (point-max))))
11447
11448 (defun org-html-protect (s)
11449 ;; convert & to &amp;, < to &lt; and > to &gt;
11450 (let ((start 0))
11451 (while (string-match "&" s start)
11452 (setq s (replace-match "&amp;" t t s)
11453 start (1+ (match-beginning 0))))
11454 (while (string-match "<" s)
11455 (setq s (replace-match "&lt;" t t s)))
11456 (while (string-match ">" s)
11457 (setq s (replace-match "&gt;" t t s))))
11458 s)
11459
11460 (defun org-html-expand (string)
11461 "Prepare STRING for HTML export. Applies all active conversions."
11462 ;; First check if there is a link in the line - if yes, apply conversions
11463 ;; only before the start of the link.
11464 ;; FIXME: This is no longer correct, because links now have an end.
11465 (let* ((m (string-match org-link-regexp string))
11466 (s (if m (substring string 0 m) string))
11467 (r (if m (substring string m) "")))
11468 ;; convert & to &amp;, < to &lt; and > to &gt;
11469 (setq s (org-html-protect s))
11470 (if org-export-html-expand
11471 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
11472 (setq s (replace-match "<\\1>" nil nil s))))
11473 (if org-export-with-emphasize
11474 (setq s (org-export-html-convert-emphasize s)))
11475 (if org-export-with-sub-superscripts
11476 (setq s (org-export-html-convert-sub-super s)))
11477 (if org-export-with-TeX-macros
11478 (let ((start 0) wd ass)
11479 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
11480 (setq wd (match-string 1 s))
11481 (if (setq ass (assoc wd org-html-entities))
11482 (setq s (replace-match (or (cdr ass)
11483 (concat "&" (car ass) ";"))
11484 t t s))
11485 (setq start (+ start (length wd)))))))
11486 (concat s r)))
11487
11488 (defun org-create-multibrace-regexp (left right n)
11489 "Create a regular expression which will match a balanced sexp.
11490 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
11491 as single character strings.
11492 The regexp returned will match the entire expression including the
11493 delimiters. It will also define a single group which contains the
11494 match except for the outermost delimiters. The maximum depth of
11495 stacked delimiters is N. Escaping delimiters is not possible."
11496 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
11497 (or "\\|")
11498 (re nothing)
11499 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
11500 (while (> n 1)
11501 (setq n (1- n)
11502 re (concat re or next)
11503 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
11504 (concat left "\\(" re "\\)" right)))
11505
11506 (defvar org-match-substring-regexp
11507 (concat
11508 "\\([^\\]\\)\\([_^]\\)\\("
11509 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
11510 "\\|"
11511 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
11512 "\\|"
11513 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
11514 "The regular expression matching a sub- or superscript.")
11515
11516 (defun org-export-html-convert-sub-super (string)
11517 "Convert sub- and superscripts in STRING to HTML."
11518 (let (key c)
11519 (while (string-match org-match-substring-regexp string)
11520 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
11521 (setq c (or (match-string 8 string)
11522 (match-string 6 string)
11523 (match-string 5 string)))
11524 (setq string (replace-match
11525 (concat (match-string 1 string)
11526 "<" key ">" c "</" key ">")
11527 t t string)))
11528 (while (string-match "\\\\\\([_^]\\)" string)
11529 (setq string (replace-match (match-string 1 string) t t string))))
11530 string)
11531
11532 (defun org-export-html-convert-emphasize (string)
11533 (while (string-match
11534 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
11535 string)
11536 (setq string (replace-match
11537 (concat "<b>" (match-string 3 string) "</b>")
11538 t t string 2)))
11539 (while (string-match
11540 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
11541 string)
11542 (setq string (replace-match
11543 (concat "<i>" (match-string 3 string) "</i>")
11544 t t string 2)))
11545 (while (string-match
11546 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
11547 string)
11548 (setq string (replace-match
11549 (concat "<u>" (match-string 3 string) "</u>")
11550 t t string 2)))
11551 string)
11552
11553 (defun org-parse-key-lines ()
11554 "Find the special key lines with the information for exporters."
11555 (save-excursion
11556 (goto-char 0)
11557 (let ((re (org-make-options-regexp
11558 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
11559 key)
11560 (while (re-search-forward re nil t)
11561 (setq key (match-string 1))
11562 (cond ((string-equal key "TITLE")
11563 (setq title (match-string 2)))
11564 ((string-equal key "AUTHOR")
11565 (setq author (match-string 2)))
11566 ((string-equal key "EMAIL")
11567 (setq email (match-string 2)))
11568 ((string-equal key "LANGUAGE")
11569 (setq language (match-string 2)))
11570 ((string-equal key "TEXT")
11571 (setq text (concat text "\n" (match-string 2))))
11572 ((string-equal key "OPTIONS")
11573 (setq options (match-string 2))))))))
11574
11575 (defun org-parse-export-options (s)
11576 "Parse the export options line."
11577 (let ((op '(("H" . org-export-headline-levels)
11578 ("num" . org-export-with-section-numbers)
11579 ("toc" . org-export-with-toc)
11580 ("\\n" . org-export-preserve-breaks)
11581 ("@" . org-export-html-expand)
11582 (":" . org-export-with-fixed-width)
11583 ("|" . org-export-with-tables)
11584 ("^" . org-export-with-sub-superscripts)
11585 ("*" . org-export-with-emphasize)
11586 ("TeX" . org-export-with-TeX-macros)))
11587 o)
11588 (while (setq o (pop op))
11589 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
11590 s)
11591 (set (make-local-variable (cdr o))
11592 (car (read-from-string (match-string 1 s))))))))
11593
11594 (defun org-html-level-start (level title umax with-toc head-count)
11595 "Insert a new level in HTML export."
11596 (let ((l (1+ (max level umax))))
11597 (while (<= l org-level-max)
11598 (if (aref levels-open (1- l))
11599 (progn
11600 (org-html-level-close l)
11601 (aset levels-open (1- l) nil)))
11602 (setq l (1+ l)))
11603 (if (> level umax)
11604 (progn
11605 (if (aref levels-open (1- level))
11606 (insert "<li>" title "<p>\n")
11607 (aset levels-open (1- level) t)
11608 (insert "<ul><li>" title "<p>\n")))
11609 (if org-export-with-section-numbers
11610 (setq title (concat (org-section-number level) " " title)))
11611 (setq level (+ level 1))
11612 (if with-toc
11613 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
11614 level head-count title level))
11615 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
11616
11617 (defun org-html-level-close (&rest args)
11618 "Terminate one level in HTML export."
11619 (insert "</ul>"))
11620
11621 ;; Variable holding the vector with section numbers
11622 (defvar org-section-numbers (make-vector org-level-max 0))
11623
11624 (defun org-init-section-numbers ()
11625 "Initialize the vector for the section numbers."
11626 (let* ((level -1)
11627 (numbers (nreverse (org-split-string "" "\\.")))
11628 (depth (1- (length org-section-numbers)))
11629 (i depth) number-string)
11630 (while (>= i 0)
11631 (if (> i level)
11632 (aset org-section-numbers i 0)
11633 (setq number-string (or (car numbers) "0"))
11634 (if (string-match "\\`[A-Z]\\'" number-string)
11635 (aset org-section-numbers i
11636 (- (string-to-char number-string) ?A -1))
11637 (aset org-section-numbers i (string-to-number number-string)))
11638 (pop numbers))
11639 (setq i (1- i)))))
11640
11641 (defun org-section-number (&optional level)
11642 "Return a string with the current section number.
11643 When LEVEL is non-nil, increase section numbers on that level."
11644 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
11645 (when level
11646 (when (> level -1)
11647 (aset org-section-numbers
11648 level (1+ (aref org-section-numbers level))))
11649 (setq idx (1+ level))
11650 (while (<= idx depth)
11651 (if (not (= idx 1))
11652 (aset org-section-numbers idx 0))
11653 (setq idx (1+ idx))))
11654 (setq idx 0)
11655 (while (<= idx depth)
11656 (setq n (aref org-section-numbers idx))
11657 (setq string (concat string (if (not (string= string "")) "." "")
11658 (int-to-string n)))
11659 (setq idx (1+ idx)))
11660 (save-match-data
11661 (if (string-match "\\`\\([@0]\\.\\)+" string)
11662 (setq string (replace-match "" nil nil string)))
11663 (if (string-match "\\(\\.0\\)+\\'" string)
11664 (setq string (replace-match "" nil nil string))))
11665 string))
11666
11667
11668 (defun org-export-icalendar-this-file ()
11669 "Export current file as an iCalendar file.
11670 The iCalendar file will be located in the same directory as the Org-mode
11671 file, but with extension `.ics'."
11672 (interactive)
11673 (org-export-icalendar nil buffer-file-name))
11674
11675 ;;;###autoload
11676 (defun org-export-icalendar-all-agenda-files ()
11677 "Export all files in `org-agenda-files' to iCalendar .ics files.
11678 Each iCalendar file will be located in the same directory as the Org-mode
11679 file, but with extension `.ics'."
11680 (interactive)
11681 (apply 'org-export-icalendar nil org-agenda-files))
11682
11683 ;;;###autoload
11684 (defun org-export-icalendar-combine-agenda-files ()
11685 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11686 The file is stored under the name `org-combined-agenda-icalendar-file'."
11687 (interactive)
11688 (apply 'org-export-icalendar t org-agenda-files))
11689
11690 (defun org-export-icalendar (combine &rest files)
11691 "Create iCalendar files for all elements of FILES.
11692 If COMBINE is non-nil, combine all calendar entries into a single large
11693 file and store it under the name `org-combined-agenda-icalendar-file'."
11694 (save-excursion
11695 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11696 (when combine
11697 (setq ical-file org-combined-agenda-icalendar-file
11698 ical-buffer (org-get-agenda-file-buffer ical-file))
11699 (set-buffer ical-buffer) (erase-buffer))
11700 (while (setq file (pop files))
11701 (catch 'nextfile
11702 (org-check-agenda-file file)
11703 (unless combine
11704 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11705 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11706 (set-buffer ical-buffer) (erase-buffer))
11707 (set-buffer (org-get-agenda-file-buffer file))
11708 (setq category (or org-category
11709 (file-name-sans-extension
11710 (file-name-nondirectory buffer-file-name))))
11711 (if (symbolp category) (setq category (symbol-name category)))
11712 (let ((standard-output ical-buffer))
11713 (if combine
11714 (and (not started) (setq started t)
11715 (org-start-icalendar-file org-icalendar-combined-name))
11716 (org-start-icalendar-file category))
11717 (org-print-icalendar-entries combine category)
11718 (when (or (and combine (not files)) (not combine))
11719 (org-finish-icalendar-file)
11720 (set-buffer ical-buffer)
11721 (save-buffer)
11722 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11723 (org-release-buffers org-agenda-new-buffers))))
11724
11725 (defvar org-after-save-iCalendar-file-hook nil
11726 "Hook run after an iCalendar file has been saved.
11727 The iCalendar buffer is still current when this hook is run.
11728 A good way to use this is to tell a desktop calenndar application to re-read
11729 the iCalendar file.")
11730
11731 (defun org-print-icalendar-entries (&optional combine category)
11732 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11733 When COMBINE is non nil, add the category to each line."
11734 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11735 (dts (org-ical-ts-to-string
11736 (format-time-string (cdr org-time-stamp-formats) (current-time))
11737 "DTSTART"))
11738 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11739 (save-excursion
11740 (goto-char (point-min))
11741 (while (re-search-forward org-ts-regexp nil t)
11742 (setq pos (match-beginning 0)
11743 ts (match-string 0)
11744 inc t
11745 hd (org-get-heading))
11746 (if (looking-at re2)
11747 (progn
11748 (goto-char (match-end 0))
11749 (setq ts2 (match-string 1) inc nil))
11750 (setq ts2 ts
11751 tmp (buffer-substring (max (point-min)
11752 (- pos org-ds-keyword-length))
11753 pos)
11754 deadlinep (string-match org-deadline-regexp tmp)
11755 scheduledp (string-match org-scheduled-regexp tmp)
11756 ;; donep (org-entry-is-done-p)
11757 ))
11758 (if (or (string-match org-tr-regexp hd)
11759 (string-match org-ts-regexp hd))
11760 (setq hd (replace-match "" t t hd)))
11761 (if combine
11762 (setq hd (concat hd " (category " category ")")))
11763 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11764 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11765 (princ (format "BEGIN:VEVENT
11766 %s
11767 %s
11768 SUMMARY:%s
11769 END:VEVENT\n"
11770 (org-ical-ts-to-string ts "DTSTART")
11771 (org-ical-ts-to-string ts2 "DTEND" inc)
11772 hd)))
11773 (when org-icalendar-include-todo
11774 (goto-char (point-min))
11775 (while (re-search-forward org-todo-line-regexp nil t)
11776 (setq state (match-string 1))
11777 (unless (equal state org-done-string)
11778 (setq hd (match-string 3))
11779 (if (string-match org-priority-regexp hd)
11780 (setq pri (string-to-char (match-string 2 hd))
11781 hd (concat (substring hd 0 (match-beginning 1))
11782 (substring hd (- (match-end 1)))))
11783 (setq pri org-default-priority))
11784 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11785 (- org-lowest-priority ?A))))))
11786
11787 (princ (format "BEGIN:VTODO
11788 %s
11789 SUMMARY:%s
11790 SEQUENCE:1
11791 PRIORITY:%d
11792 END:VTODO\n"
11793 dts hd pri))))))))
11794
11795 (defun org-start-icalendar-file (name)
11796 "Start an iCalendar file by inserting the header."
11797 (let ((user user-full-name)
11798 (name (or name "unknown"))
11799 (timezone (cadr (current-time-zone))))
11800 (princ
11801 (format "BEGIN:VCALENDAR
11802 VERSION:2.0
11803 X-WR-CALNAME:%s
11804 PRODID:-//%s//Emacs with Org-mode//EN
11805 X-WR-TIMEZONE:%s
11806 CALSCALE:GREGORIAN\n" name user timezone))))
11807
11808 (defun org-finish-icalendar-file ()
11809 "Finish an iCalendar file by inserting the END statement."
11810 (princ "END:VCALENDAR\n"))
11811
11812 (defun org-ical-ts-to-string (s keyword &optional inc)
11813 "Take a time string S and convert it to iCalendar format.
11814 KEYWORD is added in front, to make a complete line like DTSTART....
11815 When INC is non-nil, increase the hour by two (if time string contains
11816 a time), or the day by one (if it does not contain a time)."
11817 (let ((t1 (org-parse-time-string s 'nodefault))
11818 t2 fmt have-time time)
11819 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11820 (setq t2 t1 have-time t)
11821 (setq t2 (org-parse-time-string s)))
11822 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11823 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11824 (when inc
11825 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11826 (setq time (encode-time s mi h d m y)))
11827 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11828 (concat keyword (format-time-string fmt time))))
11829
11830
11831 ;;; Key bindings
11832
11833 ;; - Bindings in Org-mode map are currently
11834 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11835 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
11836 ;; e (?) useful from outline-mode
11837 ;; i k @ expendable from outline-mode
11838 ;; 0123456789 % & ()_{} " ` free
11839
11840 ;; Make `C-c C-x' a prefix key
11841 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11842
11843 ;; TAB key with modifiers
11844 (define-key org-mode-map "\C-i" 'org-cycle)
11845 (define-key org-mode-map [(meta tab)] 'org-complete)
11846 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11847 ;; The following line is necessary under Suse GNU/Linux
11848 (unless org-xemacs-p
11849 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11850 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11851
11852 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11853 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11854 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11855 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11856 (define-key org-mode-map [(meta return)] 'org-meta-return)
11857 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11858 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11859
11860 ;; Cursor keys with modifiers
11861 (define-key org-mode-map [(meta left)] 'org-metaleft)
11862 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11863 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11864 (define-key org-mode-map [(meta right)] 'org-metaright)
11865 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11866 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11867 (define-key org-mode-map [(meta up)] 'org-metaup)
11868 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11869 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11870 (define-key org-mode-map [(meta down)] 'org-metadown)
11871 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11872 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11873
11874 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11875 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11876 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11877 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11878 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11879 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11880 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11881 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11882 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11883 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11884 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11885 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11886 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11887 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11888 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11889 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11890
11891 ;; All the other keys
11892 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11893 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11894 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11895 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11896 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11897 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11898 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11899 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11900 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11901 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11902 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11903 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11904 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11905 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11906 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
11907 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
11908 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11909 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11910 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11911 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11912 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11913 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11914 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11915 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11916 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
11917 (define-key org-mode-map "\C-c]" 'org-remove-file)
11918 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
11919 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
11920 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
11921 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11922 (define-key org-mode-map "\C-m" 'org-return)
11923 (define-key org-mode-map "\C-c?" 'org-table-current-column)
11924 (define-key org-mode-map "\C-c " 'org-table-blank-field)
11925 (define-key org-mode-map "\C-c+" 'org-table-sum)
11926 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
11927 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
11928 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
11929 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
11930 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11931 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
11932 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11933 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
11934 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
11935 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
11936 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
11937 ;; OPML support is only an option for the future
11938 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
11939 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
11940 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
11941 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
11942 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
11943 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11944 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
11945 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11946 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
11947 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
11948 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
11949
11950 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11951 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11952 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11953 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11954
11955 (defsubst org-table-p () (org-at-table-p))
11956
11957 (defun org-self-insert-command (N)
11958 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11959 If the cursor is in a table looking at whitespace, the whitespace is
11960 overwritten, and the table is not marked as requiring realignment."
11961 (interactive "p")
11962 (if (and (org-table-p)
11963 (or
11964 (and org-table-auto-blank-field
11965 (member last-command
11966 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11967 (org-table-blank-field))
11968 t)
11969 (eq N 1)
11970 (looking-at "[^|\n]* +|"))
11971 (let (org-table-may-need-update)
11972 (goto-char (1- (match-end 0)))
11973 (delete-backward-char 1)
11974 (goto-char (match-beginning 0))
11975 (self-insert-command N))
11976 (setq org-table-may-need-update t)
11977 (self-insert-command N)))
11978
11979 ;; FIXME:
11980 ;; The following two functions might still be optimized to trigger
11981 ;; re-alignment less frequently.
11982
11983 (defun org-delete-backward-char (N)
11984 "Like `delete-backward-char', insert whitespace at field end in tables.
11985 When deleting backwards, in tables this function will insert whitespace in
11986 front of the next \"|\" separator, to keep the table aligned. The table will
11987 still be marked for re-alignment, because a narrow field may lead to a
11988 reduced column width."
11989 (interactive "p")
11990 (if (and (org-table-p)
11991 (eq N 1)
11992 (string-match "|" (buffer-substring (point-at-bol) (point)))
11993 (looking-at ".*?|"))
11994 (let ((pos (point)))
11995 (backward-delete-char N)
11996 (skip-chars-forward "^|")
11997 (insert " ")
11998 (goto-char (1- pos)))
11999 (backward-delete-char N)))
12000
12001 (defun org-delete-char (N)
12002 "Like `delete-char', but insert whitespace at field end in tables.
12003 When deleting characters, in tables this function will insert whitespace in
12004 front of the next \"|\" separator, to keep the table aligned. The table
12005 will still be marked for re-alignment, because a narrow field may lead to
12006 a reduced column width."
12007 (interactive "p")
12008 (if (and (org-table-p)
12009 (not (bolp))
12010 (not (= (char-after) ?|))
12011 (eq N 1))
12012 (if (looking-at ".*?|")
12013 (let ((pos (point)))
12014 (replace-match (concat
12015 (substring (match-string 0) 1 -1)
12016 " |"))
12017 (goto-char pos)))
12018 (delete-char N)))
12019
12020 ;; How to do this: Measure non-white length of current string
12021 ;; If equal to column width, we should realign.
12022
12023 (defun org-remap (map &rest commands)
12024 "In MAP, remap the functions given in COMMANDS.
12025 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12026 (let (new old)
12027 (while commands
12028 (setq old (pop commands) new (pop commands))
12029 (if (fboundp 'command-remapping)
12030 (define-key map (vector 'remap old) new)
12031 (substitute-key-definition old new map global-map)))))
12032
12033 (when (eq org-enable-table-editor 'optimized)
12034 ;; If the user wants maximum table support, we need to hijack
12035 ;; some standard editing functions
12036 (org-remap org-mode-map
12037 'self-insert-command 'org-self-insert-command
12038 'delete-char 'org-delete-char
12039 'delete-backward-char 'org-delete-backward-char)
12040 (define-key org-mode-map "|" 'org-force-self-insert))
12041
12042 (defun org-shiftcursor-error ()
12043 "Throw an error because Shift-Cursor command was applied in wrong context."
12044 (error "This command is active in special context like tables, headlines or timestamps"))
12045
12046 (defun org-shifttab ()
12047 "Global visibility cycling or move to previous table field.
12048 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12049 See the individual commands for more information."
12050 (interactive)
12051 (cond
12052 ((org-at-table-p) (org-table-previous-field))
12053 (t (org-cycle '(4)))))
12054
12055 (defun org-shiftmetaleft ()
12056 "Promote subtree or delete table column.
12057 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12058 See the individual commands for more information."
12059 (interactive)
12060 (cond
12061 ((org-at-table-p) (org-table-delete-column))
12062 ((org-on-heading-p) (org-promote-subtree))
12063 ((org-at-item-p) (call-interactively 'org-outdent-item))
12064 (t (org-shiftcursor-error))))
12065
12066 (defun org-shiftmetaright ()
12067 "Demote subtree or insert table column.
12068 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12069 See the individual commands for more information."
12070 (interactive)
12071 (cond
12072 ((org-at-table-p) (org-table-insert-column))
12073 ((org-on-heading-p) (org-demote-subtree))
12074 ((org-at-item-p) (call-interactively 'org-indent-item))
12075 (t (org-shiftcursor-error))))
12076
12077 (defun org-shiftmetaup (&optional arg)
12078 "Move subtree up or kill table row.
12079 Calls `org-move-subtree-up' or `org-table-kill-row' or
12080 `org-move-item-up' depending on context. See the individual commands
12081 for more information."
12082 (interactive "P")
12083 (cond
12084 ((org-at-table-p) (org-table-kill-row))
12085 ((org-on-heading-p) (org-move-subtree-up arg))
12086 ((org-at-item-p) (org-move-item-up arg))
12087 (t (org-shiftcursor-error))))
12088 (defun org-shiftmetadown (&optional arg)
12089 "Move subtree down or insert table row.
12090 Calls `org-move-subtree-down' or `org-table-insert-row' or
12091 `org-move-item-down', depending on context. See the individual
12092 commands for more information."
12093 (interactive "P")
12094 (cond
12095 ((org-at-table-p) (org-table-insert-row arg))
12096 ((org-on-heading-p) (org-move-subtree-down arg))
12097 ((org-at-item-p) (org-move-item-down arg))
12098 (t (org-shiftcursor-error))))
12099
12100 (defun org-metaleft (&optional arg)
12101 "Promote heading or move table column to left.
12102 Calls `org-do-promote' or `org-table-move-column', depending on context.
12103 With no specific context, calls the Emacs default `backward-word'.
12104 See the individual commands for more information."
12105 (interactive "P")
12106 (cond
12107 ((org-at-table-p) (org-table-move-column 'left))
12108 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12109 (t (backward-word (prefix-numeric-value arg)))))
12110
12111 (defun org-metaright (&optional arg)
12112 "Demote subtree or move table column to right.
12113 Calls `org-do-demote' or `org-table-move-column', depending on context.
12114 With no specific context, calls the Emacs default `forward-word'.
12115 See the individual commands for more information."
12116 (interactive "P")
12117 (cond
12118 ((org-at-table-p) (org-table-move-column nil))
12119 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12120 (t (forward-word (prefix-numeric-value arg)))))
12121
12122 (defun org-metaup (&optional arg)
12123 "Move subtree up or move table row up.
12124 Calls `org-move-subtree-up' or `org-table-move-row' or
12125 `org-move-item-up', depending on context. See the individual commands
12126 for more information."
12127 (interactive "P")
12128 (cond
12129 ((org-at-table-p) (org-table-move-row 'up))
12130 ((org-on-heading-p) (org-move-subtree-up arg))
12131 ((org-at-item-p) (org-move-item-up arg))
12132 (t (org-shiftcursor-error))))
12133
12134 (defun org-metadown (&optional arg)
12135 "Move subtree down or move table row down.
12136 Calls `org-move-subtree-down' or `org-table-move-row' or
12137 `org-move-item-down', depending on context. See the individual
12138 commands for more information."
12139 (interactive "P")
12140 (cond
12141 ((org-at-table-p) (org-table-move-row nil))
12142 ((org-on-heading-p) (org-move-subtree-down arg))
12143 ((org-at-item-p) (org-move-item-down arg))
12144 (t (org-shiftcursor-error))))
12145
12146 (defun org-shiftup (&optional arg)
12147 "Increase item in timestamp or increase priority of current item.
12148 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12149 See the individual commands for more information."
12150 (interactive "P")
12151 (cond
12152 ((org-at-timestamp-p) (org-timestamp-up arg))
12153 (t (org-priority-up))))
12154
12155 (defun org-shiftdown (&optional arg)
12156 "Decrease item in timestamp or decrease priority of current item.
12157 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12158 See the individual commands for more information."
12159 (interactive "P")
12160 (cond
12161 ((org-at-timestamp-p) (org-timestamp-down arg))
12162 (t (org-priority-down))))
12163
12164 (defun org-shiftright ()
12165 "Next TODO keyword or timestamp one day later, depending on context."
12166 (interactive)
12167 (cond
12168 ((org-at-timestamp-p) (org-timestamp-up-day))
12169 ((org-on-heading-p) (org-todo 'right))
12170 (t (org-shiftcursor-error))))
12171
12172 (defun org-shiftleft ()
12173 "Previous TODO keyword or timestamp one day earlier, depending on context."
12174 (interactive)
12175 (cond
12176 ((org-at-timestamp-p) (org-timestamp-down-day))
12177 ((org-on-heading-p) (org-todo 'left))
12178 (t (org-shiftcursor-error))))
12179
12180 (defun org-copy-special ()
12181 "Copy region in table or copy current subtree.
12182 Calls `org-table-copy' or `org-copy-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-copy-region 'org-copy-subtree)))
12187
12188 (defun org-cut-special ()
12189 "Cut region in table or cut current subtree.
12190 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12191 See the individual commands for more information."
12192 (interactive)
12193 (call-interactively
12194 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12195
12196 (defun org-paste-special (arg)
12197 "Paste rectangular region into table, or past subtree relative to level.
12198 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12199 See the individual commands for more information."
12200 (interactive "P")
12201 (if (org-at-table-p)
12202 (org-table-paste-rectangle)
12203 (org-paste-subtree arg)))
12204
12205 (defun org-ctrl-c-ctrl-c (&optional arg)
12206 "Call realign table, or recognize a table.el table, or update keywords.
12207 When the cursor is inside a table created by the table.el package,
12208 activate that table. Otherwise, if the cursor is at a normal table
12209 created with org.el, re-align that table. This command works even if
12210 the automatic table editor has been turned off.
12211
12212 If the cursor is in a headline, prompt for tags and insert them into
12213 the current line, aligned to `org-tags-column'. When in a headline and
12214 called with prefix arg, realign all tags in the current buffer.
12215
12216 If the cursor is in one of the special #+KEYWORD lines, this triggers
12217 scanning the buffer for these lines and updating the information.
12218 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
12219 (interactive "P")
12220 (let ((org-enable-table-editor t))
12221 (cond
12222 ((org-on-target-p) (org-update-radio-target-regexp))
12223 ((org-on-heading-p) (org-set-tags arg))
12224 ((org-at-table.el-p)
12225 (require 'table)
12226 (beginning-of-line 1)
12227 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12228 (table-recognize-table))
12229 ((org-at-table-p)
12230 (org-table-maybe-eval-formula)
12231 (if arg
12232 (org-table-recalculate t)
12233 (org-table-maybe-recalculate-line))
12234 (org-table-align))
12235 ((org-at-item-p)
12236 (org-renumber-ordered-list (prefix-numeric-value arg)))
12237 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12238 (cond
12239 ((equal (match-string 1) "TBLFM")
12240 ;; Recalculate the table before this line
12241 (save-excursion
12242 (beginning-of-line 1)
12243 (skip-chars-backward " \r\n\t")
12244 (if (org-at-table-p) (org-table-recalculate t))))
12245 (t
12246 (org-mode-restart))))
12247 ((org-region-active-p)
12248 (org-table-convert-region (region-beginning) (region-end) arg))
12249 ((condition-case nil
12250 (and (region-beginning) (region-end))
12251 (error nil))
12252 (if (y-or-n-p "Convert inactive region to table? ")
12253 (org-table-convert-region (region-beginning) (region-end) arg)
12254 (error "Abort")))
12255 (t (error "C-c C-c can do nothing useful at this location.")))))
12256
12257 (defun org-mode-restart ()
12258 "Restart Org-mode, to scan again for special lines.
12259 Also updates the keyword regular expressions."
12260 (interactive)
12261 (let ((org-inhibit-startup t)) (org-mode))
12262 (message "Org-mode restarted to refresh keyword and special line setup"))
12263
12264 (defun org-return ()
12265 "Goto next table row or insert a newline.
12266 Calls `org-table-next-row' or `newline', depending on context.
12267 See the individual commands for more information."
12268 (interactive)
12269 (cond
12270 ((org-at-table-p)
12271 (org-table-justify-field-maybe)
12272 (org-table-next-row))
12273 (t (newline))))
12274
12275 (defun org-meta-return (&optional arg)
12276 "Insert a new heading or wrap a region in a table.
12277 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12278 See the individual commands for more information."
12279 (interactive "P")
12280 (cond
12281 ((org-at-table-p)
12282 (org-table-wrap-region arg))
12283 (t (org-insert-heading arg))))
12284
12285 ;;; Menu entries
12286
12287 ;; Define the Org-mode menus
12288 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12289 '("Tbl"
12290 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
12291 ["Next Field" org-cycle (org-at-table-p)]
12292 ["Previous Field" org-shifttab (org-at-table-p)]
12293 ["Next Row" org-return (org-at-table-p)]
12294 "--"
12295 ["Blank Field" org-table-blank-field (org-at-table-p)]
12296 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12297 "--"
12298 ("Column"
12299 ["Move Column Left" org-metaleft (org-at-table-p)]
12300 ["Move Column Right" org-metaright (org-at-table-p)]
12301 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12302 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12303 ("Row"
12304 ["Move Row Up" org-metaup (org-at-table-p)]
12305 ["Move Row Down" org-metadown (org-at-table-p)]
12306 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12307 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12308 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12309 "--"
12310 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
12311 ("Rectangle"
12312 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12313 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12314 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12315 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12316 "--"
12317 ("Calculate"
12318 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12319 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12320 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12321 "--"
12322 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12323 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12324 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12325 "--"
12326 ["Sum Column/Rectangle" org-table-sum
12327 (or (org-at-table-p) (org-region-active-p))]
12328 ["Which Column?" org-table-current-column (org-at-table-p)])
12329 ["Debug Formulas"
12330 (setq org-table-formula-debug (not org-table-formula-debug))
12331 :style toggle :selected org-table-formula-debug]
12332 "--"
12333 ["Invisible Vlines" org-table-toggle-vline-visibility
12334 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
12335 "--"
12336 ["Create" org-table-create (and (not (org-at-table-p))
12337 org-enable-table-editor)]
12338 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
12339 ["Import from File" org-table-import (not (org-at-table-p))]
12340 ["Export to File" org-table-export (org-at-table-p)]
12341 "--"
12342 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12343
12344 (easy-menu-define org-org-menu org-mode-map "Org menu"
12345 '("Org"
12346 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
12347 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
12348 ["Sparse Tree" org-occur t]
12349 ["Show All" show-all t]
12350 "--"
12351 ["New Heading" org-insert-heading t]
12352 ("Navigate Headings"
12353 ["Up" outline-up-heading t]
12354 ["Next" outline-next-visible-heading t]
12355 ["Previous" outline-previous-visible-heading t]
12356 ["Next Same Level" outline-forward-same-level t]
12357 ["Previous Same Level" outline-backward-same-level t]
12358 "--"
12359 ["Jump" org-goto t])
12360 ("Edit Structure"
12361 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12362 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12363 "--"
12364 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12365 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12366 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12367 "--"
12368 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12369 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12370 ["Demote Heading" org-metaright (not (org-at-table-p))]
12371 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12372 "--"
12373 ["Archive Subtree" org-archive-subtree t]
12374 "--"
12375 ["Convert file to odd levels" org-convert-to-odd-levels t])
12376 "--"
12377 ("TODO Lists"
12378 ["TODO/DONE/-" org-todo t]
12379 ["Show TODO Tree" org-show-todo-tree t]
12380 ["Global TODO list" org-todo-list t]
12381 "--"
12382 ["Set Priority" org-priority t]
12383 ["Priority Up" org-shiftup t]
12384 ["Priority Down" org-shiftdown t])
12385 ("Dates and Scheduling"
12386 ["Timestamp" org-time-stamp t]
12387 ["Timestamp (inactive)" org-time-stamp-inactive t]
12388 ("Change Date"
12389 ["1 Day Later" org-timestamp-up-day t]
12390 ["1 Day Earlier" org-timestamp-down-day t]
12391 ["1 ... Later" org-shiftup t]
12392 ["1 ... Earlier" org-shiftdown t])
12393 ["Compute Time Range" org-evaluate-time-range t]
12394 ["Schedule Item" org-schedule t]
12395 ["Deadline" org-deadline t]
12396 "--"
12397 ["Goto Calendar" org-goto-calendar t]
12398 ["Date from Calendar" org-date-from-calendar t])
12399 "--"
12400 ["Agenda Command" org-agenda t]
12401 ("File List for Agenda")
12402 ("Special views current file"
12403 ["TODO Tree" org-show-todo-tree t]
12404 ["Check Deadlines" org-check-deadlines t]
12405 ["Timeline" org-timeline t]
12406 ["Tags Tree" org-tags-sparse-tree t])
12407 "--"
12408 ("Hyperlinks"
12409 ["Store Link (Global)" org-store-link t]
12410 ["Insert Link" org-insert-link t]
12411 ["Follow Link" org-open-at-point t])
12412 "--"
12413 ("Export"
12414 ["ASCII" org-export-as-ascii t]
12415 ["Extract Visible Text" org-export-copy-visible t]
12416 ["HTML" org-export-as-html t]
12417 ["HTML and Open" org-export-as-html-and-open t]
12418 ; ["OPML" org-export-as-opml nil]
12419 "--"
12420 ["iCalendar this file" org-export-icalendar-this-file t]
12421 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
12422 :active t :keys "C-c C-x C-i"]
12423 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
12424 "--"
12425 ["Option Template" org-insert-export-options-template t]
12426 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
12427 "--"
12428 ("Documentation"
12429 ["Show Version" org-version t]
12430 ["Info Documentation" org-info t])
12431 ("Customize"
12432 ["Browse Org Group" org-customize t]
12433 "--"
12434 ["Build Full Customize Menu" org-create-customize-menu
12435 (fboundp 'customize-menu-create)])
12436 "--"
12437 ["Refresh setup" org-mode-restart t]
12438 ))
12439
12440 (defun org-info (&optional node)
12441 "Read documentation for Org-mode in the info system.
12442 With optional NODE, go directly to that node."
12443 (interactive)
12444 (require 'info)
12445 (Info-goto-node (format "(org)%s" (or node ""))))
12446
12447 (defun org-install-agenda-files-menu ()
12448 (easy-menu-change
12449 '("Org") "File List for Agenda"
12450 (append
12451 (list
12452 ["Edit File List" (customize-variable 'org-agenda-files) t]
12453 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12454 ["Remove Current File from List" org-remove-file t]
12455 ["Cycle through agenda files" org-cycle-agenda-files t]
12456 "--")
12457 (mapcar 'org-file-menu-entry org-agenda-files))))
12458
12459 ;;; Documentation
12460
12461 (defun org-customize ()
12462 "Call the customize function with org as argument."
12463 (interactive)
12464 (customize-browse 'org))
12465
12466 (defun org-create-customize-menu ()
12467 "Create a full customization menu for Org-mode, insert it into the menu."
12468 (interactive)
12469 (if (fboundp 'customize-menu-create)
12470 (progn
12471 (easy-menu-change
12472 '("Org") "Customize"
12473 `(["Browse Org group" org-customize t]
12474 "--"
12475 ,(customize-menu-create 'org)
12476 ["Set" Custom-set t]
12477 ["Save" Custom-save t]
12478 ["Reset to Current" Custom-reset-current t]
12479 ["Reset to Saved" Custom-reset-saved t]
12480 ["Reset to Standard Settings" Custom-reset-standard t]))
12481 (message "\"Org\"-menu now contains full customization menu"))
12482 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12483
12484 ;;; Miscellaneous stuff
12485
12486 (defun org-move-line-down (arg)
12487 "Move the current line down. With prefix argument, move it past ARG lines."
12488 (interactive "p")
12489 (let ((col (current-column))
12490 beg end pos)
12491 (beginning-of-line 1) (setq beg (point))
12492 (beginning-of-line 2) (setq end (point))
12493 (beginning-of-line (+ 1 arg))
12494 (setq pos (move-marker (make-marker) (point)))
12495 (insert (delete-and-extract-region beg end))
12496 (goto-char pos)
12497 (move-to-column col)))
12498
12499 (defun org-move-line-up (arg)
12500 "Move the current line up. With prefix argument, move it past ARG lines."
12501 (interactive "p")
12502 (let ((col (current-column))
12503 beg end pos)
12504 (beginning-of-line 1) (setq beg (point))
12505 (beginning-of-line 2) (setq end (point))
12506 (beginning-of-line (- arg))
12507 (setq pos (move-marker (make-marker) (point)))
12508 (insert (delete-and-extract-region beg end))
12509 (goto-char pos)
12510 (move-to-column col)))
12511
12512 ;; Paragraph filling stuff.
12513 ;; We want this to be just right, so use the full arsenal.
12514 ;; FIXME: This very likely does not work correctly for XEmacs, because the
12515 ;; filladapt package works slightly differently.
12516
12517 (defun org-set-autofill-regexps ()
12518 (interactive)
12519 ;; In the paragraph separator we include headlines, because filling
12520 ;; text in a line directly attached to a headline would otherwise
12521 ;; fill the headline as well.
12522 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
12523 ;; The paragraph starter includes hand-formatted lists.
12524 (set (make-local-variable 'paragraph-start)
12525 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
12526 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
12527 ;; But only if the user has not turned off tables or fixed-width regions
12528 (set (make-local-variable 'auto-fill-inhibit-regexp)
12529 (concat "\\*\\|#"
12530 (if (or org-enable-table-editor org-enable-fixed-width-editor)
12531 (concat
12532 "\\|[ \t]*["
12533 (if org-enable-table-editor "|" "")
12534 (if org-enable-fixed-width-editor ":" "")
12535 "]"))))
12536 ;; We use our own fill-paragraph function, to make sure that tables
12537 ;; and fixed-width regions are not wrapped. That function will pass
12538 ;; through to `fill-paragraph' when appropriate.
12539 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
12540 ;; Adaptive filling: To get full control, first make sure that
12541 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
12542 (setq adaptive-fill-regexp "\000")
12543 (setq adaptive-fill-function 'org-adaptive-fill-function))
12544
12545 (defun org-fill-paragraph (&optional justify)
12546 "Re-align a table, pass through to fill-paragraph if no table."
12547 (let ((table-p (org-at-table-p))
12548 (table.el-p (org-at-table.el-p)))
12549 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
12550 (table.el-p t) ; skip table.el tables
12551 (table-p (org-table-align) t) ; align org-mode tables
12552 (t nil)))) ; call paragraph-fill
12553
12554 ;; For reference, this is the default value of adaptive-fill-regexp
12555 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
12556
12557 (defun org-adaptive-fill-function ()
12558 "Return a fill prefix for org-mode files.
12559 In particular, this makes sure hanging paragraphs for hand-formatted lists
12560 work correctly."
12561 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
12562 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
12563
12564 ;; Functions needed for Emacs/XEmacs region compatibility
12565
12566 (defun org-add-hook (hook function &optional append local)
12567 "Add-hook, compatible with both Emacsen."
12568 (if (and local org-xemacs-p)
12569 (add-local-hook hook function append)
12570 (add-hook hook function append local)))
12571
12572 (defun org-region-active-p ()
12573 "Is `transient-mark-mode' on and the region active?
12574 Works on both Emacs and XEmacs."
12575 (if org-ignore-region
12576 nil
12577 (if org-xemacs-p
12578 (and zmacs-regions (region-active-p))
12579 (and transient-mark-mode mark-active))))
12580
12581 (defun org-add-to-invisibility-spec (arg)
12582 "Add elements to `buffer-invisibility-spec'.
12583 See documentation for `buffer-invisibility-spec' for the kind of elements
12584 that can be added."
12585 (cond
12586 ((fboundp 'add-to-invisibility-spec)
12587 (add-to-invisibility-spec arg))
12588 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
12589 (setq buffer-invisibility-spec (list arg)))
12590 (t
12591 (setq buffer-invisibility-spec
12592 (cons arg buffer-invisibility-spec)))))
12593
12594 (defun org-remove-from-invisibility-spec (arg)
12595 "Remove elements from `buffer-invisibility-spec'."
12596 (if (fboundp 'remove-from-invisibility-spec)
12597 (remove-from-invisibility-spec arg)
12598 (if (consp buffer-invisibility-spec)
12599 (setq buffer-invisibility-spec
12600 (delete arg buffer-invisibility-spec)))))
12601
12602 (defun org-in-invisibility-spec-p (arg)
12603 "Is ARG a member of `buffer-invisibility-spec'?"
12604 (if (consp buffer-invisibility-spec)
12605 (member arg buffer-invisibility-spec)
12606 nil))
12607
12608 (defun org-image-file-name-regexp ()
12609 "Return regexp matching the file names of images."
12610 (if (fboundp 'image-file-name-regexp)
12611 (image-file-name-regexp)
12612 (let ((image-file-name-extensions
12613 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
12614 "xbm" "xpm" "pbm" "pgm" "ppm")))
12615 (concat "\\."
12616 (regexp-opt (nconc (mapcar 'upcase
12617 image-file-name-extensions)
12618 image-file-name-extensions)
12619 t)
12620 "\\'"))))
12621
12622 ;; Functions needed for compatibility with old outline.el.
12623
12624 ;; Programming for the old outline.el (that uses selective display
12625 ;; instead of `invisible' text properties) is a nightmare, mostly
12626 ;; because regular expressions can no longer be anchored at
12627 ;; beginning/end of line. Therefore a number of function need special
12628 ;; treatment when the old outline.el is being used.
12629
12630 ;; The following functions capture almost the entire compatibility code
12631 ;; between the different versions of outline-mode. The only other
12632 ;; places where this is important are the font-lock-keywords, and in
12633 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
12634
12635 ;; C-a should go to the beginning of a *visible* line, also in the
12636 ;; new outline.el. I guess this should be patched into Emacs?
12637 (defun org-beginning-of-line ()
12638 "Go to the beginning of the current line. If that is invisible, continue
12639 to a visible line beginning. This makes the function of C-a more intuitive."
12640 (interactive)
12641 (beginning-of-line 1)
12642 (if (bobp)
12643 nil
12644 (backward-char 1)
12645 (if (org-invisible-p)
12646 (while (and (not (bobp)) (org-invisible-p))
12647 (backward-char 1)
12648 (beginning-of-line 1))
12649 (forward-char 1))))
12650
12651 (when org-noutline-p
12652 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
12653 ;; FIXME: should I use substitute-key-definition to reach other bindings
12654 ;; of beginning-of-line?
12655
12656 (defun org-invisible-p ()
12657 "Check if point is at a character currently not visible."
12658 (if org-noutline-p
12659 ;; Early versions of noutline don't have `outline-invisible-p'.
12660 (if (fboundp 'outline-invisible-p)
12661 (outline-invisible-p)
12662 (get-char-property (point) 'invisible))
12663 (save-excursion
12664 (skip-chars-backward "^\r\n")
12665 (equal (char-before) ?\r))))
12666
12667 (defun org-invisible-p2 ()
12668 "Check if point is at a character currently not visible."
12669 (save-excursion
12670 (if org-noutline-p
12671 (progn
12672 (if (and (eolp) (not (bobp))) (backward-char 1))
12673 ;; Early versions of noutline don't have `outline-invisible-p'.
12674 (if (fboundp 'outline-invisible-p)
12675 (outline-invisible-p)
12676 (get-char-property (point) 'invisible)))
12677 (skip-chars-backward "^\r\n")
12678 (equal (char-before) ?\r))))
12679
12680 (defun org-back-to-heading (&optional invisible-ok)
12681 "Move to previous heading line, or beg of this line if it's a heading.
12682 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
12683 (if org-noutline-p
12684 (outline-back-to-heading invisible-ok)
12685 (if (and (memq (char-before) '(?\n ?\r))
12686 (looking-at outline-regexp))
12687 t
12688 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
12689 outline-regexp)
12690 nil t)
12691 (if invisible-ok
12692 (progn (goto-char (match-end 1))
12693 (looking-at outline-regexp)))
12694 (error "Before first heading")))))
12695
12696 (defun org-on-heading-p (&optional invisible-ok)
12697 "Return t if point is on a (visible) heading line.
12698 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12699 (if org-noutline-p
12700 (outline-on-heading-p 'invisible-ok)
12701 (save-excursion
12702 (skip-chars-backward "^\n\r")
12703 (and (looking-at outline-regexp)
12704 (or invisible-ok
12705 (bobp)
12706 (equal (char-before) ?\n))))))
12707
12708 (defun org-on-target-p ()
12709 (let ((pos (point)))
12710 (save-excursion
12711 (skip-chars-forward "<")
12712 (and (re-search-backward "<<" nil t)
12713 (or (looking-at org-target-regexp)
12714 (looking-at org-radio-target-regexp))
12715 (<= (match-beginning 0) pos)
12716 (>= (match-end 0) pos)))))
12717
12718 (defun org-up-heading-all (arg)
12719 "Move to the heading line of which the present line is a subheading.
12720 This function considers both visible and invisible heading lines.
12721 With argument, move up ARG levels."
12722 (if org-noutline-p
12723 (if (fboundp 'outline-up-heading-all)
12724 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12725 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12726 (org-back-to-heading t)
12727 (looking-at outline-regexp)
12728 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12729 (error "Cannot move up %d levels" arg)
12730 (re-search-backward
12731 (concat "[\n\r]" (regexp-quote
12732 (make-string (- (match-end 0) (match-beginning 0) arg)
12733 ?*))
12734 "[^*]"))
12735 (forward-char 1))))
12736
12737 (defun org-show-hidden-entry ()
12738 "Show an entry where even the heading is hidden."
12739 (save-excursion
12740 (if (not org-noutline-p)
12741 (progn
12742 (org-back-to-heading t)
12743 (org-flag-heading nil)))
12744 (org-show-entry)))
12745
12746 (defun org-check-occur-regexp (regexp)
12747 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12748 Of course, only for the old outline mode."
12749 (if org-noutline-p
12750 regexp
12751 (if (string-match "^\\^" regexp)
12752 (concat "[\n\r]" (substring regexp 1))
12753 regexp)))
12754
12755 (defun org-flag-heading (flag &optional entry)
12756 "Flag the current heading. FLAG non-nil means make invisible.
12757 When ENTRY is non-nil, show the entire entry."
12758 (save-excursion
12759 (org-back-to-heading t)
12760 (if (not org-noutline-p)
12761 ;; Make the current headline visible
12762 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12763 ;; Check if we should show the entire entry
12764 (if entry
12765 (progn
12766 (org-show-entry)
12767 (save-excursion ;; FIXME: Is this the fix for points in the -|
12768 ;; middle of text? |
12769 (and (outline-next-heading) ;; |
12770 (org-flag-heading nil)))) ; show the next heading _|
12771 (outline-flag-region (max 1 (1- (point)))
12772 (save-excursion (outline-end-of-heading) (point))
12773 (if org-noutline-p
12774 flag
12775 (if flag ?\r ?\n))))))
12776
12777 (defun org-end-of-subtree (&optional invisible-OK)
12778 ;; This is an exact copy of the original function, but it uses
12779 ;; `org-back-to-heading', to make it work also in invisible
12780 ;; trees. And is uses an invisible-OK argument.
12781 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
12782 (org-back-to-heading invisible-OK)
12783 (let ((first t)
12784 (level (funcall outline-level)))
12785 (while (and (not (eobp))
12786 (or first (> (funcall outline-level) level)))
12787 (setq first nil)
12788 (outline-next-heading))
12789 (if (memq (preceding-char) '(?\n ?\^M))
12790 (progn
12791 ;; Go to end of line before heading
12792 (forward-char -1)
12793 (if (memq (preceding-char) '(?\n ?\^M))
12794 ;; leave blank line before heading
12795 (forward-char -1))))))
12796
12797 (defun org-show-subtree ()
12798 "Show everything after this heading at deeper levels."
12799 (outline-flag-region
12800 (point)
12801 (save-excursion
12802 (outline-end-of-subtree) (outline-next-heading) (point))
12803 (if org-noutline-p nil ?\n)))
12804
12805 (defun org-show-entry ()
12806 "Show the body directly following this heading.
12807 Show the heading too, if it is currently invisible."
12808 (interactive)
12809 (save-excursion
12810 (org-back-to-heading t)
12811 (outline-flag-region
12812 (1- (point))
12813 (save-excursion
12814 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12815 (or (match-beginning 1) (point-max)))
12816 (if org-noutline-p nil ?\n))))
12817
12818
12819 (defun org-make-options-regexp (kwds)
12820 "Make a regular expression for keyword lines."
12821 (concat
12822 (if org-noutline-p "^" "[\n\r]")
12823 "#?[ \t]*\\+\\("
12824 (mapconcat 'regexp-quote kwds "\\|")
12825 "\\):[ \t]*"
12826 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12827
12828 ;; Make `bookmark-jump' show the jump location if it was hidden.
12829 (eval-after-load "bookmark"
12830 '(if (boundp 'bookmark-after-jump-hook)
12831 ;; We can use the hook
12832 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12833 ;; Hook not available, use advice
12834 (defadvice bookmark-jump (after org-make-visible activate)
12835 "Make the position visible."
12836 (org-bookmark-jump-unhide))))
12837
12838 (defun org-bookmark-jump-unhide ()
12839 "Unhide the current position, to show the bookmark location."
12840 (and (eq major-mode 'org-mode)
12841 (or (org-invisible-p)
12842 (save-excursion (goto-char (max (point-min) (1- (point))))
12843 (org-invisible-p)))
12844 (org-show-hierarchy-above)))
12845
12846 ;;; Finish up
12847
12848 (provide 'org)
12849
12850 (run-hooks 'org-load-hook)
12851
12852 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12853 ;;; org.el ends here