]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-link-search): Avoid self-matching of links, allow
[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.09
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.09
85 ;; - Bug fixes.
86 ;; - Small improvements to font-lock support.
87 ;; - MHE support finalized.
88 ;;
89 ;; Version 4.08
90 ;; - Bug fixes.
91 ;; - Improved MHE support
92 ;;
93 ;; Version 4.07
94 ;; - Bug fixes.
95 ;; - Leading stars in headlines can be hidden, so make the outline look
96 ;; cleaner.
97 ;; - Mouse-1 can be used to follow links.
98 ;;
99 ;; Version 4.06
100 ;; - HTML exporter treats targeted internal links.
101 ;; - Bug fixes.
102 ;;
103 ;; Version 4.05
104 ;; - Changes to internal link system (thanks to David Wainberg for ideas).
105 ;; - in-file links: [[Search String]] instead of <file:::Search String>
106 ;; - automatic links to "radio targets".
107 ;; - CamelCase not longer active by default, configure org-activate-camels
108 ;; if you want to turn it back on.
109 ;; - After following a link, `C-c &' jumps back to it.
110 ;; - MH-E link support (thanks to Thomas Baumann).
111 ;; - Special table lines are no longer exported.
112 ;; - Bug fixes and minor improvements.
113 ;;
114 ;; Version 4.04
115 ;; - Cleanup tags display in agenda.
116 ;; - Bug fixes.
117 ;;
118 ;; Version 4.03
119 ;; - Table alignment fixed for use with wide characters.
120 ;; - `C-c -' leaves cursor in current table line.
121 ;; - The current TAG can be incorporated into the agenda prefix.
122 ;; See option `org-agenda-prefix-format' for details.
123 ;;
124 ;; Version 4.02
125 ;; - Minor bug fixes and improvements around tag searches.
126 ;; - XEmacs compatibility fixes.
127 ;;
128 ;; Version 4.01
129 ;; - Tags can also be set remotely from agenda buffer.
130 ;; - Boolean logic for tag searches.
131 ;; - Additional agenda commands can be configured through the variable
132 ;; `org-agenda-custom-commands'.
133 ;; - Minor bug fixes.
134 ;;
135 ;;; Code:
136
137 (eval-when-compile (require 'cl) (require 'calendar))
138 (require 'outline)
139 (require 'time-date)
140 (require 'easymenu)
141
142 (defvar calc-embedded-close-formula)
143 (defvar calc-embedded-open-formula)
144 (defvar font-lock-unfontify-region-function)
145
146 ;;; Customization variables
147
148 (defvar org-version "4.09"
149 "The version number of the file org.el.")
150 (defun org-version ()
151 (interactive)
152 (message "Org-mode version %s" org-version))
153
154 ;; The following two constants are for compatibility with different Emacs
155 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
156 ;; The compatibility code in org.el is based on these two constants.
157 (defconst org-xemacs-p (featurep 'xemacs)
158 "Are we running XEmacs?")
159 (defconst org-noutline-p (featurep 'noutline)
160 "Are we using the new outline mode?")
161
162 (defgroup org nil
163 "Outline-based notes management and organizer."
164 :tag "Org"
165 :group 'outlines
166 :group 'hypermedia
167 :group 'calendar)
168
169 (defgroup org-startup nil
170 "Options concerning startup of Org-mode."
171 :tag "Org Startup"
172 :group 'org)
173
174 (defcustom org-CUA-compatible nil
175 "Non-nil means use alternative key bindings for S-<cursor movement>.
176 Org-mode used S-<cursor movement> for changing timestamps and priorities.
177 S-<cursor movement> is also used for example by `CUA-mode' to select text.
178 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
179 alternative bindings. Setting this variable to t will replace the following
180 keys both in Org-mode and in the Org-agenda buffer.
181
182 S-RET -> C-S-RET
183 S-up -> M-p
184 S-down -> M-n
185 S-left -> M--
186 S-right -> M-+
187
188 If you do not like the alternative keys, take a look at the variable
189 `org-disputed-keys'.
190
191 This option is only relevant at load-time of Org-mode. Changing it requires
192 a restart of Emacs to become effective."
193 :group 'org-startup
194 :type 'boolean)
195
196 (defvar org-disputed-keys
197 '((S-up [(shift up)] [(meta ?p)])
198 (S-down [(shift down)] [(meta ?n)])
199 (S-left [(shift left)] [(meta ?-)])
200 (S-right [(shift right)] [(meta ?+)])
201 (S-return [(shift return)] [(control shift return)]))
202 "Keys for which Org-mode and other modes compete.
203 This is an alist, cars are symbols for lookup, 1st element is the default key,
204 second element will be used when `org-CUA-compatible' is t.")
205
206 (defun org-key (key)
207 "Select a key according to `org-CUA-compatible'."
208 (nth (if org-CUA-compatible 2 1)
209 (or (assq key org-disputed-keys)
210 (error "Invalid Key %s in `org-key'" key))))
211
212 (defcustom org-startup-folded t
213 "Non-nil means, entering Org-mode will switch to OVERVIEW.
214 This can also be configured on a per-file basis by adding one of
215 the following lines anywhere in the buffer:
216
217 #+STARTUP: fold
218 #+STARTUP: nofold
219 #+STARTUP: content"
220 :group 'org-startup
221 :type '(choice
222 (const :tag "nofold: show all" nil)
223 (const :tag "fold: overview" t)
224 (const :tag "content: all headlines" content)))
225
226 (defcustom org-startup-truncated t
227 "Non-nil means, entering Org-mode will set `truncate-lines'.
228 This is useful since some lines containing links can be very long and
229 uninteresting. Also tables look terrible when wrapped."
230 :group 'org-startup
231 :type 'boolean)
232
233 (defcustom org-startup-with-deadline-check nil
234 "Non-nil means, entering Org-mode will run the deadline check.
235 This means, if you start editing an org file, you will get an
236 immediate reminder of any due deadlines.
237 This can also be configured on a per-file basis by adding one of
238 the following lines anywhere in the buffer:
239
240 #+STARTUP: dlcheck
241 #+STARTUP: nodlcheck"
242 :group 'org-startup
243 :type 'boolean)
244
245 (defcustom org-insert-mode-line-in-empty-file nil
246 "Non-nil means insert the first line setting Org-mode in empty files.
247 When the function `org-mode' is called interactively in an empty file, this
248 normally means that the file name does not automatically trigger Org-mode.
249 To ensure that the file will always be in Org-mode in the future, a
250 line enforcing Org-mode will be inserted into the buffer, if this option
251 has been set."
252 :group 'org-startup
253 :type 'boolean)
254
255 (defgroup org-keywords nil
256 "Options concerning TODO items in Org-mode."
257 :tag "Org Keywords"
258 :group 'org)
259
260 (defcustom org-todo-keywords '("TODO" "DONE")
261 "List of TODO entry keywords.
262 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
263 considered to mean that the entry is \"done\". All the other mean that
264 action is required, and will make the entry show up in todo lists, diaries
265 etc.
266 The command \\[org-todo] cycles an entry through these states, and an
267 additional state where no keyword is present. For details about this
268 cycling, see also the variable `org-todo-interpretation'
269 Changes become only effective after restarting Emacs."
270 :group 'org-keywords
271 :type '(repeat (string :tag "Keyword")))
272
273 (defcustom org-todo-interpretation 'sequence
274 "Controls how TODO keywords are interpreted.
275 \\<org-mode-map>Possible values are `sequence' and `type'.
276 This variable is only relevant if `org-todo-keywords' contains more than two
277 states. There are two ways how these keywords can be used:
278
279 - As a sequence in the process of working on a TODO item, for example
280 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
281 org-todo-interpretation 'sequence)
282
283 - As different types of TODO items, for example
284 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
285 org-todo-interpretation 'type)
286
287 When the states are interpreted as a sequence, \\[org-todo] always cycles
288 to the next state, in order to walk through all different states. So with
289 \\[org-todo], you turn an empty entry into the state TODO. When you started
290 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
291 later to VERIFY and finally to DONE.
292
293 When the states are interpreted as types, \\[org-todo] still cycles through
294 when it is called several times in direct succession, in order to initially
295 select the type. However, if not called immediately after a previous
296 \\[org-todo], it switches from each type directly to DONE. So with the
297 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
298 RELAXED. If you later return to this entry and press \\[org-todo] again,
299 RELAXED will not be changed REMIND, but directly to DONE.
300
301 You can create a large number of types. To initially select a
302 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
303 type with completion. Of course, you can also type the keyword
304 directly into the buffer. M-TAB completes TODO keywords at the
305 beginning of a headline."
306 :group 'org-keywords
307 :type '(choice (const sequence)
308 (const type)))
309
310 (defcustom org-default-priority ?B
311 "The default priority of TODO items.
312 This is the priority an item get if no explicit priority is given."
313 :group 'org-keywords
314 :type 'character)
315
316 (defcustom org-lowest-priority ?C
317 "The lowest priority of TODO items. A character like ?A, ?B etc."
318 :group 'org-keywords
319 :type 'character)
320
321 (defcustom org-deadline-string "DEADLINE:"
322 "String to mark deadline entries.
323 A deadline is this string, followed by a time stamp. Should be a word,
324 terminated by a colon. You can insert a schedule keyword and
325 a timestamp with \\[org-deadline].
326 Changes become only effective after restarting Emacs."
327 :group 'org-keywords
328 :type 'string)
329
330 (defcustom org-scheduled-string "SCHEDULED:"
331 "String to mark scheduled TODO entries.
332 A schedule is this string, followed by a time stamp. Should be a word,
333 terminated by a colon. You can insert a schedule keyword and
334 a timestamp with \\[org-schedule].
335 Changes become only effective after restarting Emacs."
336 :group 'org-keywords
337 :type 'string)
338
339 (defcustom org-closed-string "CLOSED:"
340 "String used as the prefix for timestamps logging closing a TODO entry."
341 :group 'org-keywords
342 :type 'string)
343
344 (defcustom org-comment-string "COMMENT"
345 "Entries starting with this keyword will never be exported.
346 An entry can be toggled between COMMENT and normal with
347 \\[org-toggle-comment].
348 Changes become only effective after restarting Emacs."
349 :group 'org-keywords
350 :type 'string)
351
352 (defcustom org-quote-string "QUOTE"
353 "Entries starting with this keyword will be exported in fixed-width font.
354 Quoting applies only to the text in the entry following the headline, and does
355 not extend beyond the next headline, even if that is lower level.
356 An entry can be toggled between QUOTE and normal with
357 \\[org-toggle-fixed-width-section]."
358 :group 'org-keywords
359 :type 'string)
360
361 (defcustom org-after-todo-state-change-hook nil
362 "Hook which is run after the state of a TODO item was changed.
363 The new state (a string with a TODO keyword, or nil) is available in the
364 Lisp variable `state'."
365 :group 'org-keywords
366 :type 'hook)
367
368 ;; Variables for pre-computed regular expressions, all buffer local
369 (defvar org-todo-kwd-priority-p nil
370 "Do TODO items have priorities?")
371 (make-variable-buffer-local 'org-todo-kwd-priority-p)
372 (defvar org-todo-kwd-max-priority nil
373 "Maximum priority of TODO items.")
374 (make-variable-buffer-local 'org-todo-kwd-max-priority)
375 (defvar org-ds-keyword-length 12
376 "Maximum length of the Deadline and SCHEDULED keywords.")
377 (make-variable-buffer-local 'org-ds-keyword-length)
378 (defvar org-done-string nil
379 "The last string in `org-todo-keywords', indicating an item is DONE.")
380 (make-variable-buffer-local 'org-done-string)
381 (defvar org-todo-regexp nil
382 "Matches any of the TODO state keywords.")
383 (make-variable-buffer-local 'org-todo-regexp)
384 (defvar org-not-done-regexp nil
385 "Matches any of the TODO state keywords except the last one.")
386 (make-variable-buffer-local 'org-not-done-regexp)
387 (defvar org-todo-line-regexp nil
388 "Matches a headline and puts TODO state into group 2 if present.")
389 (make-variable-buffer-local 'org-todo-line-regexp)
390 (defvar org-nl-done-regexp nil
391 "Matches newline followed by a headline with the DONE keyword.")
392 (make-variable-buffer-local 'org-nl-done-regexp)
393 (defvar org-looking-at-done-regexp nil
394 "Matches the DONE keyword a point.")
395 (make-variable-buffer-local 'org-looking-at-done-regexp)
396 (defvar org-deadline-regexp nil
397 "Matches the DEADLINE keyword.")
398 (make-variable-buffer-local 'org-deadline-regexp)
399 (defvar org-deadline-time-regexp nil
400 "Matches the DEADLINE keyword together with a time stamp.")
401 (make-variable-buffer-local 'org-deadline-time-regexp)
402 (defvar org-deadline-line-regexp nil
403 "Matches the DEADLINE keyword and the rest of the line.")
404 (make-variable-buffer-local 'org-deadline-line-regexp)
405 (defvar org-scheduled-regexp nil
406 "Matches the SCHEDULED keyword.")
407 (make-variable-buffer-local 'org-scheduled-regexp)
408 (defvar org-scheduled-time-regexp nil
409 "Matches the SCHEDULED keyword together with a time stamp.")
410 (make-variable-buffer-local 'org-scheduled-time-regexp)
411
412 (defvar org-category nil
413 "Variable used by org files to set a category for agenda display.
414 Such files should use a file variable to set it, for example
415
416 -*- mode: org; org-category: \"ELisp\"
417
418 or contain a special line
419
420 #+CATEGORY: ELisp
421
422 If the file does not specify a category, then file's base name
423 is used instead.")
424 (make-variable-buffer-local 'org-category)
425
426 (defgroup org-time nil
427 "Options concerning time stamps and deadlines in Org-mode."
428 :tag "Org Time"
429 :group 'org)
430
431 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
432 "Formats for `format-time-string' which are used for time stamps.
433 It is not recommended to change this constant.")
434
435
436 (defcustom org-deadline-warning-days 30
437 "No. of days before expiration during which a deadline becomes active.
438 This variable governs the display in the org file."
439 :group 'org-time
440 :type 'number)
441
442 (defcustom org-popup-calendar-for-date-prompt t
443 "Non-nil means, pop up a calendar when prompting for a date.
444 In the calendar, the date can be selected with mouse-1. However, the
445 minibuffer will also be active, and you can simply enter the date as well.
446 When nil, only the minibuffer will be available."
447 :group 'org-time
448 :type 'number)
449
450 (defcustom org-calendar-follow-timestamp-change t
451 "Non-nil means, make the calendar window follow timestamp changes.
452 When a timestamp is modified and the calendar window is visible, it will be
453 moved to the new date."
454 :group 'org-time
455 :type 'boolean)
456
457 (defcustom org-log-done nil
458 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
459 When the state of an entry is changed from nothing to TODO, remove a previous
460 closing date."
461 :group 'org-time
462 :type 'boolean)
463
464 (defgroup org-agenda nil
465 "Options concerning agenda display Org-mode."
466 :tag "Org Agenda"
467 :group 'org)
468
469 (defcustom org-agenda-files nil
470 "A list of org files for agenda/diary display.
471 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
472 \\[org-remove-file]. You can also use customize to edit the list."
473 :group 'org-agenda
474 :type '(repeat file))
475
476 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
477 "Custom commands for the agenda.
478 These commands will be offered on the splash screen displayed by the
479 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
480
481 key The key (a single char as a string) to be associated with the command.
482 type The command type, any of the following symbols:
483 todo Entries with a specific TODO keyword, in all agenda files.
484 tags Tags match in all agenda files.
485 todo-tree Sparse tree of specific TODO keyword in *current* file.
486 tags-tree Sparse tree with all tags matches in *current* file.
487 occur-tree Occur sparse tree for current file.
488 match What to search for:
489 - a single keyword for TODO keyword searches
490 - a tags match expression for tags searches
491 - a regular expression for occur searches"
492 :group 'org-agenda
493 :type '(repeat
494 (list (string :tag "Key")
495 (choice :tag "Type"
496 (const :tag "Tags search in all agenda files" tags)
497 (const :tag "TODO keyword search in all agenda files" todo)
498 (const :tag "Tags sparse tree in current buffer" tags-tree)
499 (const :tag "TODO keyword tree in current buffer" todo-tree)
500 (const :tag "Occur tree in current buffer" occur-tree))
501 (string :tag "Match"))))
502
503 (defcustom org-select-timeline-window t
504 "Non-nil means, after creating a timeline, move cursor into Timeline window.
505 When nil, cursor will remain in the current window."
506 :group 'org-agenda
507 :type 'boolean)
508
509 (defcustom org-select-agenda-window t
510 "Non-nil means, after creating an agenda, move cursor into Agenda window.
511 When nil, cursor will remain in the current window."
512 :group 'org-agenda
513 :type 'boolean)
514
515 (defcustom org-fit-agenda-window t
516 "Non-nil means, change window size of agenda to fit content."
517 :group 'org-agenda
518 :type 'boolean)
519
520 (defcustom org-agenda-show-all-dates t
521 "Non-nil means, `org-agenda' shows every day in the selected range.
522 When nil, only the days which actually have entries are shown."
523 :group 'org-agenda
524 :type 'boolean)
525
526 ;; FIXME: First day of month works only for current month because it would
527 ;; require a variable ndays treatment.
528 (defcustom org-agenda-start-on-weekday 1
529 "Non-nil means, start the overview always on the specified weekday.
530 0 Denotes Sunday, 1 denotes Monday etc.
531 When nil, always start on the current day."
532 :group 'org-agenda
533 :type '(choice (const :tag "Today" nil)
534 (const :tag "First day of month" t)
535 (number :tag "Weekday No.")))
536
537 (defcustom org-agenda-ndays 7
538 "Number of days to include in overview display."
539 :group 'org-agenda
540 :type 'number)
541
542 (defcustom org-agenda-include-all-todo t
543 "Non-nil means, the agenda will always contain all TODO entries.
544 When nil, date-less entries will only be shown if `org-agenda' is called
545 with a prefix argument.
546 When non-nil, the TODO entries will be listed at the top of the agenda, before
547 the entries for specific days."
548 :group 'org-agenda
549 :type 'boolean)
550
551 (defcustom org-agenda-include-diary nil
552 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
553 :group 'org-agenda
554 :type 'boolean)
555
556 (defcustom org-calendar-to-agenda-key [?c]
557 "The key to be installed in `calendar-mode-map' for switching to the agenda.
558 The command `org-calendar-goto-agenda' will be bound to this key. The
559 default is the character `c' because then `c' can be used to switch back and
560 forth between agenda and calendar."
561 :group 'org-agenda
562 :type 'sexp)
563
564 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
565 "Sorting structure for the agenda items of a single day.
566 This is a list of symbols which will be used in sequence to determine
567 if an entry should be listed before another entry. The following
568 symbols are recognized:
569
570 time-up Put entries with time-of-day indications first, early first
571 time-down Put entries with time-of-day indications first, late first
572 category-keep Keep the default order of categories, corresponding to the
573 sequence in `org-agenda-files'.
574 category-up Sort alphabetically by category, A-Z.
575 category-down Sort alphabetically by category, Z-A.
576 priority-up Sort numerically by priority, high priority last.
577 priority-down Sort numerically by priority, high priority first.
578
579 The different possibilities will be tried in sequence, and testing stops
580 if one comparison returns a \"not-equal\". For example, the default
581 '(time-up category-keep priority-down)
582 means: Pull out all entries having a specified time of day and sort them,
583 in order to make a time schedule for the current day the first thing in the
584 agenda listing for the day. Of the entries without a time indication, keep
585 the grouped in categories, don't sort the categories, but keep them in
586 the sequence given in `org-agenda-files'. Within each category sort by
587 priority.
588
589 Leaving out `category-keep' would mean that items will be sorted across
590 categories by priority."
591 :group 'org-agenda
592 :type '(repeat
593 (choice
594 (const time-up)
595 (const time-down)
596 (const category-keep)
597 (const category-up)
598 (const category-down)
599 (const priority-up)
600 (const priority-down))))
601
602 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
603 "Format specification for the prefix of items in the agenda buffer.
604 This format works similar to a printf format, with the following meaning:
605
606 %c the category of the item, \"Diary\" for entries from the diary, or
607 as given by the CATEGORY keyword or derived from the file name.
608 %T the first tag of the item.
609 %t the time-of-day specification if one applies to the entry, in the
610 format HH:MM
611 %s Scheduling/Deadline information, a short string
612
613 All specifiers work basically like the standard `%s' of printf, but may
614 contain two additional characters: A question mark just after the `%' and
615 a whitespace/punctuation character just before the final letter.
616
617 If the first character after `%' is a question mark, the entire field
618 will only be included if the corresponding value applies to the
619 current entry. This is useful for fields which should have fixed
620 width when present, but zero width when absent. For example,
621 \"%?-12t\" will result in a 12 character time field if a time of the
622 day is specified, but will completely disappear in entries which do
623 not contain a time.
624
625 If there is punctuation or whitespace character just before the final
626 format letter, this character will be appended to the field value if
627 the value is not empty. For example, the format \"%-12:c\" leads to
628 \"Diary: \" if the category is \"Diary\". If the category were be
629 empty, no additional colon would be interted.
630
631 The default value of this option is \" %-12:c%?-12t% s\", meaning:
632 - Indent the line with two space characters
633 - Give the category in a 12 chars wide field, padded with whitespace on
634 the right (because of `-'). Append a colon if there is a category
635 (because of `:').
636 - If there is a time-of-day, put it into a 12 chars wide field. If no
637 time, don't put in an empty field, just skip it (because of '?').
638 - Finally, put the scheduling information and append a whitespace.
639
640 As another example, if you don't want the time-of-day of entries in
641 the prefix, you could use:
642
643 (setq org-agenda-prefix-format \" %-11:c% s\")
644
645 See also the variables `org-agenda-remove-times-when-in-prefix' and
646 `org-agenda-remove-tags-when-in-prefix'."
647 :type 'string
648 :group 'org-agenda)
649
650 (defcustom org-timeline-prefix-format " % s"
651 "Like `org-agenda-prefix-format', but for the timeline of a single file."
652 :type 'string
653 :group 'org-agenda)
654
655 (defvar org-prefix-format-compiled nil
656 "The compiled version of the most recently used prefix format.
657 Depending on which command was used last, this may be the compiled version
658 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
659
660 (defcustom org-agenda-use-time-grid t
661 "Non-nil means, show a time grid in the agenda schedule.
662 A time grid is a set of lines for specific times (like every two hours between
663 8:00 and 20:00). The items scheduled for a day at specific times are
664 sorted in between these lines.
665 For details about when the grid will be shown, and what it will look like, see
666 the variable `org-agenda-time-grid'."
667 :group 'org-agenda
668 :type 'boolean)
669
670 (defcustom org-agenda-time-grid
671 '((daily today require-timed)
672 "----------------"
673 (800 1000 1200 1400 1600 1800 2000))
674
675 "The settings for time grid for agenda display.
676 This is a list of three items. The first item is again a list. It contains
677 symbols specifying conditions when the grid should be displayed:
678
679 daily if the agenda shows a single day
680 weekly if the agenda shows an entire week
681 today show grid on current date, independent of daily/weekly display
682 require-timed show grid only if at least on item has a time specification
683
684 The second item is a string which will be places behing the grid time.
685
686 The third item is a list of integers, indicating the times that should have
687 a grid line."
688 :group 'org-agenda
689 :type
690 '(list
691 (set :greedy t :tag "Grid Display Options"
692 (const :tag "Show grid in single day agenda display" daily)
693 (const :tag "Show grid in weekly agenda display" weekly)
694 (const :tag "Always show grid for today" today)
695 (const :tag "Show grid only if any timed entries are present"
696 require-timed)
697 (const :tag "Skip grid times already present in an entry"
698 remove-match))
699 (string :tag "Grid String")
700 (repeat :tag "Grid Times" (integer :tag "Time"))))
701
702 (defcustom org-agenda-remove-times-when-in-prefix t
703 "Non-nil means, remove duplicate time specifications in agenda items.
704 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
705 time-of-day specification in a headline or diary entry is extracted and
706 placed into the prefix. If this option is non-nil, the original specification
707 \(a timestamp or -range, or just a plain time(range) specification like
708 11:30-4pm) will be removed for agenda display. This makes the agenda less
709 cluttered.
710 The option can be t or nil. It may also be the symbol `beg', indicating
711 that the time should only be removed what it is located at the beginning of
712 the headline/diary entry."
713 :group 'org-agenda
714 :type '(choice
715 (const :tag "Always" t)
716 (const :tag "Never" nil)
717 (const :tag "When at beginning of entry" beg)))
718
719 (defcustom org-sort-agenda-notime-is-late t
720 "Non-nil means, items without time are considered late.
721 This is only relevant for sorting. When t, items which have no explicit
722 time like 15:30 will be considered as 24:01, i.e. later than any items which
723 do have a time. When nil, the default time is before 0:00. You can use this
724 option to decide if the schedule for today should come before or after timeless
725 agenda entries."
726 :group 'org-agenda
727 :type 'boolean)
728
729 (defcustom org-agenda-remove-tags-when-in-prefix nil
730 "Non-nil means, the tags from copy of headline in agenda.
731 When this is the symbol `prefix', only remove tags when
732 `org-agenda-prefix-format' contains a `%T' specifier."
733 :group 'org-agenda
734 :type '(choice
735 (const :tag "Always" t)
736 (const :tag "Never" nil)
737 (const :tag "When prefix format contains %T" prefix)))
738
739 (defgroup org-structure nil
740 "Options concerning structure editing in Org-mode."
741 :tag "Org Structure"
742 :group 'org)
743
744 (defcustom org-cycle-include-plain-lists nil
745 "Non-nil means, include plain lists into visibility cycling.
746 This means that during cycling, plain list items will *temporarily* be
747 interpreted as outline headlines with a level given by 1000+i where i is the
748 indentation of the bullet. In all other operations, plain list items are
749 not seen as headlines. For example, you cannot assign a TODO keyword to
750 such an item."
751 :group 'org-structure
752 :type 'boolean)
753
754 (defcustom org-cycle-emulate-tab t
755 "Where should `org-cycle' emulate TAB.
756 nil Never
757 white Only in completely white lines
758 t Everywhere except in headlines"
759 :group 'org-structure
760 :type '(choice (const :tag "Never" nil)
761 (const :tag "Only in completely white lines" white)
762 (const :tag "Everywhere except in headlines" t)
763 ))
764
765 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
766 "Hook that is run after `org-cycle' has changed the buffer visibility.
767 The function(s) in this hook must accept a single argument which indicates
768 the new state that was set by the most recent `org-cycle' command. The
769 argument is a symbol. After a global state change, it can have the values
770 `overview', `content', or `all'. After a local state change, it can have
771 the values `folded', `children', or `subtree'."
772 :group 'org-structure
773 :type 'hook)
774
775 (defcustom org-highlight-sparse-tree-matches t
776 "Non-nil means, highlight all matches that define a sparse tree.
777 The highlights will automatically disappear the next time the buffer is
778 changed by an edit command."
779 :group 'org-structure
780 :type 'boolean)
781
782 (defcustom org-show-hierarchy-above t
783 "Non-nil means, show full hierarchy when showing a spot in the tree.
784 Turning this off makes sparse trees more compact, but also less clear."
785 :group 'org-structure
786 :type 'boolean)
787
788 (defcustom org-show-following-heading t
789 "Non-nil means, show heading following match in `org-occur'.
790 When doing an `org-occur' it is useful to show the headline which
791 follows the match, even if they do not match the regexp. This makes it
792 easier to edit directly inside the sparse tree. However, if you use
793 `org-occur' mainly as an overview, the following headlines are
794 unnecessary clutter."
795 :group 'org-structure
796 :type 'boolean)
797
798 (defcustom org-occur-hook '(org-first-headline-recenter)
799 "Hook that is run after `org-occur' has constructed a sparse tree.
800 This can be used to recenter the window to show as much of the structure
801 as possible."
802 :group 'org-structure
803 :type 'hook)
804
805 (defcustom org-odd-levels-only nil
806 "Non-nil means, skip even levels and only use odd levels for the outline.
807 This has the effect that two stars are being added/taken away in
808 promotion/demotion commands. It also influences how levels are
809 handled by the exporters.
810 Changing it requires restart of `font-lock-mode' to become effective
811 for fontification also in regions already fontified."
812 :group 'org-structure
813 :group 'org-font-lock
814 :type 'boolean)
815
816 (defcustom org-adapt-indentation t
817 "Non-nil means, adapt indentation when promoting and demoting.
818 When this is set and the *entire* text in an entry is indented, the
819 indentation is increased by one space in a demotion command, and
820 decreased by one in a promotion command. If any line in the entry
821 body starts at column 0, indentation is not changed at all."
822 :group 'org-structure
823 :type 'boolean)
824
825 (defcustom org-plain-list-ordered-item-terminator t
826 "The character that makes a line with leading number an ordered list item.
827 Valid values are ?. and ?\). To get both terminators, use t. While
828 ?. may look nicer, it creates the danger that a line with leading
829 number may be incorrectly interpreted as an item. ?\) therefore is
830 the safe choice."
831 :group 'org-structure
832 :type '(choice (const :tag "dot like in \"2.\"" ?.)
833 (const :tag "paren like in \"2)\"" ?\))
834 (const :tab "both" t)))
835
836 (defcustom org-auto-renumber-ordered-lists t
837 "Non-nil means, automatically renumber ordered plain lists.
838 Renumbering happens when the sequence have been changed with
839 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
840 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
841 :group 'org-structure
842 :type 'boolean)
843
844 (defcustom org-enable-fixed-width-editor t
845 "Non-nil means, lines starting with \":\" are treated as fixed-width.
846 This currently only means, they are never auto-wrapped.
847 When nil, such lines will be treated like ordinary lines.
848 See also the QUOTE keyword."
849 :group 'org-structure
850 :type 'boolean)
851
852 (defcustom org-archive-location "%s_archive::"
853 "The location where subtrees should be archived.
854 This string consists of two parts, separated by a double-colon.
855
856 The first part is a file name - when omitted, archiving happens in the same
857 file. %s will be replaced by the current file name (without directory part).
858 Archiving to a different file is useful to keep archived entries from
859 contributing to the Org-mode Agenda.
860
861 The part after the double colon is a headline. The archived entries will be
862 filed under that headline. When omitted, the subtrees are simply filed away
863 at the end of the file, as top-level entries.
864
865 Here are a few examples:
866 \"%s_archive::\"
867 If the current file is Projects.org, archive in file
868 Projects.org_archive, as top-level trees. This is the default.
869
870 \"::* Archived Tasks\"
871 Archive in the current file, under the top-level headline
872 \"* Archived Tasks\".
873
874 \"~/org/archive.org::\"
875 Archive in file ~/org/archive.org (absolute path), as top-level trees.
876
877 \"basement::** Finished Tasks\"
878 Archive in file ./basement (relative path), as level 3 trees
879 below the level 2 heading \"** Finished Tasks\".
880
881 You may set this option on a per-file basis by adding to the buffer a
882 line like
883
884 #+ARCHIVE: basement::** Finished Tasks"
885 :group 'org-structure
886 :type 'string)
887
888 (defcustom org-archive-mark-done t
889 "Non-nil means, mark archived entries as DONE."
890 :group 'org-structure
891 :type 'boolean)
892
893 (defcustom org-archive-stamp-time t
894 "Non-nil means, add a time stamp to archived entries.
895 The time stamp will be added directly after the TODO state keyword in the
896 first line, so it is probably best to use this in combinations with
897 `org-archive-mark-done'."
898 :group 'org-structure
899 :type 'boolean)
900
901 (defgroup org-tags nil
902 "Options concerning startup of Org-mode."
903 :tag "Org Tags"
904 :group 'org)
905
906 (defcustom org-tags-column 48
907 "The column to which tags should be indented in a headline.
908 If this number is positive, it specifies the column. If it is negative,
909 it means that the tags should be flushright to that column. For example,
910 -79 works well for a normal 80 character screen."
911 :group 'org-tags
912 :type 'integer)
913
914 (defcustom org-auto-align-tags t
915 "Non-nil means, realign tags after pro/demotion of TODO state change.
916 These operations change the length of a headline and therefore shift
917 the tags around. With this options turned on, after each such operation
918 the tags are again aligned to `org-tags-column'."
919 :group 'org-tags
920 :type 'boolean)
921
922 (defcustom org-use-tag-inheritance t
923 "Non-nil means, tags in levels apply also for sublevels.
924 When nil, only the tags directly given in a specific line apply there.
925 If you turn off this option, you very likely want to turn on the
926 companion option `org-tags-match-list-sublevels'."
927 :group 'org-tags
928 :type 'boolean)
929
930 (defcustom org-tags-match-list-sublevels nil
931 "Non-nil means list also sublevels of headlines matching tag search.
932 Because of tag inheritance (see variable `org-use-tag-inheritance'),
933 the sublevels of a headline matching a tag search often also match
934 the same search. Listing all of them can create very long lists.
935 Setting this variable to nil causes subtrees to be skipped.
936 This option is off by default, because inheritance in on. If you turn
937 inheritance off, you very likely want to turn this option on.
938
939 As a special case, if the tag search is restricted to TODO items, the
940 value of this variable is ignored and sublevels are always checked, to
941 make sure all corresponding TODO items find their way into the list."
942 :group 'org-tags
943 :type 'boolean)
944
945 (defvar org-tags-history nil
946 "History of minibuffer reads for tags.")
947 (defvar org-last-tags-completion-table nil
948 "The last used completion table for tags.")
949
950 (defgroup org-link nil
951 "Options concerning links in Org-mode."
952 :tag "Org Link"
953 :group 'org)
954
955 (defcustom org-tab-follows-link nil
956 "Non-nil means, on links TAB will follow the link.
957 Needs to be set before org.el is loaded."
958 :group 'org-link
959 :type 'boolean)
960
961 (defcustom org-return-follows-link nil
962 "Non-nil means, on links RET will follow the link.
963 Needs to be set before org.el is loaded."
964 :group 'org-link
965 :type 'boolean)
966
967 (defcustom org-mark-ring-length 4
968 "Number of different positions to be recorded in the ring
969 Changing this requires a restart of Emacs to work correctly."
970 :group 'org-link
971 :type 'interger)
972
973 (defcustom org-link-format "<%s>"
974 "Default format for linkes in the buffer.
975 This is a format string for printf, %s will be replaced by the link text.
976 If you want to make sure that your link is always properly terminated,
977 include angle brackets into this format, like \"<%s>\". Some people also
978 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
979 :group 'org-link
980 :type '(choice
981 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
982 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
983 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
984 (string :tag "Other" :value "<%s>")))
985
986 (defcustom org-allow-space-in-links t
987 "Non-nil means, file names in links may contain space characters.
988 When nil, it becomes possible to put several links into a line.
989 Note that in tables, a link never extends accross fields, so in a table
990 it is always possible to put several links into a line.
991 Changing this variable requires a restart of Emacs of become effective."
992 :group 'org-link
993 :type 'boolean)
994
995 (defcustom org-radio-targets t
996 "Non-nil means activate text matching a link target.
997 Radio targets are strings in triple angular brackets, like <<<My Target>>>.
998 When this option is set, any occurrence of \"my target\" in normal text
999 becomes a link."
1000 :group 'org-link
1001 :type 'boolean)
1002
1003 (defcustom org-activate-camels nil
1004 "Non-nil means, treat words in CamelCase as in-file links.
1005 Changing this requires restart of Emacs to become effective."
1006 :group 'org-link
1007 :type 'boolean)
1008
1009 (defcustom org-context-in-file-links t
1010 "Non-nil means, file links from `org-store-link' contain context.
1011 A search string will be added to the file name with :: as separator and
1012 used to find the context when the link is activated by the command
1013 `org-open-at-point'.
1014 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1015 negates this setting for the duration of the command."
1016 :group 'org-link
1017 :type 'boolean)
1018
1019 (defcustom org-file-link-context-use-camel-case nil
1020 "Non-nil means, use CamelCase to store a search context in a file link.
1021 When nil, the search string simply consists of the words of the string."
1022 :group 'org-link
1023 :type 'boolean)
1024
1025 (defcustom org-keep-stored-link-after-insertion nil
1026 "Non-nil means, keep link in list for entire session.
1027
1028 The command `org-store-link' adds a link pointing to the current
1029 location to an internal list. These links accumulate during a session.
1030 The command `org-insert-link' can be used to insert links into any
1031 Org-mode file (offering completion for all stored links). When this
1032 option is nil, every link which has been inserted once using \\[org-insert-link]
1033 will be removed from the list, to make completing the unused links
1034 more efficient."
1035 :group 'org-link
1036 :type 'boolean)
1037
1038 (defcustom org-link-frame-setup
1039 '((vm . vm-visit-folder-other-frame)
1040 (gnus . gnus-other-frame)
1041 (file . find-file-other-window))
1042 "Setup the frame configuration for following links.
1043 When following a link with Emacs, it may often be useful to display
1044 this link in another window or frame. This variable can be used to
1045 set this up for the different types of links.
1046 For VM, use any of
1047 `vm-visit-folder'
1048 `vm-visit-folder-other-frame'
1049 For Gnus, use any of
1050 `gnus'
1051 `gnus-other-frame'
1052 For FILE, use any of
1053 `find-file'
1054 `find-file-other-window'
1055 `find-file-other-frame'
1056 For the calendar, use the variable `calendar-setup'.
1057 For BBDB, it is currently only possible to display the matches in
1058 another window."
1059 :group 'org-link
1060 :type '(list
1061 (cons (const vm)
1062 (choice
1063 (const vm-visit-folder)
1064 (const vm-visit-folder-other-window)
1065 (const vm-visit-folder-other-frame)))
1066 (cons (const gnus)
1067 (choice
1068 (const gnus)
1069 (const gnus-other-frame)))
1070 (cons (const file)
1071 (choice
1072 (const find-file)
1073 (const find-file-other-window)
1074 (const find-file-other-frame)))))
1075
1076 (defcustom org-usenet-links-prefer-google nil
1077 "Non-nil means, `org-store-link' will create web links to Google groups.
1078 When nil, Gnus will be used for such links.
1079 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1080 negates this setting for the duration of the command."
1081 :group 'org-link
1082 :type 'boolean)
1083
1084 (defcustom org-open-non-existing-files nil
1085 "Non-nil means, `org-open-file' will open non-existing file.
1086 When nil, an error will be generated."
1087 :group 'org-link
1088 :type 'boolean)
1089
1090 (defcustom org-confirm-shell-links t
1091 "Non-nil means, ask for confirmation before executing shell links.
1092 The default is true, to keep new users from shooting into their own foot."
1093 :group 'org-link
1094 :type 'boolean)
1095
1096 (defconst org-file-apps-defaults-gnu
1097 '((t . mailcap))
1098 "Default file applications on a UNIX or GNU/Linux system.
1099 See `org-file-apps'.")
1100
1101 (defconst org-file-apps-defaults-macosx
1102 '((t . "open %s")
1103 ("ps" . "gv %s")
1104 ("ps.gz" . "gv %s")
1105 ("eps" . "gv %s")
1106 ("eps.gz" . "gv %s")
1107 ("dvi" . "xdvi %s")
1108 ("fig" . "xfig %s"))
1109 "Default file applications on a MacOS X system.
1110 The system \"open\" is known as a default, but we use X11 applications
1111 for some files for which the OS does not have a good default.
1112 See `org-file-apps'.")
1113
1114 (defconst org-file-apps-defaults-windowsnt
1115 '((t . (w32-shell-execute "open" file)))
1116 "Default file applications on a Windows NT system.
1117 The system \"open\" is used for most files.
1118 See `org-file-apps'.")
1119
1120 (defcustom org-file-apps
1121 '(
1122 ("txt" . emacs)
1123 ("tex" . emacs)
1124 ("ltx" . emacs)
1125 ("org" . emacs)
1126 ("el" . emacs)
1127 )
1128 "External applications for opening `file:path' items in a document.
1129 Org-mode uses system defaults for different file types, but
1130 you can use this variable to set the application for a given file
1131 extension. The entries in this list are cons cells with a file extension
1132 and the corresponding command. Possible values for the command are:
1133 `emacs' The file will be visited by the current Emacs process.
1134 `default' Use the default application for this file type.
1135 string A command to be executed by a shell; %s will be replaced
1136 by the path to the file.
1137 sexp A Lisp form which will be evaluated. The file path will
1138 be available in the Lisp variable `file'.
1139 For more examples, see the system specific constants
1140 `org-file-apps-defaults-macosx'
1141 `org-file-apps-defaults-windowsnt'
1142 `org-file-apps-defaults-gnu'."
1143 :group 'org-link
1144 :type '(repeat
1145 (cons (choice :value ""
1146 (string :tag "Extension")
1147 (const :tag "Default for unrecognized files" t)
1148 (const :tag "Links to a directory" directory))
1149 (choice :value ""
1150 (const :tag "Visit with Emacs" emacs)
1151 (const :tag "Use system default" default)
1152 (string :tag "Command")
1153 (sexp :tag "Lisp form")))))
1154
1155 (defcustom org-mhe-search-all-folders nil
1156 "Non-nil means, that the search for the mh-message will be extended to
1157 all folders if the message cannot be found in the folder given in the link.
1158 Searching all folders is very effective with one of the search engines
1159 supported by MH-E, but will be slow with pick."
1160 :group 'org-link
1161 :type 'boolean)
1162
1163 (defgroup org-remember nil
1164 "Options concerning interaction with remember.el."
1165 :tag "Org Remember"
1166 :group 'org)
1167
1168 (defcustom org-directory "~/org"
1169 "Directory with org files.
1170 This directory will be used as default to prompt for org files.
1171 Used by the hooks for remember.el."
1172 :group 'org-remember
1173 :type 'directory)
1174
1175 (defcustom org-default-notes-file "~/.notes"
1176 "Default target for storing notes.
1177 Used by the hooks for remember.el. This can be a string, or nil to mean
1178 the value of `remember-data-file'."
1179 :group 'org-remember
1180 :type '(choice
1181 (const :tag "Default from remember-data-file" nil)
1182 file))
1183
1184 (defcustom org-reverse-note-order nil
1185 "Non-nil means, store new notes at the beginning of a file or entry.
1186 When nil, new notes will be filed to the end of a file or entry."
1187 :group 'org-remember
1188 :type '(choice
1189 (const :tag "Reverse always" t)
1190 (const :tag "Reverse never" nil)
1191 (repeat :tag "By file name regexp"
1192 (cons regexp boolean))))
1193
1194 (defgroup org-table nil
1195 "Options concerning tables in Org-mode."
1196 :tag "Org Table"
1197 :group 'org)
1198
1199 (defcustom org-enable-table-editor 'optimized
1200 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1201 When nil, such lines will be treated like ordinary lines.
1202
1203 When equal to the symbol `optimized', the table editor will be optimized to
1204 do the following:
1205 - Use automatic overwrite mode in front of whitespace in table fields.
1206 This make the structure of the table stay in tact as long as the edited
1207 field does not exceed the column width.
1208 - Minimize the number of realigns. Normally, the table is aligned each time
1209 TAB or RET are pressed to move to another field. With optimization this
1210 happens only if changes to a field might have changed the column width.
1211 Optimization requires replacing the functions `self-insert-command',
1212 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1213 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1214 very good at guessing when a re-align will be necessary, but you can always
1215 force one with \\[org-ctrl-c-ctrl-c].
1216
1217 If you would like to use the optimized version in Org-mode, but the
1218 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1219
1220 This variable can be used to turn on and off the table editor during a session,
1221 but in order to toggle optimization, a restart is required.
1222
1223 See also the variable `org-table-auto-blank-field'."
1224 :group 'org-table
1225 :type '(choice
1226 (const :tag "off" nil)
1227 (const :tag "on" t)
1228 (const :tag "on, optimized" optimized)))
1229
1230 ;; FIXME: We could have a third option which makes it jump only over the first
1231 ;; hline in a table.
1232 (defcustom org-table-tab-jumps-over-hlines t
1233 "Non-nil means, tab in the last column of a table with jump over a hline.
1234 If a horizontal separator line is following the current line,
1235 `org-table-next-field' can either create a new row before that line, or jump
1236 over the line. When this option is nil, a new line will be created before
1237 this line."
1238 :group 'org-table
1239 :type 'boolean)
1240
1241 (defcustom org-table-auto-blank-field t
1242 "Non-nil means, automatically blank table field when starting to type into it.
1243 This only happens when typing immediately after a field motion
1244 command (TAB, S-TAB or RET).
1245 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1246 :group 'org-table
1247 :type 'boolean)
1248
1249 (defcustom org-table-default-size "5x2"
1250 "The default size for newly created tables, Columns x Rows."
1251 :group 'org-table
1252 :type 'string)
1253
1254 (defcustom org-table-automatic-realign t
1255 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1256 When nil, aligning is only done with \\[org-table-align], or after column
1257 removal/insertion."
1258 :group 'org-table
1259 :type 'boolean)
1260
1261 (defcustom org-table-spaces-around-separators '(1 . 1)
1262 "The number of spaces to be placed before and after separators."
1263 :group 'org-table
1264 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1265
1266 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1267 "The number of spaces to be placed before and after separators.
1268 This option applies when the column separators have been made invisible."
1269 :group 'org-table
1270 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1271
1272 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1273 "Regular expression for recognizing numbers in table columns.
1274 If a table column contains mostly numbers, it will be aligned to the
1275 right. If not, it will be aligned to the left.
1276
1277 The default value of this option is a regular expression which allows
1278 anything which looks remotely like a number as used in scientific
1279 context. For example, all of the following will be considered a
1280 number:
1281 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1282
1283 Other options offered by the customize interface are more restrictive."
1284 :group 'org-table
1285 :type '(choice
1286 (const :tag "Positive Integers"
1287 "^[0-9]+$")
1288 (const :tag "Integers"
1289 "^[-+]?[0-9]+$")
1290 (const :tag "Floating Point Numbers"
1291 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1292 (const :tag "Floating Point Number or Integer"
1293 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1294 (const :tag "Exponential, Floating point, Integer"
1295 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1296 (const :tag "Very General Number-Like"
1297 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1298 (string :tag "Regexp:")))
1299
1300 (defcustom org-table-number-fraction 0.5
1301 "Fraction of numbers in a column required to make the column align right.
1302 In a column all non-white fields are considered. If at least this
1303 fraction of fields is matched by `org-table-number-fraction',
1304 alignment to the right border applies."
1305 :group 'org-table
1306 :type 'number)
1307
1308 (defcustom org-export-highlight-first-table-line t
1309 "Non-nil means, highlight the first table line.
1310 In HTML export, this means use <th> instead of <td>.
1311 In tables created with table.el, this applies to the first table line.
1312 In Org-mode tables, all lines before the first horizontal separator
1313 line will be formatted with <th> tags."
1314 :group 'org-table
1315 :type 'boolean)
1316
1317 (defcustom org-table-tab-recognizes-table.el t
1318 "Non-nil means, TAB will automatically notice a table.el table.
1319 When it sees such a table, it moves point into it and - if necessary -
1320 calls `table-recognize-table'."
1321 :group 'org-table
1322 :type 'boolean)
1323
1324 (defgroup org-table-calculation nil
1325 "Options concerning tables in Org-mode."
1326 :tag "Org Table Calculation"
1327 :group 'org)
1328
1329 (defcustom org-table-copy-increment t
1330 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1331 :group 'org-table-calculation
1332 :type 'boolean)
1333
1334 (defcustom org-calc-default-modes
1335 '(calc-internal-prec 12
1336 calc-float-format (float 5)
1337 calc-angle-mode deg
1338 calc-prefer-frac nil
1339 calc-symbolic-mode nil
1340 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1341 calc-display-working-message t
1342 )
1343 "List with Calc mode settings for use in calc-eval for table formulas.
1344 The list must contain alternating symbols (Calc modes variables and values).
1345 Don't remove any of the default settings, just change the values. Org-mode
1346 relies on the variables to be present in the list."
1347 :group 'org-table-calculation
1348 :type 'plist)
1349
1350 (defcustom org-table-formula-evaluate-inline t
1351 "Non-nil means, TAB and RET evaluate a formula in current table field.
1352 If the current field starts with an equal sign, it is assumed to be a formula
1353 which should be evaluated as described in the manual and in the documentation
1354 string of the command `org-table-eval-formula'. This feature requires the
1355 Emacs calc package.
1356 When this variable is nil, formula calculation is only available through
1357 the command \\[org-table-eval-formula]."
1358 :group 'org-table-calculation
1359 :type 'boolean)
1360
1361
1362 (defcustom org-table-formula-use-constants t
1363 "Non-nil means, interpret constants in formulas in tables.
1364 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1365 by the value given in `org-table-formula-constants', or by a value obtained
1366 from the `constants.el' package."
1367 :group 'org-table-calculation
1368 :type 'boolean)
1369
1370 (defcustom org-table-formula-constants nil
1371 "Alist with constant names and values, for use in table formulas.
1372 The car of each element is a name of a constant, without the `$' before it.
1373 The cdr is the value as a string. For example, if you'd like to use the
1374 speed of light in a formula, you would configure
1375
1376 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1377
1378 and then use it in an equation like `$1*$c'."
1379 :group 'org-table-calculation
1380 :type '(repeat
1381 (cons (string :tag "name")
1382 (string :tag "value"))))
1383
1384 (defcustom org-table-formula-numbers-only nil
1385 "Non-nil means, calculate only with numbers in table formulas.
1386 Then all input fields will be converted to a number, and the result
1387 must also be a number. When nil, calc's full potential is available
1388 in table calculations, including symbolics etc."
1389 :group 'org-table-calculation
1390 :type 'boolean)
1391
1392 (defcustom org-table-allow-automatic-line-recalculation t
1393 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1394 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1395 :group 'org-table-calculation
1396 :type 'boolean)
1397
1398 (defgroup org-export nil
1399 "Options for exporting org-listings."
1400 :tag "Org Export"
1401 :group 'org)
1402
1403 (defcustom org-export-language-setup
1404 '(("en" "Author" "Date" "Table of Contents")
1405 ("da" "Ophavsmand" "Dato" "Indhold")
1406 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1407 ("es" "Autor" "Fecha" "\xccndice")
1408 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1409 ("it" "Autore" "Data" "Indice")
1410 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1411 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1412 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1413 "Terms used in export text, translated to different languages.
1414 Use the variable `org-export-default-language' to set the language,
1415 or use the +OPTION lines for a per-file setting."
1416 :group 'org-export
1417 :type '(repeat
1418 (list
1419 (string :tag "HTML language tag")
1420 (string :tag "Author")
1421 (string :tag "Date")
1422 (string :tag "Table of Contents"))))
1423
1424 (defcustom org-export-default-language "en"
1425 "The default language of HTML export, as a string.
1426 This should have an association in `org-export-language-setup'."
1427 :group 'org-export
1428 :type 'string)
1429
1430 (defcustom org-export-html-style
1431 "<style type=\"text/css\">
1432 html {
1433 font-family: Times, serif;
1434 font-size: 12pt;
1435 }
1436 .title { text-align: center; }
1437 .todo, .deadline { color: red; }
1438 .done { color: green; }
1439 .target { background-color: lavender; }
1440 pre {
1441 border: 1pt solid #AEBDCC;
1442 background-color: #F3F5F7;
1443 padding: 5pt;
1444 font-family: courier, monospace;
1445 }
1446 table { border-collapse: collapse; }
1447 td, th {
1448 vertical-align: top;
1449 border: 1pt solid #ADB9CC;
1450 }
1451 </style>"
1452 "The default style specification for exported HTML files.
1453 Since there are different ways of setting style information, this variable
1454 needs to contain the full HTML structure to provide a style, including the
1455 surrounding HTML tags. The style specifications should include definitions
1456 for new classes todo, done, title, and deadline. For example, legal values
1457 would be:
1458
1459 <style type=\"text/css\">
1460 p { font-weight: normal; color: gray; }
1461 h1 { color: black; }
1462 .title { text-align: center; }
1463 .todo, .deadline { color: red; }
1464 .done { color: green; }
1465 </style>
1466
1467 or, if you want to keep the style in a file,
1468
1469 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1470
1471 As the value of this option simply gets inserted into the HTML <head> header,
1472 you can \"misuse\" it to add arbitrary text to the header."
1473 :group 'org-export
1474 :type 'string)
1475
1476 (defcustom org-export-headline-levels 3
1477 "The last level which is still exported as a headline.
1478 Inferior levels will produce itemize lists when exported.
1479 Note that a numeric prefix argument to an exporter function overrides
1480 this setting.
1481
1482 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1483 :group 'org-export
1484 :type 'number)
1485
1486 (defcustom org-export-with-section-numbers t
1487 "Non-nil means, add section numbers to headlines when exporting.
1488
1489 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1490 :group 'org-export
1491 :type 'boolean)
1492
1493 (defcustom org-export-with-toc t
1494 "Non-nil means, create a table of contents in exported files.
1495 The TOC contains headlines with levels up to`org-export-headline-levels'.
1496
1497 Headlines which contain any TODO items will be marked with \"(*)\" in
1498 ASCII export, and with red color in HTML output.
1499
1500 In HTML output, the TOC will be clickable.
1501
1502 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1503 :group 'org-export
1504 :type 'boolean)
1505
1506 (defcustom org-export-plain-list-max-depth 20
1507 "Maximum depth of hand-formatted lists in HTML export.
1508
1509 Org-mode parses hand-formatted enumeration and bullet lists and
1510 transforms them to HTML open export. Different indentation of the
1511 bullet or number indicates different list nesting levels. To avoid
1512 confusion, only a single level is allowed by default. When this is
1513 larger than 1, deeper indentation leads to deeper list nesting. For
1514 example, the default value of 3 allows the following list to be
1515 formatted correctly in HTML:
1516
1517 * Fruit
1518 - Apple
1519 - Banana
1520 1. from Africa
1521 2. from South America
1522 - Pineapple
1523 * Bread
1524 * Dairy products"
1525 :group 'org-export
1526 :type 'integer)
1527
1528 (defcustom org-export-preserve-breaks nil
1529 "Non-nil means, preserve all line breaks when exporting.
1530 Normally, in HTML output paragraphs will be reformatted. In ASCII
1531 export, line breaks will always be preserved, regardless of this variable.
1532
1533 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1534 :group 'org-export
1535 :type 'boolean)
1536
1537 (defcustom org-export-html-inline-images t
1538 "Non-nil means, inline images into exported HTML pages.
1539 The link will still be to the original location of the image file.
1540 So if you are moving the page, lets say to your public HTML site,
1541 you will have to move the image and maybe change the link."
1542 :group 'org-export
1543 :type 'boolean)
1544
1545 (defcustom org-export-html-expand t
1546 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1547 When nil, these tags will be exported as plain text and therefore
1548 not be interpreted by a browser.
1549
1550 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1551 :group 'org-export
1552 :type 'boolean)
1553
1554 (defcustom org-export-with-fixed-width t
1555 "Non-nil means, lines starting with \":\" will be in fixed width font.
1556 This can be used to have pre-formatted text, fragments of code etc. For
1557 example:
1558 : ;; Some Lisp examples
1559 : (while (defc cnt)
1560 : (ding))
1561 will be looking just like this in also HTML. In ASCII export, this option
1562 has no effect.
1563
1564 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1565 :group 'org-export
1566 :type 'boolean)
1567
1568 (defcustom org-export-with-tables t
1569 "If non-nil, lines starting with \"|\" define a table.
1570 For example:
1571
1572 | Name | Address | Birthday |
1573 |-------------+----------+-----------|
1574 | Arthur Dent | England | 29.2.2100 |
1575
1576 In ASCII export, this option has no effect.
1577
1578 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1579 :group 'org-export
1580 :type 'boolean)
1581
1582 (defcustom org-export-table-remove-special-lines t
1583 "Remove special lines and marking characters in calculating tables.
1584 This removes the special marking character column from tables that are set
1585 up for spreadsheet calculations. It also removes the entire lines
1586 marked with `!', `_', or `^'. The lines with `$' are kept, because
1587 the values of constants may be useful to have."
1588 :group 'org-export
1589 :type 'boolean)
1590
1591 (defcustom org-export-prefer-native-exporter-for-tables nil
1592 "Non-nil means, always export tables created with table.el natively.
1593 Natively means, use the HTML code generator in table.el.
1594 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1595 the table does not use row- or column-spanning). This has the
1596 advantage, that the automatic HTML conversions for math symbols and
1597 sub/superscripts can be applied. Org-mode's HTML generator is also
1598 much faster."
1599 :group 'org-export
1600 :type 'boolean)
1601
1602 (defcustom org-export-html-table-tag
1603 "<table border=1 cellspacing=0 cellpadding=6>"
1604 "The HTML tag used to start a table.
1605 This must be a <table> tag, but you may change the options like
1606 borders and spacing."
1607 :group 'org-export
1608 :type 'string)
1609
1610 (defcustom org-export-with-emphasize t
1611 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1612 If the export target supports emphasizing text, the word will be
1613 typeset in bold, italic, or underlined, respectively. Works only for
1614 single words, but you can say: I *really* *mean* *this*.
1615 In ASCII export, this option has no effect.
1616
1617 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1618 :group 'org-export
1619 :type 'boolean)
1620
1621 (defcustom org-match-sexp-depth 3
1622 "Number of stacked braces for sub/superscript matching.
1623 This has to be set before loading org.el to be effective."
1624 :group 'org-export
1625 :type 'integer)
1626
1627 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1628 (defcustom org-export-with-sub-superscripts t
1629 "Non-nil means, interpret \"_\" and \"^\" for export.
1630 When this option is turned on, you can use TeX-like syntax for sub- and
1631 superscripts. Several characters after \"_\" or \"^\" will be
1632 considered as a single item - so grouping with {} is normally not
1633 needed. For example, the following things will be parsed as single
1634 sub- or superscripts.
1635
1636 10^24 or 10^tau several digits will be considered 1 item.
1637 10^-12 or 10^-tau a leading sign with digits or a word
1638 x^2-y^3 will be read as x^2 - y^3, because items are
1639 terminated by almost any nonword/nondigit char.
1640 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1641
1642 Still, ambiguity is possible - so when in doubt use {} to enclose the
1643 sub/superscript.
1644 In ASCII export, this option has no effect.
1645
1646 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1647 :group 'org-export
1648 :type 'boolean)
1649
1650 (defcustom org-export-with-TeX-macros t
1651 "Non-nil means, interpret simple TeX-like macros when exporting.
1652 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1653 No only real TeX macros will work here, but the standard HTML entities
1654 for math can be used as macro names as well. For a list of supported
1655 names in HTML export, see the constant `org-html-entities'.
1656 In ASCII export, this option has no effect.
1657
1658 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1659 :group 'org-export
1660 :type 'boolean)
1661
1662 (defcustom org-export-html-with-timestamp nil
1663 "If non-nil, write `org-export-html-html-helper-timestamp'
1664 into the exported HTML text. Otherwise, the buffer will just be saved
1665 to a file."
1666 :group 'org-export
1667 :type 'boolean)
1668
1669 (defcustom org-export-html-html-helper-timestamp
1670 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1671 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1672 :group 'org-export
1673 :type 'string)
1674
1675 (defcustom org-export-ascii-show-new-buffer t
1676 "Non-nil means, popup buffer containing the exported ASCII text.
1677 Otherwise the buffer will just be saved to a file and stay hidden."
1678 :group 'org-export
1679 :type 'boolean)
1680
1681 (defcustom org-export-html-show-new-buffer nil
1682 "Non-nil means, popup buffer containing the exported html text.
1683 Otherwise, the buffer will just be saved to a file and stay hidden."
1684 :group 'org-export
1685 :type 'boolean)
1686
1687 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1688 "The file name for the iCalendar file covering all agenda files.
1689 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1690 :group 'org-export
1691 :type 'file)
1692
1693 (defcustom org-icalendar-include-todo nil
1694 "Non-nil means, export to iCalendar files should also cover TODO items."
1695 :group 'org-export
1696 :type 'boolean)
1697
1698 (defcustom org-icalendar-combined-name "OrgMode"
1699 "Calendar name for the combined iCalendar representing all agenda files."
1700 :group 'org-export
1701 :type 'string)
1702
1703 (defgroup org-font-lock nil
1704 "Faces and settings for highlighting in Org-mode."
1705 :tag "Org Font Lock"
1706 :group 'org)
1707
1708 (defcustom org-level-color-stars-only nil
1709 "Non-nil means fontify only the stars in each headline.
1710 When nil, the entire headline is fontified.
1711 Changing it requires restart of `font-lock-mode' to become effective
1712 also in regions already fontified."
1713 :group 'org-font-lock
1714 :type 'boolean)
1715
1716 (defcustom org-hide-leading-stars nil
1717 "Non-nil means, hide the first N-1 stars in a headline.
1718 This works by using the face `org-hide' for these stars. This
1719 face is white for a light background, and black for a dark
1720 background. You may have to customize the face `org-hide' to
1721 make this work.
1722 Changing it requires restart of `font-lock-mode' to become effective
1723 also in regions already fontified."
1724 :group 'org-font-lock
1725 :type 'boolean)
1726
1727 (defcustom org-fontify-done-headline nil
1728 "Non-nil means, change the face of a headline if it is marked DONE.
1729 Normally, only the TODO/DONE keyword indicates the state of a headline.
1730 When this is non-nil, the headline after the keyword is set to the
1731 `org-headline-done' as an additional indication."
1732 :group 'org-font-lock
1733 :type 'boolean)
1734
1735 (defcustom org-fontify-emphasized-text t
1736 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
1737 Changing this variable requires a restart of Emacs to take effect."
1738 :group 'org-font-lock
1739 :type 'boolean)
1740
1741 (defface org-hide
1742 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1743 (((class color) (background light)) (:foreground "white"))
1744 (((class color) (background dark)) (:foreground "black"))
1745 ; (((class color) (background light)) (:foreground "grey90"))
1746 ; (((class color) (background dark)) (:foreground "grey10"))
1747 (t (:inverse-video nil)))
1748 "Face used for level 1 headlines."
1749 :group 'org-font-lock)
1750
1751 (defface org-level-1 ;; font-lock-function-name-face
1752 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1753 (((class color) (background light)) (:foreground "Blue"))
1754 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1755 (t (:inverse-video t :bold t)))
1756 "Face used for level 1 headlines."
1757 :group 'org-font-lock)
1758
1759 (defface org-level-2 ;; font-lock-variable-name-face
1760 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1761 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1762 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1763 (t (:bold t :italic t)))
1764 "Face used for level 2 headlines."
1765 :group 'org-font-lock)
1766
1767 (defface org-level-3 ;; font-lock-keyword-face
1768 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1769 (((class color) (background light)) (:foreground "Purple"))
1770 (((class color) (background dark)) (:foreground "Cyan"))
1771 (t (:bold t)))
1772 "Face used for level 3 headlines."
1773 :group 'org-font-lock)
1774
1775 (defface org-level-4 ;; font-lock-comment-face
1776 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1777 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1778 (((class color) (background light)) (:foreground "Firebrick"))
1779 (((class color) (background dark)) (:foreground "chocolate1"))
1780 (t (:bold t :italic t)))
1781 "Face used for level 4 headlines."
1782 :group 'org-font-lock)
1783
1784 (defface org-level-5 ;; font-lock-type-face
1785 '((((type tty) (class color)) (:foreground "green"))
1786 (((class color) (background light)) (:foreground "ForestGreen"))
1787 (((class color) (background dark)) (:foreground "PaleGreen"))
1788 (t (:bold t :underline t)))
1789 "Face used for level 5 headlines."
1790 :group 'org-font-lock)
1791
1792 (defface org-level-6 ;; font-lock-constant-face
1793 '((((type tty) (class color)) (:foreground "magenta"))
1794 (((class color) (background light)) (:foreground "CadetBlue"))
1795 (((class color) (background dark)) (:foreground "Aquamarine"))
1796 (t (:bold t :underline t)))
1797 "Face used for level 6 headlines."
1798 :group 'org-font-lock)
1799
1800 (defface org-level-7 ;; font-lock-builtin-face
1801 '((((type tty) (class color)) (:foreground "blue" :weight light))
1802 (((class color) (background light)) (:foreground "Orchid"))
1803 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1804 (t (:bold t)))
1805 "Face used for level 7 headlines."
1806 :group 'org-font-lock)
1807
1808 (defface org-level-8 ;; font-lock-string-face
1809 '((((type tty) (class color)) (:foreground "green"))
1810 (((class color) (background light)) (:foreground "RosyBrown"))
1811 (((class color) (background dark)) (:foreground "LightSalmon"))
1812 (t (:italic t)))
1813 "Face used for level 8 headlines."
1814 :group 'org-font-lock)
1815
1816 (defface org-special-keyword ;; font-lock-string-face
1817 '((((type tty) (class color)) (:foreground "green"))
1818 (((class color) (background light)) (:foreground "RosyBrown"))
1819 (((class color) (background dark)) (:foreground "LightSalmon"))
1820 (t (:italic t)))
1821 "Face used for special keywords."
1822 :group 'org-font-lock)
1823
1824 (defface org-warning ;; font-lock-warning-face
1825 '((((type tty) (class color)) (:foreground "red"))
1826 (((class color) (background light)) (:foreground "Red" :bold t))
1827 (((class color) (background dark)) (:foreground "Red1" :bold t))
1828 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1829 (t (:inverse-video t :bold t)))
1830 "Face for deadlines and TODO keywords."
1831 :group 'org-font-lock)
1832
1833 (defface org-headline-done ;; font-lock-string-face
1834 '((((type tty) (class color)) (:foreground "green"))
1835 (((class color) (background light)) (:foreground "RosyBrown"))
1836 (((class color) (background dark)) (:foreground "LightSalmon"))
1837 (t (:italic t)))
1838 "Face used to indicate that a headline is DONE. See also the variable
1839 `org-fontify-done-headline'."
1840 :group 'org-font-lock)
1841
1842 ;; Inheritance does not yet work for xemacs. So we just copy...
1843
1844 (defface org-deadline-announce
1845 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1846 (((class color) (background light)) (:foreground "Blue"))
1847 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1848 (t (:inverse-video t :bold t)))
1849 "Face for upcoming deadlines."
1850 :group 'org-font-lock)
1851
1852 (defface org-scheduled-today
1853 '((((type tty) (class color)) (:foreground "green"))
1854 (((class color) (background light)) (:foreground "DarkGreen"))
1855 (((class color) (background dark)) (:foreground "PaleGreen"))
1856 (t (:bold t :underline t)))
1857 "Face for items scheduled for a certain day."
1858 :group 'org-font-lock)
1859
1860 (defface org-scheduled-previously
1861 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1862 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1863 (((class color) (background light)) (:foreground "Firebrick"))
1864 (((class color) (background dark)) (:foreground "chocolate1"))
1865 (t (:bold t :italic t)))
1866 "Face for items scheduled previously, and not yet done."
1867 :group 'org-font-lock)
1868
1869 (defface org-formula
1870 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1871 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1872 (((class color) (background light)) (:foreground "Firebrick"))
1873 (((class color) (background dark)) (:foreground "chocolate1"))
1874 (t (:bold t :italic t)))
1875 "Face for formulas."
1876 :group 'org-font-lock)
1877
1878 (defface org-link
1879 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1880 (((class color) (background light)) (:foreground "Purple"))
1881 (((class color) (background dark)) (:foreground "Cyan"))
1882 (t (:bold t)))
1883 "Face for links."
1884 :group 'org-font-lock)
1885
1886 (defface org-tag
1887 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1888 (((class color) (background light)) (:foreground "Purple" :weight bold))
1889 (((class color) (background dark)) (:foreground "Cyan" :weight bold))
1890 (t (:bold t)))
1891 "Face for tags."
1892 :group 'org-font-lock)
1893
1894 (defface org-done ;; font-lock-type-face
1895 '((((type tty) (class color)) (:foreground "green"))
1896 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1897 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1898 (t (:bold t :underline t)))
1899 "Face used for DONE."
1900 :group 'org-font-lock)
1901
1902 (defface org-table ;; font-lock-function-name-face
1903 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1904 (((class color) (background light)) (:foreground "Blue"))
1905 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1906 (t (:inverse-video t :bold t)))
1907 "Face used for tables."
1908 :group 'org-font-lock)
1909
1910 (defface org-time-grid ;; font-lock-variable-name-face
1911 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1912 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1913 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1914 (t (:bold t :italic t)))
1915 "Face used for time grids."
1916 :group 'org-font-lock)
1917
1918 (defvar org-level-faces
1919 '(org-level-1 org-level-2 org-level-3 org-level-4
1920 org-level-5 org-level-6 org-level-7 org-level-8
1921 ))
1922 (defvar org-n-levels (length org-level-faces))
1923
1924 (defun org-set-regexps-and-options ()
1925 "Precompute regular expressions for current buffer."
1926 (when (eq major-mode 'org-mode)
1927 (let ((re (org-make-options-regexp
1928 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1929 "STARTUP" "ARCHIVE")))
1930 (splitre "[ \t]+")
1931 kwds int key value cat arch)
1932 (save-excursion
1933 (save-restriction
1934 (widen)
1935 (goto-char (point-min))
1936 (while (re-search-forward re nil t)
1937 (setq key (match-string 1) value (match-string 2))
1938 (cond
1939 ((equal key "CATEGORY")
1940 (if (string-match "[ \t]+$" value)
1941 (setq value (replace-match "" t t value)))
1942 (setq cat (intern value)))
1943 ((equal key "SEQ_TODO")
1944 (setq int 'sequence
1945 kwds (append kwds (org-split-string value splitre))))
1946 ((equal key "PRI_TODO")
1947 (setq int 'priority
1948 kwds (append kwds (org-split-string value splitre))))
1949 ((equal key "TYP_TODO")
1950 (setq int 'type
1951 kwds (append kwds (org-split-string value splitre))))
1952 ((equal key "STARTUP")
1953 (let ((opts (org-split-string value splitre))
1954 (set '(("fold" org-startup-folded t)
1955 ("nofold" org-startup-folded nil)
1956 ("content" org-startup-folded content)
1957 ("hidestars" org-hide-leading-stars t)
1958 ("showstars" org-hide-leading-stars nil)
1959 ("odd" org-odd-levels-only t)
1960 ("oddeven" org-odd-levels-only nil)
1961 ("dlcheck" org-startup-with-deadline-check t)
1962 ("nodlcheck" org-startup-with-deadline-check nil)))
1963 l var val)
1964 (while (setq l (assoc (pop opts) set))
1965 (setq var (nth 1 l) val (nth 2 l))
1966 (set (make-local-variable var) val))))
1967 ((equal key "ARCHIVE")
1968 (string-match " *$" value)
1969 (setq arch (replace-match "" t t value))
1970 (remove-text-properties 0 (length arch)
1971 '(face t fontified t) arch)))
1972 )))
1973 (and cat (set (make-local-variable 'org-category) cat))
1974 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1975 (and arch (set (make-local-variable 'org-archive-location) arch))
1976 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1977 ;; Compute the regular expressions and other local variables
1978 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1979 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1980 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1981 (length org-scheduled-string)))
1982 org-done-string
1983 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1984 org-todo-regexp
1985 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1986 "\\|") "\\)\\>")
1987 org-not-done-regexp
1988 (concat "\\<\\("
1989 (mapconcat 'regexp-quote
1990 (nreverse (cdr (reverse org-todo-keywords)))
1991 "\\|")
1992 "\\)\\>")
1993 org-todo-line-regexp
1994 (concat "^\\(\\*+\\)[ \t]*\\("
1995 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1996 "\\)? *\\(.*\\)")
1997 org-nl-done-regexp
1998 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1999 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2000 org-deadline-regexp (concat "\\<" org-deadline-string)
2001 org-deadline-time-regexp
2002 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2003 org-deadline-line-regexp
2004 (concat "\\<\\(" org-deadline-string "\\).*")
2005 org-scheduled-regexp
2006 (concat "\\<" org-scheduled-string)
2007 org-scheduled-time-regexp
2008 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2009 (org-set-font-lock-defaults)))
2010
2011 ;; Tell the compiler about dynamically scoped variables,
2012 ;; and variables from other packages
2013 (defvar zmacs-regions)
2014 (defvar original-date)
2015 (defvar org-transient-mark-mode)
2016 (defvar org-old-auto-fill-inhibit-regexp)
2017 (defvar orgtbl-mode-menu)
2018 (defvar org-html-entities)
2019 (defvar org-goto-start-pos)
2020 (defvar org-cursor-color)
2021 (defvar org-time-was-given)
2022 (defvar org-ts-what)
2023 (defvar mark-active)
2024 (defvar timecnt)
2025 (defvar levels-open)
2026 (defvar title)
2027 (defvar author)
2028 (defvar email)
2029 (defvar text)
2030 (defvar entry)
2031 (defvar date)
2032 (defvar language)
2033 (defvar options)
2034 (defvar ans1)
2035 (defvar ans2)
2036 (defvar starting-day)
2037 (defvar include-all-loc)
2038 (defvar vm-message-pointer)
2039 (defvar vm-folder-directory)
2040 (defvar wl-summary-buffer-elmo-folder)
2041 (defvar wl-summary-buffer-folder-name)
2042 (defvar gnus-group-name)
2043 (defvar gnus-article-current)
2044 (defvar w3m-current-url)
2045 (defvar mh-progs)
2046 (defvar mh-current-folder)
2047 (defvar mh-show-folder-buffer)
2048 (defvar mh-index-folder)
2049 (defvar mh-searcher)
2050 (defvar org-selected-point)
2051 (defvar calendar-mode-map)
2052 (defvar remember-save-after-remembering)
2053 (defvar remember-data-file)
2054 (defvar last-arg)
2055
2056 ;;; Define the mode
2057
2058 (defvar org-mode-map (copy-keymap outline-mode-map)
2059 "Keymap for Org-mode.")
2060
2061 (defvar org-struct-menu)
2062 (defvar org-org-menu)
2063 (defvar org-tbl-menu)
2064
2065 ;; We use a before-change function to check if a table might need
2066 ;; an update.
2067 (defvar org-table-may-need-update t
2068 "Indicates that a table might need an update.
2069 This variable is set by `org-before-change-function'.
2070 `org-table-align' sets it back to nil.")
2071 (defvar org-mode-hook nil)
2072 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2073 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2074
2075
2076 ;;;###autoload
2077 (define-derived-mode org-mode outline-mode "Org"
2078 "Outline-based notes management and organizer, alias
2079 \"Carsten's outline-mode for keeping track of everything.\"
2080
2081 Org-mode develops organizational tasks around a NOTES file which
2082 contains information about projects as plain text. Org-mode is
2083 implemented on top of outline-mode, which is ideal to keep the content
2084 of large files well structured. It supports ToDo items, deadlines and
2085 time stamps, which magically appear in the diary listing of the Emacs
2086 calendar. Tables are easily created with a built-in table editor.
2087 Plain text URL-like links connect to websites, emails (VM), Usenet
2088 messages (Gnus), BBDB entries, and any files related to the project.
2089 For printing and sharing of notes, an Org-mode file (or a part of it)
2090 can be exported as a structured ASCII or HTML file.
2091
2092 The following commands are available:
2093
2094 \\{org-mode-map}"
2095 (easy-menu-add org-org-menu)
2096 (easy-menu-add org-tbl-menu)
2097 (org-install-agenda-files-menu)
2098 (setq outline-regexp "\\*+")
2099 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2100 (setq outline-level 'org-outline-level)
2101 (if org-startup-truncated (setq truncate-lines t))
2102 (org-set-regexps-and-options)
2103 (set (make-local-variable 'font-lock-unfontify-region-function)
2104 'org-unfontify-region)
2105 ;; Activate before-change-function
2106 (set (make-local-variable 'org-table-may-need-update) t)
2107 (org-add-hook 'before-change-functions 'org-before-change-function nil
2108 'local)
2109 ;; Paragraphs and auto-filling
2110 (org-set-autofill-regexps)
2111 (org-update-radio-target-regexp)
2112 ;; Settings for Calc embedded mode
2113 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2114 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2115 (if (and org-insert-mode-line-in-empty-file
2116 (interactive-p)
2117 (= (point-min) (point-max)))
2118 (insert " -*- mode: org -*-\n\n"))
2119
2120 ;; Get rid of Outline menus, they are not needed
2121 ;; Need to do this here because define-derived-mode sets up
2122 ;; the keymap so late.
2123 (if org-xemacs-p
2124 (progn
2125 (delete-menu-item '("Headings"))
2126 (delete-menu-item '("Show"))
2127 (delete-menu-item '("Hide"))
2128 (set-menubar-dirty-flag))
2129 (define-key org-mode-map [menu-bar headings] 'undefined)
2130 (define-key org-mode-map [menu-bar hide] 'undefined)
2131 (define-key org-mode-map [menu-bar show] 'undefined))
2132
2133 (unless org-inhibit-startup
2134 (if org-startup-with-deadline-check
2135 (call-interactively 'org-check-deadlines)
2136 (cond
2137 ((eq org-startup-folded t)
2138 (org-cycle '(4)))
2139 ((eq org-startup-folded 'content)
2140 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2141 (org-cycle '(4)) (org-cycle '(4))))))))
2142
2143 (defsubst org-current-line (&optional pos)
2144 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2145
2146
2147 ;; FIXME: Do we need to copy?
2148 (defun org-string-props (string &rest properties)
2149 "Add PROPERTIES to string."
2150 (add-text-properties 0 (length string) properties string)
2151 string)
2152
2153 ;;; Font-Lock stuff
2154
2155 (defvar org-mouse-map (make-sparse-keymap))
2156 (define-key org-mouse-map
2157 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2158 (define-key org-mouse-map
2159 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2160 (define-key org-mouse-map [follow-link] 'mouse-face)
2161 (when org-tab-follows-link
2162 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2163 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2164 (when org-return-follows-link
2165 (define-key org-mouse-map [(return)] 'org-open-at-point)
2166 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2167
2168 (require 'font-lock)
2169
2170 (defconst org-non-link-chars "\t\n\r|<>\000")
2171 (defconst org-link-regexp
2172 (if org-allow-space-in-links
2173 (concat
2174 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2175 (concat
2176 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2177 )
2178 "Regular expression for matching links.")
2179 (defconst org-link-maybe-angles-regexp
2180 (concat "<?\\(" org-link-regexp "\\)>?")
2181 "Matches a link and optionally surrounding angle brackets.")
2182 (defconst org-protected-link-regexp
2183 (concat "\000" org-link-regexp "\000")
2184 "Matches a link and optionally surrounding angle brackets.")
2185
2186 (defconst org-bracket-link-regexp
2187 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2188 "Matches a link in double brackets.")
2189
2190 (defconst org-ts-lengths
2191 (cons (length (format-time-string (car org-time-stamp-formats)))
2192 (length (format-time-string (cdr org-time-stamp-formats))))
2193 "This holds the lengths of the two different time formats.")
2194 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2195 "Regular expression for fast time stamp matching.")
2196 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2197 "Regular expression for fast time stamp matching.")
2198 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2199 "Regular expression matching time strings for analysis.")
2200 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2201 "Regular expression matching time stamps, with groups.")
2202 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2203 "Regular expression matching a time stamp range.")
2204 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2205 org-ts-regexp "\\)?")
2206 "Regular expression matching a time stamp or time stamp range.")
2207
2208 (defun org-activate-links (limit)
2209 "Run through the buffer and add overlays to links."
2210 (if (re-search-forward org-link-regexp limit t)
2211 (progn
2212 (add-text-properties (match-beginning 0) (match-end 0)
2213 (list 'mouse-face 'highlight
2214 'keymap org-mouse-map))
2215 t)))
2216
2217 (defun org-activate-links2 (limit)
2218 "Run through the buffer and add overlays to links."
2219 (if (re-search-forward org-bracket-link-regexp limit t)
2220 (progn
2221 (add-text-properties (match-beginning 0) (match-end 0)
2222 (list 'mouse-face 'highlight
2223 'keymap org-mouse-map))
2224 t)))
2225
2226 (defun org-activate-dates (limit)
2227 "Run through the buffer and add overlays to dates."
2228 (if (re-search-forward org-tsr-regexp limit t)
2229 (progn
2230 (add-text-properties (match-beginning 0) (match-end 0)
2231 (list 'mouse-face 'highlight
2232 'keymap org-mouse-map))
2233 t)))
2234
2235 (defvar org-target-link-regexp nil
2236 "Regular expression matching radio targets in plain text.")
2237 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2238 "Regular expression matching a link target.")
2239 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2240 "Regular expression matching a link target.")
2241
2242 (defun org-activate-target-links (limit)
2243 "Run through the buffer and add overlays to target matches."
2244 (when (and org-radio-targets org-target-link-regexp)
2245 (let ((case-fold-search t))
2246 (if (re-search-forward org-target-link-regexp limit t)
2247 (progn
2248 (add-text-properties (match-beginning 0) (match-end 0)
2249 (list 'mouse-face 'highlight
2250 'keymap org-mouse-map
2251 'org-linked-text t))
2252 t)))))
2253
2254 (defun org-update-radio-target-regexp ()
2255 "Find all radio targets in this file and update the regular expression."
2256 (interactive)
2257 (when org-radio-targets
2258 (setq org-target-link-regexp
2259 (org-make-target-link-regexp (org-all-targets 'radio)))
2260 (font-lock-mode -1)
2261 (font-lock-mode 1)))
2262
2263 (defun org-all-targets (&optional radio)
2264 "Return a list of all targets in this file.
2265 With optional argument RADIO, only find radio targets."
2266 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2267 rtn)
2268 (save-excursion
2269 (goto-char (point-min))
2270 (while (re-search-forward re nil t)
2271 (add-to-list 'rtn (downcase
2272 (if (fboundp 'match-string-no-properties)
2273 (match-string-no-properties 1)
2274 (match-string 1)))))
2275 rtn)))
2276
2277 (defun org-make-target-link-regexp (targets)
2278 "Make regular expression matching all strings in TARGETS.
2279 The regular expression finds the targets also if there is a line break
2280 between words."
2281 (and targets
2282 (concat
2283 "\\<\\("
2284 (mapconcat
2285 (lambda (x)
2286 (while (string-match " +" x)
2287 (setq x (replace-match "\\s-+" t t x)))
2288 x)
2289 targets
2290 "\\|")
2291 "\\)\\>")))
2292
2293 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2294 "Matches CamelCase words, possibly with a star before it.")
2295
2296 (defun org-activate-camels (limit)
2297 "Run through the buffer and add overlays to dates."
2298 (if org-activate-camels
2299 (if (re-search-forward org-camel-regexp limit t)
2300 (progn
2301 (add-text-properties (match-beginning 0) (match-end 0)
2302 (list 'mouse-face 'highlight
2303 'keymap org-mouse-map))
2304 t))))
2305
2306 (defun org-activate-tags (limit)
2307 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2308 (progn
2309 (add-text-properties (match-beginning 1) (match-end 1)
2310 (list 'mouse-face 'highlight
2311 'keymap org-mouse-map))
2312 t)))
2313
2314 (defun org-font-lock-level ()
2315 (save-excursion
2316 (org-back-to-heading t)
2317 (- (match-end 0) (match-beginning 0))))
2318
2319 (defun org-outline-level ()
2320 (save-excursion
2321 (looking-at outline-regexp)
2322 (if (match-beginning 1)
2323 (+ (org-get-string-indentation (match-string 1)) 1000)
2324 (- (match-end 0) (match-beginning 0)))))
2325
2326 (defvar org-font-lock-keywords nil)
2327
2328 (defun org-set-font-lock-defaults ()
2329 (let* ((em org-fontify-emphasized-text)
2330 (org-font-lock-extra-keywords
2331 (list
2332 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2333 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2334 '(org-activate-links (0 'org-link t))
2335 '(org-activate-links2 (0 'org-link t))
2336 '(org-activate-target-links (0 'org-link t))
2337 '(org-activate-dates (0 'org-link t))
2338 '(org-activate-camels (0 'org-link t))
2339 '(org-activate-tags (1 'org-tag t))
2340 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2341 '(1 'org-warning t))
2342 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2343 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2344 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2345 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2346 ; (if em '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)" (3 'bold)))
2347 ; (if em '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)" (3 'italic)))
2348 ; (if em '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)" (3 'underline)))
2349 (if em '("\\*[a-zA-Z]+\\*" 0 'bold))
2350 (if em '("/*[a-zA-Z]+/" 0 'italic))
2351 (if em '("_[a-zA-Z]+_" 0 'underline))
2352 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2353 "\\|" org-quote-string "\\)\\>")
2354 '(1 'org-special-keyword t))
2355 '("^#.*" (0 'font-lock-comment-face t))
2356 (if org-fontify-done-headline
2357 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2358 '(1 'org-done t) '(2 'org-headline-done t))
2359 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2360 '(1 'org-done t)))
2361 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2362 (1 'org-table t))
2363 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2364 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2365 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2366 )))
2367 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
2368 ;; Now set the full font-lock-keywords
2369 (set (make-local-variable 'org-font-lock-keywords)
2370 org-font-lock-extra-keywords)
2371 (set (make-local-variable 'font-lock-defaults)
2372 '(org-font-lock-keywords t nil nil backward-paragraph))
2373 (kill-local-variable 'font-lock-keywords) nil))
2374
2375 (defvar org-m nil)
2376 (defvar org-l nil)
2377 (defvar org-f nil)
2378 (defun org-get-level-face (n)
2379 "Get the right face for match N in font-lock matching of healdines."
2380 (setq org-l (- (match-end 2) (match-beginning 1)))
2381 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2382 (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2383 (cond
2384 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2385 ((eq n 2) org-f)
2386 (t (if org-level-color-stars-only nil org-f))))
2387
2388 (defun org-unfontify-region (beg end &optional maybe_loudly)
2389 "Remove fontification and activation overlays from links."
2390 (font-lock-default-unfontify-region beg end)
2391 (let* ((buffer-undo-list t)
2392 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2393 (inhibit-modification-hooks t)
2394 deactivate-mark buffer-file-name buffer-file-truename)
2395 (remove-text-properties beg end
2396 '(mouse-face nil keymap nil org-linked-text nil))))
2397
2398 ;;; Visibility cycling
2399
2400 (defvar org-cycle-global-status nil)
2401 (defvar org-cycle-subtree-status nil)
2402 (defun org-cycle (&optional arg)
2403 "Visibility cycling for Org-mode.
2404
2405 - When this function is called with a prefix argument, rotate the entire
2406 buffer through 3 states (global cycling)
2407 1. OVERVIEW: Show only top-level headlines.
2408 2. CONTENTS: Show all headlines of all levels, but no body text.
2409 3. SHOW ALL: Show everything.
2410
2411 - When point is at the beginning of a headline, rotate the subtree started
2412 by this line through 3 different states (local cycling)
2413 1. FOLDED: Only the main headline is shown.
2414 2. CHILDREN: The main headline and the direct children are shown.
2415 From this state, you can move to one of the children
2416 and zoom in further.
2417 3. SUBTREE: Show the entire subtree, including body text.
2418
2419 - When there is a numeric prefix, go up to a heading with level ARG, do
2420 a `show-subtree' and return to the previous cursor position. If ARG
2421 is negative, go up that many levels.
2422
2423 - When point is not at the beginning of a headline, execute
2424 `indent-relative', like TAB normally does. See the option
2425 `org-cycle-emulate-tab' for details.
2426
2427 - Special case: if point is the the beginning of the buffer and there is
2428 no headline in line 1, this function will act as if called with prefix arg."
2429 (interactive "P")
2430
2431 (if (or (and (bobp) (not (looking-at outline-regexp)))
2432 (equal arg '(4)))
2433 ;; special case: use global cycling
2434 (setq arg t))
2435
2436 (let ((outline-regexp
2437 (if org-cycle-include-plain-lists
2438 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2439 outline-regexp)))
2440
2441 (cond
2442
2443 ((org-at-table-p 'any)
2444 ;; Enter the table or move to the next field in the table
2445 (or (org-table-recognize-table.el)
2446 (progn
2447 (org-table-justify-field-maybe)
2448 (org-table-next-field))))
2449
2450 ((eq arg t) ;; Global cycling
2451
2452 (cond
2453 ((and (eq last-command this-command)
2454 (eq org-cycle-global-status 'overview))
2455 ;; We just created the overview - now do table of contents
2456 ;; This can be slow in very large buffers, so indicate action
2457 (message "CONTENTS...")
2458 (save-excursion
2459 ;; Visit all headings and show their offspring
2460 (goto-char (point-max))
2461 (catch 'exit
2462 (while (and (progn (condition-case nil
2463 (outline-previous-visible-heading 1)
2464 (error (goto-char (point-min))))
2465 t)
2466 (looking-at outline-regexp))
2467 (show-branches)
2468 (if (bobp) (throw 'exit nil))))
2469 (message "CONTENTS...done"))
2470 (setq org-cycle-global-status 'contents)
2471 (run-hook-with-args 'org-cycle-hook 'contents))
2472
2473 ((and (eq last-command this-command)
2474 (eq org-cycle-global-status 'contents))
2475 ;; We just showed the table of contents - now show everything
2476 (show-all)
2477 (message "SHOW ALL")
2478 (setq org-cycle-global-status 'all)
2479 (run-hook-with-args 'org-cycle-hook 'all))
2480
2481 (t
2482 ;; Default action: go to overview
2483 (hide-sublevels 1)
2484 (message "OVERVIEW")
2485 (setq org-cycle-global-status 'overview)
2486 (run-hook-with-args 'org-cycle-hook 'overview))))
2487
2488 ((integerp arg)
2489 ;; Show-subtree, ARG levels up from here.
2490 (save-excursion
2491 (org-back-to-heading)
2492 (outline-up-heading (if (< arg 0) (- arg)
2493 (- (funcall outline-level) arg)))
2494 (org-show-subtree)))
2495
2496 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2497 ;; At a heading: rotate between three different views
2498 (org-back-to-heading)
2499 (let ((goal-column 0) eoh eol eos)
2500 ;; First, some boundaries
2501 (save-excursion
2502 (org-back-to-heading)
2503 (save-excursion
2504 (beginning-of-line 2)
2505 (while (and (not (eobp)) ;; this is like `next-line'
2506 (get-char-property (1- (point)) 'invisible))
2507 (beginning-of-line 2)) (setq eol (point)))
2508 (outline-end-of-heading) (setq eoh (point))
2509 (org-end-of-subtree t) (setq eos (point))
2510 (outline-next-heading))
2511 ;; Find out what to do next and set `this-command'
2512 (cond
2513 ((= eos eoh)
2514 ;; Nothing is hidden behind this heading
2515 (message "EMPTY ENTRY")
2516 (setq org-cycle-subtree-status nil))
2517 ((>= eol eos)
2518 ;; Entire subtree is hidden in one line: open it
2519 (org-show-entry)
2520 (show-children)
2521 (message "CHILDREN")
2522 (setq org-cycle-subtree-status 'children)
2523 (run-hook-with-args 'org-cycle-hook 'children))
2524 ((and (eq last-command this-command)
2525 (eq org-cycle-subtree-status 'children))
2526 ;; We just showed the children, now show everything.
2527 (org-show-subtree)
2528 (message "SUBTREE")
2529 (setq org-cycle-subtree-status 'subtree)
2530 (run-hook-with-args 'org-cycle-hook 'subtree))
2531 (t
2532 ;; Default action: hide the subtree.
2533 (hide-subtree)
2534 (message "FOLDED")
2535 (setq org-cycle-subtree-status 'folded)
2536 (run-hook-with-args 'org-cycle-hook 'folded)))))
2537
2538 ;; TAB emulation
2539 (buffer-read-only (org-back-to-heading))
2540 ((if (and (eq org-cycle-emulate-tab 'white)
2541 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2542 t
2543 (eq org-cycle-emulate-tab t))
2544 (if (and (looking-at "[ \n\r\t]")
2545 (string-match "^[ \t]*$" (buffer-substring
2546 (point-at-bol) (point))))
2547 (progn
2548 (beginning-of-line 1)
2549 (and (looking-at "[ \t]+") (replace-match ""))))
2550 (indent-relative))
2551
2552 (t (save-excursion
2553 (org-back-to-heading)
2554 (org-cycle))))))
2555
2556 (defun org-optimize-window-after-visibility-change (state)
2557 "Adjust the window after a change in outline visibility.
2558 This function is the default value of the hook `org-cycle-hook'."
2559 (cond
2560 ((eq state 'overview) (org-first-headline-recenter 1))
2561 ((eq state 'content) nil)
2562 ((eq state 'all) nil)
2563 ((eq state 'folded) nil)
2564 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2565 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2566
2567 (defun org-subtree-end-visible-p ()
2568 "Is the end of the current subtree visible?"
2569 (pos-visible-in-window-p
2570 (save-excursion (org-end-of-subtree t) (point))))
2571
2572 (defun org-first-headline-recenter (&optional N)
2573 "Move cursor to the first headline and recenter the headline.
2574 Optional argument N means, put the headline into the Nth line of the window."
2575 (goto-char (point-min))
2576 (when (re-search-forward (concat "^" outline-regexp) nil t)
2577 (beginning-of-line)
2578 (recenter (prefix-numeric-value N))))
2579
2580 (defvar org-goto-window-configuration nil)
2581 (defvar org-goto-marker nil)
2582 (defvar org-goto-map (make-sparse-keymap))
2583 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2584 (while (setq cmd (pop cmds))
2585 (substitute-key-definition cmd cmd org-goto-map global-map)))
2586 (define-key org-goto-map "\C-m" 'org-goto-ret)
2587 (define-key org-goto-map [(left)] 'org-goto-left)
2588 (define-key org-goto-map [(right)] 'org-goto-right)
2589 (define-key org-goto-map [(?q)] 'org-goto-quit)
2590 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2591 (define-key org-goto-map "\C-i" 'org-cycle)
2592 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2593 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2594 (define-key org-goto-map "n" 'outline-next-visible-heading)
2595 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2596 (define-key org-goto-map "f" 'outline-forward-same-level)
2597 (define-key org-goto-map "b" 'outline-backward-same-level)
2598 (define-key org-goto-map "u" 'outline-up-heading)
2599 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2600 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2601 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2602 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2603 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2604 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2605 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2606
2607 (defconst org-goto-help
2608 "Select a location to jump to, press RET
2609 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2610
2611 (defun org-goto ()
2612 "Go to a different location of the document, keeping current visibility.
2613
2614 When you want to go to a different location in a document, the fastest way
2615 is often to fold the entire buffer and then dive into the tree. This
2616 method has the disadvantage, that the previous location will be folded,
2617 which may not be what you want.
2618
2619 This command works around this by showing a copy of the current buffer in
2620 overview mode. You can dive into the tree in that copy, to find the
2621 location you want to reach. When pressing RET, the command returns to the
2622 original buffer in which the visibility is still unchanged. It then jumps
2623 to the new location, making it and the headline hierarchy above it visible."
2624 (interactive)
2625 (let* ((org-goto-start-pos (point))
2626 (selected-point
2627 (org-get-location (current-buffer) org-goto-help)))
2628 (if selected-point
2629 (progn
2630 (org-mark-ring-push org-goto-start-pos)
2631 (goto-char selected-point)
2632 (if (or (org-invisible-p) (org-invisible-p2))
2633 (org-show-hierarchy-above)))
2634 (error "Quit"))))
2635
2636 (defun org-get-location (buf help)
2637 "Let the user select a location in the Org-mode buffer BUF.
2638 This function uses a recursive edit. It returns the selected position
2639 or nil."
2640 (let (org-selected-point)
2641 (save-excursion
2642 (save-window-excursion
2643 (delete-other-windows)
2644 (switch-to-buffer (get-buffer-create "*org-goto*"))
2645 (with-output-to-temp-buffer "*Help*"
2646 (princ help))
2647 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2648 (setq buffer-read-only nil)
2649 (erase-buffer)
2650 (insert-buffer-substring buf)
2651 (let ((org-startup-truncated t)
2652 (org-startup-folded t)
2653 (org-startup-with-deadline-check nil))
2654 (org-mode))
2655 (setq buffer-read-only t)
2656 (if (boundp 'org-goto-start-pos)
2657 (goto-char org-goto-start-pos)
2658 (goto-char (point-min)))
2659 (org-beginning-of-line)
2660 (message "Select location and press RET")
2661 ;; now we make sure that during selection, ony very few keys work
2662 ;; and that it is impossible to switch to another window.
2663 (let ((gm (current-global-map))
2664 (overriding-local-map org-goto-map))
2665 (unwind-protect
2666 (progn
2667 (use-global-map org-goto-map)
2668 (recursive-edit))
2669 (use-global-map gm)))))
2670 (kill-buffer "*org-goto*")
2671 org-selected-point))
2672
2673 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2674 (defun org-goto-ret (&optional arg)
2675 "Finish `org-goto' by going to the new location."
2676 (interactive "P")
2677 (setq org-selected-point (point)
2678 current-prefix-arg arg)
2679 (throw 'exit nil))
2680
2681 (defun org-goto-left ()
2682 "Finish `org-goto' by going to the new location."
2683 (interactive)
2684 (if (org-on-heading-p)
2685 (progn
2686 (beginning-of-line 1)
2687 (setq org-selected-point (point)
2688 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2689 (throw 'exit nil))
2690 (error "Not on a heading")))
2691
2692 (defun org-goto-right ()
2693 "Finish `org-goto' by going to the new location."
2694 (interactive)
2695 (if (org-on-heading-p)
2696 (progn
2697 (outline-end-of-subtree)
2698 (or (eobp) (forward-char 1))
2699 (setq org-selected-point (point)
2700 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2701 (throw 'exit nil))
2702 (error "Not on a heading")))
2703
2704 (defun org-goto-quit ()
2705 "Finish `org-goto' without cursor motion."
2706 (interactive)
2707 (setq org-selected-point nil)
2708 (throw 'exit nil))
2709
2710 ;;; Promotion, Demotion, Inserting new headlines
2711
2712 (defvar org-ignore-region nil
2713 "To temporarily disable the active region.")
2714
2715 (defun org-insert-heading (&optional force-heading)
2716 "Insert a new heading or item with same depth at point."
2717 (interactive "P")
2718 (when (or force-heading (not (org-insert-item)))
2719 (let* ((head (save-excursion
2720 (condition-case nil
2721 (org-back-to-heading)
2722 (error (outline-next-heading)))
2723 (prog1 (match-string 0)
2724 (funcall outline-level)))))
2725 (unless (bolp) (newline))
2726 (insert head)
2727 (unless (eolp)
2728 (save-excursion (newline-and-indent)))
2729 (unless (equal (char-before) ?\ )
2730 (insert " "))
2731 (run-hooks 'org-insert-heading-hook))))
2732
2733 (defun org-insert-item ()
2734 "Insert a new item at the current level.
2735 Return t when things worked, nil when we are not in an item."
2736 (when (save-excursion
2737 (condition-case nil
2738 (progn
2739 (org-beginning-of-item)
2740 (org-at-item-p)
2741 t)
2742 (error nil)))
2743 (unless (bolp) (newline))
2744 (insert (match-string 0))
2745 (org-maybe-renumber-ordered-list)
2746 t))
2747
2748 (defun org-insert-todo-heading (arg)
2749 "Insert a new heading with the same level and TODO state as current heading.
2750 If the heading has no TODO state, or if the state is DONE, use the first
2751 state (TODO by default). Also with prefix arg, force first state."
2752 (interactive "P")
2753 (org-insert-heading)
2754 (save-excursion
2755 (org-back-to-heading)
2756 (outline-previous-heading)
2757 (looking-at org-todo-line-regexp))
2758 (if (or arg
2759 (not (match-beginning 2))
2760 (equal (match-string 2) org-done-string))
2761 (insert (car org-todo-keywords) " ")
2762 (insert (match-string 2) " ")))
2763
2764 (defun org-promote-subtree ()
2765 "Promote the entire subtree.
2766 See also `org-promote'."
2767 (interactive)
2768 (save-excursion
2769 (org-map-tree 'org-promote)))
2770
2771 (defun org-demote-subtree ()
2772 "Demote the entire subtree. See `org-demote'.
2773 See also `org-promote'."
2774 (interactive)
2775 (save-excursion
2776 (org-map-tree 'org-demote)))
2777
2778 (defun org-do-promote ()
2779 "Promote the current heading higher up the tree.
2780 If the region is active in `transient-mark-mode', promote all headings
2781 in the region."
2782 (interactive)
2783 (save-excursion
2784 (if (org-region-active-p)
2785 (org-map-region 'org-promote (region-beginning) (region-end))
2786 (org-promote)))
2787 (org-fix-position-after-promote))
2788
2789 (defun org-do-demote ()
2790 "Demote the current heading lower down the tree.
2791 If the region is active in `transient-mark-mode', demote all headings
2792 in the region."
2793 (interactive)
2794 (save-excursion
2795 (if (org-region-active-p)
2796 (org-map-region 'org-demote (region-beginning) (region-end))
2797 (org-demote)))
2798 (org-fix-position-after-promote))
2799
2800 (defun org-fix-position-after-promote ()
2801 "Make sure that after pro/demotion cursor position is right."
2802 (and (equal (char-after) ?\ )
2803 (equal (char-before) ?*)
2804 (forward-char 1)))
2805
2806 (defun org-get-legal-level (level change)
2807 "Rectify a level change under the influence of `org-odd-levels-only'
2808 LEVEL is a current level, CHANGE is by how much the level should be
2809 modified. Even if CHANGE is nil, LEVEL may be returned modified because
2810 even level numbers will become the next higher odd number."
2811 (if org-odd-levels-only
2812 (cond ((not change) (1+ (* 2 (/ level 2))))
2813 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
2814 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
2815 (max 1 (+ level change))))
2816
2817 (defun org-promote ()
2818 "Promote the current heading higher up the tree.
2819 If the region is active in `transient-mark-mode', promote all headings
2820 in the region."
2821 (org-back-to-heading t)
2822 (let* ((level (save-match-data (funcall outline-level)))
2823 (up-head (make-string (org-get-legal-level level -1) ?*))
2824 (diff (abs (- level (length up-head)))))
2825 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2826 (replace-match up-head nil t)
2827 ;; Fixup tag positioning
2828 (and org-auto-align-tags (org-set-tags nil t))
2829 (if org-adapt-indentation
2830 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
2831 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
2832
2833 (defun org-demote ()
2834 "Demote the current heading lower down the tree.
2835 If the region is active in `transient-mark-mode', demote all headings
2836 in the region."
2837 (org-back-to-heading t)
2838 (let* ((level (save-match-data (funcall outline-level)))
2839 (down-head (make-string (org-get-legal-level level 1) ?*))
2840 (diff (abs (- level (length down-head)))))
2841 (replace-match down-head nil t)
2842 ;; Fixup tag positioning
2843 (and org-auto-align-tags (org-set-tags nil t))
2844 (if org-adapt-indentation
2845 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
2846
2847 (defun org-map-tree (fun)
2848 "Call FUN for every heading underneath the current one."
2849 (org-back-to-heading)
2850 (let ((level (funcall outline-level)))
2851 (save-excursion
2852 (funcall fun)
2853 (while (and (progn
2854 (outline-next-heading)
2855 (> (funcall outline-level) level))
2856 (not (eobp)))
2857 (funcall fun)))))
2858
2859 (defun org-map-region (fun beg end)
2860 "Call FUN for every heading between BEG and END."
2861 (let ((org-ignore-region t))
2862 (save-excursion
2863 (setq end (copy-marker end))
2864 (goto-char beg)
2865 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2866 (< (point) end))
2867 (funcall fun))
2868 (while (and (progn
2869 (outline-next-heading)
2870 (< (point) end))
2871 (not (eobp)))
2872 (funcall fun)))))
2873
2874 (defun org-fixup-indentation (from to prohibit)
2875 "Change the indentation in the current entry by re-replacing FROM with TO.
2876 However, if the regexp PROHIBIT matches at all, don't do anything.
2877 This is being used to change indentation along with the length of the
2878 heading marker. But if there are any lines which are not indented, nothing
2879 is changed at all."
2880 (save-excursion
2881 (let ((end (save-excursion (outline-next-heading)
2882 (point-marker))))
2883 (unless (save-excursion (re-search-forward prohibit end t))
2884 (while (re-search-forward from end t)
2885 (replace-match to)
2886 (beginning-of-line 2)))
2887 (move-marker end nil))))
2888
2889 ;;; Vertical tree motion, cutting and pasting of subtrees
2890
2891 (defun org-move-subtree-up (&optional arg)
2892 "Move the current subtree up past ARG headlines of the same level."
2893 (interactive "p")
2894 (org-move-subtree-down (- (prefix-numeric-value arg))))
2895
2896 (defun org-move-subtree-down (&optional arg)
2897 "Move the current subtree down past ARG headlines of the same level."
2898 (interactive "p")
2899 (setq arg (prefix-numeric-value arg))
2900 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2901 'outline-get-last-sibling))
2902 (ins-point (make-marker))
2903 (cnt (abs arg))
2904 beg end txt folded)
2905 ;; Select the tree
2906 (org-back-to-heading)
2907 (setq beg (point))
2908 (save-match-data
2909 (save-excursion (outline-end-of-heading)
2910 (setq folded (org-invisible-p)))
2911 (outline-end-of-subtree))
2912 (outline-next-heading)
2913 (setq end (point))
2914 ;; Find insertion point, with error handling
2915 (goto-char beg)
2916 (while (> cnt 0)
2917 (or (and (funcall movfunc) (looking-at outline-regexp))
2918 (progn (goto-char beg)
2919 (error "Cannot move past superior level or buffer limit")))
2920 (setq cnt (1- cnt)))
2921 (if (> arg 0)
2922 ;; Moving forward - still need to move over subtree
2923 (progn (outline-end-of-subtree)
2924 (outline-next-heading)
2925 (if (not (or (looking-at (concat "^" outline-regexp))
2926 (bolp)))
2927 (newline))))
2928 (move-marker ins-point (point))
2929 (setq txt (buffer-substring beg end))
2930 (delete-region beg end)
2931 (insert txt)
2932 (goto-char ins-point)
2933 (if folded (hide-subtree))
2934 (move-marker ins-point nil)))
2935
2936 (defvar org-subtree-clip ""
2937 "Clipboard for cut and paste of subtrees.
2938 This is actually only a copy of the kill, because we use the normal kill
2939 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2940
2941 (defvar org-subtree-clip-folded nil
2942 "Was the last copied subtree folded?
2943 This is used to fold the tree back after pasting.")
2944
2945 (defun org-cut-subtree ()
2946 "Cut the current subtree into the clipboard.
2947 This is a short-hand for marking the subtree and then cutting it."
2948 (interactive)
2949 (org-copy-subtree 'cut))
2950
2951 (defun org-copy-subtree (&optional cut)
2952 "Cut the current subtree into the clipboard.
2953 This is a short-hand for marking the subtree and then copying it.
2954 If CUT is non nil, actually cut the subtree."
2955 (interactive)
2956 (let (beg end folded)
2957 (org-back-to-heading)
2958 (setq beg (point))
2959 (save-match-data
2960 (save-excursion (outline-end-of-heading)
2961 (setq folded (org-invisible-p)))
2962 (outline-end-of-subtree))
2963 (if (equal (char-after) ?\n) (forward-char 1))
2964 (setq end (point))
2965 (goto-char beg)
2966 (when (> end beg)
2967 (setq org-subtree-clip-folded folded)
2968 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2969 (setq org-subtree-clip (current-kill 0))
2970 (message "%s: Subtree with %d characters"
2971 (if cut "Cut" "Copied")
2972 (length org-subtree-clip)))))
2973
2974 ;; FIXME: this needs to be adapted for the odd-level-only stuff.
2975 (defun org-paste-subtree (&optional level tree)
2976 "Paste the clipboard as a subtree, with modification of headline level.
2977 The entire subtree is promoted or demoted in order to match a new headline
2978 level. By default, the new level is derived from the visible headings
2979 before and after the insertion point, and taken to be the inferior headline
2980 level of the two. So if the previous visible heading is level 3 and the
2981 next is level 4 (or vice versa), level 4 will be used for insertion.
2982 This makes sure that the subtree remains an independent subtree and does
2983 not swallow low level entries.
2984
2985 You can also force a different level, either by using a numeric prefix
2986 argument, or by inserting the heading marker by hand. For example, if the
2987 cursor is after \"*****\", then the tree will be shifted to level 5.
2988
2989 If you want to insert the tree as is, just use \\[yank].
2990
2991 If optional TREE is given, use this text instead of the kill ring."
2992 (interactive "P")
2993 (unless (org-kill-is-subtree-p tree)
2994 (error
2995 (substitute-command-keys
2996 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2997 (let* ((txt (or tree (current-kill 0)))
2998 (^re (concat "^\\(" outline-regexp "\\)"))
2999 (re (concat "\\(" outline-regexp "\\)"))
3000 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3001
3002 (old-level (if (string-match ^re txt)
3003 (- (match-end 0) (match-beginning 0))
3004 -1))
3005 (force-level (cond (level (prefix-numeric-value level))
3006 ((string-match
3007 ^re_ (buffer-substring (point-at-bol) (point)))
3008 (- (match-end 0) (match-beginning 0)))
3009 (t nil)))
3010 (previous-level (save-excursion
3011 (condition-case nil
3012 (progn
3013 (outline-previous-visible-heading 1)
3014 (if (looking-at re)
3015 (- (match-end 0) (match-beginning 0))
3016 1))
3017 (error 1))))
3018 (next-level (save-excursion
3019 (condition-case nil
3020 (progn
3021 (outline-next-visible-heading 1)
3022 (if (looking-at re)
3023 (- (match-end 0) (match-beginning 0))
3024 1))
3025 (error 1))))
3026 (new-level (or force-level (max previous-level next-level)))
3027 (shift (if (or (= old-level -1)
3028 (= new-level -1)
3029 (= old-level new-level))
3030 0
3031 (- new-level old-level)))
3032 (shift1 shift)
3033 (delta (if (> shift 0) -1 1))
3034 (func (if (> shift 0) 'org-demote 'org-promote))
3035 (org-odd-levels-only nil)
3036 beg end)
3037 ;; Remove the forces level indicator
3038 (if force-level
3039 (delete-region (point-at-bol) (point)))
3040 ;; Make sure we start at the beginning of an empty line
3041 (if (not (bolp)) (insert "\n"))
3042 (if (not (looking-at "[ \t]*$"))
3043 (progn (insert "\n") (backward-char 1)))
3044 ;; Paste
3045 (setq beg (point))
3046 (insert txt)
3047 (setq end (point))
3048 (goto-char beg)
3049 ;; Shift if necessary
3050 (if (= shift 0)
3051 (message "Pasted at level %d, without shift" new-level)
3052 (save-restriction
3053 (narrow-to-region beg end)
3054 (while (not (= shift 0))
3055 (org-map-region func (point-min) (point-max))
3056 (setq shift (+ delta shift)))
3057 (goto-char (point-min))
3058 (message "Pasted at level %d, with shift by %d levels"
3059 new-level shift1)))
3060 (if (and (eq org-subtree-clip (current-kill 0))
3061 org-subtree-clip-folded)
3062 ;; The tree was folded before it was killed/copied
3063 (hide-subtree))))
3064
3065 (defun org-kill-is-subtree-p (&optional txt)
3066 "Check if the current kill is an outline subtree, or a set of trees.
3067 Returns nil if kill does not start with a headline, or if the first
3068 headline level is not the largest headline level in the tree.
3069 So this will actually accept several entries of equal levels as well,
3070 which is OK for `org-paste-subtree'.
3071 If optional TXT is given, check this string instead of the current kill."
3072 (let* ((kill (or txt (current-kill 0) ""))
3073 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3074 (- (match-end 0) (match-beginning 0))))
3075 (re (concat "^" outline-regexp))
3076 (start 1))
3077 (if (not start-level)
3078 nil ;; does not even start with a heading
3079 (catch 'exit
3080 (while (setq start (string-match re kill (1+ start)))
3081 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3082 (throw 'exit nil)))
3083 t))))
3084
3085 ;;; Plain list items
3086
3087 (defun org-at-item-p ()
3088 "Is point in a line starting a hand-formatted item?"
3089 (let ((llt org-plain-list-ordered-item-terminator))
3090 (save-excursion
3091 (goto-char (point-at-bol))
3092 (looking-at
3093 (cond
3094 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3095 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3096 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3097 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3098
3099 (defun org-get-indentation ()
3100 "Get the indentation of the current line, interpreting tabs."
3101 (save-excursion
3102 (beginning-of-line 1)
3103 (skip-chars-forward " \t")
3104 (current-column)))
3105
3106 (defun org-beginning-of-item ()
3107 "Go to the beginning of the current hand-formatted item.
3108 If the cursor is not in an item, throw an error."
3109 (let ((pos (point))
3110 (limit (save-excursion (org-back-to-heading)
3111 (beginning-of-line 2) (point)))
3112 ind ind1)
3113 (if (org-at-item-p)
3114 (beginning-of-line 1)
3115 (beginning-of-line 1)
3116 (skip-chars-forward " \t")
3117 (setq ind (current-column))
3118 (if (catch 'exit
3119 (while t
3120 (beginning-of-line 0)
3121 (if (< (point) limit) (throw 'exit nil))
3122 (unless (looking-at " \t]*$")
3123 (skip-chars-forward " \t")
3124 (setq ind1 (current-column))
3125 (if (< ind1 ind)
3126 (throw 'exit (org-at-item-p))))))
3127 nil
3128 (goto-char pos)
3129 (error "Not in an item")))))
3130
3131 (defun org-end-of-item ()
3132 "Go to the end of the current hand-formatted item.
3133 If the cursor is not in an item, throw an error."
3134 (let ((pos (point))
3135 (limit (save-excursion (outline-next-heading) (point)))
3136 (ind (save-excursion
3137 (org-beginning-of-item)
3138 (skip-chars-forward " \t")
3139 (current-column)))
3140 ind1)
3141 (if (catch 'exit
3142 (while t
3143 (beginning-of-line 2)
3144 (if (>= (point) limit) (throw 'exit t))
3145 (unless (looking-at "[ \t]*$")
3146 (skip-chars-forward " \t")
3147 (setq ind1 (current-column))
3148 (if (<= ind1 ind) (throw 'exit t)))))
3149 (beginning-of-line 1)
3150 (goto-char pos)
3151 (error "Not in an item"))))
3152
3153 (defun org-move-item-down (arg)
3154 "Move the plain list item at point down, i.e. swap with following item.
3155 Subitems (items with larger indentation) are considered part of the item,
3156 so this really moves item trees."
3157 (interactive "p")
3158 (let (beg end ind ind1 (pos (point)) txt)
3159 (org-beginning-of-item)
3160 (setq beg (point))
3161 (setq ind (org-get-indentation))
3162 (org-end-of-item)
3163 (setq end (point))
3164 (setq ind1 (org-get-indentation))
3165 (if (and (org-at-item-p) (= ind ind1))
3166 (progn
3167 (org-end-of-item)
3168 (setq txt (buffer-substring beg end))
3169 (save-excursion
3170 (delete-region beg end))
3171 (setq pos (point))
3172 (insert txt)
3173 (goto-char pos)
3174 (org-maybe-renumber-ordered-list))
3175 (goto-char pos)
3176 (error "Cannot move this item further down"))))
3177
3178 (defun org-move-item-up (arg)
3179 "Move the plain list item at point up, i.e. swap with previous item.
3180 Subitems (items with larger indentation) are considered part of the item,
3181 so this really moves item trees."
3182 (interactive "p")
3183 (let (beg end ind ind1 (pos (point)) txt)
3184 (org-beginning-of-item)
3185 (setq beg (point))
3186 (setq ind (org-get-indentation))
3187 (org-end-of-item)
3188 (setq end (point))
3189 (goto-char beg)
3190 (catch 'exit
3191 (while t
3192 (beginning-of-line 0)
3193 (if (looking-at "[ \t]*$")
3194 nil
3195 (if (<= (setq ind1 (org-get-indentation)) ind)
3196 (throw 'exit t)))))
3197 (condition-case nil
3198 (org-beginning-of-item)
3199 (error (goto-char beg)
3200 (error "Cannot move this item further up")))
3201 (setq ind1 (org-get-indentation))
3202 (if (and (org-at-item-p) (= ind ind1))
3203 (progn
3204 (setq txt (buffer-substring beg end))
3205 (save-excursion
3206 (delete-region beg end))
3207 (setq pos (point))
3208 (insert txt)
3209 (goto-char pos)
3210 (org-maybe-renumber-ordered-list))
3211 (goto-char pos)
3212 (error "Cannot move this item further up"))))
3213
3214 (defun org-maybe-renumber-ordered-list ()
3215 "Renumber the ordered list at point if setup allows it.
3216 This tests the user option `org-auto-renumber-ordered-lists' before
3217 doing the renumbering."
3218 (and org-auto-renumber-ordered-lists
3219 (org-at-item-p)
3220 (match-beginning 3)
3221 (org-renumber-ordered-list 1)))
3222
3223 (defun org-get-string-indentation (s)
3224 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3225 (let ((n -1) (i 0) (w tab-width) c)
3226 (catch 'exit
3227 (while (< (setq n (1+ n)) (length s))
3228 (setq c (aref s n))
3229 (cond ((= c ?\ ) (setq i (1+ i)))
3230 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3231 (t (throw 'exit t)))))
3232 i))
3233
3234 (defun org-renumber-ordered-list (arg)
3235 "Renumber an ordered plain list.
3236 Cursor next to be in the first line of an item, the line that starts
3237 with something like \"1.\" or \"2)\"."
3238 (interactive "p")
3239 (unless (and (org-at-item-p)
3240 (match-beginning 3))
3241 (error "This is not an ordered list"))
3242 (let ((line (org-current-line))
3243 (col (current-column))
3244 (ind (org-get-string-indentation
3245 (buffer-substring (point-at-bol) (match-beginning 3))))
3246 ;; (term (substring (match-string 3) -1))
3247 ind1 (n (1- arg)))
3248 ;; find where this list begins
3249 (catch 'exit
3250 (while t
3251 (catch 'next
3252 (beginning-of-line 0)
3253 (if (looking-at "[ \t]*$") (throw 'next t))
3254 (skip-chars-forward " \t") (setq ind1 (current-column))
3255 (if (or (< ind1 ind)
3256 (and (= ind1 ind)
3257 (not (org-at-item-p))))
3258 (throw 'exit t)))))
3259 ;; Walk forward and replace these numbers
3260 (catch 'exit
3261 (while t
3262 (catch 'next
3263 (beginning-of-line 2)
3264 (if (eobp) (throw 'exit nil))
3265 (if (looking-at "[ \t]*$") (throw 'next nil))
3266 (skip-chars-forward " \t") (setq ind1 (current-column))
3267 (if (> ind1 ind) (throw 'next t))
3268 (if (< ind1 ind) (throw 'exit t))
3269 (if (not (org-at-item-p)) (throw 'exit nil))
3270 (if (not (match-beginning 3))
3271 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3272 (delete-region (match-beginning 3) (1- (match-end 3)))
3273 (goto-char (match-beginning 3))
3274 (insert (format "%d" (setq n (1+ n)))))))
3275 (goto-line line)
3276 (move-to-column col)))
3277
3278 (defvar org-last-indent-begin-marker (make-marker))
3279 (defvar org-last-indent-end-marker (make-marker))
3280
3281
3282 (defun org-outdent-item (arg)
3283 "Outdent a local list item."
3284 (interactive "p")
3285 (org-indent-item (- arg)))
3286
3287 (defun org-indent-item (arg)
3288 "Indent a local list item."
3289 (interactive "p")
3290 (unless (org-at-item-p)
3291 (error "Not on an item"))
3292 (let (beg end ind ind1)
3293 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3294 (setq beg org-last-indent-begin-marker
3295 end org-last-indent-end-marker)
3296 (org-beginning-of-item)
3297 (setq beg (move-marker org-last-indent-begin-marker (point)))
3298 (org-end-of-item)
3299 (setq end (move-marker org-last-indent-end-marker (point))))
3300 (goto-char beg)
3301 (skip-chars-forward " \t") (setq ind (current-column))
3302 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3303 (while (< (point) end)
3304 (beginning-of-line 1)
3305 (skip-chars-forward " \t") (setq ind1 (current-column))
3306 (delete-region (point-at-bol) (point))
3307 (indent-to-column (+ ind1 arg))
3308 (beginning-of-line 2))
3309 (goto-char beg)))
3310
3311 ;;; Archiving
3312
3313 (defun org-archive-subtree ()
3314 "Move the current subtree to the archive.
3315 The archive can be a certain top-level heading in the current file, or in
3316 a different file. The tree will be moved to that location, the subtree
3317 heading be marked DONE, and the current time will be added."
3318 (interactive)
3319 ;; Save all relevant TODO keyword-relatex variables
3320 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3321 (tr-org-todo-keywords org-todo-keywords)
3322 (tr-org-todo-interpretation org-todo-interpretation)
3323 (tr-org-done-string org-done-string)
3324 (tr-org-todo-regexp org-todo-regexp)
3325 (tr-org-todo-line-regexp org-todo-line-regexp)
3326 (this-buffer (current-buffer))
3327 file heading buffer level newfile-p)
3328 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3329 (progn
3330 (setq file (format (match-string 1 org-archive-location)
3331 (file-name-nondirectory buffer-file-name))
3332 heading (match-string 2 org-archive-location)))
3333 (error "Invalid `org-archive-location'"))
3334 (if (> (length file) 0)
3335 (setq newfile-p (not (file-exists-p file))
3336 buffer (find-file-noselect file))
3337 (setq buffer (current-buffer)))
3338 (unless buffer
3339 (error "Cannot access file \"%s\"" file))
3340 (if (and (> (length heading) 0)
3341 (string-match "^\\*+" heading))
3342 (setq level (match-end 0))
3343 (setq heading nil level 0))
3344 (save-excursion
3345 ;; We first only copy, in case something goes wrong
3346 ;; we need to protect this-command, to avoid kill-region sets it,
3347 ;; which would lead to duplication of subtrees
3348 (let (this-command) (org-copy-subtree))
3349 (set-buffer buffer)
3350 ;; Enforce org-mode for the archive buffer
3351 (if (not (eq major-mode 'org-mode))
3352 ;; Force the mode for future visits.
3353 (let ((org-insert-mode-line-in-empty-file t))
3354 (call-interactively 'org-mode)))
3355 (when newfile-p
3356 (goto-char (point-max))
3357 (insert (format "\nArchived entries from file %s\n\n"
3358 (buffer-file-name this-buffer))))
3359 ;; Force the TODO keywords of the original buffer
3360 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3361 (org-todo-keywords tr-org-todo-keywords)
3362 (org-todo-interpretation tr-org-todo-interpretation)
3363 (org-done-string tr-org-done-string)
3364 (org-todo-regexp tr-org-todo-regexp)
3365 (org-todo-line-regexp tr-org-todo-line-regexp))
3366 (goto-char (point-min))
3367 (if heading
3368 (progn
3369 (if (re-search-forward
3370 (concat "\\(^\\|\r\\)"
3371 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3372 nil t)
3373 (goto-char (match-end 0))
3374 ;; Heading not found, just insert it at the end
3375 (goto-char (point-max))
3376 (or (bolp) (insert "\n"))
3377 (insert "\n" heading "\n")
3378 (end-of-line 0))
3379 ;; Make the heading visible, and the following as well
3380 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3381 (if (re-search-forward
3382 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3383 nil t)
3384 (progn (goto-char (match-beginning 0)) (insert "\n")
3385 (beginning-of-line 0))
3386 (goto-char (point-max)) (insert "\n")))
3387 (goto-char (point-max)) (insert "\n"))
3388 ;; Paste
3389 (org-paste-subtree (1+ level))
3390 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3391 (if org-archive-mark-done
3392 (org-todo (length org-todo-keywords)))
3393 ;; Move cursor to right after the TODO keyword
3394 (when org-archive-stamp-time
3395 (beginning-of-line 1)
3396 (looking-at org-todo-line-regexp)
3397 (goto-char (or (match-end 2) (match-beginning 3)))
3398 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3399 (current-time))
3400 ")"))
3401 ;; Save the buffer, if it is not the same buffer.
3402 (if (not (eq this-buffer buffer)) (save-buffer))))
3403 ;; Here we are back in the original buffer. Everything seems to have
3404 ;; worked. So now cut the tree and finish up.
3405 (let (this-command) (org-cut-subtree))
3406 (if (looking-at "[ \t]*$") (kill-line))
3407 (message "Subtree archived %s"
3408 (if (eq this-buffer buffer)
3409 (concat "under heading: " heading)
3410 (concat "in file: " (abbreviate-file-name file))))))
3411
3412 ;;; Completion
3413
3414 (defun org-complete (&optional arg)
3415 "Perform completion on word at point.
3416 At the beginning of a headline, this completes TODO keywords as given in
3417 `org-todo-keywords'.
3418 If the current word is preceded by a backslash, completes the TeX symbols
3419 that are supported for HTML support.
3420 If the current word is preceded by \"#+\", completes special words for
3421 setting file options.
3422 At all other locations, this simply calls `ispell-complete-word'."
3423 (interactive "P")
3424 (catch 'exit
3425 (let* ((end (point))
3426 (beg1 (save-excursion
3427 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3428 (skip-chars-backward "a-zA-Z_@0-9")
3429 (point)))
3430 (beg (save-excursion
3431 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3432 (skip-chars-backward "a-zA-Z0-9_:$")
3433 (point)))
3434 (camel (equal (char-before beg) ?*))
3435 (tag (equal (char-before beg1) ?:))
3436 (texp (equal (char-before beg) ?\\))
3437 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3438 beg)
3439 "#+"))
3440 (completion-ignore-case opt)
3441 (type nil)
3442 (tbl nil)
3443 (table (cond
3444 (opt
3445 (setq type :opt)
3446 (mapcar (lambda (x)
3447 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3448 (cons (match-string 2 x) (match-string 1 x)))
3449 (org-split-string (org-get-current-options) "\n")))
3450 (texp
3451 (setq type :tex)
3452 org-html-entities)
3453 ((string-match "\\`\\*+[ \t]*\\'"
3454 (buffer-substring (point-at-bol) beg))
3455 (setq type :todo)
3456 (mapcar 'list org-todo-keywords))
3457 (camel
3458 (setq type :camel)
3459 (save-excursion
3460 (goto-char (point-min))
3461 (while (re-search-forward org-todo-line-regexp nil t)
3462 (push (list
3463 (if org-file-link-context-use-camel-case
3464 (org-make-org-heading-camel (match-string 3) t)
3465 (org-make-org-heading-search-string
3466 (match-string 3) t)))
3467 tbl)))
3468 tbl)
3469 (tag (setq type :tag beg beg1)
3470 (org-get-buffer-tags))
3471 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3472 (pattern (buffer-substring-no-properties beg end))
3473 (completion (try-completion pattern table)))
3474 (cond ((eq completion t)
3475 (if (equal type :opt)
3476 (insert (substring (cdr (assoc (upcase pattern) table))
3477 (length pattern)))))
3478 ((null completion)
3479 (message "Can't find completion for \"%s\"" pattern)
3480 (ding))
3481 ((not (string= pattern completion))
3482 (delete-region beg end)
3483 (if (string-match " +$" completion)
3484 (setq completion (replace-match "" t t completion)))
3485 (insert completion)
3486 (if (get-buffer-window "*Completions*")
3487 (delete-window (get-buffer-window "*Completions*")))
3488 (if (assoc completion table)
3489 (if (eq type :todo) (insert " ")
3490 (if (eq type :tag) (insert ":"))))
3491 (if (and (equal type :opt) (assoc completion table))
3492 (message "%s" (substitute-command-keys
3493 "Press \\[org-complete] again to insert example settings"))))
3494 (t
3495 (message "Making completion list...")
3496 (let ((list (sort (all-completions pattern table) 'string<)))
3497 (with-output-to-temp-buffer "*Completions*"
3498 (condition-case nil
3499 ;; Protection needed for XEmacs and emacs 21
3500 (display-completion-list list pattern)
3501 (error (display-completion-list list)))))
3502 (message "Making completion list...%s" "done"))))))
3503
3504 ;;; Comments, TODO and DEADLINE
3505
3506 (defun org-toggle-comment ()
3507 "Change the COMMENT state of an entry."
3508 (interactive)
3509 (save-excursion
3510 (org-back-to-heading)
3511 (if (looking-at (concat outline-regexp
3512 "\\( +\\<" org-comment-string "\\>\\)"))
3513 (replace-match "" t t nil 1)
3514 (if (looking-at outline-regexp)
3515 (progn
3516 (goto-char (match-end 0))
3517 (insert " " org-comment-string))))))
3518
3519 (defvar org-last-todo-state-is-todo nil
3520 "This is non-nil when the last TODO state change led to a TODO state.
3521 If the last change removed the TODO tag or switched to DONE, then
3522 this is nil.")
3523
3524 (defun org-todo (&optional arg)
3525 "Change the TODO state of an item.
3526 The state of an item is given by a keyword at the start of the heading,
3527 like
3528 *** TODO Write paper
3529 *** DONE Call mom
3530
3531 The different keywords are specified in the variable `org-todo-keywords'.
3532 By default the available states are \"TODO\" and \"DONE\".
3533 So for this example: when the item starts with TODO, it is changed to DONE.
3534 When it starts with DONE, the DONE is removed. And when neither TODO nor
3535 DONE are present, add TODO at the beginning of the heading.
3536
3537 With prefix arg, use completion to determine the new state. With numeric
3538 prefix arg, switch to that state."
3539 (interactive "P")
3540 (save-excursion
3541 (org-back-to-heading)
3542 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3543 (or (looking-at (concat " +" org-todo-regexp " *"))
3544 (looking-at " *"))
3545 (let* ((this (match-string 1))
3546 (completion-ignore-case t)
3547 (member (member this org-todo-keywords))
3548 (tail (cdr member))
3549 (state (cond
3550 ((equal arg '(4))
3551 ;; Read a state with completion
3552 (completing-read "State: " (mapcar (lambda(x) (list x))
3553 org-todo-keywords)
3554 nil t))
3555 ((eq arg 'right)
3556 (if this
3557 (if tail (car tail) nil)
3558 (car org-todo-keywords)))
3559 ((eq arg 'left)
3560 (if (equal member org-todo-keywords)
3561 nil
3562 (if this
3563 (nth (- (length org-todo-keywords) (length tail) 2)
3564 org-todo-keywords)
3565 org-done-string)))
3566 (arg
3567 ;; user requests a specific state
3568 (nth (1- (prefix-numeric-value arg))
3569 org-todo-keywords))
3570 ((null member) (car org-todo-keywords))
3571 ((null tail) nil) ;; -> first entry
3572 ((eq org-todo-interpretation 'sequence)
3573 (car tail))
3574 ((memq org-todo-interpretation '(type priority))
3575 (if (eq this-command last-command)
3576 (car tail)
3577 (if (> (length tail) 0) org-done-string nil)))
3578 (t nil)))
3579 (next (if state (concat " " state " ") " ")))
3580 (replace-match next t t)
3581 (setq org-last-todo-state-is-todo
3582 (not (equal state org-done-string)))
3583 (when org-log-done
3584 (if (equal state org-done-string)
3585 (org-log-done)
3586 (if (not this)
3587 (org-log-done t))))
3588 ;; Fixup tag positioning
3589 (and org-auto-align-tags (org-set-tags nil t))
3590 (run-hooks 'org-after-todo-state-change-hook)))
3591 ;; Fixup cursor location if close to the keyword
3592 (if (and (outline-on-heading-p)
3593 (not (bolp))
3594 (save-excursion (beginning-of-line 1)
3595 (looking-at org-todo-line-regexp))
3596 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3597 (progn
3598 (goto-char (or (match-end 2) (match-end 1)))
3599 (just-one-space))))
3600
3601 (defun org-log-done (&optional undone)
3602 "Add a time stamp logging that a TODO entry has been closed.
3603 When UNDONE is non-nil, remove such a time stamp again."
3604 (interactive)
3605 (let (beg end col)
3606 (save-excursion
3607 (org-back-to-heading t)
3608 (setq beg (point))
3609 (looking-at (concat outline-regexp " *"))
3610 (goto-char (match-end 0))
3611 (setq col (current-column))
3612 (outline-next-heading)
3613 (setq end (point))
3614 (goto-char beg)
3615 (when (re-search-forward (concat
3616 "[\r\n]\\([ \t]*"
3617 (regexp-quote org-closed-string)
3618 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3619 (delete-region (match-beginning 1) (match-end 1)))
3620 (unless undone
3621 (org-back-to-heading t)
3622 (skip-chars-forward "^\n\r")
3623 (goto-char (min (1+ (point)) (point-max)))
3624 (when (not (member (char-before) '(?\r ?\n)))
3625 (insert "\n"))
3626 (indent-to col)
3627 (insert org-closed-string " "
3628 (format-time-string
3629 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3630 (current-time))
3631 "\n")))))
3632
3633 (defun org-show-todo-tree (arg)
3634 "Make a compact tree which shows all headlines marked with TODO.
3635 The tree will show the lines where the regexp matches, and all higher
3636 headlines above the match.
3637 With \\[universal-argument] prefix, also show the DONE entries.
3638 With a numeric prefix N, construct a sparse tree for the Nth element
3639 of `org-todo-keywords'."
3640 (interactive "P")
3641 (let ((case-fold-search nil)
3642 (kwd-re
3643 (cond ((null arg) org-not-done-regexp)
3644 ((equal arg '(4)) org-todo-regexp)
3645 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3646 (regexp-quote (nth (1- (prefix-numeric-value arg))
3647 org-todo-keywords)))
3648 (t (error "Invalid prefix argument: %s" arg)))))
3649 (message "%d TODO entries found"
3650 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3651
3652 (defun org-deadline ()
3653 "Insert the DEADLINE: string to make a deadline.
3654 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3655 to modify it to the correct date."
3656 (interactive)
3657 (insert
3658 org-deadline-string " "
3659 (format-time-string (car org-time-stamp-formats)
3660 (org-read-date nil 'to-time)))
3661 (message "%s" (substitute-command-keys
3662 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3663
3664 (defun org-schedule ()
3665 "Insert the SCHEDULED: string to schedule a TODO item.
3666 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3667 to modify it to the correct date."
3668 (interactive)
3669 (insert
3670 org-scheduled-string " "
3671 (format-time-string (car org-time-stamp-formats)
3672 (org-read-date nil 'to-time)))
3673 (message "%s" (substitute-command-keys
3674 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3675
3676
3677 (defun org-occur (regexp &optional callback)
3678 "Make a compact tree which shows all matches of REGEXP.
3679 The tree will show the lines where the regexp matches, and all higher
3680 headlines above the match. It will also show the heading after the match,
3681 to make sure editing the matching entry is easy.
3682 If CALLBACK is non-nil, it is a function which is called to confirm
3683 that the match should indeed be shown."
3684 (interactive "sRegexp: ")
3685 (org-remove-occur-highlights nil nil t)
3686 (setq regexp (org-check-occur-regexp regexp))
3687 (let ((cnt 0))
3688 (save-excursion
3689 (goto-char (point-min))
3690 (hide-sublevels 1)
3691 (while (re-search-forward regexp nil t)
3692 (when (or (not callback)
3693 (save-match-data (funcall callback)))
3694 (setq cnt (1+ cnt))
3695 (org-highlight-new-match (match-beginning 0) (match-end 0))
3696 (org-show-hierarchy-above))))
3697 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
3698 nil 'local)
3699 (run-hooks 'org-occur-hook)
3700 (if (interactive-p)
3701 (message "%d match(es) for regexp %s" cnt regexp))
3702 cnt))
3703
3704 (defun org-show-hierarchy-above ()
3705 "Make sure point and the headings hierarchy above is visible."
3706 (catch 'exit
3707 (if (org-on-heading-p t)
3708 (org-flag-heading nil) ; only show the heading
3709 (and (or (org-invisible-p) (org-invisible-p2))
3710 (org-show-hidden-entry))) ; show entire entry
3711 (save-excursion
3712 (and org-show-following-heading
3713 (outline-next-heading)
3714 (org-flag-heading nil))) ; show the next heading
3715 (when org-show-hierarchy-above
3716 (save-excursion ; show all higher headings
3717 (while (and (condition-case nil
3718 (progn (org-up-heading-all 1) t)
3719 (error nil))
3720 (not (bobp)))
3721 (org-flag-heading nil))))))
3722
3723 ;; Overlay compatibility functions
3724 (defun org-make-overlay (beg end &optional buffer)
3725 (if org-xemacs-p (make-extent beg end buffer) (make-overlay beg end buffer)))
3726 (defun org-delete-overlay (ovl)
3727 (if org-xemacs-p (delete-extent ovl) (delete-overlay ovl)))
3728 (defun org-detatch-overlay (ovl)
3729 (if org-xemacs-p (detach-extent ovl) (delete-overlay ovl)))
3730 (defun org-move-overlay (ovl beg end &optional buffer)
3731 (if org-xemacs-p
3732 (set-extent-endpoints ovl beg end buffer)
3733 (move-overlay ovl beg end buffer)))
3734 (defun org-overlay-put (ovl prop value)
3735 (if org-xemacs-p
3736 (set-extent-property ovl prop value)
3737 (overlay-put ovl prop value)))
3738
3739 (defvar org-occur-highlights nil)
3740 (defun org-highlight-new-match (beg end)
3741 "Highlight from BEG to END and mark the highlight is an occur headline."
3742 (let ((ov (org-make-overlay beg end)))
3743 (org-overlay-put ov 'face 'secondary-selection)
3744 (push ov org-occur-highlights)))
3745
3746 (defun org-remove-occur-highlights (&optional beg end noremove)
3747 "Remove the occur highlights from the buffer.
3748 BEG and END are ignored. If NOREMOVE is nil, remove this function
3749 from the `before-change-functions' in the current buffer."
3750 (interactive)
3751 (mapc 'org-delete-overlay org-occur-highlights)
3752 (setq org-occur-highlights nil)
3753 (unless noremove
3754 (remove-hook 'before-change-functions
3755 'org-remove-occur-highlights 'local)))
3756
3757 ;;; Priorities
3758
3759 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3760 "Regular expression matching the priority indicator.")
3761
3762 (defvar org-remove-priority-next-time nil)
3763
3764 (defun org-priority-up ()
3765 "Increase the priority of the current item."
3766 (interactive)
3767 (org-priority 'up))
3768
3769 (defun org-priority-down ()
3770 "Decrease the priority of the current item."
3771 (interactive)
3772 (org-priority 'down))
3773
3774 (defun org-priority (&optional action)
3775 "Change the priority of an item by ARG.
3776 ACTION can be set, up, or down."
3777 (interactive)
3778 (setq action (or action 'set))
3779 (let (current new news have remove)
3780 (save-excursion
3781 (org-back-to-heading)
3782 (if (looking-at org-priority-regexp)
3783 (setq current (string-to-char (match-string 2))
3784 have t)
3785 (setq current org-default-priority))
3786 (cond
3787 ((eq action 'set)
3788 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3789 (setq new (read-char-exclusive))
3790 (cond ((equal new ?\ ) (setq remove t))
3791 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3792 (error "Priority must be between `%c' and `%c'"
3793 ?A org-lowest-priority))))
3794 ((eq action 'up)
3795 (setq new (1- current)))
3796 ((eq action 'down)
3797 (setq new (1+ current)))
3798 (t (error "Invalid action")))
3799 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3800 (setq news (format "%c" new))
3801 (if have
3802 (if remove
3803 (replace-match "" t t nil 1)
3804 (replace-match news t t nil 2))
3805 (if remove
3806 (error "No priority cookie found in line")
3807 (looking-at org-todo-line-regexp)
3808 (if (match-end 2)
3809 (progn
3810 (goto-char (match-end 2))
3811 (insert " [#" news "]"))
3812 (goto-char (match-beginning 3))
3813 (insert "[#" news "] ")))))
3814 (if remove
3815 (message "Priority removed")
3816 (message "Priority of current item set to %s" news))))
3817
3818
3819 (defun org-get-priority (s)
3820 "Find priority cookie and return priority."
3821 (save-match-data
3822 (if (not (string-match org-priority-regexp s))
3823 (* 1000 (- org-lowest-priority org-default-priority))
3824 (* 1000 (- org-lowest-priority
3825 (string-to-char (match-string 2 s)))))))
3826
3827 ;;; Timestamps
3828
3829 (defvar org-last-changed-timestamp nil)
3830
3831 (defun org-time-stamp (arg)
3832 "Prompt for a date/time and insert a time stamp.
3833 If the user specifies a time like HH:MM, or if this command is called
3834 with a prefix argument, the time stamp will contain date and time.
3835 Otherwise, only the date will be included. All parts of a date not
3836 specified by the user will be filled in from the current date/time.
3837 So if you press just return without typing anything, the time stamp
3838 will represent the current date/time. If there is already a timestamp
3839 at the cursor, it will be modified."
3840 (interactive "P")
3841 (let ((fmt (if arg (cdr org-time-stamp-formats)
3842 (car org-time-stamp-formats)))
3843 (org-time-was-given nil)
3844 time)
3845 (cond
3846 ((and (org-at-timestamp-p)
3847 (eq last-command 'org-time-stamp)
3848 (eq this-command 'org-time-stamp))
3849 (insert "--")
3850 (setq time (let ((this-command this-command))
3851 (org-read-date arg 'totime)))
3852 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3853 (insert (format-time-string fmt time)))
3854 ((org-at-timestamp-p)
3855 (setq time (let ((this-command this-command))
3856 (org-read-date arg 'totime)))
3857 (and (org-at-timestamp-p) (replace-match
3858 (setq org-last-changed-timestamp
3859 (format-time-string fmt time))
3860 t t))
3861 (message "Timestamp updated"))
3862 (t
3863 (setq time (let ((this-command this-command))
3864 (org-read-date arg 'totime)))
3865 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3866 (insert (format-time-string fmt time))))))
3867
3868 (defun org-time-stamp-inactive (&optional arg)
3869 "Insert an inactive time stamp.
3870 An inactive time stamp is enclosed in square brackets instead of angle
3871 brackets. It is inactive in the sense that it does not trigger agenda entries,
3872 does not link to the calendar and cannot be changed with the S-cursor keys.
3873 So these are more for recording a certain time/date."
3874 ;; FIXME: Would it be better not to ask for a date/time here?
3875 (interactive "P")
3876 (let ((fmt (if arg (cdr org-time-stamp-formats)
3877 (car org-time-stamp-formats)))
3878 (org-time-was-given nil)
3879 time)
3880 (setq time (org-read-date arg 'totime))
3881 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3882 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3883 (insert (format-time-string fmt time))))
3884
3885 (defvar org-date-ovl (org-make-overlay 1 1))
3886 (org-overlay-put org-date-ovl 'face 'org-warning)
3887 (org-detatch-overlay org-date-ovl)
3888
3889 ;;; FIXME: Make the function take "Fri" as "next friday"
3890 ;;; because these are mostly being used to record the current time.
3891 (defun org-read-date (&optional with-time to-time)
3892 "Read a date and make things smooth for the user.
3893 The prompt will suggest to enter an ISO date, but you can also enter anything
3894 which will at least partially be understood by `parse-time-string'.
3895 Unrecognized parts of the date will default to the current day, month, year,
3896 hour and minute. For example,
3897 3-2-5 --> 2003-02-05
3898 feb 15 --> currentyear-02-15
3899 sep 12 9 --> 2009-09-12
3900 12:45 --> today 12:45
3901 22 sept 0:34 --> currentyear-09-22 0:34
3902 12 --> currentyear-currentmonth-12
3903 etc.
3904 The function understands only English month and weekday abbreviations,
3905 but this can be configured with the variables `parse-time-months' and
3906 `parse-time-weekdays'.
3907
3908 While prompting, a calendar is popped up - you can also select the
3909 date with the mouse (button 1). The calendar shows a period of three
3910 months. To scroll it to other months, use the keys `>' and `<'.
3911 If you don't like the calendar, turn it off with
3912 \(setq org-popup-calendar-for-date-prompt nil)
3913
3914 With optional argument TO-TIME, the date will immediately be converted
3915 to an internal time.
3916 With an optional argument WITH-TIME, the prompt will suggest to also
3917 insert a time. Note that when WITH-TIME is not set, you can still
3918 enter a time, and this function will inform the calling routine about
3919 this change. The calling routine may then choose to change the format
3920 used to insert the time stamp into the buffer to include the time."
3921 (require 'parse-time)
3922 (let* ((default-time
3923 ;; Default time is either today, or, when entering a range,
3924 ;; the range start.
3925 (if (save-excursion
3926 (re-search-backward
3927 (concat org-ts-regexp "--\\=")
3928 (- (point) 20) t))
3929 (apply
3930 'encode-time
3931 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3932 (parse-time-string (match-string 1))))
3933 (current-time)))
3934 (calendar-move-hook nil)
3935 (view-diary-entries-initially nil)
3936 (timestr (format-time-string
3937 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3938 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3939 ans ans1 ans2
3940 second minute hour day month year tl)
3941
3942 (if org-popup-calendar-for-date-prompt
3943 ;; Also show a calendar for date selection
3944 ;; Copied (with modifications) from planner.el by John Wiegley
3945 (save-excursion
3946 (save-window-excursion
3947 (calendar)
3948 (calendar-forward-day (- (time-to-days default-time)
3949 (calendar-absolute-from-gregorian
3950 (calendar-current-date))))
3951 (org-eval-in-calendar nil)
3952 (let* ((old-map (current-local-map))
3953 (map (copy-keymap calendar-mode-map))
3954 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3955 (define-key map (kbd "RET") 'org-calendar-select)
3956 (define-key map (if org-xemacs-p [button1] [mouse-1])
3957 'org-calendar-select-mouse)
3958 (define-key map (if org-xemacs-p [button2] [mouse-2])
3959 'org-calendar-select-mouse)
3960 (define-key minibuffer-local-map [(meta shift left)]
3961 (lambda () (interactive)
3962 (org-eval-in-calendar '(calendar-backward-month 1))))
3963 (define-key minibuffer-local-map [(meta shift right)]
3964 (lambda () (interactive)
3965 (org-eval-in-calendar '(calendar-forward-month 1))))
3966 (define-key minibuffer-local-map [(shift up)]
3967 (lambda () (interactive)
3968 (org-eval-in-calendar '(calendar-backward-week 1))))
3969 (define-key minibuffer-local-map [(shift down)]
3970 (lambda () (interactive)
3971 (org-eval-in-calendar '(calendar-forward-week 1))))
3972 (define-key minibuffer-local-map [(shift left)]
3973 (lambda () (interactive)
3974 (org-eval-in-calendar '(calendar-backward-day 1))))
3975 (define-key minibuffer-local-map [(shift right)]
3976 (lambda () (interactive)
3977 (org-eval-in-calendar '(calendar-forward-day 1))))
3978 (define-key minibuffer-local-map ">"
3979 (lambda () (interactive)
3980 (org-eval-in-calendar '(scroll-calendar-left 1))))
3981 (define-key minibuffer-local-map "<"
3982 (lambda () (interactive)
3983 (org-eval-in-calendar '(scroll-calendar-right 1))))
3984 (unwind-protect
3985 (progn
3986 (use-local-map map)
3987 (setq ans (read-string prompt "" nil nil))
3988 (if (not (string-match "\\S-" ans)) (setq ans nil))
3989 (setq ans (or ans1 ans ans2)))
3990 (use-local-map old-map)))))
3991 ;; Naked prompt only
3992 (setq ans (read-string prompt "" nil timestr)))
3993 (org-detatch-overlay org-date-ovl)
3994
3995 (if (string-match
3996 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3997 (progn
3998 (setq year (if (match-end 2)
3999 (string-to-number (match-string 2 ans))
4000 (string-to-number (format-time-string "%Y")))
4001 month (string-to-number (match-string 3 ans))
4002 day (string-to-number (match-string 4 ans)))
4003 (if (< year 100) (setq year (+ 2000 year)))
4004 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
4005 t t ans))))
4006 (setq tl (parse-time-string ans)
4007 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
4008 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
4009 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
4010 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
4011 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
4012 second (or (nth 0 tl) 0))
4013 (if (and (boundp 'org-time-was-given)
4014 (nth 2 tl))
4015 (setq org-time-was-given t))
4016 (if (< year 100) (setq year (+ 2000 year)))
4017 (if to-time
4018 (encode-time second minute hour day month year)
4019 (if (or (nth 1 tl) (nth 2 tl))
4020 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4021 (format "%04d-%02d-%02d" year month day)))))
4022
4023 (defun org-eval-in-calendar (form)
4024 "Eval FORM in the calendar window and return to current window.
4025 Also, store the cursor date in variable ans2."
4026 (let ((sw (selected-window)))
4027 (select-window (get-buffer-window "*Calendar*"))
4028 (eval form)
4029 (when (calendar-cursor-to-date)
4030 (let* ((date (calendar-cursor-to-date))
4031 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4032 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4033 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4034 (select-window sw)))
4035
4036 (defun org-calendar-select ()
4037 "Return to `org-read-date' with the date currently selected.
4038 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4039 (interactive)
4040 (when (calendar-cursor-to-date)
4041 (let* ((date (calendar-cursor-to-date))
4042 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4043 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4044 (if (active-minibuffer-window) (exit-minibuffer))))
4045
4046 (defun org-calendar-select-mouse (ev)
4047 "Return to `org-read-date' with the date currently selected.
4048 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4049 (interactive "e")
4050 (mouse-set-point ev)
4051 (when (calendar-cursor-to-date)
4052 (let* ((date (calendar-cursor-to-date))
4053 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4054 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4055 (if (active-minibuffer-window) (exit-minibuffer))))
4056
4057 (defun org-check-deadlines (ndays)
4058 "Check if there are any deadlines due or past due.
4059 A deadline is considered due if it happens within `org-deadline-warning-days'
4060 days from today's date. If the deadline appears in an entry marked DONE,
4061 it is not shown. The prefix arg NDAYS can be used to test that many
4062 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4063 (interactive "P")
4064 (let* ((org-warn-days
4065 (cond
4066 ((equal ndays '(4)) 100000)
4067 (ndays (prefix-numeric-value ndays))
4068 (t org-deadline-warning-days)))
4069 (case-fold-search nil)
4070 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4071 (callback
4072 (lambda ()
4073 (and (let ((d1 (time-to-days (current-time)))
4074 (d2 (time-to-days
4075 (org-time-string-to-time (match-string 1)))))
4076 (< (- d2 d1) org-warn-days))
4077 (not (org-entry-is-done-p))))))
4078 (message "%d deadlines past-due or due within %d days"
4079 (org-occur regexp callback)
4080 org-warn-days)))
4081
4082 (defun org-evaluate-time-range (&optional to-buffer)
4083 "Evaluate a time range by computing the difference between start and end.
4084 Normally the result is just printed in the echo area, but with prefix arg
4085 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4086 If the time range is actually in a table, the result is inserted into the
4087 next column.
4088 For time difference computation, a year is assumed to be exactly 365
4089 days in order to avoid rounding problems."
4090 (interactive "P")
4091 (save-excursion
4092 (unless (org-at-date-range-p)
4093 (goto-char (point-at-bol))
4094 (re-search-forward org-tr-regexp (point-at-eol) t))
4095 (if (not (org-at-date-range-p))
4096 (error "Not at a time-stamp range, and none found in current line")))
4097 (let* ((ts1 (match-string 1))
4098 (ts2 (match-string 2))
4099 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4100 (match-end (match-end 0))
4101 (time1 (org-time-string-to-time ts1))
4102 (time2 (org-time-string-to-time ts2))
4103 (t1 (time-to-seconds time1))
4104 (t2 (time-to-seconds time2))
4105 (diff (abs (- t2 t1)))
4106 (negative (< (- t2 t1) 0))
4107 ;; (ys (floor (* 365 24 60 60)))
4108 (ds (* 24 60 60))
4109 (hs (* 60 60))
4110 (fy "%dy %dd %02d:%02d")
4111 (fy1 "%dy %dd")
4112 (fd "%dd %02d:%02d")
4113 (fd1 "%dd")
4114 (fh "%02d:%02d")
4115 y d h m align)
4116 ;; FIXME: Should I re-introduce years, make year refer to same date?
4117 ;; This would be the only useful way to have years, actually.
4118 (if havetime
4119 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4120 y 0
4121 d (floor (/ diff ds)) diff (mod diff ds)
4122 h (floor (/ diff hs)) diff (mod diff hs)
4123 m (floor (/ diff 60)))
4124 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4125 y 0
4126 d (floor (+ (/ diff ds) 0.5))
4127 h 0 m 0))
4128 (if (not to-buffer)
4129 (message (org-make-tdiff-string y d h m))
4130 (when (org-at-table-p)
4131 (goto-char match-end)
4132 (setq align t)
4133 (and (looking-at " *|") (goto-char (match-end 0))))
4134 (if (looking-at
4135 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4136 (replace-match ""))
4137 (if negative (insert " -"))
4138 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4139 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4140 (insert " " (format fh h m))))
4141 (if align (org-table-align))
4142 (message "Time difference inserted"))))
4143
4144 (defun org-make-tdiff-string (y d h m)
4145 (let ((fmt "")
4146 (l nil))
4147 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4148 l (push y l)))
4149 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4150 l (push d l)))
4151 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4152 l (push h l)))
4153 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4154 l (push m l)))
4155 (apply 'format fmt (nreverse l))))
4156
4157 (defun org-time-string-to-time (s)
4158 (apply 'encode-time (org-parse-time-string s)))
4159
4160 (defun org-parse-time-string (s &optional nodefault)
4161 "Parse the standard Org-mode time string.
4162 This should be a lot faster than the normal `parse-time-string'.
4163 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4164 hour and minute fields will be nil if not given."
4165 (if (string-match org-ts-regexp1 s)
4166 (list 0
4167 (if (or (match-beginning 8) (not nodefault))
4168 (string-to-number (or (match-string 8 s) "0")))
4169 (if (or (match-beginning 7) (not nodefault))
4170 (string-to-number (or (match-string 7 s) "0")))
4171 (string-to-number (match-string 4 s))
4172 (string-to-number (match-string 3 s))
4173 (string-to-number (match-string 2 s))
4174 nil nil nil)
4175 (make-list 9 0)))
4176
4177 (defun org-timestamp-up (&optional arg)
4178 "Increase the date item at the cursor by one.
4179 If the cursor is on the year, change the year. If it is on the month or
4180 the day, change that.
4181 With prefix ARG, change by that many units."
4182 (interactive "p")
4183 (org-timestamp-change (prefix-numeric-value arg)))
4184
4185 (defun org-timestamp-down (&optional arg)
4186 "Decrease the date item at the cursor by one.
4187 If the cursor is on the year, change the year. If it is on the month or
4188 the day, change that.
4189 With prefix ARG, change by that many units."
4190 (interactive "p")
4191 (org-timestamp-change (- (prefix-numeric-value arg))))
4192
4193 (defun org-timestamp-up-day (&optional arg)
4194 "Increase the date in the time stamp by one day.
4195 With prefix ARG, change that many days."
4196 (interactive "p")
4197 (if (and (not (org-at-timestamp-p))
4198 (org-on-heading-p))
4199 (org-todo 'up)
4200 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4201
4202 (defun org-timestamp-down-day (&optional arg)
4203 "Decrease the date in the time stamp by one day.
4204 With prefix ARG, change that many days."
4205 (interactive "p")
4206 (if (and (not (org-at-timestamp-p))
4207 (org-on-heading-p))
4208 (org-todo 'down)
4209 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4210
4211 (defsubst org-pos-in-match-range (pos n)
4212 (and (match-beginning n)
4213 (<= (match-beginning n) pos)
4214 (>= (match-end n) pos)))
4215
4216 (defun org-at-timestamp-p ()
4217 "Determine if the cursor is in or at a timestamp."
4218 (interactive)
4219 (let* ((tsr org-ts-regexp2)
4220 (pos (point))
4221 (ans (or (looking-at tsr)
4222 (save-excursion
4223 (skip-chars-backward "^<\n\r\t")
4224 (if (> (point) 1) (backward-char 1))
4225 (and (looking-at tsr)
4226 (> (- (match-end 0) pos) -1))))))
4227 (and (boundp 'org-ts-what)
4228 (setq org-ts-what
4229 (cond
4230 ((org-pos-in-match-range pos 2) 'year)
4231 ((org-pos-in-match-range pos 3) 'month)
4232 ((org-pos-in-match-range pos 7) 'hour)
4233 ((org-pos-in-match-range pos 8) 'minute)
4234 ((or (org-pos-in-match-range pos 4)
4235 (org-pos-in-match-range pos 5)) 'day)
4236 (t 'day))))
4237 ans))
4238
4239 (defun org-timestamp-change (n &optional what)
4240 "Change the date in the time stamp at point.
4241 The date will be changed by N times WHAT. WHAT can be `day', `month',
4242 `year', `minute', `second'. If WHAT is not given, the cursor position
4243 in the timestamp determines what will be changed."
4244 (let ((fmt (car org-time-stamp-formats))
4245 org-ts-what
4246 (pos (point))
4247 ts time time0)
4248 (if (not (org-at-timestamp-p))
4249 (error "Not at a timestamp"))
4250 (setq org-ts-what (or what org-ts-what))
4251 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4252 (- (match-end 0) (match-beginning 0))))
4253 1)
4254 (cdr org-time-stamp-formats)
4255 (car org-time-stamp-formats)))
4256 (setq ts (match-string 0))
4257 (replace-match "")
4258 (setq time0 (org-parse-time-string ts))
4259 (setq time
4260 (apply 'encode-time
4261 (append
4262 (list (or (car time0) 0))
4263 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4264 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4265 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4266 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4267 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4268 (nthcdr 6 time0))))
4269 (if (eq what 'calendar)
4270 (let ((cal-date
4271 (save-excursion
4272 (save-match-data
4273 (set-buffer "*Calendar*")
4274 (calendar-cursor-to-date)))))
4275 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4276 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4277 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4278 (setcar time0 (or (car time0) 0))
4279 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4280 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4281 (setq time (apply 'encode-time time0))))
4282 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4283 (goto-char pos)
4284 ;; Try to recenter the calendar window, if any
4285 (if (and org-calendar-follow-timestamp-change
4286 (get-buffer-window "*Calendar*" t)
4287 (memq org-ts-what '(day month year)))
4288 (org-recenter-calendar (time-to-days time)))))
4289
4290 (defun org-recenter-calendar (date)
4291 "If the calendar is visible, recenter it to DATE."
4292 (let* ((win (selected-window))
4293 (cwin (get-buffer-window "*Calendar*" t))
4294 (calendar-move-hook nil))
4295 (when cwin
4296 (select-window cwin)
4297 (calendar-goto-date (if (listp date) date
4298 (calendar-gregorian-from-absolute date)))
4299 (select-window win))))
4300
4301 (defun org-goto-calendar (&optional arg)
4302 "Go to the Emacs calendar at the current date.
4303 If there is a time stamp in the current line, go to that date.
4304 A prefix ARG can be used to force the current date."
4305 (interactive "P")
4306 (let ((tsr org-ts-regexp) diff
4307 (calendar-move-hook nil)
4308 (view-diary-entries-initially nil))
4309 (if (or (org-at-timestamp-p)
4310 (save-excursion
4311 (beginning-of-line 1)
4312 (looking-at (concat ".*" tsr))))
4313 (let ((d1 (time-to-days (current-time)))
4314 (d2 (time-to-days
4315 (org-time-string-to-time (match-string 1)))))
4316 (setq diff (- d2 d1))))
4317 (calendar)
4318 (calendar-goto-today)
4319 (if (and diff (not arg)) (calendar-forward-day diff))))
4320
4321 (defun org-date-from-calendar ()
4322 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4323 If there is already a time stamp at the cursor position, update it."
4324 (interactive)
4325 (org-timestamp-change 0 'calendar))
4326
4327 ;;; Agenda, and Diary Integration
4328
4329 ;;; Define the mode
4330
4331 (defvar org-agenda-mode-map (make-sparse-keymap)
4332 "Keymap for `org-agenda-mode'.")
4333
4334 (defvar org-agenda-menu)
4335 (defvar org-agenda-follow-mode nil)
4336 (defvar org-agenda-show-log nil)
4337 (defvar org-agenda-buffer-name "*Org Agenda*")
4338 (defvar org-agenda-redo-command nil)
4339 (defvar org-agenda-mode-hook nil)
4340 (defvar org-agenda-type nil)
4341 (defvar org-agenda-force-single-file nil)
4342
4343 ;;;###autoload
4344 (defun org-agenda-mode ()
4345 "Mode for time-sorted view on action items in Org-mode files.
4346
4347 The following commands are available:
4348
4349 \\{org-agenda-mode-map}"
4350 (interactive)
4351 (kill-all-local-variables)
4352 (setq major-mode 'org-agenda-mode)
4353 (setq mode-name "Org-Agenda")
4354 (use-local-map org-agenda-mode-map)
4355 (easy-menu-add org-agenda-menu)
4356 (if org-startup-truncated (setq truncate-lines t))
4357 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4358 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4359 (unless org-agenda-keep-modes
4360 (setq org-agenda-follow-mode nil
4361 org-agenda-show-log nil))
4362 (easy-menu-change
4363 '("Agenda") "Agenda Files"
4364 (append
4365 (list
4366 (vector
4367 (if (get 'org-agenda-files 'org-restrict)
4368 "Restricted to single file"
4369 "Edit File List")
4370 '(customize-variable 'org-agenda-files)
4371 (not (get 'org-agenda-files 'org-restrict)))
4372 "--")
4373 (mapcar 'org-file-menu-entry (org-agenda-files))))
4374 (org-agenda-set-mode-name)
4375 (apply
4376 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4377 (list 'org-agenda-mode-hook)))
4378
4379 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4380 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4381 (define-key org-agenda-mode-map " " 'org-agenda-show)
4382 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4383 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4384 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4385 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4386 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4387 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4388 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4389 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4390 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4391 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4392 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4393 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4394
4395 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4396 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4397 (while l (define-key org-agenda-mode-map
4398 (int-to-string (pop l)) 'digit-argument)))
4399
4400 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4401 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4402 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4403 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4404 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4405 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4406 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4407 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4408 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4409 (define-key org-agenda-mode-map "n" 'next-line)
4410 (define-key org-agenda-mode-map "p" 'previous-line)
4411 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4412 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4413 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4414 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4415 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4416 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4417 (eval-after-load "calendar"
4418 '(define-key calendar-mode-map org-calendar-to-agenda-key
4419 'org-calendar-goto-agenda))
4420 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4421 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4422 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4423 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4424 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4425 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4426 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4427 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4428 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4429 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4430 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4431 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4432 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4433 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4434 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4435 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4436 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4437 "Local keymap for agenda entries from Org-mode.")
4438
4439 (define-key org-agenda-keymap
4440 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4441 (define-key org-agenda-keymap
4442 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4443 (define-key org-agenda-keymap [follow-link] 'mouse-face)
4444 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4445 '("Agenda"
4446 ("Agenda Files")
4447 "--"
4448 ["Show" org-agenda-show t]
4449 ["Go To (other window)" org-agenda-goto t]
4450 ["Go To (one window)" org-agenda-switch-to t]
4451 ["Follow Mode" org-agenda-follow-mode
4452 :style toggle :selected org-agenda-follow-mode :active t]
4453 "--"
4454 ["Cycle TODO" org-agenda-todo t]
4455 ("Tags"
4456 ["Show all Tags" org-agenda-show-tags t]
4457 ["Set Tags" org-agenda-set-tags t])
4458 ("Reschedule"
4459 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4460 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4461 "--"
4462 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4463 ("Priority"
4464 ["Set Priority" org-agenda-priority t]
4465 ["Increase Priority" org-agenda-priority-up t]
4466 ["Decrease Priority" org-agenda-priority-down t]
4467 ["Show Priority" org-agenda-show-priority t])
4468 "--"
4469 ;; ["New agenda command" org-agenda t]
4470 ["Rebuild buffer" org-agenda-redo t]
4471 "--"
4472 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4473 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4474 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4475 "--"
4476 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4477 :style radio :selected (equal org-agenda-ndays 1)]
4478 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4479 :style radio :selected (equal org-agenda-ndays 7)]
4480 "--"
4481 ["Show Logbook entries" org-agenda-log-mode
4482 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4483 ["Include Diary" org-agenda-toggle-diary
4484 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4485 ["Use Time Grid" org-agenda-toggle-time-grid
4486 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4487 "--"
4488 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4489 ("Calendar Commands"
4490 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4491 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4492 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4493 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4494 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4495 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4496 "--"
4497 ["Quit" org-agenda-quit t]
4498 ["Exit and Release Buffers" org-agenda-exit t]
4499 ))
4500
4501 ;;;###autoload
4502 (defun org-agenda (arg)
4503 "Dispatch agenda commands to collect entries to the agenda buffer.
4504 Prompts for a character to select a command. Any prefix arg will be passed
4505 on to the selected command. The default selections are:
4506
4507 a Call `org-agenda' to display the agenda for the current day or week.
4508 t Call `org-todo-list' to display the global todo list.
4509 T Call `org-todo-list' to display the global todo list, select only
4510 entries with a specific TODO keyword (the user gets a prompt).
4511 m Call `org-tags-view' to display headlines with tags matching
4512 a condition (the user is prompted for the condition).
4513 M Like `m', but select only TODO entries, no ordinary headlines.
4514
4515 More commands can be added by configuring the variable
4516 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4517 searches can be pre-defined in this way.
4518
4519 If the current buffer is in Org-mode and visiting a file, you can also
4520 first press `1' to indicate that the agenda should be temporarily (until the
4521 next use of \\[org-agenda]) restricted to the current file."
4522 (interactive "P")
4523 (catch 'exit
4524 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4525 (custom org-agenda-custom-commands)
4526 c entry key type string)
4527 (put 'org-agenda-files 'org-restrict nil)
4528 (save-window-excursion
4529 (delete-other-windows)
4530 (switch-to-buffer-other-window " *Agenda Commands*")
4531 (erase-buffer)
4532 (insert
4533 "Press key for an agenda command:
4534 --------------------------------
4535 a Agenda for current week or day
4536 t List of all TODO entries T Entries with special TODO kwd
4537 m Match a TAGS query M Like m, but only TODO entries
4538 C Configure your own agenda commands")
4539 (while (setq entry (pop custom))
4540 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4541 (insert (format "\n%-4s%-14s: %s"
4542 key
4543 (cond
4544 ((eq type 'tags) "Tags query")
4545 ((eq type 'todo) "TODO keyword")
4546 ((eq type 'tags-tree) "Tags tree")
4547 ((eq type 'todo-tree) "TODO kwd tree")
4548 ((eq type 'occur-tree) "Occur tree")
4549 (t "???"))
4550 (org-string-props string 'face 'org-link))))
4551 (goto-char (point-min))
4552 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4553 (message "Press key for agenda command%s"
4554 (if restrict-ok ", or [1] to restrict to current file" ""))
4555 (setq c (read-char-exclusive))
4556 (message "")
4557 (when (equal c ?1)
4558 (if restrict-ok
4559 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
4560 (error "Cannot restrict agenda to current buffer"))
4561 (message "Press key for agenda command%s"
4562 (if restrict-ok " (restricted to current file)" ""))
4563 (setq c (read-char-exclusive))
4564 (message "")))
4565 (require 'calendar) ; FIXME: can we avoid this for some commands?
4566 ;; For example the todo list should not need it (but does...)
4567 (cond
4568 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4569 ((equal c ?a) (call-interactively 'org-agenda-list))
4570 ((equal c ?t) (call-interactively 'org-todo-list))
4571 ((equal c ?T)
4572 (setq current-prefix-arg (or arg '(4)))
4573 (call-interactively 'org-todo-list))
4574 ((equal c ?m) (call-interactively 'org-tags-view))
4575 ((equal c ?M)
4576 (setq current-prefix-arg (or arg '(4)))
4577 (call-interactively 'org-tags-view))
4578 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4579 (setq type (nth 1 entry) string (nth 2 entry))
4580 (cond
4581 ((eq type 'tags)
4582 (org-tags-view current-prefix-arg string))
4583 ((eq type 'todo)
4584 (org-todo-list string))
4585 ((eq type 'tags-tree)
4586 (org-check-for-org-mode)
4587 (org-tags-sparse-tree current-prefix-arg string))
4588 ((eq type 'todo-tree)
4589 (org-check-for-org-mode)
4590 (org-occur (concat "^" outline-regexp "[ \t]*"
4591 (regexp-quote string) "\\>")))
4592 ((eq type 'occur-tree)
4593 (org-check-for-org-mode)
4594 (org-occur string))
4595 (t (error "Invalid custom agenda command type %s" type))))
4596 (t (error "Invalid key"))))))
4597
4598 (defun org-check-for-org-mode ()
4599 "Make sure current buffer is in org-mode. Error if not."
4600 (or (eq major-mode 'org-mode)
4601 (error "Cannot execute org-mode agenda command on buffer in %s."
4602 major-mode)))
4603
4604 (defun org-fit-agenda-window ()
4605 "Fit the window to the buffer size."
4606 (and org-fit-agenda-window
4607 (fboundp 'fit-window-to-buffer)
4608 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4609 (/ (frame-height) 2))))
4610
4611 (defun org-agenda-files ()
4612 "Get the list of agenda files."
4613 (or (get 'org-agenda-files 'org-restrict)
4614 org-agenda-files))
4615
4616 (defvar org-agenda-markers nil
4617 "List of all currently active markers created by `org-agenda'.")
4618 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4619 "Creation time of the last agenda marker.")
4620
4621 (defun org-agenda-new-marker (&optional pos)
4622 "Return a new agenda marker.
4623 Org-mode keeps a list of these markers and resets them when they are
4624 no longer in use."
4625 (let ((m (copy-marker (or pos (point)))))
4626 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4627 (push m org-agenda-markers)
4628 m))
4629
4630 (defun org-agenda-maybe-reset-markers (&optional force)
4631 "Reset markers created by `org-agenda'. But only if they are old enough."
4632 (if (or force
4633 (> (- (time-to-seconds (current-time))
4634 org-agenda-last-marker-time)
4635 5))
4636 (while org-agenda-markers
4637 (move-marker (pop org-agenda-markers) nil))))
4638
4639 (defvar org-agenda-new-buffers nil
4640 "Buffers created to visit agenda files.")
4641
4642 (defun org-get-agenda-file-buffer (file)
4643 "Get a buffer visiting FILE. If the buffer needs to be created, add
4644 it to the list of buffers which might be released later."
4645 (let ((buf (find-buffer-visiting file)))
4646 (if buf
4647 buf ; just return it
4648 ;; Make a new buffer and remember it
4649 (setq buf (find-file-noselect file))
4650 (if buf (push buf org-agenda-new-buffers))
4651 buf)))
4652
4653 (defun org-release-buffers (blist)
4654 "Release all buffers in list, asking the user for confirmation when needed.
4655 When a buffer is unmodified, it is just killed. When modified, it is saved
4656 \(if the user agrees) and then killed."
4657 (let (buf file)
4658 (while (setq buf (pop blist))
4659 (setq file (buffer-file-name buf))
4660 (when (and (buffer-modified-p buf)
4661 file
4662 (y-or-n-p (format "Save file %s? " file)))
4663 (with-current-buffer buf (save-buffer)))
4664 (kill-buffer buf))))
4665
4666 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4667
4668 (defun org-timeline (&optional include-all keep-modes)
4669 "Show a time-sorted view of the entries in the current org file.
4670 Only entries with a time stamp of today or later will be listed. With
4671 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4672 under the current date.
4673 If the buffer contains an active region, only check the region for
4674 dates."
4675 (interactive "P")
4676 (require 'calendar)
4677 (org-agenda-maybe-reset-markers 'force)
4678 (org-compile-prefix-format org-timeline-prefix-format)
4679 (let* ((dopast t)
4680 (dotodo include-all)
4681 (doclosed org-agenda-show-log)
4682 (org-agenda-keep-modes keep-modes)
4683 (entry buffer-file-name)
4684 (org-agenda-files (list buffer-file-name))
4685 (date (calendar-current-date))
4686 (win (selected-window))
4687 (pos1 (point))
4688 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4689 (end (if (org-region-active-p) (region-end) (point-max)))
4690 (day-numbers (org-get-all-dates beg end 'no-ranges
4691 t doclosed)) ; always include today
4692 (today (time-to-days (current-time)))
4693 (org-respect-restriction t)
4694 (past t)
4695 args
4696 s e rtn d)
4697 (setq org-agenda-redo-command
4698 (list 'progn
4699 (list 'switch-to-buffer-other-window (current-buffer))
4700 (list 'org-timeline (list 'quote include-all) t)))
4701 (if (not dopast)
4702 ;; Remove past dates from the list of dates.
4703 (setq day-numbers (delq nil (mapcar (lambda(x)
4704 (if (>= x today) x nil))
4705 day-numbers))))
4706 (switch-to-buffer-other-window
4707 (get-buffer-create org-agenda-buffer-name))
4708 (setq buffer-read-only nil)
4709 (erase-buffer)
4710 (org-agenda-mode) (setq buffer-read-only nil)
4711 (set (make-local-variable 'org-agenda-type) 'timeline)
4712 (if doclosed (push :closed args))
4713 (push :timestamp args)
4714 (if dotodo (push :todo args))
4715 (while (setq d (pop day-numbers))
4716 (if (and (>= d today)
4717 dopast
4718 past)
4719 (progn
4720 (setq past nil)
4721 (insert (make-string 79 ?-) "\n")))
4722 (setq date (calendar-gregorian-from-absolute d))
4723 (setq s (point))
4724 (setq rtn (apply 'org-agenda-get-day-entries
4725 entry date args))
4726 (if (or rtn (equal d today))
4727 (progn
4728 (insert (calendar-day-name date) " "
4729 (number-to-string (extract-calendar-day date)) " "
4730 (calendar-month-name (extract-calendar-month date)) " "
4731 (number-to-string (extract-calendar-year date)) "\n")
4732 (put-text-property s (1- (point)) 'face
4733 'org-link)
4734 (if (equal d today)
4735 (put-text-property s (1- (point)) 'org-today t))
4736 (insert (org-finalize-agenda-entries rtn) "\n")
4737 (put-text-property s (1- (point)) 'day d))))
4738 (goto-char (point-min))
4739 (setq buffer-read-only t)
4740 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4741 (point-min)))
4742 (when (not org-select-timeline-window)
4743 (select-window win)
4744 (goto-char pos1))))
4745
4746 ;;;###autoload
4747 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4748 "Produce a weekly view from all files in variable `org-agenda-files'.
4749 The view will be for the current week, but from the overview buffer you
4750 will be able to go to other weeks.
4751 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4752 also be shown, under the current date.
4753 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4754 on the days are also shown. See the variable `org-log-done' for how
4755 to turn on logging.
4756 START-DAY defaults to TODAY, or to the most recent match for the weekday
4757 given in `org-agenda-start-on-weekday'.
4758 NDAYS defaults to `org-agenda-ndays'."
4759 (interactive "P")
4760 (org-agenda-maybe-reset-markers 'force)
4761 (org-compile-prefix-format org-agenda-prefix-format)
4762 (require 'calendar)
4763 (let* ((org-agenda-start-on-weekday
4764 (if (or (equal ndays 1)
4765 (and (null ndays) (equal 1 org-agenda-ndays)))
4766 nil org-agenda-start-on-weekday))
4767 (org-agenda-keep-modes keep-modes)
4768 (files (copy-sequence (org-agenda-files)))
4769 (win (selected-window))
4770 (today (time-to-days (current-time)))
4771 (sd (or start-day today))
4772 (start (if (or (null org-agenda-start-on-weekday)
4773 (< org-agenda-ndays 7))
4774 sd
4775 (let* ((nt (calendar-day-of-week
4776 (calendar-gregorian-from-absolute sd)))
4777 (n1 org-agenda-start-on-weekday)
4778 (d (- nt n1)))
4779 (- sd (+ (if (< d 0) 7 0) d)))))
4780 (day-numbers (list start))
4781 (inhibit-redisplay t)
4782 s e rtn rtnall file date d start-pos end-pos todayp nd)
4783 (setq org-agenda-redo-command
4784 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4785 ;; Make the list of days
4786 (setq ndays (or ndays org-agenda-ndays)
4787 nd ndays)
4788 (while (> ndays 1)
4789 (push (1+ (car day-numbers)) day-numbers)
4790 (setq ndays (1- ndays)))
4791 (setq day-numbers (nreverse day-numbers))
4792 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4793 (progn
4794 (delete-other-windows)
4795 (switch-to-buffer-other-window
4796 (get-buffer-create org-agenda-buffer-name))))
4797 (setq buffer-read-only nil)
4798 (erase-buffer)
4799 (org-agenda-mode) (setq buffer-read-only nil)
4800 (set (make-local-variable 'org-agenda-type) 'agenda)
4801 (set (make-local-variable 'starting-day) (car day-numbers))
4802 (set (make-local-variable 'include-all-loc) include-all)
4803 (when (and (or include-all org-agenda-include-all-todo)
4804 (member today day-numbers))
4805 (setq files (org-agenda-files)
4806 rtnall nil)
4807 (while (setq file (pop files))
4808 (catch 'nextfile
4809 (org-check-agenda-file file)
4810 (setq date (calendar-gregorian-from-absolute today)
4811 rtn (org-agenda-get-day-entries
4812 file date :todo))
4813 (setq rtnall (append rtnall rtn))))
4814 (when rtnall
4815 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4816 (add-text-properties (point-min) (1- (point))
4817 (list 'face 'org-link))
4818 (insert (org-finalize-agenda-entries rtnall) "\n")))
4819 (while (setq d (pop day-numbers))
4820 (setq date (calendar-gregorian-from-absolute d)
4821 s (point))
4822 (if (or (setq todayp (= d today))
4823 (and (not start-pos) (= d sd)))
4824 (setq start-pos (point))
4825 (if (and start-pos (not end-pos))
4826 (setq end-pos (point))))
4827 (setq files (org-agenda-files)
4828 rtnall nil)
4829 (while (setq file (pop files))
4830 (catch 'nextfile
4831 (org-check-agenda-file file)
4832 (if org-agenda-show-log
4833 (setq rtn (org-agenda-get-day-entries
4834 file date
4835 :deadline :scheduled :timestamp :closed))
4836 (setq rtn (org-agenda-get-day-entries
4837 file date
4838 :deadline :scheduled :timestamp)))
4839 (setq rtnall (append rtnall rtn))))
4840 (if org-agenda-include-diary
4841 (progn
4842 (require 'diary-lib)
4843 (setq rtn (org-get-entries-from-diary date))
4844 (setq rtnall (append rtnall rtn))))
4845 (if (or rtnall org-agenda-show-all-dates)
4846 (progn
4847 (insert (format "%-9s %2d %s %4d\n"
4848 (calendar-day-name date)
4849 (extract-calendar-day date)
4850 (calendar-month-name (extract-calendar-month date))
4851 (extract-calendar-year date)))
4852 (put-text-property s (1- (point)) 'face
4853 'org-link)
4854 (if rtnall (insert
4855 (org-finalize-agenda-entries
4856 (org-agenda-add-time-grid-maybe
4857 rtnall nd todayp))
4858 "\n"))
4859 (put-text-property s (1- (point)) 'day d))))
4860 (goto-char (point-min))
4861 (setq buffer-read-only t)
4862 (org-fit-agenda-window)
4863 (unless (and (pos-visible-in-window-p (point-min))
4864 (pos-visible-in-window-p (point-max)))
4865 (goto-char (1- (point-max)))
4866 (recenter -1)
4867 (if (not (pos-visible-in-window-p (or start-pos 1)))
4868 (progn
4869 (goto-char (or start-pos 1))
4870 (recenter 1))))
4871 (goto-char (or start-pos 1))
4872 (if (not org-select-agenda-window) (select-window win))
4873 (message "")))
4874
4875 (defvar org-select-this-todo-keyword nil)
4876
4877 ;;;###autoload
4878 (defun org-todo-list (arg &optional keep-modes)
4879 "Show all TODO entries from all agenda file in a single list.
4880 The prefix arg can be used to select a specific TODO keyword and limit
4881 the list to these. When using \\[universal-argument], you will be prompted
4882 for a keyword. A numeric prefix directly selects the Nth keyword in
4883 `org-todo-keywords'."
4884 (interactive "P")
4885 (org-agenda-maybe-reset-markers 'force)
4886 (org-compile-prefix-format org-agenda-prefix-format)
4887 (let* ((org-agenda-keep-modes keep-modes)
4888 (today (time-to-days (current-time)))
4889 (date (calendar-gregorian-from-absolute today))
4890 (win (selected-window))
4891 (kwds org-todo-keywords)
4892 (completion-ignore-case t)
4893 (org-select-this-todo-keyword
4894 (if (stringp arg) arg
4895 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4896 rtn rtnall files file pos)
4897 (when (equal arg '(4))
4898 (setq org-select-this-todo-keyword
4899 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4900 nil t)))
4901 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4902 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4903 (progn
4904 (delete-other-windows)
4905 (switch-to-buffer-other-window
4906 (get-buffer-create org-agenda-buffer-name))))
4907 (setq buffer-read-only nil)
4908 (erase-buffer)
4909 (org-agenda-mode) (setq buffer-read-only nil)
4910 (set (make-local-variable 'org-agenda-type) 'todo)
4911 (set (make-local-variable 'last-arg) arg)
4912 (set (make-local-variable 'org-todo-keywords) kwds)
4913 (set (make-local-variable 'org-agenda-redo-command)
4914 '(org-todo-list (or current-prefix-arg last-arg) t))
4915 (setq files (org-agenda-files)
4916 rtnall nil)
4917 (while (setq file (pop files))
4918 (catch 'nextfile
4919 (org-check-agenda-file file)
4920 (setq rtn (org-agenda-get-day-entries file date :todo))
4921 (setq rtnall (append rtnall rtn))))
4922 (insert "Global list of TODO items of type: ")
4923 (add-text-properties (point-min) (1- (point))
4924 (list 'face 'org-link))
4925 (setq pos (point))
4926 (insert (or org-select-this-todo-keyword "ALL") "\n")
4927 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4928 (setq pos (point))
4929 (insert
4930 "Available with `N r': (0)ALL "
4931 (let ((n 0))
4932 (mapconcat (lambda (x)
4933 (format "(%d)%s" (setq n (1+ n)) x))
4934 org-todo-keywords " "))
4935 "\n")
4936 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4937 (when rtnall
4938 (insert (org-finalize-agenda-entries rtnall) "\n"))
4939 (goto-char (point-min))
4940 (setq buffer-read-only t)
4941 (org-fit-agenda-window)
4942 (if (not org-select-agenda-window) (select-window win))))
4943
4944 (defun org-check-agenda-file (file)
4945 "Make sure FILE exists. If not, ask user what to do."
4946 ;; FIXME: this does not correctly change the menus
4947 ;; Could probably be fixed by explicitly going to the buffer where
4948 ;; the call originated.
4949 (when (not (file-exists-p file))
4950 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4951 file)
4952 (let ((r (downcase (read-char-exclusive))))
4953 (cond
4954 ((equal r ?r)
4955 (org-remove-file file)
4956 (throw 'nextfile t))
4957 (t (error "Abort"))))))
4958
4959 (defun org-agenda-check-type (error &rest types)
4960 "Check if agenda buffer is of allowed type.
4961 If ERROR is non-nil, throw an error, otherwise just return nil."
4962 (if (memq org-agenda-type types)
4963 t
4964 (if error
4965 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
4966 nil)))
4967
4968 (defun org-agenda-quit ()
4969 "Exit agenda by removing the window or the buffer."
4970 (interactive)
4971 (let ((buf (current-buffer)))
4972 (if (not (one-window-p)) (delete-window))
4973 (kill-buffer buf)
4974 (org-agenda-maybe-reset-markers 'force)))
4975
4976 (defun org-agenda-exit ()
4977 "Exit agenda by removing the window or the buffer.
4978 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4979 Org-mode buffers visited directly by the user will not be touched."
4980 (interactive)
4981 (org-release-buffers org-agenda-new-buffers)
4982 (setq org-agenda-new-buffers nil)
4983 (org-agenda-quit))
4984
4985 (defun org-agenda-redo ()
4986 "Rebuild Agenda.
4987 When this is the global TODO list, a prefix argument will be interpreted."
4988 (interactive)
4989 (message "Rebuilding agenda buffer...")
4990 (eval org-agenda-redo-command)
4991 (message "Rebuilding agenda buffer...done"))
4992
4993 (defun org-agenda-goto-today ()
4994 "Go to today."
4995 (interactive)
4996 (org-agenda-check-type t 'timeline 'agenda)
4997 (if (boundp 'starting-day)
4998 (let ((cmd (car org-agenda-redo-command))
4999 (iall (nth 1 org-agenda-redo-command))
5000 (nday (nth 3 org-agenda-redo-command))
5001 (keep (nth 4 org-agenda-redo-command)))
5002 (eval (list cmd iall nil nday keep)))
5003 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5004 (point-min)))))
5005
5006 (defun org-agenda-later (arg)
5007 "Go forward in time by `org-agenda-ndays' days.
5008 With prefix ARG, go forward that many times `org-agenda-ndays'."
5009 (interactive "p")
5010 (org-agenda-check-type t 'agenda)
5011 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5012 (+ starting-day (* arg org-agenda-ndays)) nil t))
5013
5014 (defun org-agenda-earlier (arg)
5015 "Go back in time by `org-agenda-ndays' days.
5016 With prefix ARG, go back that many times `org-agenda-ndays'."
5017 (interactive "p")
5018 (org-agenda-check-type t 'agenda)
5019 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5020 (- starting-day (* arg org-agenda-ndays)) nil t))
5021
5022 (defun org-agenda-week-view ()
5023 "Switch to weekly view for agenda."
5024 (interactive)
5025 (org-agenda-check-type t 'agenda)
5026 (setq org-agenda-ndays 7)
5027 (org-agenda-list include-all-loc
5028 (or (get-text-property (point) 'day)
5029 starting-day)
5030 nil t)
5031 (org-agenda-set-mode-name)
5032 (message "Switched to week view"))
5033
5034 (defun org-agenda-day-view ()
5035 "Switch to daily view for agenda."
5036 (interactive)
5037 (org-agenda-check-type t 'agenda)
5038 (setq org-agenda-ndays 1)
5039 (org-agenda-list include-all-loc
5040 (or (get-text-property (point) 'day)
5041 starting-day)
5042 nil t)
5043 (org-agenda-set-mode-name)
5044 (message "Switched to day view"))
5045
5046 (defun org-agenda-next-date-line (&optional arg)
5047 "Jump to the next line indicating a date in agenda buffer."
5048 (interactive "p")
5049 (org-agenda-check-type t 'agenda 'timeline)
5050 (beginning-of-line 1)
5051 (if (looking-at "^\\S-") (forward-char 1))
5052 (if (not (re-search-forward "^\\S-" nil t arg))
5053 (progn
5054 (backward-char 1)
5055 (error "No next date after this line in this buffer")))
5056 (goto-char (match-beginning 0)))
5057
5058 (defun org-agenda-previous-date-line (&optional arg)
5059 "Jump to the previous line indicating a date in agenda buffer."
5060 (interactive "p")
5061 (org-agenda-check-type t 'agenda 'timeline)
5062 (beginning-of-line 1)
5063 (if (not (re-search-backward "^\\S-" nil t arg))
5064 (error "No previous date before this line in this buffer")))
5065
5066 ;; Initialize the highlight
5067 (defvar org-hl (org-make-overlay 1 1))
5068 (org-overlay-put org-hl 'face 'highlight)
5069
5070 (defun org-highlight (begin end &optional buffer)
5071 "Highlight a region with overlay."
5072 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
5073 org-hl begin end (or buffer (current-buffer))))
5074
5075 (defun org-unhighlight ()
5076 "Detach overlay INDEX."
5077 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
5078
5079
5080 (defun org-agenda-follow-mode ()
5081 "Toggle follow mode in an agenda buffer."
5082 (interactive)
5083 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5084 (org-agenda-set-mode-name)
5085 (message "Follow mode is %s"
5086 (if org-agenda-follow-mode "on" "off")))
5087
5088 (defun org-agenda-log-mode ()
5089 "Toggle log mode in an agenda buffer."
5090 (interactive)
5091 (org-agenda-check-type t 'agenda 'timeline)
5092 (setq org-agenda-show-log (not org-agenda-show-log))
5093 (org-agenda-set-mode-name)
5094 (org-agenda-redo)
5095 (message "Log mode is %s"
5096 (if org-agenda-show-log "on" "off")))
5097
5098 (defun org-agenda-toggle-diary ()
5099 "Toggle diary inclusion in an agenda buffer."
5100 (interactive)
5101 (org-agenda-check-type t 'agenda)
5102 (setq org-agenda-include-diary (not org-agenda-include-diary))
5103 (org-agenda-redo)
5104 (org-agenda-set-mode-name)
5105 (message "Diary inclusion turned %s"
5106 (if org-agenda-include-diary "on" "off")))
5107
5108 (defun org-agenda-toggle-time-grid ()
5109 "Toggle time grid in an agenda buffer."
5110 (interactive)
5111 (org-agenda-check-type t 'agenda)
5112 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5113 (org-agenda-redo)
5114 (org-agenda-set-mode-name)
5115 (message "Time-grid turned %s"
5116 (if org-agenda-use-time-grid "on" "off")))
5117
5118 (defun org-agenda-set-mode-name ()
5119 "Set the mode name to indicate all the small mode settings."
5120 (setq mode-name
5121 (concat "Org-Agenda"
5122 (if (equal org-agenda-ndays 1) " Day" "")
5123 (if (equal org-agenda-ndays 7) " Week" "")
5124 (if org-agenda-follow-mode " Follow" "")
5125 (if org-agenda-include-diary " Diary" "")
5126 (if org-agenda-use-time-grid " Grid" "")
5127 (if org-agenda-show-log " Log" "")))
5128 (force-mode-line-update))
5129
5130 (defun org-agenda-post-command-hook ()
5131 (and (eolp) (not (bolp)) (backward-char 1))
5132 (if (and org-agenda-follow-mode
5133 (get-text-property (point) 'org-marker))
5134 (org-agenda-show)))
5135
5136 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5137
5138 (defun org-get-entries-from-diary (date)
5139 "Get the (Emacs Calendar) diary entries for DATE."
5140 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5141 (diary-display-hook '(fancy-diary-display))
5142 (list-diary-entries-hook
5143 (cons 'org-diary-default-entry list-diary-entries-hook))
5144 (diary-file-name-prefix-function nil) ; turn this feature off
5145 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5146 entries
5147 (org-disable-agenda-to-diary t))
5148 (save-excursion
5149 (save-window-excursion
5150 (list-diary-entries date 1)))
5151 (if (not (get-buffer fancy-diary-buffer))
5152 (setq entries nil)
5153 (with-current-buffer fancy-diary-buffer
5154 (setq buffer-read-only nil)
5155 (if (= (point-max) 1)
5156 ;; No entries
5157 (setq entries nil)
5158 ;; Omit the date and other unnecessary stuff
5159 (org-agenda-cleanup-fancy-diary)
5160 ;; Add prefix to each line and extend the text properties
5161 (if (= (point-max) 1)
5162 (setq entries nil)
5163 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5164 (set-buffer-modified-p nil)
5165 (kill-buffer fancy-diary-buffer)))
5166 (when entries
5167 (setq entries (org-split-string entries "\n"))
5168 (setq entries
5169 (mapcar
5170 (lambda (x)
5171 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5172 ;; Extend the text properties to the beginning of the line
5173 (add-text-properties
5174 0 (length x)
5175 (text-properties-at (1- (length x)) x)
5176 x)
5177 x)
5178 entries)))))
5179
5180 (defun org-agenda-cleanup-fancy-diary ()
5181 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5182 This gets rid of the date, the underline under the date, and
5183 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5184 date. It also removes lines that contain only whitespace."
5185 (goto-char (point-min))
5186 (if (looking-at ".*?:[ \t]*")
5187 (progn
5188 (replace-match "")
5189 (re-search-forward "\n=+$" nil t)
5190 (replace-match "")
5191 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5192 (re-search-forward "\n=+$" nil t)
5193 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5194 (goto-char (point-min))
5195 (while (re-search-forward "^ +\n" nil t)
5196 (replace-match ""))
5197 (goto-char (point-min))
5198 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5199 (replace-match "")))
5200
5201 ;; Make sure entries from the diary have the right text properties.
5202 (eval-after-load "diary-lib"
5203 '(if (boundp 'diary-modify-entry-list-string-function)
5204 ;; We can rely on the hook, nothing to do
5205 nil
5206 ;; Hook not avaiable, must use advice to make this work
5207 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5208 "Make the position visible."
5209 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5210 (stringp string)
5211 buffer-file-name)
5212 (setq string (org-modify-diary-entry-string string))))))
5213
5214 (defun org-modify-diary-entry-string (string)
5215 "Add text properties to string, allowing org-mode to act on it."
5216 (add-text-properties
5217 0 (length string)
5218 (list 'mouse-face 'highlight
5219 'keymap org-agenda-keymap
5220 'help-echo
5221 (format
5222 "mouse-2 or RET jump to diary file %s"
5223 (abbreviate-file-name buffer-file-name))
5224 'org-agenda-diary-link t
5225 'org-marker (org-agenda-new-marker (point-at-bol)))
5226 string)
5227 string)
5228
5229 (defun org-diary-default-entry ()
5230 "Add a dummy entry to the diary.
5231 Needed to avoid empty dates which mess up holiday display."
5232 ;; Catch the error if dealing with the new add-to-diary-alist
5233 (when org-disable-agenda-to-diary
5234 (condition-case nil
5235 (add-to-diary-list original-date "Org-mode dummy" "")
5236 (error
5237 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5238
5239 (defun org-cycle-agenda-files ()
5240 "Cycle through the files in `org-agenda-files'.
5241 If the current buffer visits an agenda file, find the next one in the list.
5242 If the current buffer does not, find the first agenda file."
5243 (interactive)
5244 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5245 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5246 file)
5247 (unless files (error "No agenda files"))
5248 (catch 'exit
5249 (while (setq file (pop files))
5250 (if (equal (file-truename file) tcf)
5251 (when (car files)
5252 (find-file (car files))
5253 (throw 'exit t))))
5254 (find-file (car org-agenda-files)))))
5255
5256 (defun org-agenda-file-to-end ()
5257 "Move/add the current file to the end of the agenda file list.
5258 If the file is not present in the list, it is appended to the list. If it is
5259 present, it is moved there."
5260 (interactive)
5261 (org-agenda-file-to-front 'to-end))
5262
5263 (defun org-agenda-file-to-front (&optional to-end)
5264 "Move/add the current file to the top of the agenda file list.
5265 If the file is not present in the list, it is added to the front. If it is
5266 present, it is moved there. With optional argument TO-END, add/move to the
5267 end of the list."
5268 (interactive "P")
5269 (let ((file-alist (mapcar (lambda (x)
5270 (cons (file-truename x) x))
5271 org-agenda-files))
5272 (ctf (file-truename buffer-file-name))
5273 x had)
5274 (setq x (assoc ctf file-alist) had x)
5275
5276 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5277 (if to-end
5278 (setq file-alist (append (delq x file-alist) (list x)))
5279 (setq file-alist (cons x (delq x file-alist))))
5280 (setq org-agenda-files (mapcar 'cdr file-alist))
5281 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5282 (customize-save-variable 'org-agenda-files org-agenda-files))
5283 (org-install-agenda-files-menu)
5284 (message "File %s to %s of agenda file list"
5285 (if had "moved" "added") (if to-end "end" "front"))))
5286
5287 (defun org-remove-file (&optional file)
5288 "Remove current file from the list of files in variable `org-agenda-files'.
5289 These are the files which are being checked for agenda entries.
5290 Optional argument FILE means, use this file instead of the current."
5291 (interactive)
5292 (let* ((file (or file buffer-file-name))
5293 (true-file (file-truename file))
5294 (afile (abbreviate-file-name file))
5295 (files (delq nil (mapcar
5296 (lambda (x)
5297 (if (equal true-file
5298 (file-truename x))
5299 nil x))
5300 org-agenda-files))))
5301 (if (not (= (length files) (length org-agenda-files)))
5302 (progn
5303 (setq org-agenda-files files)
5304 (customize-save-variable 'org-agenda-files org-agenda-files)
5305 (org-install-agenda-files-menu)
5306 (message "Removed file: %s" afile))
5307 (message "File was not in list: %s" afile))))
5308
5309 (defun org-file-menu-entry (file)
5310 (vector file (list 'find-file file) t))
5311 ;; FIXME: Maybe we removed a buffer visited through the menu from
5312 ;; org-agenda-new-buffers, so that the buffer will not be removed
5313 ;; when exiting the agenda????
5314
5315 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5316 "Return a list of all relevant day numbers from BEG to END buffer positions.
5317 If NO-RANGES is non-nil, include only the start and end dates of a range,
5318 not every single day in the range. If FORCE-TODAY is non-nil, make
5319 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5320 inactive time stamps (those in square brackets) are included."
5321 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5322 dates date day day1 day2 ts1 ts2)
5323 (if force-today
5324 (setq dates (list (time-to-days (current-time)))))
5325 (save-excursion
5326 (goto-char beg)
5327 (while (re-search-forward re end t)
5328 (setq day (time-to-days (org-time-string-to-time
5329 (substring (match-string 1) 0 10))))
5330 (or (memq day dates) (push day dates)))
5331 (unless no-ranges
5332 (goto-char beg)
5333 (while (re-search-forward org-tr-regexp end t)
5334 (setq ts1 (substring (match-string 1) 0 10)
5335 ts2 (substring (match-string 2) 0 10)
5336 day1 (time-to-days (org-time-string-to-time ts1))
5337 day2 (time-to-days (org-time-string-to-time ts2)))
5338 (while (< (setq day1 (1+ day1)) day2)
5339 (or (memq day1 dates) (push day1 dates)))))
5340 (sort dates '<))))
5341
5342 ;;;###autoload
5343 (defun org-diary (&rest args)
5344 "Return diary information from org-files.
5345 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5346 It accesses org files and extracts information from those files to be
5347 listed in the diary. The function accepts arguments specifying what
5348 items should be listed. The following arguments are allowed:
5349
5350 :timestamp List the headlines of items containing a date stamp or
5351 date range matching the selected date. Deadlines will
5352 also be listed, on the expiration day.
5353
5354 :deadline List any deadlines past due, or due within
5355 `org-deadline-warning-days'. The listing occurs only
5356 in the diary for *today*, not at any other date. If
5357 an entry is marked DONE, it is no longer listed.
5358
5359 :scheduled List all items which are scheduled for the given date.
5360 The diary for *today* also contains items which were
5361 scheduled earlier and are not yet marked DONE.
5362
5363 :todo List all TODO items from the org-file. This may be a
5364 long list - so this is not turned on by default.
5365 Like deadlines, these entries only show up in the
5366 diary for *today*, not at any other date.
5367
5368 The call in the diary file should look like this:
5369
5370 &%%(org-diary) ~/path/to/some/orgfile.org
5371
5372 Use a separate line for each org file to check. Or, if you omit the file name,
5373 all files listed in `org-agenda-files' will be checked automatically:
5374
5375 &%%(org-diary)
5376
5377 If you don't give any arguments (as in the example above), the default
5378 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5379 also be written as
5380
5381 &%%(org-diary :deadline :timestamp :scheduled)
5382
5383 The function expects the lisp variables `entry' and `date' to be provided
5384 by the caller, because this is how the calendar works. Don't use this
5385 function from a program - use `org-agenda-get-day-entries' instead."
5386 (org-agenda-maybe-reset-markers)
5387 (org-compile-prefix-format org-agenda-prefix-format)
5388 (setq args (or args '(:deadline :scheduled :timestamp)))
5389 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5390 (list entry)
5391 org-agenda-files))
5392 file rtn results)
5393 ;; If this is called during org-agenda, don't return any entries to
5394 ;; the calendar. Org Agenda will list these entries itself.
5395 (if org-disable-agenda-to-diary (setq files nil))
5396 (while (setq file (pop files))
5397 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5398 (setq results (append results rtn)))
5399 (if results
5400 (concat (org-finalize-agenda-entries results) "\n"))))
5401 (defvar org-category-table nil)
5402 (defun org-get-category-table ()
5403 "Get the table of categories and positions in current buffer."
5404 (let (tbl)
5405 (save-excursion
5406 (goto-char (point-min))
5407 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5408 (push (cons (point) (org-trim (match-string 2))) tbl)))
5409 tbl))
5410 (defun org-get-category (&optional pos)
5411 "Get the category applying to position POS."
5412 (if (not org-category-table)
5413 (cond
5414 ((null org-category)
5415 (setq org-category
5416 (if buffer-file-name
5417 (file-name-sans-extension
5418 (file-name-nondirectory buffer-file-name))
5419 "???")))
5420 ((symbolp org-category) (symbol-name org-category))
5421 (t org-category))
5422 (let ((tbl org-category-table)
5423 (pos (or pos (point))))
5424 (while (and tbl (> (caar tbl) pos))
5425 (pop tbl))
5426 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5427 org-category-table))))))
5428
5429 (defun org-agenda-get-day-entries (file date &rest args)
5430 "Does the work for `org-diary' and `org-agenda'.
5431 FILE is the path to a file to be checked for entries. DATE is date like
5432 the one returned by `calendar-current-date'. ARGS are symbols indicating
5433 which kind of entries should be extracted. For details about these, see
5434 the documentation of `org-diary'."
5435 (setq args (or args '(:deadline :scheduled :timestamp)))
5436 (let* ((org-startup-with-deadline-check nil)
5437 (org-startup-folded nil)
5438 (buffer (if (file-exists-p file)
5439 (org-get-agenda-file-buffer file)
5440 (error "No such file %s" file)))
5441 arg results rtn)
5442 (if (not buffer)
5443 ;; If file does not exist, make sure an error message ends up in diary
5444 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5445 (with-current-buffer buffer
5446 (unless (eq major-mode 'org-mode)
5447 (error "Agenda file %s is not in `org-mode'" file))
5448 (setq org-category-table (org-get-category-table))
5449 (let ((case-fold-search nil))
5450 (save-excursion
5451 (save-restriction
5452 (if org-respect-restriction
5453 (if (org-region-active-p)
5454 ;; Respect a region to restrict search
5455 (narrow-to-region (region-beginning) (region-end)))
5456 ;; If we work for the calendar or many files,
5457 ;; get rid of any restriction
5458 (widen))
5459 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5460 (while (setq arg (pop args))
5461 (cond
5462 ((and (eq arg :todo)
5463 (equal date (calendar-current-date)))
5464 (setq rtn (org-agenda-get-todos))
5465 (setq results (append results rtn)))
5466 ((eq arg :timestamp)
5467 (setq rtn (org-agenda-get-blocks))
5468 (setq results (append results rtn))
5469 (setq rtn (org-agenda-get-timestamps))
5470 (setq results (append results rtn)))
5471 ((eq arg :scheduled)
5472 (setq rtn (org-agenda-get-scheduled))
5473 (setq results (append results rtn)))
5474 ((eq arg :closed)
5475 (setq rtn (org-agenda-get-closed))
5476 (setq results (append results rtn)))
5477 ((and (eq arg :deadline)
5478 (equal date (calendar-current-date)))
5479 (setq rtn (org-agenda-get-deadlines))
5480 (setq results (append results rtn))))))))
5481 results))))
5482
5483 (defun org-entry-is-done-p ()
5484 "Is the current entry marked DONE?"
5485 (save-excursion
5486 (and (re-search-backward "[\r\n]\\*" nil t)
5487 (looking-at org-nl-done-regexp))))
5488
5489 (defun org-at-date-range-p ()
5490 "Is the cursor inside a date range?"
5491 (interactive)
5492 (save-excursion
5493 (catch 'exit
5494 (let ((pos (point)))
5495 (skip-chars-backward "^<\r\n")
5496 (skip-chars-backward "<")
5497 (and (looking-at org-tr-regexp)
5498 (>= (match-end 0) pos)
5499 (throw 'exit t))
5500 (skip-chars-backward "^<\r\n")
5501 (skip-chars-backward "<")
5502 (and (looking-at org-tr-regexp)
5503 (>= (match-end 0) pos)
5504 (throw 'exit t)))
5505 nil)))
5506
5507 (defun org-agenda-get-todos ()
5508 "Return the TODO information for agenda display."
5509 (let* ((props (list 'face nil
5510 'done-face 'org-done
5511 'mouse-face 'highlight
5512 'keymap org-agenda-keymap
5513 'help-echo
5514 (format "mouse-2 or RET jump to org file %s"
5515 (abbreviate-file-name buffer-file-name))))
5516 (regexp (concat "[\n\r]\\*+ *\\("
5517 (if org-select-this-todo-keyword
5518 (concat "\\<\\(" org-select-this-todo-keyword
5519 "\\)\\>")
5520 org-not-done-regexp)
5521 "[^\n\r]*\\)"))
5522 marker priority category tags
5523 ee txt)
5524 (goto-char (point-min))
5525 (while (re-search-forward regexp nil t)
5526 (goto-char (match-beginning 1))
5527 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5528 category (org-get-category)
5529 tags (org-get-tags-at (point))
5530 txt (org-format-agenda-item "" (match-string 1) category tags)
5531 priority
5532 (+ (org-get-priority txt)
5533 (if org-todo-kwd-priority-p
5534 (- org-todo-kwd-max-priority -2
5535 (length
5536 (member (match-string 2) org-todo-keywords)))
5537 1)))
5538 (add-text-properties
5539 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5540 'priority priority 'category category)
5541 props)
5542 txt)
5543 (push txt ee)
5544 (goto-char (match-end 1)))
5545 (nreverse ee)))
5546
5547 (defconst org-agenda-no-heading-message
5548 "No heading for this item in buffer or region.")
5549
5550 (defun org-agenda-get-timestamps ()
5551 "Return the date stamp information for agenda display."
5552 (let* ((props (list 'face nil
5553 'mouse-face 'highlight
5554 'keymap org-agenda-keymap
5555 'help-echo
5556 (format "mouse-2 or RET jump to org file %s"
5557 (abbreviate-file-name buffer-file-name))))
5558 (regexp (regexp-quote
5559 (substring
5560 (format-time-string
5561 (car org-time-stamp-formats)
5562 (apply 'encode-time ; DATE bound by calendar
5563 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5564 0 11)))
5565 marker hdmarker deadlinep scheduledp donep tmp priority category
5566 ee txt timestr tags)
5567 (goto-char (point-min))
5568 (while (re-search-forward regexp nil t)
5569 (if (not (save-match-data (org-at-date-range-p)))
5570 (progn
5571 (setq marker (org-agenda-new-marker (match-beginning 0))
5572 category (org-get-category (match-beginning 0))
5573 tmp (buffer-substring (max (point-min)
5574 (- (match-beginning 0)
5575 org-ds-keyword-length))
5576 (match-beginning 0))
5577 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5578 deadlinep (string-match org-deadline-regexp tmp)
5579 scheduledp (string-match org-scheduled-regexp tmp)
5580 donep (org-entry-is-done-p))
5581 (if (string-match ">" timestr)
5582 ;; substring should only run to end of time stamp
5583 (setq timestr (substring timestr 0 (match-end 0))))
5584 (save-excursion
5585 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5586 (progn
5587 (goto-char (match-end 1))
5588 (setq hdmarker (org-agenda-new-marker)
5589 tags (org-get-tags-at))
5590 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5591 (setq txt (org-format-agenda-item
5592 (format "%s%s"
5593 (if deadlinep "Deadline: " "")
5594 (if scheduledp "Scheduled: " ""))
5595 (match-string 1) category tags timestr)))
5596 (setq txt org-agenda-no-heading-message))
5597 (setq priority (org-get-priority txt))
5598 (add-text-properties
5599 0 (length txt) (append (list 'org-marker marker
5600 'org-hd-marker hdmarker) props)
5601 txt)
5602 (if deadlinep
5603 (add-text-properties
5604 0 (length txt)
5605 (list 'face
5606 (if donep 'org-done 'org-warning)
5607 'undone-face 'org-warning
5608 'done-face 'org-done
5609 'category category
5610 'priority (+ 100 priority))
5611 txt)
5612 (if scheduledp
5613 (add-text-properties
5614 0 (length txt)
5615 (list 'face 'org-scheduled-today
5616 'undone-face 'org-scheduled-today
5617 'done-face 'org-done
5618 'category category
5619 priority (+ 99 priority))
5620 txt)
5621 (add-text-properties
5622 0 (length txt)
5623 (list 'priority priority 'category category) txt)))
5624 (push txt ee))
5625 (outline-next-heading))))
5626 (nreverse ee)))
5627
5628 (defun org-agenda-get-closed ()
5629 "Return the logged TODO entries for agenda display."
5630 (let* ((props (list 'mouse-face 'highlight
5631 'keymap org-agenda-keymap
5632 'help-echo
5633 (format "mouse-2 or RET jump to org file %s"
5634 (abbreviate-file-name buffer-file-name))))
5635 (regexp (concat
5636 "\\<" org-closed-string " *\\["
5637 (regexp-quote
5638 (substring
5639 (format-time-string
5640 (car org-time-stamp-formats)
5641 (apply 'encode-time ; DATE bound by calendar
5642 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5643 1 11))))
5644 marker hdmarker priority category tags
5645 ee txt timestr)
5646 (goto-char (point-min))
5647 (while (re-search-forward regexp nil t)
5648 (if (not (save-match-data (org-at-date-range-p)))
5649 (progn
5650 (setq marker (org-agenda-new-marker (match-beginning 0))
5651 category (org-get-category (match-beginning 0))
5652 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5653 ;; donep (org-entry-is-done-p)
5654 )
5655 (if (string-match "\\]" timestr)
5656 ;; substring should only run to end of time stamp
5657 (setq timestr (substring timestr 0 (match-end 0))))
5658 (save-excursion
5659 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5660 (progn
5661 (goto-char (match-end 1))
5662 (setq hdmarker (org-agenda-new-marker)
5663 tags (org-get-tags-at))
5664 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5665 (setq txt (org-format-agenda-item
5666 "Closed: "
5667 (match-string 1) category tags timestr)))
5668 (setq txt org-agenda-no-heading-message))
5669 (setq priority 100000)
5670 (add-text-properties
5671 0 (length txt) (append (list 'org-marker marker
5672 'org-hd-marker hdmarker
5673 'face 'org-done
5674 'priority priority
5675 'category category
5676 'undone-face 'org-warning
5677 'done-face 'org-done) props)
5678 txt)
5679 (push txt ee))
5680 (outline-next-heading))))
5681 (nreverse ee)))
5682
5683 (defun org-agenda-get-deadlines ()
5684 "Return the deadline information for agenda display."
5685 (let* ((wdays org-deadline-warning-days)
5686 (props (list 'mouse-face 'highlight
5687 'keymap org-agenda-keymap
5688 'help-echo
5689 (format "mouse-2 or RET jump to org file %s"
5690 (abbreviate-file-name buffer-file-name))))
5691 (regexp org-deadline-time-regexp)
5692 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5693 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5694 d2 diff pos pos1 category tags
5695 ee txt head)
5696 (goto-char (point-min))
5697 (while (re-search-forward regexp nil t)
5698 (setq pos (1- (match-beginning 1))
5699 d2 (time-to-days
5700 (org-time-string-to-time (match-string 1)))
5701 diff (- d2 d1))
5702 ;; When to show a deadline in the calendar:
5703 ;; If the expiration is within wdays warning time.
5704 ;; Past-due deadlines are only shown on the current date
5705 (if (and (< diff wdays) todayp (not (= diff 0)))
5706 (save-excursion
5707 (setq category (org-get-category))
5708 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5709 (progn
5710 (goto-char (match-end 0))
5711 (setq pos1 (match-end 1))
5712 (setq tags (org-get-tags-at pos1))
5713 (setq head (buffer-substring-no-properties
5714 (point)
5715 (progn (skip-chars-forward "^\r\n")
5716 (point))))
5717 (if (string-match org-looking-at-done-regexp head)
5718 (setq txt nil)
5719 (setq txt (org-format-agenda-item
5720 (format "In %3d d.: " diff) head category tags))))
5721 (setq txt org-agenda-no-heading-message))
5722 (when txt
5723 (add-text-properties
5724 0 (length txt)
5725 (append
5726 (list 'org-marker (org-agenda-new-marker pos)
5727 'org-hd-marker (org-agenda-new-marker pos1)
5728 'priority (+ (- 10 diff) (org-get-priority txt))
5729 'category category
5730 'face (cond ((<= diff 0) 'org-warning)
5731 ((<= diff 5) 'org-scheduled-previously)
5732 (t nil))
5733 'undone-face (cond
5734 ((<= diff 0) 'org-warning)
5735 ((<= diff 5) 'org-scheduled-previously)
5736 (t nil))
5737 'done-face 'org-done)
5738 props)
5739 txt)
5740 (push txt ee)))))
5741 ee))
5742
5743 (defun org-agenda-get-scheduled ()
5744 "Return the scheduled information for agenda display."
5745 (let* ((props (list 'face 'org-scheduled-previously
5746 'undone-face 'org-scheduled-previously
5747 'done-face 'org-done
5748 'mouse-face 'highlight
5749 'keymap org-agenda-keymap
5750 'help-echo
5751 (format "mouse-2 or RET jump to org file %s"
5752 (abbreviate-file-name buffer-file-name))))
5753 (regexp org-scheduled-time-regexp)
5754 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5755 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5756 d2 diff pos pos1 category tags
5757 ee txt head)
5758 (goto-char (point-min))
5759 (while (re-search-forward regexp nil t)
5760 (setq pos (1- (match-beginning 1))
5761 d2 (time-to-days
5762 (org-time-string-to-time (match-string 1)))
5763 diff (- d2 d1))
5764 ;; When to show a scheduled item in the calendar:
5765 ;; If it is on or past the date.
5766 (if (and (< diff 0) todayp)
5767 (save-excursion
5768 (setq category (org-get-category))
5769 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5770 (progn
5771 (goto-char (match-end 0))
5772 (setq pos1 (match-end 1))
5773 (setq tags (org-get-tags-at))
5774 (setq head (buffer-substring-no-properties
5775 (point)
5776 (progn (skip-chars-forward "^\r\n") (point))))
5777 (if (string-match org-looking-at-done-regexp head)
5778 (setq txt nil)
5779 (setq txt (org-format-agenda-item
5780 (format "Sched.%2dx: " (- 1 diff)) head
5781 category tags))))
5782 (setq txt org-agenda-no-heading-message))
5783 (when txt
5784 (add-text-properties
5785 0 (length txt)
5786 (append (list 'org-marker (org-agenda-new-marker pos)
5787 'org-hd-marker (org-agenda-new-marker pos1)
5788 'priority (+ (- 5 diff) (org-get-priority txt))
5789 'category category)
5790 props) txt)
5791 (push txt ee)))))
5792 ee))
5793
5794 (defun org-agenda-get-blocks ()
5795 "Return the date-range information for agenda display."
5796 (let* ((props (list 'face nil
5797 'mouse-face 'highlight
5798 'keymap org-agenda-keymap
5799 'help-echo
5800 (format "mouse-2 or RET jump to org file %s"
5801 (abbreviate-file-name buffer-file-name))))
5802 (regexp org-tr-regexp)
5803 (d0 (calendar-absolute-from-gregorian date))
5804 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
5805 (goto-char (point-min))
5806 (while (re-search-forward regexp nil t)
5807 (setq timestr (match-string 0)
5808 s1 (match-string 1)
5809 s2 (match-string 2)
5810 d1 (time-to-days (org-time-string-to-time s1))
5811 d2 (time-to-days (org-time-string-to-time s2)))
5812 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5813 ;; Only allow days between the limits, because the normal
5814 ;; date stamps will catch the limits.
5815 (save-excursion
5816 (setq marker (org-agenda-new-marker (point)))
5817 (setq category (org-get-category))
5818 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5819 (progn
5820 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5821 (goto-char (match-end 1))
5822 (setq tags (org-get-tags-at))
5823 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5824 (setq txt (org-format-agenda-item
5825 (format (if (= d1 d2) "" "(%d/%d): ")
5826 (1+ (- d0 d1)) (1+ (- d2 d1)))
5827 (match-string 1) category tags
5828 (if (= d0 d1) timestr))))
5829 (setq txt org-agenda-no-heading-message))
5830 (add-text-properties
5831 0 (length txt) (append (list 'org-marker marker
5832 'org-hd-marker hdmarker
5833 'priority (org-get-priority txt)
5834 'category category)
5835 props)
5836 txt)
5837 (push txt ee)))
5838 (outline-next-heading))
5839 ;; Sort the entries by expiration date.
5840 (nreverse ee)))
5841
5842 (defconst org-plain-time-of-day-regexp
5843 (concat
5844 "\\(\\<[012]?[0-9]"
5845 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5846 "\\(--?"
5847 "\\(\\<[012]?[0-9]"
5848 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5849 "\\)?")
5850 "Regular expression to match a plain time or time range.
5851 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5852 groups carry important information:
5853 0 the full match
5854 1 the first time, range or not
5855 8 the second time, if it is a range.")
5856
5857 (defconst org-stamp-time-of-day-regexp
5858 (concat
5859 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5860 "\\([012][0-9]:[0-5][0-9]\\)>"
5861 "\\(--?"
5862 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5863 "Regular expression to match a timestamp time or time range.
5864 After a match, the following groups carry important information:
5865 0 the full match
5866 1 date plus weekday, for backreferencing to make sure both times on same day
5867 2 the first time, range or not
5868 4 the second time, if it is a range.")
5869
5870 (defvar org-prefix-has-time nil
5871 "A flag, set by `org-compile-prefix-format'.
5872 The flag is set if the currently compiled format contains a `%t'.")
5873 (defvar org-prefix-has-tag nil
5874 "A flag, set by `org-compile-prefix-format'.
5875 The flag is set if the currently compiled format contains a `%T'.")
5876
5877 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
5878 "Format TXT to be inserted into the agenda buffer.
5879 In particular, it adds the prefix and corresponding text properties. EXTRA
5880 must be a string and replaces the `%s' specifier in the prefix format.
5881 CATEGORY (string, symbol or nil) may be used to overrule the default
5882 category taken from local variable or file name. It will replace the `%c'
5883 specifier in the format. DOTIME, when non-nil, indicates that a
5884 time-of-day should be extracted from TXT for sorting of this entry, and for
5885 the `%t' specifier in the format. When DOTIME is a string, this string is
5886 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5887 only the correctly processes TXT should be returned - this is used by
5888 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
5889 (save-match-data
5890 ;; Diary entries sometimes have extra whitespace at the beginning
5891 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5892 (let* ((category (or category
5893 org-category
5894 (if buffer-file-name
5895 (file-name-sans-extension
5896 (file-name-nondirectory buffer-file-name))
5897 "")))
5898 (tag (or (nth (1- (or (length tags) 0)) tags) ""))
5899 time ;; needed for the eval of the prefix format
5900 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5901 (time-of-day (and dotime (org-get-time-of-day ts)))
5902 stamp plain s0 s1 s2 rtn)
5903 (when (and dotime time-of-day org-prefix-has-time)
5904 ;; Extract starting and ending time and move them to prefix
5905 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5906 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5907 (setq s0 (match-string 0 ts)
5908 s1 (match-string (if plain 1 2) ts)
5909 s2 (match-string (if plain 8 4) ts))
5910
5911 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5912 ;; them, we might want to remove them there to avoid duplication.
5913 ;; The user can turn this off with a variable.
5914 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5915 (string-match (concat (regexp-quote s0) " *") txt)
5916 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5917 (= (match-beginning 0) 0)
5918 t))
5919 (setq txt (replace-match "" nil nil txt))))
5920 ;; Normalize the time(s) to 24 hour
5921 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5922 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5923
5924 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
5925 (and org-agenda-remove-tags-when-in-prefix
5926 org-prefix-has-tag))
5927 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
5928 (setq txt (replace-match "" t t txt)))
5929
5930 ;; Create the final string
5931 (if noprefix
5932 (setq rtn txt)
5933 ;; Prepare the variables needed in the eval of the compiled format
5934 (setq time (cond (s2 (concat s1 "-" s2))
5935 (s1 (concat s1 "......"))
5936 (t ""))
5937 extra (or extra "")
5938 category (if (symbolp category) (symbol-name category) category))
5939 ;; Evaluate the compiled format
5940 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5941
5942 ;; And finally add the text properties
5943 (add-text-properties
5944 0 (length rtn) (list 'category (downcase category)
5945 'tags tags
5946 'prefix-length (- (length rtn) (length txt))
5947 'time-of-day time-of-day
5948 'dotime dotime)
5949 rtn)
5950 rtn)))
5951
5952 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5953 (catch 'exit
5954 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5955 ((and todayp (member 'today (car org-agenda-time-grid))))
5956 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5957 ((member 'weekly (car org-agenda-time-grid)))
5958 (t (throw 'exit list)))
5959 (let* ((have (delq nil (mapcar
5960 (lambda (x) (get-text-property 1 'time-of-day x))
5961 list)))
5962 (string (nth 1 org-agenda-time-grid))
5963 (gridtimes (nth 2 org-agenda-time-grid))
5964 (req (car org-agenda-time-grid))
5965 (remove (member 'remove-match req))
5966 new time)
5967 (if (and (member 'require-timed req) (not have))
5968 ;; don't show empty grid
5969 (throw 'exit list))
5970 (while (setq time (pop gridtimes))
5971 (unless (and remove (member time have))
5972 (setq time (int-to-string time))
5973 (push (org-format-agenda-item
5974 nil string "" nil ;; FIXME: put a category for the grid?
5975 (concat (substring time 0 -2) ":" (substring time -2)))
5976 new)
5977 (put-text-property
5978 1 (length (car new)) 'face 'org-time-grid (car new))))
5979 (if (member 'time-up org-agenda-sorting-strategy)
5980 (append new list)
5981 (append list new)))))
5982
5983 (defun org-compile-prefix-format (format)
5984 "Compile the prefix format into a Lisp form that can be evaluated.
5985 The resulting form is returned and stored in the variable
5986 `org-prefix-format-compiled'."
5987 (setq org-prefix-has-time nil org-prefix-has-tag nil)
5988 (let ((start 0) varform vars var (s format)e c f opt)
5989 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5990 s start)
5991 (setq var (cdr (assoc (match-string 4 s)
5992 '(("c" . category) ("t" . time) ("s" . extra)
5993 ("T" . tag))))
5994 c (or (match-string 3 s) "")
5995 opt (match-beginning 1)
5996 start (1+ (match-beginning 0)))
5997 (if (equal var 'time) (setq org-prefix-has-time t))
5998 (if (equal var 'tag) (setq org-prefix-has-tag t))
5999 (setq f (concat "%" (match-string 2 s) "s"))
6000 (if opt
6001 (setq varform
6002 `(if (equal "" ,var)
6003 ""
6004 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6005 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6006 (setq s (replace-match "%s" t nil s))
6007 (push varform vars))
6008 (setq vars (nreverse vars))
6009 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6010
6011 (defun org-get-time-of-day (s &optional string)
6012 "Check string S for a time of day.
6013 If found, return it as a military time number between 0 and 2400.
6014 If not found, return nil.
6015 The optional STRING argument forces conversion into a 5 character wide string
6016 HH:MM."
6017 (save-match-data
6018 (when
6019 (or
6020 (string-match
6021 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6022 (string-match
6023 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6024 (let* ((t0 (+ (* 100
6025 (+ (string-to-number (match-string 1 s))
6026 (if (and (match-beginning 4)
6027 (equal (downcase (match-string 4 s)) "pm"))
6028 12 0)))
6029 (if (match-beginning 3)
6030 (string-to-number (match-string 3 s))
6031 0)))
6032 (t1 (concat " "
6033 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6034 (int-to-string t0))))
6035 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6036
6037 (defun org-finalize-agenda-entries (list)
6038 "Sort and concatenate the agenda items."
6039 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6040
6041 (defsubst org-cmp-priority (a b)
6042 "Compare the priorities of string A and B."
6043 (let ((pa (or (get-text-property 1 'priority a) 0))
6044 (pb (or (get-text-property 1 'priority b) 0)))
6045 (cond ((> pa pb) +1)
6046 ((< pa pb) -1)
6047 (t nil))))
6048
6049 (defsubst org-cmp-category (a b)
6050 "Compare the string values of categories of strings A and B."
6051 (let ((ca (or (get-text-property 1 'category a) ""))
6052 (cb (or (get-text-property 1 'category b) "")))
6053 (cond ((string-lessp ca cb) -1)
6054 ((string-lessp cb ca) +1)
6055 (t nil))))
6056
6057 (defsubst org-cmp-time (a b)
6058 "Compare the time-of-day values of strings A and B."
6059 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6060 (ta (or (get-text-property 1 'time-of-day a) def))
6061 (tb (or (get-text-property 1 'time-of-day b) def)))
6062 (cond ((< ta tb) -1)
6063 ((< tb ta) +1)
6064 (t nil))))
6065
6066 (defun org-entries-lessp (a b)
6067 "Predicate for sorting agenda entries."
6068 ;; The following variables will be used when the form is evaluated.
6069 (let* ((time-up (org-cmp-time a b))
6070 (time-down (if time-up (- time-up) nil))
6071 (priority-up (org-cmp-priority a b))
6072 (priority-down (if priority-up (- priority-up) nil))
6073 (category-up (org-cmp-category a b))
6074 (category-down (if category-up (- category-up) nil))
6075 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
6076 (cdr (assoc
6077 (eval (cons 'or org-agenda-sorting-strategy))
6078 '((-1 . t) (1 . nil) (nil . nil))))))
6079
6080 (defun org-agenda-show-priority ()
6081 "Show the priority of the current item.
6082 This priority is composed of the main priority given with the [#A] cookies,
6083 and by additional input from the age of a schedules or deadline entry."
6084 (interactive)
6085 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6086 (message "Priority is %d" (if pri pri -1000))))
6087
6088 (defun org-agenda-show-tags ()
6089 "Show the tags applicable to the current item."
6090 (interactive)
6091 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6092 (if tags
6093 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6094 (message "No tags associated with this line"))))
6095
6096 (defun org-agenda-goto (&optional highlight)
6097 "Go to the Org-mode file which contains the item at point."
6098 (interactive)
6099 (let* ((marker (or (get-text-property (point) 'org-marker)
6100 (org-agenda-error)))
6101 (buffer (marker-buffer marker))
6102 (pos (marker-position marker)))
6103 (switch-to-buffer-other-window buffer)
6104 (widen)
6105 (goto-char pos)
6106 (when (eq major-mode 'org-mode)
6107 (org-show-hidden-entry)
6108 (save-excursion
6109 (and (outline-next-heading)
6110 (org-flag-heading nil)))) ; show the next heading
6111 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6112
6113 (defun org-agenda-switch-to ()
6114 "Go to the Org-mode file which contains the item at point."
6115 (interactive)
6116 (let* ((marker (or (get-text-property (point) 'org-marker)
6117 (org-agenda-error)))
6118 (buffer (marker-buffer marker))
6119 (pos (marker-position marker)))
6120 (switch-to-buffer buffer)
6121 (delete-other-windows)
6122 (widen)
6123 (goto-char pos)
6124 (when (eq major-mode 'org-mode)
6125 (org-show-hidden-entry)
6126 (save-excursion
6127 (and (outline-next-heading)
6128 (org-flag-heading nil)))))) ; show the next heading
6129
6130 (defun org-agenda-goto-mouse (ev)
6131 "Go to the Org-mode file which contains the item at the mouse click."
6132 (interactive "e")
6133 (mouse-set-point ev)
6134 (org-agenda-goto))
6135
6136 (defun org-agenda-show ()
6137 "Display the Org-mode file which contains the item at point."
6138 (interactive)
6139 (let ((win (selected-window)))
6140 (org-agenda-goto t)
6141 (select-window win)))
6142
6143 (defun org-agenda-recenter (arg)
6144 "Display the Org-mode file which contains the item at point and recenter."
6145 (interactive "P")
6146 (let ((win (selected-window)))
6147 (org-agenda-goto t)
6148 (recenter arg)
6149 (select-window win)))
6150
6151 (defun org-agenda-show-mouse (ev)
6152 "Display the Org-mode file which contains the item at the mouse click."
6153 (interactive "e")
6154 (mouse-set-point ev)
6155 (org-agenda-show))
6156
6157 (defun org-agenda-check-no-diary ()
6158 "Check if the entry is a diary link and abort if yes."
6159 (if (get-text-property (point) 'org-agenda-diary-link)
6160 (org-agenda-error)))
6161
6162 (defun org-agenda-error ()
6163 (error "Command not allowed in this line"))
6164
6165 (defvar org-last-heading-marker (make-marker)
6166 "Marker pointing to the headline that last changed its TODO state
6167 by a remote command from the agenda.")
6168
6169 (defun org-agenda-todo (&optional arg)
6170 "Cycle TODO state of line at point, also in Org-mode file.
6171 This changes the line at point, all other lines in the agenda referring to
6172 the same tree node, and the headline of the tree node in the Org-mode file."
6173 (interactive "P")
6174 (org-agenda-check-no-diary)
6175 (let* ((col (current-column))
6176 (marker (or (get-text-property (point) 'org-marker)
6177 (org-agenda-error)))
6178 (buffer (marker-buffer marker))
6179 (pos (marker-position marker))
6180 (hdmarker (get-text-property (point) 'org-hd-marker))
6181 (buffer-read-only nil)
6182 newhead)
6183 (with-current-buffer buffer
6184 (widen)
6185 (goto-char pos)
6186 (org-show-hidden-entry)
6187 (save-excursion
6188 (and (outline-next-heading)
6189 (org-flag-heading nil))) ; show the next heading
6190 (org-todo arg)
6191 (forward-char 1)
6192 (setq newhead (org-get-heading))
6193 (save-excursion
6194 (org-back-to-heading)
6195 (move-marker org-last-heading-marker (point))))
6196 (beginning-of-line 1)
6197 (save-excursion
6198 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6199 (move-to-column col)))
6200
6201 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6202 "Change all lines in the agenda buffer which match HDMARKER.
6203 The new content of the line will be NEWHEAD (as modified by
6204 `org-format-agenda-item'). HDMARKER is checked with
6205 `equal' against all `org-hd-marker' text properties in the file.
6206 If FIXFACE is non-nil, the face of each item is modified acording to
6207 the new TODO state."
6208 (let* (props m pl undone-face done-face finish new dotime cat tags)
6209 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6210 (save-excursion
6211 (goto-char (point-max))
6212 (beginning-of-line 1)
6213 (while (not finish)
6214 (setq finish (bobp))
6215 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6216 (equal m hdmarker))
6217 (setq props (text-properties-at (point))
6218 dotime (get-text-property (point) 'dotime)
6219 cat (get-text-property (point) 'category)
6220 tags (get-text-property (point) 'tags)
6221 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6222 pl (get-text-property (point) 'prefix-length)
6223 undone-face (get-text-property (point) 'undone-face)
6224 done-face (get-text-property (point) 'done-face))
6225 (move-to-column pl)
6226 (if (looking-at ".*")
6227 (progn
6228 (replace-match new t t)
6229 (beginning-of-line 1)
6230 (add-text-properties (point-at-bol) (point-at-eol) props)
6231 (if fixface
6232 (add-text-properties
6233 (point-at-bol) (point-at-eol)
6234 (list 'face
6235 (if org-last-todo-state-is-todo
6236 undone-face done-face))))
6237 (beginning-of-line 1))
6238 (error "Line update did not work")))
6239 (beginning-of-line 0)))))
6240
6241 (defun org-agenda-priority-up ()
6242 "Increase the priority of line at point, also in Org-mode file."
6243 (interactive)
6244 (org-agenda-priority 'up))
6245
6246 (defun org-agenda-priority-down ()
6247 "Decrease the priority of line at point, also in Org-mode file."
6248 (interactive)
6249 (org-agenda-priority 'down))
6250
6251 (defun org-agenda-priority (&optional force-direction)
6252 "Set the priority of line at point, also in Org-mode file.
6253 This changes the line at point, all other lines in the agenda referring to
6254 the same tree node, and the headline of the tree node in the Org-mode file."
6255 (interactive)
6256 (org-agenda-check-no-diary)
6257 (let* ((marker (or (get-text-property (point) 'org-marker)
6258 (org-agenda-error)))
6259 (buffer (marker-buffer marker))
6260 (pos (marker-position marker))
6261 (hdmarker (get-text-property (point) 'org-hd-marker))
6262 (buffer-read-only nil)
6263 newhead)
6264 (with-current-buffer buffer
6265 (widen)
6266 (goto-char pos)
6267 (org-show-hidden-entry)
6268 (save-excursion
6269 (and (outline-next-heading)
6270 (org-flag-heading nil))) ; show the next heading
6271 (funcall 'org-priority force-direction)
6272 (end-of-line 1)
6273 (setq newhead (org-get-heading)))
6274 (org-agenda-change-all-lines newhead hdmarker)
6275 (beginning-of-line 1)))
6276
6277 (defun org-get-tags-at (&optional pos)
6278 "Get a list of all headline targs applicable at POS.
6279 POS defaults to point. If tags are inherited, the list contains
6280 the targets in the same sequence as the headlines appear, i.e.
6281 the tags of the current headline come last."
6282 (interactive)
6283 (let (tags)
6284 (save-excursion
6285 (goto-char (or pos (point)))
6286 (save-match-data
6287 (org-back-to-heading t)
6288 (condition-case nil
6289 (while t
6290 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6291 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6292 (or org-use-tag-inheritance (error ""))
6293 (org-up-heading-all 1))
6294 (error nil))))
6295 (message "%s" tags)
6296 tags))
6297
6298 (defun org-agenda-set-tags ()
6299 "Set tags for the current headline."
6300 (interactive)
6301 (org-agenda-check-no-diary)
6302 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6303 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6304 (org-agenda-error)))
6305 (buffer (marker-buffer hdmarker))
6306 (pos (marker-position hdmarker))
6307 (buffer-read-only nil)
6308 newhead)
6309 (with-current-buffer buffer
6310 (widen)
6311 (goto-char pos)
6312 (org-show-hidden-entry)
6313 (save-excursion
6314 (and (outline-next-heading)
6315 (org-flag-heading nil))) ; show the next heading
6316 (call-interactively 'org-set-tags)
6317 (end-of-line 1)
6318 (setq newhead (org-get-heading)))
6319 (org-agenda-change-all-lines newhead hdmarker)
6320 (beginning-of-line 1)))
6321
6322 (defun org-agenda-date-later (arg &optional what)
6323 "Change the date of this item to one day later."
6324 (interactive "p")
6325 (org-agenda-check-type t 'agenda 'timeline)
6326 (org-agenda-check-no-diary)
6327 (let* ((marker (or (get-text-property (point) 'org-marker)
6328 (org-agenda-error)))
6329 (buffer (marker-buffer marker))
6330 (pos (marker-position marker)))
6331 (with-current-buffer buffer
6332 (widen)
6333 (goto-char pos)
6334 (if (not (org-at-timestamp-p))
6335 (error "Cannot find time stamp"))
6336 (org-timestamp-change arg (or what 'day))
6337 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6338
6339 (defun org-agenda-date-earlier (arg &optional what)
6340 "Change the date of this item to one day earlier."
6341 (interactive "p")
6342 (org-agenda-date-later (- arg) what))
6343
6344 (defun org-agenda-date-prompt (arg)
6345 "Change the date of this item. Date is prompted for, with default today.
6346 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6347 be used to request time specification in the time stamp."
6348 (interactive "P")
6349 (org-agenda-check-type t 'agenda 'timeline)
6350 (org-agenda-check-no-diary)
6351 (let* ((marker (or (get-text-property (point) 'org-marker)
6352 (org-agenda-error)))
6353 (buffer (marker-buffer marker))
6354 (pos (marker-position marker)))
6355 (with-current-buffer buffer
6356 (widen)
6357 (goto-char pos)
6358 (if (not (org-at-timestamp-p))
6359 (error "Cannot find time stamp"))
6360 (org-time-stamp arg)
6361 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6362
6363 (defun org-get-heading ()
6364 "Return the heading of the current entry, without the stars."
6365 (save-excursion
6366 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6367 ;;FIXME???????? (and (bolp) (end-of-line 1))
6368 (if (and (re-search-backward "[\r\n]\\*" nil t)
6369 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6370 (match-string 1)
6371 "")))
6372
6373 (defun org-agenda-diary-entry ()
6374 "Make a diary entry, like the `i' command from the calendar.
6375 All the standard commands work: block, weekly etc."
6376 (interactive)
6377 (org-agenda-check-type t 'agenda 'timeline)
6378 (require 'diary-lib)
6379 (let* ((char (progn
6380 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6381 (read-char-exclusive)))
6382 (cmd (cdr (assoc char
6383 '((?d . insert-diary-entry)
6384 (?w . insert-weekly-diary-entry)
6385 (?m . insert-monthly-diary-entry)
6386 (?y . insert-yearly-diary-entry)
6387 (?a . insert-anniversary-diary-entry)
6388 (?b . insert-block-diary-entry)
6389 (?c . insert-cyclic-diary-entry)))))
6390 (oldf (symbol-function 'calendar-cursor-to-date))
6391 (point (point))
6392 (mark (or (mark t) (point))))
6393 (unless cmd
6394 (error "No command associated with <%c>" char))
6395 (unless (and (get-text-property point 'day)
6396 (or (not (equal ?b char))
6397 (get-text-property mark 'day)))
6398 (error "Don't know which date to use for diary entry"))
6399 ;; We implement this by hacking the `calendar-cursor-to-date' function
6400 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6401 (let ((calendar-mark-ring
6402 (list (calendar-gregorian-from-absolute
6403 (or (get-text-property mark 'day)
6404 (get-text-property point 'day))))))
6405 (unwind-protect
6406 (progn
6407 (fset 'calendar-cursor-to-date
6408 (lambda (&optional error)
6409 (calendar-gregorian-from-absolute
6410 (get-text-property point 'day))))
6411 (call-interactively cmd))
6412 (fset 'calendar-cursor-to-date oldf)))))
6413
6414
6415 (defun org-agenda-execute-calendar-command (cmd)
6416 "Execute a calendar command from the agenda, with the date associated to
6417 the cursor position."
6418 (org-agenda-check-type t 'agenda 'timeline)
6419 (require 'diary-lib)
6420 (unless (get-text-property (point) 'day)
6421 (error "Don't know which date to use for calendar command"))
6422 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6423 (point (point))
6424 (date (calendar-gregorian-from-absolute
6425 (get-text-property point 'day)))
6426 (displayed-day (extract-calendar-day date))
6427 (displayed-month (extract-calendar-month date))
6428 (displayed-year (extract-calendar-year date)))
6429 (unwind-protect
6430 (progn
6431 (fset 'calendar-cursor-to-date
6432 (lambda (&optional error)
6433 (calendar-gregorian-from-absolute
6434 (get-text-property point 'day))))
6435 (call-interactively cmd))
6436 (fset 'calendar-cursor-to-date oldf))))
6437
6438 (defun org-agenda-phases-of-moon ()
6439 "Display the phases of the moon for the 3 months around the cursor date."
6440 (interactive)
6441 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6442
6443 (defun org-agenda-holidays ()
6444 "Display the holidays for the 3 months around the cursor date."
6445 (interactive)
6446 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6447
6448 (defun org-agenda-sunrise-sunset (arg)
6449 "Display sunrise and sunset for the cursor date.
6450 Latitude and longitude can be specified with the variables
6451 `calendar-latitude' and `calendar-longitude'. When called with prefix
6452 argument, latitude and longitude will be prompted for."
6453 (interactive "P")
6454 (let ((calendar-longitude (if arg nil calendar-longitude))
6455 (calendar-latitude (if arg nil calendar-latitude))
6456 (calendar-location-name
6457 (if arg "the given coordinates" calendar-location-name)))
6458 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6459
6460 (defun org-agenda-goto-calendar ()
6461 "Open the Emacs calendar with the date at the cursor."
6462 (interactive)
6463 (org-agenda-check-type t 'agenda 'timeline)
6464 (let* ((day (or (get-text-property (point) 'day)
6465 (error "Don't know which date to open in calendar")))
6466 (date (calendar-gregorian-from-absolute day))
6467 (calendar-move-hook nil)
6468 (view-diary-entries-initially nil))
6469 (calendar)
6470 (calendar-goto-date date)))
6471
6472 (defun org-calendar-goto-agenda ()
6473 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6474 This is a command that has to be installed in `calendar-mode-map'."
6475 (interactive)
6476 (org-agenda-list nil (calendar-absolute-from-gregorian
6477 (calendar-cursor-to-date))
6478 nil t))
6479
6480 (defun org-agenda-convert-date ()
6481 (interactive)
6482 (org-agenda-check-type t 'agenda 'timeline)
6483 (let ((day (get-text-property (point) 'day))
6484 date s)
6485 (unless day
6486 (error "Don't know which date to convert"))
6487 (setq date (calendar-gregorian-from-absolute day))
6488 (setq s (concat
6489 "Gregorian: " (calendar-date-string date) "\n"
6490 "ISO: " (calendar-iso-date-string date) "\n"
6491 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6492 "Julian: " (calendar-julian-date-string date) "\n"
6493 "Astron. JD: " (calendar-astro-date-string date)
6494 " (Julian date number at noon UTC)\n"
6495 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6496 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6497 "French: " (calendar-french-date-string date) "\n"
6498 "Mayan: " (calendar-mayan-date-string date) "\n"
6499 "Coptic: " (calendar-coptic-date-string date) "\n"
6500 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6501 "Persian: " (calendar-persian-date-string date) "\n"
6502 "Chinese: " (calendar-chinese-date-string date) "\n"))
6503 (with-output-to-temp-buffer "*Dates*"
6504 (princ s))
6505 (if (fboundp 'fit-window-to-buffer)
6506 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6507
6508 ;;; Tags
6509
6510 (defun org-scan-tags (action matcher &optional todo-only)
6511 "Scan headline tags with inheritance and produce output ACTION.
6512 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6513 evaluated, testing if a given set of tags qualifies a headline for
6514 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6515 are included in the output."
6516 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6517 (mapconcat 'regexp-quote
6518 (nreverse (cdr (reverse org-todo-keywords)))
6519 "\\|")
6520 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6521 (props (list 'face nil
6522 'done-face 'org-done
6523 'undone-face nil
6524 'mouse-face 'highlight
6525 'keymap org-agenda-keymap
6526 'help-echo
6527 (format "mouse-2 or RET jump to org file %s"
6528 (abbreviate-file-name buffer-file-name))))
6529 lspos
6530 tags tags-list tags-alist (llast 0) rtn level category i txt
6531 todo marker)
6532
6533 (save-excursion
6534 (goto-char (point-min))
6535 (when (eq action 'sparse-tree) (hide-sublevels 1))
6536 (while (re-search-forward re nil t)
6537 (setq todo (if (match-end 1) (match-string 2))
6538 tags (if (match-end 4) (match-string 4)))
6539 (goto-char (setq lspos (1+ (match-beginning 0))))
6540 (setq level (funcall outline-level)
6541 category (org-get-category))
6542 (setq i llast llast level)
6543 ;; remove tag lists from same and sublevels
6544 (while (>= i level)
6545 (when (setq entry (assoc i tags-alist))
6546 (setq tags-alist (delete entry tags-alist)))
6547 (setq i (1- i)))
6548 ;; add the nex tags
6549 (when tags
6550 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6551 tags-alist
6552 (cons (cons level tags) tags-alist)))
6553 ;; compile tags for current headline
6554 (setq tags-list
6555 (if org-use-tag-inheritance
6556 (apply 'append (mapcar 'cdr tags-alist))
6557 tags))
6558 (when (and (or (not todo-only) todo)
6559 (eval matcher))
6560 ;; list this headline
6561 (if (eq action 'sparse-tree)
6562 (progn
6563 (org-show-hierarchy-above))
6564 (setq txt (org-format-agenda-item
6565 ""
6566 (concat
6567 (if org-tags-match-list-sublevels
6568 (make-string (1- level) ?.) "")
6569 (org-get-heading))
6570 category tags-list))
6571 (goto-char lspos)
6572 (setq marker (org-agenda-new-marker))
6573 (add-text-properties
6574 0 (length txt)
6575 (append (list 'org-marker marker 'org-hd-marker marker
6576 'category category)
6577 props)
6578 txt)
6579 (push txt rtn))
6580 ;; if we are to skip sublevels, jump to end of subtree
6581 (point)
6582 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6583 (nreverse rtn)))
6584
6585 (defun org-tags-sparse-tree (&optional arg match)
6586 "Create a sparse tree according to tags search string MATCH.
6587 MATCH can contain positive and negative selection of tags, like
6588 \"+WORK+URGENT-WITHBOSS\"."
6589 (interactive "P")
6590 (let ((org-show-following-heading nil)
6591 (org-show-hierarchy-above nil))
6592 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6593
6594 (defun org-make-tags-matcher (match)
6595 "Create the TAGS matcher form for the tags-selecting string MATCH."
6596 (unless match
6597 ;; Get a new match request, with completion
6598 (setq org-last-tags-completion-table
6599 (or (org-get-buffer-tags)
6600 org-last-tags-completion-table))
6601 (setq match (completing-read
6602 "Tags: " 'org-tags-completion-function nil nil nil
6603 'org-tags-history)))
6604 ;; parse the string and create a lisp form
6605 (let ((match0 match) minus tag mm matcher orterms term orlist)
6606 (setq orterms (org-split-string match "|"))
6607 (while (setq term (pop orterms))
6608 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
6609 (setq minus (and (match-end 1)
6610 (equal (match-string 1 term) "-"))
6611 tag (match-string 2 term)
6612 term (substring term (match-end 0))
6613 mm (list 'member (downcase tag) 'tags-list)
6614 mm (if minus (list 'not mm) mm))
6615 (push mm matcher))
6616 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6617 orlist)
6618 (setq matcher nil))
6619 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6620 ;; Return the string and lisp forms of the matcher
6621 (cons match0 matcher)))
6622
6623 ;;;###autoload
6624 (defun org-tags-view (&optional todo-only match keep-modes)
6625 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
6626 The prefix arg TODO-ONLY limits the search to TODO entries."
6627 (interactive "P")
6628 (org-agenda-maybe-reset-markers 'force)
6629 (org-compile-prefix-format org-agenda-prefix-format)
6630 (let* ((org-agenda-keep-modes keep-modes)
6631 (org-tags-match-list-sublevels
6632 (if todo-only t org-tags-match-list-sublevels))
6633 (win (selected-window))
6634 (completion-ignore-case t)
6635 rtn rtnall files file pos matcher
6636 buffer)
6637 (setq matcher (org-make-tags-matcher match)
6638 match (car matcher) matcher (cdr matcher))
6639 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6640 (progn
6641 (delete-other-windows)
6642 (switch-to-buffer-other-window
6643 (get-buffer-create org-agenda-buffer-name))))
6644 (setq buffer-read-only nil)
6645 (erase-buffer)
6646 (org-agenda-mode) (setq buffer-read-only nil)
6647 (set (make-local-variable 'org-agenda-type) 'tags)
6648 (set (make-local-variable 'org-agenda-redo-command)
6649 (list 'org-tags-view (list 'quote todo-only)
6650 (list 'if 'current-prefix-arg nil match) t))
6651 (setq files (org-agenda-files)
6652 rtnall nil)
6653 (while (setq file (pop files))
6654 (catch 'nextfile
6655 (org-check-agenda-file file)
6656 (setq buffer (if (file-exists-p file)
6657 (org-get-agenda-file-buffer file)
6658 (error "No such file %s" file)))
6659 (if (not buffer)
6660 ;; If file does not exist, merror message to agenda
6661 (setq rtn (list
6662 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6663 rtnall (append rtnall rtn))
6664 (with-current-buffer buffer
6665 (unless (eq major-mode 'org-mode)
6666 (error "Agenda file %s is not in `org-mode'" file))
6667 (save-excursion
6668 (save-restriction
6669 (if org-respect-restriction
6670 (if (org-region-active-p)
6671 ;; Respect a region to restrict search
6672 (narrow-to-region (region-beginning) (region-end)))
6673 ;; If we work for the calendar or many files,
6674 ;; get rid of any restriction
6675 (widen))
6676 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6677 (setq rtnall (append rtnall rtn))))))))
6678 (insert "Headlines with TAGS match: ")
6679 (add-text-properties (point-min) (1- (point))
6680 (list 'face 'org-link))
6681 (setq pos (point))
6682 (insert match "\n")
6683 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6684 (setq pos (point))
6685 (insert "Press `C-u r' to search again with new search string\n")
6686 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6687 (when rtnall
6688 (insert (mapconcat 'identity rtnall "\n")))
6689 (goto-char (point-min))
6690 (setq buffer-read-only t)
6691 (org-fit-agenda-window)
6692 (if (not org-select-agenda-window) (select-window win))))
6693
6694 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6695 (defun org-set-tags (&optional arg just-align)
6696 "Set the tags for the current headline.
6697 With prefix ARG, realign all tags in headings in the current buffer."
6698 (interactive)
6699 (let* (;(inherit (org-get-inherited-tags))
6700 (re (concat "^" outline-regexp))
6701 (col (current-column))
6702 (current (org-get-tags))
6703 tags hd empty invis)
6704 (if arg
6705 (save-excursion
6706 (goto-char (point-min))
6707 (while (re-search-forward re nil t)
6708 (org-set-tags nil t))
6709 (message "All tags realigned to column %d" org-tags-column))
6710 (if just-align
6711 (setq tags current)
6712 (setq org-last-tags-completion-table
6713 (or (org-get-buffer-tags)
6714 org-last-tags-completion-table))
6715 (setq tags
6716 (let ((org-add-colon-after-tag-completion t))
6717 (completing-read "Tags: " 'org-tags-completion-function
6718 nil nil current 'org-tags-history)))
6719 (while (string-match "[-+&]+" tags)
6720 (setq tags (replace-match ":" t t tags))))
6721 ;; FIXME: still optimize this byt not checking when JUST-ALIGN?
6722 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6723 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6724 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
6725 (if (equal current "")
6726 (progn
6727 (end-of-line 1)
6728 (or empty (insert-before-markers " ")))
6729 (beginning-of-line 1)
6730 (setq invis (org-invisible-p))
6731 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6732 (setq hd (match-string 1))
6733 (delete-region (match-beginning 0) (match-end 0))
6734 (insert-before-markers (org-trim hd) (if empty "" " ")))
6735 ;; FIXME: What happens when adding a new tag??? Seems OK!!!
6736 (unless (equal tags "")
6737 (move-to-column (max (current-column)
6738 (if (> org-tags-column 0)
6739 org-tags-column
6740 (- (- org-tags-column) (length tags))))
6741 t)
6742 (insert-before-markers tags)
6743 (if (and (not invis) (org-invisible-p))
6744 (outline-flag-region (point-at-bol) (point) nil)))
6745 (move-to-column col))))
6746
6747 (defun org-tags-completion-function (string predicate &optional flag)
6748 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6749 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6750 (setq s1 (match-string 1 string)
6751 s2 (match-string 2 string))
6752 (setq s1 "" s2 string))
6753 (cond
6754 ((eq flag nil)
6755 ;; try completion
6756 (setq rtn (try-completion s2 ctable))
6757 (if (stringp rtn)
6758 (concat s1 s2 (substring rtn (length s2))
6759 (if (and org-add-colon-after-tag-completion
6760 (assoc rtn ctable))
6761 ":" "")))
6762 )
6763 ((eq flag t)
6764 ;; all-completions
6765 (all-completions s2 ctable)
6766 )
6767 ((eq flag 'lambda)
6768 ;; exact match?
6769 (assoc s2 ctable)))
6770 ))
6771
6772 (defun org-get-tags ()
6773 "Get the TAGS string in the current headline."
6774 (unless (org-on-heading-p)
6775 (error "Not on a heading"))
6776 (save-excursion
6777 (beginning-of-line 1)
6778 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
6779 (match-string 1)
6780 "")))
6781
6782 (defun org-get-buffer-tags ()
6783 "Get a table of all tags used in the buffer, for completion."
6784 (let (tags)
6785 (save-excursion
6786 (goto-char (point-min))
6787 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
6788 (mapc (lambda (x) (add-to-list 'tags x))
6789 (org-split-string (match-string 1) ":"))))
6790 (mapcar 'list tags)))
6791
6792 ;;; Link Stuff
6793
6794 (defun org-find-file-at-mouse (ev)
6795 "Open file link or URL at mouse."
6796 (interactive "e")
6797 (mouse-set-point ev)
6798 (org-open-at-point 'in-emacs))
6799
6800 (defun org-open-at-mouse (ev)
6801 "Open file link or URL at mouse."
6802 (interactive "e")
6803 (mouse-set-point ev)
6804 (org-open-at-point))
6805
6806 (defun org-open-at-point (&optional in-emacs)
6807 "Open link at or after point.
6808 If there is no link at point, this function will search forward up to
6809 the end of the current subtree.
6810 Normally, files will be opened by an appropriate application. If the
6811 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6812 (interactive "P")
6813 (org-remove-occur-highlights nil nil t)
6814 (if (org-at-timestamp-p)
6815 (org-agenda-list nil (time-to-days (org-time-string-to-time
6816 (substring (match-string 1) 0 10)))
6817 1)
6818 (let (type path link line search (pos (point)))
6819 (catch 'match
6820 (save-excursion
6821 (skip-chars-forward "^]\n\r")
6822 (when (and (re-search-backward "\\[\\[" nil t)
6823 (looking-at org-bracket-link-regexp)
6824 (<= (match-beginning 0) pos)
6825 (>= (match-end 0) pos))
6826 (setq link (match-string 1))
6827 (while (string-match " *\n *" link)
6828 (setq link (replace-match " " t t link)))
6829 (if (string-match org-link-regexp link)
6830 (setq type (match-string 1)
6831 path (match-string 2))
6832 (setq type "thisfile"
6833 path link))
6834 (throw 'match t)))
6835
6836 (when (get-text-property (point) 'org-linked-text)
6837 (setq type "thisfile"
6838 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6839 (1+ (point)) (point))
6840 path (buffer-substring
6841 (previous-single-property-change pos 'org-linked-text)
6842 (next-single-property-change pos 'org-linked-text)))
6843 (throw 'match t))
6844
6845 (save-excursion
6846 (skip-chars-backward
6847 (concat (if org-allow-space-in-links "^" "^ ")
6848 org-non-link-chars))
6849 (when (or (looking-at org-link-regexp)
6850 (and (re-search-forward org-link-regexp (point-at-eol) t)
6851 (<= (match-beginning 0) pos)
6852 (>= (match-end 0) pos)))
6853 (setq type (match-string 1)
6854 path (match-string 2))
6855 (throw 'match t)))
6856 (save-excursion
6857 (skip-chars-backward "^ \t\n\r")
6858 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
6859 (setq type "tags"
6860 path (match-string 1))
6861 (while (string-match ":" path)
6862 (setq path (replace-match "+" t t path)))
6863 (throw 'match t)))
6864 (save-excursion
6865 (skip-chars-backward "a-zA-Z_")
6866 (when (and org-activate-camels
6867 (looking-at org-camel-regexp))
6868 (setq type "camel" path (match-string 0))
6869 (if (equal (char-before) ?*)
6870 (setq path (concat "*" path))))
6871 (throw 'match t))
6872 (save-excursion
6873 (when (re-search-forward
6874 org-link-regexp
6875 (save-excursion
6876 (condition-case nil
6877 (progn (outline-end-of-subtree) (max pos (point)))
6878 (error (end-of-line 1) (point))))
6879 t)
6880 (setq type (match-string 1)
6881 path (match-string 2)))))
6882 (unless path
6883 (error "No link found"))
6884 ;; Remove any trailing spaces in path
6885 (if (string-match " +\\'" path)
6886 (setq path (replace-match "" t t path)))
6887
6888 (cond
6889
6890 ((string= type "tags")
6891 (org-tags-view in-emacs path))
6892 ((or (string= type "camel")
6893 (string= type "thisfile"))
6894 (org-mark-ring-push)
6895 (org-link-search
6896 path
6897 (cond ((equal in-emacs '(4)) 'occur)
6898 ((equal in-emacs '(16)) 'org-occur)
6899 (t nil))))
6900
6901 ((string= type "file")
6902 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6903 (setq line (string-to-number (match-string 1 path))
6904 path (substring path 0 (match-beginning 0)))
6905 (if (string-match "::\\(.+\\)\\'" path)
6906 (setq search (match-string 1 path)
6907 path (substring path 0 (match-beginning 0)))))
6908 (org-open-file path in-emacs line search))
6909
6910 ((string= type "news")
6911 (org-follow-gnus-link path))
6912
6913 ((string= type "bbdb")
6914 (org-follow-bbdb-link path))
6915
6916 ((string= type "gnus")
6917 (let (group article)
6918 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6919 (error "Error in Gnus link"))
6920 (setq group (match-string 1 path)
6921 article (match-string 3 path))
6922 (org-follow-gnus-link group article)))
6923
6924 ((string= type "vm")
6925 (let (folder article)
6926 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6927 (error "Error in VM link"))
6928 (setq folder (match-string 1 path)
6929 article (match-string 3 path))
6930 ;; in-emacs is the prefix arg, will be interpreted as read-only
6931 (org-follow-vm-link folder article in-emacs)))
6932
6933 ((string= type "wl")
6934 (let (folder article)
6935 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6936 (error "Error in Wanderlust link"))
6937 (setq folder (match-string 1 path)
6938 article (match-string 3 path))
6939 (org-follow-wl-link folder article)))
6940
6941 ((string= type "mhe")
6942 (let (folder article)
6943 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6944 (error "Error in MHE link"))
6945 (setq folder (match-string 1 path)
6946 article (match-string 3 path))
6947 (org-follow-mhe-link folder article)))
6948
6949 ((string= type "rmail")
6950 (let (folder article)
6951 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6952 (error "Error in RMAIL link"))
6953 (setq folder (match-string 1 path)
6954 article (match-string 3 path))
6955 (org-follow-rmail-link folder article)))
6956
6957 ((string= type "shell")
6958 (let ((cmd path))
6959 (while (string-match "@{" cmd)
6960 (setq cmd (replace-match "<" t t cmd)))
6961 (while (string-match "@}" cmd)
6962 (setq cmd (replace-match ">" t t cmd)))
6963 (if (or (not org-confirm-shell-links)
6964 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6965 (shell-command cmd)
6966 (error "Abort"))))
6967
6968 (t
6969 (browse-url-at-point))))))
6970
6971 (defun org-link-search (s &optional type)
6972 "Search for a link search option.
6973 When S is a CamelCaseWord, search for a target, or for a sentence containing
6974 the words. If S is surrounded by forward slashes, it is interpreted as a
6975 regular expression. In org-mode files, this will create an `org-occur'
6976 sparse tree. In ordinary files, `occur' will be used to list matches.
6977 If the current buffer is in `dired-mode', grep will be used to search
6978 in all files."
6979 (let ((case-fold-search t)
6980 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6981 (pos (point))
6982 (pre "") (post "")
6983 words re0 re1 re2 re3 re4 re5 re2a reall camel)
6984 (cond ((save-excursion
6985 (goto-char (point-min))
6986 (and
6987 (re-search-forward
6988 (concat "<<" (regexp-quote s0) ">>") nil t)
6989 (setq pos (match-beginning 0))))
6990 ;; There is an exact target for this
6991 (goto-char pos))
6992 ((string-match "^/\\(.*\\)/$" s)
6993 ;; A regular expression
6994 (cond
6995 ((eq major-mode 'org-mode)
6996 (org-occur (match-string 1 s)))
6997 ;;((eq major-mode 'dired-mode)
6998 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6999 (t (org-do-occur (match-string 1 s)))))
7000 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
7001 t)
7002 ;; A camel or a normal search string
7003 (when (equal (string-to-char s) ?*)
7004 ;; Anchor on headlines, post may include tags.
7005 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
7006 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
7007 s (substring s 1)))
7008 (remove-text-properties
7009 0 (length s)
7010 '(face nil mouse-face nil keymap nil fontified nil) s)
7011 ;; Make a series of regular expressions to find a match
7012 (setq words
7013 (if camel
7014 (org-camel-to-words s)
7015 (org-split-string s "[ \n\r\t]+"))
7016 re0 (concat "<<" (regexp-quote s0) ">>")
7017 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
7018 re2a (concat "\\<" (mapconcat 'downcase words "[ \t\r\n]+") "\\>")
7019 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
7020 re1 (concat pre re2 post)
7021 re3 (concat pre re4 post)
7022 re5 (concat pre ".*" re4)
7023 re2 (concat pre re2)
7024 re2a (concat pre re2a)
7025 re4 (concat pre re4)
7026 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7027 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7028 re5 "\\)"
7029 ))
7030 (cond
7031 ((eq type 'org-occur) (org-occur reall))
7032 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7033 (t (goto-char (point-min))
7034 (if (or (org-search-not-link re0 nil t)
7035 (org-search-not-link re1 nil t)
7036 (org-search-not-link re2 nil t)
7037 (org-search-not-link re2a nil t) ;; FIXME: Right place???
7038 (org-search-not-link re3 nil t)
7039 (org-search-not-link re4 nil t)
7040 (org-search-not-link re5 nil t)
7041 )
7042 (goto-char (match-beginning 0))
7043 (goto-char pos)
7044 (error "No match")))))
7045 (t
7046 ;; Normal string-search
7047 (goto-char (point-min))
7048 (if (search-forward s nil t)
7049 (goto-char (match-beginning 0))
7050 (error "No match"))))
7051 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7052
7053 (defun org-search-not-link (&rest args)
7054 "Execute `re-search-forward', but only accept matches that are not a link."
7055 (catch 'exit
7056 (let ((pos (point)) p1)
7057 (while (apply 're-search-forward args)
7058 (setq p1 (point))
7059 (if (not (save-match-data
7060 (and (re-search-backward "\\[\\[" nil t)
7061 (looking-at org-bracket-link-regexp)
7062 (<= (match-beginning 0) p1)
7063 (>= (match-end 0) p1))))
7064 (progn (goto-char (match-end 0))
7065 (throw 'exit (point)))
7066 (goto-char (match-end 0)))))))
7067
7068 (defun org-do-occur (regexp &optional cleanup)
7069 "Call the Emacs command `occur'.
7070 If CLEANUP is non-nil, remove the printout of the regular expression
7071 in the *Occur* buffer. This is useful if the regex is long and not useful
7072 to read."
7073 (occur regexp)
7074 (when cleanup
7075 (let ((cwin (selected-window)) win beg end)
7076 (when (setq win (get-buffer-window "*Occur*"))
7077 (select-window win))
7078 (goto-char (point-min))
7079 (when (re-search-forward "match[a-z]+" nil t)
7080 (setq beg (match-end 0))
7081 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7082 (setq end (1- (match-beginning 0)))))
7083 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7084 (goto-char (point-min))
7085 (select-window cwin))))
7086
7087 (defvar org-mark-ring nil
7088 "Mark ring for positions before jumps in Org-mode.")
7089 (defvar org-mark-ring-last-goto nil
7090 "Last position in the mark ring used to go back.")
7091 ;; Fill and close the ring
7092 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7093 (loop for i from 1 to org-mark-ring-length do
7094 (push (make-marker) org-mark-ring))
7095 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7096 org-mark-ring)
7097
7098 (defun org-mark-ring-push (&optional pos buffer)
7099 "Put the current position or POS into the mark ring and rotate it."
7100 (interactive)
7101 (setq pos (or pos (point)))
7102 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7103 (move-marker (car org-mark-ring)
7104 (or pos (point))
7105 (or buffer (current-buffer)))
7106 (message
7107 (substitute-command-keys
7108 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7109
7110 (defun org-mark-ring-goto (&optional n)
7111 "Jump to the previous position in the mark ring.
7112 With prefix arg N, jump back that many stored positions. When
7113 called several times in succession, walk through the entire ring.
7114 Org-mode commands jumping to a different position in the current file,
7115 or to another Org-mode file, automatically push the old position
7116 onto the ring."
7117 (interactive "p")
7118 (let (p m)
7119 (if (eq last-command this-command)
7120 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7121 (setq p org-mark-ring))
7122 (setq org-mark-ring-last-goto p)
7123 (setq m (car p))
7124 (switch-to-buffer (marker-buffer m))
7125 (goto-char m)
7126 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7127
7128 (defun org-camel-to-words (s)
7129 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7130 (let ((case-fold-search nil)
7131 words)
7132 (while (string-match "[a-z][A-Z]" s)
7133 (push (substring s 0 (1+ (match-beginning 0))) words)
7134 (setq s (substring s (1+ (match-beginning 0)))))
7135 (nreverse (cons s words))))
7136
7137 (defun org-remove-angle-brackets (s)
7138 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7139 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7140 s)
7141 (defun org-add-angle-brackets (s)
7142 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7143 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7144 s)
7145
7146 (defun org-follow-bbdb-link (name)
7147 "Follow a BBDB link to NAME."
7148 (require 'bbdb)
7149 (let ((inhibit-redisplay t)
7150 (bbdb-electric-p nil))
7151 (catch 'exit
7152 ;; Exact match on name
7153 (bbdb-name (concat "\\`" name "\\'") nil)
7154 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7155 ;; Exact match on name
7156 (bbdb-company (concat "\\`" name "\\'") nil)
7157 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7158 ;; Partial match on name
7159 (bbdb-name name nil)
7160 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7161 ;; Partial match on company
7162 (bbdb-company name nil)
7163 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7164 ;; General match including network address and notes
7165 (bbdb name nil)
7166 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7167 (delete-window (get-buffer-window "*BBDB*"))
7168 (error "No matching BBDB record")))))
7169
7170 (defun org-follow-gnus-link (&optional group article)
7171 "Follow a Gnus link to GROUP and ARTICLE."
7172 (require 'gnus)
7173 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7174 (if group (gnus-fetch-group group))
7175 (if article
7176 (or (gnus-summary-goto-article article nil 'force)
7177 (if (fboundp 'gnus-summary-insert-cached-articles)
7178 (progn
7179 (gnus-summary-insert-cached-articles)
7180 (gnus-summary-goto-article article nil 'force))
7181 (message "Message could not be found.")))))
7182
7183 (defun org-follow-vm-link (&optional folder article readonly)
7184 "Follow a VM link to FOLDER and ARTICLE."
7185 (require 'vm)
7186 (setq article (org-add-angle-brackets article))
7187 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7188 ;; ange-ftp or efs or tramp access
7189 (let ((user (or (match-string 1 folder) (user-login-name)))
7190 (host (match-string 2 folder))
7191 (file (match-string 3 folder)))
7192 (cond
7193 ((featurep 'tramp)
7194 ;; use tramp to access the file
7195 (if org-xemacs-p
7196 (setq folder (format "[%s@%s]%s" user host file))
7197 (setq folder (format "/%s@%s:%s" user host file))))
7198 (t
7199 ;; use ange-ftp or efs
7200 (require (if org-xemacs-p 'efs 'ange-ftp))
7201 (setq folder (format "/%s@%s:%s" user host file))))))
7202 (when folder
7203 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7204 (sit-for 0.1)
7205 (when article
7206 (vm-select-folder-buffer)
7207 (widen)
7208 (let ((case-fold-search t))
7209 (goto-char (point-min))
7210 (if (not (re-search-forward
7211 (concat "^" "message-id: *" (regexp-quote article))))
7212 (error "Could not find the specified message in this folder"))
7213 (vm-isearch-update)
7214 (vm-isearch-narrow)
7215 (vm-beginning-of-message)
7216 (vm-summarize)))))
7217
7218 (defun org-follow-wl-link (folder article)
7219 "Follow a Wanderlust link to FOLDER and ARTICLE."
7220 (setq article (org-add-angle-brackets article))
7221 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7222 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7223 (wl-summary-redisplay))
7224
7225 (defun org-follow-rmail-link (folder article)
7226 "Follow an RMAIL link to FOLDER and ARTICLE."
7227 (setq article (org-add-angle-brackets article))
7228 (let (message-number)
7229 (save-excursion
7230 (save-window-excursion
7231 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7232 (setq message-number
7233 (save-restriction
7234 (widen)
7235 (goto-char (point-max))
7236 (if (re-search-backward
7237 (concat "^Message-ID:\\s-+" (regexp-quote
7238 (or article "")))
7239 nil t)
7240 (rmail-what-message))))))
7241 (if message-number
7242 (progn
7243 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7244 (rmail-show-message message-number)
7245 message-number)
7246 (error "Message not found"))))
7247
7248 ;; mh-e integration based on planner-mode
7249 (defun org-mhe-get-message-real-folder ()
7250 "Return the name of the current message real folder, so if you use
7251 sequences, it will now work."
7252 (save-excursion
7253 (let* ((folder
7254 (if (equal major-mode 'mh-folder-mode)
7255 mh-current-folder
7256 ;; Refer to the show buffer
7257 mh-show-folder-buffer))
7258 (end-index
7259 (if (boundp 'mh-index-folder)
7260 (min (length mh-index-folder) (length folder))))
7261 )
7262 ;; a simple test on mh-index-data does not work, because
7263 ;; mh-index-data is always nil in a show buffer.
7264 (if (and (boundp 'mh-index-folder)
7265 (string= mh-index-folder (substring folder 0 end-index)))
7266 (if (equal major-mode 'mh-show-mode)
7267 (save-window-excursion
7268 (when (buffer-live-p (get-buffer folder))
7269 (progn
7270 (pop-to-buffer folder)
7271 (org-mhe-get-message-folder-from-index)
7272 )
7273 ))
7274 (org-mhe-get-message-folder-from-index)
7275 )
7276 folder
7277 )
7278 )))
7279
7280 (defun org-mhe-get-message-folder-from-index ()
7281 "Returns the name of the message folder in a index folder buffer."
7282 (save-excursion
7283 (mh-index-previous-folder)
7284 (re-search-forward "^\\(+.*\\)$" nil t)
7285 (message (match-string 1))))
7286
7287 (defun org-mhe-get-message-folder ()
7288 "Return the name of the current message folder. Be careful if you
7289 use sequences."
7290 (save-excursion
7291 (if (equal major-mode 'mh-folder-mode)
7292 mh-current-folder
7293 ;; Refer to the show buffer
7294 mh-show-folder-buffer)))
7295
7296 (defun org-mhe-get-message-num ()
7297 "Return the number of the current message. Be careful if you
7298 use sequences."
7299 (save-excursion
7300 (if (equal major-mode 'mh-folder-mode)
7301 (mh-get-msg-num nil)
7302 ;; Refer to the show buffer
7303 (mh-show-buffer-message-number))))
7304
7305 (defun org-mhe-get-header (header)
7306 "Return a header of the message in folder mode. This will create a
7307 show buffer for the corresponding message. If you have a more clever
7308 idea..."
7309 (let* ((folder (org-mhe-get-message-folder))
7310 (num (org-mhe-get-message-num))
7311 (buffer (get-buffer-create (concat "show-" folder)))
7312 (header-field))
7313 (with-current-buffer buffer
7314 (mh-display-msg num folder)
7315 (if (equal major-mode 'mh-folder-mode)
7316 (mh-header-display)
7317 (mh-show-header-display))
7318 (set-buffer buffer)
7319 (setq header-field (mh-get-header-field header))
7320 (if (equal major-mode 'mh-folder-mode)
7321 (mh-show)
7322 (mh-show-show))
7323 header-field)))
7324
7325 (defun org-follow-mhe-link (folder article)
7326 "Follow an MHE link to FOLDER and ARTICLE.
7327 If ARTICLE is nil FOLDER is shown. If the configuration variable
7328 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
7329 ARTICLE is searched in all folders. Indexed searches (swish++,
7330 namazu, and others supported by MH-E) will always search in all
7331 folders."
7332 (require 'mh-e)
7333 (require 'mh-search)
7334 (require 'mh-utils)
7335 (mh-find-path)
7336 (if (not article)
7337 (mh-visit-folder (mh-normalize-folder-name folder))
7338 (setq article (org-add-angle-brackets article))
7339 (mh-search-choose)
7340 (if (equal mh-searcher 'pick)
7341 (progn
7342 (mh-search folder (list "--message-id" article))
7343 (when (and org-mhe-search-all-folders
7344 (not (org-mhe-get-message-real-folder)))
7345 (kill-this-buffer)
7346 (mh-search "+" (list "--message-id" article))))
7347 (mh-search "+" article))
7348 (if (org-mhe-get-message-real-folder)
7349 (mh-show-msg 1)
7350 (kill-this-buffer)
7351 (error "Message not found"))))
7352
7353 (defun org-open-file (path &optional in-emacs line search)
7354 "Open the file at PATH.
7355 First, this expands any special file name abbreviations. Then the
7356 configuration variable `org-file-apps' is checked if it contains an
7357 entry for this file type, and if yes, the corresponding command is launched.
7358 If no application is found, Emacs simply visits the file.
7359 With optional argument IN-EMACS, Emacs will visit the file.
7360 Optional LINE specifies a line to go to, optional SEARCH a string to
7361 search for. If LINE or SEARCH is given, the file will always be
7362 opened in Emacs.
7363 If the file does not exist, an error is thrown."
7364 (setq in-emacs (or in-emacs line search))
7365 (let* ((file (if (equal path "")
7366 buffer-file-name
7367 (convert-standard-filename (org-expand-file-name path))))
7368 (dirp (file-directory-p file))
7369 (dfile (downcase file))
7370 (old-buffer (current-buffer))
7371 (old-pos (point))
7372 (old-mode major-mode)
7373 ext cmd apps)
7374 (if (and (not (file-exists-p file))
7375 (not org-open-non-existing-files))
7376 (error "No such file: %s" file))
7377 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7378 (setq ext (match-string 1 dfile))
7379 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7380 (setq ext (match-string 1 dfile))))
7381 (setq apps (append org-file-apps (org-default-apps)))
7382 (if in-emacs
7383 (setq cmd 'emacs)
7384 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7385 (cdr (assoc ext apps))
7386 (cdr (assoc t apps)))))
7387 (when (eq cmd 'mailcap)
7388 (require 'mailcap)
7389 (mailcap-parse-mailcaps)
7390 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7391 (command (mailcap-mime-info mime-type)))
7392 (if (stringp command)
7393 (setq cmd command)
7394 (setq cmd 'emacs))))
7395 (cond
7396 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7397 (setq cmd (format cmd (concat "\"" file "\"")))
7398 (save-window-excursion
7399 (shell-command (concat cmd " &"))))
7400 ((or (stringp cmd)
7401 (eq cmd 'emacs))
7402 (unless (equal (file-truename file) (file-truename buffer-file-name))
7403 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7404 (if line (goto-line line)
7405 (if search (org-link-search search))))
7406 ((consp cmd)
7407 (eval cmd))
7408 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7409 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7410 (or (not (equal old-buffer (current-buffer)))
7411 (not (equal old-pos (point))))
7412 (org-mark-ring-push old-pos old-buffer))))
7413
7414 (defun org-default-apps ()
7415 "Return the default applications for this operating system."
7416 (cond
7417 ((eq system-type 'darwin)
7418 org-file-apps-defaults-macosx)
7419 ((eq system-type 'windows-nt)
7420 org-file-apps-defaults-windowsnt)
7421 (t org-file-apps-defaults-gnu)))
7422
7423 (defun org-expand-file-name (path)
7424 "Replace special path abbreviations and expand the file name."
7425 (expand-file-name path))
7426
7427
7428 (defvar org-insert-link-history nil
7429 "Minibuffer history for links inserted with `org-insert-link'.")
7430
7431 (defvar org-stored-links nil
7432 "Contains the links stored with `org-store-link'.")
7433
7434 ;;;###autoload
7435 (defun org-store-link (arg)
7436 "\\<org-mode-map>Store an org-link to the current location.
7437 This link can later be inserted into an org-buffer with
7438 \\[org-insert-link].
7439 For some link types, a prefix arg is interpreted:
7440 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7441 For file links, arg negates `org-context-in-file-links'."
7442 (interactive "P")
7443 (let (link cpltxt txt (pos (point)))
7444 (cond
7445
7446 ((eq major-mode 'bbdb-mode)
7447 (setq cpltxt (concat
7448 "bbdb:"
7449 (or (bbdb-record-name (bbdb-current-record))
7450 (bbdb-record-company (bbdb-current-record))))
7451 link (org-make-link cpltxt)))
7452
7453 ((eq major-mode 'calendar-mode)
7454 (let ((cd (calendar-cursor-to-date)))
7455 (setq link
7456 (format-time-string
7457 (car org-time-stamp-formats)
7458 (apply 'encode-time
7459 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7460 nil nil nil))))))
7461
7462 ((or (eq major-mode 'vm-summary-mode)
7463 (eq major-mode 'vm-presentation-mode))
7464 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7465 (vm-follow-summary-cursor)
7466 (save-excursion
7467 (vm-select-folder-buffer)
7468 (let* ((message (car vm-message-pointer))
7469 (folder buffer-file-name)
7470 (subject (vm-su-subject message))
7471 (author (vm-su-full-name message))
7472 (message-id (vm-su-message-id message)))
7473 (setq message-id (org-remove-angle-brackets message-id))
7474 (setq folder (abbreviate-file-name folder))
7475 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7476 folder)
7477 (setq folder (replace-match "" t t folder)))
7478 (setq cpltxt (concat author " on: " subject))
7479 (setq link (concat cpltxt "\n "
7480 (org-make-link
7481 "vm:" folder "#" message-id))))))
7482
7483 ((eq major-mode 'wl-summary-mode)
7484 (let* ((msgnum (wl-summary-message-number))
7485 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7486 msgnum 'message-id))
7487 (wl-message-entity (elmo-msgdb-overview-get-entity
7488 msgnum (wl-summary-buffer-msgdb)))
7489 (author (wl-summary-line-from)) ; FIXME: how to get author name?
7490 (subject "???")) ; FIXME: How to get subject of email?
7491 (setq message-id (org-remove-angle-brackets message-id))
7492 (setq cpltxt (concat author " on: " subject))
7493 (setq link (concat cpltxt "\n "
7494 (org-make-link
7495 "wl:" wl-summary-buffer-folder-name
7496 "#" message-id)))))
7497
7498 ((or (equal major-mode 'mh-folder-mode)
7499 (equal major-mode 'mh-show-mode))
7500 (let ((from-header (org-mhe-get-header "From:"))
7501 (to-header (org-mhe-get-header "To:"))
7502 (subject (org-mhe-get-header "Subject:")))
7503 (setq cpltxt (concat from-header " on: " subject))
7504 (setq link (concat cpltxt "\n "
7505 (org-make-link
7506 "mhe:" (org-mhe-get-message-real-folder) "#"
7507 (org-remove-angle-brackets
7508 (org-mhe-get-header "Message-Id:")))))))
7509
7510 ((eq major-mode 'rmail-mode)
7511 (save-excursion
7512 (save-restriction
7513 (rmail-narrow-to-non-pruned-header)
7514 (let ((folder buffer-file-name)
7515 (message-id (mail-fetch-field "message-id"))
7516 (author (mail-fetch-field "from"))
7517 (subject (mail-fetch-field "subject")))
7518 (setq message-id (org-remove-angle-brackets message-id))
7519 (setq cpltxt (concat author " on: " subject))
7520 (setq link (concat cpltxt "\n "
7521 (org-make-link
7522 "rmail:" folder "#" message-id)))))))
7523
7524 ((eq major-mode 'gnus-group-mode)
7525 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7526 (gnus-group-group-name)) ; version
7527 ((fboundp 'gnus-group-name)
7528 (gnus-group-name))
7529 (t "???"))))
7530 (setq cpltxt (concat
7531 (if (org-xor arg org-usenet-links-prefer-google)
7532 "http://groups.google.com/groups?group="
7533 "gnus:")
7534 group)
7535 link (org-make-link cpltxt))))
7536
7537 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7538 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7539 (gnus-summary-beginning-of-article)
7540 (let* ((group (car gnus-article-current))
7541 (article (cdr gnus-article-current))
7542 (header (gnus-summary-article-header article))
7543 (author (mail-header-from header))
7544 (message-id (mail-header-id header))
7545 (date (mail-header-date header))
7546 (subject (gnus-summary-subject-string)))
7547 (setq cpltxt (concat author " on: " subject))
7548 (if (org-xor arg org-usenet-links-prefer-google)
7549 (setq link
7550 (concat
7551 cpltxt "\n "
7552 (format "http://groups.google.com/groups?as_umsgid=%s"
7553 (org-fixup-message-id-for-http message-id))))
7554 (setq link (concat cpltxt "\n"
7555 (org-make-link
7556 "gnus:" group
7557 "#" (number-to-string article)))))))
7558
7559 ((eq major-mode 'w3-mode)
7560 (setq cpltxt (url-view-url t)
7561 link (org-make-link cpltxt)))
7562 ((eq major-mode 'w3m-mode)
7563 (setq cpltxt w3m-current-url
7564 link (org-make-link cpltxt)))
7565
7566 ((eq major-mode 'org-mode)
7567 ;; Just link to current headline
7568 (setq cpltxt (concat "file:"
7569 (abbreviate-file-name buffer-file-name)))
7570 ;; Add a context search string
7571 (when (org-xor org-context-in-file-links arg)
7572 ;; Check if we are on a target
7573 (if (save-excursion
7574 (skip-chars-forward "^>\n\r")
7575 (and (re-search-backward "<<" nil t)
7576 (looking-at "<<\\(.*?\\)>>")
7577 (<= (match-beginning 0) pos)
7578 (>= (match-end 0) pos)))
7579 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7580 (setq txt (cond
7581 ((org-on-heading-p) nil)
7582 ((org-region-active-p)
7583 (buffer-substring (region-beginning) (region-end)))
7584 (t (buffer-substring (point-at-bol) (point-at-eol)))))
7585 (setq cpltxt
7586 (concat cpltxt "::"
7587 (if org-file-link-context-use-camel-case
7588 (org-make-org-heading-camel txt)
7589 (org-make-org-heading-search-string txt))))))
7590 (if (string-match "::\\'" cpltxt)
7591 (setq cpltxt (substring cpltxt 0 -2)))
7592 (setq link (org-make-link cpltxt)))
7593
7594 (buffer-file-name
7595 ;; Just link to this file here.
7596 (setq cpltxt (concat "file:"
7597 (abbreviate-file-name buffer-file-name)))
7598 ;; Add a context string
7599 (when (org-xor org-context-in-file-links arg)
7600 (setq txt (if (org-region-active-p)
7601 (buffer-substring (region-beginning) (region-end))
7602 (buffer-substring (point-at-bol) (point-at-eol))))
7603 (setq cpltxt
7604 (concat cpltxt "::"
7605 (if org-file-link-context-use-camel-case
7606 (org-make-org-heading-camel txt)
7607 (org-make-org-heading-search-string txt)))))
7608 (setq link (org-make-link cpltxt)))
7609
7610 ((interactive-p)
7611 (error "Cannot link to a buffer which is not visiting a file"))
7612
7613 (t (setq link nil)))
7614
7615 (if (and (interactive-p) link)
7616 (progn
7617 (setq org-stored-links
7618 (cons (cons (or cpltxt link) link) org-stored-links))
7619 (message "Stored: %s" (or cpltxt link)))
7620 link)))
7621
7622 (defun org-make-org-heading-search-string (&optional string heading)
7623 "Make search string for STRING or current headline."
7624 (interactive)
7625 (let ((s (or string (org-get-heading))))
7626 (unless (and string (not heading))
7627 ;; We are using a headline, clean up garbage in there.
7628 (if (string-match org-todo-regexp s)
7629 (setq s (replace-match "" t t s)))
7630 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7631 (setq s (replace-match "" t t s)))
7632 (setq s (org-trim s))
7633 (if (string-match (concat "^\\(" org-quote-string "\\|"
7634 org-comment-string "\\)") s)
7635 (setq s (replace-match "" t t s)))
7636 (while (string-match org-ts-regexp s)
7637 (setq s (replace-match "" t t s))))
7638 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7639 (setq s (replace-match " " t t s)))
7640 (or string (setq s (concat "*" s))) ; Add * for headlines
7641 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7642
7643 (defun org-make-org-heading-camel (&optional string heading)
7644 "Make a CamelCase string for STRING or the current headline."
7645 (interactive)
7646 (let ((s (or string (org-get-heading))))
7647 (unless (and string (not heading))
7648 ;; We are using a headline, clean up garbage in there.
7649 (if (string-match org-todo-regexp s)
7650 (setq s (replace-match "" t t s)))
7651 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7652 (setq s (replace-match "" t t s)))
7653 (setq s (org-trim s))
7654 (if (string-match (concat "^\\(" org-quote-string "\\|"
7655 org-comment-string "\\)") s)
7656 (setq s (replace-match "" t t s)))
7657 (while (string-match org-ts-regexp s)
7658 (setq s (replace-match "" t t s))))
7659 (while (string-match "[^a-zA-Z_ \t]+" s)
7660 (setq s (replace-match " " t t s)))
7661 (or string (setq s (concat "*" s))) ; Add * for headlines
7662 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7663
7664 (defun org-make-link (&rest strings)
7665 "Concatenate STRINGS, format resulting string with `org-link-format'."
7666 (format org-link-format (apply 'concat strings)))
7667
7668 (defun org-make-link2 (link &optional description)
7669 "Make a link with brackets."
7670 (concat "[[" link "]"
7671 (if description (concat "[" description "]") "")
7672 "]"))
7673
7674 (defun org-xor (a b)
7675 "Exclusive or."
7676 (if a (not b) b))
7677
7678 (defun org-get-header (header)
7679 "Find a header field in the current buffer."
7680 (save-excursion
7681 (goto-char (point-min))
7682 (let ((case-fold-search t) s)
7683 (cond
7684 ((eq header 'from)
7685 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7686 (setq s (match-string 1)))
7687 (while (string-match "\"" s)
7688 (setq s (replace-match "" t t s)))
7689 (if (string-match "[<(].*" s)
7690 (setq s (replace-match "" t t s))))
7691 ((eq header 'message-id)
7692 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7693 (setq s (match-string 1))))
7694 ((eq header 'subject)
7695 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7696 (setq s (match-string 1)))))
7697 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7698 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7699 s)))
7700
7701
7702 (defun org-fixup-message-id-for-http (s)
7703 "Replace special characters in a message id, so it can be used in an http query."
7704 (while (string-match "<" s)
7705 (setq s (replace-match "%3C" t t s)))
7706 (while (string-match ">" s)
7707 (setq s (replace-match "%3E" t t s)))
7708 (while (string-match "@" s)
7709 (setq s (replace-match "%40" t t s)))
7710 s)
7711
7712 (defun org-insert-link (&optional complete-file)
7713 "Insert a link. At the prompt, enter the link.
7714
7715 Completion can be used to select a link previously stored with
7716 `org-store-link'. When the empty string is entered (i.e. if you just
7717 press RET at the prompt), the link defaults to the most recently
7718 stored link. As SPC triggers completion in the minibuffer, you need to
7719 use M-SPC or C-q SPC to force the insertion of a space character.
7720
7721 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7722 selected using completion. The path to the file will be relative to
7723 the current directory if the file is in the current directory or a
7724 subdirectory. Otherwise, the link will be the absolute path as
7725 completed in the minibuffer (i.e. normally ~/path/to/file).
7726
7727 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7728 is in the current directory or below."
7729 (interactive "P")
7730 (let ((link (if complete-file
7731 (read-file-name "File: ")
7732 (completing-read
7733 "Link: " org-stored-links nil nil nil
7734 org-insert-link-history
7735 (or (car (car org-stored-links))))))
7736 linktxt matched)
7737 (if (or (not link) (equal link ""))
7738 (error "No links available"))
7739 (if complete-file
7740 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7741 (cond
7742 ((equal complete-file '(16))
7743 (insert
7744 (org-make-link
7745 "file:" (abbreviate-file-name (expand-file-name link)))))
7746 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7747 (expand-file-name link))
7748 (insert
7749 (org-make-link
7750 "file:" (match-string 1 (expand-file-name link)))))
7751 (t (insert (org-make-link "file:" link)))))
7752 (setq linktxt (cdr (assoc link org-stored-links)))
7753 (if (not org-keep-stored-link-after-insertion)
7754 (setq org-stored-links (delq (assoc link org-stored-links)
7755 org-stored-links)))
7756 (if (not linktxt) (setq link (org-make-link link)))
7757 (setq link (or linktxt link))
7758 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7759 (let* ((path (match-string 1 link))
7760 (case-fold-search nil)
7761 (search (match-string 2 link)))
7762 (when (save-match-data
7763 (equal (file-truename buffer-file-name)
7764 (file-truename path)))
7765 ;; We are linking to this same file
7766 (if (and org-file-link-context-use-camel-case
7767 (save-match-data
7768 (string-match (concat "^" org-camel-regexp "$") search)))
7769 (setq link (replace-match search t t link)
7770 matched t)
7771 (setq link (replace-match (concat "[[" search "]]")
7772 t t link)
7773 matched t)))))
7774 (let ((lines (org-split-string link "\n")))
7775 (insert (car lines))
7776 (setq matched (or matched (string-match org-link-regexp (car lines))))
7777 (setq lines (cdr lines))
7778 (while lines
7779 (insert "\n")
7780 (if (save-excursion
7781 (beginning-of-line 0)
7782 (looking-at "[ \t]+\\S-"))
7783 (indent-relative))
7784 (setq matched (or matched
7785 (string-match org-link-regexp (car lines))))
7786 (insert (car lines))
7787 (setq lines (cdr lines))))
7788 (unless matched
7789 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7790
7791 ;;; Hooks for remember.el
7792 ;;;###autoload
7793 (defun org-remember-annotation ()
7794 "Return a link to the current location as an annotation for remember.el.
7795 If you are using Org-mode files as target for data storage with
7796 remember.el, then the annotations should include a link compatible with the
7797 conventions in Org-mode. This function returns such a link."
7798 (org-store-link nil))
7799
7800 (defconst org-remember-help
7801 "Select a destination location for the note.
7802 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7803 RET at beg-of-buf -> Append to file as level 2 headline
7804 RET on headline -> Store as sublevel entry to current headline
7805 <left>/<right> -> before/after current headline, same headings level")
7806
7807 ;;;###autoload
7808 (defun org-remember-handler ()
7809 "Store stuff from remember.el into an org file.
7810 First prompts for an org file. If the user just presses return, the value
7811 of `org-default-notes-file' is used.
7812 Then the command offers the headings tree of the selected file in order to
7813 file the text at a specific location.
7814 You can either immediately press RET to get the note appended to the
7815 file, or you can use vertical cursor motion and visibility cycling (TAB) to
7816 find a better place. Then press RET or <left> or <right> in insert the note.
7817
7818 Key Cursor position Note gets inserted
7819 -----------------------------------------------------------------------------
7820 RET buffer-start as level 2 heading at end of file
7821 RET on headline as sublevel of the heading at cursor
7822 RET no heading at cursor position, level taken from context.
7823 Or use prefix arg to specify level manually.
7824 <left> on headline as same level, before current heading
7825 <right> on headline as same level, after current heading
7826
7827 So the fastest way to store the note is to press RET RET to append it to
7828 the default file. This way your current train of thought is not
7829 interrupted, in accordance with the principles of remember.el. But with
7830 little extra effort, you can push it directly to the correct location.
7831
7832 Before being stored away, the function ensures that the text has a
7833 headline, i.e. a first line that starts with a \"*\". If not, a headline
7834 is constructed from the current date and some additional data.
7835
7836 If the variable `org-adapt-indentation' is non-nil, the entire text is
7837 also indented so that it starts in the same column as the headline
7838 \(i.e. after the stars).
7839
7840 See also the variable `org-reverse-note-order'."
7841 (catch 'quit
7842 (let* ((txt (buffer-substring (point-min) (point-max)))
7843 (fastp current-prefix-arg)
7844 (file (if fastp org-default-notes-file (org-get-org-file)))
7845 (visiting (find-buffer-visiting file))
7846 (org-startup-with-deadline-check nil)
7847 (org-startup-folded nil)
7848 spos level indent reversed)
7849 ;; Modify text so that it becomes a nice subtree which can be inserted
7850 ;; into an org tree.
7851 (let* ((lines (split-string txt "\n"))
7852 (first (car lines))
7853 (lines (cdr lines)))
7854 (if (string-match "^\\*+" first)
7855 ;; Is already a headline
7856 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7857 -1) ?\ ))
7858 ;; We need to add a headline: Use time and first buffer line
7859 (setq lines (cons first lines)
7860 first (concat "* " (current-time-string)
7861 " (" (remember-buffer-desc) ")")
7862 indent " "))
7863 (if org-adapt-indentation
7864 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7865 (setq txt (concat first "\n"
7866 (mapconcat 'identity lines "\n"))))
7867 ;; Find the file
7868 (if (not visiting)
7869 (find-file-noselect file))
7870 (with-current-buffer (get-file-buffer file)
7871 (setq reversed (org-notes-order-reversed-p))
7872 (save-excursion
7873 (save-restriction
7874 (widen)
7875 ;; Ask the User for a location
7876 (setq spos (if fastp 1 (org-get-location
7877 (current-buffer)
7878 org-remember-help)))
7879 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7880 ; not handle this note
7881 (goto-char spos)
7882 (cond ((bobp)
7883 ;; Put it at the start or end, as level 2
7884 (save-restriction
7885 (widen)
7886 (goto-char (if reversed (point-min) (point-max)))
7887 (if (not (bolp)) (newline))
7888 (org-paste-subtree (or current-prefix-arg 2) txt)))
7889 ((and (org-on-heading-p nil) (not current-prefix-arg))
7890 ;; Put it below this entry, at the beg/end of the subtree
7891 (org-back-to-heading)
7892 (setq level (funcall outline-level))
7893 (if reversed
7894 (outline-end-of-heading)
7895 (outline-end-of-subtree))
7896 (if (not (bolp)) (newline))
7897 (beginning-of-line 1)
7898 (org-paste-subtree (1+ level) txt))
7899 (t
7900 ;; Put it right there, with automatic level determined by
7901 ;; org-paste-subtree or from prefix arg
7902 (org-paste-subtree current-prefix-arg txt)))
7903 (when remember-save-after-remembering
7904 (save-buffer)
7905 (if (not visiting) (kill-buffer (current-buffer)))))))))
7906 t) ;; return t to indicate that we took care of this note.
7907
7908 (defun org-get-org-file ()
7909 "Read a filename, with default directory `org-directory'."
7910 (let ((default (or org-default-notes-file remember-data-file)))
7911 (read-file-name (format "File name [%s]: " default)
7912 (file-name-as-directory org-directory)
7913 default)))
7914
7915 (defun org-notes-order-reversed-p ()
7916 "Check if the current file should receive notes in reversed order."
7917 (cond
7918 ((not org-reverse-note-order) nil)
7919 ((eq t org-reverse-note-order) t)
7920 ((not (listp org-reverse-note-order)) nil)
7921 (t (catch 'exit
7922 (let ((all org-reverse-note-order)
7923 entry)
7924 (while (setq entry (pop all))
7925 (if (string-match (car entry) buffer-file-name)
7926 (throw 'exit (cdr entry))))
7927 nil)))))
7928
7929 ;;; Tables
7930
7931 ;; Watch out: Here we are talking about two different kind of tables.
7932 ;; Most of the code is for the tables created with the Org-mode table editor.
7933 ;; Sometimes, we talk about tables created and edited with the table.el
7934 ;; Emacs package. We call the former org-type tables, and the latter
7935 ;; table.el-type tables.
7936
7937
7938 (defun org-before-change-function (beg end)
7939 "Every change indicates that a table might need an update."
7940 (setq org-table-may-need-update t))
7941
7942 (defconst org-table-line-regexp "^[ \t]*|"
7943 "Detects an org-type table line.")
7944 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7945 "Detects an org-type table line.")
7946 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7947 "Detects a table line marked for automatic recalculation.")
7948 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7949 "Detects a table line marked for automatic recalculation.")
7950 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7951 "Detects a table line marked for automatic recalculation.")
7952 (defconst org-table-hline-regexp "^[ \t]*|-"
7953 "Detects an org-type table hline.")
7954 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7955 "Detects a table-type table hline.")
7956 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7957 "Detects an org-type or table-type table.")
7958 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7959 "Searching from within a table (any type) this finds the first line
7960 outside the table.")
7961 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7962 "Searching from within a table (any type) this finds the first line
7963 outside the table.")
7964
7965 (defun org-table-create-with-table.el ()
7966 "Use the table.el package to insert a new table.
7967 If there is already a table at point, convert between Org-mode tables
7968 and table.el tables."
7969 (interactive)
7970 (require 'table)
7971 (cond
7972 ((org-at-table.el-p)
7973 (if (y-or-n-p "Convert table to Org-mode table? ")
7974 (org-table-convert)))
7975 ((org-at-table-p)
7976 (if (y-or-n-p "Convert table to table.el table? ")
7977 (org-table-convert)))
7978 (t (call-interactively 'table-insert))))
7979
7980 (defun org-table-create (&optional size)
7981 "Query for a size and insert a table skeleton.
7982 SIZE is a string Columns x Rows like for example \"3x2\"."
7983 (interactive "P")
7984 (unless size
7985 (setq size (read-string
7986 (concat "Table size Columns x Rows [e.g. "
7987 org-table-default-size "]: ")
7988 "" nil org-table-default-size)))
7989
7990 (let* ((pos (point))
7991 (indent (make-string (current-column) ?\ ))
7992 (split (org-split-string size " *x *"))
7993 (rows (string-to-number (nth 1 split)))
7994 (columns (string-to-number (car split)))
7995 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7996 "\n")))
7997 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7998 (point-at-bol) (point)))
7999 (beginning-of-line 1)
8000 (newline))
8001 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8002 (dotimes (i rows) (insert line))
8003 (goto-char pos)
8004 (if (> rows 1)
8005 ;; Insert a hline after the first row.
8006 (progn
8007 (end-of-line 1)
8008 (insert "\n|-")
8009 (goto-char pos)))
8010 (org-table-align)))
8011
8012 (defun org-table-convert-region (beg0 end0 nspace)
8013 "Convert region to a table.
8014 The region goes from BEG0 to END0, but these borders will be moved
8015 slightly, to make sure a beginning of line in the first line is included.
8016 When NSPACE is non-nil, it indicates the minimum number of spaces that
8017 separate columns (default: just one space)."
8018 (let* ((beg (min beg0 end0))
8019 (end (max beg0 end0))
8020 (tabsep t)
8021 re)
8022 (goto-char beg)
8023 (beginning-of-line 1)
8024 (setq beg (move-marker (make-marker) (point)))
8025 (goto-char end)
8026 (if (bolp) (backward-char 1) (end-of-line 1))
8027 (setq end (move-marker (make-marker) (point)))
8028 ;; Lets see if this is tab-separated material. If every nonempty line
8029 ;; contains a tab, we will assume that it is tab-separated material
8030 (if nspace
8031 (setq tabsep nil)
8032 (goto-char beg)
8033 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
8034 (if nspace (setq tabsep nil))
8035 (if tabsep
8036 (setq re "^\\|\t")
8037 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
8038 (max 1 (prefix-numeric-value nspace)))))
8039 (goto-char beg)
8040 (while (re-search-forward re end t)
8041 (replace-match "|" t t))
8042 (goto-char beg)
8043 (insert " ")
8044 (org-table-align)))
8045
8046 (defun org-table-import (file arg)
8047 "Import FILE as a table.
8048 The file is assumed to be tab-separated. Such files can be produced by most
8049 spreadsheet and database applications. If no tabs (at least one per line)
8050 are found, lines will be split on whitespace into fields."
8051 (interactive "f\nP")
8052 (or (bolp) (newline))
8053 (let ((beg (point))
8054 (pm (point-max)))
8055 (insert-file-contents file)
8056 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8057
8058 (defun org-table-export ()
8059 "Export table as a tab-separated file.
8060 Such a file can be imported into a spreadsheet program like Excel."
8061 (interactive)
8062 (let* ((beg (org-table-begin))
8063 (end (org-table-end))
8064 (table (buffer-substring beg end))
8065 (file (read-file-name "Export table to: "))
8066 buf)
8067 (unless (or (not (file-exists-p file))
8068 (y-or-n-p (format "Overwrite file %s? " file)))
8069 (error "Abort"))
8070 (with-current-buffer (find-file-noselect file)
8071 (setq buf (current-buffer))
8072 (erase-buffer)
8073 (fundamental-mode)
8074 (insert table)
8075 (goto-char (point-min))
8076 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8077 (replace-match "" t t)
8078 (end-of-line 1))
8079 (goto-char (point-min))
8080 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8081 (replace-match "" t t)
8082 (goto-char (min (1+ (point)) (point-max))))
8083 (goto-char (point-min))
8084 (while (re-search-forward "^-[-+]*$" nil t)
8085 (replace-match "")
8086 (if (looking-at "\n")
8087 (delete-char 1)))
8088 (goto-char (point-min))
8089 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8090 (replace-match "\t" t t))
8091 (save-buffer))
8092 (kill-buffer buf)))
8093
8094 (defvar org-table-aligned-begin-marker (make-marker)
8095 "Marker at the beginning of the table last aligned.
8096 Used to check if cursor still is in that table, to minimize realignment.")
8097 (defvar org-table-aligned-end-marker (make-marker)
8098 "Marker at the end of the table last aligned.
8099 Used to check if cursor still is in that table, to minimize realignment.")
8100 (defvar org-table-last-alignment nil
8101 "List of flags for flushright alignment, from the last re-alignment.
8102 This is being used to correctly align a single field after TAB or RET.")
8103 ;; FIXME: The following is currently not used.
8104 (defvar org-table-last-column-widths nil
8105 "List of max width of fields in each column.
8106 This is being used to correctly align a single field after TAB or RET.")
8107
8108 (defvar org-last-recalc-line nil)
8109
8110 (defun org-table-align ()
8111 "Align the table at point by aligning all vertical bars."
8112 (interactive)
8113 ;; (message "align") (sit-for 2)
8114 (let* (
8115 ;; Limits of table
8116 (beg (org-table-begin))
8117 (end (org-table-end))
8118 ;; Current cursor position
8119 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8120 (colpos (org-table-current-column))
8121 (winstart (window-start))
8122 text lines (new "") lengths l typenums ty fields maxfields i
8123 column
8124 (indent "") cnt frac
8125 rfmt hfmt
8126 (spaces (if (org-in-invisibility-spec-p '(org-table))
8127 org-table-spaces-around-invisible-separators
8128 org-table-spaces-around-separators))
8129 (sp1 (car spaces))
8130 (sp2 (cdr spaces))
8131 (rfmt1 (concat
8132 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8133 (hfmt1 (concat
8134 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8135 emptystrings)
8136 (untabify beg end)
8137 ;; (message "Aligning table...")
8138 ;; Get the rows
8139 (setq lines (org-split-string
8140 (buffer-substring-no-properties beg end) "\n"))
8141 ;; Store the indentation of the first line
8142 (if (string-match "^ *" (car lines))
8143 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8144 ;; Mark the hlines
8145 (setq lines (mapcar (lambda (l)
8146 (if (string-match "^ *|-" l)
8147 nil
8148 (if (string-match "[ \t]+$" l)
8149 (substring l 0 (match-beginning 0))
8150 l)))
8151 lines))
8152 ;; Get the data fields
8153 (setq fields (mapcar
8154 (lambda (l)
8155 (org-split-string l " *| *"))
8156 (delq nil (copy-sequence lines))))
8157 ;; How many fields in the longest line?
8158 (condition-case nil
8159 (setq maxfields (apply 'max (mapcar 'length fields)))
8160 (error
8161 (kill-region beg end)
8162 (org-table-create org-table-default-size)
8163 (error "Empty table - created default table")))
8164 ;; A list of empty string to fill any short rows on output
8165 (setq emptystrings (make-list maxfields ""))
8166 ;; Get the maximum length of a field and the most common datatype
8167 ;; for each column
8168 (setq i -1)
8169 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8170 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8171 ;; maximum length
8172 (push (apply 'max 1 (mapcar 'string-width column)) lengths)
8173 ;; compute the fraction stepwise, ignoring empty fields
8174 (setq cnt 0 frac 0.0)
8175 (mapcar
8176 (lambda (x)
8177 (if (equal x "")
8178 nil
8179 (setq frac ( / (+ (* frac cnt)
8180 (if (string-match org-table-number-regexp x) 1 0))
8181 (setq cnt (1+ cnt))))))
8182 column)
8183 (push (>= frac org-table-number-fraction) typenums))
8184 (setq lengths (nreverse lengths)
8185 typenums (nreverse typenums))
8186 (setq org-table-last-alignment typenums
8187 org-table-last-column-widths lengths)
8188 ;; Compute the formats needed for output of the table
8189 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8190 (while (setq l (pop lengths))
8191 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8192 (setq rfmt (concat rfmt (format rfmt1 ty l))
8193 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8194 (setq rfmt (concat rfmt "\n")
8195 hfmt (concat (substring hfmt 0 -1) "|\n"))
8196 ;; Produce the new table
8197 ;;(while lines
8198 ;; (setq l (pop lines))
8199 ;; (if l
8200 ;; (setq new (concat new (apply 'format rfmt
8201 ;; (append (pop fields) emptystrings))))
8202 ;; (setq new (concat new hfmt))))
8203 (setq new (mapconcat
8204 (lambda (l)
8205 (if l (apply 'format rfmt
8206 (append (pop fields) emptystrings))
8207 hfmt))
8208 lines ""))
8209 ;; Replace the old one
8210 (delete-region beg end)
8211 (move-marker end nil)
8212 (move-marker org-table-aligned-begin-marker (point))
8213 (insert new)
8214 (move-marker org-table-aligned-end-marker (point))
8215 ;; Try to move to the old location (approximately)
8216 (goto-line linepos)
8217 (set-window-start (selected-window) winstart 'noforce)
8218 (org-table-goto-column colpos)
8219 (setq org-table-may-need-update nil)
8220 (if (org-in-invisibility-spec-p '(org-table))
8221 (org-table-add-invisible-to-vertical-lines))
8222 ))
8223
8224 (defun org-table-begin (&optional table-type)
8225 "Find the beginning of the table and return its position.
8226 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8227 (save-excursion
8228 (if (not (re-search-backward
8229 (if table-type org-table-any-border-regexp
8230 org-table-border-regexp)
8231 nil t))
8232 (error "Can't find beginning of table")
8233 (goto-char (match-beginning 0))
8234 (beginning-of-line 2)
8235 (point))))
8236
8237 (defun org-table-end (&optional table-type)
8238 "Find the end of the table and return its position.
8239 With argument TABLE-TYPE, go to the end of a table.el-type table."
8240 (save-excursion
8241 (if (not (re-search-forward
8242 (if table-type org-table-any-border-regexp
8243 org-table-border-regexp)
8244 nil t))
8245 (goto-char (point-max))
8246 (goto-char (match-beginning 0)))
8247 (point-marker)))
8248
8249 (defun org-table-justify-field-maybe (&optional new)
8250 "Justify the current field, text to left, number to right.
8251 Optional argument NEW may specify text to replace the current field content."
8252 (cond
8253 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8254 ((org-at-table-hline-p)
8255 ;; FIXME: I used to enforce realign here, but I think this is not needed.
8256 ;; (setq org-table-may-need-update t)
8257 )
8258 ((and (not new)
8259 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8260 (current-buffer)))
8261 (< (point) org-table-aligned-begin-marker)
8262 (>= (point) org-table-aligned-end-marker)))
8263 ;; This is not the same table, force a full re-align
8264 (setq org-table-may-need-update t))
8265 (t ;; realign the current field, based on previous full realign
8266 (let* ((pos (point)) s
8267 (col (org-table-current-column))
8268 (num (nth (1- col) org-table-last-alignment))
8269 l f n o e)
8270 (when (> col 0)
8271 (skip-chars-backward "^|\n")
8272 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8273 (progn
8274 (setq s (match-string 1)
8275 o (match-string 0)
8276 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8277 e (not (= (match-beginning 2) (match-end 2))))
8278 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8279 l (if e "|" (setq org-table-may-need-update t) ""))
8280 n (format f s t t))
8281 (if new
8282 (if (<= (length new) l)
8283 (setq n (format f new t t)) ;; FIXME: why t t?????
8284 (setq n (concat new "|") org-table-may-need-update t)))
8285 (or (equal n o)
8286 (let (org-table-may-need-update)
8287 (replace-match n))))
8288 (setq org-table-may-need-update t))
8289 (goto-char pos))))))
8290
8291 (defun org-table-next-field ()
8292 "Go to the next field in the current table, creating new lines as needed.
8293 Before doing so, re-align the table if necessary."
8294 (interactive)
8295 (org-table-maybe-eval-formula)
8296 (org-table-maybe-recalculate-line)
8297 (if (and org-table-automatic-realign
8298 org-table-may-need-update)
8299 (org-table-align))
8300 (let ((end (org-table-end)))
8301 (if (org-at-table-hline-p)
8302 (end-of-line 1))
8303 (condition-case nil
8304 (progn
8305 (re-search-forward "|" end)
8306 (if (looking-at "[ \t]*$")
8307 (re-search-forward "|" end))
8308 (if (and (looking-at "-")
8309 org-table-tab-jumps-over-hlines
8310 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8311 (goto-char (match-beginning 1)))
8312 (if (looking-at "-")
8313 (progn
8314 (beginning-of-line 0)
8315 (org-table-insert-row 'below))
8316 (if (looking-at " ") (forward-char 1))))
8317 (error
8318 (org-table-insert-row 'below)))))
8319
8320 (defun org-table-previous-field ()
8321 "Go to the previous field in the table.
8322 Before doing so, re-align the table if necessary."
8323 (interactive)
8324 (org-table-justify-field-maybe)
8325 (org-table-maybe-recalculate-line)
8326 (if (and org-table-automatic-realign
8327 org-table-may-need-update)
8328 (org-table-align))
8329 (if (org-at-table-hline-p)
8330 (end-of-line 1))
8331 (re-search-backward "|" (org-table-begin))
8332 (re-search-backward "|" (org-table-begin))
8333 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8334 (re-search-backward "|" (org-table-begin)))
8335 (if (looking-at "| ?")
8336 (goto-char (match-end 0))))
8337
8338 (defun org-table-next-row ()
8339 "Go to the next row (same column) in the current table.
8340 Before doing so, re-align the table if necessary."
8341 (interactive)
8342 (org-table-maybe-eval-formula)
8343 (org-table-maybe-recalculate-line)
8344 (if (or (looking-at "[ \t]*$")
8345 (save-excursion (skip-chars-backward " \t") (bolp)))
8346 (newline)
8347 (if (and org-table-automatic-realign
8348 org-table-may-need-update)
8349 (org-table-align))
8350 (let ((col (org-table-current-column)))
8351 (beginning-of-line 2)
8352 (if (or (not (org-at-table-p))
8353 (org-at-table-hline-p))
8354 (progn
8355 (beginning-of-line 0)
8356 (org-table-insert-row 'below)))
8357 (org-table-goto-column col)
8358 (skip-chars-backward "^|\n\r")
8359 (if (looking-at " ") (forward-char 1)))))
8360
8361 (defun org-table-copy-down (n)
8362 "Copy a field down in the current column.
8363 If the field at the cursor is empty, copy into it the content of the nearest
8364 non-empty field above. With argument N, use the Nth non-empty field.
8365 If the current field is not empty, it is copied down to the next row, and
8366 the cursor is moved with it. Therefore, repeating this command causes the
8367 column to be filled row-by-row.
8368 If the variable `org-table-copy-increment' is non-nil and the field is an
8369 integer, it will be incremented while copying."
8370 (interactive "p")
8371 (let* ((colpos (org-table-current-column))
8372 (field (org-table-get-field))
8373 (non-empty (string-match "[^ \t]" field))
8374 (beg (org-table-begin))
8375 txt)
8376 (org-table-check-inside-data-field)
8377 (if non-empty
8378 (progn
8379 (setq txt (org-trim field))
8380 (org-table-next-row)
8381 (org-table-blank-field))
8382 (save-excursion
8383 (setq txt
8384 (catch 'exit
8385 (while (progn (beginning-of-line 1)
8386 (re-search-backward org-table-dataline-regexp
8387 beg t))
8388 (org-table-goto-column colpos t)
8389 (if (and (looking-at
8390 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8391 (= (setq n (1- n)) 0))
8392 (throw 'exit (match-string 1))))))))
8393 (if txt
8394 (progn
8395 (if (and org-table-copy-increment
8396 (string-match "^[0-9]+$" txt))
8397 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8398 (insert txt)
8399 (org-table-maybe-recalculate-line)
8400 (org-table-align))
8401 (error "No non-empty field found"))))
8402
8403 (defun org-table-check-inside-data-field ()
8404 "Is point inside a table data field?
8405 I.e. not on a hline or before the first or after the last column?
8406 This actually throws an error, so it aborts the current command."
8407 (if (or (not (org-at-table-p))
8408 (= (org-table-current-column) 0)
8409 (org-at-table-hline-p)
8410 (looking-at "[ \t]*$"))
8411 (error "Not in table data field")))
8412
8413 (defvar org-table-clip nil
8414 "Clipboard for table regions.")
8415
8416 (defun org-table-blank-field ()
8417 "Blank the current table field or active region."
8418 (interactive)
8419 (org-table-check-inside-data-field)
8420 (if (and (interactive-p) (org-region-active-p))
8421 (let (org-table-clip)
8422 (org-table-cut-region (region-beginning) (region-end)))
8423 (skip-chars-backward "^|")
8424 (backward-char 1)
8425 (if (looking-at "|[^|\n]+")
8426 (let* ((pos (match-beginning 0))
8427 (match (match-string 0))
8428 (len (string-width match)))
8429 (replace-match (concat "|" (make-string (1- len) ?\ )))
8430 (goto-char (+ 2 pos))
8431 (substring match 1)))))
8432
8433 (defun org-table-get-field (&optional n replace)
8434 "Return the value of the field in column N of current row.
8435 N defaults to current field.
8436 If REPLACE is a string, replace field with this value. The return value
8437 is always the old value."
8438 (and n (org-table-goto-column n))
8439 (skip-chars-backward "^|\n")
8440 (backward-char 1)
8441 (if (looking-at "|[^|\r\n]*")
8442 (let* ((pos (match-beginning 0))
8443 (val (buffer-substring (1+ pos) (match-end 0))))
8444 (if replace
8445 (replace-match (concat "|" replace)))
8446 (goto-char (min (point-at-eol) (+ 2 pos)))
8447 val)
8448 (forward-char 1) ""))
8449
8450 (defun org-table-current-column ()
8451 "Find out which column we are in.
8452 When called interactively, column is also displayed in echo area."
8453 (interactive)
8454 (if (interactive-p) (org-table-check-inside-data-field))
8455 (save-excursion
8456 (let ((cnt 0) (pos (point)))
8457 (beginning-of-line 1)
8458 (while (search-forward "|" pos t)
8459 (setq cnt (1+ cnt)))
8460 (if (interactive-p) (message "This is table column %d" cnt))
8461 cnt)))
8462
8463 (defun org-table-goto-column (n &optional on-delim force)
8464 "Move the cursor to the Nth column in the current table line.
8465 With optional argument ON-DELIM, stop with point before the left delimiter
8466 of the field.
8467 If there are less than N fields, just go to after the last delimiter.
8468 However, when FORCE is non-nil, create new columns if necessary."
8469 (interactive "p")
8470 (let ((pos (point-at-eol)))
8471 (beginning-of-line 1)
8472 (when (> n 0)
8473 (while (and (> (setq n (1- n)) -1)
8474 (or (search-forward "|" pos t)
8475 (and force
8476 (progn (end-of-line 1)
8477 (skip-chars-backward "^|")
8478 (insert " | "))))))
8479 ; (backward-char 2) t)))))
8480 (when (and force (not (looking-at ".*|")))
8481 (save-excursion (end-of-line 1) (insert " | ")))
8482 (if on-delim
8483 (backward-char 1)
8484 (if (looking-at " ") (forward-char 1))))))
8485
8486 (defun org-at-table-p (&optional table-type)
8487 "Return t if the cursor is inside an org-type table.
8488 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8489 (if org-enable-table-editor
8490 (save-excursion
8491 (beginning-of-line 1)
8492 (looking-at (if table-type org-table-any-line-regexp
8493 org-table-line-regexp)))
8494 nil))
8495
8496 (defun org-at-table.el-p ()
8497 "Return t if and only if we are at a table.el table."
8498 (and (org-at-table-p 'any)
8499 (save-excursion
8500 (goto-char (org-table-begin 'any))
8501 (looking-at org-table1-hline-regexp))))
8502
8503 (defun org-table-recognize-table.el ()
8504 "If there is a table.el table nearby, recognize it and move into it."
8505 (if org-table-tab-recognizes-table.el
8506 (if (org-at-table.el-p)
8507 (progn
8508 (beginning-of-line 1)
8509 (if (looking-at org-table-dataline-regexp)
8510 nil
8511 (if (looking-at org-table1-hline-regexp)
8512 (progn
8513 (beginning-of-line 2)
8514 (if (looking-at org-table-any-border-regexp)
8515 (beginning-of-line -1)))))
8516 (if (re-search-forward "|" (org-table-end t) t)
8517 (progn
8518 (require 'table)
8519 (if (table--at-cell-p (point))
8520 t
8521 (message "recognizing table.el table...")
8522 (table-recognize-table)
8523 (message "recognizing table.el table...done")))
8524 (error "This should not happen..."))
8525 t)
8526 nil)
8527 nil))
8528
8529 (defun org-at-table-hline-p ()
8530 "Return t if the cursor is inside a hline in a table."
8531 (if org-enable-table-editor
8532 (save-excursion
8533 (beginning-of-line 1)
8534 (looking-at org-table-hline-regexp))
8535 nil))
8536
8537 (defun org-table-insert-column ()
8538 "Insert a new column into the table."
8539 (interactive)
8540 (if (not (org-at-table-p))
8541 (error "Not at a table"))
8542 (org-table-find-dataline)
8543 (let* ((col (max 1 (org-table-current-column)))
8544 (beg (org-table-begin))
8545 (end (org-table-end))
8546 ;; Current cursor position
8547 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8548 (colpos col))
8549 (goto-char beg)
8550 (while (< (point) end)
8551 (if (org-at-table-hline-p)
8552 nil
8553 (org-table-goto-column col t)
8554 (insert "| "))
8555 (beginning-of-line 2))
8556 (move-marker end nil)
8557 (goto-line linepos)
8558 (org-table-goto-column colpos)
8559 (org-table-align)
8560 (org-table-modify-formulas 'insert col)))
8561
8562 (defun org-table-find-dataline ()
8563 "Find a dataline in the current table, which is needed for column commands."
8564 (if (and (org-at-table-p)
8565 (not (org-at-table-hline-p)))
8566 t
8567 (let ((col (current-column))
8568 (end (org-table-end)))
8569 (move-to-column col)
8570 (while (and (< (point) end)
8571 (or (not (= (current-column) col))
8572 (org-at-table-hline-p)))
8573 (beginning-of-line 2)
8574 (move-to-column col))
8575 (if (and (org-at-table-p)
8576 (not (org-at-table-hline-p)))
8577 t
8578 (error
8579 "Please position cursor in a data line for column operations")))))
8580
8581 (defun org-table-delete-column ()
8582 "Delete a column into the table."
8583 (interactive)
8584 (if (not (org-at-table-p))
8585 (error "Not at a table"))
8586 (org-table-find-dataline)
8587 (org-table-check-inside-data-field)
8588 (let* ((col (org-table-current-column))
8589 (beg (org-table-begin))
8590 (end (org-table-end))
8591 ;; Current cursor position
8592 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8593 (colpos col))
8594 (goto-char beg)
8595 (while (< (point) end)
8596 (if (org-at-table-hline-p)
8597 nil
8598 (org-table-goto-column col t)
8599 (and (looking-at "|[^|\n]+|")
8600 (replace-match "|")))
8601 (beginning-of-line 2))
8602 (move-marker end nil)
8603 (goto-line linepos)
8604 (org-table-goto-column colpos)
8605 (org-table-align)
8606 (org-table-modify-formulas 'remove col)))
8607
8608 (defun org-table-move-column-right ()
8609 "Move column to the right."
8610 (interactive)
8611 (org-table-move-column nil))
8612 (defun org-table-move-column-left ()
8613 "Move column to the left."
8614 (interactive)
8615 (org-table-move-column 'left))
8616
8617 (defun org-table-move-column (&optional left)
8618 "Move the current column to the right. With arg LEFT, move to the left."
8619 (interactive "P")
8620 (if (not (org-at-table-p))
8621 (error "Not at a table"))
8622 (org-table-find-dataline)
8623 (org-table-check-inside-data-field)
8624 (let* ((col (org-table-current-column))
8625 (col1 (if left (1- col) col))
8626 (beg (org-table-begin))
8627 (end (org-table-end))
8628 ;; Current cursor position
8629 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8630 (colpos (if left (1- col) (1+ col))))
8631 (if (and left (= col 1))
8632 (error "Cannot move column further left"))
8633 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8634 (error "Cannot move column further right"))
8635 (goto-char beg)
8636 (while (< (point) end)
8637 (if (org-at-table-hline-p)
8638 nil
8639 (org-table-goto-column col1 t)
8640 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8641 (replace-match "|\\2|\\1|")))
8642 (beginning-of-line 2))
8643 (move-marker end nil)
8644 (goto-line linepos)
8645 (org-table-goto-column colpos)
8646 (org-table-align)
8647 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8648
8649 (defun org-table-move-row-down ()
8650 "Move table row down."
8651 (interactive)
8652 (org-table-move-row nil))
8653 (defun org-table-move-row-up ()
8654 "Move table row up."
8655 (interactive)
8656 (org-table-move-row 'up))
8657
8658 (defun org-table-move-row (&optional up)
8659 "Move the current table line down. With arg UP, move it up."
8660 (interactive "P")
8661 (let ((col (current-column))
8662 (pos (point))
8663 (tonew (if up 0 2))
8664 txt)
8665 (beginning-of-line tonew)
8666 (if (not (org-at-table-p))
8667 (progn
8668 (goto-char pos)
8669 (error "Cannot move row further")))
8670 (goto-char pos)
8671 (beginning-of-line 1)
8672 (setq pos (point))
8673 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8674 (delete-region (point) (1+ (point-at-eol)))
8675 (beginning-of-line tonew)
8676 (insert txt)
8677 (beginning-of-line 0)
8678 (move-to-column col)))
8679
8680 (defun org-table-insert-row (&optional arg)
8681 "Insert a new row above the current line into the table.
8682 With prefix ARG, insert below the current line."
8683 (interactive "P")
8684 (if (not (org-at-table-p))
8685 (error "Not at a table"))
8686 (let* ((line
8687 (org-expand-wide-chars
8688 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8689 new)
8690 (if (string-match "^[ \t]*|-" line)
8691 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8692 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8693 ;; Fix the first field if necessary
8694 (setq new (concat new))
8695 (if (string-match "^[ \t]*| *[#$] *|" line)
8696 (setq new (replace-match (match-string 0 line) t t new)))
8697 (beginning-of-line (if arg 2 1))
8698 (let (org-table-may-need-update)
8699 (insert-before-markers new)
8700 (insert-before-markers "\n"))
8701 (beginning-of-line 0)
8702 (re-search-forward "| ?" (point-at-eol) t)
8703 (and org-table-may-need-update (org-table-align))))
8704
8705 (defun org-table-insert-hline (&optional arg)
8706 "Insert a horizontal-line below the current line into the table.
8707 With prefix ARG, insert above the current line."
8708 (interactive "P")
8709 (if (not (org-at-table-p))
8710 (error "Not at a table"))
8711 (let ((line
8712 (org-expand-wide-chars
8713 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8714 (col (current-column))
8715 start)
8716 (if (string-match "^[ \t]*|-" line)
8717 (setq line
8718 (mapcar (lambda (x) (if (member x '(?| ?+))
8719 (prog1 (if start ?+ ?|) (setq start t))
8720 (if start ?- ?\ )))
8721 line))
8722 (setq line
8723 (mapcar (lambda (x) (if (equal x ?|)
8724 (prog1 (if start ?+ ?|) (setq start t))
8725 (if start ?- ?\ )))
8726 line)))
8727 (beginning-of-line (if arg 1 2))
8728 (apply 'insert line)
8729 (if (equal (char-before (point)) ?+)
8730 (progn (backward-delete-char 1) (insert "|")))
8731 (insert "\n")
8732 (beginning-of-line (if arg 1 -1))
8733 (move-to-column col)))
8734
8735 (defun org-expand-wide-chars (s)
8736 "Expand wide characters to spaces."
8737 (let (w a)
8738 (mapconcat
8739 (lambda (x)
8740 (if (> (setq w (string-width (setq a (char-to-string x)))) 1)
8741 (make-string w ?\ )
8742 a))
8743 s "")))
8744
8745 (defun org-table-kill-row ()
8746 "Delete the current row or horizontal line from the table."
8747 (interactive)
8748 (if (not (org-at-table-p))
8749 (error "Not at a table"))
8750 (let ((col (current-column)))
8751 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8752 (if (not (org-at-table-p)) (beginning-of-line 0))
8753 (move-to-column col)))
8754
8755 (defun org-table-sort-lines (beg end numericp)
8756 "Sort table lines in region.
8757 Point and mark define the first and last line to include. Both point and
8758 mark should be in the column that is used for sorting. For example, to
8759 sort according to column 3, put the mark in the first line to sort, in
8760 table column 3. Put point into the last line to be included in the sorting,
8761 also in table column 3. The command will prompt for the sorting method
8762 \(n for numerical, a for alphanumeric)."
8763 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8764 (setq numericp (string-match "[nN]" numericp))
8765 (org-table-align) ;; Just to be safe
8766 (let* (bcol ecol cmp column lns)
8767 (goto-char beg)
8768 (org-table-check-inside-data-field)
8769 (setq column (org-table-current-column)
8770 beg (move-marker (make-marker) (point-at-bol)))
8771 (goto-char end)
8772 (org-table-check-inside-data-field)
8773 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8774 (untabify beg end)
8775 (goto-char beg)
8776 (org-table-goto-column column)
8777 (skip-chars-backward "^|")
8778 (setq bcol (current-column))
8779 (org-table-goto-column (1+ column))
8780 (skip-chars-backward "^|")
8781 (setq ecol (1- (current-column)))
8782 (setq cmp (if numericp
8783 (lambda (a b) (< (car a) (car b)))
8784 (lambda (a b) (string< (car a) (car b)))))
8785 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8786 (split-string (buffer-substring beg end) "\n")))
8787 (if numericp
8788 (setq lns (mapcar (lambda(x)
8789 (cons (string-to-number (car x)) (cdr x)))
8790 lns)))
8791 (delete-region beg end)
8792 (move-marker beg nil)
8793 (move-marker end nil)
8794 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8795 (message "%d lines sorted %s based on column %d"
8796 (length lns)
8797 (if numericp "numerically" "alphabetically") column)))
8798
8799 (defun org-table-cut-region (beg end)
8800 "Copy region in table to the clipboard and blank all relevant fields."
8801 (interactive "r")
8802 (org-table-copy-region beg end 'cut))
8803
8804 (defun org-table-copy-region (beg end &optional cut)
8805 "Copy rectangular region in table to clipboard.
8806 A special clipboard is used which can only be accessed
8807 with `org-table-paste-rectangle'."
8808 (interactive "rP")
8809 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8810 region cols
8811 (rpl (if cut " " nil)))
8812 (goto-char beg)
8813 (org-table-check-inside-data-field)
8814 (setq l01 (count-lines (point-min) (point))
8815 c01 (org-table-current-column))
8816 (goto-char end)
8817 (org-table-check-inside-data-field)
8818 (setq l02 (count-lines (point-min) (point))
8819 c02 (org-table-current-column))
8820 (setq l1 (min l01 l02) l2 (max l01 l02)
8821 c1 (min c01 c02) c2 (max c01 c02))
8822 (catch 'exit
8823 (while t
8824 (catch 'nextline
8825 (if (> l1 l2) (throw 'exit t))
8826 (goto-line l1)
8827 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8828 (setq cols nil ic1 c1 ic2 c2)
8829 (while (< ic1 (1+ ic2))
8830 (push (org-table-get-field ic1 rpl) cols)
8831 (setq ic1 (1+ ic1)))
8832 (push (nreverse cols) region)
8833 (setq l1 (1+ l1)))))
8834 (setq org-table-clip (nreverse region))
8835 (if cut (org-table-align))
8836 org-table-clip))
8837
8838 (defun org-table-paste-rectangle ()
8839 "Paste a rectangular region into a table.
8840 The upper right corner ends up in the current field. All involved fields
8841 will be overwritten. If the rectangle does not fit into the present table,
8842 the table is enlarged as needed. The process ignores horizontal separator
8843 lines."
8844 (interactive)
8845 (unless (and org-table-clip (listp org-table-clip))
8846 (error "First cut/copy a region to paste!"))
8847 (org-table-check-inside-data-field)
8848 (let* ((clip org-table-clip)
8849 (line (count-lines (point-min) (point)))
8850 (col (org-table-current-column))
8851 (org-enable-table-editor t)
8852 (org-table-automatic-realign nil)
8853 c cols field)
8854 (while (setq cols (pop clip))
8855 (while (org-at-table-hline-p) (beginning-of-line 2))
8856 (if (not (org-at-table-p))
8857 (progn (end-of-line 0) (org-table-next-field)))
8858 (setq c col)
8859 (while (setq field (pop cols))
8860 (org-table-goto-column c nil 'force)
8861 (org-table-get-field nil field)
8862 (setq c (1+ c)))
8863 (beginning-of-line 2))
8864 (goto-line line)
8865 (org-table-goto-column col)
8866 (org-table-align)))
8867
8868 (defun org-table-convert ()
8869 "Convert from `org-mode' table to table.el and back.
8870 Obviously, this only works within limits. When an Org-mode table is
8871 converted to table.el, all horizontal separator lines get lost, because
8872 table.el uses these as cell boundaries and has no notion of horizontal lines.
8873 A table.el table can be converted to an Org-mode table only if it does not
8874 do row or column spanning. Multiline cells will become multiple cells.
8875 Beware, Org-mode does not test if the table can be successfully converted - it
8876 blindly applies a recipe that works for simple tables."
8877 (interactive)
8878 (require 'table)
8879 (if (org-at-table.el-p)
8880 ;; convert to Org-mode table
8881 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8882 (end (move-marker (make-marker) (org-table-end t))))
8883 (table-unrecognize-region beg end)
8884 (goto-char beg)
8885 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8886 (replace-match ""))
8887 (goto-char beg))
8888 (if (org-at-table-p)
8889 ;; convert to table.el table
8890 (let ((beg (move-marker (make-marker) (org-table-begin)))
8891 (end (move-marker (make-marker) (org-table-end))))
8892 ;; first, get rid of all horizontal lines
8893 (goto-char beg)
8894 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8895 (replace-match ""))
8896 ;; insert a hline before first
8897 (goto-char beg)
8898 (org-table-insert-hline 'above)
8899 (beginning-of-line -1)
8900 ;; insert a hline after each line
8901 (while (progn (beginning-of-line 3) (< (point) end))
8902 (org-table-insert-hline))
8903 (goto-char beg)
8904 (setq end (move-marker end (org-table-end)))
8905 ;; replace "+" at beginning and ending of hlines
8906 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8907 (replace-match "\\1+-"))
8908 (goto-char beg)
8909 (while (re-search-forward "-|[ \t]*$" end t)
8910 (replace-match "-+"))
8911 (goto-char beg)))))
8912
8913 (defun org-table-wrap-region (arg)
8914 "Wrap several fields in a column like a paragraph.
8915 This is useful if you'd like to spread the contents of a field over several
8916 lines, in order to keep the table compact.
8917
8918 If there is an active region, and both point and mark are in the same column,
8919 the text in the column is wrapped to minimum width for the given number of
8920 lines. Generally, this makes the table more compact. A prefix ARG may be
8921 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8922 formats the selected text to two lines. If the region was longer than two
8923 lines, the remaining lines remain empty. A negative prefix argument reduces
8924 the current number of lines by that amount. The wrapped text is pasted back
8925 into the table. If you formatted it to more lines than it was before, fields
8926 further down in the table get overwritten - so you might need to make space in
8927 the table first.
8928
8929 If there is no region, the current field is split at the cursor position and
8930 the text fragment to the right of the cursor is prepended to the field one
8931 line down.
8932
8933 If there is no region, but you specify a prefix ARG, the current field gets
8934 blank, and the content is appended to the field above."
8935 (interactive "P")
8936 (org-table-check-inside-data-field)
8937 (if (org-region-active-p)
8938 ;; There is a region: fill as a paragraph
8939 (let ((beg (region-beginning))
8940 nlines)
8941 (org-table-cut-region (region-beginning) (region-end))
8942 (if (> (length (car org-table-clip)) 1)
8943 (error "Region must be limited to single column"))
8944 (setq nlines (if arg
8945 (if (< arg 1)
8946 (+ (length org-table-clip) arg)
8947 arg)
8948 (length org-table-clip)))
8949 (setq org-table-clip
8950 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8951 nil nlines)))
8952 (goto-char beg)
8953 (org-table-paste-rectangle))
8954 ;; No region, split the current field at point
8955 (if arg
8956 ;; combine with field above
8957 (let ((s (org-table-blank-field))
8958 (col (org-table-current-column)))
8959 (beginning-of-line 0)
8960 (while (org-at-table-hline-p) (beginning-of-line 0))
8961 (org-table-goto-column col)
8962 (skip-chars-forward "^|")
8963 (skip-chars-backward " ")
8964 (insert " " (org-trim s))
8965 (org-table-align))
8966 ;; split field
8967 (when (looking-at "\\([^|]+\\)+|")
8968 (let ((s (match-string 1)))
8969 (replace-match " |")
8970 (goto-char (match-beginning 0))
8971 (org-table-next-row)
8972 (insert (org-trim s) " ")
8973 (org-table-align))))))
8974
8975 (defun org-trim (s)
8976 "Remove whitespace at beginning and end of string."
8977 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8978 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8979 s)
8980
8981 (defun org-wrap (string &optional width lines)
8982 "Wrap string to either a number of lines, or a width in characters.
8983 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8984 that costs. If there is a word longer than WIDTH, the text is actually
8985 wrapped to the length of that word.
8986 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8987 many lines, whatever width that takes.
8988 The return value is a list of lines, without newlines at the end."
8989 (let* ((words (org-split-string string "[ \t\n]+"))
8990 (maxword (apply 'max (mapcar 'string-width words)))
8991 w ll)
8992 (cond (width
8993 (org-do-wrap words (max maxword width)))
8994 (lines
8995 (setq w maxword)
8996 (setq ll (org-do-wrap words maxword))
8997 (if (<= (length ll) lines)
8998 ll
8999 (setq ll words)
9000 (while (> (length ll) lines)
9001 (setq w (1+ w))
9002 (setq ll (org-do-wrap words w)))
9003 ll))
9004 (t (error "Cannot wrap this")))))
9005
9006
9007 (defun org-do-wrap (words width)
9008 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9009 (let (lines line)
9010 (while words
9011 (setq line (pop words))
9012 (while (and words (< (+ (length line) (length (car words))) width))
9013 (setq line (concat line " " (pop words))))
9014 (setq lines (push line lines)))
9015 (nreverse lines)))
9016
9017 ;; FIXME: I think I can make this more efficient
9018 (defun org-split-string (string &optional separators)
9019 "Splits STRING into substrings at SEPARATORS.
9020 No empty strings are returned if there are matches at the beginning
9021 and end of string."
9022 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9023 (start 0)
9024 notfirst
9025 (list nil))
9026 (while (and (string-match rexp string
9027 (if (and notfirst
9028 (= start (match-beginning 0))
9029 (< start (length string)))
9030 (1+ start) start))
9031 (< (match-beginning 0) (length string)))
9032 (setq notfirst t)
9033 (or (eq (match-beginning 0) 0)
9034 (and (eq (match-beginning 0) (match-end 0))
9035 (eq (match-beginning 0) start))
9036 (setq list
9037 (cons (substring string start (match-beginning 0))
9038 list)))
9039 (setq start (match-end 0)))
9040 (or (eq start (length string))
9041 (setq list
9042 (cons (substring string start)
9043 list)))
9044 (nreverse list)))
9045
9046 (defun org-table-add-invisible-to-vertical-lines ()
9047 "Add an `invisible' property to vertical lines of current table."
9048 (interactive)
9049 (let* ((beg (org-table-begin))
9050 (end (org-table-end))
9051 (end1))
9052 (save-excursion
9053 (goto-char beg)
9054 (while (< (point) end)
9055 (setq end1 (point-at-eol))
9056 (if (looking-at org-table-dataline-regexp)
9057 (while (re-search-forward "|" end1 t)
9058 (add-text-properties (1- (point)) (point)
9059 '(invisible org-table)))
9060 (while (re-search-forward "[+|]" end1 t)
9061 (add-text-properties (1- (point)) (point)
9062 '(invisible org-table))))
9063 (beginning-of-line 2)))))
9064
9065 (defun org-table-toggle-vline-visibility (&optional arg)
9066 "Toggle the visibility of table vertical lines.
9067 The effect is immediate and on all tables in the file.
9068 With prefix ARG, make lines invisible when ARG is positive, make lines
9069 visible when ARG is not positive."
9070 (interactive "P")
9071 (let ((action (cond
9072 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
9073 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
9074 (t (if (org-in-invisibility-spec-p '(org-table))
9075 'off
9076 'on)))))
9077 (if (eq action 'off)
9078 (progn
9079 (org-remove-from-invisibility-spec '(org-table))
9080 (org-table-map-tables 'org-table-align)
9081 (message "Vertical table lines visible")
9082 (if (org-at-table-p)
9083 (org-table-align)))
9084 (org-add-to-invisibility-spec '(org-table))
9085 (org-table-map-tables 'org-table-align)
9086 (message "Vertical table lines invisible"))
9087 (redraw-frame (selected-frame))))
9088
9089 (defun org-table-map-tables (function)
9090 "Apply FUNCTION to the start of all tables in the buffer."
9091 (save-excursion
9092 (save-restriction
9093 (widen)
9094 (goto-char (point-min))
9095 (while (re-search-forward org-table-any-line-regexp nil t)
9096 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9097 (beginning-of-line 1)
9098 (if (looking-at org-table-line-regexp)
9099 (save-excursion (funcall function)))
9100 (re-search-forward org-table-any-border-regexp nil 1)))))
9101
9102 (defun org-table-sum (&optional beg end nlast)
9103 "Sum numbers in region of current table column.
9104 The result will be displayed in the echo area, and will be available
9105 as kill to be inserted with \\[yank].
9106
9107 If there is an active region, it is interpreted as a rectangle and all
9108 numbers in that rectangle will be summed. If there is no active
9109 region and point is located in a table column, sum all numbers in that
9110 column.
9111
9112 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9113 numbers are assumed to be times as well (in decimal hours) and the
9114 numbers are added as such.
9115
9116 If NLAST is a number, only the NLAST fields will actually be summed."
9117 (interactive)
9118 (save-excursion
9119 (let (col (timecnt 0) diff h m s org-table-clip)
9120 (cond
9121 ((and beg end)) ; beg and end given explicitly
9122 ((org-region-active-p)
9123 (setq beg (region-beginning) end (region-end)))
9124 (t
9125 (setq col (org-table-current-column))
9126 (goto-char (org-table-begin))
9127 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9128 (error "No table data"))
9129 (org-table-goto-column col)
9130 ;not needed? (skip-chars-backward "^|")
9131 (setq beg (point))
9132 (goto-char (org-table-end))
9133 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9134 (error "No table data"))
9135 (org-table-goto-column col)
9136 ;not needed? (skip-chars-forward "^|")
9137 (setq end (point))))
9138 (let* ((items (apply 'append (org-table-copy-region beg end)))
9139 (items1 (cond ((not nlast) items)
9140 ((>= nlast (length items)) items)
9141 (t (setq items (reverse items))
9142 (setcdr (nthcdr (1- nlast) items) nil)
9143 (nreverse items))))
9144 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9145 items1)))
9146 (res (apply '+ numbers))
9147 (sres (if (= timecnt 0)
9148 (format "%g" res)
9149 (setq diff (* 3600 res)
9150 h (floor (/ diff 3600)) diff (mod diff 3600)
9151 m (floor (/ diff 60)) diff (mod diff 60)
9152 s diff)
9153 (format "%d:%02d:%02d" h m s))))
9154 (kill-new sres)
9155 (if (interactive-p)
9156 (message "%s"
9157 (substitute-command-keys
9158 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9159 (length numbers) sres))))
9160 sres))))
9161
9162 (defun org-table-get-number-for-summing (s)
9163 (let (n)
9164 (if (string-match "^ *|? *" s)
9165 (setq s (replace-match "" nil nil s)))
9166 (if (string-match " *|? *$" s)
9167 (setq s (replace-match "" nil nil s)))
9168 (setq n (string-to-number s))
9169 (cond
9170 ((and (string-match "0" s)
9171 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9172 ((string-match "\\`[ \t]+\\'" s) nil)
9173 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9174 (let ((h (string-to-number (or (match-string 1 s) "0")))
9175 (m (string-to-number (or (match-string 2 s) "0")))
9176 (s (string-to-number (or (match-string 4 s) "0"))))
9177 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9178 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9179 ((equal n 0) nil)
9180 (t n))))
9181
9182 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9183 "Get a calc vector from a column, accorting to descriptor DESC.
9184 Optional arguments TBEG and COL can give the beginning of the table and
9185 the current column, to avoid unnecessary parsing."
9186 (save-excursion
9187 (or tbeg (setq tbeg (org-table-begin)))
9188 (or col (setq col (org-table-current-column)))
9189 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9190 (cond
9191 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9192 (setq n1 (- (match-end 1) (match-beginning 1)))
9193 (if (match-beginning 3)
9194 (setq n2 (- (match-end 2) (match-beginning 3))))
9195 (setq n (if n2 (max n1 n2) n1))
9196 (setq n1 (if n2 (min n1 n2)))
9197 (setq nn n)
9198 (while (and (> nn 0)
9199 (re-search-backward org-table-hline-regexp tbeg t))
9200 (push (org-current-line) hline-list)
9201 (setq nn (1- nn)))
9202 (setq hline-list (nreverse hline-list))
9203 (goto-line (nth (1- n) hline-list))
9204 (when (re-search-forward org-table-dataline-regexp)
9205 (org-table-goto-column col)
9206 (setq beg (point)))
9207 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9208 (when (re-search-backward org-table-dataline-regexp)
9209 (org-table-goto-column col)
9210 (setq end (point)))
9211 (setq l (apply 'append (org-table-copy-region beg end)))
9212 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9213 (if (equal x "") "0" x))
9214 l ",") "]"))
9215 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9216 (setq n1 (string-to-number (match-string 1 desc))
9217 n2 (string-to-number (match-string 2 desc)))
9218 (beginning-of-line 1)
9219 (save-excursion
9220 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9221 (org-table-goto-column col)
9222 (setq beg (point))))
9223 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9224 (org-table-goto-column col)
9225 (setq end (point)))
9226 (setq l (apply 'append (org-table-copy-region beg end)))
9227 (concat "[" (mapconcat
9228 (lambda (x) (setq x (org-trim x))
9229 (if (equal x "") "0" x))
9230 l ",") "]"))
9231 ((string-match "\\([0-9]+\\)" desc)
9232 (beginning-of-line 1)
9233 (when (re-search-backward org-table-dataline-regexp tbeg t
9234 (string-to-number (match-string 0 desc)))
9235 (org-table-goto-column col)
9236 (org-trim (org-table-get-field))))))))
9237
9238 (defvar org-table-formula-history nil)
9239
9240 (defvar org-table-column-names nil
9241 "Alist with column names, derived from the `!' line.")
9242 (defvar org-table-column-name-regexp nil
9243 "Regular expression matching the current column names.")
9244 (defvar org-table-local-parameters nil
9245 "Alist with parameter names, derived from the `$' line.")
9246 (defvar org-table-named-field-locations nil
9247 "Alist with locations of named fields.")
9248
9249 (defun org-table-get-formula (&optional equation named)
9250 "Read a formula from the minibuffer, offer stored formula as default."
9251 (let* ((name (car (rassoc (list (org-current-line)
9252 (org-table-current-column))
9253 org-table-named-field-locations)))
9254 (scol (if named
9255 (if name name
9256 (error "Not in a named field"))
9257 (int-to-string (org-table-current-column))))
9258 (dummy (and name (not named)
9259 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9260 (error "Abort")))
9261 (org-table-may-need-update nil)
9262 (stored-list (org-table-get-stored-formulas))
9263 (stored (cdr (assoc scol stored-list)))
9264 (eq (cond
9265 ((and stored equation (string-match "^ *=? *$" equation))
9266 stored)
9267 ((stringp equation)
9268 equation)
9269 (t (read-string
9270 (format "%s formula $%s=" (if named "Field" "Column") scol)
9271 (or stored "") 'org-table-formula-history
9272 ;stored
9273 ))))
9274 mustsave)
9275 (when (not (string-match "\\S-" eq))
9276 ;; remove formula
9277 (setq stored-list (delq (assoc scol stored-list) stored-list))
9278 (org-table-store-formulas stored-list)
9279 (error "Formula removed"))
9280 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9281 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9282 (if (and name (not named))
9283 ;; We set the column equation, delete the named one.
9284 (setq stored-list (delq (assoc name stored-list) stored-list)
9285 mustsave t))
9286 (if stored
9287 (setcdr (assoc scol stored-list) eq)
9288 (setq stored-list (cons (cons scol eq) stored-list)))
9289 (if (or mustsave (not (equal stored eq)))
9290 (org-table-store-formulas stored-list))
9291 eq))
9292
9293 (defun org-table-store-formulas (alist)
9294 "Store the list of formulas below the current table."
9295 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9296 (save-excursion
9297 (goto-char (org-table-end))
9298 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9299 (delete-region (point) (match-end 0)))
9300 (insert "#+TBLFM: "
9301 (mapconcat (lambda (x)
9302 (concat "$" (car x) "=" (cdr x)))
9303 alist "::")
9304 "\n")))
9305
9306 (defun org-table-get-stored-formulas ()
9307 "Return an alist with the t=stored formulas directly after current table."
9308 (interactive)
9309 (let (scol eq eq-alist strings string seen)
9310 (save-excursion
9311 (goto-char (org-table-end))
9312 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9313 (setq strings (org-split-string (match-string 2) " *:: *"))
9314 (while (setq string (pop strings))
9315 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9316 (setq scol (match-string 1 string)
9317 eq (match-string 2 string)
9318 eq-alist (cons (cons scol eq) eq-alist))
9319 (if (member scol seen)
9320 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9321 (push scol seen))))))
9322 (nreverse eq-alist)))
9323
9324 (defun org-table-modify-formulas (action &rest columns)
9325 "Modify the formulas stored below the current table.
9326 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9327 expected, for the other actions only a single column number is needed."
9328 (let ((list (org-table-get-stored-formulas))
9329 (nmax (length (org-split-string
9330 (buffer-substring (point-at-bol) (point-at-eol))
9331 "|")))
9332 col col1 col2 scol si sc1 sc2)
9333 (cond
9334 ((null list)) ; No action needed if there are no stored formulas
9335 ((eq action 'remove)
9336 (setq col (car columns)
9337 scol (int-to-string col))
9338 (org-table-replace-in-formulas list scol "INVALID")
9339 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9340 (loop for i from (1+ col) upto nmax by 1 do
9341 (setq si (int-to-string i))
9342 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9343 (if (assoc si list) (setcar (assoc si list)
9344 (int-to-string (1- i))))))
9345 ((eq action 'insert)
9346 (setq col (car columns))
9347 (loop for i from nmax downto col by 1 do
9348 (setq si (int-to-string i))
9349 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9350 (if (assoc si list) (setcar (assoc si list)
9351 (int-to-string (1+ i))))))
9352 ((eq action 'swap)
9353 (setq col1 (car columns) col2 (nth 1 columns)
9354 sc1 (int-to-string col1) sc2 (int-to-string col2))
9355 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
9356 (org-table-replace-in-formulas list sc1 "ZqZ")
9357 (org-table-replace-in-formulas list sc2 sc1)
9358 (org-table-replace-in-formulas list "ZqZ" sc2)
9359 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
9360 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9361 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
9362 (t (error "Invalid action in `org-table-modify-formulas'")))
9363 (if list (org-table-store-formulas list))))
9364
9365 (defun org-table-replace-in-formulas (list s1 s2)
9366 (let (elt re s)
9367 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9368 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
9369 re (concat (regexp-quote s1) "\\>"))
9370 (while (setq elt (pop list))
9371 (setq s (cdr elt))
9372 (while (string-match re s)
9373 (setq s (replace-match s2 t t s)))
9374 (setcdr elt s))))
9375
9376 (defun org-table-get-specials ()
9377 "Get the column names and local parameters for this table."
9378 (save-excursion
9379 (let ((beg (org-table-begin)) (end (org-table-end))
9380 names name fields fields1 field cnt c v line col)
9381 (setq org-table-column-names nil
9382 org-table-local-parameters nil
9383 org-table-named-field-locations nil)
9384 (goto-char beg)
9385 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9386 (setq names (org-split-string (match-string 1) " *| *")
9387 cnt 1)
9388 (while (setq name (pop names))
9389 (setq cnt (1+ cnt))
9390 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9391 (push (cons name (int-to-string cnt)) org-table-column-names))))
9392 (setq org-table-column-names (nreverse org-table-column-names))
9393 (setq org-table-column-name-regexp
9394 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9395 (goto-char beg)
9396 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9397 (setq fields (org-split-string (match-string 1) " *| *"))
9398 (while (setq field (pop fields))
9399 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9400 (push (cons (match-string 1 field) (match-string 2 field))
9401 org-table-local-parameters))))
9402 (goto-char beg)
9403 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9404 (setq c (match-string 1)
9405 fields (org-split-string (match-string 2) " *| *"))
9406 (save-excursion
9407 (beginning-of-line (if (equal c "_") 2 0))
9408 (setq line (org-current-line) col 1)
9409 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9410 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9411 (while (and fields1 (setq field (pop fields)))
9412 (setq v (pop fields1) col (1+ col))
9413 (when (and (stringp field) (stringp v)
9414 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9415 (push (cons field v) org-table-local-parameters)
9416 (push (list field line col) org-table-named-field-locations)))))))
9417
9418 (defun org-this-word ()
9419 ;; Get the current word
9420 (save-excursion
9421 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
9422 (end (progn (skip-chars-forward "^ \t\n") (point))))
9423 (buffer-substring-no-properties beg end))))
9424
9425 (defun org-table-maybe-eval-formula ()
9426 "Check if the current field starts with \"=\" or \":=\".
9427 If yes, store the formula and apply it."
9428 ;; We already know we are in a table. Get field will only return a formula
9429 ;; when appropriate. It might return a separator line, but no problem.
9430 (when org-table-formula-evaluate-inline
9431 (let* ((field (org-trim (or (org-table-get-field) "")))
9432 named eq)
9433 (when (string-match "^:?=\\(.*\\)" field)
9434 (setq named (equal (string-to-char field) ?:)
9435 eq (match-string 1 field))
9436 (if (fboundp 'calc-eval)
9437 (org-table-eval-formula (if named '(4) nil) eq))))))
9438
9439 (defvar org-recalc-commands nil
9440 "List of commands triggering the recalculation of a line.
9441 Will be filled automatically during use.")
9442
9443 (defvar org-recalc-marks
9444 '((" " . "Unmarked: no special line, no automatic recalculation")
9445 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9446 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9447 ("!" . "Column name definition line. Reference in formula as $name.")
9448 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9449 ("_" . "Names for values in row below this one.")
9450 ("^" . "Names for values in row above this one.")))
9451
9452 (defun org-table-rotate-recalc-marks (&optional newchar)
9453 "Rotate the recalculation mark in the first column.
9454 If in any row, the first field is not consistent with a mark,
9455 insert a new column for the markers.
9456 When there is an active region, change all the lines in the region,
9457 after prompting for the marking character.
9458 After each change, a message will be displayed indicating the meaning
9459 of the new mark."
9460 (interactive)
9461 (unless (org-at-table-p) (error "Not at a table"))
9462 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9463 (beg (org-table-begin))
9464 (end (org-table-end))
9465 (l (org-current-line))
9466 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9467 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9468 (have-col
9469 (save-excursion
9470 (goto-char beg)
9471 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9472 (col (org-table-current-column))
9473 (forcenew (car (assoc newchar org-recalc-marks)))
9474 epos new)
9475 (when l1
9476 (message "Change region to what mark? Type # * ! $ or SPC: ")
9477 (setq newchar (char-to-string (read-char-exclusive))
9478 forcenew (car (assoc newchar org-recalc-marks))))
9479 (if (and newchar (not forcenew))
9480 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9481 newchar))
9482 (if l1 (goto-line l1))
9483 (save-excursion
9484 (beginning-of-line 1)
9485 (unless (looking-at org-table-dataline-regexp)
9486 (error "Not at a table data line")))
9487 (unless have-col
9488 (org-table-goto-column 1)
9489 (org-table-insert-column)
9490 (org-table-goto-column (1+ col)))
9491 (setq epos (point-at-eol))
9492 (save-excursion
9493 (beginning-of-line 1)
9494 (org-table-get-field
9495 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9496 (concat " "
9497 (setq new (or forcenew
9498 (cadr (member (match-string 1) marks))))
9499 " ")
9500 " # ")))
9501 (if (and l1 l2)
9502 (progn
9503 (goto-line l1)
9504 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9505 (and (looking-at org-table-dataline-regexp)
9506 (org-table-get-field 1 (concat " " new " "))))
9507 (goto-line l1)))
9508 (if (not (= epos (point-at-eol))) (org-table-align))
9509 (goto-line l)
9510 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9511
9512 (defun org-table-maybe-recalculate-line ()
9513 "Recompute the current line if marked for it, and if we haven't just done it."
9514 (interactive)
9515 (and org-table-allow-automatic-line-recalculation
9516 (not (and (memq last-command org-recalc-commands)
9517 (equal org-last-recalc-line (org-current-line))))
9518 (save-excursion (beginning-of-line 1)
9519 (looking-at org-table-auto-recalculate-regexp))
9520 (fboundp 'calc-eval)
9521 (org-table-recalculate) t))
9522
9523 (defvar org-table-formula-debug nil
9524 "Non-nil means, debug table formulas.
9525 When nil, simply write \"#ERROR\" in corrupted fields.")
9526
9527 (defvar modes)
9528 (defsubst org-set-calc-mode (var &optional value)
9529 (if (stringp var)
9530 (setq var (assoc var '(("D" calc-angle-mode deg)
9531 ("R" calc-angle-mode rad)
9532 ("F" calc-prefer-frac t)
9533 ("S" calc-symbolic-mode t)))
9534 value (nth 2 var) var (nth 1 var)))
9535 (if (memq var modes)
9536 (setcar (cdr (memq var modes)) value)
9537 (cons var (cons value modes)))
9538 modes)
9539
9540 (defun org-table-eval-formula (&optional arg equation
9541 suppress-align suppress-const
9542 suppress-store)
9543 "Replace the table field value at the cursor by the result of a calculation.
9544
9545 This function makes use of Dave Gillespie's Calc package, in my view the
9546 most exciting program ever written for GNU Emacs. So you need to have Calc
9547 installed in order to use this function.
9548
9549 In a table, this command replaces the value in the current field with the
9550 result of a formula. It also installs the formula as the \"current\" column
9551 formula, by storing it in a special line below the table. When called
9552 with a `C-u' prefix, the current field must ba a named field, and the
9553 formula is installed as valid in only this specific field.
9554
9555 When called, the command first prompts for a formula, which is read in
9556 the minibuffer. Previously entered formulas are available through the
9557 history list, and the last used formula is offered as a default.
9558 These stored formulas are adapted correctly when moving, inserting, or
9559 deleting columns with the corresponding commands.
9560
9561 The formula can be any algebraic expression understood by the Calc package.
9562 For details, see the Org-mode manual.
9563
9564 This function can also be called from Lisp programs and offers
9565 additional arguments: EQUATION can be the formula to apply. If this
9566 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9567 used to speed-up recursive calls by by-passing unnecessary aligns.
9568 SUPPRESS-CONST suppresses the interpretation of constants in the
9569 formula, assuming that this has been done already outside the function.
9570 SUPPRESS-STORE means the formula should not be stored, either because
9571 it is already stored, or because it is a modified equation that should
9572 not overwrite the stored one."
9573 (interactive "P")
9574 (require 'calc)
9575 (org-table-check-inside-data-field)
9576 (org-table-get-specials)
9577 (let* (fields
9578 (ndown (if (integerp arg) arg 1))
9579 (org-table-automatic-realign nil)
9580 (case-fold-search nil)
9581 (down (> ndown 1))
9582 (formula (if (and equation suppress-store)
9583 equation
9584 (org-table-get-formula equation (equal arg '(4)))))
9585 (n0 (org-table-current-column))
9586 (modes (copy-sequence org-calc-default-modes))
9587 n form fmt x ev orig c)
9588 ;; Parse the format string. Since we have a lot of modes, this is
9589 ;; a lot of work. However, I think calc still uses most of the time.
9590 (if (string-match ";" formula)
9591 (let ((tmp (org-split-string formula ";")))
9592 (setq formula (car tmp)
9593 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9594 (nth 1 tmp)))
9595 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9596 (setq c (string-to-char (match-string 1 fmt))
9597 n (string-to-number (or (match-string 1 fmt) "")))
9598 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9599 (setq modes (org-set-calc-mode
9600 'calc-float-format
9601 (list (cdr (assoc c '((?n . float) (?f . fix)
9602 (?s . sci) (?e . eng))))
9603 n))))
9604 (setq fmt (replace-match "" t t fmt)))
9605 (while (string-match "[DRFS]" fmt)
9606 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9607 (setq fmt (replace-match "" t t fmt)))
9608 (unless (string-match "\\S-" fmt)
9609 (setq fmt nil))))
9610 (if (and (not suppress-const) org-table-formula-use-constants)
9611 (setq formula (org-table-formula-substitute-names formula)))
9612 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9613 (while (> ndown 0)
9614 (setq fields (org-split-string
9615 (buffer-substring
9616 (point-at-bol) (point-at-eol)) " *| *"))
9617 (if org-table-formula-numbers-only
9618 (setq fields (mapcar
9619 (lambda (x) (number-to-string (string-to-number x)))
9620 fields)))
9621 (setq ndown (1- ndown))
9622 (setq form (copy-sequence formula))
9623 ;; Insert the references to fields in same row
9624 (while (string-match "\\$\\([0-9]+\\)?" form)
9625 (setq n (if (match-beginning 1)
9626 (string-to-number (match-string 1 form))
9627 n0)
9628 x (nth (1- n) fields))
9629 (unless x (error "Invalid field specifier \"%s\""
9630 (match-string 0 form)))
9631 (if (equal x "") (setq x "0"))
9632 (setq form (replace-match (concat "(" x ")") t t form)))
9633 ;; Insert ranges in current column
9634 (while (string-match "\\&[-I0-9]+" form)
9635 (setq form (replace-match
9636 (save-match-data
9637 (org-table-get-vertical-vector (match-string 0 form)
9638 nil n0))
9639 t t form)))
9640 (setq ev (calc-eval (cons form modes)
9641 (if org-table-formula-numbers-only 'num)))
9642
9643 (when org-table-formula-debug
9644 (with-output-to-temp-buffer "*Help*"
9645 (princ (format "Substitution history of formula
9646 Orig: %s
9647 $xyz-> %s
9648 $1-> %s\n" orig formula form))
9649 (if (listp ev)
9650 (princ (format " %s^\nError: %s"
9651 (make-string (car ev) ?\-) (nth 1 ev)))
9652 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9653 ev (or fmt "NONE")
9654 (if fmt (format fmt (string-to-number ev)) ev)))))
9655 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9656 (unless (and (interactive-p) (not ndown))
9657 (unless (let (inhibit-redisplay)
9658 (y-or-n-p "Debugging Formula. Continue to next? "))
9659 (org-table-align)
9660 (error "Abort"))
9661 (delete-window (get-buffer-window "*Help*"))
9662 (message "")))
9663 (if (listp ev) (setq fmt nil ev "#ERROR"))
9664 (org-table-justify-field-maybe
9665 (if fmt (format fmt (string-to-number ev)) ev))
9666 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9667 (call-interactively 'org-return)
9668 (setq ndown 0)))
9669 (and down (org-table-maybe-recalculate-line))
9670 (or suppress-align (and org-table-may-need-update
9671 (org-table-align)))))
9672
9673 (defun org-table-recalculate (&optional all noalign)
9674 "Recalculate the current table line by applying all stored formulas."
9675 (interactive "P")
9676 (or (memq this-command org-recalc-commands)
9677 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9678 (unless (org-at-table-p) (error "Not at a table"))
9679 (org-table-get-specials)
9680 (let* ((eqlist (sort (org-table-get-stored-formulas)
9681 (lambda (a b) (string< (car a) (car b)))))
9682 (inhibit-redisplay t)
9683 (line-re org-table-dataline-regexp)
9684 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9685 (thiscol (org-table-current-column))
9686 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9687 ;; Insert constants in all formulas
9688 (setq eqlist
9689 (mapcar (lambda (x)
9690 (setcdr x (org-table-formula-substitute-names (cdr x)))
9691 x)
9692 eqlist))
9693 ;; Split the equation list
9694 (while (setq eq (pop eqlist))
9695 (if (<= (string-to-char (car eq)) ?9)
9696 (push eq eqlnum)
9697 (push eq eqlname)))
9698 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9699 (if all
9700 (progn
9701 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9702 (goto-char (setq beg (org-table-begin)))
9703 (if (re-search-forward org-table-calculate-mark-regexp end t)
9704 ;; This is a table with marked lines, only compute selected lines
9705 (setq line-re org-table-recalculate-regexp)
9706 ;; Move forward to the first non-header line
9707 (if (and (re-search-forward org-table-dataline-regexp end t)
9708 (re-search-forward org-table-hline-regexp end t)
9709 (re-search-forward org-table-dataline-regexp end t))
9710 (setq beg (match-beginning 0))
9711 nil))) ;; just leave beg where it is
9712 (setq beg (point-at-bol)
9713 end (move-marker (make-marker) (1+ (point-at-eol)))))
9714 (goto-char beg)
9715 (and all (message "Re-applying formulas to full table..."))
9716 (while (re-search-forward line-re end t)
9717 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9718 ;; Unprotected line, recalculate
9719 (and all (message "Re-applying formulas to full table...(line %d)"
9720 (setq cnt (1+ cnt))))
9721 (setq org-last-recalc-line (org-current-line))
9722 (setq eql eqlnum)
9723 (while (setq entry (pop eql))
9724 (goto-line org-last-recalc-line)
9725 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9726 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9727 (goto-line thisline)
9728 (org-table-goto-column thiscol)
9729 (or noalign (and org-table-may-need-update (org-table-align))
9730 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9731 ;; Now do the names fields
9732 (while (setq eq (pop eqlname))
9733 (setq name (car eq)
9734 a (assoc name org-table-named-field-locations))
9735 (when a
9736 (message "Re-applying formula to named field: %s" name)
9737 (goto-line (nth 1 a))
9738 (org-table-goto-column (nth 2 a))
9739 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9740 ;; back to initial position
9741 (goto-line thisline)
9742 (org-table-goto-column thiscol)
9743 (or noalign (and org-table-may-need-update (org-table-align))
9744 (and all (message "Re-applying formulas...done")))))
9745
9746 (defun org-table-formula-substitute-names (f)
9747 "Replace $const with values in string F."
9748 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9749 ;; First, check for column names
9750 (while (setq start (string-match org-table-column-name-regexp f start))
9751 (setq start (1+ start))
9752 (setq a (assoc (match-string 1 f) org-table-column-names))
9753 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9754 ;; Expand ranges to vectors
9755 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9756 (setq n1 (string-to-number (match-string 1 f))
9757 n2 (string-to-number (match-string 2 f))
9758 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9759 s (concat "[($" (number-to-string (1- nn1)) ")"))
9760 (loop for i from nn1 upto nn2 do
9761 (setq s (concat s ",($" (int-to-string i) ")")))
9762 (setq s (concat s "]"))
9763 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9764 (setq f (replace-match s t t f)))
9765 ;; Parameters and constants
9766 (setq start 0)
9767 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9768 (setq start (1+ start))
9769 (if (setq a (save-match-data
9770 (org-table-get-constant (match-string 1 f))))
9771 (setq f (replace-match (concat "(" a ")") t t f))))
9772 (if org-table-formula-debug
9773 (put-text-property 0 (length f) :orig-formula f1 f))
9774 f))
9775
9776 (defun org-table-get-constant (const)
9777 "Find the value for a parameter or constant in a formula.
9778 Parameters get priority."
9779 (or (cdr (assoc const org-table-local-parameters))
9780 (cdr (assoc const org-table-formula-constants))
9781 (and (fboundp 'constants-get) (constants-get const))
9782 "#UNDEFINED_NAME"))
9783
9784 (defvar org-edit-formulas-map (make-sparse-keymap))
9785 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9786 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9787 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9788
9789 (defvar org-pos)
9790 (defvar org-window-configuration)
9791
9792 (defun org-table-edit-formulas ()
9793 "Edit the formulas of the current table in a separate buffer."
9794 (interactive)
9795 (unless (org-at-table-p)
9796 (error "Not at a table"))
9797 (org-table-get-specials)
9798 (let ((eql (org-table-get-stored-formulas))
9799 (pos (move-marker (make-marker) (point)))
9800 (wc (current-window-configuration))
9801 entry loc s)
9802 (switch-to-buffer-other-window "*Edit Formulas*")
9803 (erase-buffer)
9804 (fundamental-mode)
9805 (set (make-local-variable 'org-pos) pos)
9806 (set (make-local-variable 'org-window-configuration) wc)
9807 (use-local-map org-edit-formulas-map)
9808 (setq s "# Edit formulas and finish with `C-c C-c'.
9809 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9810 # Use `C-c ?' to get information about $name at point.
9811 # To cancel editing, press `C-c C-q'.\n")
9812 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9813 (insert s)
9814 (while (setq entry (pop eql))
9815 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9816 (setq s (format "# Named formula, referring to column %d in line %d\n"
9817 (nth 2 loc) (nth 1 loc)))
9818 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9819 (insert s))
9820 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9821 (remove-text-properties 0 (length s) '(face nil) s)
9822 (insert s))
9823 (goto-char (point-min))
9824 (message "Edit formulas and finish with `C-c C-c'.")))
9825
9826 (defun org-show-variable ()
9827 "Show the location/value of the $ expression at point."
9828 (interactive)
9829 (let (var (pos org-pos) (win (selected-window)) e)
9830 (save-excursion
9831 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9832 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9833 (setq var (match-string 1))
9834 (error "No variable at point")))
9835 (cond
9836 ((setq e (assoc var org-table-named-field-locations))
9837 (switch-to-buffer-other-window (marker-buffer pos))
9838 (goto-line (nth 1 e))
9839 (org-table-goto-column (nth 2 e))
9840 (select-window win)
9841 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9842 ((setq e (assoc var org-table-column-names))
9843 (switch-to-buffer-other-window (marker-buffer pos))
9844 (goto-char pos)
9845 (goto-char (org-table-begin))
9846 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9847 (org-table-end) t)
9848 (progn
9849 (goto-char (match-beginning 1))
9850 (message "Named column (column %s)" (cdr e)))
9851 (error "Column name not found"))
9852 (select-window win))
9853 ((string-match "^[0-9]$" var)
9854 ;; column number
9855 (switch-to-buffer-other-window (marker-buffer pos))
9856 (goto-char pos)
9857 (goto-char (org-table-begin))
9858 (recenter 1)
9859 (if (re-search-forward org-table-dataline-regexp
9860 (org-table-end) t)
9861 (progn
9862 (goto-char (match-beginning 0))
9863 (org-table-goto-column (string-to-number var))
9864 (message "Column %s" var))
9865 (error "Column name not found"))
9866 (select-window win))
9867 ((setq e (assoc var org-table-local-parameters))
9868 (switch-to-buffer-other-window (marker-buffer pos))
9869 (goto-char pos)
9870 (goto-char (org-table-begin))
9871 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9872 (progn
9873 (goto-char (match-beginning 1))
9874 (message "Local parameter."))
9875 (error "Parameter not found"))
9876 (select-window win))
9877 (t
9878 (cond
9879 ((setq e (assoc var org-table-formula-constants))
9880 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9881 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9882 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9883 (t (error "Undefined name $%s" var)))))))
9884
9885 (defun org-finish-edit-formulas (&optional arg)
9886 "Parse the buffer for formula definitions and install them.
9887 With prefix ARG, apply the new formulas to the table."
9888 (interactive "P")
9889 (let ((pos org-pos) eql)
9890 (goto-char (point-min))
9891 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9892 (push (cons (match-string 1) (match-string 2)) eql))
9893 (set-window-configuration org-window-configuration)
9894 (select-window (get-buffer-window (marker-buffer pos)))
9895 (goto-char pos)
9896 (unless (org-at-table-p)
9897 (error "Lost table position - cannot install formulae"))
9898 (org-table-store-formulas eql)
9899 (move-marker pos nil)
9900 (kill-buffer "*Edit Formulas*")
9901 (if arg
9902 (org-table-recalculate 'all)
9903 (message "New formulas installed - press C-u C-c C-c to apply."))))
9904
9905 (defun org-abort-edit-formulas ()
9906 "Abort editing formulas, without installing the changes."
9907 (interactive)
9908 (let ((pos org-pos))
9909 (set-window-configuration org-window-configuration)
9910 (select-window (get-buffer-window (marker-buffer pos)))
9911 (goto-char pos)
9912 (message "Formula editing aborted without installing changes")))
9913
9914 ;;; The orgtbl minor mode
9915
9916 ;; Define a minor mode which can be used in other modes in order to
9917 ;; integrate the org-mode table editor.
9918
9919 ;; This is really a hack, because the org-mode table editor uses several
9920 ;; keys which normally belong to the major mode, for example the TAB and
9921 ;; RET keys. Here is how it works: The minor mode defines all the keys
9922 ;; necessary to operate the table editor, but wraps the commands into a
9923 ;; function which tests if the cursor is currently inside a table. If that
9924 ;; is the case, the table editor command is executed. However, when any of
9925 ;; those keys is used outside a table, the function uses `key-binding' to
9926 ;; look up if the key has an associated command in another currently active
9927 ;; keymap (minor modes, major mode, global), and executes that command.
9928 ;; There might be problems if any of the keys used by the table editor is
9929 ;; otherwise used as a prefix key.
9930
9931 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9932 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9933 ;; addresses this by checking explicitly for both bindings.
9934
9935 ;; The optimized version (see variable `orgtbl-optimized') takes over
9936 ;; all keys which are bound to `self-insert-command' in the *global map*.
9937 ;; Some modes bind other commands to simple characters, for example
9938 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9939 ;; active, this binding is ignored inside tables and replaced with a
9940 ;; modified self-insert.
9941
9942 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9943 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9944 In the optimized version, the table editor takes over all simple keys that
9945 normally just insert a character. In tables, the characters are inserted
9946 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9947 for empty fields). Outside tables, the correct binding of the keys is
9948 restored.
9949
9950 The default for this option is t if the optimized version is also used in
9951 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9952 this variable requires a restart of Emacs to become effective."
9953 :group 'org-table
9954 :type 'boolean)
9955
9956 (defvar orgtbl-mode nil
9957 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9958 table editor in arbitrary modes.")
9959 (make-variable-buffer-local 'orgtbl-mode)
9960
9961 (defvar orgtbl-mode-map (make-keymap)
9962 "Keymap for `orgtbl-mode'.")
9963
9964 ;;;###autoload
9965 (defun turn-on-orgtbl ()
9966 "Unconditionally turn on `orgtbl-mode'."
9967 (orgtbl-mode 1))
9968
9969 ;;;###autoload
9970 (defun orgtbl-mode (&optional arg)
9971 "The `org-mode' table editor as a minor mode for use in other modes."
9972 (interactive)
9973 (if (eq major-mode 'org-mode)
9974 ;; Exit without error, in case some hook functions calls this
9975 ;; by accident in org-mode.
9976 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9977 (setq orgtbl-mode
9978 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9979 (if orgtbl-mode
9980 (progn
9981 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9982 ;; Make sure we are first in minor-mode-map-alist
9983 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9984 (and c (setq minor-mode-map-alist
9985 (cons c (delq c minor-mode-map-alist)))))
9986 (set (make-local-variable (quote org-table-may-need-update)) t)
9987 (org-add-hook 'before-change-functions 'org-before-change-function
9988 nil 'local)
9989 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
9990 auto-fill-inhibit-regexp)
9991 (set (make-local-variable 'auto-fill-inhibit-regexp)
9992 (if auto-fill-inhibit-regexp
9993 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
9994 "[ \t]*|"))
9995 (easy-menu-add orgtbl-mode-menu)
9996 (run-hooks 'orgtbl-mode-hook))
9997 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9998 (remove-hook 'before-change-functions 'org-before-change-function t)
9999 (easy-menu-remove orgtbl-mode-menu)
10000 (force-mode-line-update 'all))))
10001
10002 ;; Install it as a minor mode.
10003 (put 'orgtbl-mode :included t)
10004 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10005 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10006
10007 (defun orgtbl-make-binding (fun n &rest keys)
10008 "Create a function for binding in the table minor mode.
10009 FUN is the command to call inside a table. N is used to create a unique
10010 command name. KEYS are keys that should be checked in for a command
10011 to execute outside of tables."
10012 (eval
10013 (list 'defun
10014 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10015 '(arg)
10016 (concat "In tables, run `" (symbol-name fun) "'.\n"
10017 "Outside of tables, run the binding of `"
10018 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10019 "'.")
10020 '(interactive "p")
10021 (list 'if
10022 '(org-at-table-p)
10023 (list 'call-interactively (list 'quote fun))
10024 (list 'let '(orgtbl-mode)
10025 (list 'call-interactively
10026 (append '(or)
10027 (mapcar (lambda (k)
10028 (list 'key-binding k))
10029 keys)
10030 '('orgtbl-error))))))))
10031
10032 (defun orgtbl-error ()
10033 "Error when there is no default binding for a table key."
10034 (interactive)
10035 (error "This key is has no function outside tables"))
10036
10037 (defun orgtbl-setup ()
10038 "Setup orgtbl keymaps."
10039 (let ((nfunc 0)
10040 (bindings
10041 (list
10042 '([(meta shift left)] org-table-delete-column)
10043 '([(meta left)] org-table-move-column-left)
10044 '([(meta right)] org-table-move-column-right)
10045 '([(meta shift right)] org-table-insert-column)
10046 '([(meta shift up)] org-table-kill-row)
10047 '([(meta shift down)] org-table-insert-row)
10048 '([(meta up)] org-table-move-row-up)
10049 '([(meta down)] org-table-move-row-down)
10050 '("\C-c\C-w" org-table-cut-region)
10051 '("\C-c\M-w" org-table-copy-region)
10052 '("\C-c\C-y" org-table-paste-rectangle)
10053 '("\C-c-" org-table-insert-hline)
10054 ; '([(shift tab)] org-table-previous-field)
10055 '("\C-m" org-table-next-row)
10056 (list (org-key 'S-return) 'org-table-copy-down)
10057 '([(meta return)] org-table-wrap-region)
10058 '("\C-c\C-q" org-table-wrap-region)
10059 '("\C-c?" org-table-current-column)
10060 '("\C-c " org-table-blank-field)
10061 '("\C-c+" org-table-sum)
10062 '("\C-c|" org-table-toggle-vline-visibility)
10063 '("\C-c=" org-table-eval-formula)
10064 '("\C-c'" org-table-edit-formulas)
10065 '("\C-c*" org-table-recalculate)
10066 '("\C-c^" org-table-sort-lines)
10067 '([(control ?#)] org-table-rotate-recalc-marks)))
10068 elt key fun cmd)
10069 (while (setq elt (pop bindings))
10070 (setq nfunc (1+ nfunc))
10071 (setq key (car elt)
10072 fun (nth 1 elt)
10073 cmd (orgtbl-make-binding fun nfunc key))
10074 (define-key orgtbl-mode-map key cmd))
10075 ;; Special treatment needed for TAB and RET
10076 (define-key orgtbl-mode-map [(return)]
10077 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10078 (define-key orgtbl-mode-map "\C-m"
10079 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10080 (define-key orgtbl-mode-map [(tab)]
10081 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10082 (define-key orgtbl-mode-map "\C-i"
10083 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10084 (define-key orgtbl-mode-map "\C-i"
10085 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10086 (define-key orgtbl-mode-map "\C-c\C-c"
10087 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10088 (when orgtbl-optimized
10089 ;; If the user wants maximum table support, we need to hijack
10090 ;; some standard editing functions
10091 (org-remap orgtbl-mode-map
10092 'self-insert-command 'orgtbl-self-insert-command
10093 'delete-char 'orgtbl-delete-char
10094 'delete-backward-char 'orgtbl-delete-backward-char)
10095 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10096 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10097 '("OrgTbl"
10098 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10099 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10100 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10101 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10102 "--"
10103 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10104 ["Copy Field from Above"
10105 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10106 "--"
10107 ("Column"
10108 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10109 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10110 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10111 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10112 ("Row"
10113 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10114 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10115 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10116 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10117 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10118 "--"
10119 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10120 ("Rectangle"
10121 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10122 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10123 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10124 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10125 "--"
10126 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10127 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10128 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10129 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10130 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10131 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10132 ["Sum Column/Rectangle" org-table-sum
10133 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10134 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10135 ["Debug Formulas"
10136 (setq org-table-formula-debug (not org-table-formula-debug))
10137 :style toggle :selected org-table-formula-debug]
10138 ))
10139 t)
10140
10141 (defun orgtbl-tab ()
10142 "Justification and field motion for `orgtbl-mode'."
10143 (interactive)
10144 (org-table-justify-field-maybe)
10145 (org-table-next-field))
10146
10147 (defun orgtbl-ret ()
10148 "Justification and field motion for `orgtbl-mode'."
10149 (interactive)
10150 (org-table-justify-field-maybe)
10151 (org-table-next-row))
10152
10153 (defun orgtbl-self-insert-command (N)
10154 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10155 If the cursor is in a table looking at whitespace, the whitespace is
10156 overwritten, and the table is not marked as requiring realignment."
10157 (interactive "p")
10158 (if (and (org-at-table-p)
10159 (or
10160 (and org-table-auto-blank-field
10161 (member last-command
10162 '(orgtbl-hijacker-command-100
10163 orgtbl-hijacker-command-101
10164 orgtbl-hijacker-command-102
10165 orgtbl-hijacker-command-103
10166 orgtbl-hijacker-command-104
10167 orgtbl-hijacker-command-105))
10168 (org-table-blank-field))
10169 t)
10170 (eq N 1)
10171 (looking-at "[^|\n]* +|"))
10172 (let (org-table-may-need-update)
10173 (goto-char (1- (match-end 0)))
10174 (delete-backward-char 1)
10175 (goto-char (match-beginning 0))
10176 (self-insert-command N))
10177 (setq org-table-may-need-update t)
10178 (let (orgtbl-mode)
10179 (call-interactively (key-binding (vector last-input-event))))))
10180
10181 (defun org-force-self-insert (N)
10182 "Needed to enforce self-insert under remapping."
10183 (interactive "p")
10184 (self-insert-command N))
10185
10186 (defun orgtbl-delete-backward-char (N)
10187 "Like `delete-backward-char', insert whitespace at field end in tables.
10188 When deleting backwards, in tables this function will insert whitespace in
10189 front of the next \"|\" separator, to keep the table aligned. The table will
10190 still be marked for re-alignment, because a narrow field may lead to a
10191 reduced column width."
10192 (interactive "p")
10193 (if (and (org-at-table-p)
10194 (eq N 1)
10195 (string-match "|" (buffer-substring (point-at-bol) (point)))
10196 (looking-at ".*?|"))
10197 (let ((pos (point)))
10198 (backward-delete-char N)
10199 (skip-chars-forward "^|")
10200 (insert " ")
10201 (goto-char (1- pos)))
10202 (delete-backward-char N)))
10203
10204 (defun orgtbl-delete-char (N)
10205 "Like `delete-char', but insert whitespace at field end in tables.
10206 When deleting characters, in tables this function will insert whitespace in
10207 front of the next \"|\" separator, to keep the table aligned. The table
10208 will still be marked for re-alignment, because a narrow field may lead to
10209 a reduced column width."
10210 (interactive "p")
10211 (if (and (org-at-table-p)
10212 (not (bolp))
10213 (not (= (char-after) ?|))
10214 (eq N 1))
10215 (if (looking-at ".*?|")
10216 (let ((pos (point)))
10217 (replace-match (concat
10218 (substring (match-string 0) 1 -1)
10219 " |"))
10220 (goto-char pos)))
10221 (delete-char N)))
10222
10223 ;;; Exporting
10224
10225 (defconst org-level-max 20)
10226
10227 (defun org-export-find-first-heading-line (list)
10228 "Remove all lines from LIST which are before the first headline."
10229 (let ((orig-list list)
10230 (re (concat "^" outline-regexp)))
10231 (while (and list
10232 (not (string-match re (car list))))
10233 (pop list))
10234 (or list orig-list)))
10235
10236 (defun org-skip-comments (lines)
10237 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10238 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10239 (re2 "^\\(\\*+\\)[ \t\n\r]")
10240 rtn line level)
10241 (while (setq line (pop lines))
10242 (cond
10243 ((and (string-match re1 line)
10244 (setq level (- (match-end 1) (match-beginning 1))))
10245 ;; Beginning of a COMMENT subtree. Skip it.
10246 (while (and (setq line (pop lines))
10247 (or (not (string-match re2 line))
10248 (> (- (match-end 1) (match-beginning 1)) level))))
10249 (setq lines (cons line lines)))
10250 ((string-match "^#" line)
10251 ;; an ordinary comment line
10252 )
10253 ((and org-export-table-remove-special-lines
10254 (string-match "^[ \t]*| *[!_^] *|" line))
10255 ;; a special table line that should be removed
10256 )
10257 (t (setq rtn (cons line rtn)))))
10258 (nreverse rtn)))
10259
10260 ;; ASCII
10261
10262 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10263 "Characters for underlining headings in ASCII export.")
10264
10265 (defconst org-html-entities
10266 '(("nbsp")
10267 ("iexcl")
10268 ("cent")
10269 ("pound")
10270 ("curren")
10271 ("yen")
10272 ("brvbar")
10273 ("sect")
10274 ("uml")
10275 ("copy")
10276 ("ordf")
10277 ("laquo")
10278 ("not")
10279 ("shy")
10280 ("reg")
10281 ("macr")
10282 ("deg")
10283 ("plusmn")
10284 ("sup2")
10285 ("sup3")
10286 ("acute")
10287 ("micro")
10288 ("para")
10289 ("middot")
10290 ("odot"."o")
10291 ("star"."*")
10292 ("cedil")
10293 ("sup1")
10294 ("ordm")
10295 ("raquo")
10296 ("frac14")
10297 ("frac12")
10298 ("frac34")
10299 ("iquest")
10300 ("Agrave")
10301 ("Aacute")
10302 ("Acirc")
10303 ("Atilde")
10304 ("Auml")
10305 ("Aring") ("AA"."&Aring;")
10306 ("AElig")
10307 ("Ccedil")
10308 ("Egrave")
10309 ("Eacute")
10310 ("Ecirc")
10311 ("Euml")
10312 ("Igrave")
10313 ("Iacute")
10314 ("Icirc")
10315 ("Iuml")
10316 ("ETH")
10317 ("Ntilde")
10318 ("Ograve")
10319 ("Oacute")
10320 ("Ocirc")
10321 ("Otilde")
10322 ("Ouml")
10323 ("times")
10324 ("Oslash")
10325 ("Ugrave")
10326 ("Uacute")
10327 ("Ucirc")
10328 ("Uuml")
10329 ("Yacute")
10330 ("THORN")
10331 ("szlig")
10332 ("agrave")
10333 ("aacute")
10334 ("acirc")
10335 ("atilde")
10336 ("auml")
10337 ("aring")
10338 ("aelig")
10339 ("ccedil")
10340 ("egrave")
10341 ("eacute")
10342 ("ecirc")
10343 ("euml")
10344 ("igrave")
10345 ("iacute")
10346 ("icirc")
10347 ("iuml")
10348 ("eth")
10349 ("ntilde")
10350 ("ograve")
10351 ("oacute")
10352 ("ocirc")
10353 ("otilde")
10354 ("ouml")
10355 ("divide")
10356 ("oslash")
10357 ("ugrave")
10358 ("uacute")
10359 ("ucirc")
10360 ("uuml")
10361 ("yacute")
10362 ("thorn")
10363 ("yuml")
10364 ("fnof")
10365 ("Alpha")
10366 ("Beta")
10367 ("Gamma")
10368 ("Delta")
10369 ("Epsilon")
10370 ("Zeta")
10371 ("Eta")
10372 ("Theta")
10373 ("Iota")
10374 ("Kappa")
10375 ("Lambda")
10376 ("Mu")
10377 ("Nu")
10378 ("Xi")
10379 ("Omicron")
10380 ("Pi")
10381 ("Rho")
10382 ("Sigma")
10383 ("Tau")
10384 ("Upsilon")
10385 ("Phi")
10386 ("Chi")
10387 ("Psi")
10388 ("Omega")
10389 ("alpha")
10390 ("beta")
10391 ("gamma")
10392 ("delta")
10393 ("epsilon")
10394 ("varepsilon"."&epsilon;")
10395 ("zeta")
10396 ("eta")
10397 ("theta")
10398 ("iota")
10399 ("kappa")
10400 ("lambda")
10401 ("mu")
10402 ("nu")
10403 ("xi")
10404 ("omicron")
10405 ("pi")
10406 ("rho")
10407 ("sigmaf") ("varsigma"."&sigmaf;")
10408 ("sigma")
10409 ("tau")
10410 ("upsilon")
10411 ("phi")
10412 ("chi")
10413 ("psi")
10414 ("omega")
10415 ("thetasym") ("vartheta"."&thetasym;")
10416 ("upsih")
10417 ("piv")
10418 ("bull") ("bullet"."&bull;")
10419 ("hellip") ("dots"."&hellip;")
10420 ("prime")
10421 ("Prime")
10422 ("oline")
10423 ("frasl")
10424 ("weierp")
10425 ("image")
10426 ("real")
10427 ("trade")
10428 ("alefsym")
10429 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
10430 ("uarr") ("uparrow"."&uarr;")
10431 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
10432 ("darr")("downarrow"."&darr;")
10433 ("harr") ("leftrightarrow"."&harr;")
10434 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
10435 ("lArr") ("Leftarrow"."&lArr;")
10436 ("uArr") ("Uparrow"."&uArr;")
10437 ("rArr") ("Rightarrow"."&rArr;")
10438 ("dArr") ("Downarrow"."&dArr;")
10439 ("hArr") ("Leftrightarrow"."&hArr;")
10440 ("forall")
10441 ("part") ("partial"."&part;")
10442 ("exist") ("exists"."&exist;")
10443 ("empty") ("emptyset"."&empty;")
10444 ("nabla")
10445 ("isin") ("in"."&isin;")
10446 ("notin")
10447 ("ni")
10448 ("prod")
10449 ("sum")
10450 ("minus")
10451 ("lowast") ("ast"."&lowast;")
10452 ("radic")
10453 ("prop") ("proptp"."&prop;")
10454 ("infin") ("infty"."&infin;")
10455 ("ang") ("angle"."&ang;")
10456 ("and") ("vee"."&and;")
10457 ("or") ("wedge"."&or;")
10458 ("cap")
10459 ("cup")
10460 ("int")
10461 ("there4")
10462 ("sim")
10463 ("cong") ("simeq"."&cong;")
10464 ("asymp")("approx"."&asymp;")
10465 ("ne") ("neq"."&ne;")
10466 ("equiv")
10467 ("le")
10468 ("ge")
10469 ("sub") ("subset"."&sub;")
10470 ("sup") ("supset"."&sup;")
10471 ("nsub")
10472 ("sube")
10473 ("supe")
10474 ("oplus")
10475 ("otimes")
10476 ("perp")
10477 ("sdot") ("cdot"."&sdot;")
10478 ("lceil")
10479 ("rceil")
10480 ("lfloor")
10481 ("rfloor")
10482 ("lang")
10483 ("rang")
10484 ("loz") ("Diamond"."&loz;")
10485 ("spades") ("spadesuit"."&spades;")
10486 ("clubs") ("clubsuit"."&clubs;")
10487 ("hearts") ("diamondsuit"."&hearts;")
10488 ("diams") ("diamondsuit"."&diams;")
10489 ("quot")
10490 ("amp")
10491 ("lt")
10492 ("gt")
10493 ("OElig")
10494 ("oelig")
10495 ("Scaron")
10496 ("scaron")
10497 ("Yuml")
10498 ("circ")
10499 ("tilde")
10500 ("ensp")
10501 ("emsp")
10502 ("thinsp")
10503 ("zwnj")
10504 ("zwj")
10505 ("lrm")
10506 ("rlm")
10507 ("ndash")
10508 ("mdash")
10509 ("lsquo")
10510 ("rsquo")
10511 ("sbquo")
10512 ("ldquo")
10513 ("rdquo")
10514 ("bdquo")
10515 ("dagger")
10516 ("Dagger")
10517 ("permil")
10518 ("lsaquo")
10519 ("rsaquo")
10520 ("euro")
10521
10522 ("arccos"."arccos")
10523 ("arcsin"."arcsin")
10524 ("arctan"."arctan")
10525 ("arg"."arg")
10526 ("cos"."cos")
10527 ("cosh"."cosh")
10528 ("cot"."cot")
10529 ("coth"."coth")
10530 ("csc"."csc")
10531 ("deg"."deg")
10532 ("det"."det")
10533 ("dim"."dim")
10534 ("exp"."exp")
10535 ("gcd"."gcd")
10536 ("hom"."hom")
10537 ("inf"."inf")
10538 ("ker"."ker")
10539 ("lg"."lg")
10540 ("lim"."lim")
10541 ("liminf"."liminf")
10542 ("limsup"."limsup")
10543 ("ln"."ln")
10544 ("log"."log")
10545 ("max"."max")
10546 ("min"."min")
10547 ("Pr"."Pr")
10548 ("sec"."sec")
10549 ("sin"."sin")
10550 ("sinh"."sinh")
10551 ("sup"."sup")
10552 ("tan"."tan")
10553 ("tanh"."tanh")
10554 )
10555 "Entities for TeX->HTML translation.
10556 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
10557 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
10558 In that case, \"\\ent\" will be translated to \"&other;\".
10559 The list contains HTML entities for Latin-1, Greek and other symbols.
10560 It is supplemented by a number of commonly used TeX macros with appropriate
10561 translations. There is currently no way for users to extend this.")
10562
10563 (defun org-cleaned-string-for-export (string)
10564 "Cleanup a buffer substring so that links can be created safely."
10565 (interactive)
10566 (let* ((cb (current-buffer))
10567 (re-radio (and org-target-link-regexp
10568 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
10569 rtn)
10570 (save-excursion
10571 (set-buffer (get-buffer-create " org-mode-tmp"))
10572 (erase-buffer)
10573 (insert string)
10574 (org-mode)
10575 ;; Find targets in comments and move them out of comments,
10576 ;; but mark them as targets that should be invisible
10577 (goto-char (point-min))
10578 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
10579 (replace-match "\\1(INVISIBLE)"))
10580 ;; Find matches for radio targets and turn them into links
10581 (goto-char (point-min))
10582 (when re-radio
10583 (while (re-search-forward re-radio nil t)
10584 (replace-match "\\1[[\\2]]")))
10585 ;; Find all links that contain a newline and put them into a single line
10586 (goto-char (point-min))
10587 (while (re-search-forward "\\(\\[\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\]\\)" nil t)
10588 (replace-match "\\1 \\2")
10589 (goto-char (match-beginning 0)))
10590 ;; Remove comments
10591 (goto-char (point-min))
10592 (while (re-search-forward "^#.*\n?" nil t)
10593 (replace-match ""))
10594 (setq rtn (buffer-string)))
10595 (kill-buffer " org-mode-tmp")
10596 rtn))
10597
10598 (defun org-solidify-link-text (s &optional alist)
10599 "Take link text and make a safe target out of it."
10600 (save-match-data
10601 (let* ((rtn
10602 (mapconcat
10603 'identity
10604 (org-split-string s "[ \t\r\n]+") "--"))
10605 (a (assoc rtn alist)))
10606 (or (cdr a) rtn))))
10607
10608 (defun org-convert-to-odd-levels ()
10609 "Convert an org-mode file with all levels allowed to one with odd levels.
10610 This will leave level 1 alone, convert level 2 to level 3, level 3 to
10611 level 5 etc."
10612 (interactive)
10613 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
10614 (let ((org-odd-levels-only nil) n)
10615 (save-excursion
10616 (goto-char (point-min))
10617 (while (re-search-forward "^\\*\\*+" nil t)
10618 (setq n (1- (length (match-string 0))))
10619 (while (>= (setq n (1- n)) 0)
10620 (org-demote))
10621 (end-of-line 1))))))
10622
10623
10624 (defun org-convert-to-oddeven-levels ()
10625 "Convert an org-mode file with only odd levels to one with odd and even levels.
10626 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
10627 section with an even level, conversion would destroy the structure of the file. An error
10628 is signaled in this case."
10629 (interactive)
10630 (goto-char (point-min))
10631 ;; First check if there are no even levels
10632 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
10633 (org-show-hierarchy-above)
10634 (error "Not all levels are odd in this file. Conversion not possible."))
10635 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
10636 (let ((org-odd-levels-only nil) n)
10637 (save-excursion
10638 (goto-char (point-min))
10639 (while (re-search-forward "^\\*\\*+" nil t)
10640 (setq n (/ (length (match-string 0)) 2))
10641 (while (>= (setq n (1- n)) 0)
10642 (org-promote))
10643 (end-of-line 1))))))
10644
10645 (defun org-tr-level (n)
10646 "Make N odd if required."
10647 (if org-odd-levels-only (1+ (/ n 2)) n))
10648
10649 (defvar org-last-level nil) ; dynamically scoped variable
10650
10651 (defun org-export-as-ascii (arg)
10652 "Export the outline as a pretty ASCII file.
10653 If there is an active region, export only the region.
10654 The prefix ARG specifies how many levels of the outline should become
10655 underlined headlines. The default is 3."
10656 (interactive "P")
10657 (setq-default org-todo-line-regexp org-todo-line-regexp)
10658 (let* ((region
10659 (buffer-substring
10660 (if (org-region-active-p) (region-beginning) (point-min))
10661 (if (org-region-active-p) (region-end) (point-max))))
10662 (lines (org-export-find-first-heading-line
10663 (org-skip-comments
10664 (org-split-string
10665 (org-cleaned-string-for-export region)
10666 "[\r\n]"))))
10667 (org-startup-with-deadline-check nil)
10668 (level 0) line txt
10669 (umax nil)
10670 (case-fold-search nil)
10671 (filename (concat (file-name-sans-extension buffer-file-name)
10672 ".txt"))
10673 (buffer (find-file-noselect filename))
10674 (levels-open (make-vector org-level-max nil))
10675 (date (format-time-string "%Y/%m/%d" (current-time)))
10676 (time (format-time-string "%X" (current-time)))
10677 (author user-full-name)
10678 (title (buffer-name))
10679 (options nil)
10680 (email user-mail-address)
10681 (language org-export-default-language)
10682 (text nil)
10683 (todo nil)
10684 (lang-words nil))
10685
10686 (setq org-last-level 1)
10687 (org-init-section-numbers)
10688
10689 (find-file-noselect filename)
10690
10691 ;; Search for the export key lines
10692 (org-parse-key-lines)
10693
10694 (setq lang-words (or (assoc language org-export-language-setup)
10695 (assoc "en" org-export-language-setup)))
10696 (if org-export-ascii-show-new-buffer
10697 (switch-to-buffer-other-window buffer)
10698 (set-buffer buffer))
10699 (erase-buffer)
10700 (fundamental-mode)
10701 (if options (org-parse-export-options options))
10702 (setq umax (if arg (prefix-numeric-value arg)
10703 org-export-headline-levels))
10704
10705 ;; File header
10706 (if title (org-insert-centered title ?=))
10707 (insert "\n")
10708 (if (or author email)
10709 (insert (concat (nth 1 lang-words) ": " (or author "")
10710 (if email (concat " <" email ">") "")
10711 "\n")))
10712 (if (and date time)
10713 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10714 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10715
10716 (insert "\n\n")
10717
10718 (if org-export-with-toc
10719 (progn
10720 (insert (nth 3 lang-words) "\n"
10721 (make-string (length (nth 3 lang-words)) ?=) "\n")
10722 (mapcar '(lambda (line)
10723 (if (string-match org-todo-line-regexp
10724 line)
10725 ;; This is a headline
10726 (progn
10727 (setq level (- (match-end 1) (match-beginning 1))
10728 level (org-tr-level level)
10729 txt (match-string 3 line)
10730 todo
10731 (or (and (match-beginning 2)
10732 (not (equal (match-string 2 line)
10733 org-done-string)))
10734 ; TODO, not DONE
10735 (and (= level umax)
10736 (org-search-todo-below
10737 line lines level))))
10738 (setq txt (org-html-expand-for-ascii txt))
10739
10740 (if org-export-with-section-numbers
10741 (setq txt (concat (org-section-number level)
10742 " " txt)))
10743 (if (<= level umax)
10744 (progn
10745 (insert
10746 (make-string (* (1- level) 4) ?\ )
10747 (format (if todo "%s (*)\n" "%s\n") txt))
10748 (setq org-last-level level))
10749 ))))
10750 lines)))
10751
10752 (org-init-section-numbers)
10753 (while (setq line (pop lines))
10754 ;; Remove the quoted HTML tags.
10755 (setq line (org-html-expand-for-ascii line))
10756 ;; Remove targets
10757 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
10758 (setq line (replace-match "" t t line)))
10759 ;; Replace internal links
10760 (while (string-match org-bracket-link-regexp line)
10761 (setq line (replace-match
10762 (if (match-end 3) "[\\3]" "[\\1]")
10763 t nil line)))
10764 (cond
10765 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10766 ;; a Headline
10767 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
10768 txt (match-string 2 line))
10769 (org-ascii-level-start level txt umax))
10770 (t (insert line "\n"))))
10771 (normal-mode)
10772 (save-buffer)
10773 (goto-char (point-min))))
10774
10775 (defun org-search-todo-below (line lines level)
10776 "Search the subtree below LINE for any TODO entries."
10777 (let ((rest (cdr (memq line lines)))
10778 (re org-todo-line-regexp)
10779 line lv todo)
10780 (catch 'exit
10781 (while (setq line (pop rest))
10782 (if (string-match re line)
10783 (progn
10784 (setq lv (- (match-end 1) (match-beginning 1))
10785 todo (and (match-beginning 2)
10786 (not (equal (match-string 2 line)
10787 org-done-string))))
10788 ; TODO, not DONE
10789 (if (<= lv level) (throw 'exit nil))
10790 (if todo (throw 'exit t))))))))
10791
10792 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10793 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10794 (defun org-html-expand-for-ascii (line)
10795 "Handle quoted HTML for ASCII export."
10796 (if org-export-html-expand
10797 (while (string-match "@<[^<>\n]*>" line)
10798 ;; We just remove the tags for now.
10799 (setq line (replace-match "" nil nil line))))
10800 line)
10801
10802 (defun org-insert-centered (s &optional underline)
10803 "Insert the string S centered and underline it with character UNDERLINE."
10804 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
10805 (insert (make-string ind ?\ ) s "\n")
10806 (if underline
10807 (insert (make-string ind ?\ )
10808 (make-string (length s) underline)
10809 "\n"))))
10810
10811 (defun org-ascii-level-start (level title umax)
10812 "Insert a new level in ASCII export."
10813 (let (char)
10814 (if (> level umax)
10815 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10816 (if (or (not (equal (char-before) ?\n))
10817 (not (equal (char-before (1- (point))) ?\n)))
10818 (insert "\n"))
10819 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10820 (if org-export-with-section-numbers
10821 (setq title (concat (org-section-number level) " " title)))
10822 (insert title "\n" (make-string (string-width title) char) "\n"))))
10823
10824 (defun org-export-copy-visible ()
10825 "Copy the visible part of the buffer to another buffer, for printing.
10826 Also removes the first line of the buffer if it specifies a mode,
10827 and all options lines."
10828 (interactive)
10829 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
10830 ".txt"))
10831 (buffer (find-file-noselect filename))
10832 (ore (concat
10833 (org-make-options-regexp
10834 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10835 "STARTUP" "ARCHIVE"
10836 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10837 (if org-noutline-p "\\(\n\\|$\\)" "")))
10838 s e)
10839 (with-current-buffer buffer
10840 (erase-buffer)
10841 (text-mode))
10842 (save-excursion
10843 (setq s (goto-char (point-min)))
10844 (while (not (= (point) (point-max)))
10845 (goto-char (org-find-invisible))
10846 (append-to-buffer buffer s (point))
10847 (setq s (goto-char (org-find-visible)))))
10848 (switch-to-buffer-other-window buffer)
10849 (newline)
10850 (goto-char (point-min))
10851 (if (looking-at ".*-\\*- mode:.*\n")
10852 (replace-match ""))
10853 (while (re-search-forward ore nil t)
10854 (replace-match ""))
10855 (goto-char (point-min))))
10856
10857 (defun org-find-visible ()
10858 (if (featurep 'noutline)
10859 (let ((s (point)))
10860 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10861 (get-char-property s 'invisible)))
10862 s)
10863 (skip-chars-forward "^\n")
10864 (point)))
10865 (defun org-find-invisible ()
10866 (if (featurep 'noutline)
10867 (let ((s (point)))
10868 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10869 (not (get-char-property s 'invisible))))
10870 s)
10871 (skip-chars-forward "^\r")
10872 (point)))
10873
10874 ;; HTML
10875
10876 (defun org-get-current-options ()
10877 "Return a string with current options as keyword options.
10878 Does include HTML export options as well as TODO and CATEGORY stuff."
10879 (format
10880 "#+TITLE: %s
10881 #+AUTHOR: %s
10882 #+EMAIL: %s
10883 #+LANGUAGE: %s
10884 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10885 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10886 #+CATEGORY: %s
10887 #+SEQ_TODO: %s
10888 #+TYP_TODO: %s
10889 #+STARTUP: %s %s %s %s
10890 #+ARCHIVE: %s
10891 "
10892 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10893 org-export-headline-levels
10894 org-export-with-section-numbers
10895 org-export-with-toc
10896 org-export-preserve-breaks
10897 org-export-html-expand
10898 org-export-with-fixed-width
10899 org-export-with-tables
10900 org-export-with-sub-superscripts
10901 org-export-with-emphasize
10902 org-export-with-TeX-macros
10903 (file-name-nondirectory buffer-file-name)
10904 (if (equal org-todo-interpretation 'sequence)
10905 (mapconcat 'identity org-todo-keywords " ")
10906 "TODO FEEDBACK VERIFY DONE")
10907 (if (equal org-todo-interpretation 'type)
10908 (mapconcat 'identity org-todo-keywords " ")
10909 "Me Jason Marie DONE")
10910 (cdr (assoc org-startup-folded
10911 '((nil . "nofold")(t . "fold")(content . "content"))))
10912 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10913 (if org-odd-levels-only "odd" "oddeven")
10914 (if org-hide-leading-stars "hidestars" "showstars")
10915 org-archive-location
10916 ))
10917
10918 (defun org-insert-export-options-template ()
10919 "Insert into the buffer a template with information for exporting."
10920 (interactive)
10921 (if (not (bolp)) (newline))
10922 (let ((s (org-get-current-options)))
10923 (and (string-match "#\\+CATEGORY" s)
10924 (setq s (substring s 0 (match-beginning 0))))
10925 (insert s)))
10926
10927 (defun org-toggle-fixed-width-section (arg)
10928 "Toggle the fixed-width export.
10929 If there is no active region, the QUOTE keyword at the current headline is
10930 inserted or removed. When present, it causes the text between this headline
10931 and the next to be exported as fixed-width text, and unmodified.
10932 If there is an active region, this command adds or removes a colon as the
10933 first character of this line. If the first character of a line is a colon,
10934 this line is also exported in fixed-width font."
10935 (interactive "P")
10936 (let* ((cc 0)
10937 (regionp (org-region-active-p))
10938 (beg (if regionp (region-beginning) (point)))
10939 (end (if regionp (region-end)))
10940 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10941 (re "[ \t]*\\(:\\)")
10942 off)
10943 (if regionp
10944 (save-excursion
10945 (goto-char beg)
10946 (setq cc (current-column))
10947 (beginning-of-line 1)
10948 (setq off (looking-at re))
10949 (while (> nlines 0)
10950 (setq nlines (1- nlines))
10951 (beginning-of-line 1)
10952 (cond
10953 (arg
10954 (move-to-column cc t)
10955 (insert ":\n")
10956 (forward-line -1))
10957 ((and off (looking-at re))
10958 (replace-match "" t t nil 1))
10959 ((not off) (move-to-column cc t) (insert ":")))
10960 (forward-line 1)))
10961 (save-excursion
10962 (org-back-to-heading)
10963 (if (looking-at (concat outline-regexp
10964 "\\( +\\<" org-quote-string "\\>\\)"))
10965 (replace-match "" t t nil 1)
10966 (if (looking-at outline-regexp)
10967 (progn
10968 (goto-char (match-end 0))
10969 (insert " " org-quote-string))))))))
10970
10971 (defun org-export-as-html-and-open (arg)
10972 "Export the outline as HTML and immediately open it with a browser.
10973 If there is an active region, export only the region.
10974 The prefix ARG specifies how many levels of the outline should become
10975 headlines. The default is 3. Lower levels will become bulleted lists."
10976 (interactive "P")
10977 (org-export-as-html arg 'hidden)
10978 (org-open-file buffer-file-name))
10979
10980 (defun org-export-as-html-batch ()
10981 "Call `org-export-as-html', may be used in batch processing as
10982 emacs --batch
10983 --load=$HOME/lib/emacs/org.el
10984 --eval \"(setq org-export-headline-levels 2)\"
10985 --visit=MyFile --funcall org-export-as-html-batch"
10986 (org-export-as-html org-export-headline-levels 'hidden))
10987
10988 (defun org-export-as-html (arg &optional hidden)
10989 "Export the outline as a pretty HTML file.
10990 If there is an active region, export only the region.
10991 The prefix ARG specifies how many levels of the outline should become
10992 headlines. The default is 3. Lower levels will become bulleted lists."
10993 (interactive "P")
10994 (setq-default org-todo-line-regexp org-todo-line-regexp)
10995 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
10996 (setq-default org-done-string org-done-string)
10997 (let* ((style org-export-html-style)
10998 (odd org-odd-levels-only)
10999 (region-p (org-region-active-p))
11000 (region
11001 (buffer-substring
11002 (if region-p (region-beginning) (point-min))
11003 (if region-p (region-end) (point-max))))
11004 (all_lines
11005 (org-skip-comments (org-split-string
11006 (org-cleaned-string-for-export region)
11007 "[\r\n]")))
11008 (lines (org-export-find-first-heading-line all_lines))
11009 (level 0) (line "") (origline "") txt todo
11010 (umax nil)
11011 (filename (concat (file-name-sans-extension buffer-file-name)
11012 ".html"))
11013 (buffer (find-file-noselect filename))
11014 (levels-open (make-vector org-level-max nil))
11015 (date (format-time-string "%Y/%m/%d" (current-time)))
11016 (time (format-time-string "%X" (current-time)))
11017 (author user-full-name)
11018 (title (buffer-name))
11019 (options nil)
11020 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
11021 (inquote nil)
11022 (infixed nil)
11023 (in-local-list nil)
11024 (local-list-num nil)
11025 (local-list-indent nil)
11026 (llt org-plain-list-ordered-item-terminator)
11027 (email user-mail-address)
11028 (language org-export-default-language)
11029 (text nil)
11030 (lang-words nil)
11031 (target-alist nil) tg
11032 (head-count 0) cnt
11033 (start 0)
11034 ;; FIXME: The following returns always nil under XEmacs
11035 (coding-system (and (fboundp 'coding-system-get)
11036 (boundp 'buffer-file-coding-system)
11037 buffer-file-coding-system))
11038 (coding-system-for-write (or coding-system coding-system-for-write))
11039 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
11040 (charset (and coding-system
11041 (coding-system-get coding-system 'mime-charset)))
11042 table-open type
11043 table-buffer table-orig-buffer
11044 ind start-is-num starter
11045 )
11046 (message "Exporting...")
11047
11048 (setq org-last-level 1)
11049 (org-init-section-numbers)
11050
11051 ;; Search for the export key lines
11052 (org-parse-key-lines)
11053 (setq lang-words (or (assoc language org-export-language-setup)
11054 (assoc "en" org-export-language-setup)))
11055
11056 ;; Switch to the output buffer
11057 (if (or hidden (not org-export-html-show-new-buffer))
11058 (set-buffer buffer)
11059 (switch-to-buffer-other-window buffer))
11060 (erase-buffer)
11061 (fundamental-mode)
11062 (let ((case-fold-search nil)
11063 (org-odd-levels-only odd))
11064 (if options (org-parse-export-options options))
11065 (setq umax (if arg (prefix-numeric-value arg)
11066 org-export-headline-levels))
11067
11068 ;; File header
11069 (insert (format
11070 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
11071 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
11072 <html lang=\"%s\"><head>
11073 <title>%s</title>
11074 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
11075 <meta name=generator content=\"Org-mode\">
11076 <meta name=generated content=\"%s %s\">
11077 <meta name=author content=\"%s\">
11078 %s
11079 </head><body>
11080 "
11081 language (org-html-expand title) (or charset "iso-8859-1")
11082 date time author style))
11083 (if title (insert (concat "<H1 class=\"title\">"
11084 (org-html-expand title) "</H1>\n")))
11085 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11086 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11087 email "&gt;</a>\n")))
11088 (if (or author email) (insert "<br>\n"))
11089 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11090 date " " time "<br>\n")))
11091 (if text (insert (concat "<p>\n" (org-html-expand text))))
11092 (if org-export-with-toc
11093 (progn
11094 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11095 (insert "<ul>\n")
11096 (setq lines
11097 (mapcar '(lambda (line)
11098 (if (string-match org-todo-line-regexp line)
11099 ;; This is a headline
11100 (progn
11101 (setq level (- (match-end 1) (match-beginning 1))
11102 level (org-tr-level level)
11103 txt (save-match-data
11104 (org-html-expand
11105 (match-string 3 line)))
11106 todo
11107 (or (and (match-beginning 2)
11108 (not (equal (match-string 2 line)
11109 org-done-string)))
11110 ; TODO, not DONE
11111 (and (= level umax)
11112 (org-search-todo-below
11113 line lines level))))
11114 (if org-export-with-section-numbers
11115 (setq txt (concat (org-section-number level)
11116 " " txt)))
11117 (if (<= level umax)
11118 (progn
11119 (setq head-count (+ head-count 1))
11120 (if (> level org-last-level)
11121 (progn
11122 (setq cnt (- level org-last-level))
11123 (while (>= (setq cnt (1- cnt)) 0)
11124 (insert "<ul>"))
11125 (insert "\n")))
11126 (if (< level org-last-level)
11127 (progn
11128 (setq cnt (- org-last-level level))
11129 (while (>= (setq cnt (1- cnt)) 0)
11130 (insert "</ul>"))
11131 (insert "\n")))
11132 ;; Check for targets
11133 (while (string-match org-target-regexp line)
11134 (setq tg (match-string 1 line)
11135 line (replace-match
11136 (concat "@<span class=\"target\">" tg "@</span> ")
11137 t t line))
11138 (push (cons (org-solidify-link-text tg)
11139 (format "sec-%d" head-count))
11140 target-alist))
11141 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11142 (setq txt (replace-match "" t t txt)))
11143 (insert
11144 (format
11145 (if todo
11146 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11147 "<li><a href=\"#sec-%d\">%s</a>\n")
11148 head-count txt))
11149
11150 (setq org-last-level level))
11151 )))
11152 line)
11153 lines))
11154 (while (> org-last-level 0)
11155 (setq org-last-level (1- org-last-level))
11156 (insert "</ul>\n"))
11157 ))
11158 (setq head-count 0)
11159 (org-init-section-numbers)
11160
11161 (while (setq line (pop lines) origline line)
11162 (catch 'nextline
11163
11164 ;; end of quote section?
11165 (when (and inquote (string-match "^\\*+" line))
11166 (insert "</pre>\n")
11167 (setq inquote nil))
11168 ;; inside a quote section?
11169 (when inquote
11170 (insert (org-html-protect line) "\n")
11171 (throw 'nextline nil))
11172
11173 ;; verbatim lines
11174 (when (and org-export-with-fixed-width
11175 (string-match "^[ \t]*:\\(.*\\)" line))
11176 (when (not infixed)
11177 (setq infixed t)
11178 (insert "<pre>\n"))
11179 (insert (org-html-protect (match-string 1 line)) "\n")
11180 (when (and lines
11181 (not (string-match "^[ \t]*\\(:.*\\)"
11182 (car lines))))
11183 (setq infixed nil)
11184 (insert "</pre>\n"))
11185 (throw 'nextline nil))
11186
11187
11188 ;; make targets to anchors
11189 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11190 (cond
11191 ((match-end 2)
11192 (setq line (replace-match
11193 (concat "@<a name=\""
11194 (org-solidify-link-text (match-string 1 line))
11195 "\">\\nbsp@</a>")
11196 t t line)))
11197 ((and org-export-with-toc (equal (string-to-char line) ?*))
11198 (setq line (replace-match
11199 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11200 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11201 t t line)))
11202 (t
11203 (setq line (replace-match
11204 (concat "@<a name=\""
11205 (org-solidify-link-text (match-string 1 line))
11206 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11207 t t line)))))
11208 ;; Replace internal links
11209 (while (string-match org-bracket-link-regexp line)
11210 (setq line (replace-match
11211 (concat
11212 "@<a href=\"#"
11213 (org-solidify-link-text (match-string 1 line) target-alist)
11214 "\">"
11215 (match-string (if (match-end 3) 3 1) line)
11216 "@</a>")
11217 t t line)))
11218
11219 ;; Protect the external links
11220 (setq start 0)
11221 (while (string-match org-link-maybe-angles-regexp line start)
11222 (setq start (match-end 0))
11223 (setq line (replace-match
11224 (concat "\000" (match-string 1 line) "\000")
11225 t t line)))
11226
11227 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11228 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11229 (setq line (org-html-expand line))
11230
11231 ;; Format the links
11232 (setq start 0)
11233 (while (string-match org-protected-link-regexp line start)
11234 (setq start (- (match-end 0) 2))
11235 (setq type (match-string 1 line))
11236 (cond
11237 ((member type '("http" "https" "ftp" "mailto" "news"))
11238 ;; standard URL
11239 (setq line (replace-match
11240 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
11241 "<a href=\"\\1:\\2\">\\1:\\2</a>"
11242 nil nil line)))
11243 ((string= type "file")
11244 ;; FILE link
11245 (let* ((filename (match-string 2 line))
11246 (abs-p (file-name-absolute-p filename))
11247 (thefile (if abs-p (expand-file-name filename) filename))
11248 (thefile (save-match-data
11249 (if (string-match ":[0-9]+$" thefile)
11250 (replace-match "" t t thefile)
11251 thefile)))
11252 (file-is-image-p
11253 (save-match-data
11254 (string-match (org-image-file-name-regexp) thefile))))
11255 (setq line (replace-match
11256 (if (and org-export-html-inline-images
11257 file-is-image-p)
11258 (concat "<img src=\"" thefile "\"/>")
11259 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
11260 nil nil line))))
11261
11262 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11263 (setq line (replace-match
11264 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
11265
11266 ;; TODO items
11267 (if (and (string-match org-todo-line-regexp line)
11268 (match-beginning 2))
11269 (if (equal (match-string 2 line) org-done-string)
11270 (setq line (replace-match
11271 "<span class=\"done\">\\2</span>"
11272 nil nil line 2))
11273 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11274 nil nil line 2))))
11275
11276 ;; DEADLINES
11277 (if (string-match org-deadline-line-regexp line)
11278 (progn
11279 (if (save-match-data
11280 (string-match "<a href"
11281 (substring line 0 (match-beginning 0))))
11282 nil ; Don't do the replacement - it is inside a link
11283 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11284 nil nil line 1)))))
11285 (cond
11286 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11287 ;; This is a headline
11288 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11289 txt (match-string 2 line))
11290 (if (<= level umax) (setq head-count (+ head-count 1)))
11291 (when in-local-list
11292 ;; Close any local lists before inserting a new header line
11293 (while local-list-num
11294 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11295 (pop local-list-num))
11296 (setq local-list-indent nil
11297 in-local-list nil))
11298 (org-html-level-start level txt umax
11299 (and org-export-with-toc (<= level umax))
11300 head-count)
11301 ;; QUOTES
11302 (when (string-match quote-re line)
11303 (insert "<pre>")
11304 (setq inquote t)))
11305
11306 ((and org-export-with-tables
11307 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11308 (if (not table-open)
11309 ;; New table starts
11310 (setq table-open t table-buffer nil table-orig-buffer nil))
11311 ;; Accumulate lines
11312 (setq table-buffer (cons line table-buffer)
11313 table-orig-buffer (cons origline table-orig-buffer))
11314 (when (or (not lines)
11315 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11316 (car lines))))
11317 (setq table-open nil
11318 table-buffer (nreverse table-buffer)
11319 table-orig-buffer (nreverse table-orig-buffer))
11320 (insert (org-format-table-html table-buffer table-orig-buffer))))
11321 (t
11322 ;; Normal lines
11323 (when (and (> org-export-plain-list-max-depth 0)
11324 (string-match
11325 (cond
11326 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11327 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11328 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11329 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11330 line))
11331 (setq ind (org-get-string-indentation line)
11332 start-is-num (match-beginning 4)
11333 starter (if (match-beginning 2) (match-string 2 line))
11334 line (substring line (match-beginning 5)))
11335 (unless (string-match "[^ \t]" line)
11336 ;; empty line. Pretend indentation is large.
11337 (setq ind (1+ (or (car local-list-indent) 1))))
11338 (while (and in-local-list
11339 (or (and (= ind (car local-list-indent))
11340 (not starter))
11341 (< ind (car local-list-indent))))
11342 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11343 (pop local-list-num) (pop local-list-indent)
11344 (setq in-local-list local-list-indent))
11345 (cond
11346 ((and starter
11347 (or (not in-local-list)
11348 (> ind (car local-list-indent)))
11349 (< (length local-list-indent)
11350 org-export-plain-list-max-depth))
11351 ;; Start new (level of ) list
11352 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11353 (push start-is-num local-list-num)
11354 (push ind local-list-indent)
11355 (setq in-local-list t))
11356 (starter
11357 ;; continue current list
11358 (insert "<li>\n"))))
11359 ;; Empty lines start a new paragraph. If hand-formatted lists
11360 ;; are not fully interpreted, lines starting with "-", "+", "*"
11361 ;; also start a new paragraph.
11362 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11363 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11364 ))
11365 (if org-export-html-with-timestamp
11366 (insert org-export-html-html-helper-timestamp))
11367 (insert "</body>\n</html>\n")
11368 (normal-mode)
11369 (save-buffer)
11370 (goto-char (point-min)))))
11371
11372 (defun org-format-table-html (lines olines)
11373 "Find out which HTML converter to use and return the HTML code."
11374 (if (string-match "^[ \t]*|" (car lines))
11375 ;; A normal org table
11376 (org-format-org-table-html lines)
11377 ;; Table made by table.el - test for spanning
11378 (let* ((hlines (delq nil (mapcar
11379 (lambda (x)
11380 (if (string-match "^[ \t]*\\+-" x) x
11381 nil))
11382 lines)))
11383 (first (car hlines))
11384 (ll (and (string-match "\\S-+" first)
11385 (match-string 0 first)))
11386 (re (concat "^[ \t]*" (regexp-quote ll)))
11387 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
11388 hlines))))
11389 (if (and (not spanning)
11390 (not org-export-prefer-native-exporter-for-tables))
11391 ;; We can use my own converter with HTML conversions
11392 (org-format-table-table-html lines)
11393 ;; Need to use the code generator in table.el, with the original text.
11394 (org-format-table-table-html-using-table-generate-source olines)))))
11395
11396 (defun org-format-org-table-html (lines)
11397 "Format a table into HTML."
11398 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11399 (setq lines (nreverse lines))
11400 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11401 (setq lines (nreverse lines))
11402 (when org-export-table-remove-special-lines
11403 ;; Check if the table has a marking column. If yes remove the
11404 ;; column and the special lines
11405 (let* ((special
11406 (not
11407 (memq nil
11408 (mapcar
11409 (lambda (x)
11410 (or (string-match "^[ \t]*|-" x)
11411 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
11412 lines)))))
11413 (if special
11414 (setq lines
11415 (delq nil
11416 (mapcar
11417 (lambda (x)
11418 (if (string-match "^[ \t]*| *[!_^] *|" x)
11419 nil ; ignore this line
11420 (and (or (string-match "^[ \t]*|-+\\+" x)
11421 (string-match "^[ \t]*|[^|]*|" x))
11422 (replace-match "|" t t x))))
11423 lines))))))
11424
11425 (let ((head (and org-export-highlight-first-table-line
11426 (delq nil (mapcar
11427 (lambda (x) (string-match "^[ \t]*|-" x))
11428 (cdr lines)))))
11429 line fields html)
11430 (setq html (concat org-export-html-table-tag "\n"))
11431 (while (setq line (pop lines))
11432 (catch 'next-line
11433 (if (string-match "^[ \t]*|-" line)
11434 (progn
11435 (setq head nil) ;; head ends here, first time around
11436 ;; ignore this line
11437 (throw 'next-line t)))
11438 ;; Break the line into fields
11439 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11440 (setq html (concat
11441 html
11442 "<tr>"
11443 (mapconcat (lambda (x)
11444 (if head
11445 (concat "<th>" x "</th>")
11446 (concat "<td>" x "</td>")))
11447 fields "")
11448 "</tr>\n"))))
11449 (setq html (concat html "</table>\n"))
11450 html))
11451
11452 (defun org-fake-empty-table-line (line)
11453 "Replace everything except \"|\" with spaces."
11454 (let ((i (length line))
11455 (newstr (copy-sequence line)))
11456 (while (> i 0)
11457 (setq i (1- i))
11458 (if (not (eq (aref newstr i) ?|))
11459 (aset newstr i ?\ )))
11460 newstr))
11461
11462 (defun org-format-table-table-html (lines)
11463 "Format a table generated by table.el into HTML.
11464 This conversion does *not* use `table-generate-source' from table.el.
11465 This has the advantage that Org-mode's HTML conversions can be used.
11466 But it has the disadvantage, that no cell- or row-spanning is allowed."
11467 (let (line field-buffer
11468 (head org-export-highlight-first-table-line)
11469 fields html empty)
11470 (setq html (concat org-export-html-table-tag "\n"))
11471 (while (setq line (pop lines))
11472 (setq empty "&nbsp")
11473 (catch 'next-line
11474 (if (string-match "^[ \t]*\\+-" line)
11475 (progn
11476 (if field-buffer
11477 (progn
11478 (setq html (concat
11479 html
11480 "<tr>"
11481 (mapconcat
11482 (lambda (x)
11483 (if (equal x "") (setq x empty))
11484 (if head
11485 (concat "<th>" x "</th>\n")
11486 (concat "<td>" x "</td>\n")))
11487 field-buffer "\n")
11488 "</tr>\n"))
11489 (setq head nil)
11490 (setq field-buffer nil)))
11491 ;; Ignore this line
11492 (throw 'next-line t)))
11493 ;; Break the line into fields and store the fields
11494 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11495 (if field-buffer
11496 (setq field-buffer (mapcar
11497 (lambda (x)
11498 (concat x "<br>" (pop fields)))
11499 field-buffer))
11500 (setq field-buffer fields))))
11501 (setq html (concat html "</table>\n"))
11502 html))
11503
11504 (defun org-format-table-table-html-using-table-generate-source (lines)
11505 "Format a table into html, using `table-generate-source' from table.el.
11506 This has the advantage that cell- or row-spanning is allowed.
11507 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
11508 (require 'table)
11509 (with-current-buffer (get-buffer-create " org-tmp1 ")
11510 (erase-buffer)
11511 (insert (mapconcat 'identity lines "\n"))
11512 (goto-char (point-min))
11513 (if (not (re-search-forward "|[^+]" nil t))
11514 (error "Error processing table"))
11515 (table-recognize-table)
11516 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
11517 (table-generate-source 'html " org-tmp2 ")
11518 (set-buffer " org-tmp2 ")
11519 (buffer-substring (point-min) (point-max))))
11520
11521 (defun org-html-protect (s)
11522 ;; convert & to &amp;, < to &lt; and > to &gt;
11523 (let ((start 0))
11524 (while (string-match "&" s start)
11525 (setq s (replace-match "&amp;" t t s)
11526 start (1+ (match-beginning 0))))
11527 (while (string-match "<" s)
11528 (setq s (replace-match "&lt;" t t s)))
11529 (while (string-match ">" s)
11530 (setq s (replace-match "&gt;" t t s))))
11531 s)
11532
11533 (defun org-html-expand (string)
11534 "Prepare STRING for HTML export. Applies all active conversions."
11535 ;; First check if there is a link in the line - if yes, apply conversions
11536 ;; only before the start of the link.
11537 ;; FIXME: This is no longer correct, because links now have an end.
11538 (let* ((m (string-match org-link-regexp string))
11539 (s (if m (substring string 0 m) string))
11540 (r (if m (substring string m) "")))
11541 ;; convert & to &amp;, < to &lt; and > to &gt;
11542 (setq s (org-html-protect s))
11543 (if org-export-html-expand
11544 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
11545 (setq s (replace-match "<\\1>" nil nil s))))
11546 (if org-export-with-emphasize
11547 (setq s (org-export-html-convert-emphasize s)))
11548 (if org-export-with-sub-superscripts
11549 (setq s (org-export-html-convert-sub-super s)))
11550 (if org-export-with-TeX-macros
11551 (let ((start 0) wd ass)
11552 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
11553 (setq wd (match-string 1 s))
11554 (if (setq ass (assoc wd org-html-entities))
11555 (setq s (replace-match (or (cdr ass)
11556 (concat "&" (car ass) ";"))
11557 t t s))
11558 (setq start (+ start (length wd)))))))
11559 (concat s r)))
11560
11561 (defun org-create-multibrace-regexp (left right n)
11562 "Create a regular expression which will match a balanced sexp.
11563 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
11564 as single character strings.
11565 The regexp returned will match the entire expression including the
11566 delimiters. It will also define a single group which contains the
11567 match except for the outermost delimiters. The maximum depth of
11568 stacked delimiters is N. Escaping delimiters is not possible."
11569 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
11570 (or "\\|")
11571 (re nothing)
11572 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
11573 (while (> n 1)
11574 (setq n (1- n)
11575 re (concat re or next)
11576 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
11577 (concat left "\\(" re "\\)" right)))
11578
11579 (defvar org-match-substring-regexp
11580 (concat
11581 "\\([^\\]\\)\\([_^]\\)\\("
11582 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
11583 "\\|"
11584 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
11585 "\\|"
11586 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
11587 "The regular expression matching a sub- or superscript.")
11588
11589 (defun org-export-html-convert-sub-super (string)
11590 "Convert sub- and superscripts in STRING to HTML."
11591 (let (key c)
11592 (while (string-match org-match-substring-regexp string)
11593 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
11594 (setq c (or (match-string 8 string)
11595 (match-string 6 string)
11596 (match-string 5 string)))
11597 (setq string (replace-match
11598 (concat (match-string 1 string)
11599 "<" key ">" c "</" key ">")
11600 t t string)))
11601 (while (string-match "\\\\\\([_^]\\)" string)
11602 (setq string (replace-match (match-string 1 string) t t string))))
11603 string)
11604
11605 (defun org-export-html-convert-emphasize (string)
11606 (while (string-match
11607 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
11608 string)
11609 (setq string (replace-match
11610 (concat "<b>" (match-string 3 string) "</b>")
11611 t t string 2)))
11612 (while (string-match
11613 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
11614 string)
11615 (setq string (replace-match
11616 (concat "<i>" (match-string 3 string) "</i>")
11617 t t string 2)))
11618 (while (string-match
11619 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
11620 string)
11621 (setq string (replace-match
11622 (concat "<u>" (match-string 3 string) "</u>")
11623 t t string 2)))
11624 string)
11625
11626 (defun org-parse-key-lines ()
11627 "Find the special key lines with the information for exporters."
11628 (save-excursion
11629 (goto-char 0)
11630 (let ((re (org-make-options-regexp
11631 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
11632 key)
11633 (while (re-search-forward re nil t)
11634 (setq key (match-string 1))
11635 (cond ((string-equal key "TITLE")
11636 (setq title (match-string 2)))
11637 ((string-equal key "AUTHOR")
11638 (setq author (match-string 2)))
11639 ((string-equal key "EMAIL")
11640 (setq email (match-string 2)))
11641 ((string-equal key "LANGUAGE")
11642 (setq language (match-string 2)))
11643 ((string-equal key "TEXT")
11644 (setq text (concat text "\n" (match-string 2))))
11645 ((string-equal key "OPTIONS")
11646 (setq options (match-string 2))))))))
11647
11648 (defun org-parse-export-options (s)
11649 "Parse the export options line."
11650 (let ((op '(("H" . org-export-headline-levels)
11651 ("num" . org-export-with-section-numbers)
11652 ("toc" . org-export-with-toc)
11653 ("\\n" . org-export-preserve-breaks)
11654 ("@" . org-export-html-expand)
11655 (":" . org-export-with-fixed-width)
11656 ("|" . org-export-with-tables)
11657 ("^" . org-export-with-sub-superscripts)
11658 ("*" . org-export-with-emphasize)
11659 ("TeX" . org-export-with-TeX-macros)))
11660 o)
11661 (while (setq o (pop op))
11662 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
11663 s)
11664 (set (make-local-variable (cdr o))
11665 (car (read-from-string (match-string 1 s))))))))
11666
11667 (defun org-html-level-start (level title umax with-toc head-count)
11668 "Insert a new level in HTML export."
11669 (let ((l (1+ (max level umax))))
11670 (while (<= l org-level-max)
11671 (if (aref levels-open (1- l))
11672 (progn
11673 (org-html-level-close l)
11674 (aset levels-open (1- l) nil)))
11675 (setq l (1+ l)))
11676 (if (> level umax)
11677 (progn
11678 (if (aref levels-open (1- level))
11679 (insert "<li>" title "<p>\n")
11680 (aset levels-open (1- level) t)
11681 (insert "<ul><li>" title "<p>\n")))
11682 (if org-export-with-section-numbers
11683 (setq title (concat (org-section-number level) " " title)))
11684 (setq level (+ level 1))
11685 (if with-toc
11686 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
11687 level head-count title level))
11688 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
11689
11690 (defun org-html-level-close (&rest args)
11691 "Terminate one level in HTML export."
11692 (insert "</ul>"))
11693
11694 ;; Variable holding the vector with section numbers
11695 (defvar org-section-numbers (make-vector org-level-max 0))
11696
11697 (defun org-init-section-numbers ()
11698 "Initialize the vector for the section numbers."
11699 (let* ((level -1)
11700 (numbers (nreverse (org-split-string "" "\\.")))
11701 (depth (1- (length org-section-numbers)))
11702 (i depth) number-string)
11703 (while (>= i 0)
11704 (if (> i level)
11705 (aset org-section-numbers i 0)
11706 (setq number-string (or (car numbers) "0"))
11707 (if (string-match "\\`[A-Z]\\'" number-string)
11708 (aset org-section-numbers i
11709 (- (string-to-char number-string) ?A -1))
11710 (aset org-section-numbers i (string-to-number number-string)))
11711 (pop numbers))
11712 (setq i (1- i)))))
11713
11714 (defun org-section-number (&optional level)
11715 "Return a string with the current section number.
11716 When LEVEL is non-nil, increase section numbers on that level."
11717 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
11718 (when level
11719 (when (> level -1)
11720 (aset org-section-numbers
11721 level (1+ (aref org-section-numbers level))))
11722 (setq idx (1+ level))
11723 (while (<= idx depth)
11724 (if (not (= idx 1))
11725 (aset org-section-numbers idx 0))
11726 (setq idx (1+ idx))))
11727 (setq idx 0)
11728 (while (<= idx depth)
11729 (setq n (aref org-section-numbers idx))
11730 (setq string (concat string (if (not (string= string "")) "." "")
11731 (int-to-string n)))
11732 (setq idx (1+ idx)))
11733 (save-match-data
11734 (if (string-match "\\`\\([@0]\\.\\)+" string)
11735 (setq string (replace-match "" nil nil string)))
11736 (if (string-match "\\(\\.0\\)+\\'" string)
11737 (setq string (replace-match "" nil nil string))))
11738 string))
11739
11740
11741 (defun org-export-icalendar-this-file ()
11742 "Export current file as an iCalendar file.
11743 The iCalendar file will be located in the same directory as the Org-mode
11744 file, but with extension `.ics'."
11745 (interactive)
11746 (org-export-icalendar nil buffer-file-name))
11747
11748 ;;;###autoload
11749 (defun org-export-icalendar-all-agenda-files ()
11750 "Export all files in `org-agenda-files' to iCalendar .ics files.
11751 Each iCalendar file will be located in the same directory as the Org-mode
11752 file, but with extension `.ics'."
11753 (interactive)
11754 (apply 'org-export-icalendar nil org-agenda-files))
11755
11756 ;;;###autoload
11757 (defun org-export-icalendar-combine-agenda-files ()
11758 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11759 The file is stored under the name `org-combined-agenda-icalendar-file'."
11760 (interactive)
11761 (apply 'org-export-icalendar t org-agenda-files))
11762
11763 (defun org-export-icalendar (combine &rest files)
11764 "Create iCalendar files for all elements of FILES.
11765 If COMBINE is non-nil, combine all calendar entries into a single large
11766 file and store it under the name `org-combined-agenda-icalendar-file'."
11767 (save-excursion
11768 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11769 (when combine
11770 (setq ical-file org-combined-agenda-icalendar-file
11771 ical-buffer (org-get-agenda-file-buffer ical-file))
11772 (set-buffer ical-buffer) (erase-buffer))
11773 (while (setq file (pop files))
11774 (catch 'nextfile
11775 (org-check-agenda-file file)
11776 (unless combine
11777 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11778 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11779 (set-buffer ical-buffer) (erase-buffer))
11780 (set-buffer (org-get-agenda-file-buffer file))
11781 (setq category (or org-category
11782 (file-name-sans-extension
11783 (file-name-nondirectory buffer-file-name))))
11784 (if (symbolp category) (setq category (symbol-name category)))
11785 (let ((standard-output ical-buffer))
11786 (if combine
11787 (and (not started) (setq started t)
11788 (org-start-icalendar-file org-icalendar-combined-name))
11789 (org-start-icalendar-file category))
11790 (org-print-icalendar-entries combine category)
11791 (when (or (and combine (not files)) (not combine))
11792 (org-finish-icalendar-file)
11793 (set-buffer ical-buffer)
11794 (save-buffer)
11795 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11796 (org-release-buffers org-agenda-new-buffers))))
11797
11798 (defvar org-after-save-iCalendar-file-hook nil
11799 "Hook run after an iCalendar file has been saved.
11800 The iCalendar buffer is still current when this hook is run.
11801 A good way to use this is to tell a desktop calenndar application to re-read
11802 the iCalendar file.")
11803
11804 (defun org-print-icalendar-entries (&optional combine category)
11805 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11806 When COMBINE is non nil, add the category to each line."
11807 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11808 (dts (org-ical-ts-to-string
11809 (format-time-string (cdr org-time-stamp-formats) (current-time))
11810 "DTSTART"))
11811 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11812 (save-excursion
11813 (goto-char (point-min))
11814 (while (re-search-forward org-ts-regexp nil t)
11815 (setq pos (match-beginning 0)
11816 ts (match-string 0)
11817 inc t
11818 hd (org-get-heading))
11819 (if (looking-at re2)
11820 (progn
11821 (goto-char (match-end 0))
11822 (setq ts2 (match-string 1) inc nil))
11823 (setq ts2 ts
11824 tmp (buffer-substring (max (point-min)
11825 (- pos org-ds-keyword-length))
11826 pos)
11827 deadlinep (string-match org-deadline-regexp tmp)
11828 scheduledp (string-match org-scheduled-regexp tmp)
11829 ;; donep (org-entry-is-done-p)
11830 ))
11831 (if (or (string-match org-tr-regexp hd)
11832 (string-match org-ts-regexp hd))
11833 (setq hd (replace-match "" t t hd)))
11834 (if combine
11835 (setq hd (concat hd " (category " category ")")))
11836 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11837 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11838 (princ (format "BEGIN:VEVENT
11839 %s
11840 %s
11841 SUMMARY:%s
11842 END:VEVENT\n"
11843 (org-ical-ts-to-string ts "DTSTART")
11844 (org-ical-ts-to-string ts2 "DTEND" inc)
11845 hd)))
11846 (when org-icalendar-include-todo
11847 (goto-char (point-min))
11848 (while (re-search-forward org-todo-line-regexp nil t)
11849 (setq state (match-string 1))
11850 (unless (equal state org-done-string)
11851 (setq hd (match-string 3))
11852 (if (string-match org-priority-regexp hd)
11853 (setq pri (string-to-char (match-string 2 hd))
11854 hd (concat (substring hd 0 (match-beginning 1))
11855 (substring hd (- (match-end 1)))))
11856 (setq pri org-default-priority))
11857 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11858 (- org-lowest-priority ?A))))))
11859
11860 (princ (format "BEGIN:VTODO
11861 %s
11862 SUMMARY:%s
11863 SEQUENCE:1
11864 PRIORITY:%d
11865 END:VTODO\n"
11866 dts hd pri))))))))
11867
11868 (defun org-start-icalendar-file (name)
11869 "Start an iCalendar file by inserting the header."
11870 (let ((user user-full-name)
11871 (name (or name "unknown"))
11872 (timezone (cadr (current-time-zone))))
11873 (princ
11874 (format "BEGIN:VCALENDAR
11875 VERSION:2.0
11876 X-WR-CALNAME:%s
11877 PRODID:-//%s//Emacs with Org-mode//EN
11878 X-WR-TIMEZONE:%s
11879 CALSCALE:GREGORIAN\n" name user timezone))))
11880
11881 (defun org-finish-icalendar-file ()
11882 "Finish an iCalendar file by inserting the END statement."
11883 (princ "END:VCALENDAR\n"))
11884
11885 (defun org-ical-ts-to-string (s keyword &optional inc)
11886 "Take a time string S and convert it to iCalendar format.
11887 KEYWORD is added in front, to make a complete line like DTSTART....
11888 When INC is non-nil, increase the hour by two (if time string contains
11889 a time), or the day by one (if it does not contain a time)."
11890 (let ((t1 (org-parse-time-string s 'nodefault))
11891 t2 fmt have-time time)
11892 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11893 (setq t2 t1 have-time t)
11894 (setq t2 (org-parse-time-string s)))
11895 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11896 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11897 (when inc
11898 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11899 (setq time (encode-time s mi h d m y)))
11900 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11901 (concat keyword (format-time-string fmt time))))
11902
11903
11904 ;;; Key bindings
11905
11906 ;; - Bindings in Org-mode map are currently
11907 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11908 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
11909 ;; e (?) useful from outline-mode
11910 ;; i k @ expendable from outline-mode
11911 ;; 0123456789 % & ()_{} " ` free
11912
11913 ;; Make `C-c C-x' a prefix key
11914 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11915
11916 ;; TAB key with modifiers
11917 (define-key org-mode-map "\C-i" 'org-cycle)
11918 (define-key org-mode-map [(meta tab)] 'org-complete)
11919 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11920 ;; The following line is necessary under Suse GNU/Linux
11921 (unless org-xemacs-p
11922 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11923 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11924
11925 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11926 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11927 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11928 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11929 (define-key org-mode-map [(meta return)] 'org-meta-return)
11930 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11931 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11932
11933 ;; Cursor keys with modifiers
11934 (define-key org-mode-map [(meta left)] 'org-metaleft)
11935 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11936 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11937 (define-key org-mode-map [(meta right)] 'org-metaright)
11938 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11939 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11940 (define-key org-mode-map [(meta up)] 'org-metaup)
11941 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11942 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11943 (define-key org-mode-map [(meta down)] 'org-metadown)
11944 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11945 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11946
11947 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11948 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11949 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11950 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11951 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11952 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11953 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11954 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11955 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11956 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11957 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11958 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11959 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11960 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11961 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11962 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11963
11964 ;; All the other keys
11965 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11966 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11967 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11968 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11969 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11970 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11971 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11972 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11973 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11974 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11975 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11976 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11977 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11978 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11979 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
11980 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
11981 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11982 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11983 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11984 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11985 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11986 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11987 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11988 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11989 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
11990 (define-key org-mode-map "\C-c]" 'org-remove-file)
11991 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
11992 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
11993 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
11994 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11995 (define-key org-mode-map "\C-m" 'org-return)
11996 (define-key org-mode-map "\C-c?" 'org-table-current-column)
11997 (define-key org-mode-map "\C-c " 'org-table-blank-field)
11998 (define-key org-mode-map "\C-c+" 'org-table-sum)
11999 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
12000 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
12001 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
12002 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
12003 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12004 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
12005 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12006 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
12007 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
12008 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
12009 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
12010 ;; OPML support is only an option for the future
12011 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
12012 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
12013 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
12014 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
12015 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
12016 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
12017 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
12018 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12019 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
12020 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
12021 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
12022
12023 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12024 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12025 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12026 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12027
12028 (defsubst org-table-p () (org-at-table-p))
12029
12030 (defun org-self-insert-command (N)
12031 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12032 If the cursor is in a table looking at whitespace, the whitespace is
12033 overwritten, and the table is not marked as requiring realignment."
12034 (interactive "p")
12035 (if (and (org-table-p)
12036 (or
12037 (and org-table-auto-blank-field
12038 (member last-command
12039 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12040 (org-table-blank-field))
12041 t)
12042 (eq N 1)
12043 (looking-at "[^|\n]* +|"))
12044 (let (org-table-may-need-update)
12045 (goto-char (1- (match-end 0)))
12046 (delete-backward-char 1)
12047 (goto-char (match-beginning 0))
12048 (self-insert-command N))
12049 (setq org-table-may-need-update t)
12050 (self-insert-command N)))
12051
12052 ;; FIXME:
12053 ;; The following two functions might still be optimized to trigger
12054 ;; re-alignment less frequently.
12055
12056 (defun org-delete-backward-char (N)
12057 "Like `delete-backward-char', insert whitespace at field end in tables.
12058 When deleting backwards, in tables this function will insert whitespace in
12059 front of the next \"|\" separator, to keep the table aligned. The table will
12060 still be marked for re-alignment, because a narrow field may lead to a
12061 reduced column width."
12062 (interactive "p")
12063 (if (and (org-table-p)
12064 (eq N 1)
12065 (string-match "|" (buffer-substring (point-at-bol) (point)))
12066 (looking-at ".*?|"))
12067 (let ((pos (point)))
12068 (backward-delete-char N)
12069 (skip-chars-forward "^|")
12070 (insert " ")
12071 (goto-char (1- pos)))
12072 (backward-delete-char N)))
12073
12074 (defun org-delete-char (N)
12075 "Like `delete-char', but insert whitespace at field end in tables.
12076 When deleting characters, in tables this function will insert whitespace in
12077 front of the next \"|\" separator, to keep the table aligned. The table
12078 will still be marked for re-alignment, because a narrow field may lead to
12079 a reduced column width."
12080 (interactive "p")
12081 (if (and (org-table-p)
12082 (not (bolp))
12083 (not (= (char-after) ?|))
12084 (eq N 1))
12085 (if (looking-at ".*?|")
12086 (let ((pos (point)))
12087 (replace-match (concat
12088 (substring (match-string 0) 1 -1)
12089 " |"))
12090 (goto-char pos)))
12091 (delete-char N)))
12092
12093 ;; How to do this: Measure non-white length of current string
12094 ;; If equal to column width, we should realign.
12095
12096 (defun org-remap (map &rest commands)
12097 "In MAP, remap the functions given in COMMANDS.
12098 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12099 (let (new old)
12100 (while commands
12101 (setq old (pop commands) new (pop commands))
12102 (if (fboundp 'command-remapping)
12103 (define-key map (vector 'remap old) new)
12104 (substitute-key-definition old new map global-map)))))
12105
12106 (when (eq org-enable-table-editor 'optimized)
12107 ;; If the user wants maximum table support, we need to hijack
12108 ;; some standard editing functions
12109 (org-remap org-mode-map
12110 'self-insert-command 'org-self-insert-command
12111 'delete-char 'org-delete-char
12112 'delete-backward-char 'org-delete-backward-char)
12113 (define-key org-mode-map "|" 'org-force-self-insert))
12114
12115 (defun org-shiftcursor-error ()
12116 "Throw an error because Shift-Cursor command was applied in wrong context."
12117 (error "This command is active in special context like tables, headlines or timestamps"))
12118
12119 (defun org-shifttab ()
12120 "Global visibility cycling or move to previous table field.
12121 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12122 See the individual commands for more information."
12123 (interactive)
12124 (cond
12125 ((org-at-table-p) (org-table-previous-field))
12126 (t (org-cycle '(4)))))
12127
12128 (defun org-shiftmetaleft ()
12129 "Promote subtree or delete table column.
12130 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12131 See the individual commands for more information."
12132 (interactive)
12133 (cond
12134 ((org-at-table-p) (org-table-delete-column))
12135 ((org-on-heading-p) (org-promote-subtree))
12136 ((org-at-item-p) (call-interactively 'org-outdent-item))
12137 (t (org-shiftcursor-error))))
12138
12139 (defun org-shiftmetaright ()
12140 "Demote subtree or insert table column.
12141 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12142 See the individual commands for more information."
12143 (interactive)
12144 (cond
12145 ((org-at-table-p) (org-table-insert-column))
12146 ((org-on-heading-p) (org-demote-subtree))
12147 ((org-at-item-p) (call-interactively 'org-indent-item))
12148 (t (org-shiftcursor-error))))
12149
12150 (defun org-shiftmetaup (&optional arg)
12151 "Move subtree up or kill table row.
12152 Calls `org-move-subtree-up' or `org-table-kill-row' or
12153 `org-move-item-up' depending on context. See the individual commands
12154 for more information."
12155 (interactive "P")
12156 (cond
12157 ((org-at-table-p) (org-table-kill-row))
12158 ((org-on-heading-p) (org-move-subtree-up arg))
12159 ((org-at-item-p) (org-move-item-up arg))
12160 (t (org-shiftcursor-error))))
12161 (defun org-shiftmetadown (&optional arg)
12162 "Move subtree down or insert table row.
12163 Calls `org-move-subtree-down' or `org-table-insert-row' or
12164 `org-move-item-down', depending on context. See the individual
12165 commands for more information."
12166 (interactive "P")
12167 (cond
12168 ((org-at-table-p) (org-table-insert-row arg))
12169 ((org-on-heading-p) (org-move-subtree-down arg))
12170 ((org-at-item-p) (org-move-item-down arg))
12171 (t (org-shiftcursor-error))))
12172
12173 (defun org-metaleft (&optional arg)
12174 "Promote heading or move table column to left.
12175 Calls `org-do-promote' or `org-table-move-column', depending on context.
12176 With no specific context, calls the Emacs default `backward-word'.
12177 See the individual commands for more information."
12178 (interactive "P")
12179 (cond
12180 ((org-at-table-p) (org-table-move-column 'left))
12181 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12182 (t (backward-word (prefix-numeric-value arg)))))
12183
12184 (defun org-metaright (&optional arg)
12185 "Demote subtree or move table column to right.
12186 Calls `org-do-demote' or `org-table-move-column', depending on context.
12187 With no specific context, calls the Emacs default `forward-word'.
12188 See the individual commands for more information."
12189 (interactive "P")
12190 (cond
12191 ((org-at-table-p) (org-table-move-column nil))
12192 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12193 (t (forward-word (prefix-numeric-value arg)))))
12194
12195 (defun org-metaup (&optional arg)
12196 "Move subtree up or move table row up.
12197 Calls `org-move-subtree-up' or `org-table-move-row' or
12198 `org-move-item-up', depending on context. See the individual commands
12199 for more information."
12200 (interactive "P")
12201 (cond
12202 ((org-at-table-p) (org-table-move-row 'up))
12203 ((org-on-heading-p) (org-move-subtree-up arg))
12204 ((org-at-item-p) (org-move-item-up arg))
12205 (t (org-shiftcursor-error))))
12206
12207 (defun org-metadown (&optional arg)
12208 "Move subtree down or move table row down.
12209 Calls `org-move-subtree-down' or `org-table-move-row' or
12210 `org-move-item-down', depending on context. See the individual
12211 commands for more information."
12212 (interactive "P")
12213 (cond
12214 ((org-at-table-p) (org-table-move-row nil))
12215 ((org-on-heading-p) (org-move-subtree-down arg))
12216 ((org-at-item-p) (org-move-item-down arg))
12217 (t (org-shiftcursor-error))))
12218
12219 (defun org-shiftup (&optional arg)
12220 "Increase item in timestamp or increase priority of current item.
12221 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12222 See the individual commands for more information."
12223 (interactive "P")
12224 (cond
12225 ((org-at-timestamp-p) (org-timestamp-up arg))
12226 (t (org-priority-up))))
12227
12228 (defun org-shiftdown (&optional arg)
12229 "Decrease item in timestamp or decrease priority of current item.
12230 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12231 See the individual commands for more information."
12232 (interactive "P")
12233 (cond
12234 ((org-at-timestamp-p) (org-timestamp-down arg))
12235 (t (org-priority-down))))
12236
12237 (defun org-shiftright ()
12238 "Next TODO keyword or timestamp one day later, depending on context."
12239 (interactive)
12240 (cond
12241 ((org-at-timestamp-p) (org-timestamp-up-day))
12242 ((org-on-heading-p) (org-todo 'right))
12243 (t (org-shiftcursor-error))))
12244
12245 (defun org-shiftleft ()
12246 "Previous TODO keyword or timestamp one day earlier, depending on context."
12247 (interactive)
12248 (cond
12249 ((org-at-timestamp-p) (org-timestamp-down-day))
12250 ((org-on-heading-p) (org-todo 'left))
12251 (t (org-shiftcursor-error))))
12252
12253 (defun org-copy-special ()
12254 "Copy region in table or copy current subtree.
12255 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12256 See the individual commands for more information."
12257 (interactive)
12258 (call-interactively
12259 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12260
12261 (defun org-cut-special ()
12262 "Cut region in table or cut current subtree.
12263 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12264 See the individual commands for more information."
12265 (interactive)
12266 (call-interactively
12267 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12268
12269 (defun org-paste-special (arg)
12270 "Paste rectangular region into table, or past subtree relative to level.
12271 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12272 See the individual commands for more information."
12273 (interactive "P")
12274 (if (org-at-table-p)
12275 (org-table-paste-rectangle)
12276 (org-paste-subtree arg)))
12277
12278 (defun org-ctrl-c-ctrl-c (&optional arg)
12279 "Call realign table, or recognize a table.el table, or update keywords.
12280 When the cursor is inside a table created by the table.el package,
12281 activate that table. Otherwise, if the cursor is at a normal table
12282 created with org.el, re-align that table. This command works even if
12283 the automatic table editor has been turned off.
12284
12285 If the cursor is in a headline, prompt for tags and insert them into
12286 the current line, aligned to `org-tags-column'. When in a headline and
12287 called with prefix arg, realign all tags in the current buffer.
12288
12289 If the cursor is in one of the special #+KEYWORD lines, this triggers
12290 scanning the buffer for these lines and updating the information.
12291 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
12292 (interactive "P")
12293 (let ((org-enable-table-editor t))
12294 (cond
12295 ((org-on-target-p) (org-update-radio-target-regexp))
12296 ((org-on-heading-p) (org-set-tags arg))
12297 ((org-at-table.el-p)
12298 (require 'table)
12299 (beginning-of-line 1)
12300 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12301 (table-recognize-table))
12302 ((org-at-table-p)
12303 (org-table-maybe-eval-formula)
12304 (if arg
12305 (org-table-recalculate t)
12306 (org-table-maybe-recalculate-line))
12307 (org-table-align))
12308 ((org-at-item-p)
12309 (org-renumber-ordered-list (prefix-numeric-value arg)))
12310 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12311 (cond
12312 ((equal (match-string 1) "TBLFM")
12313 ;; Recalculate the table before this line
12314 (save-excursion
12315 (beginning-of-line 1)
12316 (skip-chars-backward " \r\n\t")
12317 (if (org-at-table-p) (org-table-recalculate t))))
12318 (t
12319 (org-mode-restart))))
12320 ((org-region-active-p)
12321 (org-table-convert-region (region-beginning) (region-end) arg))
12322 ((condition-case nil
12323 (and (region-beginning) (region-end))
12324 (error nil))
12325 (if (y-or-n-p "Convert inactive region to table? ")
12326 (org-table-convert-region (region-beginning) (region-end) arg)
12327 (error "Abort")))
12328 (t (error "C-c C-c can do nothing useful at this location.")))))
12329
12330 (defun org-mode-restart ()
12331 "Restart Org-mode, to scan again for special lines.
12332 Also updates the keyword regular expressions."
12333 (interactive)
12334 (let ((org-inhibit-startup t)) (org-mode))
12335 (message "Org-mode restarted to refresh keyword and special line setup"))
12336
12337 (defun org-return ()
12338 "Goto next table row or insert a newline.
12339 Calls `org-table-next-row' or `newline', depending on context.
12340 See the individual commands for more information."
12341 (interactive)
12342 (cond
12343 ((org-at-table-p)
12344 (org-table-justify-field-maybe)
12345 (org-table-next-row))
12346 (t (newline))))
12347
12348 (defun org-meta-return (&optional arg)
12349 "Insert a new heading or wrap a region in a table.
12350 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12351 See the individual commands for more information."
12352 (interactive "P")
12353 (cond
12354 ((org-at-table-p)
12355 (org-table-wrap-region arg))
12356 (t (org-insert-heading arg))))
12357
12358 ;;; Menu entries
12359
12360 ;; Define the Org-mode menus
12361 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12362 '("Tbl"
12363 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
12364 ["Next Field" org-cycle (org-at-table-p)]
12365 ["Previous Field" org-shifttab (org-at-table-p)]
12366 ["Next Row" org-return (org-at-table-p)]
12367 "--"
12368 ["Blank Field" org-table-blank-field (org-at-table-p)]
12369 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12370 "--"
12371 ("Column"
12372 ["Move Column Left" org-metaleft (org-at-table-p)]
12373 ["Move Column Right" org-metaright (org-at-table-p)]
12374 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12375 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12376 ("Row"
12377 ["Move Row Up" org-metaup (org-at-table-p)]
12378 ["Move Row Down" org-metadown (org-at-table-p)]
12379 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12380 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12381 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12382 "--"
12383 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
12384 ("Rectangle"
12385 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12386 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12387 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12388 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12389 "--"
12390 ("Calculate"
12391 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12392 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12393 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12394 "--"
12395 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12396 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12397 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12398 "--"
12399 ["Sum Column/Rectangle" org-table-sum
12400 (or (org-at-table-p) (org-region-active-p))]
12401 ["Which Column?" org-table-current-column (org-at-table-p)])
12402 ["Debug Formulas"
12403 (setq org-table-formula-debug (not org-table-formula-debug))
12404 :style toggle :selected org-table-formula-debug]
12405 "--"
12406 ["Invisible Vlines" org-table-toggle-vline-visibility
12407 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
12408 "--"
12409 ["Create" org-table-create (and (not (org-at-table-p))
12410 org-enable-table-editor)]
12411 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
12412 ["Import from File" org-table-import (not (org-at-table-p))]
12413 ["Export to File" org-table-export (org-at-table-p)]
12414 "--"
12415 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12416
12417 (easy-menu-define org-org-menu org-mode-map "Org menu"
12418 '("Org"
12419 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
12420 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
12421 ["Sparse Tree" org-occur t]
12422 ["Show All" show-all t]
12423 "--"
12424 ["New Heading" org-insert-heading t]
12425 ("Navigate Headings"
12426 ["Up" outline-up-heading t]
12427 ["Next" outline-next-visible-heading t]
12428 ["Previous" outline-previous-visible-heading t]
12429 ["Next Same Level" outline-forward-same-level t]
12430 ["Previous Same Level" outline-backward-same-level t]
12431 "--"
12432 ["Jump" org-goto t])
12433 ("Edit Structure"
12434 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12435 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12436 "--"
12437 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12438 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12439 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12440 "--"
12441 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12442 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12443 ["Demote Heading" org-metaright (not (org-at-table-p))]
12444 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12445 "--"
12446 ["Archive Subtree" org-archive-subtree t]
12447 "--"
12448 ["Convert to odd levels" org-convert-to-odd-levels t]
12449 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12450 "--"
12451 ("TODO Lists"
12452 ["TODO/DONE/-" org-todo t]
12453 ["Show TODO Tree" org-show-todo-tree t]
12454 ["Global TODO list" org-todo-list t]
12455 "--"
12456 ["Set Priority" org-priority t]
12457 ["Priority Up" org-shiftup t]
12458 ["Priority Down" org-shiftdown t])
12459 ("Dates and Scheduling"
12460 ["Timestamp" org-time-stamp t]
12461 ["Timestamp (inactive)" org-time-stamp-inactive t]
12462 ("Change Date"
12463 ["1 Day Later" org-timestamp-up-day t]
12464 ["1 Day Earlier" org-timestamp-down-day t]
12465 ["1 ... Later" org-shiftup t]
12466 ["1 ... Earlier" org-shiftdown t])
12467 ["Compute Time Range" org-evaluate-time-range t]
12468 ["Schedule Item" org-schedule t]
12469 ["Deadline" org-deadline t]
12470 "--"
12471 ["Goto Calendar" org-goto-calendar t]
12472 ["Date from Calendar" org-date-from-calendar t])
12473 "--"
12474 ["Agenda Command" org-agenda t]
12475 ("File List for Agenda")
12476 ("Special views current file"
12477 ["TODO Tree" org-show-todo-tree t]
12478 ["Check Deadlines" org-check-deadlines t]
12479 ["Timeline" org-timeline t]
12480 ["Tags Tree" org-tags-sparse-tree t])
12481 "--"
12482 ("Hyperlinks"
12483 ["Store Link (Global)" org-store-link t]
12484 ["Insert Link" org-insert-link t]
12485 ["Follow Link" org-open-at-point t])
12486 "--"
12487 ("Export"
12488 ["ASCII" org-export-as-ascii t]
12489 ["Extract Visible Text" org-export-copy-visible t]
12490 ["HTML" org-export-as-html t]
12491 ["HTML and Open" org-export-as-html-and-open t]
12492 ; ["OPML" org-export-as-opml nil]
12493 "--"
12494 ["iCalendar this file" org-export-icalendar-this-file t]
12495 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
12496 :active t :keys "C-c C-x C-i"]
12497 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
12498 "--"
12499 ["Option Template" org-insert-export-options-template t]
12500 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
12501 "--"
12502 ("Documentation"
12503 ["Show Version" org-version t]
12504 ["Info Documentation" org-info t])
12505 ("Customize"
12506 ["Browse Org Group" org-customize t]
12507 "--"
12508 ["Build Full Customize Menu" org-create-customize-menu
12509 (fboundp 'customize-menu-create)])
12510 "--"
12511 ["Refresh setup" org-mode-restart t]
12512 ))
12513
12514 (defun org-info (&optional node)
12515 "Read documentation for Org-mode in the info system.
12516 With optional NODE, go directly to that node."
12517 (interactive)
12518 (require 'info)
12519 (Info-goto-node (format "(org)%s" (or node ""))))
12520
12521 (defun org-install-agenda-files-menu ()
12522 (easy-menu-change
12523 '("Org") "File List for Agenda"
12524 (append
12525 (list
12526 ["Edit File List" (customize-variable 'org-agenda-files) t]
12527 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12528 ["Remove Current File from List" org-remove-file t]
12529 ["Cycle through agenda files" org-cycle-agenda-files t]
12530 "--")
12531 (mapcar 'org-file-menu-entry org-agenda-files))))
12532
12533 ;;; Documentation
12534
12535 (defun org-customize ()
12536 "Call the customize function with org as argument."
12537 (interactive)
12538 (customize-browse 'org))
12539
12540 (defun org-create-customize-menu ()
12541 "Create a full customization menu for Org-mode, insert it into the menu."
12542 (interactive)
12543 (if (fboundp 'customize-menu-create)
12544 (progn
12545 (easy-menu-change
12546 '("Org") "Customize"
12547 `(["Browse Org group" org-customize t]
12548 "--"
12549 ,(customize-menu-create 'org)
12550 ["Set" Custom-set t]
12551 ["Save" Custom-save t]
12552 ["Reset to Current" Custom-reset-current t]
12553 ["Reset to Saved" Custom-reset-saved t]
12554 ["Reset to Standard Settings" Custom-reset-standard t]))
12555 (message "\"Org\"-menu now contains full customization menu"))
12556 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12557
12558 ;;; Miscellaneous stuff
12559
12560 (defun org-move-line-down (arg)
12561 "Move the current line down. With prefix argument, move it past ARG lines."
12562 (interactive "p")
12563 (let ((col (current-column))
12564 beg end pos)
12565 (beginning-of-line 1) (setq beg (point))
12566 (beginning-of-line 2) (setq end (point))
12567 (beginning-of-line (+ 1 arg))
12568 (setq pos (move-marker (make-marker) (point)))
12569 (insert (delete-and-extract-region beg end))
12570 (goto-char pos)
12571 (move-to-column col)))
12572
12573 (defun org-move-line-up (arg)
12574 "Move the current line up. With prefix argument, move it past ARG lines."
12575 (interactive "p")
12576 (let ((col (current-column))
12577 beg end pos)
12578 (beginning-of-line 1) (setq beg (point))
12579 (beginning-of-line 2) (setq end (point))
12580 (beginning-of-line (- arg))
12581 (setq pos (move-marker (make-marker) (point)))
12582 (insert (delete-and-extract-region beg end))
12583 (goto-char pos)
12584 (move-to-column col)))
12585
12586 ;; Paragraph filling stuff.
12587 ;; We want this to be just right, so use the full arsenal.
12588 ;; FIXME: This very likely does not work correctly for XEmacs, because the
12589 ;; filladapt package works slightly differently.
12590
12591 (defun org-set-autofill-regexps ()
12592 (interactive)
12593 ;; In the paragraph separator we include headlines, because filling
12594 ;; text in a line directly attached to a headline would otherwise
12595 ;; fill the headline as well.
12596 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
12597 ;; The paragraph starter includes hand-formatted lists.
12598 (set (make-local-variable 'paragraph-start)
12599 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
12600 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
12601 ;; But only if the user has not turned off tables or fixed-width regions
12602 (set (make-local-variable 'auto-fill-inhibit-regexp)
12603 (concat "\\*\\|#"
12604 (if (or org-enable-table-editor org-enable-fixed-width-editor)
12605 (concat
12606 "\\|[ \t]*["
12607 (if org-enable-table-editor "|" "")
12608 (if org-enable-fixed-width-editor ":" "")
12609 "]"))))
12610 ;; We use our own fill-paragraph function, to make sure that tables
12611 ;; and fixed-width regions are not wrapped. That function will pass
12612 ;; through to `fill-paragraph' when appropriate.
12613 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
12614 ;; Adaptive filling: To get full control, first make sure that
12615 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
12616 (setq adaptive-fill-regexp "\000")
12617 (setq adaptive-fill-function 'org-adaptive-fill-function))
12618
12619 (defun org-fill-paragraph (&optional justify)
12620 "Re-align a table, pass through to fill-paragraph if no table."
12621 (let ((table-p (org-at-table-p))
12622 (table.el-p (org-at-table.el-p)))
12623 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
12624 (table.el-p t) ; skip table.el tables
12625 (table-p (org-table-align) t) ; align org-mode tables
12626 (t nil)))) ; call paragraph-fill
12627
12628 ;; For reference, this is the default value of adaptive-fill-regexp
12629 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
12630
12631 (defun org-adaptive-fill-function ()
12632 "Return a fill prefix for org-mode files.
12633 In particular, this makes sure hanging paragraphs for hand-formatted lists
12634 work correctly."
12635 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
12636 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
12637
12638 ;; Functions needed for Emacs/XEmacs region compatibility
12639
12640 (defun org-add-hook (hook function &optional append local)
12641 "Add-hook, compatible with both Emacsen."
12642 (if (and local org-xemacs-p)
12643 (add-local-hook hook function append)
12644 (add-hook hook function append local)))
12645
12646 (defun org-region-active-p ()
12647 "Is `transient-mark-mode' on and the region active?
12648 Works on both Emacs and XEmacs."
12649 (if org-ignore-region
12650 nil
12651 (if org-xemacs-p
12652 (and zmacs-regions (region-active-p))
12653 (and transient-mark-mode mark-active))))
12654
12655 (defun org-add-to-invisibility-spec (arg)
12656 "Add elements to `buffer-invisibility-spec'.
12657 See documentation for `buffer-invisibility-spec' for the kind of elements
12658 that can be added."
12659 (cond
12660 ((fboundp 'add-to-invisibility-spec)
12661 (add-to-invisibility-spec arg))
12662 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
12663 (setq buffer-invisibility-spec (list arg)))
12664 (t
12665 (setq buffer-invisibility-spec
12666 (cons arg buffer-invisibility-spec)))))
12667
12668 (defun org-remove-from-invisibility-spec (arg)
12669 "Remove elements from `buffer-invisibility-spec'."
12670 (if (fboundp 'remove-from-invisibility-spec)
12671 (remove-from-invisibility-spec arg)
12672 (if (consp buffer-invisibility-spec)
12673 (setq buffer-invisibility-spec
12674 (delete arg buffer-invisibility-spec)))))
12675
12676 (defun org-in-invisibility-spec-p (arg)
12677 "Is ARG a member of `buffer-invisibility-spec'?"
12678 (if (consp buffer-invisibility-spec)
12679 (member arg buffer-invisibility-spec)
12680 nil))
12681
12682 (defun org-image-file-name-regexp ()
12683 "Return regexp matching the file names of images."
12684 (if (fboundp 'image-file-name-regexp)
12685 (image-file-name-regexp)
12686 (let ((image-file-name-extensions
12687 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
12688 "xbm" "xpm" "pbm" "pgm" "ppm")))
12689 (concat "\\."
12690 (regexp-opt (nconc (mapcar 'upcase
12691 image-file-name-extensions)
12692 image-file-name-extensions)
12693 t)
12694 "\\'"))))
12695
12696 ;; Functions needed for compatibility with old outline.el.
12697
12698 ;; Programming for the old outline.el (that uses selective display
12699 ;; instead of `invisible' text properties) is a nightmare, mostly
12700 ;; because regular expressions can no longer be anchored at
12701 ;; beginning/end of line. Therefore a number of function need special
12702 ;; treatment when the old outline.el is being used.
12703
12704 ;; The following functions capture almost the entire compatibility code
12705 ;; between the different versions of outline-mode. The only other
12706 ;; places where this is important are the font-lock-keywords, and in
12707 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
12708
12709 ;; C-a should go to the beginning of a *visible* line, also in the
12710 ;; new outline.el. I guess this should be patched into Emacs?
12711 (defun org-beginning-of-line ()
12712 "Go to the beginning of the current line. If that is invisible, continue
12713 to a visible line beginning. This makes the function of C-a more intuitive."
12714 (interactive)
12715 (beginning-of-line 1)
12716 (if (bobp)
12717 nil
12718 (backward-char 1)
12719 (if (org-invisible-p)
12720 (while (and (not (bobp)) (org-invisible-p))
12721 (backward-char 1)
12722 (beginning-of-line 1))
12723 (forward-char 1))))
12724
12725 (when org-noutline-p
12726 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
12727 ;; FIXME: should I use substitute-key-definition to reach other bindings
12728 ;; of beginning-of-line?
12729
12730 (defun org-invisible-p ()
12731 "Check if point is at a character currently not visible."
12732 (if org-noutline-p
12733 ;; Early versions of noutline don't have `outline-invisible-p'.
12734 (if (fboundp 'outline-invisible-p)
12735 (outline-invisible-p)
12736 (get-char-property (point) 'invisible))
12737 (save-excursion
12738 (skip-chars-backward "^\r\n")
12739 (equal (char-before) ?\r))))
12740
12741 (defun org-invisible-p2 ()
12742 "Check if point is at a character currently not visible."
12743 (save-excursion
12744 (if org-noutline-p
12745 (progn
12746 (if (and (eolp) (not (bobp))) (backward-char 1))
12747 ;; Early versions of noutline don't have `outline-invisible-p'.
12748 (if (fboundp 'outline-invisible-p)
12749 (outline-invisible-p)
12750 (get-char-property (point) 'invisible)))
12751 (skip-chars-backward "^\r\n")
12752 (equal (char-before) ?\r))))
12753
12754 (defun org-back-to-heading (&optional invisible-ok)
12755 "Move to previous heading line, or beg of this line if it's a heading.
12756 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
12757 (if org-noutline-p
12758 (outline-back-to-heading invisible-ok)
12759 (if (and (memq (char-before) '(?\n ?\r))
12760 (looking-at outline-regexp))
12761 t
12762 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
12763 outline-regexp)
12764 nil t)
12765 (if invisible-ok
12766 (progn (goto-char (match-end 1))
12767 (looking-at outline-regexp)))
12768 (error "Before first heading")))))
12769
12770 (defun org-on-heading-p (&optional invisible-ok)
12771 "Return t if point is on a (visible) heading line.
12772 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12773 (if org-noutline-p
12774 (outline-on-heading-p 'invisible-ok)
12775 (save-excursion
12776 (skip-chars-backward "^\n\r")
12777 (and (looking-at outline-regexp)
12778 (or invisible-ok
12779 (bobp)
12780 (equal (char-before) ?\n))))))
12781
12782 (defun org-on-target-p ()
12783 (let ((pos (point)))
12784 (save-excursion
12785 (skip-chars-forward "<")
12786 (and (re-search-backward "<<" nil t)
12787 (or (looking-at org-target-regexp)
12788 (looking-at org-radio-target-regexp))
12789 (<= (match-beginning 0) pos)
12790 (>= (match-end 0) pos)))))
12791
12792 (defun org-up-heading-all (arg)
12793 "Move to the heading line of which the present line is a subheading.
12794 This function considers both visible and invisible heading lines.
12795 With argument, move up ARG levels."
12796 (if org-noutline-p
12797 (if (fboundp 'outline-up-heading-all)
12798 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12799 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12800 (org-back-to-heading t)
12801 (looking-at outline-regexp)
12802 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12803 (error "Cannot move up %d levels" arg)
12804 (re-search-backward
12805 (concat "[\n\r]" (regexp-quote
12806 (make-string (- (match-end 0) (match-beginning 0) arg)
12807 ?*))
12808 "[^*]"))
12809 (forward-char 1))))
12810
12811 (defun org-show-hidden-entry ()
12812 "Show an entry where even the heading is hidden."
12813 (save-excursion
12814 (if (not org-noutline-p)
12815 (progn
12816 (org-back-to-heading t)
12817 (org-flag-heading nil)))
12818 (org-show-entry)))
12819
12820 (defun org-check-occur-regexp (regexp)
12821 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12822 Of course, only for the old outline mode."
12823 (if org-noutline-p
12824 regexp
12825 (if (string-match "^\\^" regexp)
12826 (concat "[\n\r]" (substring regexp 1))
12827 regexp)))
12828
12829 (defun org-flag-heading (flag &optional entry)
12830 "Flag the current heading. FLAG non-nil means make invisible.
12831 When ENTRY is non-nil, show the entire entry."
12832 (save-excursion
12833 (org-back-to-heading t)
12834 (if (not org-noutline-p)
12835 ;; Make the current headline visible
12836 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12837 ;; Check if we should show the entire entry
12838 (if entry
12839 (progn
12840 (org-show-entry)
12841 (save-excursion ;; FIXME: Is this the fix for points in the -|
12842 ;; middle of text? |
12843 (and (outline-next-heading) ;; |
12844 (org-flag-heading nil)))) ; show the next heading _|
12845 (outline-flag-region (max 1 (1- (point)))
12846 (save-excursion (outline-end-of-heading) (point))
12847 (if org-noutline-p
12848 flag
12849 (if flag ?\r ?\n))))))
12850
12851 (defun org-end-of-subtree (&optional invisible-OK)
12852 ;; This is an exact copy of the original function, but it uses
12853 ;; `org-back-to-heading', to make it work also in invisible
12854 ;; trees. And is uses an invisible-OK argument.
12855 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
12856 (org-back-to-heading invisible-OK)
12857 (let ((first t)
12858 (level (funcall outline-level)))
12859 (while (and (not (eobp))
12860 (or first (> (funcall outline-level) level)))
12861 (setq first nil)
12862 (outline-next-heading))
12863 (if (memq (preceding-char) '(?\n ?\^M))
12864 (progn
12865 ;; Go to end of line before heading
12866 (forward-char -1)
12867 (if (memq (preceding-char) '(?\n ?\^M))
12868 ;; leave blank line before heading
12869 (forward-char -1))))))
12870
12871 (defun org-show-subtree ()
12872 "Show everything after this heading at deeper levels."
12873 (outline-flag-region
12874 (point)
12875 (save-excursion
12876 (outline-end-of-subtree) (outline-next-heading) (point))
12877 (if org-noutline-p nil ?\n)))
12878
12879 (defun org-show-entry ()
12880 "Show the body directly following this heading.
12881 Show the heading too, if it is currently invisible."
12882 (interactive)
12883 (save-excursion
12884 (org-back-to-heading t)
12885 (outline-flag-region
12886 (1- (point))
12887 (save-excursion
12888 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12889 (or (match-beginning 1) (point-max)))
12890 (if org-noutline-p nil ?\n))))
12891
12892
12893 (defun org-make-options-regexp (kwds)
12894 "Make a regular expression for keyword lines."
12895 (concat
12896 (if org-noutline-p "^" "[\n\r]")
12897 "#?[ \t]*\\+\\("
12898 (mapconcat 'regexp-quote kwds "\\|")
12899 "\\):[ \t]*"
12900 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12901
12902 ;; Make `bookmark-jump' show the jump location if it was hidden.
12903 (eval-after-load "bookmark"
12904 '(if (boundp 'bookmark-after-jump-hook)
12905 ;; We can use the hook
12906 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12907 ;; Hook not available, use advice
12908 (defadvice bookmark-jump (after org-make-visible activate)
12909 "Make the position visible."
12910 (org-bookmark-jump-unhide))))
12911
12912 (defun org-bookmark-jump-unhide ()
12913 "Unhide the current position, to show the bookmark location."
12914 (and (eq major-mode 'org-mode)
12915 (or (org-invisible-p)
12916 (save-excursion (goto-char (max (point-min) (1- (point))))
12917 (org-invisible-p)))
12918 (org-show-hierarchy-above)))
12919
12920 ;;; Finish up
12921
12922 (provide 'org)
12923
12924 (run-hooks 'org-load-hook)
12925
12926 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12927 ;;; org.el ends here
12928