]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-open-at-point): Fixed bug in wiki-style bracket links.
[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.10
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.10
85 ;; - Bug fixes.
86 ;;
87 ;; Version 4.09
88 ;; - Bug fixes.
89 ;; - Small improvements to font-lock support.
90 ;; - MHE support finalized.
91 ;;
92 ;; Version 4.08
93 ;; - Bug fixes.
94 ;; - Improved MHE support
95 ;;
96 ;; Version 4.07
97 ;; - Bug fixes.
98 ;; - Leading stars in headlines can be hidden, so make the outline look
99 ;; cleaner.
100 ;; - Mouse-1 can be used to follow links.
101 ;;
102 ;; Version 4.06
103 ;; - HTML exporter treats targeted internal links.
104 ;; - Bug fixes.
105 ;;
106 ;; Version 4.05
107 ;; - Changes to internal link system (thanks to David Wainberg for ideas).
108 ;; - in-file links: [[Search String]] instead of <file:::Search String>
109 ;; - automatic links to "radio targets".
110 ;; - CamelCase not longer active by default, configure org-activate-camels
111 ;; if you want to turn it back on.
112 ;; - After following a link, `C-c &' jumps back to it.
113 ;; - MH-E link support (thanks to Thomas Baumann).
114 ;; - Special table lines are no longer exported.
115 ;; - Bug fixes and minor improvements.
116 ;;
117 ;; Version 4.04
118 ;; - Cleanup tags display in agenda.
119 ;; - Bug fixes.
120 ;;
121 ;; Version 4.03
122 ;; - Table alignment fixed for use with wide characters.
123 ;; - `C-c -' leaves cursor in current table line.
124 ;; - The current TAG can be incorporated into the agenda prefix.
125 ;; See option `org-agenda-prefix-format' for details.
126 ;;
127 ;; Version 4.02
128 ;; - Minor bug fixes and improvements around tag searches.
129 ;; - XEmacs compatibility fixes.
130 ;;
131 ;; Version 4.01
132 ;; - Tags can also be set remotely from agenda buffer.
133 ;; - Boolean logic for tag searches.
134 ;; - Additional agenda commands can be configured through the variable
135 ;; `org-agenda-custom-commands'.
136 ;; - Minor bug fixes.
137 ;;
138 ;;; Code:
139
140 (eval-when-compile (require 'cl) (require 'calendar))
141 (require 'outline)
142 (require 'time-date)
143 (require 'easymenu)
144
145 (defvar calc-embedded-close-formula)
146 (defvar calc-embedded-open-formula)
147 (defvar font-lock-unfontify-region-function)
148
149 ;;; Customization variables
150
151 (defvar org-version "4.10"
152 "The version number of the file org.el.")
153 (defun org-version ()
154 (interactive)
155 (message "Org-mode version %s" org-version))
156
157 ;; The following two constants are for compatibility with different Emacs
158 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
159 ;; The compatibility code in org.el is based on these two constants.
160 (defconst org-xemacs-p (featurep 'xemacs)
161 "Are we running XEmacs?")
162 (defconst org-noutline-p (featurep 'noutline)
163 "Are we using the new outline mode?")
164
165 (defgroup org nil
166 "Outline-based notes management and organizer."
167 :tag "Org"
168 :group 'outlines
169 :group 'hypermedia
170 :group 'calendar)
171
172 (defgroup org-startup nil
173 "Options concerning startup of Org-mode."
174 :tag "Org Startup"
175 :group 'org)
176
177 (defcustom org-CUA-compatible nil
178 "Non-nil means use alternative key bindings for S-<cursor movement>.
179 Org-mode used S-<cursor movement> for changing timestamps and priorities.
180 S-<cursor movement> is also used for example by `CUA-mode' to select text.
181 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
182 alternative bindings. Setting this variable to t will replace the following
183 keys both in Org-mode and in the Org-agenda buffer.
184
185 S-RET -> C-S-RET
186 S-up -> M-p
187 S-down -> M-n
188 S-left -> M--
189 S-right -> M-+
190
191 If you do not like the alternative keys, take a look at the variable
192 `org-disputed-keys'.
193
194 This option is only relevant at load-time of Org-mode. Changing it requires
195 a restart of Emacs to become effective."
196 :group 'org-startup
197 :type 'boolean)
198
199 (defvar org-disputed-keys
200 '((S-up [(shift up)] [(meta ?p)])
201 (S-down [(shift down)] [(meta ?n)])
202 (S-left [(shift left)] [(meta ?-)])
203 (S-right [(shift right)] [(meta ?+)])
204 (S-return [(shift return)] [(control shift return)]))
205 "Keys for which Org-mode and other modes compete.
206 This is an alist, cars are symbols for lookup, 1st element is the default key,
207 second element will be used when `org-CUA-compatible' is t.")
208
209 (defun org-key (key)
210 "Select a key according to `org-CUA-compatible'."
211 (nth (if org-CUA-compatible 2 1)
212 (or (assq key org-disputed-keys)
213 (error "Invalid Key %s in `org-key'" key))))
214
215 (defcustom org-startup-folded t
216 "Non-nil means, entering Org-mode will switch to OVERVIEW.
217 This can also be configured on a per-file basis by adding one of
218 the following lines anywhere in the buffer:
219
220 #+STARTUP: fold
221 #+STARTUP: nofold
222 #+STARTUP: content"
223 :group 'org-startup
224 :type '(choice
225 (const :tag "nofold: show all" nil)
226 (const :tag "fold: overview" t)
227 (const :tag "content: all headlines" content)))
228
229 (defcustom org-startup-truncated t
230 "Non-nil means, entering Org-mode will set `truncate-lines'.
231 This is useful since some lines containing links can be very long and
232 uninteresting. Also tables look terrible when wrapped."
233 :group 'org-startup
234 :type 'boolean)
235
236 (defcustom org-startup-with-deadline-check nil
237 "Non-nil means, entering Org-mode will run the deadline check.
238 This means, if you start editing an org file, you will get an
239 immediate reminder of any due deadlines.
240 This can also be configured on a per-file basis by adding one of
241 the following lines anywhere in the buffer:
242
243 #+STARTUP: dlcheck
244 #+STARTUP: nodlcheck"
245 :group 'org-startup
246 :type 'boolean)
247
248 (defcustom org-insert-mode-line-in-empty-file nil
249 "Non-nil means insert the first line setting Org-mode in empty files.
250 When the function `org-mode' is called interactively in an empty file, this
251 normally means that the file name does not automatically trigger Org-mode.
252 To ensure that the file will always be in Org-mode in the future, a
253 line enforcing Org-mode will be inserted into the buffer, if this option
254 has been set."
255 :group 'org-startup
256 :type 'boolean)
257
258 (defgroup org-keywords nil
259 "Options concerning TODO items in Org-mode."
260 :tag "Org Keywords"
261 :group 'org)
262
263 (defcustom org-todo-keywords '("TODO" "DONE")
264 "List of TODO entry keywords.
265 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
266 considered to mean that the entry is \"done\". All the other mean that
267 action is required, and will make the entry show up in todo lists, diaries
268 etc.
269 The command \\[org-todo] cycles an entry through these states, and an
270 additional state where no keyword is present. For details about this
271 cycling, see also the variable `org-todo-interpretation'
272 Changes become only effective after restarting Emacs."
273 :group 'org-keywords
274 :type '(repeat (string :tag "Keyword")))
275
276 (defcustom org-todo-interpretation 'sequence
277 "Controls how TODO keywords are interpreted.
278 \\<org-mode-map>Possible values are `sequence' and `type'.
279 This variable is only relevant if `org-todo-keywords' contains more than two
280 states. There are two ways how these keywords can be used:
281
282 - As a sequence in the process of working on a TODO item, for example
283 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
284 org-todo-interpretation 'sequence)
285
286 - As different types of TODO items, for example
287 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
288 org-todo-interpretation 'type)
289
290 When the states are interpreted as a sequence, \\[org-todo] always cycles
291 to the next state, in order to walk through all different states. So with
292 \\[org-todo], you turn an empty entry into the state TODO. When you started
293 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
294 later to VERIFY and finally to DONE.
295
296 When the states are interpreted as types, \\[org-todo] still cycles through
297 when it is called several times in direct succession, in order to initially
298 select the type. However, if not called immediately after a previous
299 \\[org-todo], it switches from each type directly to DONE. So with the
300 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
301 RELAXED. If you later return to this entry and press \\[org-todo] again,
302 RELAXED will not be changed REMIND, but directly to DONE.
303
304 You can create a large number of types. To initially select a
305 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
306 type with completion. Of course, you can also type the keyword
307 directly into the buffer. M-TAB completes TODO keywords at the
308 beginning of a headline."
309 :group 'org-keywords
310 :type '(choice (const sequence)
311 (const type)))
312
313 (defcustom org-default-priority ?B
314 "The default priority of TODO items.
315 This is the priority an item get if no explicit priority is given."
316 :group 'org-keywords
317 :type 'character)
318
319 (defcustom org-lowest-priority ?C
320 "The lowest priority of TODO items. A character like ?A, ?B etc."
321 :group 'org-keywords
322 :type 'character)
323
324 (defcustom org-deadline-string "DEADLINE:"
325 "String to mark deadline entries.
326 A deadline 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-deadline].
329 Changes become only effective after restarting Emacs."
330 :group 'org-keywords
331 :type 'string)
332
333 (defcustom org-scheduled-string "SCHEDULED:"
334 "String to mark scheduled TODO entries.
335 A schedule is this string, followed by a time stamp. Should be a word,
336 terminated by a colon. You can insert a schedule keyword and
337 a timestamp with \\[org-schedule].
338 Changes become only effective after restarting Emacs."
339 :group 'org-keywords
340 :type 'string)
341
342 (defcustom org-closed-string "CLOSED:"
343 "String used as the prefix for timestamps logging closing a TODO entry."
344 :group 'org-keywords
345 :type 'string)
346
347 (defcustom org-comment-string "COMMENT"
348 "Entries starting with this keyword will never be exported.
349 An entry can be toggled between COMMENT and normal with
350 \\[org-toggle-comment].
351 Changes become only effective after restarting Emacs."
352 :group 'org-keywords
353 :type 'string)
354
355 (defcustom org-quote-string "QUOTE"
356 "Entries starting with this keyword will be exported in fixed-width font.
357 Quoting applies only to the text in the entry following the headline, and does
358 not extend beyond the next headline, even if that is lower level.
359 An entry can be toggled between QUOTE and normal with
360 \\[org-toggle-fixed-width-section]."
361 :group 'org-keywords
362 :type 'string)
363
364 (defcustom org-after-todo-state-change-hook nil
365 "Hook which is run after the state of a TODO item was changed.
366 The new state (a string with a TODO keyword, or nil) is available in the
367 Lisp variable `state'."
368 :group 'org-keywords
369 :type 'hook)
370
371 ;; Variables for pre-computed regular expressions, all buffer local
372 (defvar org-todo-kwd-priority-p nil
373 "Do TODO items have priorities?")
374 (make-variable-buffer-local 'org-todo-kwd-priority-p)
375 (defvar org-todo-kwd-max-priority nil
376 "Maximum priority of TODO items.")
377 (make-variable-buffer-local 'org-todo-kwd-max-priority)
378 (defvar org-ds-keyword-length 12
379 "Maximum length of the Deadline and SCHEDULED keywords.")
380 (make-variable-buffer-local 'org-ds-keyword-length)
381 (defvar org-done-string nil
382 "The last string in `org-todo-keywords', indicating an item is DONE.")
383 (make-variable-buffer-local 'org-done-string)
384 (defvar org-todo-regexp nil
385 "Matches any of the TODO state keywords.")
386 (make-variable-buffer-local 'org-todo-regexp)
387 (defvar org-not-done-regexp nil
388 "Matches any of the TODO state keywords except the last one.")
389 (make-variable-buffer-local 'org-not-done-regexp)
390 (defvar org-todo-line-regexp nil
391 "Matches a headline and puts TODO state into group 2 if present.")
392 (make-variable-buffer-local 'org-todo-line-regexp)
393 (defvar org-nl-done-regexp nil
394 "Matches newline followed by a headline with the DONE keyword.")
395 (make-variable-buffer-local 'org-nl-done-regexp)
396 (defvar org-looking-at-done-regexp nil
397 "Matches the DONE keyword a point.")
398 (make-variable-buffer-local 'org-looking-at-done-regexp)
399 (defvar org-deadline-regexp nil
400 "Matches the DEADLINE keyword.")
401 (make-variable-buffer-local 'org-deadline-regexp)
402 (defvar org-deadline-time-regexp nil
403 "Matches the DEADLINE keyword together with a time stamp.")
404 (make-variable-buffer-local 'org-deadline-time-regexp)
405 (defvar org-deadline-line-regexp nil
406 "Matches the DEADLINE keyword and the rest of the line.")
407 (make-variable-buffer-local 'org-deadline-line-regexp)
408 (defvar org-scheduled-regexp nil
409 "Matches the SCHEDULED keyword.")
410 (make-variable-buffer-local 'org-scheduled-regexp)
411 (defvar org-scheduled-time-regexp nil
412 "Matches the SCHEDULED keyword together with a time stamp.")
413 (make-variable-buffer-local 'org-scheduled-time-regexp)
414
415 (defvar org-category nil
416 "Variable used by org files to set a category for agenda display.
417 Such files should use a file variable to set it, for example
418
419 -*- mode: org; org-category: \"ELisp\"
420
421 or contain a special line
422
423 #+CATEGORY: ELisp
424
425 If the file does not specify a category, then file's base name
426 is used instead.")
427 (make-variable-buffer-local 'org-category)
428
429 (defgroup org-time nil
430 "Options concerning time stamps and deadlines in Org-mode."
431 :tag "Org Time"
432 :group 'org)
433
434 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
435 "Formats for `format-time-string' which are used for time stamps.
436 It is not recommended to change this constant.")
437
438
439 (defcustom org-deadline-warning-days 30
440 "No. of days before expiration during which a deadline becomes active.
441 This variable governs the display in the org file."
442 :group 'org-time
443 :type 'number)
444
445 (defcustom org-popup-calendar-for-date-prompt t
446 "Non-nil means, pop up a calendar when prompting for a date.
447 In the calendar, the date can be selected with mouse-1. However, the
448 minibuffer will also be active, and you can simply enter the date as well.
449 When nil, only the minibuffer will be available."
450 :group 'org-time
451 :type 'boolean)
452
453 (defcustom org-calendar-follow-timestamp-change t
454 "Non-nil means, make the calendar window follow timestamp changes.
455 When a timestamp is modified and the calendar window is visible, it will be
456 moved to the new date."
457 :group 'org-time
458 :type 'boolean)
459
460 (defcustom org-log-done nil
461 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
462 When the state of an entry is changed from nothing to TODO, remove a previous
463 closing date."
464 :group 'org-time
465 :type 'boolean)
466
467 (defgroup org-agenda nil
468 "Options concerning agenda display Org-mode."
469 :tag "Org Agenda"
470 :group 'org)
471
472 (defcustom org-agenda-files nil
473 "A list of org files for agenda/diary display.
474 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
475 \\[org-remove-file]. You can also use customize to edit the list."
476 :group 'org-agenda
477 :type '(repeat file))
478
479 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
480 "Custom commands for the agenda.
481 These commands will be offered on the splash screen displayed by the
482 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
483
484 key The key (a single char as a string) to be associated with the command.
485 type The command type, any of the following symbols:
486 todo Entries with a specific TODO keyword, in all agenda files.
487 tags Tags match in all agenda files.
488 todo-tree Sparse tree of specific TODO keyword in *current* file.
489 tags-tree Sparse tree with all tags matches in *current* file.
490 occur-tree Occur sparse tree for current file.
491 match What to search for:
492 - a single keyword for TODO keyword searches
493 - a tags match expression for tags searches
494 - a regular expression for occur searches"
495 :group 'org-agenda
496 :type '(repeat
497 (list (string :tag "Key")
498 (choice :tag "Type"
499 (const :tag "Tags search in all agenda files" tags)
500 (const :tag "TODO keyword search in all agenda files" todo)
501 (const :tag "Tags sparse tree in current buffer" tags-tree)
502 (const :tag "TODO keyword tree in current buffer" todo-tree)
503 (const :tag "Occur tree in current buffer" occur-tree))
504 (string :tag "Match"))))
505
506 (defcustom org-select-timeline-window t
507 "Non-nil means, after creating a timeline, move cursor into Timeline window.
508 When nil, cursor will remain in the current window."
509 :group 'org-agenda
510 :type 'boolean)
511
512 (defcustom org-select-agenda-window t
513 "Non-nil means, after creating an agenda, move cursor into Agenda window.
514 When nil, cursor will remain in the current window."
515 :group 'org-agenda
516 :type 'boolean)
517
518 (defcustom org-fit-agenda-window t
519 "Non-nil means, change window size of agenda to fit content."
520 :group 'org-agenda
521 :type 'boolean)
522
523 (defcustom org-agenda-show-all-dates t
524 "Non-nil means, `org-agenda' shows every day in the selected range.
525 When nil, only the days which actually have entries are shown."
526 :group 'org-agenda
527 :type 'boolean)
528
529 ;; FIXME: First day of month works only for current month because it would
530 ;; require a variable ndays treatment.
531 (defcustom org-agenda-start-on-weekday 1
532 "Non-nil means, start the overview always on the specified weekday.
533 0 Denotes Sunday, 1 denotes Monday etc.
534 When nil, always start on the current day."
535 :group 'org-agenda
536 :type '(choice (const :tag "Today" nil)
537 (const :tag "First day of month" t)
538 (number :tag "Weekday No.")))
539
540 (defcustom org-agenda-ndays 7
541 "Number of days to include in overview display."
542 :group 'org-agenda
543 :type 'number)
544
545 (defcustom org-agenda-include-all-todo t
546 "Non-nil means, the agenda will always contain all TODO entries.
547 When nil, date-less entries will only be shown if `org-agenda' is called
548 with a prefix argument.
549 When non-nil, the TODO entries will be listed at the top of the agenda, before
550 the entries for specific days."
551 :group 'org-agenda
552 :type 'boolean)
553
554 (defcustom org-agenda-include-diary nil
555 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
556 :group 'org-agenda
557 :type 'boolean)
558
559 (defcustom org-calendar-to-agenda-key [?c]
560 "The key to be installed in `calendar-mode-map' for switching to the agenda.
561 The command `org-calendar-goto-agenda' will be bound to this key. The
562 default is the character `c' because then `c' can be used to switch back and
563 forth between agenda and calendar."
564 :group 'org-agenda
565 :type 'sexp)
566
567 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
568 "Sorting structure for the agenda items of a single day.
569 This is a list of symbols which will be used in sequence to determine
570 if an entry should be listed before another entry. The following
571 symbols are recognized:
572
573 time-up Put entries with time-of-day indications first, early first
574 time-down Put entries with time-of-day indications first, late first
575 category-keep Keep the default order of categories, corresponding to the
576 sequence in `org-agenda-files'.
577 category-up Sort alphabetically by category, A-Z.
578 category-down Sort alphabetically by category, Z-A.
579 priority-up Sort numerically by priority, high priority last.
580 priority-down Sort numerically by priority, high priority first.
581
582 The different possibilities will be tried in sequence, and testing stops
583 if one comparison returns a \"not-equal\". For example, the default
584 '(time-up category-keep priority-down)
585 means: Pull out all entries having a specified time of day and sort them,
586 in order to make a time schedule for the current day the first thing in the
587 agenda listing for the day. Of the entries without a time indication, keep
588 the grouped in categories, don't sort the categories, but keep them in
589 the sequence given in `org-agenda-files'. Within each category sort by
590 priority.
591
592 Leaving out `category-keep' would mean that items will be sorted across
593 categories by priority."
594 :group 'org-agenda
595 :type '(repeat
596 (choice
597 (const time-up)
598 (const time-down)
599 (const category-keep)
600 (const category-up)
601 (const category-down)
602 (const priority-up)
603 (const priority-down))))
604
605 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
606 "Format specification for the prefix of items in the agenda buffer.
607 This format works similar to a printf format, with the following meaning:
608
609 %c the category of the item, \"Diary\" for entries from the diary, or
610 as given by the CATEGORY keyword or derived from the file name.
611 %T the first tag of the item.
612 %t the time-of-day specification if one applies to the entry, in the
613 format HH:MM
614 %s Scheduling/Deadline information, a short string
615
616 All specifiers work basically like the standard `%s' of printf, but may
617 contain two additional characters: A question mark just after the `%' and
618 a whitespace/punctuation character just before the final letter.
619
620 If the first character after `%' is a question mark, the entire field
621 will only be included if the corresponding value applies to the
622 current entry. This is useful for fields which should have fixed
623 width when present, but zero width when absent. For example,
624 \"%?-12t\" will result in a 12 character time field if a time of the
625 day is specified, but will completely disappear in entries which do
626 not contain a time.
627
628 If there is punctuation or whitespace character just before the final
629 format letter, this character will be appended to the field value if
630 the value is not empty. For example, the format \"%-12:c\" leads to
631 \"Diary: \" if the category is \"Diary\". If the category were be
632 empty, no additional colon would be interted.
633
634 The default value of this option is \" %-12:c%?-12t% s\", meaning:
635 - Indent the line with two space characters
636 - Give the category in a 12 chars wide field, padded with whitespace on
637 the right (because of `-'). Append a colon if there is a category
638 (because of `:').
639 - If there is a time-of-day, put it into a 12 chars wide field. If no
640 time, don't put in an empty field, just skip it (because of '?').
641 - Finally, put the scheduling information and append a whitespace.
642
643 As another example, if you don't want the time-of-day of entries in
644 the prefix, you could use:
645
646 (setq org-agenda-prefix-format \" %-11:c% s\")
647
648 See also the variables `org-agenda-remove-times-when-in-prefix' and
649 `org-agenda-remove-tags-when-in-prefix'."
650 :type 'string
651 :group 'org-agenda)
652
653 (defcustom org-timeline-prefix-format " % s"
654 "Like `org-agenda-prefix-format', but for the timeline of a single file."
655 :type 'string
656 :group 'org-agenda)
657
658 (defvar org-prefix-format-compiled nil
659 "The compiled version of the most recently used prefix format.
660 Depending on which command was used last, this may be the compiled version
661 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
662
663 (defcustom org-agenda-use-time-grid t
664 "Non-nil means, show a time grid in the agenda schedule.
665 A time grid is a set of lines for specific times (like every two hours between
666 8:00 and 20:00). The items scheduled for a day at specific times are
667 sorted in between these lines.
668 For details about when the grid will be shown, and what it will look like, see
669 the variable `org-agenda-time-grid'."
670 :group 'org-agenda
671 :type 'boolean)
672
673 (defcustom org-agenda-time-grid
674 '((daily today require-timed)
675 "----------------"
676 (800 1000 1200 1400 1600 1800 2000))
677
678 "The settings for time grid for agenda display.
679 This is a list of three items. The first item is again a list. It contains
680 symbols specifying conditions when the grid should be displayed:
681
682 daily if the agenda shows a single day
683 weekly if the agenda shows an entire week
684 today show grid on current date, independent of daily/weekly display
685 require-timed show grid only if at least on item has a time specification
686
687 The second item is a string which will be places behing the grid time.
688
689 The third item is a list of integers, indicating the times that should have
690 a grid line."
691 :group 'org-agenda
692 :type
693 '(list
694 (set :greedy t :tag "Grid Display Options"
695 (const :tag "Show grid in single day agenda display" daily)
696 (const :tag "Show grid in weekly agenda display" weekly)
697 (const :tag "Always show grid for today" today)
698 (const :tag "Show grid only if any timed entries are present"
699 require-timed)
700 (const :tag "Skip grid times already present in an entry"
701 remove-match))
702 (string :tag "Grid String")
703 (repeat :tag "Grid Times" (integer :tag "Time"))))
704
705 (defcustom org-agenda-remove-times-when-in-prefix t
706 "Non-nil means, remove duplicate time specifications in agenda items.
707 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
708 time-of-day specification in a headline or diary entry is extracted and
709 placed into the prefix. If this option is non-nil, the original specification
710 \(a timestamp or -range, or just a plain time(range) specification like
711 11:30-4pm) will be removed for agenda display. This makes the agenda less
712 cluttered.
713 The option can be t or nil. It may also be the symbol `beg', indicating
714 that the time should only be removed what it is located at the beginning of
715 the headline/diary entry."
716 :group 'org-agenda
717 :type '(choice
718 (const :tag "Always" t)
719 (const :tag "Never" nil)
720 (const :tag "When at beginning of entry" beg)))
721
722 (defcustom org-sort-agenda-notime-is-late t
723 "Non-nil means, items without time are considered late.
724 This is only relevant for sorting. When t, items which have no explicit
725 time like 15:30 will be considered as 24:01, i.e. later than any items which
726 do have a time. When nil, the default time is before 0:00. You can use this
727 option to decide if the schedule for today should come before or after timeless
728 agenda entries."
729 :group 'org-agenda
730 :type 'boolean)
731
732 (defcustom org-agenda-remove-tags-when-in-prefix nil
733 "Non-nil means, the tags from copy of headline in agenda.
734 When this is the symbol `prefix', only remove tags when
735 `org-agenda-prefix-format' contains a `%T' specifier."
736 :group 'org-agenda
737 :type '(choice
738 (const :tag "Always" t)
739 (const :tag "Never" nil)
740 (const :tag "When prefix format contains %T" prefix)))
741
742 (defgroup org-structure nil
743 "Options concerning structure editing in Org-mode."
744 :tag "Org Structure"
745 :group 'org)
746
747 (defcustom org-cycle-include-plain-lists nil
748 "Non-nil means, include plain lists into visibility cycling.
749 This means that during cycling, plain list items will *temporarily* be
750 interpreted as outline headlines with a level given by 1000+i where i is the
751 indentation of the bullet. In all other operations, plain list items are
752 not seen as headlines. For example, you cannot assign a TODO keyword to
753 such an item."
754 :group 'org-structure
755 :type 'boolean)
756
757 (defcustom org-cycle-emulate-tab t
758 "Where should `org-cycle' emulate TAB.
759 nil Never
760 white Only in completely white lines
761 t Everywhere except in headlines"
762 :group 'org-structure
763 :type '(choice (const :tag "Never" nil)
764 (const :tag "Only in completely white lines" white)
765 (const :tag "Everywhere except in headlines" t)
766 ))
767
768 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
769 "Hook that is run after `org-cycle' has changed the buffer visibility.
770 The function(s) in this hook must accept a single argument which indicates
771 the new state that was set by the most recent `org-cycle' command. The
772 argument is a symbol. After a global state change, it can have the values
773 `overview', `content', or `all'. After a local state change, it can have
774 the values `folded', `children', or `subtree'."
775 :group 'org-structure
776 :type 'hook)
777
778 (defcustom org-highlight-sparse-tree-matches t
779 "Non-nil means, highlight all matches that define a sparse tree.
780 The highlights will automatically disappear the next time the buffer is
781 changed by an edit command."
782 :group 'org-structure
783 :type 'boolean)
784
785 (defcustom org-show-hierarchy-above t
786 "Non-nil means, show full hierarchy when showing a spot in the tree.
787 Turning this off makes sparse trees more compact, but also less clear."
788 :group 'org-structure
789 :type 'boolean)
790
791 (defcustom org-show-following-heading t
792 "Non-nil means, show heading following match in `org-occur'.
793 When doing an `org-occur' it is useful to show the headline which
794 follows the match, even if they do not match the regexp. This makes it
795 easier to edit directly inside the sparse tree. However, if you use
796 `org-occur' mainly as an overview, the following headlines are
797 unnecessary clutter."
798 :group 'org-structure
799 :type 'boolean)
800
801 (defcustom org-occur-hook '(org-first-headline-recenter)
802 "Hook that is run after `org-occur' has constructed a sparse tree.
803 This can be used to recenter the window to show as much of the structure
804 as possible."
805 :group 'org-structure
806 :type 'hook)
807
808 (defcustom org-odd-levels-only nil
809 "Non-nil means, skip even levels and only use odd levels for the outline.
810 This has the effect that two stars are being added/taken away in
811 promotion/demotion commands. It also influences how levels are
812 handled by the exporters.
813 Changing it requires restart of `font-lock-mode' to become effective
814 for fontification also in regions already fontified."
815 :group 'org-structure
816 :group 'org-font-lock
817 :type 'boolean)
818
819 (defcustom org-adapt-indentation t
820 "Non-nil means, adapt indentation when promoting and demoting.
821 When this is set and the *entire* text in an entry is indented, the
822 indentation is increased by one space in a demotion command, and
823 decreased by one in a promotion command. If any line in the entry
824 body starts at column 0, indentation is not changed at all."
825 :group 'org-structure
826 :type 'boolean)
827
828 (defcustom org-plain-list-ordered-item-terminator t
829 "The character that makes a line with leading number an ordered list item.
830 Valid values are ?. and ?\). To get both terminators, use t. While
831 ?. may look nicer, it creates the danger that a line with leading
832 number may be incorrectly interpreted as an item. ?\) therefore is
833 the safe choice."
834 :group 'org-structure
835 :type '(choice (const :tag "dot like in \"2.\"" ?.)
836 (const :tag "paren like in \"2)\"" ?\))
837 (const :tab "both" t)))
838
839 (defcustom org-auto-renumber-ordered-lists t
840 "Non-nil means, automatically renumber ordered plain lists.
841 Renumbering happens when the sequence have been changed with
842 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
843 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
844 :group 'org-structure
845 :type 'boolean)
846
847 (defcustom org-enable-fixed-width-editor t
848 "Non-nil means, lines starting with \":\" are treated as fixed-width.
849 This currently only means, they are never auto-wrapped.
850 When nil, such lines will be treated like ordinary lines.
851 See also the QUOTE keyword."
852 :group 'org-structure
853 :type 'boolean)
854
855 (defcustom org-archive-location "%s_archive::"
856 "The location where subtrees should be archived.
857 This string consists of two parts, separated by a double-colon.
858
859 The first part is a file name - when omitted, archiving happens in the same
860 file. %s will be replaced by the current file name (without directory part).
861 Archiving to a different file is useful to keep archived entries from
862 contributing to the Org-mode Agenda.
863
864 The part after the double colon is a headline. The archived entries will be
865 filed under that headline. When omitted, the subtrees are simply filed away
866 at the end of the file, as top-level entries.
867
868 Here are a few examples:
869 \"%s_archive::\"
870 If the current file is Projects.org, archive in file
871 Projects.org_archive, as top-level trees. This is the default.
872
873 \"::* Archived Tasks\"
874 Archive in the current file, under the top-level headline
875 \"* Archived Tasks\".
876
877 \"~/org/archive.org::\"
878 Archive in file ~/org/archive.org (absolute path), as top-level trees.
879
880 \"basement::** Finished Tasks\"
881 Archive in file ./basement (relative path), as level 3 trees
882 below the level 2 heading \"** Finished Tasks\".
883
884 You may set this option on a per-file basis by adding to the buffer a
885 line like
886
887 #+ARCHIVE: basement::** Finished Tasks"
888 :group 'org-structure
889 :type 'string)
890
891 (defcustom org-archive-mark-done t
892 "Non-nil means, mark archived entries as DONE."
893 :group 'org-structure
894 :type 'boolean)
895
896 (defcustom org-archive-stamp-time t
897 "Non-nil means, add a time stamp to archived entries.
898 The time stamp will be added directly after the TODO state keyword in the
899 first line, so it is probably best to use this in combinations with
900 `org-archive-mark-done'."
901 :group 'org-structure
902 :type 'boolean)
903
904 (defgroup org-tags nil
905 "Options concerning startup of Org-mode."
906 :tag "Org Tags"
907 :group 'org)
908
909 (defcustom org-tags-column 48
910 "The column to which tags should be indented in a headline.
911 If this number is positive, it specifies the column. If it is negative,
912 it means that the tags should be flushright to that column. For example,
913 -79 works well for a normal 80 character screen."
914 :group 'org-tags
915 :type 'integer)
916
917 (defcustom org-auto-align-tags t
918 "Non-nil means, realign tags after pro/demotion of TODO state change.
919 These operations change the length of a headline and therefore shift
920 the tags around. With this options turned on, after each such operation
921 the tags are again aligned to `org-tags-column'."
922 :group 'org-tags
923 :type 'boolean)
924
925 (defcustom org-use-tag-inheritance t
926 "Non-nil means, tags in levels apply also for sublevels.
927 When nil, only the tags directly given in a specific line apply there.
928 If you turn off this option, you very likely want to turn on the
929 companion option `org-tags-match-list-sublevels'."
930 :group 'org-tags
931 :type 'boolean)
932
933 (defcustom org-tags-match-list-sublevels nil
934 "Non-nil means list also sublevels of headlines matching tag search.
935 Because of tag inheritance (see variable `org-use-tag-inheritance'),
936 the sublevels of a headline matching a tag search often also match
937 the same search. Listing all of them can create very long lists.
938 Setting this variable to nil causes subtrees to be skipped.
939 This option is off by default, because inheritance in on. If you turn
940 inheritance off, you very likely want to turn this option on.
941
942 As a special case, if the tag search is restricted to TODO items, the
943 value of this variable is ignored and sublevels are always checked, to
944 make sure all corresponding TODO items find their way into the list."
945 :group 'org-tags
946 :type 'boolean)
947
948 (defvar org-tags-history nil
949 "History of minibuffer reads for tags.")
950 (defvar org-last-tags-completion-table nil
951 "The last used completion table for tags.")
952
953 (defgroup org-link nil
954 "Options concerning links in Org-mode."
955 :tag "Org Link"
956 :group 'org)
957
958 (defcustom org-tab-follows-link nil
959 "Non-nil means, on links TAB will follow the link.
960 Needs to be set before org.el is loaded."
961 :group 'org-link
962 :type 'boolean)
963
964 (defcustom org-return-follows-link nil
965 "Non-nil means, on links RET will follow the link.
966 Needs to be set before org.el is loaded."
967 :group 'org-link
968 :type 'boolean)
969
970 (defcustom org-mark-ring-length 4
971 "Number of different positions to be recorded in the ring
972 Changing this requires a restart of Emacs to work correctly."
973 :group 'org-link
974 :type 'interger)
975
976 (defcustom org-link-format "<%s>"
977 "Default format for linkes in the buffer.
978 This is a format string for printf, %s will be replaced by the link text.
979 If you want to make sure that your link is always properly terminated,
980 include angle brackets into this format, like \"<%s>\". Some people also
981 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
982 :group 'org-link
983 :type '(choice
984 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
985 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
986 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
987 (string :tag "Other" :value "<%s>")))
988
989 (defcustom org-allow-space-in-links t
990 "Non-nil means, file names in links may contain space characters.
991 When nil, it becomes possible to put several links into a line.
992 Note that in tables, a link never extends accross fields, so in a table
993 it is always possible to put several links into a line.
994 Changing this variable requires a restart of Emacs of become effective."
995 :group 'org-link
996 :type 'boolean)
997
998 (defcustom org-radio-targets t
999 "Non-nil means activate text matching a link target.
1000 Radio targets are strings in triple angular brackets, like <<<My Target>>>.
1001 When this option is set, any occurrence of \"my target\" in normal text
1002 becomes a link."
1003 :group 'org-link
1004 :type 'boolean)
1005
1006 (defcustom org-activate-camels nil
1007 "Non-nil means, treat words in CamelCase as in-file links.
1008 Changing this requires restart of Emacs to become effective."
1009 :group 'org-link
1010 :type 'boolean)
1011
1012 (defcustom org-context-in-file-links t
1013 "Non-nil means, file links from `org-store-link' contain context.
1014 A search string will be added to the file name with :: as separator and
1015 used to find the context when the link is activated by the command
1016 `org-open-at-point'.
1017 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1018 negates this setting for the duration of the command."
1019 :group 'org-link
1020 :type 'boolean)
1021
1022 (defcustom org-file-link-context-use-camel-case nil
1023 "Non-nil means, use CamelCase to store a search context in a file link.
1024 When nil, the search string simply consists of the words of the string."
1025 :group 'org-link
1026 :type 'boolean)
1027
1028 (defcustom org-keep-stored-link-after-insertion nil
1029 "Non-nil means, keep link in list for entire session.
1030
1031 The command `org-store-link' adds a link pointing to the current
1032 location to an internal list. These links accumulate during a session.
1033 The command `org-insert-link' can be used to insert links into any
1034 Org-mode file (offering completion for all stored links). When this
1035 option is nil, every link which has been inserted once using \\[org-insert-link]
1036 will be removed from the list, to make completing the unused links
1037 more efficient."
1038 :group 'org-link
1039 :type 'boolean)
1040
1041 (defcustom org-link-frame-setup
1042 '((vm . vm-visit-folder-other-frame)
1043 (gnus . gnus-other-frame)
1044 (file . find-file-other-window))
1045 "Setup the frame configuration for following links.
1046 When following a link with Emacs, it may often be useful to display
1047 this link in another window or frame. This variable can be used to
1048 set this up for the different types of links.
1049 For VM, use any of
1050 `vm-visit-folder'
1051 `vm-visit-folder-other-frame'
1052 For Gnus, use any of
1053 `gnus'
1054 `gnus-other-frame'
1055 For FILE, use any of
1056 `find-file'
1057 `find-file-other-window'
1058 `find-file-other-frame'
1059 For the calendar, use the variable `calendar-setup'.
1060 For BBDB, it is currently only possible to display the matches in
1061 another window."
1062 :group 'org-link
1063 :type '(list
1064 (cons (const vm)
1065 (choice
1066 (const vm-visit-folder)
1067 (const vm-visit-folder-other-window)
1068 (const vm-visit-folder-other-frame)))
1069 (cons (const gnus)
1070 (choice
1071 (const gnus)
1072 (const gnus-other-frame)))
1073 (cons (const file)
1074 (choice
1075 (const find-file)
1076 (const find-file-other-window)
1077 (const find-file-other-frame)))))
1078
1079 (defcustom org-usenet-links-prefer-google nil
1080 "Non-nil means, `org-store-link' will create web links to Google groups.
1081 When nil, Gnus will be used for such links.
1082 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1083 negates this setting for the duration of the command."
1084 :group 'org-link
1085 :type 'boolean)
1086
1087 (defcustom org-open-non-existing-files nil
1088 "Non-nil means, `org-open-file' will open non-existing file.
1089 When nil, an error will be generated."
1090 :group 'org-link
1091 :type 'boolean)
1092
1093 (defcustom org-confirm-shell-links t
1094 "Non-nil means, ask for confirmation before executing shell links.
1095 The default is true, to keep new users from shooting into their own foot."
1096 :group 'org-link
1097 :type 'boolean)
1098
1099 (defconst org-file-apps-defaults-gnu
1100 '((t . mailcap))
1101 "Default file applications on a UNIX or GNU/Linux system.
1102 See `org-file-apps'.")
1103
1104 (defconst org-file-apps-defaults-macosx
1105 '((t . "open %s")
1106 ("ps" . "gv %s")
1107 ("ps.gz" . "gv %s")
1108 ("eps" . "gv %s")
1109 ("eps.gz" . "gv %s")
1110 ("dvi" . "xdvi %s")
1111 ("fig" . "xfig %s"))
1112 "Default file applications on a MacOS X system.
1113 The system \"open\" is known as a default, but we use X11 applications
1114 for some files for which the OS does not have a good default.
1115 See `org-file-apps'.")
1116
1117 (defconst org-file-apps-defaults-windowsnt
1118 '((t . (w32-shell-execute "open" file)))
1119 "Default file applications on a Windows NT system.
1120 The system \"open\" is used for most files.
1121 See `org-file-apps'.")
1122
1123 (defcustom org-file-apps
1124 '(
1125 ("txt" . emacs)
1126 ("tex" . emacs)
1127 ("ltx" . emacs)
1128 ("org" . emacs)
1129 ("el" . emacs)
1130 )
1131 "External applications for opening `file:path' items in a document.
1132 Org-mode uses system defaults for different file types, but
1133 you can use this variable to set the application for a given file
1134 extension. The entries in this list are cons cells with a file extension
1135 and the corresponding command. Possible values for the command are:
1136 `emacs' The file will be visited by the current Emacs process.
1137 `default' Use the default application for this file type.
1138 string A command to be executed by a shell; %s will be replaced
1139 by the path to the file.
1140 sexp A Lisp form which will be evaluated. The file path will
1141 be available in the Lisp variable `file'.
1142 For more examples, see the system specific constants
1143 `org-file-apps-defaults-macosx'
1144 `org-file-apps-defaults-windowsnt'
1145 `org-file-apps-defaults-gnu'."
1146 :group 'org-link
1147 :type '(repeat
1148 (cons (choice :value ""
1149 (string :tag "Extension")
1150 (const :tag "Default for unrecognized files" t)
1151 (const :tag "Links to a directory" directory))
1152 (choice :value ""
1153 (const :tag "Visit with Emacs" emacs)
1154 (const :tag "Use system default" default)
1155 (string :tag "Command")
1156 (sexp :tag "Lisp form")))))
1157
1158 (defcustom org-mhe-search-all-folders nil
1159 "Non-nil means, that the search for the mh-message will be extended to
1160 all folders if the message cannot be found in the folder given in the link.
1161 Searching all folders is very effective with one of the search engines
1162 supported by MH-E, but will be slow with pick."
1163 :group 'org-link
1164 :type 'boolean)
1165
1166 (defgroup org-remember nil
1167 "Options concerning interaction with remember.el."
1168 :tag "Org Remember"
1169 :group 'org)
1170
1171 (defcustom org-directory "~/org"
1172 "Directory with org files.
1173 This directory will be used as default to prompt for org files.
1174 Used by the hooks for remember.el."
1175 :group 'org-remember
1176 :type 'directory)
1177
1178 (defcustom org-default-notes-file "~/.notes"
1179 "Default target for storing notes.
1180 Used by the hooks for remember.el. This can be a string, or nil to mean
1181 the value of `remember-data-file'."
1182 :group 'org-remember
1183 :type '(choice
1184 (const :tag "Default from remember-data-file" nil)
1185 file))
1186
1187 (defcustom org-reverse-note-order nil
1188 "Non-nil means, store new notes at the beginning of a file or entry.
1189 When nil, new notes will be filed to the end of a file or entry."
1190 :group 'org-remember
1191 :type '(choice
1192 (const :tag "Reverse always" t)
1193 (const :tag "Reverse never" nil)
1194 (repeat :tag "By file name regexp"
1195 (cons regexp boolean))))
1196
1197 (defgroup org-table nil
1198 "Options concerning tables in Org-mode."
1199 :tag "Org Table"
1200 :group 'org)
1201
1202 (defcustom org-enable-table-editor 'optimized
1203 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1204 When nil, such lines will be treated like ordinary lines.
1205
1206 When equal to the symbol `optimized', the table editor will be optimized to
1207 do the following:
1208 - Use automatic overwrite mode in front of whitespace in table fields.
1209 This make the structure of the table stay in tact as long as the edited
1210 field does not exceed the column width.
1211 - Minimize the number of realigns. Normally, the table is aligned each time
1212 TAB or RET are pressed to move to another field. With optimization this
1213 happens only if changes to a field might have changed the column width.
1214 Optimization requires replacing the functions `self-insert-command',
1215 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1216 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1217 very good at guessing when a re-align will be necessary, but you can always
1218 force one with \\[org-ctrl-c-ctrl-c].
1219
1220 If you would like to use the optimized version in Org-mode, but the
1221 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1222
1223 This variable can be used to turn on and off the table editor during a session,
1224 but in order to toggle optimization, a restart is required.
1225
1226 See also the variable `org-table-auto-blank-field'."
1227 :group 'org-table
1228 :type '(choice
1229 (const :tag "off" nil)
1230 (const :tag "on" t)
1231 (const :tag "on, optimized" optimized)))
1232
1233 ;; FIXME: We could have a third option which makes it jump only over the first
1234 ;; hline in a table.
1235 (defcustom org-table-tab-jumps-over-hlines t
1236 "Non-nil means, tab in the last column of a table with jump over a hline.
1237 If a horizontal separator line is following the current line,
1238 `org-table-next-field' can either create a new row before that line, or jump
1239 over the line. When this option is nil, a new line will be created before
1240 this line."
1241 :group 'org-table
1242 :type 'boolean)
1243
1244 (defcustom org-table-auto-blank-field t
1245 "Non-nil means, automatically blank table field when starting to type into it.
1246 This only happens when typing immediately after a field motion
1247 command (TAB, S-TAB or RET).
1248 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1249 :group 'org-table
1250 :type 'boolean)
1251
1252 (defcustom org-table-default-size "5x2"
1253 "The default size for newly created tables, Columns x Rows."
1254 :group 'org-table
1255 :type 'string)
1256
1257 (defcustom org-table-automatic-realign t
1258 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1259 When nil, aligning is only done with \\[org-table-align], or after column
1260 removal/insertion."
1261 :group 'org-table
1262 :type 'boolean)
1263
1264 (defcustom org-table-spaces-around-separators '(1 . 1)
1265 "The number of spaces to be placed before and after separators."
1266 :group 'org-table
1267 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1268
1269 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1270 "The number of spaces to be placed before and after separators.
1271 This option applies when the column separators have been made invisible."
1272 :group 'org-table
1273 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1274
1275 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1276 "Regular expression for recognizing numbers in table columns.
1277 If a table column contains mostly numbers, it will be aligned to the
1278 right. If not, it will be aligned to the left.
1279
1280 The default value of this option is a regular expression which allows
1281 anything which looks remotely like a number as used in scientific
1282 context. For example, all of the following will be considered a
1283 number:
1284 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1285
1286 Other options offered by the customize interface are more restrictive."
1287 :group 'org-table
1288 :type '(choice
1289 (const :tag "Positive Integers"
1290 "^[0-9]+$")
1291 (const :tag "Integers"
1292 "^[-+]?[0-9]+$")
1293 (const :tag "Floating Point Numbers"
1294 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1295 (const :tag "Floating Point Number or Integer"
1296 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1297 (const :tag "Exponential, Floating point, Integer"
1298 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1299 (const :tag "Very General Number-Like"
1300 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1301 (string :tag "Regexp:")))
1302
1303 (defcustom org-table-number-fraction 0.5
1304 "Fraction of numbers in a column required to make the column align right.
1305 In a column all non-white fields are considered. If at least this
1306 fraction of fields is matched by `org-table-number-fraction',
1307 alignment to the right border applies."
1308 :group 'org-table
1309 :type 'number)
1310
1311 (defcustom org-export-highlight-first-table-line t
1312 "Non-nil means, highlight the first table line.
1313 In HTML export, this means use <th> instead of <td>.
1314 In tables created with table.el, this applies to the first table line.
1315 In Org-mode tables, all lines before the first horizontal separator
1316 line will be formatted with <th> tags."
1317 :group 'org-table
1318 :type 'boolean)
1319
1320 (defcustom org-table-tab-recognizes-table.el t
1321 "Non-nil means, TAB will automatically notice a table.el table.
1322 When it sees such a table, it moves point into it and - if necessary -
1323 calls `table-recognize-table'."
1324 :group 'org-table
1325 :type 'boolean)
1326
1327 (defgroup org-table-calculation nil
1328 "Options concerning tables in Org-mode."
1329 :tag "Org Table Calculation"
1330 :group 'org)
1331
1332 (defcustom org-table-copy-increment t
1333 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1334 :group 'org-table-calculation
1335 :type 'boolean)
1336
1337 (defcustom org-calc-default-modes
1338 '(calc-internal-prec 12
1339 calc-float-format (float 5)
1340 calc-angle-mode deg
1341 calc-prefer-frac nil
1342 calc-symbolic-mode nil
1343 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1344 calc-display-working-message t
1345 )
1346 "List with Calc mode settings for use in calc-eval for table formulas.
1347 The list must contain alternating symbols (Calc modes variables and values).
1348 Don't remove any of the default settings, just change the values. Org-mode
1349 relies on the variables to be present in the list."
1350 :group 'org-table-calculation
1351 :type 'plist)
1352
1353 (defcustom org-table-formula-evaluate-inline t
1354 "Non-nil means, TAB and RET evaluate a formula in current table field.
1355 If the current field starts with an equal sign, it is assumed to be a formula
1356 which should be evaluated as described in the manual and in the documentation
1357 string of the command `org-table-eval-formula'. This feature requires the
1358 Emacs calc package.
1359 When this variable is nil, formula calculation is only available through
1360 the command \\[org-table-eval-formula]."
1361 :group 'org-table-calculation
1362 :type 'boolean)
1363
1364
1365 (defcustom org-table-formula-use-constants t
1366 "Non-nil means, interpret constants in formulas in tables.
1367 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1368 by the value given in `org-table-formula-constants', or by a value obtained
1369 from the `constants.el' package."
1370 :group 'org-table-calculation
1371 :type 'boolean)
1372
1373 (defcustom org-table-formula-constants nil
1374 "Alist with constant names and values, for use in table formulas.
1375 The car of each element is a name of a constant, without the `$' before it.
1376 The cdr is the value as a string. For example, if you'd like to use the
1377 speed of light in a formula, you would configure
1378
1379 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1380
1381 and then use it in an equation like `$1*$c'."
1382 :group 'org-table-calculation
1383 :type '(repeat
1384 (cons (string :tag "name")
1385 (string :tag "value"))))
1386
1387 (defcustom org-table-formula-numbers-only nil
1388 "Non-nil means, calculate only with numbers in table formulas.
1389 Then all input fields will be converted to a number, and the result
1390 must also be a number. When nil, calc's full potential is available
1391 in table calculations, including symbolics etc."
1392 :group 'org-table-calculation
1393 :type 'boolean)
1394
1395 (defcustom org-table-allow-automatic-line-recalculation t
1396 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1397 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1398 :group 'org-table-calculation
1399 :type 'boolean)
1400
1401 (defgroup org-export nil
1402 "Options for exporting org-listings."
1403 :tag "Org Export"
1404 :group 'org)
1405
1406 (defcustom org-export-language-setup
1407 '(("en" "Author" "Date" "Table of Contents")
1408 ("da" "Ophavsmand" "Dato" "Indhold")
1409 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1410 ("es" "Autor" "Fecha" "\xccndice")
1411 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1412 ("it" "Autore" "Data" "Indice")
1413 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1414 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1415 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1416 "Terms used in export text, translated to different languages.
1417 Use the variable `org-export-default-language' to set the language,
1418 or use the +OPTION lines for a per-file setting."
1419 :group 'org-export
1420 :type '(repeat
1421 (list
1422 (string :tag "HTML language tag")
1423 (string :tag "Author")
1424 (string :tag "Date")
1425 (string :tag "Table of Contents"))))
1426
1427 (defcustom org-export-default-language "en"
1428 "The default language of HTML export, as a string.
1429 This should have an association in `org-export-language-setup'."
1430 :group 'org-export
1431 :type 'string)
1432
1433 (defcustom org-export-html-style
1434 "<style type=\"text/css\">
1435 html {
1436 font-family: Times, serif;
1437 font-size: 12pt;
1438 }
1439 .title { text-align: center; }
1440 .todo, .deadline { color: red; }
1441 .done { color: green; }
1442 .target { background-color: lavender; }
1443 pre {
1444 border: 1pt solid #AEBDCC;
1445 background-color: #F3F5F7;
1446 padding: 5pt;
1447 font-family: courier, monospace;
1448 }
1449 table { border-collapse: collapse; }
1450 td, th {
1451 vertical-align: top;
1452 border: 1pt solid #ADB9CC;
1453 }
1454 </style>"
1455 "The default style specification for exported HTML files.
1456 Since there are different ways of setting style information, this variable
1457 needs to contain the full HTML structure to provide a style, including the
1458 surrounding HTML tags. The style specifications should include definitions
1459 for new classes todo, done, title, and deadline. For example, legal values
1460 would be:
1461
1462 <style type=\"text/css\">
1463 p { font-weight: normal; color: gray; }
1464 h1 { color: black; }
1465 .title { text-align: center; }
1466 .todo, .deadline { color: red; }
1467 .done { color: green; }
1468 </style>
1469
1470 or, if you want to keep the style in a file,
1471
1472 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1473
1474 As the value of this option simply gets inserted into the HTML <head> header,
1475 you can \"misuse\" it to add arbitrary text to the header."
1476 :group 'org-export
1477 :type 'string)
1478
1479 (defcustom org-export-headline-levels 3
1480 "The last level which is still exported as a headline.
1481 Inferior levels will produce itemize lists when exported.
1482 Note that a numeric prefix argument to an exporter function overrides
1483 this setting.
1484
1485 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1486 :group 'org-export
1487 :type 'number)
1488
1489 (defcustom org-export-with-section-numbers t
1490 "Non-nil means, add section numbers to headlines when exporting.
1491
1492 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1493 :group 'org-export
1494 :type 'boolean)
1495
1496 (defcustom org-export-with-toc t
1497 "Non-nil means, create a table of contents in exported files.
1498 The TOC contains headlines with levels up to`org-export-headline-levels'.
1499
1500 Headlines which contain any TODO items will be marked with \"(*)\" in
1501 ASCII export, and with red color in HTML output.
1502
1503 In HTML output, the TOC will be clickable.
1504
1505 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1506 :group 'org-export
1507 :type 'boolean)
1508
1509 (defcustom org-export-plain-list-max-depth 20
1510 "Maximum depth of hand-formatted lists in HTML export.
1511
1512 Org-mode parses hand-formatted enumeration and bullet lists and
1513 transforms them to HTML open export. Different indentation of the
1514 bullet or number indicates different list nesting levels. To avoid
1515 confusion, only a single level is allowed by default. When this is
1516 larger than 1, deeper indentation leads to deeper list nesting. For
1517 example, the default value of 3 allows the following list to be
1518 formatted correctly in HTML:
1519
1520 * Fruit
1521 - Apple
1522 - Banana
1523 1. from Africa
1524 2. from South America
1525 - Pineapple
1526 * Bread
1527 * Dairy products"
1528 :group 'org-export
1529 :type 'integer)
1530
1531 (defcustom org-export-preserve-breaks nil
1532 "Non-nil means, preserve all line breaks when exporting.
1533 Normally, in HTML output paragraphs will be reformatted. In ASCII
1534 export, line breaks will always be preserved, regardless of this variable.
1535
1536 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1537 :group 'org-export
1538 :type 'boolean)
1539
1540 (defcustom org-export-html-inline-images t
1541 "Non-nil means, inline images into exported HTML pages.
1542 The link will still be to the original location of the image file.
1543 So if you are moving the page, lets say to your public HTML site,
1544 you will have to move the image and maybe change the link."
1545 :group 'org-export
1546 :type 'boolean)
1547
1548 (defcustom org-export-html-expand t
1549 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1550 When nil, these tags will be exported as plain text and therefore
1551 not be interpreted by a browser.
1552
1553 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1554 :group 'org-export
1555 :type 'boolean)
1556
1557 (defcustom org-export-with-fixed-width t
1558 "Non-nil means, lines starting with \":\" will be in fixed width font.
1559 This can be used to have pre-formatted text, fragments of code etc. For
1560 example:
1561 : ;; Some Lisp examples
1562 : (while (defc cnt)
1563 : (ding))
1564 will be looking just like this in also HTML. In ASCII export, this option
1565 has no effect.
1566
1567 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1568 :group 'org-export
1569 :type 'boolean)
1570
1571 (defcustom org-export-with-tables t
1572 "If non-nil, lines starting with \"|\" define a table.
1573 For example:
1574
1575 | Name | Address | Birthday |
1576 |-------------+----------+-----------|
1577 | Arthur Dent | England | 29.2.2100 |
1578
1579 In ASCII export, this option has no effect.
1580
1581 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1582 :group 'org-export
1583 :type 'boolean)
1584
1585 (defcustom org-export-table-remove-special-lines t
1586 "Remove special lines and marking characters in calculating tables.
1587 This removes the special marking character column from tables that are set
1588 up for spreadsheet calculations. It also removes the entire lines
1589 marked with `!', `_', or `^'. The lines with `$' are kept, because
1590 the values of constants may be useful to have."
1591 :group 'org-export
1592 :type 'boolean)
1593
1594 (defcustom org-export-prefer-native-exporter-for-tables nil
1595 "Non-nil means, always export tables created with table.el natively.
1596 Natively means, use the HTML code generator in table.el.
1597 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1598 the table does not use row- or column-spanning). This has the
1599 advantage, that the automatic HTML conversions for math symbols and
1600 sub/superscripts can be applied. Org-mode's HTML generator is also
1601 much faster."
1602 :group 'org-export
1603 :type 'boolean)
1604
1605 (defcustom org-export-html-table-tag
1606 "<table border=1 cellspacing=0 cellpadding=6>"
1607 "The HTML tag used to start a table.
1608 This must be a <table> tag, but you may change the options like
1609 borders and spacing."
1610 :group 'org-export
1611 :type 'string)
1612
1613 (defcustom org-export-with-emphasize t
1614 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1615 If the export target supports emphasizing text, the word will be
1616 typeset in bold, italic, or underlined, respectively. Works only for
1617 single words, but you can say: I *really* *mean* *this*.
1618 In ASCII export, this option has no effect.
1619
1620 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1621 :group 'org-export
1622 :type 'boolean)
1623
1624 (defcustom org-match-sexp-depth 3
1625 "Number of stacked braces for sub/superscript matching.
1626 This has to be set before loading org.el to be effective."
1627 :group 'org-export
1628 :type 'integer)
1629
1630 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1631 (defcustom org-export-with-sub-superscripts t
1632 "Non-nil means, interpret \"_\" and \"^\" for export.
1633 When this option is turned on, you can use TeX-like syntax for sub- and
1634 superscripts. Several characters after \"_\" or \"^\" will be
1635 considered as a single item - so grouping with {} is normally not
1636 needed. For example, the following things will be parsed as single
1637 sub- or superscripts.
1638
1639 10^24 or 10^tau several digits will be considered 1 item.
1640 10^-12 or 10^-tau a leading sign with digits or a word
1641 x^2-y^3 will be read as x^2 - y^3, because items are
1642 terminated by almost any nonword/nondigit char.
1643 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1644
1645 Still, ambiguity is possible - so when in doubt use {} to enclose the
1646 sub/superscript.
1647 In ASCII export, this option has no effect.
1648
1649 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1650 :group 'org-export
1651 :type 'boolean)
1652
1653 (defcustom org-export-with-TeX-macros t
1654 "Non-nil means, interpret simple TeX-like macros when exporting.
1655 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1656 No only real TeX macros will work here, but the standard HTML entities
1657 for math can be used as macro names as well. For a list of supported
1658 names in HTML export, see the constant `org-html-entities'.
1659 In ASCII export, this option has no effect.
1660
1661 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1662 :group 'org-export
1663 :type 'boolean)
1664
1665 (defcustom org-export-html-with-timestamp nil
1666 "If non-nil, write `org-export-html-html-helper-timestamp'
1667 into the exported HTML text. Otherwise, the buffer will just be saved
1668 to a file."
1669 :group 'org-export
1670 :type 'boolean)
1671
1672 (defcustom org-export-html-html-helper-timestamp
1673 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1674 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1675 :group 'org-export
1676 :type 'string)
1677
1678 (defcustom org-export-ascii-show-new-buffer t
1679 "Non-nil means, popup buffer containing the exported ASCII text.
1680 Otherwise the buffer will just be saved to a file and stay hidden."
1681 :group 'org-export
1682 :type 'boolean)
1683
1684 (defcustom org-export-html-show-new-buffer nil
1685 "Non-nil means, popup buffer containing the exported html text.
1686 Otherwise, the buffer will just be saved to a file and stay hidden."
1687 :group 'org-export
1688 :type 'boolean)
1689
1690 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1691 "The file name for the iCalendar file covering all agenda files.
1692 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1693 :group 'org-export
1694 :type 'file)
1695
1696 (defcustom org-icalendar-include-todo nil
1697 "Non-nil means, export to iCalendar files should also cover TODO items."
1698 :group 'org-export
1699 :type 'boolean)
1700
1701 (defcustom org-icalendar-combined-name "OrgMode"
1702 "Calendar name for the combined iCalendar representing all agenda files."
1703 :group 'org-export
1704 :type 'string)
1705
1706 (defgroup org-font-lock nil
1707 "Faces and settings for highlighting in Org-mode."
1708 :tag "Org Font Lock"
1709 :group 'org)
1710
1711 (defcustom org-level-color-stars-only nil
1712 "Non-nil means fontify only the stars in each headline.
1713 When nil, the entire headline is fontified.
1714 Changing it requires restart of `font-lock-mode' to become effective
1715 also in regions already fontified."
1716 :group 'org-font-lock
1717 :type 'boolean)
1718
1719 (defcustom org-hide-leading-stars nil
1720 "Non-nil means, hide the first N-1 stars in a headline.
1721 This works by using the face `org-hide' for these stars. This
1722 face is white for a light background, and black for a dark
1723 background. You may have to customize the face `org-hide' to
1724 make this work.
1725 Changing it requires restart of `font-lock-mode' to become effective
1726 also in regions already fontified."
1727 :group 'org-font-lock
1728 :type 'boolean)
1729
1730 (defcustom org-fontify-done-headline nil
1731 "Non-nil means, change the face of a headline if it is marked DONE.
1732 Normally, only the TODO/DONE keyword indicates the state of a headline.
1733 When this is non-nil, the headline after the keyword is set to the
1734 `org-headline-done' as an additional indication."
1735 :group 'org-font-lock
1736 :type 'boolean)
1737
1738 (defcustom org-fontify-emphasized-text t
1739 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
1740 Changing this variable requires a restart of Emacs to take effect."
1741 :group 'org-font-lock
1742 :type 'boolean)
1743
1744 (defface org-hide
1745 '(
1746 (((type tty) (class color)) (:foreground "white"))
1747 (((class color) (background light)) (:foreground "white"))
1748 (((class color) (background dark)) (:foreground "black"))
1749 ; (((class color) (background light)) (:foreground "grey90"))
1750 ; (((class color) (background dark)) (:foreground "grey10"))
1751 (t (:inverse-video nil)))
1752 "Face used for level 1 headlines."
1753 :group 'org-font-lock)
1754
1755 (defface org-level-1 ;; font-lock-function-name-face
1756 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1757 (((class color) (background light)) (:foreground "Blue"))
1758 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1759 (t (:inverse-video t :bold t)))
1760 "Face used for level 1 headlines."
1761 :group 'org-font-lock)
1762
1763 (defface org-level-2 ;; font-lock-variable-name-face
1764 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1765 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1766 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1767 (t (:bold t :italic t)))
1768 "Face used for level 2 headlines."
1769 :group 'org-font-lock)
1770
1771 (defface org-level-3 ;; font-lock-keyword-face
1772 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1773 (((class color) (background light)) (:foreground "Purple"))
1774 (((class color) (background dark)) (:foreground "Cyan"))
1775 (t (:bold t)))
1776 "Face used for level 3 headlines."
1777 :group 'org-font-lock)
1778
1779 (defface org-level-4 ;; font-lock-comment-face
1780 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1781 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1782 (((class color) (background light)) (:foreground "Firebrick"))
1783 (((class color) (background dark)) (:foreground "chocolate1"))
1784 (t (:bold t :italic t)))
1785 "Face used for level 4 headlines."
1786 :group 'org-font-lock)
1787
1788 (defface org-level-5 ;; font-lock-type-face
1789 '((((type tty) (class color)) (:foreground "green"))
1790 (((class color) (background light)) (:foreground "ForestGreen"))
1791 (((class color) (background dark)) (:foreground "PaleGreen"))
1792 (t (:bold t :underline t)))
1793 "Face used for level 5 headlines."
1794 :group 'org-font-lock)
1795
1796 (defface org-level-6 ;; font-lock-constant-face
1797 '((((type tty) (class color)) (:foreground "magenta"))
1798 (((class color) (background light)) (:foreground "CadetBlue"))
1799 (((class color) (background dark)) (:foreground "Aquamarine"))
1800 (t (:bold t :underline t)))
1801 "Face used for level 6 headlines."
1802 :group 'org-font-lock)
1803
1804 (defface org-level-7 ;; font-lock-builtin-face
1805 '((((type tty) (class color)) (:foreground "blue" :weight light))
1806 (((class color) (background light)) (:foreground "Orchid"))
1807 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1808 (t (:bold t)))
1809 "Face used for level 7 headlines."
1810 :group 'org-font-lock)
1811
1812 (defface org-level-8 ;; font-lock-string-face
1813 '((((type tty) (class color)) (:foreground "green"))
1814 (((class color) (background light)) (:foreground "RosyBrown"))
1815 (((class color) (background dark)) (:foreground "LightSalmon"))
1816 (t (:italic t)))
1817 "Face used for level 8 headlines."
1818 :group 'org-font-lock)
1819
1820 (defface org-special-keyword ;; font-lock-string-face
1821 '((((type tty) (class color)) (:foreground "green"))
1822 (((class color) (background light)) (:foreground "RosyBrown"))
1823 (((class color) (background dark)) (:foreground "LightSalmon"))
1824 (t (:italic t)))
1825 "Face used for special keywords."
1826 :group 'org-font-lock)
1827
1828 (defface org-warning ;; font-lock-warning-face
1829 '((((type tty) (class color)) (:foreground "red"))
1830 (((class color) (background light)) (:foreground "Red" :bold t))
1831 (((class color) (background dark)) (:foreground "Red1" :bold t))
1832 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1833 (t (:inverse-video t :bold t)))
1834 "Face for deadlines and TODO keywords."
1835 :group 'org-font-lock)
1836
1837 (defface org-headline-done ;; font-lock-string-face
1838 '((((type tty) (class color)) (:foreground "green"))
1839 (((class color) (background light)) (:foreground "RosyBrown"))
1840 (((class color) (background dark)) (:foreground "LightSalmon"))
1841 (t (:italic t)))
1842 "Face used to indicate that a headline is DONE. See also the variable
1843 `org-fontify-done-headline'."
1844 :group 'org-font-lock)
1845
1846 ;; Inheritance does not yet work for xemacs. So we just copy...
1847
1848 (defface org-deadline-announce
1849 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1850 (((class color) (background light)) (:foreground "Blue"))
1851 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1852 (t (:inverse-video t :bold t)))
1853 "Face for upcoming deadlines."
1854 :group 'org-font-lock)
1855
1856 (defface org-scheduled-today
1857 '((((type tty) (class color)) (:foreground "green"))
1858 (((class color) (background light)) (:foreground "DarkGreen"))
1859 (((class color) (background dark)) (:foreground "PaleGreen"))
1860 (t (:bold t :underline t)))
1861 "Face for items scheduled for a certain day."
1862 :group 'org-font-lock)
1863
1864 (defface org-scheduled-previously
1865 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1866 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1867 (((class color) (background light)) (:foreground "Firebrick"))
1868 (((class color) (background dark)) (:foreground "chocolate1"))
1869 (t (:bold t :italic t)))
1870 "Face for items scheduled previously, and not yet done."
1871 :group 'org-font-lock)
1872
1873 (defface org-formula
1874 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1875 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1876 (((class color) (background light)) (:foreground "Firebrick"))
1877 (((class color) (background dark)) (:foreground "chocolate1"))
1878 (t (:bold t :italic t)))
1879 "Face for formulas."
1880 :group 'org-font-lock)
1881
1882 (defface org-link
1883 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1884 (((class color) (background light)) (:foreground "Purple"))
1885 (((class color) (background dark)) (:foreground "Cyan"))
1886 (t (:bold t)))
1887 "Face for links."
1888 :group 'org-font-lock)
1889
1890 (defface org-tag
1891 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1892 (((class color) (background light)) (:foreground "Purple" :weight bold))
1893 (((class color) (background dark)) (:foreground "Cyan" :weight bold))
1894 (t (:bold t)))
1895 "Face for tags."
1896 :group 'org-font-lock)
1897
1898 (defface org-done ;; font-lock-type-face
1899 '((((type tty) (class color)) (:foreground "green"))
1900 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1901 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1902 (t (:bold t :underline t)))
1903 "Face used for DONE."
1904 :group 'org-font-lock)
1905
1906 (defface org-table ;; font-lock-function-name-face
1907 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1908 (((class color) (background light)) (:foreground "Blue"))
1909 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1910 (t (:inverse-video t :bold t)))
1911 "Face used for tables."
1912 :group 'org-font-lock)
1913
1914 (defface org-time-grid ;; font-lock-variable-name-face
1915 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1916 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1917 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1918 (t (:bold t :italic t)))
1919 "Face used for time grids."
1920 :group 'org-font-lock)
1921
1922 (defvar org-level-faces
1923 '(org-level-1 org-level-2 org-level-3 org-level-4
1924 org-level-5 org-level-6 org-level-7 org-level-8
1925 ))
1926 (defvar org-n-levels (length org-level-faces))
1927
1928 (defun org-set-regexps-and-options ()
1929 "Precompute regular expressions for current buffer."
1930 (when (eq major-mode 'org-mode)
1931 (let ((re (org-make-options-regexp
1932 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1933 "STARTUP" "ARCHIVE")))
1934 (splitre "[ \t]+")
1935 kwds int key value cat arch)
1936 (save-excursion
1937 (save-restriction
1938 (widen)
1939 (goto-char (point-min))
1940 (while (re-search-forward re nil t)
1941 (setq key (match-string 1) value (match-string 2))
1942 (cond
1943 ((equal key "CATEGORY")
1944 (if (string-match "[ \t]+$" value)
1945 (setq value (replace-match "" t t value)))
1946 (setq cat (intern value)))
1947 ((equal key "SEQ_TODO")
1948 (setq int 'sequence
1949 kwds (append kwds (org-split-string value splitre))))
1950 ((equal key "PRI_TODO")
1951 (setq int 'priority
1952 kwds (append kwds (org-split-string value splitre))))
1953 ((equal key "TYP_TODO")
1954 (setq int 'type
1955 kwds (append kwds (org-split-string value splitre))))
1956 ((equal key "STARTUP")
1957 (let ((opts (org-split-string value splitre))
1958 (set '(("fold" org-startup-folded t)
1959 ("nofold" org-startup-folded nil)
1960 ("content" org-startup-folded content)
1961 ("hidestars" org-hide-leading-stars t)
1962 ("showstars" org-hide-leading-stars nil)
1963 ("odd" org-odd-levels-only t)
1964 ("oddeven" org-odd-levels-only nil)
1965 ("dlcheck" org-startup-with-deadline-check t)
1966 ("nodlcheck" org-startup-with-deadline-check nil)))
1967 l var val)
1968 (while (setq l (assoc (pop opts) set))
1969 (setq var (nth 1 l) val (nth 2 l))
1970 (set (make-local-variable var) val))))
1971 ((equal key "ARCHIVE")
1972 (string-match " *$" value)
1973 (setq arch (replace-match "" t t value))
1974 (remove-text-properties 0 (length arch)
1975 '(face t fontified t) arch)))
1976 )))
1977 (and cat (set (make-local-variable 'org-category) cat))
1978 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1979 (and arch (set (make-local-variable 'org-archive-location) arch))
1980 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1981 ;; Compute the regular expressions and other local variables
1982 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1983 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1984 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1985 (length org-scheduled-string)))
1986 org-done-string
1987 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1988 org-todo-regexp
1989 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1990 "\\|") "\\)\\>")
1991 org-not-done-regexp
1992 (concat "\\<\\("
1993 (mapconcat 'regexp-quote
1994 (nreverse (cdr (reverse org-todo-keywords)))
1995 "\\|")
1996 "\\)\\>")
1997 org-todo-line-regexp
1998 (concat "^\\(\\*+\\)[ \t]*\\("
1999 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2000 "\\)? *\\(.*\\)")
2001 org-nl-done-regexp
2002 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2003 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2004 org-deadline-regexp (concat "\\<" org-deadline-string)
2005 org-deadline-time-regexp
2006 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2007 org-deadline-line-regexp
2008 (concat "\\<\\(" org-deadline-string "\\).*")
2009 org-scheduled-regexp
2010 (concat "\\<" org-scheduled-string)
2011 org-scheduled-time-regexp
2012 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2013 (org-set-font-lock-defaults)))
2014
2015 ;; Tell the compiler about dynamically scoped variables,
2016 ;; and variables from other packages
2017 (defvar zmacs-regions)
2018 (defvar original-date)
2019 (defvar org-transient-mark-mode)
2020 (defvar org-old-auto-fill-inhibit-regexp)
2021 (defvar orgtbl-mode-menu)
2022 (defvar org-html-entities)
2023 (defvar org-goto-start-pos)
2024 (defvar org-cursor-color)
2025 (defvar org-time-was-given)
2026 (defvar org-ts-what)
2027 (defvar mark-active)
2028 (defvar timecnt)
2029 (defvar levels-open)
2030 (defvar title)
2031 (defvar author)
2032 (defvar email)
2033 (defvar text)
2034 (defvar entry)
2035 (defvar date)
2036 (defvar language)
2037 (defvar options)
2038 (defvar ans1)
2039 (defvar ans2)
2040 (defvar starting-day)
2041 (defvar include-all-loc)
2042 (defvar vm-message-pointer)
2043 (defvar vm-folder-directory)
2044 (defvar wl-summary-buffer-elmo-folder)
2045 (defvar wl-summary-buffer-folder-name)
2046 (defvar gnus-group-name)
2047 (defvar gnus-article-current)
2048 (defvar w3m-current-url)
2049 (defvar mh-progs)
2050 (defvar mh-current-folder)
2051 (defvar mh-show-folder-buffer)
2052 (defvar mh-index-folder)
2053 (defvar mh-searcher)
2054 (defvar org-selected-point)
2055 (defvar calendar-mode-map)
2056 (defvar remember-save-after-remembering)
2057 (defvar remember-data-file)
2058 (defvar last-arg)
2059
2060 ;;; Define the mode
2061
2062 (defvar org-mode-map (copy-keymap outline-mode-map)
2063 "Keymap for Org-mode.")
2064
2065 (defvar org-struct-menu)
2066 (defvar org-org-menu)
2067 (defvar org-tbl-menu)
2068
2069 ;; We use a before-change function to check if a table might need
2070 ;; an update.
2071 (defvar org-table-may-need-update t
2072 "Indicates that a table might need an update.
2073 This variable is set by `org-before-change-function'.
2074 `org-table-align' sets it back to nil.")
2075 (defvar org-mode-hook nil)
2076 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2077 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2078
2079
2080 ;;;###autoload
2081 (define-derived-mode org-mode outline-mode "Org"
2082 "Outline-based notes management and organizer, alias
2083 \"Carsten's outline-mode for keeping track of everything.\"
2084
2085 Org-mode develops organizational tasks around a NOTES file which
2086 contains information about projects as plain text. Org-mode is
2087 implemented on top of outline-mode, which is ideal to keep the content
2088 of large files well structured. It supports ToDo items, deadlines and
2089 time stamps, which magically appear in the diary listing of the Emacs
2090 calendar. Tables are easily created with a built-in table editor.
2091 Plain text URL-like links connect to websites, emails (VM), Usenet
2092 messages (Gnus), BBDB entries, and any files related to the project.
2093 For printing and sharing of notes, an Org-mode file (or a part of it)
2094 can be exported as a structured ASCII or HTML file.
2095
2096 The following commands are available:
2097
2098 \\{org-mode-map}"
2099 (easy-menu-add org-org-menu)
2100 (easy-menu-add org-tbl-menu)
2101 (org-install-agenda-files-menu)
2102 (setq outline-regexp "\\*+")
2103 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2104 (setq outline-level 'org-outline-level)
2105 (if org-startup-truncated (setq truncate-lines t))
2106 (org-set-regexps-and-options)
2107 (set (make-local-variable 'font-lock-unfontify-region-function)
2108 'org-unfontify-region)
2109 ;; Activate before-change-function
2110 (set (make-local-variable 'org-table-may-need-update) t)
2111 (org-add-hook 'before-change-functions 'org-before-change-function nil
2112 'local)
2113 ;; Paragraphs and auto-filling
2114 (org-set-autofill-regexps)
2115 (org-update-radio-target-regexp)
2116 ;; Settings for Calc embedded mode
2117 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2118 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2119 (if (and org-insert-mode-line-in-empty-file
2120 (interactive-p)
2121 (= (point-min) (point-max)))
2122 (insert " -*- mode: org -*-\n\n"))
2123
2124 ;; Get rid of Outline menus, they are not needed
2125 ;; Need to do this here because define-derived-mode sets up
2126 ;; the keymap so late.
2127 (if org-xemacs-p
2128 (progn
2129 (delete-menu-item '("Headings"))
2130 (delete-menu-item '("Show"))
2131 (delete-menu-item '("Hide"))
2132 (set-menubar-dirty-flag))
2133 (define-key org-mode-map [menu-bar headings] 'undefined)
2134 (define-key org-mode-map [menu-bar hide] 'undefined)
2135 (define-key org-mode-map [menu-bar show] 'undefined))
2136
2137 (unless org-inhibit-startup
2138 (if org-startup-with-deadline-check
2139 (call-interactively 'org-check-deadlines)
2140 (cond
2141 ((eq org-startup-folded t)
2142 (org-cycle '(4)))
2143 ((eq org-startup-folded 'content)
2144 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2145 (org-cycle '(4)) (org-cycle '(4))))))))
2146
2147 (defsubst org-current-line (&optional pos)
2148 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2149
2150
2151 ;; FIXME: Do we need to copy?
2152 (defun org-string-props (string &rest properties)
2153 "Add PROPERTIES to string."
2154 (add-text-properties 0 (length string) properties string)
2155 string)
2156
2157 ;;; Font-Lock stuff
2158
2159 (defvar org-mouse-map (make-sparse-keymap))
2160 (define-key org-mouse-map
2161 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2162 (define-key org-mouse-map
2163 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2164 (define-key org-mouse-map [follow-link] 'mouse-face)
2165 (when org-tab-follows-link
2166 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2167 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2168 (when org-return-follows-link
2169 (define-key org-mouse-map [(return)] 'org-open-at-point)
2170 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2171
2172 (require 'font-lock)
2173
2174 (defconst org-non-link-chars "\t\n\r|<>\000")
2175 (defconst org-link-regexp
2176 (if org-allow-space-in-links
2177 (concat
2178 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2179 (concat
2180 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2181 )
2182 "Regular expression for matching links.")
2183 (defconst org-link-maybe-angles-regexp
2184 (concat "<?\\(" org-link-regexp "\\)>?")
2185 "Matches a link and optionally surrounding angle brackets.")
2186 (defconst org-protected-link-regexp
2187 (concat "\000" org-link-regexp "\000")
2188 "Matches a link and optionally surrounding angle brackets.")
2189
2190 (defconst org-bracket-link-regexp
2191 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2192 "Matches a link in double brackets.")
2193
2194 (defconst org-ts-lengths
2195 (cons (length (format-time-string (car org-time-stamp-formats)))
2196 (length (format-time-string (cdr org-time-stamp-formats))))
2197 "This holds the lengths of the two different time formats.")
2198 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2199 "Regular expression for fast time stamp matching.")
2200 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2201 "Regular expression for fast time stamp matching.")
2202 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2203 "Regular expression matching time strings for analysis.")
2204 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2205 "Regular expression matching time stamps, with groups.")
2206 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2207 "Regular expression matching a time stamp range.")
2208 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2209 org-ts-regexp "\\)?")
2210 "Regular expression matching a time stamp or time stamp range.")
2211
2212 (defun org-activate-links (limit)
2213 "Run through the buffer and add overlays to links."
2214 (if (re-search-forward org-link-regexp limit t)
2215 (progn
2216 (add-text-properties (match-beginning 0) (match-end 0)
2217 (list 'mouse-face 'highlight
2218 'keymap org-mouse-map))
2219 t)))
2220
2221 (defun org-activate-links2 (limit)
2222 "Run through the buffer and add overlays to links."
2223 (if (re-search-forward org-bracket-link-regexp limit t)
2224 (progn
2225 (add-text-properties (match-beginning 0) (match-end 0)
2226 (list 'mouse-face 'highlight
2227 'keymap org-mouse-map))
2228 t)))
2229
2230 (defun org-activate-dates (limit)
2231 "Run through the buffer and add overlays to dates."
2232 (if (re-search-forward org-tsr-regexp limit t)
2233 (progn
2234 (add-text-properties (match-beginning 0) (match-end 0)
2235 (list 'mouse-face 'highlight
2236 'keymap org-mouse-map))
2237 t)))
2238
2239 (defvar org-target-link-regexp nil
2240 "Regular expression matching radio targets in plain text.")
2241 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2242 "Regular expression matching a link target.")
2243 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2244 "Regular expression matching a link target.")
2245
2246 (defun org-activate-target-links (limit)
2247 "Run through the buffer and add overlays to target matches."
2248 (when (and org-radio-targets org-target-link-regexp)
2249 (let ((case-fold-search t))
2250 (if (re-search-forward org-target-link-regexp limit t)
2251 (progn
2252 (add-text-properties (match-beginning 0) (match-end 0)
2253 (list 'mouse-face 'highlight
2254 'keymap org-mouse-map
2255 'org-linked-text t))
2256 t)))))
2257
2258 (defun org-update-radio-target-regexp ()
2259 "Find all radio targets in this file and update the regular expression."
2260 (interactive)
2261 (when org-radio-targets
2262 (setq org-target-link-regexp
2263 (org-make-target-link-regexp (org-all-targets 'radio)))
2264 (font-lock-mode -1)
2265 (font-lock-mode 1)))
2266
2267 (defun org-all-targets (&optional radio)
2268 "Return a list of all targets in this file.
2269 With optional argument RADIO, only find radio targets."
2270 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2271 rtn)
2272 (save-excursion
2273 (goto-char (point-min))
2274 (while (re-search-forward re nil t)
2275 (add-to-list 'rtn (downcase
2276 (if (fboundp 'match-string-no-properties)
2277 (match-string-no-properties 1)
2278 (match-string 1)))))
2279 rtn)))
2280
2281 (defun org-make-target-link-regexp (targets)
2282 "Make regular expression matching all strings in TARGETS.
2283 The regular expression finds the targets also if there is a line break
2284 between words."
2285 (and targets
2286 (concat
2287 "\\<\\("
2288 (mapconcat
2289 (lambda (x)
2290 (while (string-match " +" x)
2291 (setq x (replace-match "\\s-+" t t x)))
2292 x)
2293 targets
2294 "\\|")
2295 "\\)\\>")))
2296
2297 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2298 "Matches CamelCase words, possibly with a star before it.")
2299
2300 (defun org-activate-camels (limit)
2301 "Run through the buffer and add overlays to dates."
2302 (if org-activate-camels
2303 (if (re-search-forward org-camel-regexp limit t)
2304 (progn
2305 (add-text-properties (match-beginning 0) (match-end 0)
2306 (list 'mouse-face 'highlight
2307 'keymap org-mouse-map))
2308 t))))
2309
2310 (defun org-activate-tags (limit)
2311 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2312 (progn
2313 (add-text-properties (match-beginning 1) (match-end 1)
2314 (list 'mouse-face 'highlight
2315 'keymap org-mouse-map))
2316 t)))
2317
2318 (defun org-font-lock-level ()
2319 (save-excursion
2320 (org-back-to-heading t)
2321 (- (match-end 0) (match-beginning 0))))
2322
2323 (defun org-outline-level ()
2324 (save-excursion
2325 (looking-at outline-regexp)
2326 (if (match-beginning 1)
2327 (+ (org-get-string-indentation (match-string 1)) 1000)
2328 (- (match-end 0) (match-beginning 0)))))
2329
2330 (defvar org-font-lock-keywords nil)
2331
2332 (defun org-set-font-lock-defaults ()
2333 (let* ((em org-fontify-emphasized-text)
2334 (org-font-lock-extra-keywords
2335 (list
2336 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2337 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2338 '(org-activate-links (0 'org-link t))
2339 '(org-activate-links2 (0 'org-link t))
2340 '(org-activate-target-links (0 'org-link t))
2341 '(org-activate-dates (0 'org-link t))
2342 '(org-activate-camels (0 'org-link t))
2343 '(org-activate-tags (1 'org-tag t))
2344 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2345 '(1 'org-warning t))
2346 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2347 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2348 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2349 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2350 ; (if em '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)" (3 'bold)))
2351 ; (if em '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)" (3 'italic)))
2352 ; (if em '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)" (3 'underline)))
2353 (if em '("\\*[a-zA-Z]+\\*" 0 'bold))
2354 (if em '("/*[a-zA-Z]+/" 0 'italic))
2355 (if em '("_[a-zA-Z]+_" 0 'underline))
2356 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2357 "\\|" org-quote-string "\\)\\>")
2358 '(1 'org-special-keyword t))
2359 '("^#.*" (0 'font-lock-comment-face t))
2360 (if org-fontify-done-headline
2361 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2362 '(1 'org-done t) '(2 'org-headline-done t))
2363 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2364 '(1 'org-done t)))
2365 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2366 (1 'org-table t))
2367 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2368 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2369 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2370 )))
2371 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
2372 ;; Now set the full font-lock-keywords
2373 (set (make-local-variable 'org-font-lock-keywords)
2374 org-font-lock-extra-keywords)
2375 (set (make-local-variable 'font-lock-defaults)
2376 '(org-font-lock-keywords t nil nil backward-paragraph))
2377 (kill-local-variable 'font-lock-keywords) nil))
2378
2379 (defvar org-m nil)
2380 (defvar org-l nil)
2381 (defvar org-f nil)
2382 (defun org-get-level-face (n)
2383 "Get the right face for match N in font-lock matching of healdines."
2384 (setq org-l (- (match-end 2) (match-beginning 1)))
2385 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2386 (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2387 (cond
2388 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2389 ((eq n 2) org-f)
2390 (t (if org-level-color-stars-only nil org-f))))
2391
2392 (defun org-unfontify-region (beg end &optional maybe_loudly)
2393 "Remove fontification and activation overlays from links."
2394 (font-lock-default-unfontify-region beg end)
2395 (let* ((buffer-undo-list t)
2396 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2397 (inhibit-modification-hooks t)
2398 deactivate-mark buffer-file-name buffer-file-truename)
2399 (remove-text-properties beg end
2400 '(mouse-face nil keymap nil org-linked-text nil))))
2401
2402 ;;; Visibility cycling
2403
2404 (defvar org-cycle-global-status nil)
2405 (defvar org-cycle-subtree-status nil)
2406 (defun org-cycle (&optional arg)
2407 "Visibility cycling for Org-mode.
2408
2409 - When this function is called with a prefix argument, rotate the entire
2410 buffer through 3 states (global cycling)
2411 1. OVERVIEW: Show only top-level headlines.
2412 2. CONTENTS: Show all headlines of all levels, but no body text.
2413 3. SHOW ALL: Show everything.
2414
2415 - When point is at the beginning of a headline, rotate the subtree started
2416 by this line through 3 different states (local cycling)
2417 1. FOLDED: Only the main headline is shown.
2418 2. CHILDREN: The main headline and the direct children are shown.
2419 From this state, you can move to one of the children
2420 and zoom in further.
2421 3. SUBTREE: Show the entire subtree, including body text.
2422
2423 - When there is a numeric prefix, go up to a heading with level ARG, do
2424 a `show-subtree' and return to the previous cursor position. If ARG
2425 is negative, go up that many levels.
2426
2427 - When point is not at the beginning of a headline, execute
2428 `indent-relative', like TAB normally does. See the option
2429 `org-cycle-emulate-tab' for details.
2430
2431 - Special case: if point is the the beginning of the buffer and there is
2432 no headline in line 1, this function will act as if called with prefix arg."
2433 (interactive "P")
2434
2435 (if (or (and (bobp) (not (looking-at outline-regexp)))
2436 (equal arg '(4)))
2437 ;; special case: use global cycling
2438 (setq arg t))
2439
2440 (let ((outline-regexp
2441 (if org-cycle-include-plain-lists
2442 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2443 outline-regexp)))
2444
2445 (cond
2446
2447 ((org-at-table-p 'any)
2448 ;; Enter the table or move to the next field in the table
2449 (or (org-table-recognize-table.el)
2450 (progn
2451 (org-table-justify-field-maybe)
2452 (org-table-next-field))))
2453
2454 ((eq arg t) ;; Global cycling
2455
2456 (cond
2457 ((and (eq last-command this-command)
2458 (eq org-cycle-global-status 'overview))
2459 ;; We just created the overview - now do table of contents
2460 ;; This can be slow in very large buffers, so indicate action
2461 (message "CONTENTS...")
2462 (save-excursion
2463 ;; Visit all headings and show their offspring
2464 (goto-char (point-max))
2465 (catch 'exit
2466 (while (and (progn (condition-case nil
2467 (outline-previous-visible-heading 1)
2468 (error (goto-char (point-min))))
2469 t)
2470 (looking-at outline-regexp))
2471 (show-branches)
2472 (if (bobp) (throw 'exit nil))))
2473 (message "CONTENTS...done"))
2474 (setq org-cycle-global-status 'contents)
2475 (run-hook-with-args 'org-cycle-hook 'contents))
2476
2477 ((and (eq last-command this-command)
2478 (eq org-cycle-global-status 'contents))
2479 ;; We just showed the table of contents - now show everything
2480 (show-all)
2481 (message "SHOW ALL")
2482 (setq org-cycle-global-status 'all)
2483 (run-hook-with-args 'org-cycle-hook 'all))
2484
2485 (t
2486 ;; Default action: go to overview
2487 (hide-sublevels 1)
2488 (message "OVERVIEW")
2489 (setq org-cycle-global-status 'overview)
2490 (run-hook-with-args 'org-cycle-hook 'overview))))
2491
2492 ((integerp arg)
2493 ;; Show-subtree, ARG levels up from here.
2494 (save-excursion
2495 (org-back-to-heading)
2496 (outline-up-heading (if (< arg 0) (- arg)
2497 (- (funcall outline-level) arg)))
2498 (org-show-subtree)))
2499
2500 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2501 ;; At a heading: rotate between three different views
2502 (org-back-to-heading)
2503 (let ((goal-column 0) eoh eol eos)
2504 ;; First, some boundaries
2505 (save-excursion
2506 (org-back-to-heading)
2507 (save-excursion
2508 (beginning-of-line 2)
2509 (while (and (not (eobp)) ;; this is like `next-line'
2510 (get-char-property (1- (point)) 'invisible))
2511 (beginning-of-line 2)) (setq eol (point)))
2512 (outline-end-of-heading) (setq eoh (point))
2513 (org-end-of-subtree t) (setq eos (point))
2514 (outline-next-heading))
2515 ;; Find out what to do next and set `this-command'
2516 (cond
2517 ((= eos eoh)
2518 ;; Nothing is hidden behind this heading
2519 (message "EMPTY ENTRY")
2520 (setq org-cycle-subtree-status nil))
2521 ((>= eol eos)
2522 ;; Entire subtree is hidden in one line: open it
2523 (org-show-entry)
2524 (show-children)
2525 (message "CHILDREN")
2526 (setq org-cycle-subtree-status 'children)
2527 (run-hook-with-args 'org-cycle-hook 'children))
2528 ((and (eq last-command this-command)
2529 (eq org-cycle-subtree-status 'children))
2530 ;; We just showed the children, now show everything.
2531 (org-show-subtree)
2532 (message "SUBTREE")
2533 (setq org-cycle-subtree-status 'subtree)
2534 (run-hook-with-args 'org-cycle-hook 'subtree))
2535 (t
2536 ;; Default action: hide the subtree.
2537 (hide-subtree)
2538 (message "FOLDED")
2539 (setq org-cycle-subtree-status 'folded)
2540 (run-hook-with-args 'org-cycle-hook 'folded)))))
2541
2542 ;; TAB emulation
2543 (buffer-read-only (org-back-to-heading))
2544 ((if (and (eq org-cycle-emulate-tab 'white)
2545 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2546 t
2547 (eq org-cycle-emulate-tab t))
2548 (if (and (looking-at "[ \n\r\t]")
2549 (string-match "^[ \t]*$" (buffer-substring
2550 (point-at-bol) (point))))
2551 (progn
2552 (beginning-of-line 1)
2553 (and (looking-at "[ \t]+") (replace-match ""))))
2554 (indent-relative))
2555
2556 (t (save-excursion
2557 (org-back-to-heading)
2558 (org-cycle))))))
2559
2560 (defun org-optimize-window-after-visibility-change (state)
2561 "Adjust the window after a change in outline visibility.
2562 This function is the default value of the hook `org-cycle-hook'."
2563 (cond
2564 ((eq state 'overview) (org-first-headline-recenter 1))
2565 ((eq state 'content) nil)
2566 ((eq state 'all) nil)
2567 ((eq state 'folded) nil)
2568 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2569 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2570
2571 (defun org-subtree-end-visible-p ()
2572 "Is the end of the current subtree visible?"
2573 (pos-visible-in-window-p
2574 (save-excursion (org-end-of-subtree t) (point))))
2575
2576 (defun org-first-headline-recenter (&optional N)
2577 "Move cursor to the first headline and recenter the headline.
2578 Optional argument N means, put the headline into the Nth line of the window."
2579 (goto-char (point-min))
2580 (when (re-search-forward (concat "^" outline-regexp) nil t)
2581 (beginning-of-line)
2582 (recenter (prefix-numeric-value N))))
2583
2584 (defvar org-goto-window-configuration nil)
2585 (defvar org-goto-marker nil)
2586 (defvar org-goto-map (make-sparse-keymap))
2587 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2588 (while (setq cmd (pop cmds))
2589 (substitute-key-definition cmd cmd org-goto-map global-map)))
2590 (define-key org-goto-map "\C-m" 'org-goto-ret)
2591 (define-key org-goto-map [(left)] 'org-goto-left)
2592 (define-key org-goto-map [(right)] 'org-goto-right)
2593 (define-key org-goto-map [(?q)] 'org-goto-quit)
2594 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2595 (define-key org-goto-map "\C-i" 'org-cycle)
2596 (define-key org-goto-map [(tab)] 'org-cycle)
2597 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2598 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2599 (define-key org-goto-map "n" 'outline-next-visible-heading)
2600 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2601 (define-key org-goto-map "f" 'outline-forward-same-level)
2602 (define-key org-goto-map "b" 'outline-backward-same-level)
2603 (define-key org-goto-map "u" 'outline-up-heading)
2604 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2605 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2606 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2607 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2608 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2609 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2610 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2611
2612 (defconst org-goto-help
2613 "Select a location to jump to, press RET
2614 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2615
2616 (defun org-goto ()
2617 "Go to a different location of the document, keeping current visibility.
2618
2619 When you want to go to a different location in a document, the fastest way
2620 is often to fold the entire buffer and then dive into the tree. This
2621 method has the disadvantage, that the previous location will be folded,
2622 which may not be what you want.
2623
2624 This command works around this by showing a copy of the current buffer in
2625 overview mode. You can dive into the tree in that copy, to find the
2626 location you want to reach. When pressing RET, the command returns to the
2627 original buffer in which the visibility is still unchanged. It then jumps
2628 to the new location, making it and the headline hierarchy above it visible."
2629 (interactive)
2630 (let* ((org-goto-start-pos (point))
2631 (selected-point
2632 (org-get-location (current-buffer) org-goto-help)))
2633 (if selected-point
2634 (progn
2635 (org-mark-ring-push org-goto-start-pos)
2636 (goto-char selected-point)
2637 (if (or (org-invisible-p) (org-invisible-p2))
2638 (org-show-hierarchy-above)))
2639 (error "Quit"))))
2640
2641 (defun org-get-location (buf help)
2642 "Let the user select a location in the Org-mode buffer BUF.
2643 This function uses a recursive edit. It returns the selected position
2644 or nil."
2645 (let (org-selected-point)
2646 (save-excursion
2647 (save-window-excursion
2648 (delete-other-windows)
2649 (switch-to-buffer (get-buffer-create "*org-goto*"))
2650 (with-output-to-temp-buffer "*Help*"
2651 (princ help))
2652 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2653 (setq buffer-read-only nil)
2654 (erase-buffer)
2655 (insert-buffer-substring buf)
2656 (let ((org-startup-truncated t)
2657 (org-startup-folded t)
2658 (org-startup-with-deadline-check nil))
2659 (org-mode))
2660 (setq buffer-read-only t)
2661 (if (boundp 'org-goto-start-pos)
2662 (goto-char org-goto-start-pos)
2663 (goto-char (point-min)))
2664 (org-beginning-of-line)
2665 (message "Select location and press RET")
2666 ;; now we make sure that during selection, ony very few keys work
2667 ;; and that it is impossible to switch to another window.
2668 (let ((gm (current-global-map))
2669 (overriding-local-map org-goto-map))
2670 (unwind-protect
2671 (progn
2672 (use-global-map org-goto-map)
2673 (recursive-edit))
2674 (use-global-map gm)))))
2675 (kill-buffer "*org-goto*")
2676 org-selected-point))
2677
2678 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2679 (defun org-goto-ret (&optional arg)
2680 "Finish `org-goto' by going to the new location."
2681 (interactive "P")
2682 (setq org-selected-point (point)
2683 current-prefix-arg arg)
2684 (throw 'exit nil))
2685
2686 (defun org-goto-left ()
2687 "Finish `org-goto' by going to the new location."
2688 (interactive)
2689 (if (org-on-heading-p)
2690 (progn
2691 (beginning-of-line 1)
2692 (setq org-selected-point (point)
2693 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2694 (throw 'exit nil))
2695 (error "Not on a heading")))
2696
2697 (defun org-goto-right ()
2698 "Finish `org-goto' by going to the new location."
2699 (interactive)
2700 (if (org-on-heading-p)
2701 (progn
2702 (outline-end-of-subtree)
2703 (or (eobp) (forward-char 1))
2704 (setq org-selected-point (point)
2705 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2706 (throw 'exit nil))
2707 (error "Not on a heading")))
2708
2709 (defun org-goto-quit ()
2710 "Finish `org-goto' without cursor motion."
2711 (interactive)
2712 (setq org-selected-point nil)
2713 (throw 'exit nil))
2714
2715 ;;; Promotion, Demotion, Inserting new headlines
2716
2717 (defvar org-ignore-region nil
2718 "To temporarily disable the active region.")
2719
2720 (defun org-insert-heading (&optional force-heading)
2721 "Insert a new heading or item with same depth at point."
2722 (interactive "P")
2723 (when (or force-heading (not (org-insert-item)))
2724 (let* ((head (save-excursion
2725 (condition-case nil
2726 (org-back-to-heading)
2727 (error (outline-next-heading)))
2728 (prog1 (match-string 0)
2729 (funcall outline-level)))))
2730 (unless (bolp) (newline))
2731 (insert head)
2732 (unless (eolp)
2733 (save-excursion (newline-and-indent)))
2734 (unless (equal (char-before) ?\ )
2735 (insert " "))
2736 (run-hooks 'org-insert-heading-hook))))
2737
2738 (defun org-insert-item ()
2739 "Insert a new item at the current level.
2740 Return t when things worked, nil when we are not in an item."
2741 (when (save-excursion
2742 (condition-case nil
2743 (progn
2744 (org-beginning-of-item)
2745 (org-at-item-p)
2746 t)
2747 (error nil)))
2748 (unless (bolp) (newline))
2749 (insert (match-string 0))
2750 (org-maybe-renumber-ordered-list)
2751 t))
2752
2753 (defun org-insert-todo-heading (arg)
2754 "Insert a new heading with the same level and TODO state as current heading.
2755 If the heading has no TODO state, or if the state is DONE, use the first
2756 state (TODO by default). Also with prefix arg, force first state."
2757 (interactive "P")
2758 (org-insert-heading)
2759 (save-excursion
2760 (org-back-to-heading)
2761 (outline-previous-heading)
2762 (looking-at org-todo-line-regexp))
2763 (if (or arg
2764 (not (match-beginning 2))
2765 (equal (match-string 2) org-done-string))
2766 (insert (car org-todo-keywords) " ")
2767 (insert (match-string 2) " ")))
2768
2769 (defun org-promote-subtree ()
2770 "Promote the entire subtree.
2771 See also `org-promote'."
2772 (interactive)
2773 (save-excursion
2774 (org-map-tree 'org-promote)))
2775
2776 (defun org-demote-subtree ()
2777 "Demote the entire subtree. See `org-demote'.
2778 See also `org-promote'."
2779 (interactive)
2780 (save-excursion
2781 (org-map-tree 'org-demote)))
2782
2783 (defun org-do-promote ()
2784 "Promote the current heading higher up the tree.
2785 If the region is active in `transient-mark-mode', promote all headings
2786 in the region."
2787 (interactive)
2788 (save-excursion
2789 (if (org-region-active-p)
2790 (org-map-region 'org-promote (region-beginning) (region-end))
2791 (org-promote)))
2792 (org-fix-position-after-promote))
2793
2794 (defun org-do-demote ()
2795 "Demote the current heading lower down the tree.
2796 If the region is active in `transient-mark-mode', demote all headings
2797 in the region."
2798 (interactive)
2799 (save-excursion
2800 (if (org-region-active-p)
2801 (org-map-region 'org-demote (region-beginning) (region-end))
2802 (org-demote)))
2803 (org-fix-position-after-promote))
2804
2805 (defun org-fix-position-after-promote ()
2806 "Make sure that after pro/demotion cursor position is right."
2807 (and (equal (char-after) ?\ )
2808 (equal (char-before) ?*)
2809 (forward-char 1)))
2810
2811 (defun org-get-legal-level (level change)
2812 "Rectify a level change under the influence of `org-odd-levels-only'
2813 LEVEL is a current level, CHANGE is by how much the level should be
2814 modified. Even if CHANGE is nil, LEVEL may be returned modified because
2815 even level numbers will become the next higher odd number."
2816 (if org-odd-levels-only
2817 (cond ((not change) (1+ (* 2 (/ level 2))))
2818 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
2819 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
2820 (max 1 (+ level change))))
2821
2822 (defun org-promote ()
2823 "Promote the current heading higher up the tree.
2824 If the region is active in `transient-mark-mode', promote all headings
2825 in the region."
2826 (org-back-to-heading t)
2827 (let* ((level (save-match-data (funcall outline-level)))
2828 (up-head (make-string (org-get-legal-level level -1) ?*))
2829 (diff (abs (- level (length up-head)))))
2830 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2831 (replace-match up-head nil t)
2832 ;; Fixup tag positioning
2833 (and org-auto-align-tags (org-set-tags nil t))
2834 (if org-adapt-indentation
2835 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
2836 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
2837
2838 (defun org-demote ()
2839 "Demote the current heading lower down the tree.
2840 If the region is active in `transient-mark-mode', demote all headings
2841 in the region."
2842 (org-back-to-heading t)
2843 (let* ((level (save-match-data (funcall outline-level)))
2844 (down-head (make-string (org-get-legal-level level 1) ?*))
2845 (diff (abs (- level (length down-head)))))
2846 (replace-match down-head nil t)
2847 ;; Fixup tag positioning
2848 (and org-auto-align-tags (org-set-tags nil t))
2849 (if org-adapt-indentation
2850 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
2851
2852 (defun org-map-tree (fun)
2853 "Call FUN for every heading underneath the current one."
2854 (org-back-to-heading)
2855 (let ((level (funcall outline-level)))
2856 (save-excursion
2857 (funcall fun)
2858 (while (and (progn
2859 (outline-next-heading)
2860 (> (funcall outline-level) level))
2861 (not (eobp)))
2862 (funcall fun)))))
2863
2864 (defun org-map-region (fun beg end)
2865 "Call FUN for every heading between BEG and END."
2866 (let ((org-ignore-region t))
2867 (save-excursion
2868 (setq end (copy-marker end))
2869 (goto-char beg)
2870 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2871 (< (point) end))
2872 (funcall fun))
2873 (while (and (progn
2874 (outline-next-heading)
2875 (< (point) end))
2876 (not (eobp)))
2877 (funcall fun)))))
2878
2879 (defun org-fixup-indentation (from to prohibit)
2880 "Change the indentation in the current entry by re-replacing FROM with TO.
2881 However, if the regexp PROHIBIT matches at all, don't do anything.
2882 This is being used to change indentation along with the length of the
2883 heading marker. But if there are any lines which are not indented, nothing
2884 is changed at all."
2885 (save-excursion
2886 (let ((end (save-excursion (outline-next-heading)
2887 (point-marker))))
2888 (unless (save-excursion (re-search-forward prohibit end t))
2889 (while (re-search-forward from end t)
2890 (replace-match to)
2891 (beginning-of-line 2)))
2892 (move-marker end nil))))
2893
2894 ;;; Vertical tree motion, cutting and pasting of subtrees
2895
2896 (defun org-move-subtree-up (&optional arg)
2897 "Move the current subtree up past ARG headlines of the same level."
2898 (interactive "p")
2899 (org-move-subtree-down (- (prefix-numeric-value arg))))
2900
2901 (defun org-move-subtree-down (&optional arg)
2902 "Move the current subtree down past ARG headlines of the same level."
2903 (interactive "p")
2904 (setq arg (prefix-numeric-value arg))
2905 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2906 'outline-get-last-sibling))
2907 (ins-point (make-marker))
2908 (cnt (abs arg))
2909 beg end txt folded)
2910 ;; Select the tree
2911 (org-back-to-heading)
2912 (setq beg (point))
2913 (save-match-data
2914 (save-excursion (outline-end-of-heading)
2915 (setq folded (org-invisible-p)))
2916 (outline-end-of-subtree))
2917 (outline-next-heading)
2918 (setq end (point))
2919 ;; Find insertion point, with error handling
2920 (goto-char beg)
2921 (while (> cnt 0)
2922 (or (and (funcall movfunc) (looking-at outline-regexp))
2923 (progn (goto-char beg)
2924 (error "Cannot move past superior level or buffer limit")))
2925 (setq cnt (1- cnt)))
2926 (if (> arg 0)
2927 ;; Moving forward - still need to move over subtree
2928 (progn (outline-end-of-subtree)
2929 (outline-next-heading)
2930 (if (not (or (looking-at (concat "^" outline-regexp))
2931 (bolp)))
2932 (newline))))
2933 (move-marker ins-point (point))
2934 (setq txt (buffer-substring beg end))
2935 (delete-region beg end)
2936 (insert txt)
2937 (goto-char ins-point)
2938 (if folded (hide-subtree))
2939 (move-marker ins-point nil)))
2940
2941 (defvar org-subtree-clip ""
2942 "Clipboard for cut and paste of subtrees.
2943 This is actually only a copy of the kill, because we use the normal kill
2944 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2945
2946 (defvar org-subtree-clip-folded nil
2947 "Was the last copied subtree folded?
2948 This is used to fold the tree back after pasting.")
2949
2950 (defun org-cut-subtree ()
2951 "Cut the current subtree into the clipboard.
2952 This is a short-hand for marking the subtree and then cutting it."
2953 (interactive)
2954 (org-copy-subtree 'cut))
2955
2956 (defun org-copy-subtree (&optional cut)
2957 "Cut the current subtree into the clipboard.
2958 This is a short-hand for marking the subtree and then copying it.
2959 If CUT is non nil, actually cut the subtree."
2960 (interactive)
2961 (let (beg end folded)
2962 (org-back-to-heading)
2963 (setq beg (point))
2964 (save-match-data
2965 (save-excursion (outline-end-of-heading)
2966 (setq folded (org-invisible-p)))
2967 (outline-end-of-subtree))
2968 (if (equal (char-after) ?\n) (forward-char 1))
2969 (setq end (point))
2970 (goto-char beg)
2971 (when (> end beg)
2972 (setq org-subtree-clip-folded folded)
2973 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2974 (setq org-subtree-clip (current-kill 0))
2975 (message "%s: Subtree with %d characters"
2976 (if cut "Cut" "Copied")
2977 (length org-subtree-clip)))))
2978
2979 ;; FIXME: this needs to be adapted for the odd-level-only stuff.
2980 (defun org-paste-subtree (&optional level tree)
2981 "Paste the clipboard as a subtree, with modification of headline level.
2982 The entire subtree is promoted or demoted in order to match a new headline
2983 level. By default, the new level is derived from the visible headings
2984 before and after the insertion point, and taken to be the inferior headline
2985 level of the two. So if the previous visible heading is level 3 and the
2986 next is level 4 (or vice versa), level 4 will be used for insertion.
2987 This makes sure that the subtree remains an independent subtree and does
2988 not swallow low level entries.
2989
2990 You can also force a different level, either by using a numeric prefix
2991 argument, or by inserting the heading marker by hand. For example, if the
2992 cursor is after \"*****\", then the tree will be shifted to level 5.
2993
2994 If you want to insert the tree as is, just use \\[yank].
2995
2996 If optional TREE is given, use this text instead of the kill ring."
2997 (interactive "P")
2998 (unless (org-kill-is-subtree-p tree)
2999 (error
3000 (substitute-command-keys
3001 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3002 (let* ((txt (or tree (current-kill 0)))
3003 (^re (concat "^\\(" outline-regexp "\\)"))
3004 (re (concat "\\(" outline-regexp "\\)"))
3005 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3006
3007 (old-level (if (string-match ^re txt)
3008 (- (match-end 0) (match-beginning 0))
3009 -1))
3010 (force-level (cond (level (prefix-numeric-value level))
3011 ((string-match
3012 ^re_ (buffer-substring (point-at-bol) (point)))
3013 (- (match-end 0) (match-beginning 0)))
3014 (t nil)))
3015 (previous-level (save-excursion
3016 (condition-case nil
3017 (progn
3018 (outline-previous-visible-heading 1)
3019 (if (looking-at re)
3020 (- (match-end 0) (match-beginning 0))
3021 1))
3022 (error 1))))
3023 (next-level (save-excursion
3024 (condition-case nil
3025 (progn
3026 (outline-next-visible-heading 1)
3027 (if (looking-at re)
3028 (- (match-end 0) (match-beginning 0))
3029 1))
3030 (error 1))))
3031 (new-level (or force-level (max previous-level next-level)))
3032 (shift (if (or (= old-level -1)
3033 (= new-level -1)
3034 (= old-level new-level))
3035 0
3036 (- new-level old-level)))
3037 (shift1 shift)
3038 (delta (if (> shift 0) -1 1))
3039 (func (if (> shift 0) 'org-demote 'org-promote))
3040 (org-odd-levels-only nil)
3041 beg end)
3042 ;; Remove the forces level indicator
3043 (if force-level
3044 (delete-region (point-at-bol) (point)))
3045 ;; Make sure we start at the beginning of an empty line
3046 (if (not (bolp)) (insert "\n"))
3047 (if (not (looking-at "[ \t]*$"))
3048 (progn (insert "\n") (backward-char 1)))
3049 ;; Paste
3050 (setq beg (point))
3051 (insert txt)
3052 (setq end (point))
3053 (goto-char beg)
3054 ;; Shift if necessary
3055 (if (= shift 0)
3056 (message "Pasted at level %d, without shift" new-level)
3057 (save-restriction
3058 (narrow-to-region beg end)
3059 (while (not (= shift 0))
3060 (org-map-region func (point-min) (point-max))
3061 (setq shift (+ delta shift)))
3062 (goto-char (point-min))
3063 (message "Pasted at level %d, with shift by %d levels"
3064 new-level shift1)))
3065 (if (and (eq org-subtree-clip (current-kill 0))
3066 org-subtree-clip-folded)
3067 ;; The tree was folded before it was killed/copied
3068 (hide-subtree))))
3069
3070 (defun org-kill-is-subtree-p (&optional txt)
3071 "Check if the current kill is an outline subtree, or a set of trees.
3072 Returns nil if kill does not start with a headline, or if the first
3073 headline level is not the largest headline level in the tree.
3074 So this will actually accept several entries of equal levels as well,
3075 which is OK for `org-paste-subtree'.
3076 If optional TXT is given, check this string instead of the current kill."
3077 (let* ((kill (or txt (current-kill 0) ""))
3078 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3079 (- (match-end 0) (match-beginning 0))))
3080 (re (concat "^" outline-regexp))
3081 (start 1))
3082 (if (not start-level)
3083 nil ;; does not even start with a heading
3084 (catch 'exit
3085 (while (setq start (string-match re kill (1+ start)))
3086 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3087 (throw 'exit nil)))
3088 t))))
3089
3090 ;;; Plain list items
3091
3092 (defun org-at-item-p ()
3093 "Is point in a line starting a hand-formatted item?"
3094 (let ((llt org-plain-list-ordered-item-terminator))
3095 (save-excursion
3096 (goto-char (point-at-bol))
3097 (looking-at
3098 (cond
3099 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3100 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3101 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3102 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3103
3104 (defun org-get-indentation ()
3105 "Get the indentation of the current line, interpreting tabs."
3106 (save-excursion
3107 (beginning-of-line 1)
3108 (skip-chars-forward " \t")
3109 (current-column)))
3110
3111 (defun org-beginning-of-item ()
3112 "Go to the beginning 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 (org-back-to-heading)
3116 (beginning-of-line 2) (point)))
3117 ind ind1)
3118 (if (org-at-item-p)
3119 (beginning-of-line 1)
3120 (beginning-of-line 1)
3121 (skip-chars-forward " \t")
3122 (setq ind (current-column))
3123 (if (catch 'exit
3124 (while t
3125 (beginning-of-line 0)
3126 (if (< (point) limit) (throw 'exit nil))
3127 (unless (looking-at " \t]*$")
3128 (skip-chars-forward " \t")
3129 (setq ind1 (current-column))
3130 (if (< ind1 ind)
3131 (throw 'exit (org-at-item-p))))))
3132 nil
3133 (goto-char pos)
3134 (error "Not in an item")))))
3135
3136 (defun org-end-of-item ()
3137 "Go to the end of the current hand-formatted item.
3138 If the cursor is not in an item, throw an error."
3139 (let ((pos (point))
3140 (limit (save-excursion (outline-next-heading) (point)))
3141 (ind (save-excursion
3142 (org-beginning-of-item)
3143 (skip-chars-forward " \t")
3144 (current-column)))
3145 ind1)
3146 (if (catch 'exit
3147 (while t
3148 (beginning-of-line 2)
3149 (if (>= (point) limit) (throw 'exit t))
3150 (unless (looking-at "[ \t]*$")
3151 (skip-chars-forward " \t")
3152 (setq ind1 (current-column))
3153 (if (<= ind1 ind) (throw 'exit t)))))
3154 (beginning-of-line 1)
3155 (goto-char pos)
3156 (error "Not in an item"))))
3157
3158 (defun org-move-item-down (arg)
3159 "Move the plain list item at point down, i.e. swap with following 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 (setq ind1 (org-get-indentation))
3170 (if (and (org-at-item-p) (= ind ind1))
3171 (progn
3172 (org-end-of-item)
3173 (setq txt (buffer-substring beg end))
3174 (save-excursion
3175 (delete-region beg end))
3176 (setq pos (point))
3177 (insert txt)
3178 (goto-char pos)
3179 (org-maybe-renumber-ordered-list))
3180 (goto-char pos)
3181 (error "Cannot move this item further down"))))
3182
3183 (defun org-move-item-up (arg)
3184 "Move the plain list item at point up, i.e. swap with previous item.
3185 Subitems (items with larger indentation) are considered part of the item,
3186 so this really moves item trees."
3187 (interactive "p")
3188 (let (beg end ind ind1 (pos (point)) txt)
3189 (org-beginning-of-item)
3190 (setq beg (point))
3191 (setq ind (org-get-indentation))
3192 (org-end-of-item)
3193 (setq end (point))
3194 (goto-char beg)
3195 (catch 'exit
3196 (while t
3197 (beginning-of-line 0)
3198 (if (looking-at "[ \t]*$")
3199 nil
3200 (if (<= (setq ind1 (org-get-indentation)) ind)
3201 (throw 'exit t)))))
3202 (condition-case nil
3203 (org-beginning-of-item)
3204 (error (goto-char beg)
3205 (error "Cannot move this item further up")))
3206 (setq ind1 (org-get-indentation))
3207 (if (and (org-at-item-p) (= ind ind1))
3208 (progn
3209 (setq txt (buffer-substring beg end))
3210 (save-excursion
3211 (delete-region beg end))
3212 (setq pos (point))
3213 (insert txt)
3214 (goto-char pos)
3215 (org-maybe-renumber-ordered-list))
3216 (goto-char pos)
3217 (error "Cannot move this item further up"))))
3218
3219 (defun org-maybe-renumber-ordered-list ()
3220 "Renumber the ordered list at point if setup allows it.
3221 This tests the user option `org-auto-renumber-ordered-lists' before
3222 doing the renumbering."
3223 (and org-auto-renumber-ordered-lists
3224 (org-at-item-p)
3225 (match-beginning 3)
3226 (org-renumber-ordered-list 1)))
3227
3228 (defun org-get-string-indentation (s)
3229 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3230 (let ((n -1) (i 0) (w tab-width) c)
3231 (catch 'exit
3232 (while (< (setq n (1+ n)) (length s))
3233 (setq c (aref s n))
3234 (cond ((= c ?\ ) (setq i (1+ i)))
3235 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3236 (t (throw 'exit t)))))
3237 i))
3238
3239 (defun org-renumber-ordered-list (arg)
3240 "Renumber an ordered plain list.
3241 Cursor next to be in the first line of an item, the line that starts
3242 with something like \"1.\" or \"2)\"."
3243 (interactive "p")
3244 (unless (and (org-at-item-p)
3245 (match-beginning 3))
3246 (error "This is not an ordered list"))
3247 (let ((line (org-current-line))
3248 (col (current-column))
3249 (ind (org-get-string-indentation
3250 (buffer-substring (point-at-bol) (match-beginning 3))))
3251 ;; (term (substring (match-string 3) -1))
3252 ind1 (n (1- arg)))
3253 ;; find where this list begins
3254 (catch 'exit
3255 (while t
3256 (catch 'next
3257 (beginning-of-line 0)
3258 (if (looking-at "[ \t]*$") (throw 'next t))
3259 (skip-chars-forward " \t") (setq ind1 (current-column))
3260 (if (or (< ind1 ind)
3261 (and (= ind1 ind)
3262 (not (org-at-item-p))))
3263 (throw 'exit t)))))
3264 ;; Walk forward and replace these numbers
3265 (catch 'exit
3266 (while t
3267 (catch 'next
3268 (beginning-of-line 2)
3269 (if (eobp) (throw 'exit nil))
3270 (if (looking-at "[ \t]*$") (throw 'next nil))
3271 (skip-chars-forward " \t") (setq ind1 (current-column))
3272 (if (> ind1 ind) (throw 'next t))
3273 (if (< ind1 ind) (throw 'exit t))
3274 (if (not (org-at-item-p)) (throw 'exit nil))
3275 (if (not (match-beginning 3))
3276 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3277 (delete-region (match-beginning 3) (1- (match-end 3)))
3278 (goto-char (match-beginning 3))
3279 (insert (format "%d" (setq n (1+ n)))))))
3280 (goto-line line)
3281 (move-to-column col)))
3282
3283 (defvar org-last-indent-begin-marker (make-marker))
3284 (defvar org-last-indent-end-marker (make-marker))
3285
3286
3287 (defun org-outdent-item (arg)
3288 "Outdent a local list item."
3289 (interactive "p")
3290 (org-indent-item (- arg)))
3291
3292 (defun org-indent-item (arg)
3293 "Indent a local list item."
3294 (interactive "p")
3295 (unless (org-at-item-p)
3296 (error "Not on an item"))
3297 (let (beg end ind ind1)
3298 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3299 (setq beg org-last-indent-begin-marker
3300 end org-last-indent-end-marker)
3301 (org-beginning-of-item)
3302 (setq beg (move-marker org-last-indent-begin-marker (point)))
3303 (org-end-of-item)
3304 (setq end (move-marker org-last-indent-end-marker (point))))
3305 (goto-char beg)
3306 (skip-chars-forward " \t") (setq ind (current-column))
3307 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3308 (while (< (point) end)
3309 (beginning-of-line 1)
3310 (skip-chars-forward " \t") (setq ind1 (current-column))
3311 (delete-region (point-at-bol) (point))
3312 (indent-to-column (+ ind1 arg))
3313 (beginning-of-line 2))
3314 (goto-char beg)))
3315
3316 ;;; Archiving
3317
3318 (defun org-archive-subtree ()
3319 "Move the current subtree to the archive.
3320 The archive can be a certain top-level heading in the current file, or in
3321 a different file. The tree will be moved to that location, the subtree
3322 heading be marked DONE, and the current time will be added."
3323 (interactive)
3324 ;; Save all relevant TODO keyword-relatex variables
3325 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3326 (tr-org-todo-keywords org-todo-keywords)
3327 (tr-org-todo-interpretation org-todo-interpretation)
3328 (tr-org-done-string org-done-string)
3329 (tr-org-todo-regexp org-todo-regexp)
3330 (tr-org-todo-line-regexp org-todo-line-regexp)
3331 (this-buffer (current-buffer))
3332 file heading buffer level newfile-p)
3333 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3334 (progn
3335 (setq file (format (match-string 1 org-archive-location)
3336 (file-name-nondirectory buffer-file-name))
3337 heading (match-string 2 org-archive-location)))
3338 (error "Invalid `org-archive-location'"))
3339 (if (> (length file) 0)
3340 (setq newfile-p (not (file-exists-p file))
3341 buffer (find-file-noselect file))
3342 (setq buffer (current-buffer)))
3343 (unless buffer
3344 (error "Cannot access file \"%s\"" file))
3345 (if (and (> (length heading) 0)
3346 (string-match "^\\*+" heading))
3347 (setq level (match-end 0))
3348 (setq heading nil level 0))
3349 (save-excursion
3350 ;; We first only copy, in case something goes wrong
3351 ;; we need to protect this-command, to avoid kill-region sets it,
3352 ;; which would lead to duplication of subtrees
3353 (let (this-command) (org-copy-subtree))
3354 (set-buffer buffer)
3355 ;; Enforce org-mode for the archive buffer
3356 (if (not (eq major-mode 'org-mode))
3357 ;; Force the mode for future visits.
3358 (let ((org-insert-mode-line-in-empty-file t))
3359 (call-interactively 'org-mode)))
3360 (when newfile-p
3361 (goto-char (point-max))
3362 (insert (format "\nArchived entries from file %s\n\n"
3363 (buffer-file-name this-buffer))))
3364 ;; Force the TODO keywords of the original buffer
3365 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3366 (org-todo-keywords tr-org-todo-keywords)
3367 (org-todo-interpretation tr-org-todo-interpretation)
3368 (org-done-string tr-org-done-string)
3369 (org-todo-regexp tr-org-todo-regexp)
3370 (org-todo-line-regexp tr-org-todo-line-regexp))
3371 (goto-char (point-min))
3372 (if heading
3373 (progn
3374 (if (re-search-forward
3375 (concat "\\(^\\|\r\\)"
3376 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3377 nil t)
3378 (goto-char (match-end 0))
3379 ;; Heading not found, just insert it at the end
3380 (goto-char (point-max))
3381 (or (bolp) (insert "\n"))
3382 (insert "\n" heading "\n")
3383 (end-of-line 0))
3384 ;; Make the heading visible, and the following as well
3385 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3386 (if (re-search-forward
3387 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3388 nil t)
3389 (progn (goto-char (match-beginning 0)) (insert "\n")
3390 (beginning-of-line 0))
3391 (goto-char (point-max)) (insert "\n")))
3392 (goto-char (point-max)) (insert "\n"))
3393 ;; Paste
3394 (org-paste-subtree (1+ level))
3395 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3396 (if org-archive-mark-done
3397 (org-todo (length org-todo-keywords)))
3398 ;; Move cursor to right after the TODO keyword
3399 (when org-archive-stamp-time
3400 (beginning-of-line 1)
3401 (looking-at org-todo-line-regexp)
3402 (goto-char (or (match-end 2) (match-beginning 3)))
3403 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3404 (current-time))
3405 ")"))
3406 ;; Save the buffer, if it is not the same buffer.
3407 (if (not (eq this-buffer buffer)) (save-buffer))))
3408 ;; Here we are back in the original buffer. Everything seems to have
3409 ;; worked. So now cut the tree and finish up.
3410 (let (this-command) (org-cut-subtree))
3411 (if (looking-at "[ \t]*$") (kill-line))
3412 (message "Subtree archived %s"
3413 (if (eq this-buffer buffer)
3414 (concat "under heading: " heading)
3415 (concat "in file: " (abbreviate-file-name file))))))
3416
3417 ;;; Completion
3418
3419 (defun org-complete (&optional arg)
3420 "Perform completion on word at point.
3421 At the beginning of a headline, this completes TODO keywords as given in
3422 `org-todo-keywords'.
3423 If the current word is preceded by a backslash, completes the TeX symbols
3424 that are supported for HTML support.
3425 If the current word is preceded by \"#+\", completes special words for
3426 setting file options.
3427 At all other locations, this simply calls `ispell-complete-word'."
3428 (interactive "P")
3429 (catch 'exit
3430 (let* ((end (point))
3431 (beg1 (save-excursion
3432 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3433 (skip-chars-backward "a-zA-Z_@0-9")
3434 (point)))
3435 (beg (save-excursion
3436 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3437 (skip-chars-backward "a-zA-Z0-9_:$")
3438 (point)))
3439 (camel (equal (char-before beg) ?*))
3440 (tag (equal (char-before beg1) ?:))
3441 (texp (equal (char-before beg) ?\\))
3442 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3443 beg)
3444 "#+"))
3445 (completion-ignore-case opt)
3446 (type nil)
3447 (tbl nil)
3448 (table (cond
3449 (opt
3450 (setq type :opt)
3451 (mapcar (lambda (x)
3452 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3453 (cons (match-string 2 x) (match-string 1 x)))
3454 (org-split-string (org-get-current-options) "\n")))
3455 (texp
3456 (setq type :tex)
3457 org-html-entities)
3458 ((string-match "\\`\\*+[ \t]*\\'"
3459 (buffer-substring (point-at-bol) beg))
3460 (setq type :todo)
3461 (mapcar 'list org-todo-keywords))
3462 (camel
3463 (setq type :camel)
3464 (save-excursion
3465 (goto-char (point-min))
3466 (while (re-search-forward org-todo-line-regexp nil t)
3467 (push (list
3468 (if org-file-link-context-use-camel-case
3469 (org-make-org-heading-camel (match-string 3) t)
3470 (org-make-org-heading-search-string
3471 (match-string 3) t)))
3472 tbl)))
3473 tbl)
3474 (tag (setq type :tag beg beg1)
3475 (org-get-buffer-tags))
3476 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3477 (pattern (buffer-substring-no-properties beg end))
3478 (completion (try-completion pattern table)))
3479 (cond ((eq completion t)
3480 (if (equal type :opt)
3481 (insert (substring (cdr (assoc (upcase pattern) table))
3482 (length pattern)))))
3483 ((null completion)
3484 (message "Can't find completion for \"%s\"" pattern)
3485 (ding))
3486 ((not (string= pattern completion))
3487 (delete-region beg end)
3488 (if (string-match " +$" completion)
3489 (setq completion (replace-match "" t t completion)))
3490 (insert completion)
3491 (if (get-buffer-window "*Completions*")
3492 (delete-window (get-buffer-window "*Completions*")))
3493 (if (assoc completion table)
3494 (if (eq type :todo) (insert " ")
3495 (if (eq type :tag) (insert ":"))))
3496 (if (and (equal type :opt) (assoc completion table))
3497 (message "%s" (substitute-command-keys
3498 "Press \\[org-complete] again to insert example settings"))))
3499 (t
3500 (message "Making completion list...")
3501 (let ((list (sort (all-completions pattern table) 'string<)))
3502 (with-output-to-temp-buffer "*Completions*"
3503 (condition-case nil
3504 ;; Protection needed for XEmacs and emacs 21
3505 (display-completion-list list pattern)
3506 (error (display-completion-list list)))))
3507 (message "Making completion list...%s" "done"))))))
3508
3509 ;;; Comments, TODO and DEADLINE
3510
3511 (defun org-toggle-comment ()
3512 "Change the COMMENT state of an entry."
3513 (interactive)
3514 (save-excursion
3515 (org-back-to-heading)
3516 (if (looking-at (concat outline-regexp
3517 "\\( +\\<" org-comment-string "\\>\\)"))
3518 (replace-match "" t t nil 1)
3519 (if (looking-at outline-regexp)
3520 (progn
3521 (goto-char (match-end 0))
3522 (insert " " org-comment-string))))))
3523
3524 (defvar org-last-todo-state-is-todo nil
3525 "This is non-nil when the last TODO state change led to a TODO state.
3526 If the last change removed the TODO tag or switched to DONE, then
3527 this is nil.")
3528
3529 (defun org-todo (&optional arg)
3530 "Change the TODO state of an item.
3531 The state of an item is given by a keyword at the start of the heading,
3532 like
3533 *** TODO Write paper
3534 *** DONE Call mom
3535
3536 The different keywords are specified in the variable `org-todo-keywords'.
3537 By default the available states are \"TODO\" and \"DONE\".
3538 So for this example: when the item starts with TODO, it is changed to DONE.
3539 When it starts with DONE, the DONE is removed. And when neither TODO nor
3540 DONE are present, add TODO at the beginning of the heading.
3541
3542 With prefix arg, use completion to determine the new state. With numeric
3543 prefix arg, switch to that state."
3544 (interactive "P")
3545 (save-excursion
3546 (org-back-to-heading)
3547 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3548 (or (looking-at (concat " +" org-todo-regexp " *"))
3549 (looking-at " *"))
3550 (let* ((this (match-string 1))
3551 (completion-ignore-case t)
3552 (member (member this org-todo-keywords))
3553 (tail (cdr member))
3554 (state (cond
3555 ((equal arg '(4))
3556 ;; Read a state with completion
3557 (completing-read "State: " (mapcar (lambda(x) (list x))
3558 org-todo-keywords)
3559 nil t))
3560 ((eq arg 'right)
3561 (if this
3562 (if tail (car tail) nil)
3563 (car org-todo-keywords)))
3564 ((eq arg 'left)
3565 (if (equal member org-todo-keywords)
3566 nil
3567 (if this
3568 (nth (- (length org-todo-keywords) (length tail) 2)
3569 org-todo-keywords)
3570 org-done-string)))
3571 (arg
3572 ;; user requests a specific state
3573 (nth (1- (prefix-numeric-value arg))
3574 org-todo-keywords))
3575 ((null member) (car org-todo-keywords))
3576 ((null tail) nil) ;; -> first entry
3577 ((eq org-todo-interpretation 'sequence)
3578 (car tail))
3579 ((memq org-todo-interpretation '(type priority))
3580 (if (eq this-command last-command)
3581 (car tail)
3582 (if (> (length tail) 0) org-done-string nil)))
3583 (t nil)))
3584 (next (if state (concat " " state " ") " ")))
3585 (replace-match next t t)
3586 (setq org-last-todo-state-is-todo
3587 (not (equal state org-done-string)))
3588 (when org-log-done
3589 (if (equal state org-done-string)
3590 (org-log-done)
3591 (if (not this)
3592 (org-log-done t))))
3593 ;; Fixup tag positioning
3594 (and org-auto-align-tags (org-set-tags nil t))
3595 (run-hooks 'org-after-todo-state-change-hook)))
3596 ;; Fixup cursor location if close to the keyword
3597 (if (and (outline-on-heading-p)
3598 (not (bolp))
3599 (save-excursion (beginning-of-line 1)
3600 (looking-at org-todo-line-regexp))
3601 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3602 (progn
3603 (goto-char (or (match-end 2) (match-end 1)))
3604 (just-one-space))))
3605
3606 (defun org-log-done (&optional undone)
3607 "Add a time stamp logging that a TODO entry has been closed.
3608 When UNDONE is non-nil, remove such a time stamp again."
3609 (interactive)
3610 (let (beg end col)
3611 (save-excursion
3612 (org-back-to-heading t)
3613 (setq beg (point))
3614 (looking-at (concat outline-regexp " *"))
3615 (goto-char (match-end 0))
3616 (setq col (current-column))
3617 (outline-next-heading)
3618 (setq end (point))
3619 (goto-char beg)
3620 (when (re-search-forward (concat
3621 "[\r\n]\\([ \t]*"
3622 (regexp-quote org-closed-string)
3623 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3624 (delete-region (match-beginning 1) (match-end 1)))
3625 (unless undone
3626 (org-back-to-heading t)
3627 (skip-chars-forward "^\n\r")
3628 (goto-char (min (1+ (point)) (point-max)))
3629 (when (not (member (char-before) '(?\r ?\n)))
3630 (insert "\n"))
3631 (indent-to col)
3632 (insert org-closed-string " "
3633 (format-time-string
3634 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3635 (current-time))
3636 "\n")))))
3637
3638 (defun org-show-todo-tree (arg)
3639 "Make a compact tree which shows all headlines marked with TODO.
3640 The tree will show the lines where the regexp matches, and all higher
3641 headlines above the match.
3642 With \\[universal-argument] prefix, also show the DONE entries.
3643 With a numeric prefix N, construct a sparse tree for the Nth element
3644 of `org-todo-keywords'."
3645 (interactive "P")
3646 (let ((case-fold-search nil)
3647 (kwd-re
3648 (cond ((null arg) org-not-done-regexp)
3649 ((equal arg '(4)) org-todo-regexp)
3650 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3651 (regexp-quote (nth (1- (prefix-numeric-value arg))
3652 org-todo-keywords)))
3653 (t (error "Invalid prefix argument: %s" arg)))))
3654 (message "%d TODO entries found"
3655 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3656
3657 (defun org-deadline ()
3658 "Insert the DEADLINE: string to make a deadline.
3659 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3660 to modify it to the correct date."
3661 (interactive)
3662 (insert
3663 org-deadline-string " "
3664 (format-time-string (car org-time-stamp-formats)
3665 (org-read-date nil 'to-time)))
3666 (message "%s" (substitute-command-keys
3667 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3668
3669 (defun org-schedule ()
3670 "Insert the SCHEDULED: string to schedule a TODO item.
3671 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3672 to modify it to the correct date."
3673 (interactive)
3674 (insert
3675 org-scheduled-string " "
3676 (format-time-string (car org-time-stamp-formats)
3677 (org-read-date nil 'to-time)))
3678 (message "%s" (substitute-command-keys
3679 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3680
3681
3682 (defun org-occur (regexp &optional callback)
3683 "Make a compact tree which shows all matches of REGEXP.
3684 The tree will show the lines where the regexp matches, and all higher
3685 headlines above the match. It will also show the heading after the match,
3686 to make sure editing the matching entry is easy.
3687 If CALLBACK is non-nil, it is a function which is called to confirm
3688 that the match should indeed be shown."
3689 (interactive "sRegexp: ")
3690 (org-remove-occur-highlights nil nil t)
3691 (setq regexp (org-check-occur-regexp regexp))
3692 (let ((cnt 0))
3693 (save-excursion
3694 (goto-char (point-min))
3695 (hide-sublevels 1)
3696 (while (re-search-forward regexp nil t)
3697 (when (or (not callback)
3698 (save-match-data (funcall callback)))
3699 (setq cnt (1+ cnt))
3700 (org-highlight-new-match (match-beginning 0) (match-end 0))
3701 (org-show-hierarchy-above))))
3702 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
3703 nil 'local)
3704 (run-hooks 'org-occur-hook)
3705 (if (interactive-p)
3706 (message "%d match(es) for regexp %s" cnt regexp))
3707 cnt))
3708
3709 (defun org-show-hierarchy-above ()
3710 "Make sure point and the headings hierarchy above is visible."
3711 (catch 'exit
3712 (if (org-on-heading-p t)
3713 (org-flag-heading nil) ; only show the heading
3714 (and (or (org-invisible-p) (org-invisible-p2))
3715 (org-show-hidden-entry))) ; show entire entry
3716 (save-excursion
3717 (and org-show-following-heading
3718 (outline-next-heading)
3719 (org-flag-heading nil))) ; show the next heading
3720 (when org-show-hierarchy-above
3721 (save-excursion ; show all higher headings
3722 (while (and (condition-case nil
3723 (progn (org-up-heading-all 1) t)
3724 (error nil))
3725 (not (bobp)))
3726 (org-flag-heading nil))))))
3727
3728 ;; Overlay compatibility functions
3729 (defun org-make-overlay (beg end &optional buffer)
3730 (if org-xemacs-p (make-extent beg end buffer) (make-overlay beg end buffer)))
3731 (defun org-delete-overlay (ovl)
3732 (if org-xemacs-p (delete-extent ovl) (delete-overlay ovl)))
3733 (defun org-detatch-overlay (ovl)
3734 (if org-xemacs-p (detach-extent ovl) (delete-overlay ovl)))
3735 (defun org-move-overlay (ovl beg end &optional buffer)
3736 (if org-xemacs-p
3737 (set-extent-endpoints ovl beg end buffer)
3738 (move-overlay ovl beg end buffer)))
3739 (defun org-overlay-put (ovl prop value)
3740 (if org-xemacs-p
3741 (set-extent-property ovl prop value)
3742 (overlay-put ovl prop value)))
3743
3744 (defvar org-occur-highlights nil)
3745 (defun org-highlight-new-match (beg end)
3746 "Highlight from BEG to END and mark the highlight is an occur headline."
3747 (let ((ov (org-make-overlay beg end)))
3748 (org-overlay-put ov 'face 'secondary-selection)
3749 (push ov org-occur-highlights)))
3750
3751 (defun org-remove-occur-highlights (&optional beg end noremove)
3752 "Remove the occur highlights from the buffer.
3753 BEG and END are ignored. If NOREMOVE is nil, remove this function
3754 from the `before-change-functions' in the current buffer."
3755 (interactive)
3756 (mapc 'org-delete-overlay org-occur-highlights)
3757 (setq org-occur-highlights nil)
3758 (unless noremove
3759 (remove-hook 'before-change-functions
3760 'org-remove-occur-highlights 'local)))
3761
3762 ;;; Priorities
3763
3764 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3765 "Regular expression matching the priority indicator.")
3766
3767 (defvar org-remove-priority-next-time nil)
3768
3769 (defun org-priority-up ()
3770 "Increase the priority of the current item."
3771 (interactive)
3772 (org-priority 'up))
3773
3774 (defun org-priority-down ()
3775 "Decrease the priority of the current item."
3776 (interactive)
3777 (org-priority 'down))
3778
3779 (defun org-priority (&optional action)
3780 "Change the priority of an item by ARG.
3781 ACTION can be set, up, or down."
3782 (interactive)
3783 (setq action (or action 'set))
3784 (let (current new news have remove)
3785 (save-excursion
3786 (org-back-to-heading)
3787 (if (looking-at org-priority-regexp)
3788 (setq current (string-to-char (match-string 2))
3789 have t)
3790 (setq current org-default-priority))
3791 (cond
3792 ((eq action 'set)
3793 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3794 (setq new (read-char-exclusive))
3795 (cond ((equal new ?\ ) (setq remove t))
3796 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3797 (error "Priority must be between `%c' and `%c'"
3798 ?A org-lowest-priority))))
3799 ((eq action 'up)
3800 (setq new (1- current)))
3801 ((eq action 'down)
3802 (setq new (1+ current)))
3803 (t (error "Invalid action")))
3804 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3805 (setq news (format "%c" new))
3806 (if have
3807 (if remove
3808 (replace-match "" t t nil 1)
3809 (replace-match news t t nil 2))
3810 (if remove
3811 (error "No priority cookie found in line")
3812 (looking-at org-todo-line-regexp)
3813 (if (match-end 2)
3814 (progn
3815 (goto-char (match-end 2))
3816 (insert " [#" news "]"))
3817 (goto-char (match-beginning 3))
3818 (insert "[#" news "] ")))))
3819 (if remove
3820 (message "Priority removed")
3821 (message "Priority of current item set to %s" news))))
3822
3823
3824 (defun org-get-priority (s)
3825 "Find priority cookie and return priority."
3826 (save-match-data
3827 (if (not (string-match org-priority-regexp s))
3828 (* 1000 (- org-lowest-priority org-default-priority))
3829 (* 1000 (- org-lowest-priority
3830 (string-to-char (match-string 2 s)))))))
3831
3832 ;;; Timestamps
3833
3834 (defvar org-last-changed-timestamp nil)
3835
3836 (defun org-time-stamp (arg)
3837 "Prompt for a date/time and insert a time stamp.
3838 If the user specifies a time like HH:MM, or if this command is called
3839 with a prefix argument, the time stamp will contain date and time.
3840 Otherwise, only the date will be included. All parts of a date not
3841 specified by the user will be filled in from the current date/time.
3842 So if you press just return without typing anything, the time stamp
3843 will represent the current date/time. If there is already a timestamp
3844 at the cursor, it will be modified."
3845 (interactive "P")
3846 (let ((fmt (if arg (cdr org-time-stamp-formats)
3847 (car org-time-stamp-formats)))
3848 (org-time-was-given nil)
3849 time)
3850 (cond
3851 ((and (org-at-timestamp-p)
3852 (eq last-command 'org-time-stamp)
3853 (eq this-command 'org-time-stamp))
3854 (insert "--")
3855 (setq time (let ((this-command this-command))
3856 (org-read-date arg 'totime)))
3857 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3858 (insert (format-time-string fmt time)))
3859 ((org-at-timestamp-p)
3860 (setq time (let ((this-command this-command))
3861 (org-read-date arg 'totime)))
3862 (and (org-at-timestamp-p) (replace-match
3863 (setq org-last-changed-timestamp
3864 (format-time-string fmt time))
3865 t t))
3866 (message "Timestamp updated"))
3867 (t
3868 (setq time (let ((this-command this-command))
3869 (org-read-date arg 'totime)))
3870 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3871 (insert (format-time-string fmt time))))))
3872
3873 (defun org-time-stamp-inactive (&optional arg)
3874 "Insert an inactive time stamp.
3875 An inactive time stamp is enclosed in square brackets instead of angle
3876 brackets. It is inactive in the sense that it does not trigger agenda entries,
3877 does not link to the calendar and cannot be changed with the S-cursor keys.
3878 So these are more for recording a certain time/date."
3879 ;; FIXME: Would it be better not to ask for a date/time here?
3880 (interactive "P")
3881 (let ((fmt (if arg (cdr org-time-stamp-formats)
3882 (car org-time-stamp-formats)))
3883 (org-time-was-given nil)
3884 time)
3885 (setq time (org-read-date arg 'totime))
3886 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3887 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3888 (insert (format-time-string fmt time))))
3889
3890 (defvar org-date-ovl (org-make-overlay 1 1))
3891 (org-overlay-put org-date-ovl 'face 'org-warning)
3892 (org-detatch-overlay org-date-ovl)
3893
3894 ;;; FIXME: Make the function take "Fri" as "next friday"
3895 ;;; because these are mostly being used to record the current time.
3896 (defun org-read-date (&optional with-time to-time)
3897 "Read a date and make things smooth for the user.
3898 The prompt will suggest to enter an ISO date, but you can also enter anything
3899 which will at least partially be understood by `parse-time-string'.
3900 Unrecognized parts of the date will default to the current day, month, year,
3901 hour and minute. For example,
3902 3-2-5 --> 2003-02-05
3903 feb 15 --> currentyear-02-15
3904 sep 12 9 --> 2009-09-12
3905 12:45 --> today 12:45
3906 22 sept 0:34 --> currentyear-09-22 0:34
3907 12 --> currentyear-currentmonth-12
3908 etc.
3909 The function understands only English month and weekday abbreviations,
3910 but this can be configured with the variables `parse-time-months' and
3911 `parse-time-weekdays'.
3912
3913 While prompting, a calendar is popped up - you can also select the
3914 date with the mouse (button 1). The calendar shows a period of three
3915 months. To scroll it to other months, use the keys `>' and `<'.
3916 If you don't like the calendar, turn it off with
3917 \(setq org-popup-calendar-for-date-prompt nil)
3918
3919 With optional argument TO-TIME, the date will immediately be converted
3920 to an internal time.
3921 With an optional argument WITH-TIME, the prompt will suggest to also
3922 insert a time. Note that when WITH-TIME is not set, you can still
3923 enter a time, and this function will inform the calling routine about
3924 this change. The calling routine may then choose to change the format
3925 used to insert the time stamp into the buffer to include the time."
3926 (require 'parse-time)
3927 (let* ((default-time
3928 ;; Default time is either today, or, when entering a range,
3929 ;; the range start.
3930 (if (save-excursion
3931 (re-search-backward
3932 (concat org-ts-regexp "--\\=")
3933 (- (point) 20) t))
3934 (apply
3935 'encode-time
3936 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3937 (parse-time-string (match-string 1))))
3938 (current-time)))
3939 (calendar-move-hook nil)
3940 (view-diary-entries-initially nil)
3941 (timestr (format-time-string
3942 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3943 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3944 ans ans1 ans2
3945 second minute hour day month year tl)
3946
3947 (if org-popup-calendar-for-date-prompt
3948 ;; Also show a calendar for date selection
3949 ;; Copied (with modifications) from planner.el by John Wiegley
3950 (save-excursion
3951 (save-window-excursion
3952 (calendar)
3953 (calendar-forward-day (- (time-to-days default-time)
3954 (calendar-absolute-from-gregorian
3955 (calendar-current-date))))
3956 (org-eval-in-calendar nil)
3957 (let* ((old-map (current-local-map))
3958 (map (copy-keymap calendar-mode-map))
3959 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3960 (define-key map (kbd "RET") 'org-calendar-select)
3961 (define-key map (if org-xemacs-p [button1] [mouse-1])
3962 'org-calendar-select-mouse)
3963 (define-key map (if org-xemacs-p [button2] [mouse-2])
3964 'org-calendar-select-mouse)
3965 (define-key minibuffer-local-map [(meta shift left)]
3966 (lambda () (interactive)
3967 (org-eval-in-calendar '(calendar-backward-month 1))))
3968 (define-key minibuffer-local-map [(meta shift right)]
3969 (lambda () (interactive)
3970 (org-eval-in-calendar '(calendar-forward-month 1))))
3971 (define-key minibuffer-local-map [(shift up)]
3972 (lambda () (interactive)
3973 (org-eval-in-calendar '(calendar-backward-week 1))))
3974 (define-key minibuffer-local-map [(shift down)]
3975 (lambda () (interactive)
3976 (org-eval-in-calendar '(calendar-forward-week 1))))
3977 (define-key minibuffer-local-map [(shift left)]
3978 (lambda () (interactive)
3979 (org-eval-in-calendar '(calendar-backward-day 1))))
3980 (define-key minibuffer-local-map [(shift right)]
3981 (lambda () (interactive)
3982 (org-eval-in-calendar '(calendar-forward-day 1))))
3983 (define-key minibuffer-local-map ">"
3984 (lambda () (interactive)
3985 (org-eval-in-calendar '(scroll-calendar-left 1))))
3986 (define-key minibuffer-local-map "<"
3987 (lambda () (interactive)
3988 (org-eval-in-calendar '(scroll-calendar-right 1))))
3989 (unwind-protect
3990 (progn
3991 (use-local-map map)
3992 (setq ans (read-string prompt "" nil nil))
3993 (if (not (string-match "\\S-" ans)) (setq ans nil))
3994 (setq ans (or ans1 ans ans2)))
3995 (use-local-map old-map)))))
3996 ;; Naked prompt only
3997 (setq ans (read-string prompt "" nil timestr)))
3998 (org-detatch-overlay org-date-ovl)
3999
4000 (if (string-match
4001 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4002 (progn
4003 (setq year (if (match-end 2)
4004 (string-to-number (match-string 2 ans))
4005 (string-to-number (format-time-string "%Y")))
4006 month (string-to-number (match-string 3 ans))
4007 day (string-to-number (match-string 4 ans)))
4008 (if (< year 100) (setq year (+ 2000 year)))
4009 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4010 t nil ans))))
4011 (setq tl (parse-time-string ans)
4012 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
4013 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
4014 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
4015 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
4016 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
4017 second (or (nth 0 tl) 0))
4018 (if (and (boundp 'org-time-was-given)
4019 (nth 2 tl))
4020 (setq org-time-was-given t))
4021 (if (< year 100) (setq year (+ 2000 year)))
4022 (if to-time
4023 (encode-time second minute hour day month year)
4024 (if (or (nth 1 tl) (nth 2 tl))
4025 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4026 (format "%04d-%02d-%02d" year month day)))))
4027
4028 (defun org-eval-in-calendar (form)
4029 "Eval FORM in the calendar window and return to current window.
4030 Also, store the cursor date in variable ans2."
4031 (let ((sw (selected-window)))
4032 (select-window (get-buffer-window "*Calendar*"))
4033 (eval form)
4034 (when (calendar-cursor-to-date)
4035 (let* ((date (calendar-cursor-to-date))
4036 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4037 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4038 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4039 (select-window sw)))
4040
4041 (defun org-calendar-select ()
4042 "Return to `org-read-date' with the date currently selected.
4043 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4044 (interactive)
4045 (when (calendar-cursor-to-date)
4046 (let* ((date (calendar-cursor-to-date))
4047 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4048 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4049 (if (active-minibuffer-window) (exit-minibuffer))))
4050
4051 (defun org-calendar-select-mouse (ev)
4052 "Return to `org-read-date' with the date currently selected.
4053 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4054 (interactive "e")
4055 (mouse-set-point ev)
4056 (when (calendar-cursor-to-date)
4057 (let* ((date (calendar-cursor-to-date))
4058 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4059 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4060 (if (active-minibuffer-window) (exit-minibuffer))))
4061
4062 (defun org-check-deadlines (ndays)
4063 "Check if there are any deadlines due or past due.
4064 A deadline is considered due if it happens within `org-deadline-warning-days'
4065 days from today's date. If the deadline appears in an entry marked DONE,
4066 it is not shown. The prefix arg NDAYS can be used to test that many
4067 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4068 (interactive "P")
4069 (let* ((org-warn-days
4070 (cond
4071 ((equal ndays '(4)) 100000)
4072 (ndays (prefix-numeric-value ndays))
4073 (t org-deadline-warning-days)))
4074 (case-fold-search nil)
4075 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4076 (callback
4077 (lambda ()
4078 (and (let ((d1 (time-to-days (current-time)))
4079 (d2 (time-to-days
4080 (org-time-string-to-time (match-string 1)))))
4081 (< (- d2 d1) org-warn-days))
4082 (not (org-entry-is-done-p))))))
4083 (message "%d deadlines past-due or due within %d days"
4084 (org-occur regexp callback)
4085 org-warn-days)))
4086
4087 (defun org-evaluate-time-range (&optional to-buffer)
4088 "Evaluate a time range by computing the difference between start and end.
4089 Normally the result is just printed in the echo area, but with prefix arg
4090 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4091 If the time range is actually in a table, the result is inserted into the
4092 next column.
4093 For time difference computation, a year is assumed to be exactly 365
4094 days in order to avoid rounding problems."
4095 (interactive "P")
4096 (save-excursion
4097 (unless (org-at-date-range-p)
4098 (goto-char (point-at-bol))
4099 (re-search-forward org-tr-regexp (point-at-eol) t))
4100 (if (not (org-at-date-range-p))
4101 (error "Not at a time-stamp range, and none found in current line")))
4102 (let* ((ts1 (match-string 1))
4103 (ts2 (match-string 2))
4104 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4105 (match-end (match-end 0))
4106 (time1 (org-time-string-to-time ts1))
4107 (time2 (org-time-string-to-time ts2))
4108 (t1 (time-to-seconds time1))
4109 (t2 (time-to-seconds time2))
4110 (diff (abs (- t2 t1)))
4111 (negative (< (- t2 t1) 0))
4112 ;; (ys (floor (* 365 24 60 60)))
4113 (ds (* 24 60 60))
4114 (hs (* 60 60))
4115 (fy "%dy %dd %02d:%02d")
4116 (fy1 "%dy %dd")
4117 (fd "%dd %02d:%02d")
4118 (fd1 "%dd")
4119 (fh "%02d:%02d")
4120 y d h m align)
4121 ;; FIXME: Should I re-introduce years, make year refer to same date?
4122 ;; This would be the only useful way to have years, actually.
4123 (if havetime
4124 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4125 y 0
4126 d (floor (/ diff ds)) diff (mod diff ds)
4127 h (floor (/ diff hs)) diff (mod diff hs)
4128 m (floor (/ diff 60)))
4129 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4130 y 0
4131 d (floor (+ (/ diff ds) 0.5))
4132 h 0 m 0))
4133 (if (not to-buffer)
4134 (message (org-make-tdiff-string y d h m))
4135 (when (org-at-table-p)
4136 (goto-char match-end)
4137 (setq align t)
4138 (and (looking-at " *|") (goto-char (match-end 0))))
4139 (if (looking-at
4140 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4141 (replace-match ""))
4142 (if negative (insert " -"))
4143 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4144 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4145 (insert " " (format fh h m))))
4146 (if align (org-table-align))
4147 (message "Time difference inserted"))))
4148
4149 (defun org-make-tdiff-string (y d h m)
4150 (let ((fmt "")
4151 (l nil))
4152 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4153 l (push y l)))
4154 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4155 l (push d l)))
4156 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4157 l (push h l)))
4158 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4159 l (push m l)))
4160 (apply 'format fmt (nreverse l))))
4161
4162 (defun org-time-string-to-time (s)
4163 (apply 'encode-time (org-parse-time-string s)))
4164
4165 (defun org-parse-time-string (s &optional nodefault)
4166 "Parse the standard Org-mode time string.
4167 This should be a lot faster than the normal `parse-time-string'.
4168 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4169 hour and minute fields will be nil if not given."
4170 (if (string-match org-ts-regexp1 s)
4171 (list 0
4172 (if (or (match-beginning 8) (not nodefault))
4173 (string-to-number (or (match-string 8 s) "0")))
4174 (if (or (match-beginning 7) (not nodefault))
4175 (string-to-number (or (match-string 7 s) "0")))
4176 (string-to-number (match-string 4 s))
4177 (string-to-number (match-string 3 s))
4178 (string-to-number (match-string 2 s))
4179 nil nil nil)
4180 (make-list 9 0)))
4181
4182 (defun org-timestamp-up (&optional arg)
4183 "Increase the date item at the cursor by one.
4184 If the cursor is on the year, change the year. If it is on the month or
4185 the day, change that.
4186 With prefix ARG, change by that many units."
4187 (interactive "p")
4188 (org-timestamp-change (prefix-numeric-value arg)))
4189
4190 (defun org-timestamp-down (&optional arg)
4191 "Decrease the date item at the cursor by one.
4192 If the cursor is on the year, change the year. If it is on the month or
4193 the day, change that.
4194 With prefix ARG, change by that many units."
4195 (interactive "p")
4196 (org-timestamp-change (- (prefix-numeric-value arg))))
4197
4198 (defun org-timestamp-up-day (&optional arg)
4199 "Increase the date in the time stamp by one day.
4200 With prefix ARG, change that many days."
4201 (interactive "p")
4202 (if (and (not (org-at-timestamp-p))
4203 (org-on-heading-p))
4204 (org-todo 'up)
4205 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4206
4207 (defun org-timestamp-down-day (&optional arg)
4208 "Decrease the date in the time stamp by one day.
4209 With prefix ARG, change that many days."
4210 (interactive "p")
4211 (if (and (not (org-at-timestamp-p))
4212 (org-on-heading-p))
4213 (org-todo 'down)
4214 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4215
4216 (defsubst org-pos-in-match-range (pos n)
4217 (and (match-beginning n)
4218 (<= (match-beginning n) pos)
4219 (>= (match-end n) pos)))
4220
4221 (defun org-at-timestamp-p ()
4222 "Determine if the cursor is in or at a timestamp."
4223 (interactive)
4224 (let* ((tsr org-ts-regexp2)
4225 (pos (point))
4226 (ans (or (looking-at tsr)
4227 (save-excursion
4228 (skip-chars-backward "^<\n\r\t")
4229 (if (> (point) 1) (backward-char 1))
4230 (and (looking-at tsr)
4231 (> (- (match-end 0) pos) -1))))))
4232 (and (boundp 'org-ts-what)
4233 (setq org-ts-what
4234 (cond
4235 ((org-pos-in-match-range pos 2) 'year)
4236 ((org-pos-in-match-range pos 3) 'month)
4237 ((org-pos-in-match-range pos 7) 'hour)
4238 ((org-pos-in-match-range pos 8) 'minute)
4239 ((or (org-pos-in-match-range pos 4)
4240 (org-pos-in-match-range pos 5)) 'day)
4241 (t 'day))))
4242 ans))
4243
4244 (defun org-timestamp-change (n &optional what)
4245 "Change the date in the time stamp at point.
4246 The date will be changed by N times WHAT. WHAT can be `day', `month',
4247 `year', `minute', `second'. If WHAT is not given, the cursor position
4248 in the timestamp determines what will be changed."
4249 (let ((fmt (car org-time-stamp-formats))
4250 org-ts-what
4251 (pos (point))
4252 ts time time0)
4253 (if (not (org-at-timestamp-p))
4254 (error "Not at a timestamp"))
4255 (setq org-ts-what (or what org-ts-what))
4256 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4257 (- (match-end 0) (match-beginning 0))))
4258 1)
4259 (cdr org-time-stamp-formats)
4260 (car org-time-stamp-formats)))
4261 (setq ts (match-string 0))
4262 (replace-match "")
4263 (setq time0 (org-parse-time-string ts))
4264 (setq time
4265 (apply 'encode-time
4266 (append
4267 (list (or (car time0) 0))
4268 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4269 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4270 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4271 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4272 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4273 (nthcdr 6 time0))))
4274 (if (eq what 'calendar)
4275 (let ((cal-date
4276 (save-excursion
4277 (save-match-data
4278 (set-buffer "*Calendar*")
4279 (calendar-cursor-to-date)))))
4280 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4281 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4282 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4283 (setcar time0 (or (car time0) 0))
4284 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4285 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4286 (setq time (apply 'encode-time time0))))
4287 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4288 (goto-char pos)
4289 ;; Try to recenter the calendar window, if any
4290 (if (and org-calendar-follow-timestamp-change
4291 (get-buffer-window "*Calendar*" t)
4292 (memq org-ts-what '(day month year)))
4293 (org-recenter-calendar (time-to-days time)))))
4294
4295 (defun org-recenter-calendar (date)
4296 "If the calendar is visible, recenter it to DATE."
4297 (let* ((win (selected-window))
4298 (cwin (get-buffer-window "*Calendar*" t))
4299 (calendar-move-hook nil))
4300 (when cwin
4301 (select-window cwin)
4302 (calendar-goto-date (if (listp date) date
4303 (calendar-gregorian-from-absolute date)))
4304 (select-window win))))
4305
4306 (defun org-goto-calendar (&optional arg)
4307 "Go to the Emacs calendar at the current date.
4308 If there is a time stamp in the current line, go to that date.
4309 A prefix ARG can be used to force the current date."
4310 (interactive "P")
4311 (let ((tsr org-ts-regexp) diff
4312 (calendar-move-hook nil)
4313 (view-diary-entries-initially nil))
4314 (if (or (org-at-timestamp-p)
4315 (save-excursion
4316 (beginning-of-line 1)
4317 (looking-at (concat ".*" tsr))))
4318 (let ((d1 (time-to-days (current-time)))
4319 (d2 (time-to-days
4320 (org-time-string-to-time (match-string 1)))))
4321 (setq diff (- d2 d1))))
4322 (calendar)
4323 (calendar-goto-today)
4324 (if (and diff (not arg)) (calendar-forward-day diff))))
4325
4326 (defun org-date-from-calendar ()
4327 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4328 If there is already a time stamp at the cursor position, update it."
4329 (interactive)
4330 (org-timestamp-change 0 'calendar))
4331
4332 ;;; Agenda, and Diary Integration
4333
4334 ;;; Define the mode
4335
4336 (defvar org-agenda-mode-map (make-sparse-keymap)
4337 "Keymap for `org-agenda-mode'.")
4338
4339 (defvar org-agenda-menu)
4340 (defvar org-agenda-follow-mode nil)
4341 (defvar org-agenda-show-log nil)
4342 (defvar org-agenda-buffer-name "*Org Agenda*")
4343 (defvar org-agenda-redo-command nil)
4344 (defvar org-agenda-mode-hook nil)
4345 (defvar org-agenda-type nil)
4346 (defvar org-agenda-force-single-file nil)
4347
4348 ;;;###autoload
4349 (defun org-agenda-mode ()
4350 "Mode for time-sorted view on action items in Org-mode files.
4351
4352 The following commands are available:
4353
4354 \\{org-agenda-mode-map}"
4355 (interactive)
4356 (kill-all-local-variables)
4357 (setq major-mode 'org-agenda-mode)
4358 (setq mode-name "Org-Agenda")
4359 (use-local-map org-agenda-mode-map)
4360 (easy-menu-add org-agenda-menu)
4361 (if org-startup-truncated (setq truncate-lines t))
4362 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4363 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4364 (unless org-agenda-keep-modes
4365 (setq org-agenda-follow-mode nil
4366 org-agenda-show-log nil))
4367 (easy-menu-change
4368 '("Agenda") "Agenda Files"
4369 (append
4370 (list
4371 (vector
4372 (if (get 'org-agenda-files 'org-restrict)
4373 "Restricted to single file"
4374 "Edit File List")
4375 '(customize-variable 'org-agenda-files)
4376 (not (get 'org-agenda-files 'org-restrict)))
4377 "--")
4378 (mapcar 'org-file-menu-entry (org-agenda-files))))
4379 (org-agenda-set-mode-name)
4380 (apply
4381 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4382 (list 'org-agenda-mode-hook)))
4383
4384 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4385 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
4386 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4387 (define-key org-agenda-mode-map " " 'org-agenda-show)
4388 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4389 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4390 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4391 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4392 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4393 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4394 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4395 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4396 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4397 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4398 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4399 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4400
4401 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4402 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4403 (while l (define-key org-agenda-mode-map
4404 (int-to-string (pop l)) 'digit-argument)))
4405
4406 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4407 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4408 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4409 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4410 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4411 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4412 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4413 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4414 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4415 (define-key org-agenda-mode-map "n" 'next-line)
4416 (define-key org-agenda-mode-map "p" 'previous-line)
4417 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4418 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4419 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4420 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4421 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4422 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4423 (eval-after-load "calendar"
4424 '(define-key calendar-mode-map org-calendar-to-agenda-key
4425 'org-calendar-goto-agenda))
4426 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4427 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4428 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4429 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4430 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4431 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4432 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4433 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4434 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4435 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4436 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4437 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4438 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4439 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4440 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4441 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4442 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4443 "Local keymap for agenda entries from Org-mode.")
4444
4445 (define-key org-agenda-keymap
4446 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4447 (define-key org-agenda-keymap
4448 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4449 (define-key org-agenda-keymap [follow-link] 'mouse-face)
4450 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4451 '("Agenda"
4452 ("Agenda Files")
4453 "--"
4454 ["Show" org-agenda-show t]
4455 ["Go To (other window)" org-agenda-goto t]
4456 ["Go To (one window)" org-agenda-switch-to t]
4457 ["Follow Mode" org-agenda-follow-mode
4458 :style toggle :selected org-agenda-follow-mode :active t]
4459 "--"
4460 ["Cycle TODO" org-agenda-todo t]
4461 ("Tags"
4462 ["Show all Tags" org-agenda-show-tags t]
4463 ["Set Tags" org-agenda-set-tags t])
4464 ("Reschedule"
4465 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4466 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4467 "--"
4468 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4469 ("Priority"
4470 ["Set Priority" org-agenda-priority t]
4471 ["Increase Priority" org-agenda-priority-up t]
4472 ["Decrease Priority" org-agenda-priority-down t]
4473 ["Show Priority" org-agenda-show-priority t])
4474 "--"
4475 ;; ["New agenda command" org-agenda t]
4476 ["Rebuild buffer" org-agenda-redo t]
4477 "--"
4478 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4479 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4480 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4481 "--"
4482 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4483 :style radio :selected (equal org-agenda-ndays 1)]
4484 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4485 :style radio :selected (equal org-agenda-ndays 7)]
4486 "--"
4487 ["Show Logbook entries" org-agenda-log-mode
4488 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4489 ["Include Diary" org-agenda-toggle-diary
4490 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4491 ["Use Time Grid" org-agenda-toggle-time-grid
4492 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4493 "--"
4494 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4495 ("Calendar Commands"
4496 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4497 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4498 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4499 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4500 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4501 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4502 "--"
4503 ["Quit" org-agenda-quit t]
4504 ["Exit and Release Buffers" org-agenda-exit t]
4505 ))
4506
4507 ;;;###autoload
4508 (defun org-agenda (arg)
4509 "Dispatch agenda commands to collect entries to the agenda buffer.
4510 Prompts for a character to select a command. Any prefix arg will be passed
4511 on to the selected command. The default selections are:
4512
4513 a Call `org-agenda' to display the agenda for the current day or week.
4514 t Call `org-todo-list' to display the global todo list.
4515 T Call `org-todo-list' to display the global todo list, select only
4516 entries with a specific TODO keyword (the user gets a prompt).
4517 m Call `org-tags-view' to display headlines with tags matching
4518 a condition (the user is prompted for the condition).
4519 M Like `m', but select only TODO entries, no ordinary headlines.
4520
4521 More commands can be added by configuring the variable
4522 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4523 searches can be pre-defined in this way.
4524
4525 If the current buffer is in Org-mode and visiting a file, you can also
4526 first press `1' to indicate that the agenda should be temporarily (until the
4527 next use of \\[org-agenda]) restricted to the current file."
4528 (interactive "P")
4529 (catch 'exit
4530 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4531 (custom org-agenda-custom-commands)
4532 c entry key type string)
4533 (put 'org-agenda-files 'org-restrict nil)
4534 (save-window-excursion
4535 (delete-other-windows)
4536 (switch-to-buffer-other-window " *Agenda Commands*")
4537 (erase-buffer)
4538 (insert
4539 "Press key for an agenda command:
4540 --------------------------------
4541 a Agenda for current week or day
4542 t List of all TODO entries T Entries with special TODO kwd
4543 m Match a TAGS query M Like m, but only TODO entries
4544 C Configure your own agenda commands")
4545 (while (setq entry (pop custom))
4546 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4547 (insert (format "\n%-4s%-14s: %s"
4548 key
4549 (cond
4550 ((eq type 'tags) "Tags query")
4551 ((eq type 'todo) "TODO keyword")
4552 ((eq type 'tags-tree) "Tags tree")
4553 ((eq type 'todo-tree) "TODO kwd tree")
4554 ((eq type 'occur-tree) "Occur tree")
4555 (t "???"))
4556 (org-string-props string 'face 'org-link))))
4557 (goto-char (point-min))
4558 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4559 (message "Press key for agenda command%s"
4560 (if restrict-ok ", or [1] to restrict to current file" ""))
4561 (setq c (read-char-exclusive))
4562 (message "")
4563 (when (equal c ?1)
4564 (if restrict-ok
4565 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
4566 (error "Cannot restrict agenda to current buffer"))
4567 (message "Press key for agenda command%s"
4568 (if restrict-ok " (restricted to current file)" ""))
4569 (setq c (read-char-exclusive))
4570 (message "")))
4571 (require 'calendar) ; FIXME: can we avoid this for some commands?
4572 ;; For example the todo list should not need it (but does...)
4573 (cond
4574 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4575 ((equal c ?a) (call-interactively 'org-agenda-list))
4576 ((equal c ?t) (call-interactively 'org-todo-list))
4577 ((equal c ?T)
4578 (setq current-prefix-arg (or arg '(4)))
4579 (call-interactively 'org-todo-list))
4580 ((equal c ?m) (call-interactively 'org-tags-view))
4581 ((equal c ?M)
4582 (setq current-prefix-arg (or arg '(4)))
4583 (call-interactively 'org-tags-view))
4584 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4585 (setq type (nth 1 entry) string (nth 2 entry))
4586 (cond
4587 ((eq type 'tags)
4588 (org-tags-view current-prefix-arg string))
4589 ((eq type 'todo)
4590 (org-todo-list string))
4591 ((eq type 'tags-tree)
4592 (org-check-for-org-mode)
4593 (org-tags-sparse-tree current-prefix-arg string))
4594 ((eq type 'todo-tree)
4595 (org-check-for-org-mode)
4596 (org-occur (concat "^" outline-regexp "[ \t]*"
4597 (regexp-quote string) "\\>")))
4598 ((eq type 'occur-tree)
4599 (org-check-for-org-mode)
4600 (org-occur string))
4601 (t (error "Invalid custom agenda command type %s" type))))
4602 (t (error "Invalid key"))))))
4603
4604 (defun org-check-for-org-mode ()
4605 "Make sure current buffer is in org-mode. Error if not."
4606 (or (eq major-mode 'org-mode)
4607 (error "Cannot execute org-mode agenda command on buffer in %s."
4608 major-mode)))
4609
4610 (defun org-fit-agenda-window ()
4611 "Fit the window to the buffer size."
4612 (and org-fit-agenda-window
4613 (fboundp 'fit-window-to-buffer)
4614 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4615 (/ (frame-height) 2))))
4616
4617 (defun org-agenda-files ()
4618 "Get the list of agenda files."
4619 (or (get 'org-agenda-files 'org-restrict)
4620 org-agenda-files))
4621
4622 (defvar org-agenda-markers nil
4623 "List of all currently active markers created by `org-agenda'.")
4624 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4625 "Creation time of the last agenda marker.")
4626
4627 (defun org-agenda-new-marker (&optional pos)
4628 "Return a new agenda marker.
4629 Org-mode keeps a list of these markers and resets them when they are
4630 no longer in use."
4631 (let ((m (copy-marker (or pos (point)))))
4632 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4633 (push m org-agenda-markers)
4634 m))
4635
4636 (defun org-agenda-maybe-reset-markers (&optional force)
4637 "Reset markers created by `org-agenda'. But only if they are old enough."
4638 (if (or force
4639 (> (- (time-to-seconds (current-time))
4640 org-agenda-last-marker-time)
4641 5))
4642 (while org-agenda-markers
4643 (move-marker (pop org-agenda-markers) nil))))
4644
4645 (defvar org-agenda-new-buffers nil
4646 "Buffers created to visit agenda files.")
4647
4648 (defun org-get-agenda-file-buffer (file)
4649 "Get a buffer visiting FILE. If the buffer needs to be created, add
4650 it to the list of buffers which might be released later."
4651 (let ((buf (find-buffer-visiting file)))
4652 (if buf
4653 buf ; just return it
4654 ;; Make a new buffer and remember it
4655 (setq buf (find-file-noselect file))
4656 (if buf (push buf org-agenda-new-buffers))
4657 buf)))
4658
4659 (defun org-release-buffers (blist)
4660 "Release all buffers in list, asking the user for confirmation when needed.
4661 When a buffer is unmodified, it is just killed. When modified, it is saved
4662 \(if the user agrees) and then killed."
4663 (let (buf file)
4664 (while (setq buf (pop blist))
4665 (setq file (buffer-file-name buf))
4666 (when (and (buffer-modified-p buf)
4667 file
4668 (y-or-n-p (format "Save file %s? " file)))
4669 (with-current-buffer buf (save-buffer)))
4670 (kill-buffer buf))))
4671
4672 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4673
4674 (defun org-timeline (&optional include-all keep-modes)
4675 "Show a time-sorted view of the entries in the current org file.
4676 Only entries with a time stamp of today or later will be listed. With
4677 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4678 under the current date.
4679 If the buffer contains an active region, only check the region for
4680 dates."
4681 (interactive "P")
4682 (require 'calendar)
4683 (org-agenda-maybe-reset-markers 'force)
4684 (org-compile-prefix-format org-timeline-prefix-format)
4685 (let* ((dopast t)
4686 (dotodo include-all)
4687 (doclosed org-agenda-show-log)
4688 (org-agenda-keep-modes keep-modes)
4689 (entry buffer-file-name)
4690 (org-agenda-files (list buffer-file-name))
4691 (date (calendar-current-date))
4692 (win (selected-window))
4693 (pos1 (point))
4694 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4695 (end (if (org-region-active-p) (region-end) (point-max)))
4696 (day-numbers (org-get-all-dates beg end 'no-ranges
4697 t doclosed)) ; always include today
4698 (today (time-to-days (current-time)))
4699 (org-respect-restriction t)
4700 (past t)
4701 args
4702 s e rtn d)
4703 (setq org-agenda-redo-command
4704 (list 'progn
4705 (list 'switch-to-buffer-other-window (current-buffer))
4706 (list 'org-timeline (list 'quote include-all) t)))
4707 (if (not dopast)
4708 ;; Remove past dates from the list of dates.
4709 (setq day-numbers (delq nil (mapcar (lambda(x)
4710 (if (>= x today) x nil))
4711 day-numbers))))
4712 (switch-to-buffer-other-window
4713 (get-buffer-create org-agenda-buffer-name))
4714 (setq buffer-read-only nil)
4715 (erase-buffer)
4716 (org-agenda-mode) (setq buffer-read-only nil)
4717 (set (make-local-variable 'org-agenda-type) 'timeline)
4718 (if doclosed (push :closed args))
4719 (push :timestamp args)
4720 (if dotodo (push :todo args))
4721 (while (setq d (pop day-numbers))
4722 (if (and (>= d today)
4723 dopast
4724 past)
4725 (progn
4726 (setq past nil)
4727 (insert (make-string 79 ?-) "\n")))
4728 (setq date (calendar-gregorian-from-absolute d))
4729 (setq s (point))
4730 (setq rtn (apply 'org-agenda-get-day-entries
4731 entry date args))
4732 (if (or rtn (equal d today))
4733 (progn
4734 (insert (calendar-day-name date) " "
4735 (number-to-string (extract-calendar-day date)) " "
4736 (calendar-month-name (extract-calendar-month date)) " "
4737 (number-to-string (extract-calendar-year date)) "\n")
4738 (put-text-property s (1- (point)) 'face
4739 'org-link)
4740 (if (equal d today)
4741 (put-text-property s (1- (point)) 'org-today t))
4742 (insert (org-finalize-agenda-entries rtn) "\n")
4743 (put-text-property s (1- (point)) 'day d))))
4744 (goto-char (point-min))
4745 (setq buffer-read-only t)
4746 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4747 (point-min)))
4748 (when (not org-select-timeline-window)
4749 (select-window win)
4750 (goto-char pos1))))
4751
4752 ;;;###autoload
4753 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4754 "Produce a weekly view from all files in variable `org-agenda-files'.
4755 The view will be for the current week, but from the overview buffer you
4756 will be able to go to other weeks.
4757 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4758 also be shown, under the current date.
4759 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4760 on the days are also shown. See the variable `org-log-done' for how
4761 to turn on logging.
4762 START-DAY defaults to TODAY, or to the most recent match for the weekday
4763 given in `org-agenda-start-on-weekday'.
4764 NDAYS defaults to `org-agenda-ndays'."
4765 (interactive "P")
4766 (org-agenda-maybe-reset-markers 'force)
4767 (org-compile-prefix-format org-agenda-prefix-format)
4768 (require 'calendar)
4769 (let* ((org-agenda-start-on-weekday
4770 (if (or (equal ndays 1)
4771 (and (null ndays) (equal 1 org-agenda-ndays)))
4772 nil org-agenda-start-on-weekday))
4773 (org-agenda-keep-modes keep-modes)
4774 (files (copy-sequence (org-agenda-files)))
4775 (win (selected-window))
4776 (today (time-to-days (current-time)))
4777 (sd (or start-day today))
4778 (start (if (or (null org-agenda-start-on-weekday)
4779 (< org-agenda-ndays 7))
4780 sd
4781 (let* ((nt (calendar-day-of-week
4782 (calendar-gregorian-from-absolute sd)))
4783 (n1 org-agenda-start-on-weekday)
4784 (d (- nt n1)))
4785 (- sd (+ (if (< d 0) 7 0) d)))))
4786 (day-numbers (list start))
4787 (inhibit-redisplay t)
4788 s e rtn rtnall file date d start-pos end-pos todayp nd)
4789 (setq org-agenda-redo-command
4790 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4791 ;; Make the list of days
4792 (setq ndays (or ndays org-agenda-ndays)
4793 nd ndays)
4794 (while (> ndays 1)
4795 (push (1+ (car day-numbers)) day-numbers)
4796 (setq ndays (1- ndays)))
4797 (setq day-numbers (nreverse day-numbers))
4798 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4799 (progn
4800 (delete-other-windows)
4801 (switch-to-buffer-other-window
4802 (get-buffer-create org-agenda-buffer-name))))
4803 (setq buffer-read-only nil)
4804 (erase-buffer)
4805 (org-agenda-mode) (setq buffer-read-only nil)
4806 (set (make-local-variable 'org-agenda-type) 'agenda)
4807 (set (make-local-variable 'starting-day) (car day-numbers))
4808 (set (make-local-variable 'include-all-loc) include-all)
4809 (when (and (or include-all org-agenda-include-all-todo)
4810 (member today day-numbers))
4811 (setq files (org-agenda-files)
4812 rtnall nil)
4813 (while (setq file (pop files))
4814 (catch 'nextfile
4815 (org-check-agenda-file file)
4816 (setq date (calendar-gregorian-from-absolute today)
4817 rtn (org-agenda-get-day-entries
4818 file date :todo))
4819 (setq rtnall (append rtnall rtn))))
4820 (when rtnall
4821 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4822 (add-text-properties (point-min) (1- (point))
4823 (list 'face 'org-link))
4824 (insert (org-finalize-agenda-entries rtnall) "\n")))
4825 (while (setq d (pop day-numbers))
4826 (setq date (calendar-gregorian-from-absolute d)
4827 s (point))
4828 (if (or (setq todayp (= d today))
4829 (and (not start-pos) (= d sd)))
4830 (setq start-pos (point))
4831 (if (and start-pos (not end-pos))
4832 (setq end-pos (point))))
4833 (setq files (org-agenda-files)
4834 rtnall nil)
4835 (while (setq file (pop files))
4836 (catch 'nextfile
4837 (org-check-agenda-file file)
4838 (if org-agenda-show-log
4839 (setq rtn (org-agenda-get-day-entries
4840 file date
4841 :deadline :scheduled :timestamp :closed))
4842 (setq rtn (org-agenda-get-day-entries
4843 file date
4844 :deadline :scheduled :timestamp)))
4845 (setq rtnall (append rtnall rtn))))
4846 (if org-agenda-include-diary
4847 (progn
4848 (require 'diary-lib)
4849 (setq rtn (org-get-entries-from-diary date))
4850 (setq rtnall (append rtnall rtn))))
4851 (if (or rtnall org-agenda-show-all-dates)
4852 (progn
4853 (insert (format "%-9s %2d %s %4d\n"
4854 (calendar-day-name date)
4855 (extract-calendar-day date)
4856 (calendar-month-name (extract-calendar-month date))
4857 (extract-calendar-year date)))
4858 (put-text-property s (1- (point)) 'face
4859 'org-link)
4860 (if rtnall (insert
4861 (org-finalize-agenda-entries
4862 (org-agenda-add-time-grid-maybe
4863 rtnall nd todayp))
4864 "\n"))
4865 (put-text-property s (1- (point)) 'day d))))
4866 (goto-char (point-min))
4867 (setq buffer-read-only t)
4868 (org-fit-agenda-window)
4869 (unless (and (pos-visible-in-window-p (point-min))
4870 (pos-visible-in-window-p (point-max)))
4871 (goto-char (1- (point-max)))
4872 (recenter -1)
4873 (if (not (pos-visible-in-window-p (or start-pos 1)))
4874 (progn
4875 (goto-char (or start-pos 1))
4876 (recenter 1))))
4877 (goto-char (or start-pos 1))
4878 (if (not org-select-agenda-window) (select-window win))
4879 (message "")))
4880
4881 (defvar org-select-this-todo-keyword nil)
4882
4883 ;;;###autoload
4884 (defun org-todo-list (arg &optional keep-modes)
4885 "Show all TODO entries from all agenda file in a single list.
4886 The prefix arg can be used to select a specific TODO keyword and limit
4887 the list to these. When using \\[universal-argument], you will be prompted
4888 for a keyword. A numeric prefix directly selects the Nth keyword in
4889 `org-todo-keywords'."
4890 (interactive "P")
4891 (org-agenda-maybe-reset-markers 'force)
4892 (org-compile-prefix-format org-agenda-prefix-format)
4893 (let* ((org-agenda-keep-modes keep-modes)
4894 (today (time-to-days (current-time)))
4895 (date (calendar-gregorian-from-absolute today))
4896 (win (selected-window))
4897 (kwds org-todo-keywords)
4898 (completion-ignore-case t)
4899 (org-select-this-todo-keyword
4900 (if (stringp arg) arg
4901 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4902 rtn rtnall files file pos)
4903 (when (equal arg '(4))
4904 (setq org-select-this-todo-keyword
4905 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4906 nil t)))
4907 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4908 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4909 (progn
4910 (delete-other-windows)
4911 (switch-to-buffer-other-window
4912 (get-buffer-create org-agenda-buffer-name))))
4913 (setq buffer-read-only nil)
4914 (erase-buffer)
4915 (org-agenda-mode) (setq buffer-read-only nil)
4916 (set (make-local-variable 'org-agenda-type) 'todo)
4917 (set (make-local-variable 'last-arg) arg)
4918 (set (make-local-variable 'org-todo-keywords) kwds)
4919 (set (make-local-variable 'org-agenda-redo-command)
4920 '(org-todo-list (or current-prefix-arg last-arg) t))
4921 (setq files (org-agenda-files)
4922 rtnall nil)
4923 (while (setq file (pop files))
4924 (catch 'nextfile
4925 (org-check-agenda-file file)
4926 (setq rtn (org-agenda-get-day-entries file date :todo))
4927 (setq rtnall (append rtnall rtn))))
4928 (insert "Global list of TODO items of type: ")
4929 (add-text-properties (point-min) (1- (point))
4930 (list 'face 'org-link))
4931 (setq pos (point))
4932 (insert (or org-select-this-todo-keyword "ALL") "\n")
4933 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4934 (setq pos (point))
4935 (insert
4936 "Available with `N r': (0)ALL "
4937 (let ((n 0))
4938 (mapconcat (lambda (x)
4939 (format "(%d)%s" (setq n (1+ n)) x))
4940 org-todo-keywords " "))
4941 "\n")
4942 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4943 (when rtnall
4944 (insert (org-finalize-agenda-entries rtnall) "\n"))
4945 (goto-char (point-min))
4946 (setq buffer-read-only t)
4947 (org-fit-agenda-window)
4948 (if (not org-select-agenda-window) (select-window win))))
4949
4950 (defun org-check-agenda-file (file)
4951 "Make sure FILE exists. If not, ask user what to do."
4952 ;; FIXME: this does not correctly change the menus
4953 ;; Could probably be fixed by explicitly going to the buffer where
4954 ;; the call originated.
4955 (when (not (file-exists-p file))
4956 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4957 file)
4958 (let ((r (downcase (read-char-exclusive))))
4959 (cond
4960 ((equal r ?r)
4961 (org-remove-file file)
4962 (throw 'nextfile t))
4963 (t (error "Abort"))))))
4964
4965 (defun org-agenda-check-type (error &rest types)
4966 "Check if agenda buffer is of allowed type.
4967 If ERROR is non-nil, throw an error, otherwise just return nil."
4968 (if (memq org-agenda-type types)
4969 t
4970 (if error
4971 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
4972 nil)))
4973
4974 (defun org-agenda-quit ()
4975 "Exit agenda by removing the window or the buffer."
4976 (interactive)
4977 (let ((buf (current-buffer)))
4978 (if (not (one-window-p)) (delete-window))
4979 (kill-buffer buf)
4980 (org-agenda-maybe-reset-markers 'force)))
4981
4982 (defun org-agenda-exit ()
4983 "Exit agenda by removing the window or the buffer.
4984 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4985 Org-mode buffers visited directly by the user will not be touched."
4986 (interactive)
4987 (org-release-buffers org-agenda-new-buffers)
4988 (setq org-agenda-new-buffers nil)
4989 (org-agenda-quit))
4990
4991 (defun org-agenda-redo ()
4992 "Rebuild Agenda.
4993 When this is the global TODO list, a prefix argument will be interpreted."
4994 (interactive)
4995 (message "Rebuilding agenda buffer...")
4996 (eval org-agenda-redo-command)
4997 (message "Rebuilding agenda buffer...done"))
4998
4999 (defun org-agenda-goto-today ()
5000 "Go to today."
5001 (interactive)
5002 (org-agenda-check-type t 'timeline 'agenda)
5003 (if (boundp 'starting-day)
5004 (let ((cmd (car org-agenda-redo-command))
5005 (iall (nth 1 org-agenda-redo-command))
5006 (nday (nth 3 org-agenda-redo-command))
5007 (keep (nth 4 org-agenda-redo-command)))
5008 (eval (list cmd iall nil nday keep)))
5009 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5010 (point-min)))))
5011
5012 (defun org-agenda-later (arg)
5013 "Go forward in time by `org-agenda-ndays' days.
5014 With prefix ARG, go forward that many times `org-agenda-ndays'."
5015 (interactive "p")
5016 (org-agenda-check-type t 'agenda)
5017 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5018 (+ starting-day (* arg org-agenda-ndays)) nil t))
5019
5020 (defun org-agenda-earlier (arg)
5021 "Go back in time by `org-agenda-ndays' days.
5022 With prefix ARG, go back that many times `org-agenda-ndays'."
5023 (interactive "p")
5024 (org-agenda-check-type t 'agenda)
5025 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5026 (- starting-day (* arg org-agenda-ndays)) nil t))
5027
5028 (defun org-agenda-week-view ()
5029 "Switch to weekly view for agenda."
5030 (interactive)
5031 (org-agenda-check-type t 'agenda)
5032 (setq org-agenda-ndays 7)
5033 (org-agenda-list include-all-loc
5034 (or (get-text-property (point) 'day)
5035 starting-day)
5036 nil t)
5037 (org-agenda-set-mode-name)
5038 (message "Switched to week view"))
5039
5040 (defun org-agenda-day-view ()
5041 "Switch to daily view for agenda."
5042 (interactive)
5043 (org-agenda-check-type t 'agenda)
5044 (setq org-agenda-ndays 1)
5045 (org-agenda-list include-all-loc
5046 (or (get-text-property (point) 'day)
5047 starting-day)
5048 nil t)
5049 (org-agenda-set-mode-name)
5050 (message "Switched to day view"))
5051
5052 (defun org-agenda-next-date-line (&optional arg)
5053 "Jump to the next line indicating a date in agenda buffer."
5054 (interactive "p")
5055 (org-agenda-check-type t 'agenda 'timeline)
5056 (beginning-of-line 1)
5057 (if (looking-at "^\\S-") (forward-char 1))
5058 (if (not (re-search-forward "^\\S-" nil t arg))
5059 (progn
5060 (backward-char 1)
5061 (error "No next date after this line in this buffer")))
5062 (goto-char (match-beginning 0)))
5063
5064 (defun org-agenda-previous-date-line (&optional arg)
5065 "Jump to the previous line indicating a date in agenda buffer."
5066 (interactive "p")
5067 (org-agenda-check-type t 'agenda 'timeline)
5068 (beginning-of-line 1)
5069 (if (not (re-search-backward "^\\S-" nil t arg))
5070 (error "No previous date before this line in this buffer")))
5071
5072 ;; Initialize the highlight
5073 (defvar org-hl (org-make-overlay 1 1))
5074 (org-overlay-put org-hl 'face 'highlight)
5075
5076 (defun org-highlight (begin end &optional buffer)
5077 "Highlight a region with overlay."
5078 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
5079 org-hl begin end (or buffer (current-buffer))))
5080
5081 (defun org-unhighlight ()
5082 "Detach overlay INDEX."
5083 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
5084
5085
5086 (defun org-agenda-follow-mode ()
5087 "Toggle follow mode in an agenda buffer."
5088 (interactive)
5089 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5090 (org-agenda-set-mode-name)
5091 (message "Follow mode is %s"
5092 (if org-agenda-follow-mode "on" "off")))
5093
5094 (defun org-agenda-log-mode ()
5095 "Toggle log mode in an agenda buffer."
5096 (interactive)
5097 (org-agenda-check-type t 'agenda 'timeline)
5098 (setq org-agenda-show-log (not org-agenda-show-log))
5099 (org-agenda-set-mode-name)
5100 (org-agenda-redo)
5101 (message "Log mode is %s"
5102 (if org-agenda-show-log "on" "off")))
5103
5104 (defun org-agenda-toggle-diary ()
5105 "Toggle diary inclusion in an agenda buffer."
5106 (interactive)
5107 (org-agenda-check-type t 'agenda)
5108 (setq org-agenda-include-diary (not org-agenda-include-diary))
5109 (org-agenda-redo)
5110 (org-agenda-set-mode-name)
5111 (message "Diary inclusion turned %s"
5112 (if org-agenda-include-diary "on" "off")))
5113
5114 (defun org-agenda-toggle-time-grid ()
5115 "Toggle time grid in an agenda buffer."
5116 (interactive)
5117 (org-agenda-check-type t 'agenda)
5118 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5119 (org-agenda-redo)
5120 (org-agenda-set-mode-name)
5121 (message "Time-grid turned %s"
5122 (if org-agenda-use-time-grid "on" "off")))
5123
5124 (defun org-agenda-set-mode-name ()
5125 "Set the mode name to indicate all the small mode settings."
5126 (setq mode-name
5127 (concat "Org-Agenda"
5128 (if (equal org-agenda-ndays 1) " Day" "")
5129 (if (equal org-agenda-ndays 7) " Week" "")
5130 (if org-agenda-follow-mode " Follow" "")
5131 (if org-agenda-include-diary " Diary" "")
5132 (if org-agenda-use-time-grid " Grid" "")
5133 (if org-agenda-show-log " Log" "")))
5134 (force-mode-line-update))
5135
5136 (defun org-agenda-post-command-hook ()
5137 (and (eolp) (not (bolp)) (backward-char 1))
5138 (if (and org-agenda-follow-mode
5139 (get-text-property (point) 'org-marker))
5140 (org-agenda-show)))
5141
5142 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5143
5144 (defun org-get-entries-from-diary (date)
5145 "Get the (Emacs Calendar) diary entries for DATE."
5146 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5147 (diary-display-hook '(fancy-diary-display))
5148 (list-diary-entries-hook
5149 (cons 'org-diary-default-entry list-diary-entries-hook))
5150 (diary-file-name-prefix-function nil) ; turn this feature off
5151 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5152 entries
5153 (org-disable-agenda-to-diary t))
5154 (save-excursion
5155 (save-window-excursion
5156 (list-diary-entries date 1)))
5157 (if (not (get-buffer fancy-diary-buffer))
5158 (setq entries nil)
5159 (with-current-buffer fancy-diary-buffer
5160 (setq buffer-read-only nil)
5161 (if (= (point-max) 1)
5162 ;; No entries
5163 (setq entries nil)
5164 ;; Omit the date and other unnecessary stuff
5165 (org-agenda-cleanup-fancy-diary)
5166 ;; Add prefix to each line and extend the text properties
5167 (if (= (point-max) 1)
5168 (setq entries nil)
5169 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5170 (set-buffer-modified-p nil)
5171 (kill-buffer fancy-diary-buffer)))
5172 (when entries
5173 (setq entries (org-split-string entries "\n"))
5174 (setq entries
5175 (mapcar
5176 (lambda (x)
5177 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5178 ;; Extend the text properties to the beginning of the line
5179 (add-text-properties
5180 0 (length x)
5181 (text-properties-at (1- (length x)) x)
5182 x)
5183 x)
5184 entries)))))
5185
5186 (defun org-agenda-cleanup-fancy-diary ()
5187 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5188 This gets rid of the date, the underline under the date, and
5189 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5190 date. It also removes lines that contain only whitespace."
5191 (goto-char (point-min))
5192 (if (looking-at ".*?:[ \t]*")
5193 (progn
5194 (replace-match "")
5195 (re-search-forward "\n=+$" nil t)
5196 (replace-match "")
5197 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5198 (re-search-forward "\n=+$" nil t)
5199 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5200 (goto-char (point-min))
5201 (while (re-search-forward "^ +\n" nil t)
5202 (replace-match ""))
5203 (goto-char (point-min))
5204 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5205 (replace-match "")))
5206
5207 ;; Make sure entries from the diary have the right text properties.
5208 (eval-after-load "diary-lib"
5209 '(if (boundp 'diary-modify-entry-list-string-function)
5210 ;; We can rely on the hook, nothing to do
5211 nil
5212 ;; Hook not avaiable, must use advice to make this work
5213 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5214 "Make the position visible."
5215 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5216 (stringp string)
5217 buffer-file-name)
5218 (setq string (org-modify-diary-entry-string string))))))
5219
5220 (defun org-modify-diary-entry-string (string)
5221 "Add text properties to string, allowing org-mode to act on it."
5222 (add-text-properties
5223 0 (length string)
5224 (list 'mouse-face 'highlight
5225 'keymap org-agenda-keymap
5226 'help-echo
5227 (format
5228 "mouse-2 or RET jump to diary file %s"
5229 (abbreviate-file-name buffer-file-name))
5230 'org-agenda-diary-link t
5231 'org-marker (org-agenda-new-marker (point-at-bol)))
5232 string)
5233 string)
5234
5235 (defun org-diary-default-entry ()
5236 "Add a dummy entry to the diary.
5237 Needed to avoid empty dates which mess up holiday display."
5238 ;; Catch the error if dealing with the new add-to-diary-alist
5239 (when org-disable-agenda-to-diary
5240 (condition-case nil
5241 (add-to-diary-list original-date "Org-mode dummy" "")
5242 (error
5243 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5244
5245 (defun org-cycle-agenda-files ()
5246 "Cycle through the files in `org-agenda-files'.
5247 If the current buffer visits an agenda file, find the next one in the list.
5248 If the current buffer does not, find the first agenda file."
5249 (interactive)
5250 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5251 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5252 file)
5253 (unless files (error "No agenda files"))
5254 (catch 'exit
5255 (while (setq file (pop files))
5256 (if (equal (file-truename file) tcf)
5257 (when (car files)
5258 (find-file (car files))
5259 (throw 'exit t))))
5260 (find-file (car org-agenda-files)))))
5261
5262 (defun org-agenda-file-to-end ()
5263 "Move/add the current file to the end of the agenda file list.
5264 If the file is not present in the list, it is appended to the list. If it is
5265 present, it is moved there."
5266 (interactive)
5267 (org-agenda-file-to-front 'to-end))
5268
5269 (defun org-agenda-file-to-front (&optional to-end)
5270 "Move/add the current file to the top of the agenda file list.
5271 If the file is not present in the list, it is added to the front. If it is
5272 present, it is moved there. With optional argument TO-END, add/move to the
5273 end of the list."
5274 (interactive "P")
5275 (let ((file-alist (mapcar (lambda (x)
5276 (cons (file-truename x) x))
5277 org-agenda-files))
5278 (ctf (file-truename buffer-file-name))
5279 x had)
5280 (setq x (assoc ctf file-alist) had x)
5281
5282 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5283 (if to-end
5284 (setq file-alist (append (delq x file-alist) (list x)))
5285 (setq file-alist (cons x (delq x file-alist))))
5286 (setq org-agenda-files (mapcar 'cdr file-alist))
5287 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5288 (customize-save-variable 'org-agenda-files org-agenda-files))
5289 (org-install-agenda-files-menu)
5290 (message "File %s to %s of agenda file list"
5291 (if had "moved" "added") (if to-end "end" "front"))))
5292
5293 (defun org-remove-file (&optional file)
5294 "Remove current file from the list of files in variable `org-agenda-files'.
5295 These are the files which are being checked for agenda entries.
5296 Optional argument FILE means, use this file instead of the current."
5297 (interactive)
5298 (let* ((file (or file buffer-file-name))
5299 (true-file (file-truename file))
5300 (afile (abbreviate-file-name file))
5301 (files (delq nil (mapcar
5302 (lambda (x)
5303 (if (equal true-file
5304 (file-truename x))
5305 nil x))
5306 org-agenda-files))))
5307 (if (not (= (length files) (length org-agenda-files)))
5308 (progn
5309 (setq org-agenda-files files)
5310 (customize-save-variable 'org-agenda-files org-agenda-files)
5311 (org-install-agenda-files-menu)
5312 (message "Removed file: %s" afile))
5313 (message "File was not in list: %s" afile))))
5314
5315 (defun org-file-menu-entry (file)
5316 (vector file (list 'find-file file) t))
5317 ;; FIXME: Maybe we removed a buffer visited through the menu from
5318 ;; org-agenda-new-buffers, so that the buffer will not be removed
5319 ;; when exiting the agenda????
5320
5321 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5322 "Return a list of all relevant day numbers from BEG to END buffer positions.
5323 If NO-RANGES is non-nil, include only the start and end dates of a range,
5324 not every single day in the range. If FORCE-TODAY is non-nil, make
5325 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5326 inactive time stamps (those in square brackets) are included."
5327 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5328 dates date day day1 day2 ts1 ts2)
5329 (if force-today
5330 (setq dates (list (time-to-days (current-time)))))
5331 (save-excursion
5332 (goto-char beg)
5333 (while (re-search-forward re end t)
5334 (setq day (time-to-days (org-time-string-to-time
5335 (substring (match-string 1) 0 10))))
5336 (or (memq day dates) (push day dates)))
5337 (unless no-ranges
5338 (goto-char beg)
5339 (while (re-search-forward org-tr-regexp end t)
5340 (setq ts1 (substring (match-string 1) 0 10)
5341 ts2 (substring (match-string 2) 0 10)
5342 day1 (time-to-days (org-time-string-to-time ts1))
5343 day2 (time-to-days (org-time-string-to-time ts2)))
5344 (while (< (setq day1 (1+ day1)) day2)
5345 (or (memq day1 dates) (push day1 dates)))))
5346 (sort dates '<))))
5347
5348 ;;;###autoload
5349 (defun org-diary (&rest args)
5350 "Return diary information from org-files.
5351 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5352 It accesses org files and extracts information from those files to be
5353 listed in the diary. The function accepts arguments specifying what
5354 items should be listed. The following arguments are allowed:
5355
5356 :timestamp List the headlines of items containing a date stamp or
5357 date range matching the selected date. Deadlines will
5358 also be listed, on the expiration day.
5359
5360 :deadline List any deadlines past due, or due within
5361 `org-deadline-warning-days'. The listing occurs only
5362 in the diary for *today*, not at any other date. If
5363 an entry is marked DONE, it is no longer listed.
5364
5365 :scheduled List all items which are scheduled for the given date.
5366 The diary for *today* also contains items which were
5367 scheduled earlier and are not yet marked DONE.
5368
5369 :todo List all TODO items from the org-file. This may be a
5370 long list - so this is not turned on by default.
5371 Like deadlines, these entries only show up in the
5372 diary for *today*, not at any other date.
5373
5374 The call in the diary file should look like this:
5375
5376 &%%(org-diary) ~/path/to/some/orgfile.org
5377
5378 Use a separate line for each org file to check. Or, if you omit the file name,
5379 all files listed in `org-agenda-files' will be checked automatically:
5380
5381 &%%(org-diary)
5382
5383 If you don't give any arguments (as in the example above), the default
5384 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5385 also be written as
5386
5387 &%%(org-diary :deadline :timestamp :scheduled)
5388
5389 The function expects the lisp variables `entry' and `date' to be provided
5390 by the caller, because this is how the calendar works. Don't use this
5391 function from a program - use `org-agenda-get-day-entries' instead."
5392 (org-agenda-maybe-reset-markers)
5393 (org-compile-prefix-format org-agenda-prefix-format)
5394 (setq args (or args '(:deadline :scheduled :timestamp)))
5395 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5396 (list entry)
5397 org-agenda-files))
5398 file rtn results)
5399 ;; If this is called during org-agenda, don't return any entries to
5400 ;; the calendar. Org Agenda will list these entries itself.
5401 (if org-disable-agenda-to-diary (setq files nil))
5402 (while (setq file (pop files))
5403 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5404 (setq results (append results rtn)))
5405 (if results
5406 (concat (org-finalize-agenda-entries results) "\n"))))
5407 (defvar org-category-table nil)
5408 (defun org-get-category-table ()
5409 "Get the table of categories and positions in current buffer."
5410 (let (tbl)
5411 (save-excursion
5412 (goto-char (point-min))
5413 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5414 (push (cons (point) (org-trim (match-string 2))) tbl)))
5415 tbl))
5416 (defun org-get-category (&optional pos)
5417 "Get the category applying to position POS."
5418 (if (not org-category-table)
5419 (cond
5420 ((null org-category)
5421 (setq org-category
5422 (if buffer-file-name
5423 (file-name-sans-extension
5424 (file-name-nondirectory buffer-file-name))
5425 "???")))
5426 ((symbolp org-category) (symbol-name org-category))
5427 (t org-category))
5428 (let ((tbl org-category-table)
5429 (pos (or pos (point))))
5430 (while (and tbl (> (caar tbl) pos))
5431 (pop tbl))
5432 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5433 org-category-table))))))
5434
5435 (defun org-agenda-get-day-entries (file date &rest args)
5436 "Does the work for `org-diary' and `org-agenda'.
5437 FILE is the path to a file to be checked for entries. DATE is date like
5438 the one returned by `calendar-current-date'. ARGS are symbols indicating
5439 which kind of entries should be extracted. For details about these, see
5440 the documentation of `org-diary'."
5441 (setq args (or args '(:deadline :scheduled :timestamp)))
5442 (let* ((org-startup-with-deadline-check nil)
5443 (org-startup-folded nil)
5444 (buffer (if (file-exists-p file)
5445 (org-get-agenda-file-buffer file)
5446 (error "No such file %s" file)))
5447 arg results rtn)
5448 (if (not buffer)
5449 ;; If file does not exist, make sure an error message ends up in diary
5450 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5451 (with-current-buffer buffer
5452 (unless (eq major-mode 'org-mode)
5453 (error "Agenda file %s is not in `org-mode'" file))
5454 (setq org-category-table (org-get-category-table))
5455 (let ((case-fold-search nil))
5456 (save-excursion
5457 (save-restriction
5458 (if org-respect-restriction
5459 (if (org-region-active-p)
5460 ;; Respect a region to restrict search
5461 (narrow-to-region (region-beginning) (region-end)))
5462 ;; If we work for the calendar or many files,
5463 ;; get rid of any restriction
5464 (widen))
5465 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5466 (while (setq arg (pop args))
5467 (cond
5468 ((and (eq arg :todo)
5469 (equal date (calendar-current-date)))
5470 (setq rtn (org-agenda-get-todos))
5471 (setq results (append results rtn)))
5472 ((eq arg :timestamp)
5473 (setq rtn (org-agenda-get-blocks))
5474 (setq results (append results rtn))
5475 (setq rtn (org-agenda-get-timestamps))
5476 (setq results (append results rtn)))
5477 ((eq arg :scheduled)
5478 (setq rtn (org-agenda-get-scheduled))
5479 (setq results (append results rtn)))
5480 ((eq arg :closed)
5481 (setq rtn (org-agenda-get-closed))
5482 (setq results (append results rtn)))
5483 ((and (eq arg :deadline)
5484 (equal date (calendar-current-date)))
5485 (setq rtn (org-agenda-get-deadlines))
5486 (setq results (append results rtn))))))))
5487 results))))
5488
5489 (defun org-entry-is-done-p ()
5490 "Is the current entry marked DONE?"
5491 (save-excursion
5492 (and (re-search-backward "[\r\n]\\*" nil t)
5493 (looking-at org-nl-done-regexp))))
5494
5495 (defun org-at-date-range-p ()
5496 "Is the cursor inside a date range?"
5497 (interactive)
5498 (save-excursion
5499 (catch 'exit
5500 (let ((pos (point)))
5501 (skip-chars-backward "^<\r\n")
5502 (skip-chars-backward "<")
5503 (and (looking-at org-tr-regexp)
5504 (>= (match-end 0) pos)
5505 (throw 'exit t))
5506 (skip-chars-backward "^<\r\n")
5507 (skip-chars-backward "<")
5508 (and (looking-at org-tr-regexp)
5509 (>= (match-end 0) pos)
5510 (throw 'exit t)))
5511 nil)))
5512
5513 (defun org-agenda-get-todos ()
5514 "Return the TODO information for agenda display."
5515 (let* ((props (list 'face nil
5516 'done-face 'org-done
5517 'mouse-face 'highlight
5518 'keymap org-agenda-keymap
5519 'help-echo
5520 (format "mouse-2 or RET jump to org file %s"
5521 (abbreviate-file-name buffer-file-name))))
5522 (regexp (concat "[\n\r]\\*+ *\\("
5523 (if org-select-this-todo-keyword
5524 (concat "\\<\\(" org-select-this-todo-keyword
5525 "\\)\\>")
5526 org-not-done-regexp)
5527 "[^\n\r]*\\)"))
5528 marker priority category tags
5529 ee txt)
5530 (goto-char (point-min))
5531 (while (re-search-forward regexp nil t)
5532 (goto-char (match-beginning 1))
5533 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5534 category (org-get-category)
5535 tags (org-get-tags-at (point))
5536 txt (org-format-agenda-item "" (match-string 1) category tags)
5537 priority
5538 (+ (org-get-priority txt)
5539 (if org-todo-kwd-priority-p
5540 (- org-todo-kwd-max-priority -2
5541 (length
5542 (member (match-string 2) org-todo-keywords)))
5543 1)))
5544 (add-text-properties
5545 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5546 'priority priority 'category category)
5547 props)
5548 txt)
5549 (push txt ee)
5550 (goto-char (match-end 1)))
5551 (nreverse ee)))
5552
5553 (defconst org-agenda-no-heading-message
5554 "No heading for this item in buffer or region.")
5555
5556 (defun org-agenda-get-timestamps ()
5557 "Return the date stamp information for agenda display."
5558 (let* ((props (list 'face nil
5559 'mouse-face 'highlight
5560 'keymap org-agenda-keymap
5561 'help-echo
5562 (format "mouse-2 or RET jump to org file %s"
5563 (abbreviate-file-name buffer-file-name))))
5564 (regexp (regexp-quote
5565 (substring
5566 (format-time-string
5567 (car org-time-stamp-formats)
5568 (apply 'encode-time ; DATE bound by calendar
5569 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5570 0 11)))
5571 marker hdmarker deadlinep scheduledp donep tmp priority category
5572 ee txt timestr tags)
5573 (goto-char (point-min))
5574 (while (re-search-forward regexp nil t)
5575 (if (not (save-match-data (org-at-date-range-p)))
5576 (progn
5577 (setq marker (org-agenda-new-marker (match-beginning 0))
5578 category (org-get-category (match-beginning 0))
5579 tmp (buffer-substring (max (point-min)
5580 (- (match-beginning 0)
5581 org-ds-keyword-length))
5582 (match-beginning 0))
5583 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5584 deadlinep (string-match org-deadline-regexp tmp)
5585 scheduledp (string-match org-scheduled-regexp tmp)
5586 donep (org-entry-is-done-p))
5587 (if (string-match ">" timestr)
5588 ;; substring should only run to end of time stamp
5589 (setq timestr (substring timestr 0 (match-end 0))))
5590 (save-excursion
5591 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5592 (progn
5593 (goto-char (match-end 1))
5594 (setq hdmarker (org-agenda-new-marker)
5595 tags (org-get-tags-at))
5596 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5597 (setq txt (org-format-agenda-item
5598 (format "%s%s"
5599 (if deadlinep "Deadline: " "")
5600 (if scheduledp "Scheduled: " ""))
5601 (match-string 1) category tags timestr)))
5602 (setq txt org-agenda-no-heading-message))
5603 (setq priority (org-get-priority txt))
5604 (add-text-properties
5605 0 (length txt) (append (list 'org-marker marker
5606 'org-hd-marker hdmarker) props)
5607 txt)
5608 (if deadlinep
5609 (add-text-properties
5610 0 (length txt)
5611 (list 'face
5612 (if donep 'org-done 'org-warning)
5613 'undone-face 'org-warning
5614 'done-face 'org-done
5615 'category category
5616 'priority (+ 100 priority))
5617 txt)
5618 (if scheduledp
5619 (add-text-properties
5620 0 (length txt)
5621 (list 'face 'org-scheduled-today
5622 'undone-face 'org-scheduled-today
5623 'done-face 'org-done
5624 'category category
5625 priority (+ 99 priority))
5626 txt)
5627 (add-text-properties
5628 0 (length txt)
5629 (list 'priority priority 'category category) txt)))
5630 (push txt ee))
5631 (outline-next-heading))))
5632 (nreverse ee)))
5633
5634 (defun org-agenda-get-closed ()
5635 "Return the logged TODO entries for agenda display."
5636 (let* ((props (list 'mouse-face 'highlight
5637 'keymap org-agenda-keymap
5638 'help-echo
5639 (format "mouse-2 or RET jump to org file %s"
5640 (abbreviate-file-name buffer-file-name))))
5641 (regexp (concat
5642 "\\<" org-closed-string " *\\["
5643 (regexp-quote
5644 (substring
5645 (format-time-string
5646 (car org-time-stamp-formats)
5647 (apply 'encode-time ; DATE bound by calendar
5648 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5649 1 11))))
5650 marker hdmarker priority category tags
5651 ee txt timestr)
5652 (goto-char (point-min))
5653 (while (re-search-forward regexp nil t)
5654 (if (not (save-match-data (org-at-date-range-p)))
5655 (progn
5656 (setq marker (org-agenda-new-marker (match-beginning 0))
5657 category (org-get-category (match-beginning 0))
5658 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5659 ;; donep (org-entry-is-done-p)
5660 )
5661 (if (string-match "\\]" timestr)
5662 ;; substring should only run to end of time stamp
5663 (setq timestr (substring timestr 0 (match-end 0))))
5664 (save-excursion
5665 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5666 (progn
5667 (goto-char (match-end 1))
5668 (setq hdmarker (org-agenda-new-marker)
5669 tags (org-get-tags-at))
5670 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5671 (setq txt (org-format-agenda-item
5672 "Closed: "
5673 (match-string 1) category tags timestr)))
5674 (setq txt org-agenda-no-heading-message))
5675 (setq priority 100000)
5676 (add-text-properties
5677 0 (length txt) (append (list 'org-marker marker
5678 'org-hd-marker hdmarker
5679 'face 'org-done
5680 'priority priority
5681 'category category
5682 'undone-face 'org-warning
5683 'done-face 'org-done) props)
5684 txt)
5685 (push txt ee))
5686 (outline-next-heading))))
5687 (nreverse ee)))
5688
5689 (defun org-agenda-get-deadlines ()
5690 "Return the deadline information for agenda display."
5691 (let* ((wdays org-deadline-warning-days)
5692 (props (list 'mouse-face 'highlight
5693 'keymap org-agenda-keymap
5694 'help-echo
5695 (format "mouse-2 or RET jump to org file %s"
5696 (abbreviate-file-name buffer-file-name))))
5697 (regexp org-deadline-time-regexp)
5698 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5699 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5700 d2 diff pos pos1 category tags
5701 ee txt head)
5702 (goto-char (point-min))
5703 (while (re-search-forward regexp nil t)
5704 (setq pos (1- (match-beginning 1))
5705 d2 (time-to-days
5706 (org-time-string-to-time (match-string 1)))
5707 diff (- d2 d1))
5708 ;; When to show a deadline in the calendar:
5709 ;; If the expiration is within wdays warning time.
5710 ;; Past-due deadlines are only shown on the current date
5711 (if (and (< diff wdays) todayp (not (= diff 0)))
5712 (save-excursion
5713 (setq category (org-get-category))
5714 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5715 (progn
5716 (goto-char (match-end 0))
5717 (setq pos1 (match-end 1))
5718 (setq tags (org-get-tags-at pos1))
5719 (setq head (buffer-substring-no-properties
5720 (point)
5721 (progn (skip-chars-forward "^\r\n")
5722 (point))))
5723 (if (string-match org-looking-at-done-regexp head)
5724 (setq txt nil)
5725 (setq txt (org-format-agenda-item
5726 (format "In %3d d.: " diff) head category tags))))
5727 (setq txt org-agenda-no-heading-message))
5728 (when txt
5729 (add-text-properties
5730 0 (length txt)
5731 (append
5732 (list 'org-marker (org-agenda-new-marker pos)
5733 'org-hd-marker (org-agenda-new-marker pos1)
5734 'priority (+ (- 10 diff) (org-get-priority txt))
5735 'category category
5736 'face (cond ((<= diff 0) 'org-warning)
5737 ((<= diff 5) 'org-scheduled-previously)
5738 (t nil))
5739 'undone-face (cond
5740 ((<= diff 0) 'org-warning)
5741 ((<= diff 5) 'org-scheduled-previously)
5742 (t nil))
5743 'done-face 'org-done)
5744 props)
5745 txt)
5746 (push txt ee)))))
5747 ee))
5748
5749 (defun org-agenda-get-scheduled ()
5750 "Return the scheduled information for agenda display."
5751 (let* ((props (list 'face 'org-scheduled-previously
5752 'undone-face 'org-scheduled-previously
5753 'done-face 'org-done
5754 'mouse-face 'highlight
5755 'keymap org-agenda-keymap
5756 'help-echo
5757 (format "mouse-2 or RET jump to org file %s"
5758 (abbreviate-file-name buffer-file-name))))
5759 (regexp org-scheduled-time-regexp)
5760 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5761 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5762 d2 diff pos pos1 category tags
5763 ee txt head)
5764 (goto-char (point-min))
5765 (while (re-search-forward regexp nil t)
5766 (setq pos (1- (match-beginning 1))
5767 d2 (time-to-days
5768 (org-time-string-to-time (match-string 1)))
5769 diff (- d2 d1))
5770 ;; When to show a scheduled item in the calendar:
5771 ;; If it is on or past the date.
5772 (if (and (< diff 0) todayp)
5773 (save-excursion
5774 (setq category (org-get-category))
5775 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5776 (progn
5777 (goto-char (match-end 0))
5778 (setq pos1 (match-end 1))
5779 (setq tags (org-get-tags-at))
5780 (setq head (buffer-substring-no-properties
5781 (point)
5782 (progn (skip-chars-forward "^\r\n") (point))))
5783 (if (string-match org-looking-at-done-regexp head)
5784 (setq txt nil)
5785 (setq txt (org-format-agenda-item
5786 (format "Sched.%2dx: " (- 1 diff)) head
5787 category tags))))
5788 (setq txt org-agenda-no-heading-message))
5789 (when txt
5790 (add-text-properties
5791 0 (length txt)
5792 (append (list 'org-marker (org-agenda-new-marker pos)
5793 'org-hd-marker (org-agenda-new-marker pos1)
5794 'priority (+ (- 5 diff) (org-get-priority txt))
5795 'category category)
5796 props) txt)
5797 (push txt ee)))))
5798 ee))
5799
5800 (defun org-agenda-get-blocks ()
5801 "Return the date-range information for agenda display."
5802 (let* ((props (list 'face nil
5803 'mouse-face 'highlight
5804 'keymap org-agenda-keymap
5805 'help-echo
5806 (format "mouse-2 or RET jump to org file %s"
5807 (abbreviate-file-name buffer-file-name))))
5808 (regexp org-tr-regexp)
5809 (d0 (calendar-absolute-from-gregorian date))
5810 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
5811 (goto-char (point-min))
5812 (while (re-search-forward regexp nil t)
5813 (setq timestr (match-string 0)
5814 s1 (match-string 1)
5815 s2 (match-string 2)
5816 d1 (time-to-days (org-time-string-to-time s1))
5817 d2 (time-to-days (org-time-string-to-time s2)))
5818 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5819 ;; Only allow days between the limits, because the normal
5820 ;; date stamps will catch the limits.
5821 (save-excursion
5822 (setq marker (org-agenda-new-marker (point)))
5823 (setq category (org-get-category))
5824 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5825 (progn
5826 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5827 (goto-char (match-end 1))
5828 (setq tags (org-get-tags-at))
5829 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5830 (setq txt (org-format-agenda-item
5831 (format (if (= d1 d2) "" "(%d/%d): ")
5832 (1+ (- d0 d1)) (1+ (- d2 d1)))
5833 (match-string 1) category tags
5834 (if (= d0 d1) timestr))))
5835 (setq txt org-agenda-no-heading-message))
5836 (add-text-properties
5837 0 (length txt) (append (list 'org-marker marker
5838 'org-hd-marker hdmarker
5839 'priority (org-get-priority txt)
5840 'category category)
5841 props)
5842 txt)
5843 (push txt ee)))
5844 (outline-next-heading))
5845 ;; Sort the entries by expiration date.
5846 (nreverse ee)))
5847
5848 (defconst org-plain-time-of-day-regexp
5849 (concat
5850 "\\(\\<[012]?[0-9]"
5851 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5852 "\\(--?"
5853 "\\(\\<[012]?[0-9]"
5854 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5855 "\\)?")
5856 "Regular expression to match a plain time or time range.
5857 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5858 groups carry important information:
5859 0 the full match
5860 1 the first time, range or not
5861 8 the second time, if it is a range.")
5862
5863 (defconst org-stamp-time-of-day-regexp
5864 (concat
5865 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5866 "\\([012][0-9]:[0-5][0-9]\\)>"
5867 "\\(--?"
5868 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5869 "Regular expression to match a timestamp time or time range.
5870 After a match, the following groups carry important information:
5871 0 the full match
5872 1 date plus weekday, for backreferencing to make sure both times on same day
5873 2 the first time, range or not
5874 4 the second time, if it is a range.")
5875
5876 (defvar org-prefix-has-time nil
5877 "A flag, set by `org-compile-prefix-format'.
5878 The flag is set if the currently compiled format contains a `%t'.")
5879 (defvar org-prefix-has-tag nil
5880 "A flag, set by `org-compile-prefix-format'.
5881 The flag is set if the currently compiled format contains a `%T'.")
5882
5883 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
5884 "Format TXT to be inserted into the agenda buffer.
5885 In particular, it adds the prefix and corresponding text properties. EXTRA
5886 must be a string and replaces the `%s' specifier in the prefix format.
5887 CATEGORY (string, symbol or nil) may be used to overrule the default
5888 category taken from local variable or file name. It will replace the `%c'
5889 specifier in the format. DOTIME, when non-nil, indicates that a
5890 time-of-day should be extracted from TXT for sorting of this entry, and for
5891 the `%t' specifier in the format. When DOTIME is a string, this string is
5892 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5893 only the correctly processes TXT should be returned - this is used by
5894 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
5895 (save-match-data
5896 ;; Diary entries sometimes have extra whitespace at the beginning
5897 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5898 (let* ((category (or category
5899 org-category
5900 (if buffer-file-name
5901 (file-name-sans-extension
5902 (file-name-nondirectory buffer-file-name))
5903 "")))
5904 (tag (or (nth (1- (or (length tags) 0)) tags) ""))
5905 time ;; needed for the eval of the prefix format
5906 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5907 (time-of-day (and dotime (org-get-time-of-day ts)))
5908 stamp plain s0 s1 s2 rtn)
5909 (when (and dotime time-of-day org-prefix-has-time)
5910 ;; Extract starting and ending time and move them to prefix
5911 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5912 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5913 (setq s0 (match-string 0 ts)
5914 s1 (match-string (if plain 1 2) ts)
5915 s2 (match-string (if plain 8 4) ts))
5916
5917 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5918 ;; them, we might want to remove them there to avoid duplication.
5919 ;; The user can turn this off with a variable.
5920 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5921 (string-match (concat (regexp-quote s0) " *") txt)
5922 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5923 (= (match-beginning 0) 0)
5924 t))
5925 (setq txt (replace-match "" nil nil txt))))
5926 ;; Normalize the time(s) to 24 hour
5927 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5928 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5929
5930 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
5931 (and org-agenda-remove-tags-when-in-prefix
5932 org-prefix-has-tag))
5933 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
5934 (setq txt (replace-match "" t t txt)))
5935
5936 ;; Create the final string
5937 (if noprefix
5938 (setq rtn txt)
5939 ;; Prepare the variables needed in the eval of the compiled format
5940 (setq time (cond (s2 (concat s1 "-" s2))
5941 (s1 (concat s1 "......"))
5942 (t ""))
5943 extra (or extra "")
5944 category (if (symbolp category) (symbol-name category) category))
5945 ;; Evaluate the compiled format
5946 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5947
5948 ;; And finally add the text properties
5949 (add-text-properties
5950 0 (length rtn) (list 'category (downcase category)
5951 'tags tags
5952 'prefix-length (- (length rtn) (length txt))
5953 'time-of-day time-of-day
5954 'dotime dotime)
5955 rtn)
5956 rtn)))
5957
5958 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5959 (catch 'exit
5960 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5961 ((and todayp (member 'today (car org-agenda-time-grid))))
5962 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5963 ((member 'weekly (car org-agenda-time-grid)))
5964 (t (throw 'exit list)))
5965 (let* ((have (delq nil (mapcar
5966 (lambda (x) (get-text-property 1 'time-of-day x))
5967 list)))
5968 (string (nth 1 org-agenda-time-grid))
5969 (gridtimes (nth 2 org-agenda-time-grid))
5970 (req (car org-agenda-time-grid))
5971 (remove (member 'remove-match req))
5972 new time)
5973 (if (and (member 'require-timed req) (not have))
5974 ;; don't show empty grid
5975 (throw 'exit list))
5976 (while (setq time (pop gridtimes))
5977 (unless (and remove (member time have))
5978 (setq time (int-to-string time))
5979 (push (org-format-agenda-item
5980 nil string "" nil ;; FIXME: put a category for the grid?
5981 (concat (substring time 0 -2) ":" (substring time -2)))
5982 new)
5983 (put-text-property
5984 1 (length (car new)) 'face 'org-time-grid (car new))))
5985 (if (member 'time-up org-agenda-sorting-strategy)
5986 (append new list)
5987 (append list new)))))
5988
5989 (defun org-compile-prefix-format (format)
5990 "Compile the prefix format into a Lisp form that can be evaluated.
5991 The resulting form is returned and stored in the variable
5992 `org-prefix-format-compiled'."
5993 (setq org-prefix-has-time nil org-prefix-has-tag nil)
5994 (let ((start 0) varform vars var (s format)e c f opt)
5995 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5996 s start)
5997 (setq var (cdr (assoc (match-string 4 s)
5998 '(("c" . category) ("t" . time) ("s" . extra)
5999 ("T" . tag))))
6000 c (or (match-string 3 s) "")
6001 opt (match-beginning 1)
6002 start (1+ (match-beginning 0)))
6003 (if (equal var 'time) (setq org-prefix-has-time t))
6004 (if (equal var 'tag) (setq org-prefix-has-tag t))
6005 (setq f (concat "%" (match-string 2 s) "s"))
6006 (if opt
6007 (setq varform
6008 `(if (equal "" ,var)
6009 ""
6010 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6011 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6012 (setq s (replace-match "%s" t nil s))
6013 (push varform vars))
6014 (setq vars (nreverse vars))
6015 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6016
6017 (defun org-get-time-of-day (s &optional string)
6018 "Check string S for a time of day.
6019 If found, return it as a military time number between 0 and 2400.
6020 If not found, return nil.
6021 The optional STRING argument forces conversion into a 5 character wide string
6022 HH:MM."
6023 (save-match-data
6024 (when
6025 (or
6026 (string-match
6027 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6028 (string-match
6029 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6030 (let* ((t0 (+ (* 100
6031 (+ (string-to-number (match-string 1 s))
6032 (if (and (match-beginning 4)
6033 (equal (downcase (match-string 4 s)) "pm"))
6034 12 0)))
6035 (if (match-beginning 3)
6036 (string-to-number (match-string 3 s))
6037 0)))
6038 (t1 (concat " "
6039 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6040 (int-to-string t0))))
6041 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6042
6043 (defun org-finalize-agenda-entries (list)
6044 "Sort and concatenate the agenda items."
6045 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6046
6047 (defsubst org-cmp-priority (a b)
6048 "Compare the priorities of string A and B."
6049 (let ((pa (or (get-text-property 1 'priority a) 0))
6050 (pb (or (get-text-property 1 'priority b) 0)))
6051 (cond ((> pa pb) +1)
6052 ((< pa pb) -1)
6053 (t nil))))
6054
6055 (defsubst org-cmp-category (a b)
6056 "Compare the string values of categories of strings A and B."
6057 (let ((ca (or (get-text-property 1 'category a) ""))
6058 (cb (or (get-text-property 1 'category b) "")))
6059 (cond ((string-lessp ca cb) -1)
6060 ((string-lessp cb ca) +1)
6061 (t nil))))
6062
6063 (defsubst org-cmp-time (a b)
6064 "Compare the time-of-day values of strings A and B."
6065 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6066 (ta (or (get-text-property 1 'time-of-day a) def))
6067 (tb (or (get-text-property 1 'time-of-day b) def)))
6068 (cond ((< ta tb) -1)
6069 ((< tb ta) +1)
6070 (t nil))))
6071
6072 (defun org-entries-lessp (a b)
6073 "Predicate for sorting agenda entries."
6074 ;; The following variables will be used when the form is evaluated.
6075 (let* ((time-up (org-cmp-time a b))
6076 (time-down (if time-up (- time-up) nil))
6077 (priority-up (org-cmp-priority a b))
6078 (priority-down (if priority-up (- priority-up) nil))
6079 (category-up (org-cmp-category a b))
6080 (category-down (if category-up (- category-up) nil))
6081 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
6082 (cdr (assoc
6083 (eval (cons 'or org-agenda-sorting-strategy))
6084 '((-1 . t) (1 . nil) (nil . nil))))))
6085
6086 (defun org-agenda-show-priority ()
6087 "Show the priority of the current item.
6088 This priority is composed of the main priority given with the [#A] cookies,
6089 and by additional input from the age of a schedules or deadline entry."
6090 (interactive)
6091 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6092 (message "Priority is %d" (if pri pri -1000))))
6093
6094 (defun org-agenda-show-tags ()
6095 "Show the tags applicable to the current item."
6096 (interactive)
6097 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6098 (if tags
6099 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6100 (message "No tags associated with this line"))))
6101
6102 (defun org-agenda-goto (&optional highlight)
6103 "Go to the Org-mode file which contains the item at point."
6104 (interactive)
6105 (let* ((marker (or (get-text-property (point) 'org-marker)
6106 (org-agenda-error)))
6107 (buffer (marker-buffer marker))
6108 (pos (marker-position marker)))
6109 (switch-to-buffer-other-window buffer)
6110 (widen)
6111 (goto-char pos)
6112 (when (eq major-mode 'org-mode)
6113 (org-show-hidden-entry)
6114 (save-excursion
6115 (and (outline-next-heading)
6116 (org-flag-heading nil)))) ; show the next heading
6117 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6118
6119 (defun org-agenda-switch-to ()
6120 "Go to the Org-mode file which contains the item at point."
6121 (interactive)
6122 (let* ((marker (or (get-text-property (point) 'org-marker)
6123 (org-agenda-error)))
6124 (buffer (marker-buffer marker))
6125 (pos (marker-position marker)))
6126 (switch-to-buffer buffer)
6127 (delete-other-windows)
6128 (widen)
6129 (goto-char pos)
6130 (when (eq major-mode 'org-mode)
6131 (org-show-hidden-entry)
6132 (save-excursion
6133 (and (outline-next-heading)
6134 (org-flag-heading nil)))))) ; show the next heading
6135
6136 (defun org-agenda-goto-mouse (ev)
6137 "Go to the Org-mode file which contains the item at the mouse click."
6138 (interactive "e")
6139 (mouse-set-point ev)
6140 (org-agenda-goto))
6141
6142 (defun org-agenda-show ()
6143 "Display the Org-mode file which contains the item at point."
6144 (interactive)
6145 (let ((win (selected-window)))
6146 (org-agenda-goto t)
6147 (select-window win)))
6148
6149 (defun org-agenda-recenter (arg)
6150 "Display the Org-mode file which contains the item at point and recenter."
6151 (interactive "P")
6152 (let ((win (selected-window)))
6153 (org-agenda-goto t)
6154 (recenter arg)
6155 (select-window win)))
6156
6157 (defun org-agenda-show-mouse (ev)
6158 "Display the Org-mode file which contains the item at the mouse click."
6159 (interactive "e")
6160 (mouse-set-point ev)
6161 (org-agenda-show))
6162
6163 (defun org-agenda-check-no-diary ()
6164 "Check if the entry is a diary link and abort if yes."
6165 (if (get-text-property (point) 'org-agenda-diary-link)
6166 (org-agenda-error)))
6167
6168 (defun org-agenda-error ()
6169 (error "Command not allowed in this line"))
6170
6171 (defvar org-last-heading-marker (make-marker)
6172 "Marker pointing to the headline that last changed its TODO state
6173 by a remote command from the agenda.")
6174
6175 (defun org-agenda-todo (&optional arg)
6176 "Cycle TODO state of line at point, also in Org-mode file.
6177 This changes the line at point, all other lines in the agenda referring to
6178 the same tree node, and the headline of the tree node in the Org-mode file."
6179 (interactive "P")
6180 (org-agenda-check-no-diary)
6181 (let* ((col (current-column))
6182 (marker (or (get-text-property (point) 'org-marker)
6183 (org-agenda-error)))
6184 (buffer (marker-buffer marker))
6185 (pos (marker-position marker))
6186 (hdmarker (get-text-property (point) 'org-hd-marker))
6187 (buffer-read-only nil)
6188 newhead)
6189 (with-current-buffer buffer
6190 (widen)
6191 (goto-char pos)
6192 (org-show-hidden-entry)
6193 (save-excursion
6194 (and (outline-next-heading)
6195 (org-flag-heading nil))) ; show the next heading
6196 (org-todo arg)
6197 (forward-char 1)
6198 (setq newhead (org-get-heading))
6199 (save-excursion
6200 (org-back-to-heading)
6201 (move-marker org-last-heading-marker (point))))
6202 (beginning-of-line 1)
6203 (save-excursion
6204 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6205 (move-to-column col)))
6206
6207 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6208 "Change all lines in the agenda buffer which match HDMARKER.
6209 The new content of the line will be NEWHEAD (as modified by
6210 `org-format-agenda-item'). HDMARKER is checked with
6211 `equal' against all `org-hd-marker' text properties in the file.
6212 If FIXFACE is non-nil, the face of each item is modified acording to
6213 the new TODO state."
6214 (let* (props m pl undone-face done-face finish new dotime cat tags)
6215 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6216 (save-excursion
6217 (goto-char (point-max))
6218 (beginning-of-line 1)
6219 (while (not finish)
6220 (setq finish (bobp))
6221 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6222 (equal m hdmarker))
6223 (setq props (text-properties-at (point))
6224 dotime (get-text-property (point) 'dotime)
6225 cat (get-text-property (point) 'category)
6226 tags (get-text-property (point) 'tags)
6227 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6228 pl (get-text-property (point) 'prefix-length)
6229 undone-face (get-text-property (point) 'undone-face)
6230 done-face (get-text-property (point) 'done-face))
6231 (move-to-column pl)
6232 (if (looking-at ".*")
6233 (progn
6234 (replace-match new t t)
6235 (beginning-of-line 1)
6236 (add-text-properties (point-at-bol) (point-at-eol) props)
6237 (if fixface
6238 (add-text-properties
6239 (point-at-bol) (point-at-eol)
6240 (list 'face
6241 (if org-last-todo-state-is-todo
6242 undone-face done-face))))
6243 (beginning-of-line 1))
6244 (error "Line update did not work")))
6245 (beginning-of-line 0)))))
6246
6247 (defun org-agenda-priority-up ()
6248 "Increase the priority of line at point, also in Org-mode file."
6249 (interactive)
6250 (org-agenda-priority 'up))
6251
6252 (defun org-agenda-priority-down ()
6253 "Decrease the priority of line at point, also in Org-mode file."
6254 (interactive)
6255 (org-agenda-priority 'down))
6256
6257 (defun org-agenda-priority (&optional force-direction)
6258 "Set the priority of line at point, also in Org-mode file.
6259 This changes the line at point, all other lines in the agenda referring to
6260 the same tree node, and the headline of the tree node in the Org-mode file."
6261 (interactive)
6262 (org-agenda-check-no-diary)
6263 (let* ((marker (or (get-text-property (point) 'org-marker)
6264 (org-agenda-error)))
6265 (buffer (marker-buffer marker))
6266 (pos (marker-position marker))
6267 (hdmarker (get-text-property (point) 'org-hd-marker))
6268 (buffer-read-only nil)
6269 newhead)
6270 (with-current-buffer buffer
6271 (widen)
6272 (goto-char pos)
6273 (org-show-hidden-entry)
6274 (save-excursion
6275 (and (outline-next-heading)
6276 (org-flag-heading nil))) ; show the next heading
6277 (funcall 'org-priority force-direction)
6278 (end-of-line 1)
6279 (setq newhead (org-get-heading)))
6280 (org-agenda-change-all-lines newhead hdmarker)
6281 (beginning-of-line 1)))
6282
6283 (defun org-get-tags-at (&optional pos)
6284 "Get a list of all headline targs applicable at POS.
6285 POS defaults to point. If tags are inherited, the list contains
6286 the targets in the same sequence as the headlines appear, i.e.
6287 the tags of the current headline come last."
6288 (interactive)
6289 (let (tags)
6290 (save-excursion
6291 (goto-char (or pos (point)))
6292 (save-match-data
6293 (org-back-to-heading t)
6294 (condition-case nil
6295 (while t
6296 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6297 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6298 (or org-use-tag-inheritance (error ""))
6299 (org-up-heading-all 1))
6300 (error nil))))
6301 (message "%s" tags)
6302 tags))
6303
6304 (defun org-agenda-set-tags ()
6305 "Set tags for the current headline."
6306 (interactive)
6307 (org-agenda-check-no-diary)
6308 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6309 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6310 (org-agenda-error)))
6311 (buffer (marker-buffer hdmarker))
6312 (pos (marker-position hdmarker))
6313 (buffer-read-only nil)
6314 newhead)
6315 (with-current-buffer buffer
6316 (widen)
6317 (goto-char pos)
6318 (org-show-hidden-entry)
6319 (save-excursion
6320 (and (outline-next-heading)
6321 (org-flag-heading nil))) ; show the next heading
6322 (call-interactively 'org-set-tags)
6323 (end-of-line 1)
6324 (setq newhead (org-get-heading)))
6325 (org-agenda-change-all-lines newhead hdmarker)
6326 (beginning-of-line 1)))
6327
6328 (defun org-agenda-date-later (arg &optional what)
6329 "Change the date of this item to one day later."
6330 (interactive "p")
6331 (org-agenda-check-type t 'agenda 'timeline)
6332 (org-agenda-check-no-diary)
6333 (let* ((marker (or (get-text-property (point) 'org-marker)
6334 (org-agenda-error)))
6335 (buffer (marker-buffer marker))
6336 (pos (marker-position marker)))
6337 (with-current-buffer buffer
6338 (widen)
6339 (goto-char pos)
6340 (if (not (org-at-timestamp-p))
6341 (error "Cannot find time stamp"))
6342 (org-timestamp-change arg (or what 'day))
6343 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6344
6345 (defun org-agenda-date-earlier (arg &optional what)
6346 "Change the date of this item to one day earlier."
6347 (interactive "p")
6348 (org-agenda-date-later (- arg) what))
6349
6350 (defun org-agenda-date-prompt (arg)
6351 "Change the date of this item. Date is prompted for, with default today.
6352 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6353 be used to request time specification in the time stamp."
6354 (interactive "P")
6355 (org-agenda-check-type t 'agenda 'timeline)
6356 (org-agenda-check-no-diary)
6357 (let* ((marker (or (get-text-property (point) 'org-marker)
6358 (org-agenda-error)))
6359 (buffer (marker-buffer marker))
6360 (pos (marker-position marker)))
6361 (with-current-buffer buffer
6362 (widen)
6363 (goto-char pos)
6364 (if (not (org-at-timestamp-p))
6365 (error "Cannot find time stamp"))
6366 (org-time-stamp arg)
6367 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6368
6369 (defun org-get-heading ()
6370 "Return the heading of the current entry, without the stars."
6371 (save-excursion
6372 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6373 ;;FIXME???????? (and (bolp) (end-of-line 1))
6374 (if (and (re-search-backward "[\r\n]\\*" nil t)
6375 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6376 (match-string 1)
6377 "")))
6378
6379 (defun org-agenda-diary-entry ()
6380 "Make a diary entry, like the `i' command from the calendar.
6381 All the standard commands work: block, weekly etc."
6382 (interactive)
6383 (org-agenda-check-type t 'agenda 'timeline)
6384 (require 'diary-lib)
6385 (let* ((char (progn
6386 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6387 (read-char-exclusive)))
6388 (cmd (cdr (assoc char
6389 '((?d . insert-diary-entry)
6390 (?w . insert-weekly-diary-entry)
6391 (?m . insert-monthly-diary-entry)
6392 (?y . insert-yearly-diary-entry)
6393 (?a . insert-anniversary-diary-entry)
6394 (?b . insert-block-diary-entry)
6395 (?c . insert-cyclic-diary-entry)))))
6396 (oldf (symbol-function 'calendar-cursor-to-date))
6397 (point (point))
6398 (mark (or (mark t) (point))))
6399 (unless cmd
6400 (error "No command associated with <%c>" char))
6401 (unless (and (get-text-property point 'day)
6402 (or (not (equal ?b char))
6403 (get-text-property mark 'day)))
6404 (error "Don't know which date to use for diary entry"))
6405 ;; We implement this by hacking the `calendar-cursor-to-date' function
6406 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6407 (let ((calendar-mark-ring
6408 (list (calendar-gregorian-from-absolute
6409 (or (get-text-property mark 'day)
6410 (get-text-property point 'day))))))
6411 (unwind-protect
6412 (progn
6413 (fset 'calendar-cursor-to-date
6414 (lambda (&optional error)
6415 (calendar-gregorian-from-absolute
6416 (get-text-property point 'day))))
6417 (call-interactively cmd))
6418 (fset 'calendar-cursor-to-date oldf)))))
6419
6420
6421 (defun org-agenda-execute-calendar-command (cmd)
6422 "Execute a calendar command from the agenda, with the date associated to
6423 the cursor position."
6424 (org-agenda-check-type t 'agenda 'timeline)
6425 (require 'diary-lib)
6426 (unless (get-text-property (point) 'day)
6427 (error "Don't know which date to use for calendar command"))
6428 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6429 (point (point))
6430 (date (calendar-gregorian-from-absolute
6431 (get-text-property point 'day)))
6432 (displayed-day (extract-calendar-day date))
6433 (displayed-month (extract-calendar-month date))
6434 (displayed-year (extract-calendar-year date)))
6435 (unwind-protect
6436 (progn
6437 (fset 'calendar-cursor-to-date
6438 (lambda (&optional error)
6439 (calendar-gregorian-from-absolute
6440 (get-text-property point 'day))))
6441 (call-interactively cmd))
6442 (fset 'calendar-cursor-to-date oldf))))
6443
6444 (defun org-agenda-phases-of-moon ()
6445 "Display the phases of the moon for the 3 months around the cursor date."
6446 (interactive)
6447 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6448
6449 (defun org-agenda-holidays ()
6450 "Display the holidays for the 3 months around the cursor date."
6451 (interactive)
6452 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6453
6454 (defun org-agenda-sunrise-sunset (arg)
6455 "Display sunrise and sunset for the cursor date.
6456 Latitude and longitude can be specified with the variables
6457 `calendar-latitude' and `calendar-longitude'. When called with prefix
6458 argument, latitude and longitude will be prompted for."
6459 (interactive "P")
6460 (let ((calendar-longitude (if arg nil calendar-longitude))
6461 (calendar-latitude (if arg nil calendar-latitude))
6462 (calendar-location-name
6463 (if arg "the given coordinates" calendar-location-name)))
6464 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6465
6466 (defun org-agenda-goto-calendar ()
6467 "Open the Emacs calendar with the date at the cursor."
6468 (interactive)
6469 (org-agenda-check-type t 'agenda 'timeline)
6470 (let* ((day (or (get-text-property (point) 'day)
6471 (error "Don't know which date to open in calendar")))
6472 (date (calendar-gregorian-from-absolute day))
6473 (calendar-move-hook nil)
6474 (view-diary-entries-initially nil))
6475 (calendar)
6476 (calendar-goto-date date)))
6477
6478 (defun org-calendar-goto-agenda ()
6479 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6480 This is a command that has to be installed in `calendar-mode-map'."
6481 (interactive)
6482 (org-agenda-list nil (calendar-absolute-from-gregorian
6483 (calendar-cursor-to-date))
6484 nil t))
6485
6486 (defun org-agenda-convert-date ()
6487 (interactive)
6488 (org-agenda-check-type t 'agenda 'timeline)
6489 (let ((day (get-text-property (point) 'day))
6490 date s)
6491 (unless day
6492 (error "Don't know which date to convert"))
6493 (setq date (calendar-gregorian-from-absolute day))
6494 (setq s (concat
6495 "Gregorian: " (calendar-date-string date) "\n"
6496 "ISO: " (calendar-iso-date-string date) "\n"
6497 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6498 "Julian: " (calendar-julian-date-string date) "\n"
6499 "Astron. JD: " (calendar-astro-date-string date)
6500 " (Julian date number at noon UTC)\n"
6501 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6502 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6503 "French: " (calendar-french-date-string date) "\n"
6504 "Mayan: " (calendar-mayan-date-string date) "\n"
6505 "Coptic: " (calendar-coptic-date-string date) "\n"
6506 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6507 "Persian: " (calendar-persian-date-string date) "\n"
6508 "Chinese: " (calendar-chinese-date-string date) "\n"))
6509 (with-output-to-temp-buffer "*Dates*"
6510 (princ s))
6511 (if (fboundp 'fit-window-to-buffer)
6512 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6513
6514 ;;; Tags
6515
6516 (defun org-scan-tags (action matcher &optional todo-only)
6517 "Scan headline tags with inheritance and produce output ACTION.
6518 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6519 evaluated, testing if a given set of tags qualifies a headline for
6520 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6521 are included in the output."
6522 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6523 (mapconcat 'regexp-quote
6524 (nreverse (cdr (reverse org-todo-keywords)))
6525 "\\|")
6526 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6527 (props (list 'face nil
6528 'done-face 'org-done
6529 'undone-face nil
6530 'mouse-face 'highlight
6531 'keymap org-agenda-keymap
6532 'help-echo
6533 (format "mouse-2 or RET jump to org file %s"
6534 (abbreviate-file-name buffer-file-name))))
6535 lspos
6536 tags tags-list tags-alist (llast 0) rtn level category i txt
6537 todo marker)
6538
6539 (save-excursion
6540 (goto-char (point-min))
6541 (when (eq action 'sparse-tree) (hide-sublevels 1))
6542 (while (re-search-forward re nil t)
6543 (setq todo (if (match-end 1) (match-string 2))
6544 tags (if (match-end 4) (match-string 4)))
6545 (goto-char (setq lspos (1+ (match-beginning 0))))
6546 (setq level (funcall outline-level)
6547 category (org-get-category))
6548 (setq i llast llast level)
6549 ;; remove tag lists from same and sublevels
6550 (while (>= i level)
6551 (when (setq entry (assoc i tags-alist))
6552 (setq tags-alist (delete entry tags-alist)))
6553 (setq i (1- i)))
6554 ;; add the nex tags
6555 (when tags
6556 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6557 tags-alist
6558 (cons (cons level tags) tags-alist)))
6559 ;; compile tags for current headline
6560 (setq tags-list
6561 (if org-use-tag-inheritance
6562 (apply 'append (mapcar 'cdr tags-alist))
6563 tags))
6564 (when (and (or (not todo-only) todo)
6565 (eval matcher))
6566 ;; list this headline
6567 (if (eq action 'sparse-tree)
6568 (progn
6569 (org-show-hierarchy-above))
6570 (setq txt (org-format-agenda-item
6571 ""
6572 (concat
6573 (if org-tags-match-list-sublevels
6574 (make-string (1- level) ?.) "")
6575 (org-get-heading))
6576 category tags-list))
6577 (goto-char lspos)
6578 (setq marker (org-agenda-new-marker))
6579 (add-text-properties
6580 0 (length txt)
6581 (append (list 'org-marker marker 'org-hd-marker marker
6582 'category category)
6583 props)
6584 txt)
6585 (push txt rtn))
6586 ;; if we are to skip sublevels, jump to end of subtree
6587 (point)
6588 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6589 (nreverse rtn)))
6590
6591 (defun org-tags-sparse-tree (&optional arg match)
6592 "Create a sparse tree according to tags search string MATCH.
6593 MATCH can contain positive and negative selection of tags, like
6594 \"+WORK+URGENT-WITHBOSS\"."
6595 (interactive "P")
6596 (let ((org-show-following-heading nil)
6597 (org-show-hierarchy-above nil))
6598 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6599
6600 (defun org-make-tags-matcher (match)
6601 "Create the TAGS matcher form for the tags-selecting string MATCH."
6602 (unless match
6603 ;; Get a new match request, with completion
6604 (setq org-last-tags-completion-table
6605 (or (org-get-buffer-tags)
6606 org-last-tags-completion-table))
6607 (setq match (completing-read
6608 "Tags: " 'org-tags-completion-function nil nil nil
6609 'org-tags-history)))
6610 ;; parse the string and create a lisp form
6611 (let ((match0 match) minus tag mm matcher orterms term orlist)
6612 (setq orterms (org-split-string match "|"))
6613 (while (setq term (pop orterms))
6614 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
6615 (setq minus (and (match-end 1)
6616 (equal (match-string 1 term) "-"))
6617 tag (match-string 2 term)
6618 term (substring term (match-end 0))
6619 mm (list 'member (downcase tag) 'tags-list)
6620 mm (if minus (list 'not mm) mm))
6621 (push mm matcher))
6622 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6623 orlist)
6624 (setq matcher nil))
6625 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6626 ;; Return the string and lisp forms of the matcher
6627 (cons match0 matcher)))
6628
6629 ;;;###autoload
6630 (defun org-tags-view (&optional todo-only match keep-modes)
6631 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
6632 The prefix arg TODO-ONLY limits the search to TODO entries."
6633 (interactive "P")
6634 (org-agenda-maybe-reset-markers 'force)
6635 (org-compile-prefix-format org-agenda-prefix-format)
6636 (let* ((org-agenda-keep-modes keep-modes)
6637 (org-tags-match-list-sublevels
6638 (if todo-only t org-tags-match-list-sublevels))
6639 (win (selected-window))
6640 (completion-ignore-case t)
6641 rtn rtnall files file pos matcher
6642 buffer)
6643 (setq matcher (org-make-tags-matcher match)
6644 match (car matcher) matcher (cdr matcher))
6645 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6646 (progn
6647 (delete-other-windows)
6648 (switch-to-buffer-other-window
6649 (get-buffer-create org-agenda-buffer-name))))
6650 (setq buffer-read-only nil)
6651 (erase-buffer)
6652 (org-agenda-mode) (setq buffer-read-only nil)
6653 (set (make-local-variable 'org-agenda-type) 'tags)
6654 (set (make-local-variable 'org-agenda-redo-command)
6655 (list 'org-tags-view (list 'quote todo-only)
6656 (list 'if 'current-prefix-arg nil match) t))
6657 (setq files (org-agenda-files)
6658 rtnall nil)
6659 (while (setq file (pop files))
6660 (catch 'nextfile
6661 (org-check-agenda-file file)
6662 (setq buffer (if (file-exists-p file)
6663 (org-get-agenda-file-buffer file)
6664 (error "No such file %s" file)))
6665 (if (not buffer)
6666 ;; If file does not exist, merror message to agenda
6667 (setq rtn (list
6668 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6669 rtnall (append rtnall rtn))
6670 (with-current-buffer buffer
6671 (unless (eq major-mode 'org-mode)
6672 (error "Agenda file %s is not in `org-mode'" file))
6673 (save-excursion
6674 (save-restriction
6675 (if org-respect-restriction
6676 (if (org-region-active-p)
6677 ;; Respect a region to restrict search
6678 (narrow-to-region (region-beginning) (region-end)))
6679 ;; If we work for the calendar or many files,
6680 ;; get rid of any restriction
6681 (widen))
6682 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6683 (setq rtnall (append rtnall rtn))))))))
6684 (insert "Headlines with TAGS match: ")
6685 (add-text-properties (point-min) (1- (point))
6686 (list 'face 'org-link))
6687 (setq pos (point))
6688 (insert match "\n")
6689 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6690 (setq pos (point))
6691 (insert "Press `C-u r' to search again with new search string\n")
6692 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6693 (when rtnall
6694 (insert (mapconcat 'identity rtnall "\n")))
6695 (goto-char (point-min))
6696 (setq buffer-read-only t)
6697 (org-fit-agenda-window)
6698 (if (not org-select-agenda-window) (select-window win))))
6699
6700 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6701 (defun org-set-tags (&optional arg just-align)
6702 "Set the tags for the current headline.
6703 With prefix ARG, realign all tags in headings in the current buffer."
6704 (interactive)
6705 (let* (;(inherit (org-get-inherited-tags))
6706 (re (concat "^" outline-regexp))
6707 (col (current-column))
6708 (current (org-get-tags))
6709 tags hd empty invis)
6710 (if arg
6711 (save-excursion
6712 (goto-char (point-min))
6713 (while (re-search-forward re nil t)
6714 (org-set-tags nil t))
6715 (message "All tags realigned to column %d" org-tags-column))
6716 (if just-align
6717 (setq tags current)
6718 (setq org-last-tags-completion-table
6719 (or (org-get-buffer-tags)
6720 org-last-tags-completion-table))
6721 (setq tags
6722 (let ((org-add-colon-after-tag-completion t))
6723 (completing-read "Tags: " 'org-tags-completion-function
6724 nil nil current 'org-tags-history)))
6725 (while (string-match "[-+&]+" tags)
6726 (setq tags (replace-match ":" t t tags))))
6727 ;; FIXME: still optimize this byt not checking when JUST-ALIGN?
6728 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6729 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6730 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
6731 (if (equal current "")
6732 (progn
6733 (end-of-line 1)
6734 (or empty (insert-before-markers " ")))
6735 (beginning-of-line 1)
6736 (setq invis (org-invisible-p))
6737 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6738 (setq hd (match-string 1))
6739 (delete-region (match-beginning 0) (match-end 0))
6740 (insert-before-markers (org-trim hd) (if empty "" " ")))
6741 ;; FIXME: What happens when adding a new tag??? Seems OK!!!
6742 (unless (equal tags "")
6743 (move-to-column (max (current-column)
6744 (if (> org-tags-column 0)
6745 org-tags-column
6746 (- (- org-tags-column) (length tags))))
6747 t)
6748 (insert-before-markers tags)
6749 (if (and (not invis) (org-invisible-p))
6750 (outline-flag-region (point-at-bol) (point) nil)))
6751 (move-to-column col))))
6752
6753 (defun org-tags-completion-function (string predicate &optional flag)
6754 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6755 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6756 (setq s1 (match-string 1 string)
6757 s2 (match-string 2 string))
6758 (setq s1 "" s2 string))
6759 (cond
6760 ((eq flag nil)
6761 ;; try completion
6762 (setq rtn (try-completion s2 ctable))
6763 (if (stringp rtn)
6764 (concat s1 s2 (substring rtn (length s2))
6765 (if (and org-add-colon-after-tag-completion
6766 (assoc rtn ctable))
6767 ":" "")))
6768 )
6769 ((eq flag t)
6770 ;; all-completions
6771 (all-completions s2 ctable)
6772 )
6773 ((eq flag 'lambda)
6774 ;; exact match?
6775 (assoc s2 ctable)))
6776 ))
6777
6778 (defun org-get-tags ()
6779 "Get the TAGS string in the current headline."
6780 (unless (org-on-heading-p)
6781 (error "Not on a heading"))
6782 (save-excursion
6783 (beginning-of-line 1)
6784 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
6785 (match-string 1)
6786 "")))
6787
6788 (defun org-get-buffer-tags ()
6789 "Get a table of all tags used in the buffer, for completion."
6790 (let (tags)
6791 (save-excursion
6792 (goto-char (point-min))
6793 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
6794 (mapc (lambda (x) (add-to-list 'tags x))
6795 (org-split-string (match-string 1) ":"))))
6796 (mapcar 'list tags)))
6797
6798 ;;; Link Stuff
6799
6800 (defun org-find-file-at-mouse (ev)
6801 "Open file link or URL at mouse."
6802 (interactive "e")
6803 (mouse-set-point ev)
6804 (org-open-at-point 'in-emacs))
6805
6806 (defun org-open-at-mouse (ev)
6807 "Open file link or URL at mouse."
6808 (interactive "e")
6809 (mouse-set-point ev)
6810 (org-open-at-point))
6811
6812 (defun org-open-at-point (&optional in-emacs)
6813 "Open link at or after point.
6814 If there is no link at point, this function will search forward up to
6815 the end of the current subtree.
6816 Normally, files will be opened by an appropriate application. If the
6817 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6818 (interactive "P")
6819 (org-remove-occur-highlights nil nil t)
6820 (if (org-at-timestamp-p)
6821 (org-agenda-list nil (time-to-days (org-time-string-to-time
6822 (substring (match-string 1) 0 10)))
6823 1)
6824 (let (type path link line search (pos (point)))
6825 (catch 'match
6826 (save-excursion
6827 (skip-chars-forward "^]\n\r")
6828 (when (and (re-search-backward "\\[\\[" nil t)
6829 (looking-at org-bracket-link-regexp)
6830 (<= (match-beginning 0) pos)
6831 (>= (match-end 0) pos))
6832 (setq link (match-string 1))
6833 (while (string-match " *\n *" link)
6834 (setq link (replace-match " " t t link)))
6835 (if (string-match org-link-regexp link)
6836 (setq type (match-string 1 link)
6837 path (match-string 2 link))
6838 (setq type "thisfile"
6839 path link))
6840 (throw 'match t)))
6841
6842 (when (get-text-property (point) 'org-linked-text)
6843 (setq type "thisfile"
6844 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6845 (1+ (point)) (point))
6846 path (buffer-substring
6847 (previous-single-property-change pos 'org-linked-text)
6848 (next-single-property-change pos 'org-linked-text)))
6849 (throw 'match t))
6850
6851 (save-excursion
6852 (skip-chars-backward
6853 (concat (if org-allow-space-in-links "^" "^ ")
6854 org-non-link-chars))
6855 (when (or (looking-at org-link-regexp)
6856 (and (re-search-forward org-link-regexp (point-at-eol) t)
6857 (<= (match-beginning 0) pos)
6858 (>= (match-end 0) pos)))
6859 (setq type (match-string 1)
6860 path (match-string 2))
6861 (throw 'match t)))
6862 (save-excursion
6863 (skip-chars-backward "^ \t\n\r")
6864 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
6865 (setq type "tags"
6866 path (match-string 1))
6867 (while (string-match ":" path)
6868 (setq path (replace-match "+" t t path)))
6869 (throw 'match t)))
6870 (save-excursion
6871 (skip-chars-backward "a-zA-Z_")
6872 (when (and org-activate-camels
6873 (looking-at org-camel-regexp))
6874 (setq type "camel" path (match-string 0))
6875 (if (equal (char-before) ?*)
6876 (setq path (concat "*" path))))
6877 (throw 'match t))
6878 (save-excursion
6879 (when (re-search-forward
6880 org-link-regexp
6881 (save-excursion
6882 (condition-case nil
6883 (progn (outline-end-of-subtree) (max pos (point)))
6884 (error (end-of-line 1) (point))))
6885 t)
6886 (setq type (match-string 1)
6887 path (match-string 2)))))
6888 (unless path
6889 (error "No link found"))
6890 ;; Remove any trailing spaces in path
6891 (if (string-match " +\\'" path)
6892 (setq path (replace-match "" t t path)))
6893
6894 (cond
6895
6896 ((member type '("http" "https" "ftp" "mailto" "news"))
6897 ;; give these to some browser
6898 (browse-url (concat type ":" path)))
6899
6900 ((string= type "tags")
6901 (org-tags-view in-emacs path))
6902 ((or (string= type "camel")
6903 (string= type "thisfile"))
6904 (org-mark-ring-push)
6905 (org-link-search
6906 path
6907 (cond ((equal in-emacs '(4)) 'occur)
6908 ((equal in-emacs '(16)) 'org-occur)
6909 (t nil))))
6910
6911 ((string= type "file")
6912 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6913 (setq line (string-to-number (match-string 1 path))
6914 path (substring path 0 (match-beginning 0)))
6915 (if (string-match "::\\(.+\\)\\'" path)
6916 (setq search (match-string 1 path)
6917 path (substring path 0 (match-beginning 0)))))
6918 (org-open-file path in-emacs line search))
6919
6920 ((string= type "news")
6921 (org-follow-gnus-link path))
6922
6923 ((string= type "bbdb")
6924 (org-follow-bbdb-link path))
6925
6926 ((string= type "gnus")
6927 (let (group article)
6928 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6929 (error "Error in Gnus link"))
6930 (setq group (match-string 1 path)
6931 article (match-string 3 path))
6932 (org-follow-gnus-link group article)))
6933
6934 ((string= type "vm")
6935 (let (folder article)
6936 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6937 (error "Error in VM link"))
6938 (setq folder (match-string 1 path)
6939 article (match-string 3 path))
6940 ;; in-emacs is the prefix arg, will be interpreted as read-only
6941 (org-follow-vm-link folder article in-emacs)))
6942
6943 ((string= type "wl")
6944 (let (folder article)
6945 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6946 (error "Error in Wanderlust link"))
6947 (setq folder (match-string 1 path)
6948 article (match-string 3 path))
6949 (org-follow-wl-link folder article)))
6950
6951 ((string= type "mhe")
6952 (let (folder article)
6953 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6954 (error "Error in MHE link"))
6955 (setq folder (match-string 1 path)
6956 article (match-string 3 path))
6957 (org-follow-mhe-link folder article)))
6958
6959 ((string= type "rmail")
6960 (let (folder article)
6961 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6962 (error "Error in RMAIL link"))
6963 (setq folder (match-string 1 path)
6964 article (match-string 3 path))
6965 (org-follow-rmail-link folder article)))
6966
6967 ((string= type "shell")
6968 (let ((cmd path))
6969 (while (string-match "@{" cmd)
6970 (setq cmd (replace-match "<" t t cmd)))
6971 (while (string-match "@}" cmd)
6972 (setq cmd (replace-match ">" t t cmd)))
6973 (if (or (not org-confirm-shell-links)
6974 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6975 (shell-command cmd)
6976 (error "Abort"))))
6977
6978 (t
6979 (browse-url-at-point))))))
6980
6981 (defun org-link-search (s &optional type)
6982 "Search for a link search option.
6983 When S is a CamelCaseWord, search for a target, or for a sentence containing
6984 the words. If S is surrounded by forward slashes, it is interpreted as a
6985 regular expression. In org-mode files, this will create an `org-occur'
6986 sparse tree. In ordinary files, `occur' will be used to list matches.
6987 If the current buffer is in `dired-mode', grep will be used to search
6988 in all files."
6989 (let ((case-fold-search t)
6990 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6991 (pos (point))
6992 (pre "") (post "")
6993 words re0 re1 re2 re3 re4 re5 re2a reall camel)
6994 (cond ((save-excursion
6995 (goto-char (point-min))
6996 (and
6997 (re-search-forward
6998 (concat "<<" (regexp-quote s0) ">>") nil t)
6999 (setq pos (match-beginning 0))))
7000 ;; There is an exact target for this
7001 (goto-char pos))
7002 ((string-match "^/\\(.*\\)/$" s)
7003 ;; A regular expression
7004 (cond
7005 ((eq major-mode 'org-mode)
7006 (org-occur (match-string 1 s)))
7007 ;;((eq major-mode 'dired-mode)
7008 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7009 (t (org-do-occur (match-string 1 s)))))
7010 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
7011 t)
7012 ;; A camel or a normal search string
7013 (when (equal (string-to-char s) ?*)
7014 ;; Anchor on headlines, post may include tags.
7015 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
7016 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
7017 s (substring s 1)))
7018 (remove-text-properties
7019 0 (length s)
7020 '(face nil mouse-face nil keymap nil fontified nil) s)
7021 ;; Make a series of regular expressions to find a match
7022 (setq words
7023 (if camel
7024 (org-camel-to-words s)
7025 (org-split-string s "[ \n\r\t]+"))
7026 re0 (concat "<<" (regexp-quote s0) ">>")
7027 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
7028 re2a (concat "\\<" (mapconcat 'downcase words "[ \t\r\n]+") "\\>")
7029 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
7030 re1 (concat pre re2 post)
7031 re3 (concat pre re4 post)
7032 re5 (concat pre ".*" re4)
7033 re2 (concat pre re2)
7034 re2a (concat pre re2a)
7035 re4 (concat pre re4)
7036 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7037 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7038 re5 "\\)"
7039 ))
7040 (cond
7041 ((eq type 'org-occur) (org-occur reall))
7042 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7043 (t (goto-char (point-min))
7044 (if (or (org-search-not-link re0 nil t)
7045 (org-search-not-link re1 nil t)
7046 (org-search-not-link re2 nil t)
7047 (org-search-not-link re2a nil t) ;; FIXME: Right place???
7048 (org-search-not-link re3 nil t)
7049 (org-search-not-link re4 nil t)
7050 (org-search-not-link re5 nil t)
7051 )
7052 (goto-char (match-beginning 0))
7053 (goto-char pos)
7054 (error "No match")))))
7055 (t
7056 ;; Normal string-search
7057 (goto-char (point-min))
7058 (if (search-forward s nil t)
7059 (goto-char (match-beginning 0))
7060 (error "No match"))))
7061 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7062
7063 (defun org-search-not-link (&rest args)
7064 "Execute `re-search-forward', but only accept matches that are not a link."
7065 (catch 'exit
7066 (let ((pos (point)) p1)
7067 (while (apply 're-search-forward args)
7068 (setq p1 (point))
7069 (if (not (save-match-data
7070 (and (re-search-backward "\\[\\[" nil t)
7071 (looking-at org-bracket-link-regexp)
7072 (<= (match-beginning 0) p1)
7073 (>= (match-end 0) p1))))
7074 (progn (goto-char (match-end 0))
7075 (throw 'exit (point)))
7076 (goto-char (match-end 0)))))))
7077
7078 (defun org-do-occur (regexp &optional cleanup)
7079 "Call the Emacs command `occur'.
7080 If CLEANUP is non-nil, remove the printout of the regular expression
7081 in the *Occur* buffer. This is useful if the regex is long and not useful
7082 to read."
7083 (occur regexp)
7084 (when cleanup
7085 (let ((cwin (selected-window)) win beg end)
7086 (when (setq win (get-buffer-window "*Occur*"))
7087 (select-window win))
7088 (goto-char (point-min))
7089 (when (re-search-forward "match[a-z]+" nil t)
7090 (setq beg (match-end 0))
7091 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7092 (setq end (1- (match-beginning 0)))))
7093 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7094 (goto-char (point-min))
7095 (select-window cwin))))
7096
7097 (defvar org-mark-ring nil
7098 "Mark ring for positions before jumps in Org-mode.")
7099 (defvar org-mark-ring-last-goto nil
7100 "Last position in the mark ring used to go back.")
7101 ;; Fill and close the ring
7102 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7103 (loop for i from 1 to org-mark-ring-length do
7104 (push (make-marker) org-mark-ring))
7105 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7106 org-mark-ring)
7107
7108 (defun org-mark-ring-push (&optional pos buffer)
7109 "Put the current position or POS into the mark ring and rotate it."
7110 (interactive)
7111 (setq pos (or pos (point)))
7112 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7113 (move-marker (car org-mark-ring)
7114 (or pos (point))
7115 (or buffer (current-buffer)))
7116 (message
7117 (substitute-command-keys
7118 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7119
7120 (defun org-mark-ring-goto (&optional n)
7121 "Jump to the previous position in the mark ring.
7122 With prefix arg N, jump back that many stored positions. When
7123 called several times in succession, walk through the entire ring.
7124 Org-mode commands jumping to a different position in the current file,
7125 or to another Org-mode file, automatically push the old position
7126 onto the ring."
7127 (interactive "p")
7128 (let (p m)
7129 (if (eq last-command this-command)
7130 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7131 (setq p org-mark-ring))
7132 (setq org-mark-ring-last-goto p)
7133 (setq m (car p))
7134 (switch-to-buffer (marker-buffer m))
7135 (goto-char m)
7136 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7137
7138 (defun org-camel-to-words (s)
7139 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7140 (let ((case-fold-search nil)
7141 words)
7142 (while (string-match "[a-z][A-Z]" s)
7143 (push (substring s 0 (1+ (match-beginning 0))) words)
7144 (setq s (substring s (1+ (match-beginning 0)))))
7145 (nreverse (cons s words))))
7146
7147 (defun org-remove-angle-brackets (s)
7148 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7149 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7150 s)
7151 (defun org-add-angle-brackets (s)
7152 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7153 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7154 s)
7155
7156 (defun org-follow-bbdb-link (name)
7157 "Follow a BBDB link to NAME."
7158 (require 'bbdb)
7159 (let ((inhibit-redisplay t)
7160 (bbdb-electric-p nil))
7161 (catch 'exit
7162 ;; Exact match on name
7163 (bbdb-name (concat "\\`" name "\\'") nil)
7164 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7165 ;; Exact match on name
7166 (bbdb-company (concat "\\`" name "\\'") nil)
7167 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7168 ;; Partial match on name
7169 (bbdb-name name nil)
7170 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7171 ;; Partial match on company
7172 (bbdb-company name nil)
7173 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7174 ;; General match including network address and notes
7175 (bbdb name nil)
7176 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7177 (delete-window (get-buffer-window "*BBDB*"))
7178 (error "No matching BBDB record")))))
7179
7180 (defun org-follow-gnus-link (&optional group article)
7181 "Follow a Gnus link to GROUP and ARTICLE."
7182 (require 'gnus)
7183 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7184 (if group (gnus-fetch-group group))
7185 (if article
7186 (or (gnus-summary-goto-article article nil 'force)
7187 (if (fboundp 'gnus-summary-insert-cached-articles)
7188 (progn
7189 (gnus-summary-insert-cached-articles)
7190 (gnus-summary-goto-article article nil 'force))
7191 (message "Message could not be found.")))))
7192
7193 (defun org-follow-vm-link (&optional folder article readonly)
7194 "Follow a VM link to FOLDER and ARTICLE."
7195 (require 'vm)
7196 (setq article (org-add-angle-brackets article))
7197 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7198 ;; ange-ftp or efs or tramp access
7199 (let ((user (or (match-string 1 folder) (user-login-name)))
7200 (host (match-string 2 folder))
7201 (file (match-string 3 folder)))
7202 (cond
7203 ((featurep 'tramp)
7204 ;; use tramp to access the file
7205 (if org-xemacs-p
7206 (setq folder (format "[%s@%s]%s" user host file))
7207 (setq folder (format "/%s@%s:%s" user host file))))
7208 (t
7209 ;; use ange-ftp or efs
7210 (require (if org-xemacs-p 'efs 'ange-ftp))
7211 (setq folder (format "/%s@%s:%s" user host file))))))
7212 (when folder
7213 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7214 (sit-for 0.1)
7215 (when article
7216 (vm-select-folder-buffer)
7217 (widen)
7218 (let ((case-fold-search t))
7219 (goto-char (point-min))
7220 (if (not (re-search-forward
7221 (concat "^" "message-id: *" (regexp-quote article))))
7222 (error "Could not find the specified message in this folder"))
7223 (vm-isearch-update)
7224 (vm-isearch-narrow)
7225 (vm-beginning-of-message)
7226 (vm-summarize)))))
7227
7228 (defun org-follow-wl-link (folder article)
7229 "Follow a Wanderlust link to FOLDER and ARTICLE."
7230 (setq article (org-add-angle-brackets article))
7231 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7232 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7233 (wl-summary-redisplay))
7234
7235 (defun org-follow-rmail-link (folder article)
7236 "Follow an RMAIL link to FOLDER and ARTICLE."
7237 (setq article (org-add-angle-brackets article))
7238 (let (message-number)
7239 (save-excursion
7240 (save-window-excursion
7241 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7242 (setq message-number
7243 (save-restriction
7244 (widen)
7245 (goto-char (point-max))
7246 (if (re-search-backward
7247 (concat "^Message-ID:\\s-+" (regexp-quote
7248 (or article "")))
7249 nil t)
7250 (rmail-what-message))))))
7251 (if message-number
7252 (progn
7253 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7254 (rmail-show-message message-number)
7255 message-number)
7256 (error "Message not found"))))
7257
7258 ;; mh-e integration based on planner-mode
7259 (defun org-mhe-get-message-real-folder ()
7260 "Return the name of the current message real folder, so if you use
7261 sequences, it will now work."
7262 (save-excursion
7263 (let* ((folder
7264 (if (equal major-mode 'mh-folder-mode)
7265 mh-current-folder
7266 ;; Refer to the show buffer
7267 mh-show-folder-buffer))
7268 (end-index
7269 (if (boundp 'mh-index-folder)
7270 (min (length mh-index-folder) (length folder))))
7271 )
7272 ;; a simple test on mh-index-data does not work, because
7273 ;; mh-index-data is always nil in a show buffer.
7274 (if (and (boundp 'mh-index-folder)
7275 (string= mh-index-folder (substring folder 0 end-index)))
7276 (if (equal major-mode 'mh-show-mode)
7277 (save-window-excursion
7278 (when (buffer-live-p (get-buffer folder))
7279 (progn
7280 (pop-to-buffer folder)
7281 (org-mhe-get-message-folder-from-index)
7282 )
7283 ))
7284 (org-mhe-get-message-folder-from-index)
7285 )
7286 folder
7287 )
7288 )))
7289
7290 (defun org-mhe-get-message-folder-from-index ()
7291 "Returns the name of the message folder in a index folder buffer."
7292 (save-excursion
7293 (mh-index-previous-folder)
7294 (re-search-forward "^\\(+.*\\)$" nil t)
7295 (message (match-string 1))))
7296
7297 (defun org-mhe-get-message-folder ()
7298 "Return the name of the current message folder. Be careful if you
7299 use sequences."
7300 (save-excursion
7301 (if (equal major-mode 'mh-folder-mode)
7302 mh-current-folder
7303 ;; Refer to the show buffer
7304 mh-show-folder-buffer)))
7305
7306 (defun org-mhe-get-message-num ()
7307 "Return the number of the current message. Be careful if you
7308 use sequences."
7309 (save-excursion
7310 (if (equal major-mode 'mh-folder-mode)
7311 (mh-get-msg-num nil)
7312 ;; Refer to the show buffer
7313 (mh-show-buffer-message-number))))
7314
7315 (defun org-mhe-get-header (header)
7316 "Return a header of the message in folder mode. This will create a
7317 show buffer for the corresponding message. If you have a more clever
7318 idea..."
7319 (let* ((folder (org-mhe-get-message-folder))
7320 (num (org-mhe-get-message-num))
7321 (buffer (get-buffer-create (concat "show-" folder)))
7322 (header-field))
7323 (with-current-buffer buffer
7324 (mh-display-msg num folder)
7325 (if (equal major-mode 'mh-folder-mode)
7326 (mh-header-display)
7327 (mh-show-header-display))
7328 (set-buffer buffer)
7329 (setq header-field (mh-get-header-field header))
7330 (if (equal major-mode 'mh-folder-mode)
7331 (mh-show)
7332 (mh-show-show))
7333 header-field)))
7334
7335 (defun org-follow-mhe-link (folder article)
7336 "Follow an MHE link to FOLDER and ARTICLE.
7337 If ARTICLE is nil FOLDER is shown. If the configuration variable
7338 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
7339 ARTICLE is searched in all folders. Indexed searches (swish++,
7340 namazu, and others supported by MH-E) will always search in all
7341 folders."
7342 (require 'mh-e)
7343 (require 'mh-search)
7344 (require 'mh-utils)
7345 (mh-find-path)
7346 (if (not article)
7347 (mh-visit-folder (mh-normalize-folder-name folder))
7348 (setq article (org-add-angle-brackets article))
7349 (mh-search-choose)
7350 (if (equal mh-searcher 'pick)
7351 (progn
7352 (mh-search folder (list "--message-id" article))
7353 (when (and org-mhe-search-all-folders
7354 (not (org-mhe-get-message-real-folder)))
7355 (kill-this-buffer)
7356 (mh-search "+" (list "--message-id" article))))
7357 (mh-search "+" article))
7358 (if (org-mhe-get-message-real-folder)
7359 (mh-show-msg 1)
7360 (kill-this-buffer)
7361 (error "Message not found"))))
7362
7363 (defun org-open-file (path &optional in-emacs line search)
7364 "Open the file at PATH.
7365 First, this expands any special file name abbreviations. Then the
7366 configuration variable `org-file-apps' is checked if it contains an
7367 entry for this file type, and if yes, the corresponding command is launched.
7368 If no application is found, Emacs simply visits the file.
7369 With optional argument IN-EMACS, Emacs will visit the file.
7370 Optional LINE specifies a line to go to, optional SEARCH a string to
7371 search for. If LINE or SEARCH is given, the file will always be
7372 opened in Emacs.
7373 If the file does not exist, an error is thrown."
7374 (setq in-emacs (or in-emacs line search))
7375 (let* ((file (if (equal path "")
7376 buffer-file-name
7377 (convert-standard-filename (org-expand-file-name path))))
7378 (dirp (file-directory-p file))
7379 (dfile (downcase file))
7380 (old-buffer (current-buffer))
7381 (old-pos (point))
7382 (old-mode major-mode)
7383 ext cmd apps)
7384 (if (and (not (file-exists-p file))
7385 (not org-open-non-existing-files))
7386 (error "No such file: %s" file))
7387 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7388 (setq ext (match-string 1 dfile))
7389 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7390 (setq ext (match-string 1 dfile))))
7391 (setq apps (append org-file-apps (org-default-apps)))
7392 (if in-emacs
7393 (setq cmd 'emacs)
7394 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7395 (cdr (assoc ext apps))
7396 (cdr (assoc t apps)))))
7397 (when (eq cmd 'mailcap)
7398 (require 'mailcap)
7399 (mailcap-parse-mailcaps)
7400 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7401 (command (mailcap-mime-info mime-type)))
7402 (if (stringp command)
7403 (setq cmd command)
7404 (setq cmd 'emacs))))
7405 (cond
7406 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7407 (setq cmd (format cmd (concat "\"" file "\"")))
7408 (save-window-excursion
7409 (shell-command (concat cmd " &"))))
7410 ((or (stringp cmd)
7411 (eq cmd 'emacs))
7412 (unless (equal (file-truename file) (file-truename buffer-file-name))
7413 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7414 (if line (goto-line line)
7415 (if search (org-link-search search))))
7416 ((consp cmd)
7417 (eval cmd))
7418 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7419 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7420 (or (not (equal old-buffer (current-buffer)))
7421 (not (equal old-pos (point))))
7422 (org-mark-ring-push old-pos old-buffer))))
7423
7424 (defun org-default-apps ()
7425 "Return the default applications for this operating system."
7426 (cond
7427 ((eq system-type 'darwin)
7428 org-file-apps-defaults-macosx)
7429 ((eq system-type 'windows-nt)
7430 org-file-apps-defaults-windowsnt)
7431 (t org-file-apps-defaults-gnu)))
7432
7433 (defun org-expand-file-name (path)
7434 "Replace special path abbreviations and expand the file name."
7435 (expand-file-name path))
7436
7437
7438 (defvar org-insert-link-history nil
7439 "Minibuffer history for links inserted with `org-insert-link'.")
7440
7441 (defvar org-stored-links nil
7442 "Contains the links stored with `org-store-link'.")
7443
7444 ;;;###autoload
7445 (defun org-store-link (arg)
7446 "\\<org-mode-map>Store an org-link to the current location.
7447 This link can later be inserted into an org-buffer with
7448 \\[org-insert-link].
7449 For some link types, a prefix arg is interpreted:
7450 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7451 For file links, arg negates `org-context-in-file-links'."
7452 (interactive "P")
7453 (let (link cpltxt txt (pos (point)))
7454 (cond
7455
7456 ((eq major-mode 'bbdb-mode)
7457 (setq cpltxt (concat
7458 "bbdb:"
7459 (or (bbdb-record-name (bbdb-current-record))
7460 (bbdb-record-company (bbdb-current-record))))
7461 link (org-make-link cpltxt)))
7462
7463 ((eq major-mode 'calendar-mode)
7464 (let ((cd (calendar-cursor-to-date)))
7465 (setq link
7466 (format-time-string
7467 (car org-time-stamp-formats)
7468 (apply 'encode-time
7469 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7470 nil nil nil))))))
7471
7472 ((or (eq major-mode 'vm-summary-mode)
7473 (eq major-mode 'vm-presentation-mode))
7474 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7475 (vm-follow-summary-cursor)
7476 (save-excursion
7477 (vm-select-folder-buffer)
7478 (let* ((message (car vm-message-pointer))
7479 (folder buffer-file-name)
7480 (subject (vm-su-subject message))
7481 (author (vm-su-full-name message))
7482 (message-id (vm-su-message-id message)))
7483 (setq message-id (org-remove-angle-brackets message-id))
7484 (setq folder (abbreviate-file-name folder))
7485 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7486 folder)
7487 (setq folder (replace-match "" t t folder)))
7488 (setq cpltxt (concat author " on: " subject))
7489 (setq link (concat cpltxt "\n "
7490 (org-make-link
7491 "vm:" folder "#" message-id))))))
7492
7493 ((eq major-mode 'wl-summary-mode)
7494 (let* ((msgnum (wl-summary-message-number))
7495 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7496 msgnum 'message-id))
7497 (wl-message-entity (elmo-msgdb-overview-get-entity
7498 msgnum (wl-summary-buffer-msgdb)))
7499 (author (wl-summary-line-from)) ; FIXME: how to get author name?
7500 (subject "???")) ; FIXME: How to get subject of email?
7501 (setq message-id (org-remove-angle-brackets message-id))
7502 (setq cpltxt (concat author " on: " subject))
7503 (setq link (concat cpltxt "\n "
7504 (org-make-link
7505 "wl:" wl-summary-buffer-folder-name
7506 "#" message-id)))))
7507
7508 ((or (equal major-mode 'mh-folder-mode)
7509 (equal major-mode 'mh-show-mode))
7510 (let ((from-header (org-mhe-get-header "From:"))
7511 (to-header (org-mhe-get-header "To:"))
7512 (subject (org-mhe-get-header "Subject:")))
7513 (setq cpltxt (concat from-header " on: " subject))
7514 (setq link (concat cpltxt "\n "
7515 (org-make-link
7516 "mhe:" (org-mhe-get-message-real-folder) "#"
7517 (org-remove-angle-brackets
7518 (org-mhe-get-header "Message-Id:")))))))
7519
7520 ((eq major-mode 'rmail-mode)
7521 (save-excursion
7522 (save-restriction
7523 (rmail-narrow-to-non-pruned-header)
7524 (let ((folder buffer-file-name)
7525 (message-id (mail-fetch-field "message-id"))
7526 (author (mail-fetch-field "from"))
7527 (subject (mail-fetch-field "subject")))
7528 (setq message-id (org-remove-angle-brackets message-id))
7529 (setq cpltxt (concat author " on: " subject))
7530 (setq link (concat cpltxt "\n "
7531 (org-make-link
7532 "rmail:" folder "#" message-id)))))))
7533
7534 ((eq major-mode 'gnus-group-mode)
7535 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7536 (gnus-group-group-name)) ; version
7537 ((fboundp 'gnus-group-name)
7538 (gnus-group-name))
7539 (t "???"))))
7540 (setq cpltxt (concat
7541 (if (org-xor arg org-usenet-links-prefer-google)
7542 "http://groups.google.com/groups?group="
7543 "gnus:")
7544 group)
7545 link (org-make-link cpltxt))))
7546
7547 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7548 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7549 (gnus-summary-beginning-of-article)
7550 (let* ((group (car gnus-article-current))
7551 (article (cdr gnus-article-current))
7552 (header (gnus-summary-article-header article))
7553 (author (mail-header-from header))
7554 (message-id (mail-header-id header))
7555 (date (mail-header-date header))
7556 (subject (gnus-summary-subject-string)))
7557 (setq cpltxt (concat author " on: " subject))
7558 (if (org-xor arg org-usenet-links-prefer-google)
7559 (setq link
7560 (concat
7561 cpltxt "\n "
7562 (format "http://groups.google.com/groups?as_umsgid=%s"
7563 (org-fixup-message-id-for-http message-id))))
7564 (setq link (concat cpltxt "\n"
7565 (org-make-link
7566 "gnus:" group
7567 "#" (number-to-string article)))))))
7568
7569 ((eq major-mode 'w3-mode)
7570 (setq cpltxt (url-view-url t)
7571 link (org-make-link cpltxt)))
7572 ((eq major-mode 'w3m-mode)
7573 (setq cpltxt w3m-current-url
7574 link (org-make-link cpltxt)))
7575
7576 ((eq major-mode 'org-mode)
7577 ;; Just link to current headline
7578 (setq cpltxt (concat "file:"
7579 (abbreviate-file-name buffer-file-name)))
7580 ;; Add a context search string
7581 (when (org-xor org-context-in-file-links arg)
7582 ;; Check if we are on a target
7583 (if (save-excursion
7584 (skip-chars-forward "^>\n\r")
7585 (and (re-search-backward "<<" nil t)
7586 (looking-at "<<\\(.*?\\)>>")
7587 (<= (match-beginning 0) pos)
7588 (>= (match-end 0) pos)))
7589 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7590 (setq txt (cond
7591 ((org-on-heading-p) nil)
7592 ((org-region-active-p)
7593 (buffer-substring (region-beginning) (region-end)))
7594 (t (buffer-substring (point-at-bol) (point-at-eol)))))
7595 (setq cpltxt
7596 (concat cpltxt "::"
7597 (if org-file-link-context-use-camel-case
7598 (org-make-org-heading-camel txt)
7599 (org-make-org-heading-search-string txt))))))
7600 (if (string-match "::\\'" cpltxt)
7601 (setq cpltxt (substring cpltxt 0 -2)))
7602 (setq link (org-make-link cpltxt)))
7603
7604 (buffer-file-name
7605 ;; Just link to this file here.
7606 (setq cpltxt (concat "file:"
7607 (abbreviate-file-name buffer-file-name)))
7608 ;; Add a context string
7609 (when (org-xor org-context-in-file-links arg)
7610 (setq txt (if (org-region-active-p)
7611 (buffer-substring (region-beginning) (region-end))
7612 (buffer-substring (point-at-bol) (point-at-eol))))
7613 (setq cpltxt
7614 (concat cpltxt "::"
7615 (if org-file-link-context-use-camel-case
7616 (org-make-org-heading-camel txt)
7617 (org-make-org-heading-search-string txt)))))
7618 (setq link (org-make-link cpltxt)))
7619
7620 ((interactive-p)
7621 (error "Cannot link to a buffer which is not visiting a file"))
7622
7623 (t (setq link nil)))
7624
7625 (if (and (interactive-p) link)
7626 (progn
7627 (setq org-stored-links
7628 (cons (cons (or cpltxt link) link) org-stored-links))
7629 (message "Stored: %s" (or cpltxt link)))
7630 link)))
7631
7632 (defun org-make-org-heading-search-string (&optional string heading)
7633 "Make search string for STRING or current headline."
7634 (interactive)
7635 (let ((s (or string (org-get-heading))))
7636 (unless (and string (not heading))
7637 ;; We are using a headline, clean up garbage in there.
7638 (if (string-match org-todo-regexp s)
7639 (setq s (replace-match "" t t s)))
7640 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7641 (setq s (replace-match "" t t s)))
7642 (setq s (org-trim s))
7643 (if (string-match (concat "^\\(" org-quote-string "\\|"
7644 org-comment-string "\\)") s)
7645 (setq s (replace-match "" t t s)))
7646 (while (string-match org-ts-regexp s)
7647 (setq s (replace-match "" t t s))))
7648 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7649 (setq s (replace-match " " t t s)))
7650 (or string (setq s (concat "*" s))) ; Add * for headlines
7651 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7652
7653 (defun org-make-org-heading-camel (&optional string heading)
7654 "Make a CamelCase string for STRING or the current headline."
7655 (interactive)
7656 (let ((s (or string (org-get-heading))))
7657 (unless (and string (not heading))
7658 ;; We are using a headline, clean up garbage in there.
7659 (if (string-match org-todo-regexp s)
7660 (setq s (replace-match "" t t s)))
7661 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7662 (setq s (replace-match "" t t s)))
7663 (setq s (org-trim s))
7664 (if (string-match (concat "^\\(" org-quote-string "\\|"
7665 org-comment-string "\\)") s)
7666 (setq s (replace-match "" t t s)))
7667 (while (string-match org-ts-regexp s)
7668 (setq s (replace-match "" t t s))))
7669 (while (string-match "[^a-zA-Z_ \t]+" s)
7670 (setq s (replace-match " " t t s)))
7671 (or string (setq s (concat "*" s))) ; Add * for headlines
7672 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7673
7674 (defun org-make-link (&rest strings)
7675 "Concatenate STRINGS, format resulting string with `org-link-format'."
7676 (format org-link-format (apply 'concat strings)))
7677
7678 (defun org-make-link2 (link &optional description)
7679 "Make a link with brackets."
7680 (concat "[[" link "]"
7681 (if description (concat "[" description "]") "")
7682 "]"))
7683
7684 (defun org-xor (a b)
7685 "Exclusive or."
7686 (if a (not b) b))
7687
7688 (defun org-get-header (header)
7689 "Find a header field in the current buffer."
7690 (save-excursion
7691 (goto-char (point-min))
7692 (let ((case-fold-search t) s)
7693 (cond
7694 ((eq header 'from)
7695 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7696 (setq s (match-string 1)))
7697 (while (string-match "\"" s)
7698 (setq s (replace-match "" t t s)))
7699 (if (string-match "[<(].*" s)
7700 (setq s (replace-match "" t t s))))
7701 ((eq header 'message-id)
7702 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7703 (setq s (match-string 1))))
7704 ((eq header 'subject)
7705 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7706 (setq s (match-string 1)))))
7707 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7708 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7709 s)))
7710
7711
7712 (defun org-fixup-message-id-for-http (s)
7713 "Replace special characters in a message id, so it can be used in an http query."
7714 (while (string-match "<" s)
7715 (setq s (replace-match "%3C" t t s)))
7716 (while (string-match ">" s)
7717 (setq s (replace-match "%3E" t t s)))
7718 (while (string-match "@" s)
7719 (setq s (replace-match "%40" t t s)))
7720 s)
7721
7722 (defun org-insert-link (&optional complete-file)
7723 "Insert a link. At the prompt, enter the link.
7724
7725 Completion can be used to select a link previously stored with
7726 `org-store-link'. When the empty string is entered (i.e. if you just
7727 press RET at the prompt), the link defaults to the most recently
7728 stored link. As SPC triggers completion in the minibuffer, you need to
7729 use M-SPC or C-q SPC to force the insertion of a space character.
7730
7731 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7732 selected using completion. The path to the file will be relative to
7733 the current directory if the file is in the current directory or a
7734 subdirectory. Otherwise, the link will be the absolute path as
7735 completed in the minibuffer (i.e. normally ~/path/to/file).
7736
7737 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7738 is in the current directory or below."
7739 (interactive "P")
7740 (let ((link (if complete-file
7741 (read-file-name "File: ")
7742 (completing-read
7743 "Link: " org-stored-links nil nil nil
7744 org-insert-link-history
7745 (or (car (car org-stored-links))))))
7746 linktxt matched)
7747 (if (or (not link) (equal link ""))
7748 (error "No links available"))
7749 (if complete-file
7750 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7751 (cond
7752 ((equal complete-file '(16))
7753 (insert
7754 (org-make-link
7755 "file:" (abbreviate-file-name (expand-file-name link)))))
7756 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7757 (expand-file-name link))
7758 (insert
7759 (org-make-link
7760 "file:" (match-string 1 (expand-file-name link)))))
7761 (t (insert (org-make-link "file:" link)))))
7762 (setq linktxt (cdr (assoc link org-stored-links)))
7763 (if (not org-keep-stored-link-after-insertion)
7764 (setq org-stored-links (delq (assoc link org-stored-links)
7765 org-stored-links)))
7766 (if (not linktxt) (setq link (org-make-link link)))
7767 (setq link (or linktxt link))
7768 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7769 (let* ((path (match-string 1 link))
7770 (case-fold-search nil)
7771 (search (match-string 2 link)))
7772 (when (save-match-data
7773 (equal (file-truename buffer-file-name)
7774 (file-truename path)))
7775 ;; We are linking to this same file
7776 (if (and org-file-link-context-use-camel-case
7777 (save-match-data
7778 (string-match (concat "^" org-camel-regexp "$") search)))
7779 (setq link (replace-match search t t link)
7780 matched t)
7781 (setq link (replace-match (concat "[[" search "]]")
7782 t t link)
7783 matched t)))))
7784 (let ((lines (org-split-string link "\n")))
7785 (insert (car lines))
7786 (setq matched (or matched (string-match org-link-regexp (car lines))))
7787 (setq lines (cdr lines))
7788 (while lines
7789 (insert "\n")
7790 (if (save-excursion
7791 (beginning-of-line 0)
7792 (looking-at "[ \t]+\\S-"))
7793 (indent-relative))
7794 (setq matched (or matched
7795 (string-match org-link-regexp (car lines))))
7796 (insert (car lines))
7797 (setq lines (cdr lines))))
7798 (unless matched
7799 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7800
7801 ;;; Hooks for remember.el
7802 ;;;###autoload
7803 (defun org-remember-annotation ()
7804 "Return a link to the current location as an annotation for remember.el.
7805 If you are using Org-mode files as target for data storage with
7806 remember.el, then the annotations should include a link compatible with the
7807 conventions in Org-mode. This function returns such a link."
7808 (org-store-link nil))
7809
7810 (defconst org-remember-help
7811 "Select a destination location for the note.
7812 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7813 RET at beg-of-buf -> Append to file as level 2 headline
7814 RET on headline -> Store as sublevel entry to current headline
7815 <left>/<right> -> before/after current headline, same headings level")
7816
7817 ;;;###autoload
7818 (defun org-remember-handler ()
7819 "Store stuff from remember.el into an org file.
7820 First prompts for an org file. If the user just presses return, the value
7821 of `org-default-notes-file' is used.
7822 Then the command offers the headings tree of the selected file in order to
7823 file the text at a specific location.
7824 You can either immediately press RET to get the note appended to the
7825 file, or you can use vertical cursor motion and visibility cycling (TAB) to
7826 find a better place. Then press RET or <left> or <right> in insert the note.
7827
7828 Key Cursor position Note gets inserted
7829 -----------------------------------------------------------------------------
7830 RET buffer-start as level 2 heading at end of file
7831 RET on headline as sublevel of the heading at cursor
7832 RET no heading at cursor position, level taken from context.
7833 Or use prefix arg to specify level manually.
7834 <left> on headline as same level, before current heading
7835 <right> on headline as same level, after current heading
7836
7837 So the fastest way to store the note is to press RET RET to append it to
7838 the default file. This way your current train of thought is not
7839 interrupted, in accordance with the principles of remember.el. But with
7840 little extra effort, you can push it directly to the correct location.
7841
7842 Before being stored away, the function ensures that the text has a
7843 headline, i.e. a first line that starts with a \"*\". If not, a headline
7844 is constructed from the current date and some additional data.
7845
7846 If the variable `org-adapt-indentation' is non-nil, the entire text is
7847 also indented so that it starts in the same column as the headline
7848 \(i.e. after the stars).
7849
7850 See also the variable `org-reverse-note-order'."
7851 (catch 'quit
7852 (let* ((txt (buffer-substring (point-min) (point-max)))
7853 (fastp current-prefix-arg)
7854 (file (if fastp org-default-notes-file (org-get-org-file)))
7855 (visiting (find-buffer-visiting file))
7856 (org-startup-with-deadline-check nil)
7857 (org-startup-folded nil)
7858 spos level indent reversed)
7859 ;; Modify text so that it becomes a nice subtree which can be inserted
7860 ;; into an org tree.
7861 (let* ((lines (split-string txt "\n"))
7862 (first (car lines))
7863 (lines (cdr lines)))
7864 (if (string-match "^\\*+" first)
7865 ;; Is already a headline
7866 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7867 -1) ?\ ))
7868 ;; We need to add a headline: Use time and first buffer line
7869 (setq lines (cons first lines)
7870 first (concat "* " (current-time-string)
7871 " (" (remember-buffer-desc) ")")
7872 indent " "))
7873 (if org-adapt-indentation
7874 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7875 (setq txt (concat first "\n"
7876 (mapconcat 'identity lines "\n"))))
7877 ;; Find the file
7878 (if (not visiting)
7879 (find-file-noselect file))
7880 (with-current-buffer (get-file-buffer file)
7881 (setq reversed (org-notes-order-reversed-p))
7882 (save-excursion
7883 (save-restriction
7884 (widen)
7885 ;; Ask the User for a location
7886 (setq spos (if fastp 1 (org-get-location
7887 (current-buffer)
7888 org-remember-help)))
7889 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7890 ; not handle this note
7891 (goto-char spos)
7892 (cond ((bobp)
7893 ;; Put it at the start or end, as level 2
7894 (save-restriction
7895 (widen)
7896 (goto-char (if reversed (point-min) (point-max)))
7897 (if (not (bolp)) (newline))
7898 (org-paste-subtree (or current-prefix-arg 2) txt)))
7899 ((and (org-on-heading-p nil) (not current-prefix-arg))
7900 ;; Put it below this entry, at the beg/end of the subtree
7901 (org-back-to-heading)
7902 (setq level (funcall outline-level))
7903 (if reversed
7904 (outline-end-of-heading)
7905 (outline-end-of-subtree))
7906 (if (not (bolp)) (newline))
7907 (beginning-of-line 1)
7908 (org-paste-subtree (1+ level) txt))
7909 (t
7910 ;; Put it right there, with automatic level determined by
7911 ;; org-paste-subtree or from prefix arg
7912 (org-paste-subtree current-prefix-arg txt)))
7913 (when remember-save-after-remembering
7914 (save-buffer)
7915 (if (not visiting) (kill-buffer (current-buffer)))))))))
7916 t) ;; return t to indicate that we took care of this note.
7917
7918 (defun org-get-org-file ()
7919 "Read a filename, with default directory `org-directory'."
7920 (let ((default (or org-default-notes-file remember-data-file)))
7921 (read-file-name (format "File name [%s]: " default)
7922 (file-name-as-directory org-directory)
7923 default)))
7924
7925 (defun org-notes-order-reversed-p ()
7926 "Check if the current file should receive notes in reversed order."
7927 (cond
7928 ((not org-reverse-note-order) nil)
7929 ((eq t org-reverse-note-order) t)
7930 ((not (listp org-reverse-note-order)) nil)
7931 (t (catch 'exit
7932 (let ((all org-reverse-note-order)
7933 entry)
7934 (while (setq entry (pop all))
7935 (if (string-match (car entry) buffer-file-name)
7936 (throw 'exit (cdr entry))))
7937 nil)))))
7938
7939 ;;; Tables
7940
7941 ;; Watch out: Here we are talking about two different kind of tables.
7942 ;; Most of the code is for the tables created with the Org-mode table editor.
7943 ;; Sometimes, we talk about tables created and edited with the table.el
7944 ;; Emacs package. We call the former org-type tables, and the latter
7945 ;; table.el-type tables.
7946
7947
7948 (defun org-before-change-function (beg end)
7949 "Every change indicates that a table might need an update."
7950 (setq org-table-may-need-update t))
7951
7952 (defconst org-table-line-regexp "^[ \t]*|"
7953 "Detects an org-type table line.")
7954 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7955 "Detects an org-type table line.")
7956 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7957 "Detects a table line marked for automatic recalculation.")
7958 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7959 "Detects a table line marked for automatic recalculation.")
7960 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7961 "Detects a table line marked for automatic recalculation.")
7962 (defconst org-table-hline-regexp "^[ \t]*|-"
7963 "Detects an org-type table hline.")
7964 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7965 "Detects a table-type table hline.")
7966 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7967 "Detects an org-type or table-type table.")
7968 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7969 "Searching from within a table (any type) this finds the first line
7970 outside the table.")
7971 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7972 "Searching from within a table (any type) this finds the first line
7973 outside the table.")
7974
7975 (defun org-table-create-with-table.el ()
7976 "Use the table.el package to insert a new table.
7977 If there is already a table at point, convert between Org-mode tables
7978 and table.el tables."
7979 (interactive)
7980 (require 'table)
7981 (cond
7982 ((org-at-table.el-p)
7983 (if (y-or-n-p "Convert table to Org-mode table? ")
7984 (org-table-convert)))
7985 ((org-at-table-p)
7986 (if (y-or-n-p "Convert table to table.el table? ")
7987 (org-table-convert)))
7988 (t (call-interactively 'table-insert))))
7989
7990 (defun org-table-create (&optional size)
7991 "Query for a size and insert a table skeleton.
7992 SIZE is a string Columns x Rows like for example \"3x2\"."
7993 (interactive "P")
7994 (unless size
7995 (setq size (read-string
7996 (concat "Table size Columns x Rows [e.g. "
7997 org-table-default-size "]: ")
7998 "" nil org-table-default-size)))
7999
8000 (let* ((pos (point))
8001 (indent (make-string (current-column) ?\ ))
8002 (split (org-split-string size " *x *"))
8003 (rows (string-to-number (nth 1 split)))
8004 (columns (string-to-number (car split)))
8005 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8006 "\n")))
8007 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8008 (point-at-bol) (point)))
8009 (beginning-of-line 1)
8010 (newline))
8011 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8012 (dotimes (i rows) (insert line))
8013 (goto-char pos)
8014 (if (> rows 1)
8015 ;; Insert a hline after the first row.
8016 (progn
8017 (end-of-line 1)
8018 (insert "\n|-")
8019 (goto-char pos)))
8020 (org-table-align)))
8021
8022 (defun org-table-convert-region (beg0 end0 nspace)
8023 "Convert region to a table.
8024 The region goes from BEG0 to END0, but these borders will be moved
8025 slightly, to make sure a beginning of line in the first line is included.
8026 When NSPACE is non-nil, it indicates the minimum number of spaces that
8027 separate columns (default: just one space)."
8028 (let* ((beg (min beg0 end0))
8029 (end (max beg0 end0))
8030 (tabsep t)
8031 re)
8032 (goto-char beg)
8033 (beginning-of-line 1)
8034 (setq beg (move-marker (make-marker) (point)))
8035 (goto-char end)
8036 (if (bolp) (backward-char 1) (end-of-line 1))
8037 (setq end (move-marker (make-marker) (point)))
8038 ;; Lets see if this is tab-separated material. If every nonempty line
8039 ;; contains a tab, we will assume that it is tab-separated material
8040 (if nspace
8041 (setq tabsep nil)
8042 (goto-char beg)
8043 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
8044 (if nspace (setq tabsep nil))
8045 (if tabsep
8046 (setq re "^\\|\t")
8047 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
8048 (max 1 (prefix-numeric-value nspace)))))
8049 (goto-char beg)
8050 (while (re-search-forward re end t)
8051 (replace-match "|" t t))
8052 (goto-char beg)
8053 (insert " ")
8054 (org-table-align)))
8055
8056 (defun org-table-import (file arg)
8057 "Import FILE as a table.
8058 The file is assumed to be tab-separated. Such files can be produced by most
8059 spreadsheet and database applications. If no tabs (at least one per line)
8060 are found, lines will be split on whitespace into fields."
8061 (interactive "f\nP")
8062 (or (bolp) (newline))
8063 (let ((beg (point))
8064 (pm (point-max)))
8065 (insert-file-contents file)
8066 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8067
8068 (defun org-table-export ()
8069 "Export table as a tab-separated file.
8070 Such a file can be imported into a spreadsheet program like Excel."
8071 (interactive)
8072 (let* ((beg (org-table-begin))
8073 (end (org-table-end))
8074 (table (buffer-substring beg end))
8075 (file (read-file-name "Export table to: "))
8076 buf)
8077 (unless (or (not (file-exists-p file))
8078 (y-or-n-p (format "Overwrite file %s? " file)))
8079 (error "Abort"))
8080 (with-current-buffer (find-file-noselect file)
8081 (setq buf (current-buffer))
8082 (erase-buffer)
8083 (fundamental-mode)
8084 (insert table)
8085 (goto-char (point-min))
8086 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8087 (replace-match "" t t)
8088 (end-of-line 1))
8089 (goto-char (point-min))
8090 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8091 (replace-match "" t t)
8092 (goto-char (min (1+ (point)) (point-max))))
8093 (goto-char (point-min))
8094 (while (re-search-forward "^-[-+]*$" nil t)
8095 (replace-match "")
8096 (if (looking-at "\n")
8097 (delete-char 1)))
8098 (goto-char (point-min))
8099 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8100 (replace-match "\t" t t))
8101 (save-buffer))
8102 (kill-buffer buf)))
8103
8104 (defvar org-table-aligned-begin-marker (make-marker)
8105 "Marker at the beginning of the table last aligned.
8106 Used to check if cursor still is in that table, to minimize realignment.")
8107 (defvar org-table-aligned-end-marker (make-marker)
8108 "Marker at the end of the table last aligned.
8109 Used to check if cursor still is in that table, to minimize realignment.")
8110 (defvar org-table-last-alignment nil
8111 "List of flags for flushright alignment, from the last re-alignment.
8112 This is being used to correctly align a single field after TAB or RET.")
8113 ;; FIXME: The following is currently not used.
8114 (defvar org-table-last-column-widths nil
8115 "List of max width of fields in each column.
8116 This is being used to correctly align a single field after TAB or RET.")
8117
8118 (defvar org-last-recalc-line nil)
8119
8120 (defun org-table-align ()
8121 "Align the table at point by aligning all vertical bars."
8122 (interactive)
8123 ;; (message "align") (sit-for 2)
8124 (let* (
8125 ;; Limits of table
8126 (beg (org-table-begin))
8127 (end (org-table-end))
8128 ;; Current cursor position
8129 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8130 (colpos (org-table-current-column))
8131 (winstart (window-start))
8132 text lines (new "") lengths l typenums ty fields maxfields i
8133 column
8134 (indent "") cnt frac
8135 rfmt hfmt
8136 (spaces (if (org-in-invisibility-spec-p '(org-table))
8137 org-table-spaces-around-invisible-separators
8138 org-table-spaces-around-separators))
8139 (sp1 (car spaces))
8140 (sp2 (cdr spaces))
8141 (rfmt1 (concat
8142 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8143 (hfmt1 (concat
8144 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8145 emptystrings)
8146 (untabify beg end)
8147 ;; (message "Aligning table...")
8148 ;; Get the rows
8149 (setq lines (org-split-string
8150 (buffer-substring-no-properties beg end) "\n"))
8151 ;; Store the indentation of the first line
8152 (if (string-match "^ *" (car lines))
8153 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8154 ;; Mark the hlines
8155 (setq lines (mapcar (lambda (l)
8156 (if (string-match "^ *|-" l)
8157 nil
8158 (if (string-match "[ \t]+$" l)
8159 (substring l 0 (match-beginning 0))
8160 l)))
8161 lines))
8162 ;; Get the data fields
8163 (setq fields (mapcar
8164 (lambda (l)
8165 (org-split-string l " *| *"))
8166 (delq nil (copy-sequence lines))))
8167 ;; How many fields in the longest line?
8168 (condition-case nil
8169 (setq maxfields (apply 'max (mapcar 'length fields)))
8170 (error
8171 (kill-region beg end)
8172 (org-table-create org-table-default-size)
8173 (error "Empty table - created default table")))
8174 ;; A list of empty string to fill any short rows on output
8175 (setq emptystrings (make-list maxfields ""))
8176 ;; Get the maximum length of a field and the most common datatype
8177 ;; for each column
8178 (setq i -1)
8179 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8180 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8181 ;; maximum length
8182 (push (apply 'max 1 (mapcar 'string-width column)) lengths)
8183 ;; compute the fraction stepwise, ignoring empty fields
8184 (setq cnt 0 frac 0.0)
8185 (mapcar
8186 (lambda (x)
8187 (if (equal x "")
8188 nil
8189 (setq frac ( / (+ (* frac cnt)
8190 (if (string-match org-table-number-regexp x) 1 0))
8191 (setq cnt (1+ cnt))))))
8192 column)
8193 (push (>= frac org-table-number-fraction) typenums))
8194 (setq lengths (nreverse lengths)
8195 typenums (nreverse typenums))
8196 (setq org-table-last-alignment typenums
8197 org-table-last-column-widths lengths)
8198 ;; Compute the formats needed for output of the table
8199 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8200 (while (setq l (pop lengths))
8201 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8202 (setq rfmt (concat rfmt (format rfmt1 ty l))
8203 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8204 (setq rfmt (concat rfmt "\n")
8205 hfmt (concat (substring hfmt 0 -1) "|\n"))
8206 ;; Produce the new table
8207 ;;(while lines
8208 ;; (setq l (pop lines))
8209 ;; (if l
8210 ;; (setq new (concat new (apply 'format rfmt
8211 ;; (append (pop fields) emptystrings))))
8212 ;; (setq new (concat new hfmt))))
8213 (setq new (mapconcat
8214 (lambda (l)
8215 (if l (apply 'format rfmt
8216 (append (pop fields) emptystrings))
8217 hfmt))
8218 lines ""))
8219 ;; Replace the old one
8220 (delete-region beg end)
8221 (move-marker end nil)
8222 (move-marker org-table-aligned-begin-marker (point))
8223 (insert new)
8224 (move-marker org-table-aligned-end-marker (point))
8225 ;; Try to move to the old location (approximately)
8226 (goto-line linepos)
8227 (set-window-start (selected-window) winstart 'noforce)
8228 (org-table-goto-column colpos)
8229 (setq org-table-may-need-update nil)
8230 (if (org-in-invisibility-spec-p '(org-table))
8231 (org-table-add-invisible-to-vertical-lines))
8232 ))
8233
8234 (defun org-table-begin (&optional table-type)
8235 "Find the beginning of the table and return its position.
8236 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8237 (save-excursion
8238 (if (not (re-search-backward
8239 (if table-type org-table-any-border-regexp
8240 org-table-border-regexp)
8241 nil t))
8242 (error "Can't find beginning of table")
8243 (goto-char (match-beginning 0))
8244 (beginning-of-line 2)
8245 (point))))
8246
8247 (defun org-table-end (&optional table-type)
8248 "Find the end of the table and return its position.
8249 With argument TABLE-TYPE, go to the end of a table.el-type table."
8250 (save-excursion
8251 (if (not (re-search-forward
8252 (if table-type org-table-any-border-regexp
8253 org-table-border-regexp)
8254 nil t))
8255 (goto-char (point-max))
8256 (goto-char (match-beginning 0)))
8257 (point-marker)))
8258
8259 (defun org-table-justify-field-maybe (&optional new)
8260 "Justify the current field, text to left, number to right.
8261 Optional argument NEW may specify text to replace the current field content."
8262 (cond
8263 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8264 ((org-at-table-hline-p)
8265 ;; FIXME: I used to enforce realign here, but I think this is not needed.
8266 ;; (setq org-table-may-need-update t)
8267 )
8268 ((and (not new)
8269 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8270 (current-buffer)))
8271 (< (point) org-table-aligned-begin-marker)
8272 (>= (point) org-table-aligned-end-marker)))
8273 ;; This is not the same table, force a full re-align
8274 (setq org-table-may-need-update t))
8275 (t ;; realign the current field, based on previous full realign
8276 (let* ((pos (point)) s
8277 (col (org-table-current-column))
8278 (num (nth (1- col) org-table-last-alignment))
8279 l f n o e)
8280 (when (> col 0)
8281 (skip-chars-backward "^|\n")
8282 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8283 (progn
8284 (setq s (match-string 1)
8285 o (match-string 0)
8286 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8287 e (not (= (match-beginning 2) (match-end 2))))
8288 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8289 l (if e "|" (setq org-table-may-need-update t) ""))
8290 n (format f s t t))
8291 (if new
8292 (if (<= (length new) l)
8293 (setq n (format f new t t)) ;; FIXME: why t t?????
8294 (setq n (concat new "|") org-table-may-need-update t)))
8295 (or (equal n o)
8296 (let (org-table-may-need-update)
8297 (replace-match n))))
8298 (setq org-table-may-need-update t))
8299 (goto-char pos))))))
8300
8301 (defun org-table-next-field ()
8302 "Go to the next field in the current table, creating new lines as needed.
8303 Before doing so, re-align the table if necessary."
8304 (interactive)
8305 (org-table-maybe-eval-formula)
8306 (org-table-maybe-recalculate-line)
8307 (if (and org-table-automatic-realign
8308 org-table-may-need-update)
8309 (org-table-align))
8310 (let ((end (org-table-end)))
8311 (if (org-at-table-hline-p)
8312 (end-of-line 1))
8313 (condition-case nil
8314 (progn
8315 (re-search-forward "|" end)
8316 (if (looking-at "[ \t]*$")
8317 (re-search-forward "|" end))
8318 (if (and (looking-at "-")
8319 org-table-tab-jumps-over-hlines
8320 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8321 (goto-char (match-beginning 1)))
8322 (if (looking-at "-")
8323 (progn
8324 (beginning-of-line 0)
8325 (org-table-insert-row 'below))
8326 (if (looking-at " ") (forward-char 1))))
8327 (error
8328 (org-table-insert-row 'below)))))
8329
8330 (defun org-table-previous-field ()
8331 "Go to the previous field in the table.
8332 Before doing so, re-align the table if necessary."
8333 (interactive)
8334 (org-table-justify-field-maybe)
8335 (org-table-maybe-recalculate-line)
8336 (if (and org-table-automatic-realign
8337 org-table-may-need-update)
8338 (org-table-align))
8339 (if (org-at-table-hline-p)
8340 (end-of-line 1))
8341 (re-search-backward "|" (org-table-begin))
8342 (re-search-backward "|" (org-table-begin))
8343 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8344 (re-search-backward "|" (org-table-begin)))
8345 (if (looking-at "| ?")
8346 (goto-char (match-end 0))))
8347
8348 (defun org-table-next-row ()
8349 "Go to the next row (same column) in the current table.
8350 Before doing so, re-align the table if necessary."
8351 (interactive)
8352 (org-table-maybe-eval-formula)
8353 (org-table-maybe-recalculate-line)
8354 (if (or (looking-at "[ \t]*$")
8355 (save-excursion (skip-chars-backward " \t") (bolp)))
8356 (newline)
8357 (if (and org-table-automatic-realign
8358 org-table-may-need-update)
8359 (org-table-align))
8360 (let ((col (org-table-current-column)))
8361 (beginning-of-line 2)
8362 (if (or (not (org-at-table-p))
8363 (org-at-table-hline-p))
8364 (progn
8365 (beginning-of-line 0)
8366 (org-table-insert-row 'below)))
8367 (org-table-goto-column col)
8368 (skip-chars-backward "^|\n\r")
8369 (if (looking-at " ") (forward-char 1)))))
8370
8371 (defun org-table-copy-down (n)
8372 "Copy a field down in the current column.
8373 If the field at the cursor is empty, copy into it the content of the nearest
8374 non-empty field above. With argument N, use the Nth non-empty field.
8375 If the current field is not empty, it is copied down to the next row, and
8376 the cursor is moved with it. Therefore, repeating this command causes the
8377 column to be filled row-by-row.
8378 If the variable `org-table-copy-increment' is non-nil and the field is an
8379 integer, it will be incremented while copying."
8380 (interactive "p")
8381 (let* ((colpos (org-table-current-column))
8382 (field (org-table-get-field))
8383 (non-empty (string-match "[^ \t]" field))
8384 (beg (org-table-begin))
8385 txt)
8386 (org-table-check-inside-data-field)
8387 (if non-empty
8388 (progn
8389 (setq txt (org-trim field))
8390 (org-table-next-row)
8391 (org-table-blank-field))
8392 (save-excursion
8393 (setq txt
8394 (catch 'exit
8395 (while (progn (beginning-of-line 1)
8396 (re-search-backward org-table-dataline-regexp
8397 beg t))
8398 (org-table-goto-column colpos t)
8399 (if (and (looking-at
8400 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8401 (= (setq n (1- n)) 0))
8402 (throw 'exit (match-string 1))))))))
8403 (if txt
8404 (progn
8405 (if (and org-table-copy-increment
8406 (string-match "^[0-9]+$" txt))
8407 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8408 (insert txt)
8409 (org-table-maybe-recalculate-line)
8410 (org-table-align))
8411 (error "No non-empty field found"))))
8412
8413 (defun org-table-check-inside-data-field ()
8414 "Is point inside a table data field?
8415 I.e. not on a hline or before the first or after the last column?
8416 This actually throws an error, so it aborts the current command."
8417 (if (or (not (org-at-table-p))
8418 (= (org-table-current-column) 0)
8419 (org-at-table-hline-p)
8420 (looking-at "[ \t]*$"))
8421 (error "Not in table data field")))
8422
8423 (defvar org-table-clip nil
8424 "Clipboard for table regions.")
8425
8426 (defun org-table-blank-field ()
8427 "Blank the current table field or active region."
8428 (interactive)
8429 (org-table-check-inside-data-field)
8430 (if (and (interactive-p) (org-region-active-p))
8431 (let (org-table-clip)
8432 (org-table-cut-region (region-beginning) (region-end)))
8433 (skip-chars-backward "^|")
8434 (backward-char 1)
8435 (if (looking-at "|[^|\n]+")
8436 (let* ((pos (match-beginning 0))
8437 (match (match-string 0))
8438 (len (string-width match)))
8439 (replace-match (concat "|" (make-string (1- len) ?\ )))
8440 (goto-char (+ 2 pos))
8441 (substring match 1)))))
8442
8443 (defun org-table-get-field (&optional n replace)
8444 "Return the value of the field in column N of current row.
8445 N defaults to current field.
8446 If REPLACE is a string, replace field with this value. The return value
8447 is always the old value."
8448 (and n (org-table-goto-column n))
8449 (skip-chars-backward "^|\n")
8450 (backward-char 1)
8451 (if (looking-at "|[^|\r\n]*")
8452 (let* ((pos (match-beginning 0))
8453 (val (buffer-substring (1+ pos) (match-end 0))))
8454 (if replace
8455 (replace-match (concat "|" replace)))
8456 (goto-char (min (point-at-eol) (+ 2 pos)))
8457 val)
8458 (forward-char 1) ""))
8459
8460 (defun org-table-current-column ()
8461 "Find out which column we are in.
8462 When called interactively, column is also displayed in echo area."
8463 (interactive)
8464 (if (interactive-p) (org-table-check-inside-data-field))
8465 (save-excursion
8466 (let ((cnt 0) (pos (point)))
8467 (beginning-of-line 1)
8468 (while (search-forward "|" pos t)
8469 (setq cnt (1+ cnt)))
8470 (if (interactive-p) (message "This is table column %d" cnt))
8471 cnt)))
8472
8473 (defun org-table-goto-column (n &optional on-delim force)
8474 "Move the cursor to the Nth column in the current table line.
8475 With optional argument ON-DELIM, stop with point before the left delimiter
8476 of the field.
8477 If there are less than N fields, just go to after the last delimiter.
8478 However, when FORCE is non-nil, create new columns if necessary."
8479 (interactive "p")
8480 (let ((pos (point-at-eol)))
8481 (beginning-of-line 1)
8482 (when (> n 0)
8483 (while (and (> (setq n (1- n)) -1)
8484 (or (search-forward "|" pos t)
8485 (and force
8486 (progn (end-of-line 1)
8487 (skip-chars-backward "^|")
8488 (insert " | "))))))
8489 ; (backward-char 2) t)))))
8490 (when (and force (not (looking-at ".*|")))
8491 (save-excursion (end-of-line 1) (insert " | ")))
8492 (if on-delim
8493 (backward-char 1)
8494 (if (looking-at " ") (forward-char 1))))))
8495
8496 (defun org-at-table-p (&optional table-type)
8497 "Return t if the cursor is inside an org-type table.
8498 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8499 (if org-enable-table-editor
8500 (save-excursion
8501 (beginning-of-line 1)
8502 (looking-at (if table-type org-table-any-line-regexp
8503 org-table-line-regexp)))
8504 nil))
8505
8506 (defun org-at-table.el-p ()
8507 "Return t if and only if we are at a table.el table."
8508 (and (org-at-table-p 'any)
8509 (save-excursion
8510 (goto-char (org-table-begin 'any))
8511 (looking-at org-table1-hline-regexp))))
8512
8513 (defun org-table-recognize-table.el ()
8514 "If there is a table.el table nearby, recognize it and move into it."
8515 (if org-table-tab-recognizes-table.el
8516 (if (org-at-table.el-p)
8517 (progn
8518 (beginning-of-line 1)
8519 (if (looking-at org-table-dataline-regexp)
8520 nil
8521 (if (looking-at org-table1-hline-regexp)
8522 (progn
8523 (beginning-of-line 2)
8524 (if (looking-at org-table-any-border-regexp)
8525 (beginning-of-line -1)))))
8526 (if (re-search-forward "|" (org-table-end t) t)
8527 (progn
8528 (require 'table)
8529 (if (table--at-cell-p (point))
8530 t
8531 (message "recognizing table.el table...")
8532 (table-recognize-table)
8533 (message "recognizing table.el table...done")))
8534 (error "This should not happen..."))
8535 t)
8536 nil)
8537 nil))
8538
8539 (defun org-at-table-hline-p ()
8540 "Return t if the cursor is inside a hline in a table."
8541 (if org-enable-table-editor
8542 (save-excursion
8543 (beginning-of-line 1)
8544 (looking-at org-table-hline-regexp))
8545 nil))
8546
8547 (defun org-table-insert-column ()
8548 "Insert a new column into the table."
8549 (interactive)
8550 (if (not (org-at-table-p))
8551 (error "Not at a table"))
8552 (org-table-find-dataline)
8553 (let* ((col (max 1 (org-table-current-column)))
8554 (beg (org-table-begin))
8555 (end (org-table-end))
8556 ;; Current cursor position
8557 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8558 (colpos col))
8559 (goto-char beg)
8560 (while (< (point) end)
8561 (if (org-at-table-hline-p)
8562 nil
8563 (org-table-goto-column col t)
8564 (insert "| "))
8565 (beginning-of-line 2))
8566 (move-marker end nil)
8567 (goto-line linepos)
8568 (org-table-goto-column colpos)
8569 (org-table-align)
8570 (org-table-modify-formulas 'insert col)))
8571
8572 (defun org-table-find-dataline ()
8573 "Find a dataline in the current table, which is needed for column commands."
8574 (if (and (org-at-table-p)
8575 (not (org-at-table-hline-p)))
8576 t
8577 (let ((col (current-column))
8578 (end (org-table-end)))
8579 (move-to-column col)
8580 (while (and (< (point) end)
8581 (or (not (= (current-column) col))
8582 (org-at-table-hline-p)))
8583 (beginning-of-line 2)
8584 (move-to-column col))
8585 (if (and (org-at-table-p)
8586 (not (org-at-table-hline-p)))
8587 t
8588 (error
8589 "Please position cursor in a data line for column operations")))))
8590
8591 (defun org-table-delete-column ()
8592 "Delete a column into the table."
8593 (interactive)
8594 (if (not (org-at-table-p))
8595 (error "Not at a table"))
8596 (org-table-find-dataline)
8597 (org-table-check-inside-data-field)
8598 (let* ((col (org-table-current-column))
8599 (beg (org-table-begin))
8600 (end (org-table-end))
8601 ;; Current cursor position
8602 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8603 (colpos col))
8604 (goto-char beg)
8605 (while (< (point) end)
8606 (if (org-at-table-hline-p)
8607 nil
8608 (org-table-goto-column col t)
8609 (and (looking-at "|[^|\n]+|")
8610 (replace-match "|")))
8611 (beginning-of-line 2))
8612 (move-marker end nil)
8613 (goto-line linepos)
8614 (org-table-goto-column colpos)
8615 (org-table-align)
8616 (org-table-modify-formulas 'remove col)))
8617
8618 (defun org-table-move-column-right ()
8619 "Move column to the right."
8620 (interactive)
8621 (org-table-move-column nil))
8622 (defun org-table-move-column-left ()
8623 "Move column to the left."
8624 (interactive)
8625 (org-table-move-column 'left))
8626
8627 (defun org-table-move-column (&optional left)
8628 "Move the current column to the right. With arg LEFT, move to the left."
8629 (interactive "P")
8630 (if (not (org-at-table-p))
8631 (error "Not at a table"))
8632 (org-table-find-dataline)
8633 (org-table-check-inside-data-field)
8634 (let* ((col (org-table-current-column))
8635 (col1 (if left (1- col) col))
8636 (beg (org-table-begin))
8637 (end (org-table-end))
8638 ;; Current cursor position
8639 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8640 (colpos (if left (1- col) (1+ col))))
8641 (if (and left (= col 1))
8642 (error "Cannot move column further left"))
8643 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8644 (error "Cannot move column further right"))
8645 (goto-char beg)
8646 (while (< (point) end)
8647 (if (org-at-table-hline-p)
8648 nil
8649 (org-table-goto-column col1 t)
8650 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8651 (replace-match "|\\2|\\1|")))
8652 (beginning-of-line 2))
8653 (move-marker end nil)
8654 (goto-line linepos)
8655 (org-table-goto-column colpos)
8656 (org-table-align)
8657 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8658
8659 (defun org-table-move-row-down ()
8660 "Move table row down."
8661 (interactive)
8662 (org-table-move-row nil))
8663 (defun org-table-move-row-up ()
8664 "Move table row up."
8665 (interactive)
8666 (org-table-move-row 'up))
8667
8668 (defun org-table-move-row (&optional up)
8669 "Move the current table line down. With arg UP, move it up."
8670 (interactive "P")
8671 (let ((col (current-column))
8672 (pos (point))
8673 (tonew (if up 0 2))
8674 txt)
8675 (beginning-of-line tonew)
8676 (if (not (org-at-table-p))
8677 (progn
8678 (goto-char pos)
8679 (error "Cannot move row further")))
8680 (goto-char pos)
8681 (beginning-of-line 1)
8682 (setq pos (point))
8683 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8684 (delete-region (point) (1+ (point-at-eol)))
8685 (beginning-of-line tonew)
8686 (insert txt)
8687 (beginning-of-line 0)
8688 (move-to-column col)))
8689
8690 (defun org-table-insert-row (&optional arg)
8691 "Insert a new row above the current line into the table.
8692 With prefix ARG, insert below the current line."
8693 (interactive "P")
8694 (if (not (org-at-table-p))
8695 (error "Not at a table"))
8696 (let* ((line
8697 (org-expand-wide-chars
8698 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8699 new)
8700 (if (string-match "^[ \t]*|-" line)
8701 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8702 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8703 ;; Fix the first field if necessary
8704 (setq new (concat new))
8705 (if (string-match "^[ \t]*| *[#$] *|" line)
8706 (setq new (replace-match (match-string 0 line) t t new)))
8707 (beginning-of-line (if arg 2 1))
8708 (let (org-table-may-need-update)
8709 (insert-before-markers new)
8710 (insert-before-markers "\n"))
8711 (beginning-of-line 0)
8712 (re-search-forward "| ?" (point-at-eol) t)
8713 (and org-table-may-need-update (org-table-align))))
8714
8715 (defun org-table-insert-hline (&optional arg)
8716 "Insert a horizontal-line below the current line into the table.
8717 With prefix ARG, insert above the current line."
8718 (interactive "P")
8719 (if (not (org-at-table-p))
8720 (error "Not at a table"))
8721 (let ((line
8722 (org-expand-wide-chars
8723 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8724 (col (current-column))
8725 start)
8726 (if (string-match "^[ \t]*|-" line)
8727 (setq line
8728 (mapcar (lambda (x) (if (member x '(?| ?+))
8729 (prog1 (if start ?+ ?|) (setq start t))
8730 (if start ?- ?\ )))
8731 line))
8732 (setq line
8733 (mapcar (lambda (x) (if (equal x ?|)
8734 (prog1 (if start ?+ ?|) (setq start t))
8735 (if start ?- ?\ )))
8736 line)))
8737 (beginning-of-line (if arg 1 2))
8738 (apply 'insert line)
8739 (if (equal (char-before (point)) ?+)
8740 (progn (backward-delete-char 1) (insert "|")))
8741 (insert "\n")
8742 (beginning-of-line (if arg 1 -1))
8743 (move-to-column col)))
8744
8745 (defun org-expand-wide-chars (s)
8746 "Expand wide characters to spaces."
8747 (let (w a)
8748 (mapconcat
8749 (lambda (x)
8750 (if (> (setq w (string-width (setq a (char-to-string x)))) 1)
8751 (make-string w ?\ )
8752 a))
8753 s "")))
8754
8755 (defun org-table-kill-row ()
8756 "Delete the current row or horizontal line from the table."
8757 (interactive)
8758 (if (not (org-at-table-p))
8759 (error "Not at a table"))
8760 (let ((col (current-column)))
8761 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8762 (if (not (org-at-table-p)) (beginning-of-line 0))
8763 (move-to-column col)))
8764
8765 (defun org-table-sort-lines (beg end numericp)
8766 "Sort table lines in region.
8767 Point and mark define the first and last line to include. Both point and
8768 mark should be in the column that is used for sorting. For example, to
8769 sort according to column 3, put the mark in the first line to sort, in
8770 table column 3. Put point into the last line to be included in the sorting,
8771 also in table column 3. The command will prompt for the sorting method
8772 \(n for numerical, a for alphanumeric)."
8773 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8774 (setq numericp (string-match "[nN]" numericp))
8775 (org-table-align) ;; Just to be safe
8776 (let* (bcol ecol cmp column lns)
8777 (goto-char beg)
8778 (org-table-check-inside-data-field)
8779 (setq column (org-table-current-column)
8780 beg (move-marker (make-marker) (point-at-bol)))
8781 (goto-char end)
8782 (org-table-check-inside-data-field)
8783 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8784 (untabify beg end)
8785 (goto-char beg)
8786 (org-table-goto-column column)
8787 (skip-chars-backward "^|")
8788 (setq bcol (current-column))
8789 (org-table-goto-column (1+ column))
8790 (skip-chars-backward "^|")
8791 (setq ecol (1- (current-column)))
8792 (setq cmp (if numericp
8793 (lambda (a b) (< (car a) (car b)))
8794 (lambda (a b) (string< (car a) (car b)))))
8795 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8796 (split-string (buffer-substring beg end) "\n")))
8797 (if numericp
8798 (setq lns (mapcar (lambda(x)
8799 (cons (string-to-number (car x)) (cdr x)))
8800 lns)))
8801 (delete-region beg end)
8802 (move-marker beg nil)
8803 (move-marker end nil)
8804 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8805 (message "%d lines sorted %s based on column %d"
8806 (length lns)
8807 (if numericp "numerically" "alphabetically") column)))
8808
8809 (defun org-table-cut-region (beg end)
8810 "Copy region in table to the clipboard and blank all relevant fields."
8811 (interactive "r")
8812 (org-table-copy-region beg end 'cut))
8813
8814 (defun org-table-copy-region (beg end &optional cut)
8815 "Copy rectangular region in table to clipboard.
8816 A special clipboard is used which can only be accessed
8817 with `org-table-paste-rectangle'."
8818 (interactive "rP")
8819 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8820 region cols
8821 (rpl (if cut " " nil)))
8822 (goto-char beg)
8823 (org-table-check-inside-data-field)
8824 (setq l01 (count-lines (point-min) (point))
8825 c01 (org-table-current-column))
8826 (goto-char end)
8827 (org-table-check-inside-data-field)
8828 (setq l02 (count-lines (point-min) (point))
8829 c02 (org-table-current-column))
8830 (setq l1 (min l01 l02) l2 (max l01 l02)
8831 c1 (min c01 c02) c2 (max c01 c02))
8832 (catch 'exit
8833 (while t
8834 (catch 'nextline
8835 (if (> l1 l2) (throw 'exit t))
8836 (goto-line l1)
8837 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8838 (setq cols nil ic1 c1 ic2 c2)
8839 (while (< ic1 (1+ ic2))
8840 (push (org-table-get-field ic1 rpl) cols)
8841 (setq ic1 (1+ ic1)))
8842 (push (nreverse cols) region)
8843 (setq l1 (1+ l1)))))
8844 (setq org-table-clip (nreverse region))
8845 (if cut (org-table-align))
8846 org-table-clip))
8847
8848 (defun org-table-paste-rectangle ()
8849 "Paste a rectangular region into a table.
8850 The upper right corner ends up in the current field. All involved fields
8851 will be overwritten. If the rectangle does not fit into the present table,
8852 the table is enlarged as needed. The process ignores horizontal separator
8853 lines."
8854 (interactive)
8855 (unless (and org-table-clip (listp org-table-clip))
8856 (error "First cut/copy a region to paste!"))
8857 (org-table-check-inside-data-field)
8858 (let* ((clip org-table-clip)
8859 (line (count-lines (point-min) (point)))
8860 (col (org-table-current-column))
8861 (org-enable-table-editor t)
8862 (org-table-automatic-realign nil)
8863 c cols field)
8864 (while (setq cols (pop clip))
8865 (while (org-at-table-hline-p) (beginning-of-line 2))
8866 (if (not (org-at-table-p))
8867 (progn (end-of-line 0) (org-table-next-field)))
8868 (setq c col)
8869 (while (setq field (pop cols))
8870 (org-table-goto-column c nil 'force)
8871 (org-table-get-field nil field)
8872 (setq c (1+ c)))
8873 (beginning-of-line 2))
8874 (goto-line line)
8875 (org-table-goto-column col)
8876 (org-table-align)))
8877
8878 (defun org-table-convert ()
8879 "Convert from `org-mode' table to table.el and back.
8880 Obviously, this only works within limits. When an Org-mode table is
8881 converted to table.el, all horizontal separator lines get lost, because
8882 table.el uses these as cell boundaries and has no notion of horizontal lines.
8883 A table.el table can be converted to an Org-mode table only if it does not
8884 do row or column spanning. Multiline cells will become multiple cells.
8885 Beware, Org-mode does not test if the table can be successfully converted - it
8886 blindly applies a recipe that works for simple tables."
8887 (interactive)
8888 (require 'table)
8889 (if (org-at-table.el-p)
8890 ;; convert to Org-mode table
8891 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8892 (end (move-marker (make-marker) (org-table-end t))))
8893 (table-unrecognize-region beg end)
8894 (goto-char beg)
8895 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8896 (replace-match ""))
8897 (goto-char beg))
8898 (if (org-at-table-p)
8899 ;; convert to table.el table
8900 (let ((beg (move-marker (make-marker) (org-table-begin)))
8901 (end (move-marker (make-marker) (org-table-end))))
8902 ;; first, get rid of all horizontal lines
8903 (goto-char beg)
8904 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8905 (replace-match ""))
8906 ;; insert a hline before first
8907 (goto-char beg)
8908 (org-table-insert-hline 'above)
8909 (beginning-of-line -1)
8910 ;; insert a hline after each line
8911 (while (progn (beginning-of-line 3) (< (point) end))
8912 (org-table-insert-hline))
8913 (goto-char beg)
8914 (setq end (move-marker end (org-table-end)))
8915 ;; replace "+" at beginning and ending of hlines
8916 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8917 (replace-match "\\1+-"))
8918 (goto-char beg)
8919 (while (re-search-forward "-|[ \t]*$" end t)
8920 (replace-match "-+"))
8921 (goto-char beg)))))
8922
8923 (defun org-table-wrap-region (arg)
8924 "Wrap several fields in a column like a paragraph.
8925 This is useful if you'd like to spread the contents of a field over several
8926 lines, in order to keep the table compact.
8927
8928 If there is an active region, and both point and mark are in the same column,
8929 the text in the column is wrapped to minimum width for the given number of
8930 lines. Generally, this makes the table more compact. A prefix ARG may be
8931 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8932 formats the selected text to two lines. If the region was longer than two
8933 lines, the remaining lines remain empty. A negative prefix argument reduces
8934 the current number of lines by that amount. The wrapped text is pasted back
8935 into the table. If you formatted it to more lines than it was before, fields
8936 further down in the table get overwritten - so you might need to make space in
8937 the table first.
8938
8939 If there is no region, the current field is split at the cursor position and
8940 the text fragment to the right of the cursor is prepended to the field one
8941 line down.
8942
8943 If there is no region, but you specify a prefix ARG, the current field gets
8944 blank, and the content is appended to the field above."
8945 (interactive "P")
8946 (org-table-check-inside-data-field)
8947 (if (org-region-active-p)
8948 ;; There is a region: fill as a paragraph
8949 (let ((beg (region-beginning))
8950 nlines)
8951 (org-table-cut-region (region-beginning) (region-end))
8952 (if (> (length (car org-table-clip)) 1)
8953 (error "Region must be limited to single column"))
8954 (setq nlines (if arg
8955 (if (< arg 1)
8956 (+ (length org-table-clip) arg)
8957 arg)
8958 (length org-table-clip)))
8959 (setq org-table-clip
8960 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8961 nil nlines)))
8962 (goto-char beg)
8963 (org-table-paste-rectangle))
8964 ;; No region, split the current field at point
8965 (if arg
8966 ;; combine with field above
8967 (let ((s (org-table-blank-field))
8968 (col (org-table-current-column)))
8969 (beginning-of-line 0)
8970 (while (org-at-table-hline-p) (beginning-of-line 0))
8971 (org-table-goto-column col)
8972 (skip-chars-forward "^|")
8973 (skip-chars-backward " ")
8974 (insert " " (org-trim s))
8975 (org-table-align))
8976 ;; split field
8977 (when (looking-at "\\([^|]+\\)+|")
8978 (let ((s (match-string 1)))
8979 (replace-match " |")
8980 (goto-char (match-beginning 0))
8981 (org-table-next-row)
8982 (insert (org-trim s) " ")
8983 (org-table-align))))))
8984
8985 (defun org-trim (s)
8986 "Remove whitespace at beginning and end of string."
8987 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8988 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8989 s)
8990
8991 (defun org-wrap (string &optional width lines)
8992 "Wrap string to either a number of lines, or a width in characters.
8993 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8994 that costs. If there is a word longer than WIDTH, the text is actually
8995 wrapped to the length of that word.
8996 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8997 many lines, whatever width that takes.
8998 The return value is a list of lines, without newlines at the end."
8999 (let* ((words (org-split-string string "[ \t\n]+"))
9000 (maxword (apply 'max (mapcar 'string-width words)))
9001 w ll)
9002 (cond (width
9003 (org-do-wrap words (max maxword width)))
9004 (lines
9005 (setq w maxword)
9006 (setq ll (org-do-wrap words maxword))
9007 (if (<= (length ll) lines)
9008 ll
9009 (setq ll words)
9010 (while (> (length ll) lines)
9011 (setq w (1+ w))
9012 (setq ll (org-do-wrap words w)))
9013 ll))
9014 (t (error "Cannot wrap this")))))
9015
9016
9017 (defun org-do-wrap (words width)
9018 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9019 (let (lines line)
9020 (while words
9021 (setq line (pop words))
9022 (while (and words (< (+ (length line) (length (car words))) width))
9023 (setq line (concat line " " (pop words))))
9024 (setq lines (push line lines)))
9025 (nreverse lines)))
9026
9027 ;; FIXME: I think I can make this more efficient
9028 (defun org-split-string (string &optional separators)
9029 "Splits STRING into substrings at SEPARATORS.
9030 No empty strings are returned if there are matches at the beginning
9031 and end of string."
9032 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9033 (start 0)
9034 notfirst
9035 (list nil))
9036 (while (and (string-match rexp string
9037 (if (and notfirst
9038 (= start (match-beginning 0))
9039 (< start (length string)))
9040 (1+ start) start))
9041 (< (match-beginning 0) (length string)))
9042 (setq notfirst t)
9043 (or (eq (match-beginning 0) 0)
9044 (and (eq (match-beginning 0) (match-end 0))
9045 (eq (match-beginning 0) start))
9046 (setq list
9047 (cons (substring string start (match-beginning 0))
9048 list)))
9049 (setq start (match-end 0)))
9050 (or (eq start (length string))
9051 (setq list
9052 (cons (substring string start)
9053 list)))
9054 (nreverse list)))
9055
9056 (defun org-table-add-invisible-to-vertical-lines ()
9057 "Add an `invisible' property to vertical lines of current table."
9058 (interactive)
9059 (let* ((beg (org-table-begin))
9060 (end (org-table-end))
9061 (end1))
9062 (save-excursion
9063 (goto-char beg)
9064 (while (< (point) end)
9065 (setq end1 (point-at-eol))
9066 (if (looking-at org-table-dataline-regexp)
9067 (while (re-search-forward "|" end1 t)
9068 (add-text-properties (1- (point)) (point)
9069 '(invisible org-table)))
9070 (while (re-search-forward "[+|]" end1 t)
9071 (add-text-properties (1- (point)) (point)
9072 '(invisible org-table))))
9073 (beginning-of-line 2)))))
9074
9075 (defun org-table-toggle-vline-visibility (&optional arg)
9076 "Toggle the visibility of table vertical lines.
9077 The effect is immediate and on all tables in the file.
9078 With prefix ARG, make lines invisible when ARG is positive, make lines
9079 visible when ARG is not positive."
9080 (interactive "P")
9081 (let ((action (cond
9082 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
9083 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
9084 (t (if (org-in-invisibility-spec-p '(org-table))
9085 'off
9086 'on)))))
9087 (if (eq action 'off)
9088 (progn
9089 (org-remove-from-invisibility-spec '(org-table))
9090 (org-table-map-tables 'org-table-align)
9091 (message "Vertical table lines visible")
9092 (if (org-at-table-p)
9093 (org-table-align)))
9094 (org-add-to-invisibility-spec '(org-table))
9095 (org-table-map-tables 'org-table-align)
9096 (message "Vertical table lines invisible"))
9097 (redraw-frame (selected-frame))))
9098
9099 (defun org-table-map-tables (function)
9100 "Apply FUNCTION to the start of all tables in the buffer."
9101 (save-excursion
9102 (save-restriction
9103 (widen)
9104 (goto-char (point-min))
9105 (while (re-search-forward org-table-any-line-regexp nil t)
9106 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9107 (beginning-of-line 1)
9108 (if (looking-at org-table-line-regexp)
9109 (save-excursion (funcall function)))
9110 (re-search-forward org-table-any-border-regexp nil 1)))))
9111
9112 (defun org-table-sum (&optional beg end nlast)
9113 "Sum numbers in region of current table column.
9114 The result will be displayed in the echo area, and will be available
9115 as kill to be inserted with \\[yank].
9116
9117 If there is an active region, it is interpreted as a rectangle and all
9118 numbers in that rectangle will be summed. If there is no active
9119 region and point is located in a table column, sum all numbers in that
9120 column.
9121
9122 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9123 numbers are assumed to be times as well (in decimal hours) and the
9124 numbers are added as such.
9125
9126 If NLAST is a number, only the NLAST fields will actually be summed."
9127 (interactive)
9128 (save-excursion
9129 (let (col (timecnt 0) diff h m s org-table-clip)
9130 (cond
9131 ((and beg end)) ; beg and end given explicitly
9132 ((org-region-active-p)
9133 (setq beg (region-beginning) end (region-end)))
9134 (t
9135 (setq col (org-table-current-column))
9136 (goto-char (org-table-begin))
9137 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9138 (error "No table data"))
9139 (org-table-goto-column col)
9140 ;not needed? (skip-chars-backward "^|")
9141 (setq beg (point))
9142 (goto-char (org-table-end))
9143 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9144 (error "No table data"))
9145 (org-table-goto-column col)
9146 ;not needed? (skip-chars-forward "^|")
9147 (setq end (point))))
9148 (let* ((items (apply 'append (org-table-copy-region beg end)))
9149 (items1 (cond ((not nlast) items)
9150 ((>= nlast (length items)) items)
9151 (t (setq items (reverse items))
9152 (setcdr (nthcdr (1- nlast) items) nil)
9153 (nreverse items))))
9154 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9155 items1)))
9156 (res (apply '+ numbers))
9157 (sres (if (= timecnt 0)
9158 (format "%g" res)
9159 (setq diff (* 3600 res)
9160 h (floor (/ diff 3600)) diff (mod diff 3600)
9161 m (floor (/ diff 60)) diff (mod diff 60)
9162 s diff)
9163 (format "%d:%02d:%02d" h m s))))
9164 (kill-new sres)
9165 (if (interactive-p)
9166 (message "%s"
9167 (substitute-command-keys
9168 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9169 (length numbers) sres))))
9170 sres))))
9171
9172 (defun org-table-get-number-for-summing (s)
9173 (let (n)
9174 (if (string-match "^ *|? *" s)
9175 (setq s (replace-match "" nil nil s)))
9176 (if (string-match " *|? *$" s)
9177 (setq s (replace-match "" nil nil s)))
9178 (setq n (string-to-number s))
9179 (cond
9180 ((and (string-match "0" s)
9181 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9182 ((string-match "\\`[ \t]+\\'" s) nil)
9183 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9184 (let ((h (string-to-number (or (match-string 1 s) "0")))
9185 (m (string-to-number (or (match-string 2 s) "0")))
9186 (s (string-to-number (or (match-string 4 s) "0"))))
9187 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9188 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9189 ((equal n 0) nil)
9190 (t n))))
9191
9192 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9193 "Get a calc vector from a column, accorting to descriptor DESC.
9194 Optional arguments TBEG and COL can give the beginning of the table and
9195 the current column, to avoid unnecessary parsing."
9196 (save-excursion
9197 (or tbeg (setq tbeg (org-table-begin)))
9198 (or col (setq col (org-table-current-column)))
9199 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9200 (cond
9201 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9202 (setq n1 (- (match-end 1) (match-beginning 1)))
9203 (if (match-beginning 3)
9204 (setq n2 (- (match-end 2) (match-beginning 3))))
9205 (setq n (if n2 (max n1 n2) n1))
9206 (setq n1 (if n2 (min n1 n2)))
9207 (setq nn n)
9208 (while (and (> nn 0)
9209 (re-search-backward org-table-hline-regexp tbeg t))
9210 (push (org-current-line) hline-list)
9211 (setq nn (1- nn)))
9212 (setq hline-list (nreverse hline-list))
9213 (goto-line (nth (1- n) hline-list))
9214 (when (re-search-forward org-table-dataline-regexp)
9215 (org-table-goto-column col)
9216 (setq beg (point)))
9217 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9218 (when (re-search-backward org-table-dataline-regexp)
9219 (org-table-goto-column col)
9220 (setq end (point)))
9221 (setq l (apply 'append (org-table-copy-region beg end)))
9222 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9223 (if (equal x "") "0" x))
9224 l ",") "]"))
9225 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9226 (setq n1 (string-to-number (match-string 1 desc))
9227 n2 (string-to-number (match-string 2 desc)))
9228 (beginning-of-line 1)
9229 (save-excursion
9230 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9231 (org-table-goto-column col)
9232 (setq beg (point))))
9233 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9234 (org-table-goto-column col)
9235 (setq end (point)))
9236 (setq l (apply 'append (org-table-copy-region beg end)))
9237 (concat "[" (mapconcat
9238 (lambda (x) (setq x (org-trim x))
9239 (if (equal x "") "0" x))
9240 l ",") "]"))
9241 ((string-match "\\([0-9]+\\)" desc)
9242 (beginning-of-line 1)
9243 (when (re-search-backward org-table-dataline-regexp tbeg t
9244 (string-to-number (match-string 0 desc)))
9245 (org-table-goto-column col)
9246 (org-trim (org-table-get-field))))))))
9247
9248 (defvar org-table-formula-history nil)
9249
9250 (defvar org-table-column-names nil
9251 "Alist with column names, derived from the `!' line.")
9252 (defvar org-table-column-name-regexp nil
9253 "Regular expression matching the current column names.")
9254 (defvar org-table-local-parameters nil
9255 "Alist with parameter names, derived from the `$' line.")
9256 (defvar org-table-named-field-locations nil
9257 "Alist with locations of named fields.")
9258
9259 (defun org-table-get-formula (&optional equation named)
9260 "Read a formula from the minibuffer, offer stored formula as default."
9261 (let* ((name (car (rassoc (list (org-current-line)
9262 (org-table-current-column))
9263 org-table-named-field-locations)))
9264 (scol (if named
9265 (if name name
9266 (error "Not in a named field"))
9267 (int-to-string (org-table-current-column))))
9268 (dummy (and name (not named)
9269 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9270 (error "Abort")))
9271 (org-table-may-need-update nil)
9272 (stored-list (org-table-get-stored-formulas))
9273 (stored (cdr (assoc scol stored-list)))
9274 (eq (cond
9275 ((and stored equation (string-match "^ *=? *$" equation))
9276 stored)
9277 ((stringp equation)
9278 equation)
9279 (t (read-string
9280 (format "%s formula $%s=" (if named "Field" "Column") scol)
9281 (or stored "") 'org-table-formula-history
9282 ;stored
9283 ))))
9284 mustsave)
9285 (when (not (string-match "\\S-" eq))
9286 ;; remove formula
9287 (setq stored-list (delq (assoc scol stored-list) stored-list))
9288 (org-table-store-formulas stored-list)
9289 (error "Formula removed"))
9290 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9291 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9292 (if (and name (not named))
9293 ;; We set the column equation, delete the named one.
9294 (setq stored-list (delq (assoc name stored-list) stored-list)
9295 mustsave t))
9296 (if stored
9297 (setcdr (assoc scol stored-list) eq)
9298 (setq stored-list (cons (cons scol eq) stored-list)))
9299 (if (or mustsave (not (equal stored eq)))
9300 (org-table-store-formulas stored-list))
9301 eq))
9302
9303 (defun org-table-store-formulas (alist)
9304 "Store the list of formulas below the current table."
9305 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9306 (save-excursion
9307 (goto-char (org-table-end))
9308 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9309 (delete-region (point) (match-end 0)))
9310 (insert "#+TBLFM: "
9311 (mapconcat (lambda (x)
9312 (concat "$" (car x) "=" (cdr x)))
9313 alist "::")
9314 "\n")))
9315
9316 (defun org-table-get-stored-formulas ()
9317 "Return an alist with the t=stored formulas directly after current table."
9318 (interactive)
9319 (let (scol eq eq-alist strings string seen)
9320 (save-excursion
9321 (goto-char (org-table-end))
9322 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9323 (setq strings (org-split-string (match-string 2) " *:: *"))
9324 (while (setq string (pop strings))
9325 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9326 (setq scol (match-string 1 string)
9327 eq (match-string 2 string)
9328 eq-alist (cons (cons scol eq) eq-alist))
9329 (if (member scol seen)
9330 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9331 (push scol seen))))))
9332 (nreverse eq-alist)))
9333
9334 (defun org-table-modify-formulas (action &rest columns)
9335 "Modify the formulas stored below the current table.
9336 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9337 expected, for the other actions only a single column number is needed."
9338 (let ((list (org-table-get-stored-formulas))
9339 (nmax (length (org-split-string
9340 (buffer-substring (point-at-bol) (point-at-eol))
9341 "|")))
9342 col col1 col2 scol si sc1 sc2)
9343 (cond
9344 ((null list)) ; No action needed if there are no stored formulas
9345 ((eq action 'remove)
9346 (setq col (car columns)
9347 scol (int-to-string col))
9348 (org-table-replace-in-formulas list scol "INVALID")
9349 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9350 (loop for i from (1+ col) upto nmax by 1 do
9351 (setq si (int-to-string i))
9352 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9353 (if (assoc si list) (setcar (assoc si list)
9354 (int-to-string (1- i))))))
9355 ((eq action 'insert)
9356 (setq col (car columns))
9357 (loop for i from nmax downto col by 1 do
9358 (setq si (int-to-string i))
9359 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9360 (if (assoc si list) (setcar (assoc si list)
9361 (int-to-string (1+ i))))))
9362 ((eq action 'swap)
9363 (setq col1 (car columns) col2 (nth 1 columns)
9364 sc1 (int-to-string col1) sc2 (int-to-string col2))
9365 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
9366 (org-table-replace-in-formulas list sc1 "ZqZ")
9367 (org-table-replace-in-formulas list sc2 sc1)
9368 (org-table-replace-in-formulas list "ZqZ" sc2)
9369 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
9370 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9371 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
9372 (t (error "Invalid action in `org-table-modify-formulas'")))
9373 (if list (org-table-store-formulas list))))
9374
9375 (defun org-table-replace-in-formulas (list s1 s2)
9376 (let (elt re s)
9377 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9378 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
9379 re (concat (regexp-quote s1) "\\>"))
9380 (while (setq elt (pop list))
9381 (setq s (cdr elt))
9382 (while (string-match re s)
9383 (setq s (replace-match s2 t t s)))
9384 (setcdr elt s))))
9385
9386 (defun org-table-get-specials ()
9387 "Get the column names and local parameters for this table."
9388 (save-excursion
9389 (let ((beg (org-table-begin)) (end (org-table-end))
9390 names name fields fields1 field cnt c v line col)
9391 (setq org-table-column-names nil
9392 org-table-local-parameters nil
9393 org-table-named-field-locations nil)
9394 (goto-char beg)
9395 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9396 (setq names (org-split-string (match-string 1) " *| *")
9397 cnt 1)
9398 (while (setq name (pop names))
9399 (setq cnt (1+ cnt))
9400 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9401 (push (cons name (int-to-string cnt)) org-table-column-names))))
9402 (setq org-table-column-names (nreverse org-table-column-names))
9403 (setq org-table-column-name-regexp
9404 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9405 (goto-char beg)
9406 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9407 (setq fields (org-split-string (match-string 1) " *| *"))
9408 (while (setq field (pop fields))
9409 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9410 (push (cons (match-string 1 field) (match-string 2 field))
9411 org-table-local-parameters))))
9412 (goto-char beg)
9413 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9414 (setq c (match-string 1)
9415 fields (org-split-string (match-string 2) " *| *"))
9416 (save-excursion
9417 (beginning-of-line (if (equal c "_") 2 0))
9418 (setq line (org-current-line) col 1)
9419 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9420 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9421 (while (and fields1 (setq field (pop fields)))
9422 (setq v (pop fields1) col (1+ col))
9423 (when (and (stringp field) (stringp v)
9424 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9425 (push (cons field v) org-table-local-parameters)
9426 (push (list field line col) org-table-named-field-locations)))))))
9427
9428 (defun org-this-word ()
9429 ;; Get the current word
9430 (save-excursion
9431 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
9432 (end (progn (skip-chars-forward "^ \t\n") (point))))
9433 (buffer-substring-no-properties beg end))))
9434
9435 (defun org-table-maybe-eval-formula ()
9436 "Check if the current field starts with \"=\" or \":=\".
9437 If yes, store the formula and apply it."
9438 ;; We already know we are in a table. Get field will only return a formula
9439 ;; when appropriate. It might return a separator line, but no problem.
9440 (when org-table-formula-evaluate-inline
9441 (let* ((field (org-trim (or (org-table-get-field) "")))
9442 named eq)
9443 (when (string-match "^:?=\\(.*\\)" field)
9444 (setq named (equal (string-to-char field) ?:)
9445 eq (match-string 1 field))
9446 (if (fboundp 'calc-eval)
9447 (org-table-eval-formula (if named '(4) nil) eq))))))
9448
9449 (defvar org-recalc-commands nil
9450 "List of commands triggering the recalculation of a line.
9451 Will be filled automatically during use.")
9452
9453 (defvar org-recalc-marks
9454 '((" " . "Unmarked: no special line, no automatic recalculation")
9455 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9456 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9457 ("!" . "Column name definition line. Reference in formula as $name.")
9458 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9459 ("_" . "Names for values in row below this one.")
9460 ("^" . "Names for values in row above this one.")))
9461
9462 (defun org-table-rotate-recalc-marks (&optional newchar)
9463 "Rotate the recalculation mark in the first column.
9464 If in any row, the first field is not consistent with a mark,
9465 insert a new column for the markers.
9466 When there is an active region, change all the lines in the region,
9467 after prompting for the marking character.
9468 After each change, a message will be displayed indicating the meaning
9469 of the new mark."
9470 (interactive)
9471 (unless (org-at-table-p) (error "Not at a table"))
9472 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9473 (beg (org-table-begin))
9474 (end (org-table-end))
9475 (l (org-current-line))
9476 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9477 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9478 (have-col
9479 (save-excursion
9480 (goto-char beg)
9481 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9482 (col (org-table-current-column))
9483 (forcenew (car (assoc newchar org-recalc-marks)))
9484 epos new)
9485 (when l1
9486 (message "Change region to what mark? Type # * ! $ or SPC: ")
9487 (setq newchar (char-to-string (read-char-exclusive))
9488 forcenew (car (assoc newchar org-recalc-marks))))
9489 (if (and newchar (not forcenew))
9490 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9491 newchar))
9492 (if l1 (goto-line l1))
9493 (save-excursion
9494 (beginning-of-line 1)
9495 (unless (looking-at org-table-dataline-regexp)
9496 (error "Not at a table data line")))
9497 (unless have-col
9498 (org-table-goto-column 1)
9499 (org-table-insert-column)
9500 (org-table-goto-column (1+ col)))
9501 (setq epos (point-at-eol))
9502 (save-excursion
9503 (beginning-of-line 1)
9504 (org-table-get-field
9505 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9506 (concat " "
9507 (setq new (or forcenew
9508 (cadr (member (match-string 1) marks))))
9509 " ")
9510 " # ")))
9511 (if (and l1 l2)
9512 (progn
9513 (goto-line l1)
9514 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9515 (and (looking-at org-table-dataline-regexp)
9516 (org-table-get-field 1 (concat " " new " "))))
9517 (goto-line l1)))
9518 (if (not (= epos (point-at-eol))) (org-table-align))
9519 (goto-line l)
9520 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9521
9522 (defun org-table-maybe-recalculate-line ()
9523 "Recompute the current line if marked for it, and if we haven't just done it."
9524 (interactive)
9525 (and org-table-allow-automatic-line-recalculation
9526 (not (and (memq last-command org-recalc-commands)
9527 (equal org-last-recalc-line (org-current-line))))
9528 (save-excursion (beginning-of-line 1)
9529 (looking-at org-table-auto-recalculate-regexp))
9530 (fboundp 'calc-eval)
9531 (org-table-recalculate) t))
9532
9533 (defvar org-table-formula-debug nil
9534 "Non-nil means, debug table formulas.
9535 When nil, simply write \"#ERROR\" in corrupted fields.")
9536
9537 (defvar modes)
9538 (defsubst org-set-calc-mode (var &optional value)
9539 (if (stringp var)
9540 (setq var (assoc var '(("D" calc-angle-mode deg)
9541 ("R" calc-angle-mode rad)
9542 ("F" calc-prefer-frac t)
9543 ("S" calc-symbolic-mode t)))
9544 value (nth 2 var) var (nth 1 var)))
9545 (if (memq var modes)
9546 (setcar (cdr (memq var modes)) value)
9547 (cons var (cons value modes)))
9548 modes)
9549
9550 (defun org-table-eval-formula (&optional arg equation
9551 suppress-align suppress-const
9552 suppress-store)
9553 "Replace the table field value at the cursor by the result of a calculation.
9554
9555 This function makes use of Dave Gillespie's Calc package, in my view the
9556 most exciting program ever written for GNU Emacs. So you need to have Calc
9557 installed in order to use this function.
9558
9559 In a table, this command replaces the value in the current field with the
9560 result of a formula. It also installs the formula as the \"current\" column
9561 formula, by storing it in a special line below the table. When called
9562 with a `C-u' prefix, the current field must ba a named field, and the
9563 formula is installed as valid in only this specific field.
9564
9565 When called, the command first prompts for a formula, which is read in
9566 the minibuffer. Previously entered formulas are available through the
9567 history list, and the last used formula is offered as a default.
9568 These stored formulas are adapted correctly when moving, inserting, or
9569 deleting columns with the corresponding commands.
9570
9571 The formula can be any algebraic expression understood by the Calc package.
9572 For details, see the Org-mode manual.
9573
9574 This function can also be called from Lisp programs and offers
9575 additional arguments: EQUATION can be the formula to apply. If this
9576 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9577 used to speed-up recursive calls by by-passing unnecessary aligns.
9578 SUPPRESS-CONST suppresses the interpretation of constants in the
9579 formula, assuming that this has been done already outside the function.
9580 SUPPRESS-STORE means the formula should not be stored, either because
9581 it is already stored, or because it is a modified equation that should
9582 not overwrite the stored one."
9583 (interactive "P")
9584 (require 'calc)
9585 (org-table-check-inside-data-field)
9586 (org-table-get-specials)
9587 (let* (fields
9588 (ndown (if (integerp arg) arg 1))
9589 (org-table-automatic-realign nil)
9590 (case-fold-search nil)
9591 (down (> ndown 1))
9592 (formula (if (and equation suppress-store)
9593 equation
9594 (org-table-get-formula equation (equal arg '(4)))))
9595 (n0 (org-table-current-column))
9596 (modes (copy-sequence org-calc-default-modes))
9597 n form fmt x ev orig c)
9598 ;; Parse the format string. Since we have a lot of modes, this is
9599 ;; a lot of work. However, I think calc still uses most of the time.
9600 (if (string-match ";" formula)
9601 (let ((tmp (org-split-string formula ";")))
9602 (setq formula (car tmp)
9603 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9604 (nth 1 tmp)))
9605 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9606 (setq c (string-to-char (match-string 1 fmt))
9607 n (string-to-number (or (match-string 1 fmt) "")))
9608 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9609 (setq modes (org-set-calc-mode
9610 'calc-float-format
9611 (list (cdr (assoc c '((?n . float) (?f . fix)
9612 (?s . sci) (?e . eng))))
9613 n))))
9614 (setq fmt (replace-match "" t t fmt)))
9615 (while (string-match "[DRFS]" fmt)
9616 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9617 (setq fmt (replace-match "" t t fmt)))
9618 (unless (string-match "\\S-" fmt)
9619 (setq fmt nil))))
9620 (if (and (not suppress-const) org-table-formula-use-constants)
9621 (setq formula (org-table-formula-substitute-names formula)))
9622 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9623 (while (> ndown 0)
9624 (setq fields (org-split-string
9625 (buffer-substring
9626 (point-at-bol) (point-at-eol)) " *| *"))
9627 (if org-table-formula-numbers-only
9628 (setq fields (mapcar
9629 (lambda (x) (number-to-string (string-to-number x)))
9630 fields)))
9631 (setq ndown (1- ndown))
9632 (setq form (copy-sequence formula))
9633 ;; Insert the references to fields in same row
9634 (while (string-match "\\$\\([0-9]+\\)?" form)
9635 (setq n (if (match-beginning 1)
9636 (string-to-number (match-string 1 form))
9637 n0)
9638 x (nth (1- n) fields))
9639 (unless x (error "Invalid field specifier \"%s\""
9640 (match-string 0 form)))
9641 (if (equal x "") (setq x "0"))
9642 (setq form (replace-match (concat "(" x ")") t t form)))
9643 ;; Insert ranges in current column
9644 (while (string-match "\\&[-I0-9]+" form)
9645 (setq form (replace-match
9646 (save-match-data
9647 (org-table-get-vertical-vector (match-string 0 form)
9648 nil n0))
9649 t t form)))
9650 (setq ev (calc-eval (cons form modes)
9651 (if org-table-formula-numbers-only 'num)))
9652
9653 (when org-table-formula-debug
9654 (with-output-to-temp-buffer "*Help*"
9655 (princ (format "Substitution history of formula
9656 Orig: %s
9657 $xyz-> %s
9658 $1-> %s\n" orig formula form))
9659 (if (listp ev)
9660 (princ (format " %s^\nError: %s"
9661 (make-string (car ev) ?\-) (nth 1 ev)))
9662 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9663 ev (or fmt "NONE")
9664 (if fmt (format fmt (string-to-number ev)) ev)))))
9665 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9666 (unless (and (interactive-p) (not ndown))
9667 (unless (let (inhibit-redisplay)
9668 (y-or-n-p "Debugging Formula. Continue to next? "))
9669 (org-table-align)
9670 (error "Abort"))
9671 (delete-window (get-buffer-window "*Help*"))
9672 (message "")))
9673 (if (listp ev) (setq fmt nil ev "#ERROR"))
9674 (org-table-justify-field-maybe
9675 (if fmt (format fmt (string-to-number ev)) ev))
9676 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9677 (call-interactively 'org-return)
9678 (setq ndown 0)))
9679 (and down (org-table-maybe-recalculate-line))
9680 (or suppress-align (and org-table-may-need-update
9681 (org-table-align)))))
9682
9683 (defun org-table-recalculate (&optional all noalign)
9684 "Recalculate the current table line by applying all stored formulas."
9685 (interactive "P")
9686 (or (memq this-command org-recalc-commands)
9687 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9688 (unless (org-at-table-p) (error "Not at a table"))
9689 (org-table-get-specials)
9690 (let* ((eqlist (sort (org-table-get-stored-formulas)
9691 (lambda (a b) (string< (car a) (car b)))))
9692 (inhibit-redisplay t)
9693 (line-re org-table-dataline-regexp)
9694 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9695 (thiscol (org-table-current-column))
9696 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9697 ;; Insert constants in all formulas
9698 (setq eqlist
9699 (mapcar (lambda (x)
9700 (setcdr x (org-table-formula-substitute-names (cdr x)))
9701 x)
9702 eqlist))
9703 ;; Split the equation list
9704 (while (setq eq (pop eqlist))
9705 (if (<= (string-to-char (car eq)) ?9)
9706 (push eq eqlnum)
9707 (push eq eqlname)))
9708 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9709 (if all
9710 (progn
9711 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9712 (goto-char (setq beg (org-table-begin)))
9713 (if (re-search-forward org-table-calculate-mark-regexp end t)
9714 ;; This is a table with marked lines, only compute selected lines
9715 (setq line-re org-table-recalculate-regexp)
9716 ;; Move forward to the first non-header line
9717 (if (and (re-search-forward org-table-dataline-regexp end t)
9718 (re-search-forward org-table-hline-regexp end t)
9719 (re-search-forward org-table-dataline-regexp end t))
9720 (setq beg (match-beginning 0))
9721 nil))) ;; just leave beg where it is
9722 (setq beg (point-at-bol)
9723 end (move-marker (make-marker) (1+ (point-at-eol)))))
9724 (goto-char beg)
9725 (and all (message "Re-applying formulas to full table..."))
9726 (while (re-search-forward line-re end t)
9727 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9728 ;; Unprotected line, recalculate
9729 (and all (message "Re-applying formulas to full table...(line %d)"
9730 (setq cnt (1+ cnt))))
9731 (setq org-last-recalc-line (org-current-line))
9732 (setq eql eqlnum)
9733 (while (setq entry (pop eql))
9734 (goto-line org-last-recalc-line)
9735 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9736 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9737 (goto-line thisline)
9738 (org-table-goto-column thiscol)
9739 (or noalign (and org-table-may-need-update (org-table-align))
9740 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9741 ;; Now do the names fields
9742 (while (setq eq (pop eqlname))
9743 (setq name (car eq)
9744 a (assoc name org-table-named-field-locations))
9745 (when a
9746 (message "Re-applying formula to named field: %s" name)
9747 (goto-line (nth 1 a))
9748 (org-table-goto-column (nth 2 a))
9749 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9750 ;; back to initial position
9751 (goto-line thisline)
9752 (org-table-goto-column thiscol)
9753 (or noalign (and org-table-may-need-update (org-table-align))
9754 (and all (message "Re-applying formulas...done")))))
9755
9756 (defun org-table-formula-substitute-names (f)
9757 "Replace $const with values in string F."
9758 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9759 ;; First, check for column names
9760 (while (setq start (string-match org-table-column-name-regexp f start))
9761 (setq start (1+ start))
9762 (setq a (assoc (match-string 1 f) org-table-column-names))
9763 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9764 ;; Expand ranges to vectors
9765 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9766 (setq n1 (string-to-number (match-string 1 f))
9767 n2 (string-to-number (match-string 2 f))
9768 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9769 s (concat "[($" (number-to-string (1- nn1)) ")"))
9770 (loop for i from nn1 upto nn2 do
9771 (setq s (concat s ",($" (int-to-string i) ")")))
9772 (setq s (concat s "]"))
9773 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9774 (setq f (replace-match s t t f)))
9775 ;; Parameters and constants
9776 (setq start 0)
9777 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9778 (setq start (1+ start))
9779 (if (setq a (save-match-data
9780 (org-table-get-constant (match-string 1 f))))
9781 (setq f (replace-match (concat "(" a ")") t t f))))
9782 (if org-table-formula-debug
9783 (put-text-property 0 (length f) :orig-formula f1 f))
9784 f))
9785
9786 (defun org-table-get-constant (const)
9787 "Find the value for a parameter or constant in a formula.
9788 Parameters get priority."
9789 (or (cdr (assoc const org-table-local-parameters))
9790 (cdr (assoc const org-table-formula-constants))
9791 (and (fboundp 'constants-get) (constants-get const))
9792 "#UNDEFINED_NAME"))
9793
9794 (defvar org-edit-formulas-map (make-sparse-keymap))
9795 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9796 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9797 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9798
9799 (defvar org-pos)
9800 (defvar org-window-configuration)
9801
9802 (defun org-table-edit-formulas ()
9803 "Edit the formulas of the current table in a separate buffer."
9804 (interactive)
9805 (unless (org-at-table-p)
9806 (error "Not at a table"))
9807 (org-table-get-specials)
9808 (let ((eql (org-table-get-stored-formulas))
9809 (pos (move-marker (make-marker) (point)))
9810 (wc (current-window-configuration))
9811 entry loc s)
9812 (switch-to-buffer-other-window "*Edit Formulas*")
9813 (erase-buffer)
9814 (fundamental-mode)
9815 (set (make-local-variable 'org-pos) pos)
9816 (set (make-local-variable 'org-window-configuration) wc)
9817 (use-local-map org-edit-formulas-map)
9818 (setq s "# Edit formulas and finish with `C-c C-c'.
9819 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9820 # Use `C-c ?' to get information about $name at point.
9821 # To cancel editing, press `C-c C-q'.\n")
9822 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9823 (insert s)
9824 (while (setq entry (pop eql))
9825 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9826 (setq s (format "# Named formula, referring to column %d in line %d\n"
9827 (nth 2 loc) (nth 1 loc)))
9828 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9829 (insert s))
9830 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9831 (remove-text-properties 0 (length s) '(face nil) s)
9832 (insert s))
9833 (goto-char (point-min))
9834 (message "Edit formulas and finish with `C-c C-c'.")))
9835
9836 (defun org-show-variable ()
9837 "Show the location/value of the $ expression at point."
9838 (interactive)
9839 (let (var (pos org-pos) (win (selected-window)) e)
9840 (save-excursion
9841 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9842 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9843 (setq var (match-string 1))
9844 (error "No variable at point")))
9845 (cond
9846 ((setq e (assoc var org-table-named-field-locations))
9847 (switch-to-buffer-other-window (marker-buffer pos))
9848 (goto-line (nth 1 e))
9849 (org-table-goto-column (nth 2 e))
9850 (select-window win)
9851 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9852 ((setq e (assoc var org-table-column-names))
9853 (switch-to-buffer-other-window (marker-buffer pos))
9854 (goto-char pos)
9855 (goto-char (org-table-begin))
9856 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9857 (org-table-end) t)
9858 (progn
9859 (goto-char (match-beginning 1))
9860 (message "Named column (column %s)" (cdr e)))
9861 (error "Column name not found"))
9862 (select-window win))
9863 ((string-match "^[0-9]$" var)
9864 ;; column number
9865 (switch-to-buffer-other-window (marker-buffer pos))
9866 (goto-char pos)
9867 (goto-char (org-table-begin))
9868 (recenter 1)
9869 (if (re-search-forward org-table-dataline-regexp
9870 (org-table-end) t)
9871 (progn
9872 (goto-char (match-beginning 0))
9873 (org-table-goto-column (string-to-number var))
9874 (message "Column %s" var))
9875 (error "Column name not found"))
9876 (select-window win))
9877 ((setq e (assoc var org-table-local-parameters))
9878 (switch-to-buffer-other-window (marker-buffer pos))
9879 (goto-char pos)
9880 (goto-char (org-table-begin))
9881 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9882 (progn
9883 (goto-char (match-beginning 1))
9884 (message "Local parameter."))
9885 (error "Parameter not found"))
9886 (select-window win))
9887 (t
9888 (cond
9889 ((setq e (assoc var org-table-formula-constants))
9890 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9891 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9892 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9893 (t (error "Undefined name $%s" var)))))))
9894
9895 (defun org-finish-edit-formulas (&optional arg)
9896 "Parse the buffer for formula definitions and install them.
9897 With prefix ARG, apply the new formulas to the table."
9898 (interactive "P")
9899 (let ((pos org-pos) eql)
9900 (goto-char (point-min))
9901 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9902 (push (cons (match-string 1) (match-string 2)) eql))
9903 (set-window-configuration org-window-configuration)
9904 (select-window (get-buffer-window (marker-buffer pos)))
9905 (goto-char pos)
9906 (unless (org-at-table-p)
9907 (error "Lost table position - cannot install formulae"))
9908 (org-table-store-formulas eql)
9909 (move-marker pos nil)
9910 (kill-buffer "*Edit Formulas*")
9911 (if arg
9912 (org-table-recalculate 'all)
9913 (message "New formulas installed - press C-u C-c C-c to apply."))))
9914
9915 (defun org-abort-edit-formulas ()
9916 "Abort editing formulas, without installing the changes."
9917 (interactive)
9918 (let ((pos org-pos))
9919 (set-window-configuration org-window-configuration)
9920 (select-window (get-buffer-window (marker-buffer pos)))
9921 (goto-char pos)
9922 (message "Formula editing aborted without installing changes")))
9923
9924 ;;; The orgtbl minor mode
9925
9926 ;; Define a minor mode which can be used in other modes in order to
9927 ;; integrate the org-mode table editor.
9928
9929 ;; This is really a hack, because the org-mode table editor uses several
9930 ;; keys which normally belong to the major mode, for example the TAB and
9931 ;; RET keys. Here is how it works: The minor mode defines all the keys
9932 ;; necessary to operate the table editor, but wraps the commands into a
9933 ;; function which tests if the cursor is currently inside a table. If that
9934 ;; is the case, the table editor command is executed. However, when any of
9935 ;; those keys is used outside a table, the function uses `key-binding' to
9936 ;; look up if the key has an associated command in another currently active
9937 ;; keymap (minor modes, major mode, global), and executes that command.
9938 ;; There might be problems if any of the keys used by the table editor is
9939 ;; otherwise used as a prefix key.
9940
9941 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9942 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9943 ;; addresses this by checking explicitly for both bindings.
9944
9945 ;; The optimized version (see variable `orgtbl-optimized') takes over
9946 ;; all keys which are bound to `self-insert-command' in the *global map*.
9947 ;; Some modes bind other commands to simple characters, for example
9948 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9949 ;; active, this binding is ignored inside tables and replaced with a
9950 ;; modified self-insert.
9951
9952 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9953 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9954 In the optimized version, the table editor takes over all simple keys that
9955 normally just insert a character. In tables, the characters are inserted
9956 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9957 for empty fields). Outside tables, the correct binding of the keys is
9958 restored.
9959
9960 The default for this option is t if the optimized version is also used in
9961 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9962 this variable requires a restart of Emacs to become effective."
9963 :group 'org-table
9964 :type 'boolean)
9965
9966 (defvar orgtbl-mode nil
9967 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9968 table editor in arbitrary modes.")
9969 (make-variable-buffer-local 'orgtbl-mode)
9970
9971 (defvar orgtbl-mode-map (make-keymap)
9972 "Keymap for `orgtbl-mode'.")
9973
9974 ;;;###autoload
9975 (defun turn-on-orgtbl ()
9976 "Unconditionally turn on `orgtbl-mode'."
9977 (orgtbl-mode 1))
9978
9979 ;;;###autoload
9980 (defun orgtbl-mode (&optional arg)
9981 "The `org-mode' table editor as a minor mode for use in other modes."
9982 (interactive)
9983 (if (eq major-mode 'org-mode)
9984 ;; Exit without error, in case some hook functions calls this
9985 ;; by accident in org-mode.
9986 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9987 (setq orgtbl-mode
9988 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9989 (if orgtbl-mode
9990 (progn
9991 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9992 ;; Make sure we are first in minor-mode-map-alist
9993 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9994 (and c (setq minor-mode-map-alist
9995 (cons c (delq c minor-mode-map-alist)))))
9996 (set (make-local-variable (quote org-table-may-need-update)) t)
9997 (org-add-hook 'before-change-functions 'org-before-change-function
9998 nil 'local)
9999 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
10000 auto-fill-inhibit-regexp)
10001 (set (make-local-variable 'auto-fill-inhibit-regexp)
10002 (if auto-fill-inhibit-regexp
10003 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
10004 "[ \t]*|"))
10005 (easy-menu-add orgtbl-mode-menu)
10006 (run-hooks 'orgtbl-mode-hook))
10007 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10008 (remove-hook 'before-change-functions 'org-before-change-function t)
10009 (easy-menu-remove orgtbl-mode-menu)
10010 (force-mode-line-update 'all))))
10011
10012 ;; Install it as a minor mode.
10013 (put 'orgtbl-mode :included t)
10014 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10015 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10016
10017 (defun orgtbl-make-binding (fun n &rest keys)
10018 "Create a function for binding in the table minor mode.
10019 FUN is the command to call inside a table. N is used to create a unique
10020 command name. KEYS are keys that should be checked in for a command
10021 to execute outside of tables."
10022 (eval
10023 (list 'defun
10024 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10025 '(arg)
10026 (concat "In tables, run `" (symbol-name fun) "'.\n"
10027 "Outside of tables, run the binding of `"
10028 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10029 "'.")
10030 '(interactive "p")
10031 (list 'if
10032 '(org-at-table-p)
10033 (list 'call-interactively (list 'quote fun))
10034 (list 'let '(orgtbl-mode)
10035 (list 'call-interactively
10036 (append '(or)
10037 (mapcar (lambda (k)
10038 (list 'key-binding k))
10039 keys)
10040 '('orgtbl-error))))))))
10041
10042 (defun orgtbl-error ()
10043 "Error when there is no default binding for a table key."
10044 (interactive)
10045 (error "This key is has no function outside tables"))
10046
10047 (defun orgtbl-setup ()
10048 "Setup orgtbl keymaps."
10049 (let ((nfunc 0)
10050 (bindings
10051 (list
10052 '([(meta shift left)] org-table-delete-column)
10053 '([(meta left)] org-table-move-column-left)
10054 '([(meta right)] org-table-move-column-right)
10055 '([(meta shift right)] org-table-insert-column)
10056 '([(meta shift up)] org-table-kill-row)
10057 '([(meta shift down)] org-table-insert-row)
10058 '([(meta up)] org-table-move-row-up)
10059 '([(meta down)] org-table-move-row-down)
10060 '("\C-c\C-w" org-table-cut-region)
10061 '("\C-c\M-w" org-table-copy-region)
10062 '("\C-c\C-y" org-table-paste-rectangle)
10063 '("\C-c-" org-table-insert-hline)
10064 ; '([(shift tab)] org-table-previous-field)
10065 '("\C-m" org-table-next-row)
10066 (list (org-key 'S-return) 'org-table-copy-down)
10067 '([(meta return)] org-table-wrap-region)
10068 '("\C-c\C-q" org-table-wrap-region)
10069 '("\C-c?" org-table-current-column)
10070 '("\C-c " org-table-blank-field)
10071 '("\C-c+" org-table-sum)
10072 '("\C-c|" org-table-toggle-vline-visibility)
10073 '("\C-c=" org-table-eval-formula)
10074 '("\C-c'" org-table-edit-formulas)
10075 '("\C-c*" org-table-recalculate)
10076 '("\C-c^" org-table-sort-lines)
10077 '([(control ?#)] org-table-rotate-recalc-marks)))
10078 elt key fun cmd)
10079 (while (setq elt (pop bindings))
10080 (setq nfunc (1+ nfunc))
10081 (setq key (car elt)
10082 fun (nth 1 elt)
10083 cmd (orgtbl-make-binding fun nfunc key))
10084 (define-key orgtbl-mode-map key cmd))
10085 ;; Special treatment needed for TAB and RET
10086 (define-key orgtbl-mode-map [(return)]
10087 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10088 (define-key orgtbl-mode-map "\C-m"
10089 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10090 (define-key orgtbl-mode-map [(tab)]
10091 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10092 (define-key orgtbl-mode-map "\C-i"
10093 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10094 (define-key orgtbl-mode-map "\C-i"
10095 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10096 (define-key orgtbl-mode-map "\C-c\C-c"
10097 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10098 (when orgtbl-optimized
10099 ;; If the user wants maximum table support, we need to hijack
10100 ;; some standard editing functions
10101 (org-remap orgtbl-mode-map
10102 'self-insert-command 'orgtbl-self-insert-command
10103 'delete-char 'orgtbl-delete-char
10104 'delete-backward-char 'orgtbl-delete-backward-char)
10105 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10106 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10107 '("OrgTbl"
10108 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10109 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10110 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10111 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10112 "--"
10113 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10114 ["Copy Field from Above"
10115 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10116 "--"
10117 ("Column"
10118 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10119 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10120 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10121 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10122 ("Row"
10123 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10124 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10125 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10126 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10127 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10128 "--"
10129 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10130 ("Rectangle"
10131 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10132 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10133 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10134 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10135 "--"
10136 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10137 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10138 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10139 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10140 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10141 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10142 ["Sum Column/Rectangle" org-table-sum
10143 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10144 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10145 ["Debug Formulas"
10146 (setq org-table-formula-debug (not org-table-formula-debug))
10147 :style toggle :selected org-table-formula-debug]
10148 ))
10149 t)
10150
10151 (defun orgtbl-tab ()
10152 "Justification and field motion for `orgtbl-mode'."
10153 (interactive)
10154 (org-table-justify-field-maybe)
10155 (org-table-next-field))
10156
10157 (defun orgtbl-ret ()
10158 "Justification and field motion for `orgtbl-mode'."
10159 (interactive)
10160 (org-table-justify-field-maybe)
10161 (org-table-next-row))
10162
10163 (defun orgtbl-self-insert-command (N)
10164 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10165 If the cursor is in a table looking at whitespace, the whitespace is
10166 overwritten, and the table is not marked as requiring realignment."
10167 (interactive "p")
10168 (if (and (org-at-table-p)
10169 (or
10170 (and org-table-auto-blank-field
10171 (member last-command
10172 '(orgtbl-hijacker-command-100
10173 orgtbl-hijacker-command-101
10174 orgtbl-hijacker-command-102
10175 orgtbl-hijacker-command-103
10176 orgtbl-hijacker-command-104
10177 orgtbl-hijacker-command-105))
10178 (org-table-blank-field))
10179 t)
10180 (eq N 1)
10181 (looking-at "[^|\n]* +|"))
10182 (let (org-table-may-need-update)
10183 (goto-char (1- (match-end 0)))
10184 (delete-backward-char 1)
10185 (goto-char (match-beginning 0))
10186 (self-insert-command N))
10187 (setq org-table-may-need-update t)
10188 (let (orgtbl-mode)
10189 (call-interactively (key-binding (vector last-input-event))))))
10190
10191 (defun org-force-self-insert (N)
10192 "Needed to enforce self-insert under remapping."
10193 (interactive "p")
10194 (self-insert-command N))
10195
10196 (defun orgtbl-delete-backward-char (N)
10197 "Like `delete-backward-char', insert whitespace at field end in tables.
10198 When deleting backwards, in tables this function will insert whitespace in
10199 front of the next \"|\" separator, to keep the table aligned. The table will
10200 still be marked for re-alignment, because a narrow field may lead to a
10201 reduced column width."
10202 (interactive "p")
10203 (if (and (org-at-table-p)
10204 (eq N 1)
10205 (string-match "|" (buffer-substring (point-at-bol) (point)))
10206 (looking-at ".*?|"))
10207 (let ((pos (point)))
10208 (backward-delete-char N)
10209 (skip-chars-forward "^|")
10210 (insert " ")
10211 (goto-char (1- pos)))
10212 (delete-backward-char N)))
10213
10214 (defun orgtbl-delete-char (N)
10215 "Like `delete-char', but insert whitespace at field end in tables.
10216 When deleting characters, in tables this function will insert whitespace in
10217 front of the next \"|\" separator, to keep the table aligned. The table
10218 will still be marked for re-alignment, because a narrow field may lead to
10219 a reduced column width."
10220 (interactive "p")
10221 (if (and (org-at-table-p)
10222 (not (bolp))
10223 (not (= (char-after) ?|))
10224 (eq N 1))
10225 (if (looking-at ".*?|")
10226 (let ((pos (point)))
10227 (replace-match (concat
10228 (substring (match-string 0) 1 -1)
10229 " |"))
10230 (goto-char pos)))
10231 (delete-char N)))
10232
10233 ;;; Exporting
10234
10235 (defconst org-level-max 20)
10236
10237 (defun org-export-find-first-heading-line (list)
10238 "Remove all lines from LIST which are before the first headline."
10239 (let ((orig-list list)
10240 (re (concat "^" outline-regexp)))
10241 (while (and list
10242 (not (string-match re (car list))))
10243 (pop list))
10244 (or list orig-list)))
10245
10246 (defun org-skip-comments (lines)
10247 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10248 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10249 (re2 "^\\(\\*+\\)[ \t\n\r]")
10250 rtn line level)
10251 (while (setq line (pop lines))
10252 (cond
10253 ((and (string-match re1 line)
10254 (setq level (- (match-end 1) (match-beginning 1))))
10255 ;; Beginning of a COMMENT subtree. Skip it.
10256 (while (and (setq line (pop lines))
10257 (or (not (string-match re2 line))
10258 (> (- (match-end 1) (match-beginning 1)) level))))
10259 (setq lines (cons line lines)))
10260 ((string-match "^#" line)
10261 ;; an ordinary comment line
10262 )
10263 ((and org-export-table-remove-special-lines
10264 (string-match "^[ \t]*| *[!_^] *|" line))
10265 ;; a special table line that should be removed
10266 )
10267 (t (setq rtn (cons line rtn)))))
10268 (nreverse rtn)))
10269
10270 ;; ASCII
10271
10272 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10273 "Characters for underlining headings in ASCII export.")
10274
10275 (defconst org-html-entities
10276 '(("nbsp")
10277 ("iexcl")
10278 ("cent")
10279 ("pound")
10280 ("curren")
10281 ("yen")
10282 ("brvbar")
10283 ("sect")
10284 ("uml")
10285 ("copy")
10286 ("ordf")
10287 ("laquo")
10288 ("not")
10289 ("shy")
10290 ("reg")
10291 ("macr")
10292 ("deg")
10293 ("plusmn")
10294 ("sup2")
10295 ("sup3")
10296 ("acute")
10297 ("micro")
10298 ("para")
10299 ("middot")
10300 ("odot"."o")
10301 ("star"."*")
10302 ("cedil")
10303 ("sup1")
10304 ("ordm")
10305 ("raquo")
10306 ("frac14")
10307 ("frac12")
10308 ("frac34")
10309 ("iquest")
10310 ("Agrave")
10311 ("Aacute")
10312 ("Acirc")
10313 ("Atilde")
10314 ("Auml")
10315 ("Aring") ("AA"."&Aring;")
10316 ("AElig")
10317 ("Ccedil")
10318 ("Egrave")
10319 ("Eacute")
10320 ("Ecirc")
10321 ("Euml")
10322 ("Igrave")
10323 ("Iacute")
10324 ("Icirc")
10325 ("Iuml")
10326 ("ETH")
10327 ("Ntilde")
10328 ("Ograve")
10329 ("Oacute")
10330 ("Ocirc")
10331 ("Otilde")
10332 ("Ouml")
10333 ("times")
10334 ("Oslash")
10335 ("Ugrave")
10336 ("Uacute")
10337 ("Ucirc")
10338 ("Uuml")
10339 ("Yacute")
10340 ("THORN")
10341 ("szlig")
10342 ("agrave")
10343 ("aacute")
10344 ("acirc")
10345 ("atilde")
10346 ("auml")
10347 ("aring")
10348 ("aelig")
10349 ("ccedil")
10350 ("egrave")
10351 ("eacute")
10352 ("ecirc")
10353 ("euml")
10354 ("igrave")
10355 ("iacute")
10356 ("icirc")
10357 ("iuml")
10358 ("eth")
10359 ("ntilde")
10360 ("ograve")
10361 ("oacute")
10362 ("ocirc")
10363 ("otilde")
10364 ("ouml")
10365 ("divide")
10366 ("oslash")
10367 ("ugrave")
10368 ("uacute")
10369 ("ucirc")
10370 ("uuml")
10371 ("yacute")
10372 ("thorn")
10373 ("yuml")
10374 ("fnof")
10375 ("Alpha")
10376 ("Beta")
10377 ("Gamma")
10378 ("Delta")
10379 ("Epsilon")
10380 ("Zeta")
10381 ("Eta")
10382 ("Theta")
10383 ("Iota")
10384 ("Kappa")
10385 ("Lambda")
10386 ("Mu")
10387 ("Nu")
10388 ("Xi")
10389 ("Omicron")
10390 ("Pi")
10391 ("Rho")
10392 ("Sigma")
10393 ("Tau")
10394 ("Upsilon")
10395 ("Phi")
10396 ("Chi")
10397 ("Psi")
10398 ("Omega")
10399 ("alpha")
10400 ("beta")
10401 ("gamma")
10402 ("delta")
10403 ("epsilon")
10404 ("varepsilon"."&epsilon;")
10405 ("zeta")
10406 ("eta")
10407 ("theta")
10408 ("iota")
10409 ("kappa")
10410 ("lambda")
10411 ("mu")
10412 ("nu")
10413 ("xi")
10414 ("omicron")
10415 ("pi")
10416 ("rho")
10417 ("sigmaf") ("varsigma"."&sigmaf;")
10418 ("sigma")
10419 ("tau")
10420 ("upsilon")
10421 ("phi")
10422 ("chi")
10423 ("psi")
10424 ("omega")
10425 ("thetasym") ("vartheta"."&thetasym;")
10426 ("upsih")
10427 ("piv")
10428 ("bull") ("bullet"."&bull;")
10429 ("hellip") ("dots"."&hellip;")
10430 ("prime")
10431 ("Prime")
10432 ("oline")
10433 ("frasl")
10434 ("weierp")
10435 ("image")
10436 ("real")
10437 ("trade")
10438 ("alefsym")
10439 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
10440 ("uarr") ("uparrow"."&uarr;")
10441 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
10442 ("darr")("downarrow"."&darr;")
10443 ("harr") ("leftrightarrow"."&harr;")
10444 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
10445 ("lArr") ("Leftarrow"."&lArr;")
10446 ("uArr") ("Uparrow"."&uArr;")
10447 ("rArr") ("Rightarrow"."&rArr;")
10448 ("dArr") ("Downarrow"."&dArr;")
10449 ("hArr") ("Leftrightarrow"."&hArr;")
10450 ("forall")
10451 ("part") ("partial"."&part;")
10452 ("exist") ("exists"."&exist;")
10453 ("empty") ("emptyset"."&empty;")
10454 ("nabla")
10455 ("isin") ("in"."&isin;")
10456 ("notin")
10457 ("ni")
10458 ("prod")
10459 ("sum")
10460 ("minus")
10461 ("lowast") ("ast"."&lowast;")
10462 ("radic")
10463 ("prop") ("proptp"."&prop;")
10464 ("infin") ("infty"."&infin;")
10465 ("ang") ("angle"."&ang;")
10466 ("and") ("vee"."&and;")
10467 ("or") ("wedge"."&or;")
10468 ("cap")
10469 ("cup")
10470 ("int")
10471 ("there4")
10472 ("sim")
10473 ("cong") ("simeq"."&cong;")
10474 ("asymp")("approx"."&asymp;")
10475 ("ne") ("neq"."&ne;")
10476 ("equiv")
10477 ("le")
10478 ("ge")
10479 ("sub") ("subset"."&sub;")
10480 ("sup") ("supset"."&sup;")
10481 ("nsub")
10482 ("sube")
10483 ("supe")
10484 ("oplus")
10485 ("otimes")
10486 ("perp")
10487 ("sdot") ("cdot"."&sdot;")
10488 ("lceil")
10489 ("rceil")
10490 ("lfloor")
10491 ("rfloor")
10492 ("lang")
10493 ("rang")
10494 ("loz") ("Diamond"."&loz;")
10495 ("spades") ("spadesuit"."&spades;")
10496 ("clubs") ("clubsuit"."&clubs;")
10497 ("hearts") ("diamondsuit"."&hearts;")
10498 ("diams") ("diamondsuit"."&diams;")
10499 ("quot")
10500 ("amp")
10501 ("lt")
10502 ("gt")
10503 ("OElig")
10504 ("oelig")
10505 ("Scaron")
10506 ("scaron")
10507 ("Yuml")
10508 ("circ")
10509 ("tilde")
10510 ("ensp")
10511 ("emsp")
10512 ("thinsp")
10513 ("zwnj")
10514 ("zwj")
10515 ("lrm")
10516 ("rlm")
10517 ("ndash")
10518 ("mdash")
10519 ("lsquo")
10520 ("rsquo")
10521 ("sbquo")
10522 ("ldquo")
10523 ("rdquo")
10524 ("bdquo")
10525 ("dagger")
10526 ("Dagger")
10527 ("permil")
10528 ("lsaquo")
10529 ("rsaquo")
10530 ("euro")
10531
10532 ("arccos"."arccos")
10533 ("arcsin"."arcsin")
10534 ("arctan"."arctan")
10535 ("arg"."arg")
10536 ("cos"."cos")
10537 ("cosh"."cosh")
10538 ("cot"."cot")
10539 ("coth"."coth")
10540 ("csc"."csc")
10541 ("deg"."deg")
10542 ("det"."det")
10543 ("dim"."dim")
10544 ("exp"."exp")
10545 ("gcd"."gcd")
10546 ("hom"."hom")
10547 ("inf"."inf")
10548 ("ker"."ker")
10549 ("lg"."lg")
10550 ("lim"."lim")
10551 ("liminf"."liminf")
10552 ("limsup"."limsup")
10553 ("ln"."ln")
10554 ("log"."log")
10555 ("max"."max")
10556 ("min"."min")
10557 ("Pr"."Pr")
10558 ("sec"."sec")
10559 ("sin"."sin")
10560 ("sinh"."sinh")
10561 ("sup"."sup")
10562 ("tan"."tan")
10563 ("tanh"."tanh")
10564 )
10565 "Entities for TeX->HTML translation.
10566 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
10567 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
10568 In that case, \"\\ent\" will be translated to \"&other;\".
10569 The list contains HTML entities for Latin-1, Greek and other symbols.
10570 It is supplemented by a number of commonly used TeX macros with appropriate
10571 translations. There is currently no way for users to extend this.")
10572
10573 (defun org-cleaned-string-for-export (string)
10574 "Cleanup a buffer substring so that links can be created safely."
10575 (interactive)
10576 (let* ((cb (current-buffer))
10577 (re-radio (and org-target-link-regexp
10578 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
10579 rtn)
10580 (save-excursion
10581 (set-buffer (get-buffer-create " org-mode-tmp"))
10582 (erase-buffer)
10583 (insert string)
10584 (org-mode)
10585 ;; Find targets in comments and move them out of comments,
10586 ;; but mark them as targets that should be invisible
10587 (goto-char (point-min))
10588 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
10589 (replace-match "\\1(INVISIBLE)"))
10590 ;; Find matches for radio targets and turn them into links
10591 (goto-char (point-min))
10592 (when re-radio
10593 (while (re-search-forward re-radio nil t)
10594 (replace-match "\\1[[\\2]]")))
10595 ;; Find all links that contain a newline and put them into a single line
10596 (goto-char (point-min))
10597 (while (re-search-forward "\\(\\[\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\]\\)" nil t)
10598 (replace-match "\\1 \\2")
10599 (goto-char (match-beginning 0)))
10600 ;; Remove comments
10601 (goto-char (point-min))
10602 (while (re-search-forward "^#.*\n?" nil t)
10603 (replace-match ""))
10604 (setq rtn (buffer-string)))
10605 (kill-buffer " org-mode-tmp")
10606 rtn))
10607
10608 (defun org-solidify-link-text (s &optional alist)
10609 "Take link text and make a safe target out of it."
10610 (save-match-data
10611 (let* ((rtn
10612 (mapconcat
10613 'identity
10614 (org-split-string s "[ \t\r\n]+") "--"))
10615 (a (assoc rtn alist)))
10616 (or (cdr a) rtn))))
10617
10618 (defun org-convert-to-odd-levels ()
10619 "Convert an org-mode file with all levels allowed to one with odd levels.
10620 This will leave level 1 alone, convert level 2 to level 3, level 3 to
10621 level 5 etc."
10622 (interactive)
10623 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
10624 (let ((org-odd-levels-only nil) n)
10625 (save-excursion
10626 (goto-char (point-min))
10627 (while (re-search-forward "^\\*\\*+" nil t)
10628 (setq n (1- (length (match-string 0))))
10629 (while (>= (setq n (1- n)) 0)
10630 (org-demote))
10631 (end-of-line 1))))))
10632
10633
10634 (defun org-convert-to-oddeven-levels ()
10635 "Convert an org-mode file with only odd levels to one with odd and even levels.
10636 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
10637 section with an even level, conversion would destroy the structure of the file. An error
10638 is signaled in this case."
10639 (interactive)
10640 (goto-char (point-min))
10641 ;; First check if there are no even levels
10642 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
10643 (org-show-hierarchy-above)
10644 (error "Not all levels are odd in this file. Conversion not possible."))
10645 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
10646 (let ((org-odd-levels-only nil) n)
10647 (save-excursion
10648 (goto-char (point-min))
10649 (while (re-search-forward "^\\*\\*+" nil t)
10650 (setq n (/ (length (match-string 0)) 2))
10651 (while (>= (setq n (1- n)) 0)
10652 (org-promote))
10653 (end-of-line 1))))))
10654
10655 (defun org-tr-level (n)
10656 "Make N odd if required."
10657 (if org-odd-levels-only (1+ (/ n 2)) n))
10658
10659 (defvar org-last-level nil) ; dynamically scoped variable
10660
10661 (defun org-export-as-ascii (arg)
10662 "Export the outline as a pretty ASCII file.
10663 If there is an active region, export only the region.
10664 The prefix ARG specifies how many levels of the outline should become
10665 underlined headlines. The default is 3."
10666 (interactive "P")
10667 (setq-default org-todo-line-regexp org-todo-line-regexp)
10668 (let* ((region
10669 (buffer-substring
10670 (if (org-region-active-p) (region-beginning) (point-min))
10671 (if (org-region-active-p) (region-end) (point-max))))
10672 (lines (org-export-find-first-heading-line
10673 (org-skip-comments
10674 (org-split-string
10675 (org-cleaned-string-for-export region)
10676 "[\r\n]"))))
10677 (org-startup-with-deadline-check nil)
10678 (level 0) line txt
10679 (umax nil)
10680 (case-fold-search nil)
10681 (filename (concat (file-name-sans-extension buffer-file-name)
10682 ".txt"))
10683 (buffer (find-file-noselect filename))
10684 (levels-open (make-vector org-level-max nil))
10685 (date (format-time-string "%Y/%m/%d" (current-time)))
10686 (time (format-time-string "%X" (current-time)))
10687 (author user-full-name)
10688 (title (buffer-name))
10689 (options nil)
10690 (email user-mail-address)
10691 (language org-export-default-language)
10692 (text nil)
10693 (todo nil)
10694 (lang-words nil))
10695
10696 (setq org-last-level 1)
10697 (org-init-section-numbers)
10698
10699 (find-file-noselect filename)
10700
10701 ;; Search for the export key lines
10702 (org-parse-key-lines)
10703
10704 (setq lang-words (or (assoc language org-export-language-setup)
10705 (assoc "en" org-export-language-setup)))
10706 (if org-export-ascii-show-new-buffer
10707 (switch-to-buffer-other-window buffer)
10708 (set-buffer buffer))
10709 (erase-buffer)
10710 (fundamental-mode)
10711 (if options (org-parse-export-options options))
10712 (setq umax (if arg (prefix-numeric-value arg)
10713 org-export-headline-levels))
10714
10715 ;; File header
10716 (if title (org-insert-centered title ?=))
10717 (insert "\n")
10718 (if (or author email)
10719 (insert (concat (nth 1 lang-words) ": " (or author "")
10720 (if email (concat " <" email ">") "")
10721 "\n")))
10722 (if (and date time)
10723 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10724 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10725
10726 (insert "\n\n")
10727
10728 (if org-export-with-toc
10729 (progn
10730 (insert (nth 3 lang-words) "\n"
10731 (make-string (length (nth 3 lang-words)) ?=) "\n")
10732 (mapcar '(lambda (line)
10733 (if (string-match org-todo-line-regexp
10734 line)
10735 ;; This is a headline
10736 (progn
10737 (setq level (- (match-end 1) (match-beginning 1))
10738 level (org-tr-level level)
10739 txt (match-string 3 line)
10740 todo
10741 (or (and (match-beginning 2)
10742 (not (equal (match-string 2 line)
10743 org-done-string)))
10744 ; TODO, not DONE
10745 (and (= level umax)
10746 (org-search-todo-below
10747 line lines level))))
10748 (setq txt (org-html-expand-for-ascii txt))
10749
10750 (if org-export-with-section-numbers
10751 (setq txt (concat (org-section-number level)
10752 " " txt)))
10753 (if (<= level umax)
10754 (progn
10755 (insert
10756 (make-string (* (1- level) 4) ?\ )
10757 (format (if todo "%s (*)\n" "%s\n") txt))
10758 (setq org-last-level level))
10759 ))))
10760 lines)))
10761
10762 (org-init-section-numbers)
10763 (while (setq line (pop lines))
10764 ;; Remove the quoted HTML tags.
10765 (setq line (org-html-expand-for-ascii line))
10766 ;; Remove targets
10767 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
10768 (setq line (replace-match "" t t line)))
10769 ;; Replace internal links
10770 (while (string-match org-bracket-link-regexp line)
10771 (setq line (replace-match
10772 (if (match-end 3) "[\\3]" "[\\1]")
10773 t nil line)))
10774 (cond
10775 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10776 ;; a Headline
10777 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
10778 txt (match-string 2 line))
10779 (org-ascii-level-start level txt umax))
10780 (t (insert line "\n"))))
10781 (normal-mode)
10782 (save-buffer)
10783 (goto-char (point-min))))
10784
10785 (defun org-search-todo-below (line lines level)
10786 "Search the subtree below LINE for any TODO entries."
10787 (let ((rest (cdr (memq line lines)))
10788 (re org-todo-line-regexp)
10789 line lv todo)
10790 (catch 'exit
10791 (while (setq line (pop rest))
10792 (if (string-match re line)
10793 (progn
10794 (setq lv (- (match-end 1) (match-beginning 1))
10795 todo (and (match-beginning 2)
10796 (not (equal (match-string 2 line)
10797 org-done-string))))
10798 ; TODO, not DONE
10799 (if (<= lv level) (throw 'exit nil))
10800 (if todo (throw 'exit t))))))))
10801
10802 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10803 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10804 (defun org-html-expand-for-ascii (line)
10805 "Handle quoted HTML for ASCII export."
10806 (if org-export-html-expand
10807 (while (string-match "@<[^<>\n]*>" line)
10808 ;; We just remove the tags for now.
10809 (setq line (replace-match "" nil nil line))))
10810 line)
10811
10812 (defun org-insert-centered (s &optional underline)
10813 "Insert the string S centered and underline it with character UNDERLINE."
10814 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
10815 (insert (make-string ind ?\ ) s "\n")
10816 (if underline
10817 (insert (make-string ind ?\ )
10818 (make-string (string-width s) underline)
10819 "\n"))))
10820
10821 (defun org-ascii-level-start (level title umax)
10822 "Insert a new level in ASCII export."
10823 (let (char)
10824 (if (> level umax)
10825 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10826 (if (or (not (equal (char-before) ?\n))
10827 (not (equal (char-before (1- (point))) ?\n)))
10828 (insert "\n"))
10829 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10830 (if org-export-with-section-numbers
10831 (setq title (concat (org-section-number level) " " title)))
10832 (insert title "\n" (make-string (string-width title) char) "\n"))))
10833
10834 (defun org-export-copy-visible ()
10835 "Copy the visible part of the buffer to another buffer, for printing.
10836 Also removes the first line of the buffer if it specifies a mode,
10837 and all options lines."
10838 (interactive)
10839 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
10840 ".txt"))
10841 (buffer (find-file-noselect filename))
10842 (ore (concat
10843 (org-make-options-regexp
10844 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10845 "STARTUP" "ARCHIVE"
10846 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10847 (if org-noutline-p "\\(\n\\|$\\)" "")))
10848 s e)
10849 (with-current-buffer buffer
10850 (erase-buffer)
10851 (text-mode))
10852 (save-excursion
10853 (setq s (goto-char (point-min)))
10854 (while (not (= (point) (point-max)))
10855 (goto-char (org-find-invisible))
10856 (append-to-buffer buffer s (point))
10857 (setq s (goto-char (org-find-visible)))))
10858 (switch-to-buffer-other-window buffer)
10859 (newline)
10860 (goto-char (point-min))
10861 (if (looking-at ".*-\\*- mode:.*\n")
10862 (replace-match ""))
10863 (while (re-search-forward ore nil t)
10864 (replace-match ""))
10865 (goto-char (point-min))))
10866
10867 (defun org-find-visible ()
10868 (if (featurep 'noutline)
10869 (let ((s (point)))
10870 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10871 (get-char-property s 'invisible)))
10872 s)
10873 (skip-chars-forward "^\n")
10874 (point)))
10875 (defun org-find-invisible ()
10876 (if (featurep 'noutline)
10877 (let ((s (point)))
10878 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10879 (not (get-char-property s 'invisible))))
10880 s)
10881 (skip-chars-forward "^\r")
10882 (point)))
10883
10884 ;; HTML
10885
10886 (defun org-get-current-options ()
10887 "Return a string with current options as keyword options.
10888 Does include HTML export options as well as TODO and CATEGORY stuff."
10889 (format
10890 "#+TITLE: %s
10891 #+AUTHOR: %s
10892 #+EMAIL: %s
10893 #+LANGUAGE: %s
10894 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10895 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10896 #+CATEGORY: %s
10897 #+SEQ_TODO: %s
10898 #+TYP_TODO: %s
10899 #+STARTUP: %s %s %s %s
10900 #+ARCHIVE: %s
10901 "
10902 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10903 org-export-headline-levels
10904 org-export-with-section-numbers
10905 org-export-with-toc
10906 org-export-preserve-breaks
10907 org-export-html-expand
10908 org-export-with-fixed-width
10909 org-export-with-tables
10910 org-export-with-sub-superscripts
10911 org-export-with-emphasize
10912 org-export-with-TeX-macros
10913 (file-name-nondirectory buffer-file-name)
10914 (if (equal org-todo-interpretation 'sequence)
10915 (mapconcat 'identity org-todo-keywords " ")
10916 "TODO FEEDBACK VERIFY DONE")
10917 (if (equal org-todo-interpretation 'type)
10918 (mapconcat 'identity org-todo-keywords " ")
10919 "Me Jason Marie DONE")
10920 (cdr (assoc org-startup-folded
10921 '((nil . "nofold")(t . "fold")(content . "content"))))
10922 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10923 (if org-odd-levels-only "odd" "oddeven")
10924 (if org-hide-leading-stars "hidestars" "showstars")
10925 org-archive-location
10926 ))
10927
10928 (defun org-insert-export-options-template ()
10929 "Insert into the buffer a template with information for exporting."
10930 (interactive)
10931 (if (not (bolp)) (newline))
10932 (let ((s (org-get-current-options)))
10933 (and (string-match "#\\+CATEGORY" s)
10934 (setq s (substring s 0 (match-beginning 0))))
10935 (insert s)))
10936
10937 (defun org-toggle-fixed-width-section (arg)
10938 "Toggle the fixed-width export.
10939 If there is no active region, the QUOTE keyword at the current headline is
10940 inserted or removed. When present, it causes the text between this headline
10941 and the next to be exported as fixed-width text, and unmodified.
10942 If there is an active region, this command adds or removes a colon as the
10943 first character of this line. If the first character of a line is a colon,
10944 this line is also exported in fixed-width font."
10945 (interactive "P")
10946 (let* ((cc 0)
10947 (regionp (org-region-active-p))
10948 (beg (if regionp (region-beginning) (point)))
10949 (end (if regionp (region-end)))
10950 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10951 (re "[ \t]*\\(:\\)")
10952 off)
10953 (if regionp
10954 (save-excursion
10955 (goto-char beg)
10956 (setq cc (current-column))
10957 (beginning-of-line 1)
10958 (setq off (looking-at re))
10959 (while (> nlines 0)
10960 (setq nlines (1- nlines))
10961 (beginning-of-line 1)
10962 (cond
10963 (arg
10964 (move-to-column cc t)
10965 (insert ":\n")
10966 (forward-line -1))
10967 ((and off (looking-at re))
10968 (replace-match "" t t nil 1))
10969 ((not off) (move-to-column cc t) (insert ":")))
10970 (forward-line 1)))
10971 (save-excursion
10972 (org-back-to-heading)
10973 (if (looking-at (concat outline-regexp
10974 "\\( +\\<" org-quote-string "\\>\\)"))
10975 (replace-match "" t t nil 1)
10976 (if (looking-at outline-regexp)
10977 (progn
10978 (goto-char (match-end 0))
10979 (insert " " org-quote-string))))))))
10980
10981 (defun org-export-as-html-and-open (arg)
10982 "Export the outline as HTML and immediately open it with a browser.
10983 If there is an active region, export only the region.
10984 The prefix ARG specifies how many levels of the outline should become
10985 headlines. The default is 3. Lower levels will become bulleted lists."
10986 (interactive "P")
10987 (org-export-as-html arg 'hidden)
10988 (org-open-file buffer-file-name))
10989
10990 (defun org-export-as-html-batch ()
10991 "Call `org-export-as-html', may be used in batch processing as
10992 emacs --batch
10993 --load=$HOME/lib/emacs/org.el
10994 --eval \"(setq org-export-headline-levels 2)\"
10995 --visit=MyFile --funcall org-export-as-html-batch"
10996 (org-export-as-html org-export-headline-levels 'hidden))
10997
10998 (defun org-export-as-html (arg &optional hidden)
10999 "Export the outline as a pretty HTML file.
11000 If there is an active region, export only the region.
11001 The prefix ARG specifies how many levels of the outline should become
11002 headlines. The default is 3. Lower levels will become bulleted lists."
11003 (interactive "P")
11004 (setq-default org-todo-line-regexp org-todo-line-regexp)
11005 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
11006 (setq-default org-done-string org-done-string)
11007 (let* ((style org-export-html-style)
11008 (odd org-odd-levels-only)
11009 (region-p (org-region-active-p))
11010 (region
11011 (buffer-substring
11012 (if region-p (region-beginning) (point-min))
11013 (if region-p (region-end) (point-max))))
11014 (all_lines
11015 (org-skip-comments (org-split-string
11016 (org-cleaned-string-for-export region)
11017 "[\r\n]")))
11018 (lines (org-export-find-first-heading-line all_lines))
11019 (level 0) (line "") (origline "") txt todo
11020 (umax nil)
11021 (filename (concat (file-name-sans-extension buffer-file-name)
11022 ".html"))
11023 (buffer (find-file-noselect filename))
11024 (levels-open (make-vector org-level-max nil))
11025 (date (format-time-string "%Y/%m/%d" (current-time)))
11026 (time (format-time-string "%X" (current-time)))
11027 (author user-full-name)
11028 (title (buffer-name))
11029 (options nil)
11030 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
11031 (inquote nil)
11032 (infixed nil)
11033 (in-local-list nil)
11034 (local-list-num nil)
11035 (local-list-indent nil)
11036 (llt org-plain-list-ordered-item-terminator)
11037 (email user-mail-address)
11038 (language org-export-default-language)
11039 (text nil)
11040 (lang-words nil)
11041 (target-alist nil) tg
11042 (head-count 0) cnt
11043 (start 0)
11044 ;; FIXME: The following returns always nil under XEmacs
11045 (coding-system (and (fboundp 'coding-system-get)
11046 (boundp 'buffer-file-coding-system)
11047 buffer-file-coding-system))
11048 (coding-system-for-write (or coding-system coding-system-for-write))
11049 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
11050 (charset (and coding-system
11051 (coding-system-get coding-system 'mime-charset)))
11052 table-open type
11053 table-buffer table-orig-buffer
11054 ind start-is-num starter
11055 )
11056 (message "Exporting...")
11057
11058 (setq org-last-level 1)
11059 (org-init-section-numbers)
11060
11061 ;; Search for the export key lines
11062 (org-parse-key-lines)
11063 (setq lang-words (or (assoc language org-export-language-setup)
11064 (assoc "en" org-export-language-setup)))
11065
11066 ;; Switch to the output buffer
11067 (if (or hidden (not org-export-html-show-new-buffer))
11068 (set-buffer buffer)
11069 (switch-to-buffer-other-window buffer))
11070 (erase-buffer)
11071 (fundamental-mode)
11072 (let ((case-fold-search nil)
11073 (org-odd-levels-only odd))
11074 (if options (org-parse-export-options options))
11075 (setq umax (if arg (prefix-numeric-value arg)
11076 org-export-headline-levels))
11077
11078 ;; File header
11079 (insert (format
11080 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
11081 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
11082 <html lang=\"%s\"><head>
11083 <title>%s</title>
11084 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
11085 <meta name=generator content=\"Org-mode\">
11086 <meta name=generated content=\"%s %s\">
11087 <meta name=author content=\"%s\">
11088 %s
11089 </head><body>
11090 "
11091 language (org-html-expand title) (or charset "iso-8859-1")
11092 date time author style))
11093 (if title (insert (concat "<H1 class=\"title\">"
11094 (org-html-expand title) "</H1>\n")))
11095 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11096 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11097 email "&gt;</a>\n")))
11098 (if (or author email) (insert "<br>\n"))
11099 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11100 date " " time "<br>\n")))
11101 (if text (insert (concat "<p>\n" (org-html-expand text))))
11102 (if org-export-with-toc
11103 (progn
11104 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11105 (insert "<ul>\n")
11106 (setq lines
11107 (mapcar '(lambda (line)
11108 (if (string-match org-todo-line-regexp line)
11109 ;; This is a headline
11110 (progn
11111 (setq level (- (match-end 1) (match-beginning 1))
11112 level (org-tr-level level)
11113 txt (save-match-data
11114 (org-html-expand
11115 (match-string 3 line)))
11116 todo
11117 (or (and (match-beginning 2)
11118 (not (equal (match-string 2 line)
11119 org-done-string)))
11120 ; TODO, not DONE
11121 (and (= level umax)
11122 (org-search-todo-below
11123 line lines level))))
11124 (if org-export-with-section-numbers
11125 (setq txt (concat (org-section-number level)
11126 " " txt)))
11127 (if (<= level umax)
11128 (progn
11129 (setq head-count (+ head-count 1))
11130 (if (> level org-last-level)
11131 (progn
11132 (setq cnt (- level org-last-level))
11133 (while (>= (setq cnt (1- cnt)) 0)
11134 (insert "<ul>"))
11135 (insert "\n")))
11136 (if (< level org-last-level)
11137 (progn
11138 (setq cnt (- org-last-level level))
11139 (while (>= (setq cnt (1- cnt)) 0)
11140 (insert "</ul>"))
11141 (insert "\n")))
11142 ;; Check for targets
11143 (while (string-match org-target-regexp line)
11144 (setq tg (match-string 1 line)
11145 line (replace-match
11146 (concat "@<span class=\"target\">" tg "@</span> ")
11147 t t line))
11148 (push (cons (org-solidify-link-text tg)
11149 (format "sec-%d" head-count))
11150 target-alist))
11151 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11152 (setq txt (replace-match "" t t txt)))
11153 (insert
11154 (format
11155 (if todo
11156 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11157 "<li><a href=\"#sec-%d\">%s</a>\n")
11158 head-count txt))
11159
11160 (setq org-last-level level))
11161 )))
11162 line)
11163 lines))
11164 (while (> org-last-level 0)
11165 (setq org-last-level (1- org-last-level))
11166 (insert "</ul>\n"))
11167 ))
11168 (setq head-count 0)
11169 (org-init-section-numbers)
11170
11171 (while (setq line (pop lines) origline line)
11172 (catch 'nextline
11173
11174 ;; end of quote section?
11175 (when (and inquote (string-match "^\\*+" line))
11176 (insert "</pre>\n")
11177 (setq inquote nil))
11178 ;; inside a quote section?
11179 (when inquote
11180 (insert (org-html-protect line) "\n")
11181 (throw 'nextline nil))
11182
11183 ;; verbatim lines
11184 (when (and org-export-with-fixed-width
11185 (string-match "^[ \t]*:\\(.*\\)" line))
11186 (when (not infixed)
11187 (setq infixed t)
11188 (insert "<pre>\n"))
11189 (insert (org-html-protect (match-string 1 line)) "\n")
11190 (when (and lines
11191 (not (string-match "^[ \t]*\\(:.*\\)"
11192 (car lines))))
11193 (setq infixed nil)
11194 (insert "</pre>\n"))
11195 (throw 'nextline nil))
11196
11197
11198 ;; make targets to anchors
11199 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11200 (cond
11201 ((match-end 2)
11202 (setq line (replace-match
11203 (concat "@<a name=\""
11204 (org-solidify-link-text (match-string 1 line))
11205 "\">\\nbsp@</a>")
11206 t t line)))
11207 ((and org-export-with-toc (equal (string-to-char line) ?*))
11208 (setq line (replace-match
11209 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11210 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11211 t t line)))
11212 (t
11213 (setq line (replace-match
11214 (concat "@<a name=\""
11215 (org-solidify-link-text (match-string 1 line))
11216 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11217 t t line)))))
11218 ;; Replace internal links
11219 (while (string-match org-bracket-link-regexp line)
11220 (setq line (replace-match
11221 (concat
11222 "@<a href=\"#"
11223 (org-solidify-link-text (match-string 1 line) target-alist)
11224 "\">"
11225 (match-string (if (match-end 3) 3 1) line)
11226 "@</a>")
11227 t t line)))
11228
11229 ;; Protect the external links
11230 (setq start 0)
11231 (while (string-match org-link-maybe-angles-regexp line start)
11232 (setq start (match-end 0))
11233 (setq line (replace-match
11234 (concat "\000" (match-string 1 line) "\000")
11235 t t line)))
11236
11237 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11238 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11239 (setq line (org-html-expand line))
11240
11241 ;; Format the links
11242 (setq start 0)
11243 (while (string-match org-protected-link-regexp line start)
11244 (setq start (- (match-end 0) 2))
11245 (setq type (match-string 1 line))
11246 (cond
11247 ((member type '("http" "https" "ftp" "mailto" "news"))
11248 ;; standard URL
11249 (setq line (replace-match
11250 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
11251 "<a href=\"\\1:\\2\">\\1:\\2</a>"
11252 nil nil line)))
11253 ((string= type "file")
11254 ;; FILE link
11255 (let* ((filename (match-string 2 line))
11256 (abs-p (file-name-absolute-p filename))
11257 (thefile (if abs-p (expand-file-name filename) filename))
11258 (thefile (save-match-data
11259 (if (string-match ":[0-9]+$" thefile)
11260 (replace-match "" t t thefile)
11261 thefile)))
11262 (file-is-image-p
11263 (save-match-data
11264 (string-match (org-image-file-name-regexp) thefile))))
11265 (setq line (replace-match
11266 (if (and org-export-html-inline-images
11267 file-is-image-p)
11268 (concat "<img src=\"" thefile "\"/>")
11269 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
11270 nil nil line))))
11271
11272 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11273 (setq line (replace-match
11274 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
11275
11276 ;; TODO items
11277 (if (and (string-match org-todo-line-regexp line)
11278 (match-beginning 2))
11279 (if (equal (match-string 2 line) org-done-string)
11280 (setq line (replace-match
11281 "<span class=\"done\">\\2</span>"
11282 nil nil line 2))
11283 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11284 nil nil line 2))))
11285
11286 ;; DEADLINES
11287 (if (string-match org-deadline-line-regexp line)
11288 (progn
11289 (if (save-match-data
11290 (string-match "<a href"
11291 (substring line 0 (match-beginning 0))))
11292 nil ; Don't do the replacement - it is inside a link
11293 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11294 nil nil line 1)))))
11295 (cond
11296 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11297 ;; This is a headline
11298 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11299 txt (match-string 2 line))
11300 (if (<= level umax) (setq head-count (+ head-count 1)))
11301 (when in-local-list
11302 ;; Close any local lists before inserting a new header line
11303 (while local-list-num
11304 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11305 (pop local-list-num))
11306 (setq local-list-indent nil
11307 in-local-list nil))
11308 (org-html-level-start level txt umax
11309 (and org-export-with-toc (<= level umax))
11310 head-count)
11311 ;; QUOTES
11312 (when (string-match quote-re line)
11313 (insert "<pre>")
11314 (setq inquote t)))
11315
11316 ((and org-export-with-tables
11317 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11318 (if (not table-open)
11319 ;; New table starts
11320 (setq table-open t table-buffer nil table-orig-buffer nil))
11321 ;; Accumulate lines
11322 (setq table-buffer (cons line table-buffer)
11323 table-orig-buffer (cons origline table-orig-buffer))
11324 (when (or (not lines)
11325 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11326 (car lines))))
11327 (setq table-open nil
11328 table-buffer (nreverse table-buffer)
11329 table-orig-buffer (nreverse table-orig-buffer))
11330 (insert (org-format-table-html table-buffer table-orig-buffer))))
11331 (t
11332 ;; Normal lines
11333 (when (and (> org-export-plain-list-max-depth 0)
11334 (string-match
11335 (cond
11336 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11337 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11338 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11339 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11340 line))
11341 (setq ind (org-get-string-indentation line)
11342 start-is-num (match-beginning 4)
11343 starter (if (match-beginning 2) (match-string 2 line))
11344 line (substring line (match-beginning 5)))
11345 (unless (string-match "[^ \t]" line)
11346 ;; empty line. Pretend indentation is large.
11347 (setq ind (1+ (or (car local-list-indent) 1))))
11348 (while (and in-local-list
11349 (or (and (= ind (car local-list-indent))
11350 (not starter))
11351 (< ind (car local-list-indent))))
11352 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11353 (pop local-list-num) (pop local-list-indent)
11354 (setq in-local-list local-list-indent))
11355 (cond
11356 ((and starter
11357 (or (not in-local-list)
11358 (> ind (car local-list-indent)))
11359 (< (length local-list-indent)
11360 org-export-plain-list-max-depth))
11361 ;; Start new (level of ) list
11362 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11363 (push start-is-num local-list-num)
11364 (push ind local-list-indent)
11365 (setq in-local-list t))
11366 (starter
11367 ;; continue current list
11368 (insert "<li>\n"))))
11369 ;; Empty lines start a new paragraph. If hand-formatted lists
11370 ;; are not fully interpreted, lines starting with "-", "+", "*"
11371 ;; also start a new paragraph.
11372 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11373 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11374 ))
11375 (if org-export-html-with-timestamp
11376 (insert org-export-html-html-helper-timestamp))
11377 (insert "</body>\n</html>\n")
11378 (normal-mode)
11379 (save-buffer)
11380 (goto-char (point-min)))))
11381
11382 (defun org-format-table-html (lines olines)
11383 "Find out which HTML converter to use and return the HTML code."
11384 (if (string-match "^[ \t]*|" (car lines))
11385 ;; A normal org table
11386 (org-format-org-table-html lines)
11387 ;; Table made by table.el - test for spanning
11388 (let* ((hlines (delq nil (mapcar
11389 (lambda (x)
11390 (if (string-match "^[ \t]*\\+-" x) x
11391 nil))
11392 lines)))
11393 (first (car hlines))
11394 (ll (and (string-match "\\S-+" first)
11395 (match-string 0 first)))
11396 (re (concat "^[ \t]*" (regexp-quote ll)))
11397 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
11398 hlines))))
11399 (if (and (not spanning)
11400 (not org-export-prefer-native-exporter-for-tables))
11401 ;; We can use my own converter with HTML conversions
11402 (org-format-table-table-html lines)
11403 ;; Need to use the code generator in table.el, with the original text.
11404 (org-format-table-table-html-using-table-generate-source olines)))))
11405
11406 (defun org-format-org-table-html (lines)
11407 "Format a table into HTML."
11408 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11409 (setq lines (nreverse lines))
11410 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11411 (setq lines (nreverse lines))
11412 (when org-export-table-remove-special-lines
11413 ;; Check if the table has a marking column. If yes remove the
11414 ;; column and the special lines
11415 (let* ((special
11416 (not
11417 (memq nil
11418 (mapcar
11419 (lambda (x)
11420 (or (string-match "^[ \t]*|-" x)
11421 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
11422 lines)))))
11423 (if special
11424 (setq lines
11425 (delq nil
11426 (mapcar
11427 (lambda (x)
11428 (if (string-match "^[ \t]*| *[!_^] *|" x)
11429 nil ; ignore this line
11430 (and (or (string-match "^[ \t]*|-+\\+" x)
11431 (string-match "^[ \t]*|[^|]*|" x))
11432 (replace-match "|" t t x))))
11433 lines))))))
11434
11435 (let ((head (and org-export-highlight-first-table-line
11436 (delq nil (mapcar
11437 (lambda (x) (string-match "^[ \t]*|-" x))
11438 (cdr lines)))))
11439 line fields html)
11440 (setq html (concat org-export-html-table-tag "\n"))
11441 (while (setq line (pop lines))
11442 (catch 'next-line
11443 (if (string-match "^[ \t]*|-" line)
11444 (progn
11445 (setq head nil) ;; head ends here, first time around
11446 ;; ignore this line
11447 (throw 'next-line t)))
11448 ;; Break the line into fields
11449 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11450 (setq html (concat
11451 html
11452 "<tr>"
11453 (mapconcat (lambda (x)
11454 (if head
11455 (concat "<th>" x "</th>")
11456 (concat "<td>" x "</td>")))
11457 fields "")
11458 "</tr>\n"))))
11459 (setq html (concat html "</table>\n"))
11460 html))
11461
11462 (defun org-fake-empty-table-line (line)
11463 "Replace everything except \"|\" with spaces."
11464 (let ((i (length line))
11465 (newstr (copy-sequence line)))
11466 (while (> i 0)
11467 (setq i (1- i))
11468 (if (not (eq (aref newstr i) ?|))
11469 (aset newstr i ?\ )))
11470 newstr))
11471
11472 (defun org-format-table-table-html (lines)
11473 "Format a table generated by table.el into HTML.
11474 This conversion does *not* use `table-generate-source' from table.el.
11475 This has the advantage that Org-mode's HTML conversions can be used.
11476 But it has the disadvantage, that no cell- or row-spanning is allowed."
11477 (let (line field-buffer
11478 (head org-export-highlight-first-table-line)
11479 fields html empty)
11480 (setq html (concat org-export-html-table-tag "\n"))
11481 (while (setq line (pop lines))
11482 (setq empty "&nbsp")
11483 (catch 'next-line
11484 (if (string-match "^[ \t]*\\+-" line)
11485 (progn
11486 (if field-buffer
11487 (progn
11488 (setq html (concat
11489 html
11490 "<tr>"
11491 (mapconcat
11492 (lambda (x)
11493 (if (equal x "") (setq x empty))
11494 (if head
11495 (concat "<th>" x "</th>\n")
11496 (concat "<td>" x "</td>\n")))
11497 field-buffer "\n")
11498 "</tr>\n"))
11499 (setq head nil)
11500 (setq field-buffer nil)))
11501 ;; Ignore this line
11502 (throw 'next-line t)))
11503 ;; Break the line into fields and store the fields
11504 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11505 (if field-buffer
11506 (setq field-buffer (mapcar
11507 (lambda (x)
11508 (concat x "<br>" (pop fields)))
11509 field-buffer))
11510 (setq field-buffer fields))))
11511 (setq html (concat html "</table>\n"))
11512 html))
11513
11514 (defun org-format-table-table-html-using-table-generate-source (lines)
11515 "Format a table into html, using `table-generate-source' from table.el.
11516 This has the advantage that cell- or row-spanning is allowed.
11517 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
11518 (require 'table)
11519 (with-current-buffer (get-buffer-create " org-tmp1 ")
11520 (erase-buffer)
11521 (insert (mapconcat 'identity lines "\n"))
11522 (goto-char (point-min))
11523 (if (not (re-search-forward "|[^+]" nil t))
11524 (error "Error processing table"))
11525 (table-recognize-table)
11526 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
11527 (table-generate-source 'html " org-tmp2 ")
11528 (set-buffer " org-tmp2 ")
11529 (buffer-substring (point-min) (point-max))))
11530
11531 (defun org-html-protect (s)
11532 ;; convert & to &amp;, < to &lt; and > to &gt;
11533 (let ((start 0))
11534 (while (string-match "&" s start)
11535 (setq s (replace-match "&amp;" t t s)
11536 start (1+ (match-beginning 0))))
11537 (while (string-match "<" s)
11538 (setq s (replace-match "&lt;" t t s)))
11539 (while (string-match ">" s)
11540 (setq s (replace-match "&gt;" t t s))))
11541 s)
11542
11543 (defun org-html-expand (string)
11544 "Prepare STRING for HTML export. Applies all active conversions."
11545 ;; First check if there is a link in the line - if yes, apply conversions
11546 ;; only before the start of the link.
11547 ;; FIXME: This is no longer correct, because links now have an end.
11548 (let* ((m (string-match org-link-regexp string))
11549 (s (if m (substring string 0 m) string))
11550 (r (if m (substring string m) "")))
11551 ;; convert & to &amp;, < to &lt; and > to &gt;
11552 (setq s (org-html-protect s))
11553 (if org-export-html-expand
11554 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
11555 (setq s (replace-match "<\\1>" nil nil s))))
11556 (if org-export-with-emphasize
11557 (setq s (org-export-html-convert-emphasize s)))
11558 (if org-export-with-sub-superscripts
11559 (setq s (org-export-html-convert-sub-super s)))
11560 (if org-export-with-TeX-macros
11561 (let ((start 0) wd ass)
11562 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
11563 (setq wd (match-string 1 s))
11564 (if (setq ass (assoc wd org-html-entities))
11565 (setq s (replace-match (or (cdr ass)
11566 (concat "&" (car ass) ";"))
11567 t t s))
11568 (setq start (+ start (length wd)))))))
11569 (concat s r)))
11570
11571 (defun org-create-multibrace-regexp (left right n)
11572 "Create a regular expression which will match a balanced sexp.
11573 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
11574 as single character strings.
11575 The regexp returned will match the entire expression including the
11576 delimiters. It will also define a single group which contains the
11577 match except for the outermost delimiters. The maximum depth of
11578 stacked delimiters is N. Escaping delimiters is not possible."
11579 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
11580 (or "\\|")
11581 (re nothing)
11582 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
11583 (while (> n 1)
11584 (setq n (1- n)
11585 re (concat re or next)
11586 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
11587 (concat left "\\(" re "\\)" right)))
11588
11589 (defvar org-match-substring-regexp
11590 (concat
11591 "\\([^\\]\\)\\([_^]\\)\\("
11592 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
11593 "\\|"
11594 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
11595 "\\|"
11596 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
11597 "The regular expression matching a sub- or superscript.")
11598
11599 (defun org-export-html-convert-sub-super (string)
11600 "Convert sub- and superscripts in STRING to HTML."
11601 (let (key c)
11602 (while (string-match org-match-substring-regexp string)
11603 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
11604 (setq c (or (match-string 8 string)
11605 (match-string 6 string)
11606 (match-string 5 string)))
11607 (setq string (replace-match
11608 (concat (match-string 1 string)
11609 "<" key ">" c "</" key ">")
11610 t t string)))
11611 (while (string-match "\\\\\\([_^]\\)" string)
11612 (setq string (replace-match (match-string 1 string) t t string))))
11613 string)
11614
11615 (defun org-export-html-convert-emphasize (string)
11616 (while (string-match
11617 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
11618 string)
11619 (setq string (replace-match
11620 (concat "<b>" (match-string 3 string) "</b>")
11621 t t string 2)))
11622 (while (string-match
11623 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
11624 string)
11625 (setq string (replace-match
11626 (concat "<i>" (match-string 3 string) "</i>")
11627 t t string 2)))
11628 (while (string-match
11629 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
11630 string)
11631 (setq string (replace-match
11632 (concat "<u>" (match-string 3 string) "</u>")
11633 t t string 2)))
11634 string)
11635
11636 (defun org-parse-key-lines ()
11637 "Find the special key lines with the information for exporters."
11638 (save-excursion
11639 (goto-char 0)
11640 (let ((re (org-make-options-regexp
11641 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
11642 key)
11643 (while (re-search-forward re nil t)
11644 (setq key (match-string 1))
11645 (cond ((string-equal key "TITLE")
11646 (setq title (match-string 2)))
11647 ((string-equal key "AUTHOR")
11648 (setq author (match-string 2)))
11649 ((string-equal key "EMAIL")
11650 (setq email (match-string 2)))
11651 ((string-equal key "LANGUAGE")
11652 (setq language (match-string 2)))
11653 ((string-equal key "TEXT")
11654 (setq text (concat text "\n" (match-string 2))))
11655 ((string-equal key "OPTIONS")
11656 (setq options (match-string 2))))))))
11657
11658 (defun org-parse-export-options (s)
11659 "Parse the export options line."
11660 (let ((op '(("H" . org-export-headline-levels)
11661 ("num" . org-export-with-section-numbers)
11662 ("toc" . org-export-with-toc)
11663 ("\\n" . org-export-preserve-breaks)
11664 ("@" . org-export-html-expand)
11665 (":" . org-export-with-fixed-width)
11666 ("|" . org-export-with-tables)
11667 ("^" . org-export-with-sub-superscripts)
11668 ("*" . org-export-with-emphasize)
11669 ("TeX" . org-export-with-TeX-macros)))
11670 o)
11671 (while (setq o (pop op))
11672 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
11673 s)
11674 (set (make-local-variable (cdr o))
11675 (car (read-from-string (match-string 1 s))))))))
11676
11677 (defun org-html-level-start (level title umax with-toc head-count)
11678 "Insert a new level in HTML export."
11679 (let ((l (1+ (max level umax))))
11680 (while (<= l org-level-max)
11681 (if (aref levels-open (1- l))
11682 (progn
11683 (org-html-level-close l)
11684 (aset levels-open (1- l) nil)))
11685 (setq l (1+ l)))
11686 (if (> level umax)
11687 (progn
11688 (if (aref levels-open (1- level))
11689 (insert "<li>" title "<p>\n")
11690 (aset levels-open (1- level) t)
11691 (insert "<ul><li>" title "<p>\n")))
11692 (if org-export-with-section-numbers
11693 (setq title (concat (org-section-number level) " " title)))
11694 (setq level (+ level 1))
11695 (if with-toc
11696 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
11697 level head-count title level))
11698 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
11699
11700 (defun org-html-level-close (&rest args)
11701 "Terminate one level in HTML export."
11702 (insert "</ul>"))
11703
11704 ;; Variable holding the vector with section numbers
11705 (defvar org-section-numbers (make-vector org-level-max 0))
11706
11707 (defun org-init-section-numbers ()
11708 "Initialize the vector for the section numbers."
11709 (let* ((level -1)
11710 (numbers (nreverse (org-split-string "" "\\.")))
11711 (depth (1- (length org-section-numbers)))
11712 (i depth) number-string)
11713 (while (>= i 0)
11714 (if (> i level)
11715 (aset org-section-numbers i 0)
11716 (setq number-string (or (car numbers) "0"))
11717 (if (string-match "\\`[A-Z]\\'" number-string)
11718 (aset org-section-numbers i
11719 (- (string-to-char number-string) ?A -1))
11720 (aset org-section-numbers i (string-to-number number-string)))
11721 (pop numbers))
11722 (setq i (1- i)))))
11723
11724 (defun org-section-number (&optional level)
11725 "Return a string with the current section number.
11726 When LEVEL is non-nil, increase section numbers on that level."
11727 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
11728 (when level
11729 (when (> level -1)
11730 (aset org-section-numbers
11731 level (1+ (aref org-section-numbers level))))
11732 (setq idx (1+ level))
11733 (while (<= idx depth)
11734 (if (not (= idx 1))
11735 (aset org-section-numbers idx 0))
11736 (setq idx (1+ idx))))
11737 (setq idx 0)
11738 (while (<= idx depth)
11739 (setq n (aref org-section-numbers idx))
11740 (setq string (concat string (if (not (string= string "")) "." "")
11741 (int-to-string n)))
11742 (setq idx (1+ idx)))
11743 (save-match-data
11744 (if (string-match "\\`\\([@0]\\.\\)+" string)
11745 (setq string (replace-match "" nil nil string)))
11746 (if (string-match "\\(\\.0\\)+\\'" string)
11747 (setq string (replace-match "" nil nil string))))
11748 string))
11749
11750
11751 (defun org-export-icalendar-this-file ()
11752 "Export current file as an iCalendar file.
11753 The iCalendar file will be located in the same directory as the Org-mode
11754 file, but with extension `.ics'."
11755 (interactive)
11756 (org-export-icalendar nil buffer-file-name))
11757
11758 ;;;###autoload
11759 (defun org-export-icalendar-all-agenda-files ()
11760 "Export all files in `org-agenda-files' to iCalendar .ics files.
11761 Each iCalendar file will be located in the same directory as the Org-mode
11762 file, but with extension `.ics'."
11763 (interactive)
11764 (apply 'org-export-icalendar nil org-agenda-files))
11765
11766 ;;;###autoload
11767 (defun org-export-icalendar-combine-agenda-files ()
11768 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11769 The file is stored under the name `org-combined-agenda-icalendar-file'."
11770 (interactive)
11771 (apply 'org-export-icalendar t org-agenda-files))
11772
11773 (defun org-export-icalendar (combine &rest files)
11774 "Create iCalendar files for all elements of FILES.
11775 If COMBINE is non-nil, combine all calendar entries into a single large
11776 file and store it under the name `org-combined-agenda-icalendar-file'."
11777 (save-excursion
11778 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11779 (when combine
11780 (setq ical-file org-combined-agenda-icalendar-file
11781 ical-buffer (org-get-agenda-file-buffer ical-file))
11782 (set-buffer ical-buffer) (erase-buffer))
11783 (while (setq file (pop files))
11784 (catch 'nextfile
11785 (org-check-agenda-file file)
11786 (unless combine
11787 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11788 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11789 (set-buffer ical-buffer) (erase-buffer))
11790 (set-buffer (org-get-agenda-file-buffer file))
11791 (setq category (or org-category
11792 (file-name-sans-extension
11793 (file-name-nondirectory buffer-file-name))))
11794 (if (symbolp category) (setq category (symbol-name category)))
11795 (let ((standard-output ical-buffer))
11796 (if combine
11797 (and (not started) (setq started t)
11798 (org-start-icalendar-file org-icalendar-combined-name))
11799 (org-start-icalendar-file category))
11800 (org-print-icalendar-entries combine category)
11801 (when (or (and combine (not files)) (not combine))
11802 (org-finish-icalendar-file)
11803 (set-buffer ical-buffer)
11804 (save-buffer)
11805 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11806 (org-release-buffers org-agenda-new-buffers))))
11807
11808 (defvar org-after-save-iCalendar-file-hook nil
11809 "Hook run after an iCalendar file has been saved.
11810 The iCalendar buffer is still current when this hook is run.
11811 A good way to use this is to tell a desktop calenndar application to re-read
11812 the iCalendar file.")
11813
11814 (defun org-print-icalendar-entries (&optional combine category)
11815 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11816 When COMBINE is non nil, add the category to each line."
11817 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11818 (dts (org-ical-ts-to-string
11819 (format-time-string (cdr org-time-stamp-formats) (current-time))
11820 "DTSTART"))
11821 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11822 (save-excursion
11823 (goto-char (point-min))
11824 (while (re-search-forward org-ts-regexp nil t)
11825 (setq pos (match-beginning 0)
11826 ts (match-string 0)
11827 inc t
11828 hd (org-get-heading))
11829 (if (looking-at re2)
11830 (progn
11831 (goto-char (match-end 0))
11832 (setq ts2 (match-string 1) inc nil))
11833 (setq ts2 ts
11834 tmp (buffer-substring (max (point-min)
11835 (- pos org-ds-keyword-length))
11836 pos)
11837 deadlinep (string-match org-deadline-regexp tmp)
11838 scheduledp (string-match org-scheduled-regexp tmp)
11839 ;; donep (org-entry-is-done-p)
11840 ))
11841 (if (or (string-match org-tr-regexp hd)
11842 (string-match org-ts-regexp hd))
11843 (setq hd (replace-match "" t t hd)))
11844 (if combine
11845 (setq hd (concat hd " (category " category ")")))
11846 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11847 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11848 (princ (format "BEGIN:VEVENT
11849 %s
11850 %s
11851 SUMMARY:%s
11852 END:VEVENT\n"
11853 (org-ical-ts-to-string ts "DTSTART")
11854 (org-ical-ts-to-string ts2 "DTEND" inc)
11855 hd)))
11856 (when org-icalendar-include-todo
11857 (goto-char (point-min))
11858 (while (re-search-forward org-todo-line-regexp nil t)
11859 (setq state (match-string 1))
11860 (unless (equal state org-done-string)
11861 (setq hd (match-string 3))
11862 (if (string-match org-priority-regexp hd)
11863 (setq pri (string-to-char (match-string 2 hd))
11864 hd (concat (substring hd 0 (match-beginning 1))
11865 (substring hd (- (match-end 1)))))
11866 (setq pri org-default-priority))
11867 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11868 (- org-lowest-priority ?A))))))
11869
11870 (princ (format "BEGIN:VTODO
11871 %s
11872 SUMMARY:%s
11873 SEQUENCE:1
11874 PRIORITY:%d
11875 END:VTODO\n"
11876 dts hd pri))))))))
11877
11878 (defun org-start-icalendar-file (name)
11879 "Start an iCalendar file by inserting the header."
11880 (let ((user user-full-name)
11881 (name (or name "unknown"))
11882 (timezone (cadr (current-time-zone))))
11883 (princ
11884 (format "BEGIN:VCALENDAR
11885 VERSION:2.0
11886 X-WR-CALNAME:%s
11887 PRODID:-//%s//Emacs with Org-mode//EN
11888 X-WR-TIMEZONE:%s
11889 CALSCALE:GREGORIAN\n" name user timezone))))
11890
11891 (defun org-finish-icalendar-file ()
11892 "Finish an iCalendar file by inserting the END statement."
11893 (princ "END:VCALENDAR\n"))
11894
11895 (defun org-ical-ts-to-string (s keyword &optional inc)
11896 "Take a time string S and convert it to iCalendar format.
11897 KEYWORD is added in front, to make a complete line like DTSTART....
11898 When INC is non-nil, increase the hour by two (if time string contains
11899 a time), or the day by one (if it does not contain a time)."
11900 (let ((t1 (org-parse-time-string s 'nodefault))
11901 t2 fmt have-time time)
11902 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11903 (setq t2 t1 have-time t)
11904 (setq t2 (org-parse-time-string s)))
11905 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11906 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11907 (when inc
11908 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11909 (setq time (encode-time s mi h d m y)))
11910 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11911 (concat keyword (format-time-string fmt time))))
11912
11913
11914 ;;; Key bindings
11915
11916 ;; - Bindings in Org-mode map are currently
11917 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11918 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
11919 ;; e (?) useful from outline-mode
11920 ;; i k @ expendable from outline-mode
11921 ;; 0123456789 % & ()_{} " ` free
11922
11923 ;; Make `C-c C-x' a prefix key
11924 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11925
11926 ;; TAB key with modifiers
11927 (define-key org-mode-map "\C-i" 'org-cycle)
11928 (define-key org-mode-map [(tab)] 'org-cycle)
11929 (define-key org-mode-map [(meta tab)] 'org-complete)
11930 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11931 ;; The following line is necessary under Suse GNU/Linux
11932 (unless org-xemacs-p
11933 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11934 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11935
11936 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11937 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11938 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11939 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11940 (define-key org-mode-map [(meta return)] 'org-meta-return)
11941 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11942 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11943
11944 ;; Cursor keys with modifiers
11945 (define-key org-mode-map [(meta left)] 'org-metaleft)
11946 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11947 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11948 (define-key org-mode-map [(meta right)] 'org-metaright)
11949 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11950 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11951 (define-key org-mode-map [(meta up)] 'org-metaup)
11952 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11953 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11954 (define-key org-mode-map [(meta down)] 'org-metadown)
11955 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11956 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11957
11958 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11959 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11960 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11961 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11962 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11963 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11964 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11965 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11966 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11967 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11968 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11969 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11970 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11971 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11972 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11973 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11974
11975 ;; All the other keys
11976 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11977 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11978 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11979 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11980 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11981 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11982 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11983 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11984 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11985 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11986 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11987 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11988 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11989 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11990 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
11991 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
11992 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11993 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11994 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11995 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11996 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11997 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11998 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11999 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12000 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
12001 (define-key org-mode-map "\C-c]" 'org-remove-file)
12002 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
12003 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
12004 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
12005 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12006 (define-key org-mode-map "\C-m" 'org-return)
12007 (define-key org-mode-map "\C-c?" 'org-table-current-column)
12008 (define-key org-mode-map "\C-c " 'org-table-blank-field)
12009 (define-key org-mode-map "\C-c+" 'org-table-sum)
12010 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
12011 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
12012 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
12013 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
12014 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12015 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
12016 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12017 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
12018 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
12019 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
12020 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
12021 ;; OPML support is only an option for the future
12022 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
12023 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
12024 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
12025 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
12026 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
12027 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
12028 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
12029 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12030 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
12031 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
12032 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
12033
12034 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12035 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12036 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12037 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12038
12039 (defsubst org-table-p () (org-at-table-p))
12040
12041 (defun org-self-insert-command (N)
12042 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12043 If the cursor is in a table looking at whitespace, the whitespace is
12044 overwritten, and the table is not marked as requiring realignment."
12045 (interactive "p")
12046 (if (and (org-table-p)
12047 (or
12048 (and org-table-auto-blank-field
12049 (member last-command
12050 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12051 (org-table-blank-field))
12052 t)
12053 (eq N 1)
12054 (looking-at "[^|\n]* +|"))
12055 (let (org-table-may-need-update)
12056 (goto-char (1- (match-end 0)))
12057 (delete-backward-char 1)
12058 (goto-char (match-beginning 0))
12059 (self-insert-command N))
12060 (setq org-table-may-need-update t)
12061 (self-insert-command N)))
12062
12063 ;; FIXME:
12064 ;; The following two functions might still be optimized to trigger
12065 ;; re-alignment less frequently.
12066
12067 (defun org-delete-backward-char (N)
12068 "Like `delete-backward-char', insert whitespace at field end in tables.
12069 When deleting backwards, in tables this function will insert whitespace in
12070 front of the next \"|\" separator, to keep the table aligned. The table will
12071 still be marked for re-alignment, because a narrow field may lead to a
12072 reduced column width."
12073 (interactive "p")
12074 (if (and (org-table-p)
12075 (eq N 1)
12076 (string-match "|" (buffer-substring (point-at-bol) (point)))
12077 (looking-at ".*?|"))
12078 (let ((pos (point)))
12079 (backward-delete-char N)
12080 (skip-chars-forward "^|")
12081 (insert " ")
12082 (goto-char (1- pos)))
12083 (backward-delete-char N)))
12084
12085 (defun org-delete-char (N)
12086 "Like `delete-char', but insert whitespace at field end in tables.
12087 When deleting characters, in tables this function will insert whitespace in
12088 front of the next \"|\" separator, to keep the table aligned. The table
12089 will still be marked for re-alignment, because a narrow field may lead to
12090 a reduced column width."
12091 (interactive "p")
12092 (if (and (org-table-p)
12093 (not (bolp))
12094 (not (= (char-after) ?|))
12095 (eq N 1))
12096 (if (looking-at ".*?|")
12097 (let ((pos (point)))
12098 (replace-match (concat
12099 (substring (match-string 0) 1 -1)
12100 " |"))
12101 (goto-char pos)))
12102 (delete-char N)))
12103
12104 ;; How to do this: Measure non-white length of current string
12105 ;; If equal to column width, we should realign.
12106
12107 (defun org-remap (map &rest commands)
12108 "In MAP, remap the functions given in COMMANDS.
12109 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12110 (let (new old)
12111 (while commands
12112 (setq old (pop commands) new (pop commands))
12113 (if (fboundp 'command-remapping)
12114 (define-key map (vector 'remap old) new)
12115 (substitute-key-definition old new map global-map)))))
12116
12117 (when (eq org-enable-table-editor 'optimized)
12118 ;; If the user wants maximum table support, we need to hijack
12119 ;; some standard editing functions
12120 (org-remap org-mode-map
12121 'self-insert-command 'org-self-insert-command
12122 'delete-char 'org-delete-char
12123 'delete-backward-char 'org-delete-backward-char)
12124 (define-key org-mode-map "|" 'org-force-self-insert))
12125
12126 (defun org-shiftcursor-error ()
12127 "Throw an error because Shift-Cursor command was applied in wrong context."
12128 (error "This command is active in special context like tables, headlines or timestamps"))
12129
12130 (defun org-shifttab ()
12131 "Global visibility cycling or move to previous table field.
12132 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12133 See the individual commands for more information."
12134 (interactive)
12135 (cond
12136 ((org-at-table-p) (org-table-previous-field))
12137 (t (org-cycle '(4)))))
12138
12139 (defun org-shiftmetaleft ()
12140 "Promote subtree or delete table column.
12141 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12142 See the individual commands for more information."
12143 (interactive)
12144 (cond
12145 ((org-at-table-p) (org-table-delete-column))
12146 ((org-on-heading-p) (org-promote-subtree))
12147 ((org-at-item-p) (call-interactively 'org-outdent-item))
12148 (t (org-shiftcursor-error))))
12149
12150 (defun org-shiftmetaright ()
12151 "Demote subtree or insert table column.
12152 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12153 See the individual commands for more information."
12154 (interactive)
12155 (cond
12156 ((org-at-table-p) (org-table-insert-column))
12157 ((org-on-heading-p) (org-demote-subtree))
12158 ((org-at-item-p) (call-interactively 'org-indent-item))
12159 (t (org-shiftcursor-error))))
12160
12161 (defun org-shiftmetaup (&optional arg)
12162 "Move subtree up or kill table row.
12163 Calls `org-move-subtree-up' or `org-table-kill-row' or
12164 `org-move-item-up' depending on context. See the individual commands
12165 for more information."
12166 (interactive "P")
12167 (cond
12168 ((org-at-table-p) (org-table-kill-row))
12169 ((org-on-heading-p) (org-move-subtree-up arg))
12170 ((org-at-item-p) (org-move-item-up arg))
12171 (t (org-shiftcursor-error))))
12172 (defun org-shiftmetadown (&optional arg)
12173 "Move subtree down or insert table row.
12174 Calls `org-move-subtree-down' or `org-table-insert-row' or
12175 `org-move-item-down', depending on context. See the individual
12176 commands for more information."
12177 (interactive "P")
12178 (cond
12179 ((org-at-table-p) (org-table-insert-row arg))
12180 ((org-on-heading-p) (org-move-subtree-down arg))
12181 ((org-at-item-p) (org-move-item-down arg))
12182 (t (org-shiftcursor-error))))
12183
12184 (defun org-metaleft (&optional arg)
12185 "Promote heading or move table column to left.
12186 Calls `org-do-promote' or `org-table-move-column', depending on context.
12187 With no specific context, calls the Emacs default `backward-word'.
12188 See the individual commands for more information."
12189 (interactive "P")
12190 (cond
12191 ((org-at-table-p) (org-table-move-column 'left))
12192 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12193 (t (backward-word (prefix-numeric-value arg)))))
12194
12195 (defun org-metaright (&optional arg)
12196 "Demote subtree or move table column to right.
12197 Calls `org-do-demote' or `org-table-move-column', depending on context.
12198 With no specific context, calls the Emacs default `forward-word'.
12199 See the individual commands for more information."
12200 (interactive "P")
12201 (cond
12202 ((org-at-table-p) (org-table-move-column nil))
12203 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12204 (t (forward-word (prefix-numeric-value arg)))))
12205
12206 (defun org-metaup (&optional arg)
12207 "Move subtree up or move table row up.
12208 Calls `org-move-subtree-up' or `org-table-move-row' or
12209 `org-move-item-up', depending on context. See the individual commands
12210 for more information."
12211 (interactive "P")
12212 (cond
12213 ((org-at-table-p) (org-table-move-row 'up))
12214 ((org-on-heading-p) (org-move-subtree-up arg))
12215 ((org-at-item-p) (org-move-item-up arg))
12216 (t (org-shiftcursor-error))))
12217
12218 (defun org-metadown (&optional arg)
12219 "Move subtree down or move table row down.
12220 Calls `org-move-subtree-down' or `org-table-move-row' or
12221 `org-move-item-down', depending on context. See the individual
12222 commands for more information."
12223 (interactive "P")
12224 (cond
12225 ((org-at-table-p) (org-table-move-row nil))
12226 ((org-on-heading-p) (org-move-subtree-down arg))
12227 ((org-at-item-p) (org-move-item-down arg))
12228 (t (org-shiftcursor-error))))
12229
12230 (defun org-shiftup (&optional arg)
12231 "Increase item in timestamp or increase priority of current item.
12232 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12233 See the individual commands for more information."
12234 (interactive "P")
12235 (cond
12236 ((org-at-timestamp-p) (org-timestamp-up arg))
12237 (t (org-priority-up))))
12238
12239 (defun org-shiftdown (&optional arg)
12240 "Decrease item in timestamp or decrease priority of current item.
12241 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12242 See the individual commands for more information."
12243 (interactive "P")
12244 (cond
12245 ((org-at-timestamp-p) (org-timestamp-down arg))
12246 (t (org-priority-down))))
12247
12248 (defun org-shiftright ()
12249 "Next TODO keyword or timestamp one day later, depending on context."
12250 (interactive)
12251 (cond
12252 ((org-at-timestamp-p) (org-timestamp-up-day))
12253 ((org-on-heading-p) (org-todo 'right))
12254 (t (org-shiftcursor-error))))
12255
12256 (defun org-shiftleft ()
12257 "Previous TODO keyword or timestamp one day earlier, depending on context."
12258 (interactive)
12259 (cond
12260 ((org-at-timestamp-p) (org-timestamp-down-day))
12261 ((org-on-heading-p) (org-todo 'left))
12262 (t (org-shiftcursor-error))))
12263
12264 (defun org-copy-special ()
12265 "Copy region in table or copy current subtree.
12266 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12267 See the individual commands for more information."
12268 (interactive)
12269 (call-interactively
12270 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12271
12272 (defun org-cut-special ()
12273 "Cut region in table or cut current subtree.
12274 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12275 See the individual commands for more information."
12276 (interactive)
12277 (call-interactively
12278 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12279
12280 (defun org-paste-special (arg)
12281 "Paste rectangular region into table, or past subtree relative to level.
12282 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12283 See the individual commands for more information."
12284 (interactive "P")
12285 (if (org-at-table-p)
12286 (org-table-paste-rectangle)
12287 (org-paste-subtree arg)))
12288
12289 (defun org-ctrl-c-ctrl-c (&optional arg)
12290 "Call realign table, or recognize a table.el table, or update keywords.
12291 When the cursor is inside a table created by the table.el package,
12292 activate that table. Otherwise, if the cursor is at a normal table
12293 created with org.el, re-align that table. This command works even if
12294 the automatic table editor has been turned off.
12295
12296 If the cursor is in a headline, prompt for tags and insert them into
12297 the current line, aligned to `org-tags-column'. When in a headline and
12298 called with prefix arg, realign all tags in the current buffer.
12299
12300 If the cursor is in one of the special #+KEYWORD lines, this triggers
12301 scanning the buffer for these lines and updating the information.
12302 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
12303 (interactive "P")
12304 (let ((org-enable-table-editor t))
12305 (cond
12306 ((org-on-target-p) (org-update-radio-target-regexp))
12307 ((org-on-heading-p) (org-set-tags arg))
12308 ((org-at-table.el-p)
12309 (require 'table)
12310 (beginning-of-line 1)
12311 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12312 (table-recognize-table))
12313 ((org-at-table-p)
12314 (org-table-maybe-eval-formula)
12315 (if arg
12316 (org-table-recalculate t)
12317 (org-table-maybe-recalculate-line))
12318 (org-table-align))
12319 ((org-at-item-p)
12320 (org-renumber-ordered-list (prefix-numeric-value arg)))
12321 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12322 (cond
12323 ((equal (match-string 1) "TBLFM")
12324 ;; Recalculate the table before this line
12325 (save-excursion
12326 (beginning-of-line 1)
12327 (skip-chars-backward " \r\n\t")
12328 (if (org-at-table-p) (org-table-recalculate t))))
12329 (t
12330 (org-mode-restart))))
12331 ((org-region-active-p)
12332 (org-table-convert-region (region-beginning) (region-end) arg))
12333 ((condition-case nil
12334 (and (region-beginning) (region-end))
12335 (error nil))
12336 (if (y-or-n-p "Convert inactive region to table? ")
12337 (org-table-convert-region (region-beginning) (region-end) arg)
12338 (error "Abort")))
12339 (t (error "C-c C-c can do nothing useful at this location.")))))
12340
12341 (defun org-mode-restart ()
12342 "Restart Org-mode, to scan again for special lines.
12343 Also updates the keyword regular expressions."
12344 (interactive)
12345 (let ((org-inhibit-startup t)) (org-mode))
12346 (message "Org-mode restarted to refresh keyword and special line setup"))
12347
12348 (defun org-return ()
12349 "Goto next table row or insert a newline.
12350 Calls `org-table-next-row' or `newline', depending on context.
12351 See the individual commands for more information."
12352 (interactive)
12353 (cond
12354 ((org-at-table-p)
12355 (org-table-justify-field-maybe)
12356 (org-table-next-row))
12357 (t (newline))))
12358
12359 (defun org-meta-return (&optional arg)
12360 "Insert a new heading or wrap a region in a table.
12361 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12362 See the individual commands for more information."
12363 (interactive "P")
12364 (cond
12365 ((org-at-table-p)
12366 (org-table-wrap-region arg))
12367 (t (org-insert-heading arg))))
12368
12369 ;;; Menu entries
12370
12371 ;; Define the Org-mode menus
12372 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12373 '("Tbl"
12374 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
12375 ["Next Field" org-cycle (org-at-table-p)]
12376 ["Previous Field" org-shifttab (org-at-table-p)]
12377 ["Next Row" org-return (org-at-table-p)]
12378 "--"
12379 ["Blank Field" org-table-blank-field (org-at-table-p)]
12380 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12381 "--"
12382 ("Column"
12383 ["Move Column Left" org-metaleft (org-at-table-p)]
12384 ["Move Column Right" org-metaright (org-at-table-p)]
12385 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12386 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12387 ("Row"
12388 ["Move Row Up" org-metaup (org-at-table-p)]
12389 ["Move Row Down" org-metadown (org-at-table-p)]
12390 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12391 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12392 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12393 "--"
12394 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
12395 ("Rectangle"
12396 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12397 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12398 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12399 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12400 "--"
12401 ("Calculate"
12402 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12403 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12404 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12405 "--"
12406 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12407 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12408 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12409 "--"
12410 ["Sum Column/Rectangle" org-table-sum
12411 (or (org-at-table-p) (org-region-active-p))]
12412 ["Which Column?" org-table-current-column (org-at-table-p)])
12413 ["Debug Formulas"
12414 (setq org-table-formula-debug (not org-table-formula-debug))
12415 :style toggle :selected org-table-formula-debug]
12416 "--"
12417 ["Invisible Vlines" org-table-toggle-vline-visibility
12418 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
12419 "--"
12420 ["Create" org-table-create (and (not (org-at-table-p))
12421 org-enable-table-editor)]
12422 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
12423 ["Import from File" org-table-import (not (org-at-table-p))]
12424 ["Export to File" org-table-export (org-at-table-p)]
12425 "--"
12426 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12427
12428 (easy-menu-define org-org-menu org-mode-map "Org menu"
12429 '("Org"
12430 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
12431 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
12432 ["Sparse Tree" org-occur t]
12433 ["Show All" show-all t]
12434 "--"
12435 ["New Heading" org-insert-heading t]
12436 ("Navigate Headings"
12437 ["Up" outline-up-heading t]
12438 ["Next" outline-next-visible-heading t]
12439 ["Previous" outline-previous-visible-heading t]
12440 ["Next Same Level" outline-forward-same-level t]
12441 ["Previous Same Level" outline-backward-same-level t]
12442 "--"
12443 ["Jump" org-goto t])
12444 ("Edit Structure"
12445 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12446 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12447 "--"
12448 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12449 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12450 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12451 "--"
12452 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12453 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12454 ["Demote Heading" org-metaright (not (org-at-table-p))]
12455 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12456 "--"
12457 ["Archive Subtree" org-archive-subtree t]
12458 "--"
12459 ["Convert to odd levels" org-convert-to-odd-levels t]
12460 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12461 "--"
12462 ("TODO Lists"
12463 ["TODO/DONE/-" org-todo t]
12464 ["Show TODO Tree" org-show-todo-tree t]
12465 ["Global TODO list" org-todo-list t]
12466 "--"
12467 ["Set Priority" org-priority t]
12468 ["Priority Up" org-shiftup t]
12469 ["Priority Down" org-shiftdown t])
12470 ("Dates and Scheduling"
12471 ["Timestamp" org-time-stamp t]
12472 ["Timestamp (inactive)" org-time-stamp-inactive t]
12473 ("Change Date"
12474 ["1 Day Later" org-timestamp-up-day t]
12475 ["1 Day Earlier" org-timestamp-down-day t]
12476 ["1 ... Later" org-shiftup t]
12477 ["1 ... Earlier" org-shiftdown t])
12478 ["Compute Time Range" org-evaluate-time-range t]
12479 ["Schedule Item" org-schedule t]
12480 ["Deadline" org-deadline t]
12481 "--"
12482 ["Goto Calendar" org-goto-calendar t]
12483 ["Date from Calendar" org-date-from-calendar t])
12484 "--"
12485 ["Agenda Command" org-agenda t]
12486 ("File List for Agenda")
12487 ("Special views current file"
12488 ["TODO Tree" org-show-todo-tree t]
12489 ["Check Deadlines" org-check-deadlines t]
12490 ["Timeline" org-timeline t]
12491 ["Tags Tree" org-tags-sparse-tree t])
12492 "--"
12493 ("Hyperlinks"
12494 ["Store Link (Global)" org-store-link t]
12495 ["Insert Link" org-insert-link t]
12496 ["Follow Link" org-open-at-point t])
12497 "--"
12498 ("Export"
12499 ["ASCII" org-export-as-ascii t]
12500 ["Extract Visible Text" org-export-copy-visible t]
12501 ["HTML" org-export-as-html t]
12502 ["HTML and Open" org-export-as-html-and-open t]
12503 ; ["OPML" org-export-as-opml nil]
12504 "--"
12505 ["iCalendar this file" org-export-icalendar-this-file t]
12506 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
12507 :active t :keys "C-c C-x C-i"]
12508 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
12509 "--"
12510 ["Option Template" org-insert-export-options-template t]
12511 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
12512 "--"
12513 ("Documentation"
12514 ["Show Version" org-version t]
12515 ["Info Documentation" org-info t])
12516 ("Customize"
12517 ["Browse Org Group" org-customize t]
12518 "--"
12519 ["Build Full Customize Menu" org-create-customize-menu
12520 (fboundp 'customize-menu-create)])
12521 "--"
12522 ["Refresh setup" org-mode-restart t]
12523 ))
12524
12525 (defun org-info (&optional node)
12526 "Read documentation for Org-mode in the info system.
12527 With optional NODE, go directly to that node."
12528 (interactive)
12529 (require 'info)
12530 (Info-goto-node (format "(org)%s" (or node ""))))
12531
12532 (defun org-install-agenda-files-menu ()
12533 (easy-menu-change
12534 '("Org") "File List for Agenda"
12535 (append
12536 (list
12537 ["Edit File List" (customize-variable 'org-agenda-files) t]
12538 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12539 ["Remove Current File from List" org-remove-file t]
12540 ["Cycle through agenda files" org-cycle-agenda-files t]
12541 "--")
12542 (mapcar 'org-file-menu-entry org-agenda-files))))
12543
12544 ;;; Documentation
12545
12546 (defun org-customize ()
12547 "Call the customize function with org as argument."
12548 (interactive)
12549 (customize-browse 'org))
12550
12551 (defun org-create-customize-menu ()
12552 "Create a full customization menu for Org-mode, insert it into the menu."
12553 (interactive)
12554 (if (fboundp 'customize-menu-create)
12555 (progn
12556 (easy-menu-change
12557 '("Org") "Customize"
12558 `(["Browse Org group" org-customize t]
12559 "--"
12560 ,(customize-menu-create 'org)
12561 ["Set" Custom-set t]
12562 ["Save" Custom-save t]
12563 ["Reset to Current" Custom-reset-current t]
12564 ["Reset to Saved" Custom-reset-saved t]
12565 ["Reset to Standard Settings" Custom-reset-standard t]))
12566 (message "\"Org\"-menu now contains full customization menu"))
12567 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12568
12569 ;;; Miscellaneous stuff
12570
12571 (defun org-move-line-down (arg)
12572 "Move the current line down. With prefix argument, move it past ARG lines."
12573 (interactive "p")
12574 (let ((col (current-column))
12575 beg end pos)
12576 (beginning-of-line 1) (setq beg (point))
12577 (beginning-of-line 2) (setq end (point))
12578 (beginning-of-line (+ 1 arg))
12579 (setq pos (move-marker (make-marker) (point)))
12580 (insert (delete-and-extract-region beg end))
12581 (goto-char pos)
12582 (move-to-column col)))
12583
12584 (defun org-move-line-up (arg)
12585 "Move the current line up. With prefix argument, move it past ARG lines."
12586 (interactive "p")
12587 (let ((col (current-column))
12588 beg end pos)
12589 (beginning-of-line 1) (setq beg (point))
12590 (beginning-of-line 2) (setq end (point))
12591 (beginning-of-line (- arg))
12592 (setq pos (move-marker (make-marker) (point)))
12593 (insert (delete-and-extract-region beg end))
12594 (goto-char pos)
12595 (move-to-column col)))
12596
12597 ;; Paragraph filling stuff.
12598 ;; We want this to be just right, so use the full arsenal.
12599 ;; FIXME: This very likely does not work correctly for XEmacs, because the
12600 ;; filladapt package works slightly differently.
12601
12602 (defun org-set-autofill-regexps ()
12603 (interactive)
12604 ;; In the paragraph separator we include headlines, because filling
12605 ;; text in a line directly attached to a headline would otherwise
12606 ;; fill the headline as well.
12607 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
12608 ;; The paragraph starter includes hand-formatted lists.
12609 (set (make-local-variable 'paragraph-start)
12610 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
12611 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
12612 ;; But only if the user has not turned off tables or fixed-width regions
12613 (set (make-local-variable 'auto-fill-inhibit-regexp)
12614 (concat "\\*\\|#"
12615 (if (or org-enable-table-editor org-enable-fixed-width-editor)
12616 (concat
12617 "\\|[ \t]*["
12618 (if org-enable-table-editor "|" "")
12619 (if org-enable-fixed-width-editor ":" "")
12620 "]"))))
12621 ;; We use our own fill-paragraph function, to make sure that tables
12622 ;; and fixed-width regions are not wrapped. That function will pass
12623 ;; through to `fill-paragraph' when appropriate.
12624 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
12625 ;; Adaptive filling: To get full control, first make sure that
12626 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
12627 (setq adaptive-fill-regexp "\000")
12628 (setq adaptive-fill-function 'org-adaptive-fill-function))
12629
12630 (defun org-fill-paragraph (&optional justify)
12631 "Re-align a table, pass through to fill-paragraph if no table."
12632 (let ((table-p (org-at-table-p))
12633 (table.el-p (org-at-table.el-p)))
12634 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
12635 (table.el-p t) ; skip table.el tables
12636 (table-p (org-table-align) t) ; align org-mode tables
12637 (t nil)))) ; call paragraph-fill
12638
12639 ;; For reference, this is the default value of adaptive-fill-regexp
12640 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
12641
12642 (defun org-adaptive-fill-function ()
12643 "Return a fill prefix for org-mode files.
12644 In particular, this makes sure hanging paragraphs for hand-formatted lists
12645 work correctly."
12646 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
12647 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
12648
12649 ;; Functions needed for Emacs/XEmacs region compatibility
12650
12651 (defun org-add-hook (hook function &optional append local)
12652 "Add-hook, compatible with both Emacsen."
12653 (if (and local org-xemacs-p)
12654 (add-local-hook hook function append)
12655 (add-hook hook function append local)))
12656
12657 (defun org-region-active-p ()
12658 "Is `transient-mark-mode' on and the region active?
12659 Works on both Emacs and XEmacs."
12660 (if org-ignore-region
12661 nil
12662 (if org-xemacs-p
12663 (and zmacs-regions (region-active-p))
12664 (and transient-mark-mode mark-active))))
12665
12666 (defun org-add-to-invisibility-spec (arg)
12667 "Add elements to `buffer-invisibility-spec'.
12668 See documentation for `buffer-invisibility-spec' for the kind of elements
12669 that can be added."
12670 (cond
12671 ((fboundp 'add-to-invisibility-spec)
12672 (add-to-invisibility-spec arg))
12673 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
12674 (setq buffer-invisibility-spec (list arg)))
12675 (t
12676 (setq buffer-invisibility-spec
12677 (cons arg buffer-invisibility-spec)))))
12678
12679 (defun org-remove-from-invisibility-spec (arg)
12680 "Remove elements from `buffer-invisibility-spec'."
12681 (if (fboundp 'remove-from-invisibility-spec)
12682 (remove-from-invisibility-spec arg)
12683 (if (consp buffer-invisibility-spec)
12684 (setq buffer-invisibility-spec
12685 (delete arg buffer-invisibility-spec)))))
12686
12687 (defun org-in-invisibility-spec-p (arg)
12688 "Is ARG a member of `buffer-invisibility-spec'?"
12689 (if (consp buffer-invisibility-spec)
12690 (member arg buffer-invisibility-spec)
12691 nil))
12692
12693 (defun org-image-file-name-regexp ()
12694 "Return regexp matching the file names of images."
12695 (if (fboundp 'image-file-name-regexp)
12696 (image-file-name-regexp)
12697 (let ((image-file-name-extensions
12698 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
12699 "xbm" "xpm" "pbm" "pgm" "ppm")))
12700 (concat "\\."
12701 (regexp-opt (nconc (mapcar 'upcase
12702 image-file-name-extensions)
12703 image-file-name-extensions)
12704 t)
12705 "\\'"))))
12706
12707 ;; Functions needed for compatibility with old outline.el.
12708
12709 ;; Programming for the old outline.el (that uses selective display
12710 ;; instead of `invisible' text properties) is a nightmare, mostly
12711 ;; because regular expressions can no longer be anchored at
12712 ;; beginning/end of line. Therefore a number of function need special
12713 ;; treatment when the old outline.el is being used.
12714
12715 ;; The following functions capture almost the entire compatibility code
12716 ;; between the different versions of outline-mode. The only other
12717 ;; places where this is important are the font-lock-keywords, and in
12718 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
12719
12720 ;; C-a should go to the beginning of a *visible* line, also in the
12721 ;; new outline.el. I guess this should be patched into Emacs?
12722 (defun org-beginning-of-line ()
12723 "Go to the beginning of the current line. If that is invisible, continue
12724 to a visible line beginning. This makes the function of C-a more intuitive."
12725 (interactive)
12726 (beginning-of-line 1)
12727 (if (bobp)
12728 nil
12729 (backward-char 1)
12730 (if (org-invisible-p)
12731 (while (and (not (bobp)) (org-invisible-p))
12732 (backward-char 1)
12733 (beginning-of-line 1))
12734 (forward-char 1))))
12735
12736 (when org-noutline-p
12737 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
12738 ;; FIXME: should I use substitute-key-definition to reach other bindings
12739 ;; of beginning-of-line?
12740
12741 (defun org-invisible-p ()
12742 "Check if point is at a character currently not visible."
12743 (if org-noutline-p
12744 ;; Early versions of noutline don't have `outline-invisible-p'.
12745 (if (fboundp 'outline-invisible-p)
12746 (outline-invisible-p)
12747 (get-char-property (point) 'invisible))
12748 (save-excursion
12749 (skip-chars-backward "^\r\n")
12750 (equal (char-before) ?\r))))
12751
12752 (defun org-invisible-p2 ()
12753 "Check if point is at a character currently not visible."
12754 (save-excursion
12755 (if org-noutline-p
12756 (progn
12757 (if (and (eolp) (not (bobp))) (backward-char 1))
12758 ;; Early versions of noutline don't have `outline-invisible-p'.
12759 (if (fboundp 'outline-invisible-p)
12760 (outline-invisible-p)
12761 (get-char-property (point) 'invisible)))
12762 (skip-chars-backward "^\r\n")
12763 (equal (char-before) ?\r))))
12764
12765 (defun org-back-to-heading (&optional invisible-ok)
12766 "Move to previous heading line, or beg of this line if it's a heading.
12767 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
12768 (if org-noutline-p
12769 (outline-back-to-heading invisible-ok)
12770 (if (and (memq (char-before) '(?\n ?\r))
12771 (looking-at outline-regexp))
12772 t
12773 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
12774 outline-regexp)
12775 nil t)
12776 (if invisible-ok
12777 (progn (goto-char (match-end 1))
12778 (looking-at outline-regexp)))
12779 (error "Before first heading")))))
12780
12781 (defun org-on-heading-p (&optional invisible-ok)
12782 "Return t if point is on a (visible) heading line.
12783 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12784 (if org-noutline-p
12785 (outline-on-heading-p 'invisible-ok)
12786 (save-excursion
12787 (skip-chars-backward "^\n\r")
12788 (and (looking-at outline-regexp)
12789 (or invisible-ok
12790 (bobp)
12791 (equal (char-before) ?\n))))))
12792
12793 (defun org-on-target-p ()
12794 (let ((pos (point)))
12795 (save-excursion
12796 (skip-chars-forward "<")
12797 (and (re-search-backward "<<" nil t)
12798 (or (looking-at org-target-regexp)
12799 (looking-at org-radio-target-regexp))
12800 (<= (match-beginning 0) pos)
12801 (>= (match-end 0) pos)))))
12802
12803 (defun org-up-heading-all (arg)
12804 "Move to the heading line of which the present line is a subheading.
12805 This function considers both visible and invisible heading lines.
12806 With argument, move up ARG levels."
12807 (if org-noutline-p
12808 (if (fboundp 'outline-up-heading-all)
12809 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12810 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12811 (org-back-to-heading t)
12812 (looking-at outline-regexp)
12813 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12814 (error "Cannot move up %d levels" arg)
12815 (re-search-backward
12816 (concat "[\n\r]" (regexp-quote
12817 (make-string (- (match-end 0) (match-beginning 0) arg)
12818 ?*))
12819 "[^*]"))
12820 (forward-char 1))))
12821
12822 (defun org-show-hidden-entry ()
12823 "Show an entry where even the heading is hidden."
12824 (save-excursion
12825 (if (not org-noutline-p)
12826 (progn
12827 (org-back-to-heading t)
12828 (org-flag-heading nil)))
12829 (org-show-entry)))
12830
12831 (defun org-check-occur-regexp (regexp)
12832 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12833 Of course, only for the old outline mode."
12834 (if org-noutline-p
12835 regexp
12836 (if (string-match "^\\^" regexp)
12837 (concat "[\n\r]" (substring regexp 1))
12838 regexp)))
12839
12840 (defun org-flag-heading (flag &optional entry)
12841 "Flag the current heading. FLAG non-nil means make invisible.
12842 When ENTRY is non-nil, show the entire entry."
12843 (save-excursion
12844 (org-back-to-heading t)
12845 (if (not org-noutline-p)
12846 ;; Make the current headline visible
12847 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12848 ;; Check if we should show the entire entry
12849 (if entry
12850 (progn
12851 (org-show-entry)
12852 (save-excursion ;; FIXME: Is this the fix for points in the -|
12853 ;; middle of text? |
12854 (and (outline-next-heading) ;; |
12855 (org-flag-heading nil)))) ; show the next heading _|
12856 (outline-flag-region (max 1 (1- (point)))
12857 (save-excursion (outline-end-of-heading) (point))
12858 (if org-noutline-p
12859 flag
12860 (if flag ?\r ?\n))))))
12861
12862 (defun org-end-of-subtree (&optional invisible-OK)
12863 ;; This is an exact copy of the original function, but it uses
12864 ;; `org-back-to-heading', to make it work also in invisible
12865 ;; trees. And is uses an invisible-OK argument.
12866 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
12867 (org-back-to-heading invisible-OK)
12868 (let ((first t)
12869 (level (funcall outline-level)))
12870 (while (and (not (eobp))
12871 (or first (> (funcall outline-level) level)))
12872 (setq first nil)
12873 (outline-next-heading))
12874 (if (memq (preceding-char) '(?\n ?\^M))
12875 (progn
12876 ;; Go to end of line before heading
12877 (forward-char -1)
12878 (if (memq (preceding-char) '(?\n ?\^M))
12879 ;; leave blank line before heading
12880 (forward-char -1))))))
12881
12882 (defun org-show-subtree ()
12883 "Show everything after this heading at deeper levels."
12884 (outline-flag-region
12885 (point)
12886 (save-excursion
12887 (outline-end-of-subtree) (outline-next-heading) (point))
12888 (if org-noutline-p nil ?\n)))
12889
12890 (defun org-show-entry ()
12891 "Show the body directly following this heading.
12892 Show the heading too, if it is currently invisible."
12893 (interactive)
12894 (save-excursion
12895 (org-back-to-heading t)
12896 (outline-flag-region
12897 (1- (point))
12898 (save-excursion
12899 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12900 (or (match-beginning 1) (point-max)))
12901 (if org-noutline-p nil ?\n))))
12902
12903
12904 (defun org-make-options-regexp (kwds)
12905 "Make a regular expression for keyword lines."
12906 (concat
12907 (if org-noutline-p "^" "[\n\r]")
12908 "#?[ \t]*\\+\\("
12909 (mapconcat 'regexp-quote kwds "\\|")
12910 "\\):[ \t]*"
12911 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12912
12913 ;; Make `bookmark-jump' show the jump location if it was hidden.
12914 (eval-after-load "bookmark"
12915 '(if (boundp 'bookmark-after-jump-hook)
12916 ;; We can use the hook
12917 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12918 ;; Hook not available, use advice
12919 (defadvice bookmark-jump (after org-make-visible activate)
12920 "Make the position visible."
12921 (org-bookmark-jump-unhide))))
12922
12923 (defun org-bookmark-jump-unhide ()
12924 "Unhide the current position, to show the bookmark location."
12925 (and (eq major-mode 'org-mode)
12926 (or (org-invisible-p)
12927 (save-excursion (goto-char (max (point-min) (1- (point))))
12928 (org-invisible-p)))
12929 (org-show-hierarchy-above)))
12930
12931 ;;; Finish up
12932
12933 (provide 'org)
12934
12935 (run-hooks 'org-load-hook)
12936
12937 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12938 ;;; org.el ends here