]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-agenda-custom-commands): New option.
[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 Free Software Foundation
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.01
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:
83 ;; -------
84 ;; Version 4.01
85 ;; - Tags can also be set remotely from agenda buffer.
86 ;; - Boolean logic for tag searches.
87 ;; - Additional agenda commands can be configured through the variable
88 ;; `org-agenda-custom-commands'.
89 ;; - Minor bug fixes.
90 ;;
91 ;; Version 4.00
92 ;; - Headlines can contain TAGS, and Org-mode can produced a list
93 ;; of matching headlines based on a TAG search expression.
94 ;; - `org-agenda' has now become a dispatcher that will produce the agenda
95 ;; and other views on org-mode data with an additional keypress.
96 ;;
97 ;; Version 3.24
98 ;; - Switching and item to DONE records a time stamp when the variable
99 ;; `org-log-done' is turned on. Default is off.
100 ;;
101 ;; Version 3.23
102 ;; - M-RET makes new items as well as new headings.
103 ;; - Various small bug fixes
104 ;;
105 ;; Version 3.22
106 ;; - CamelCase words link to other locations in the same file.
107 ;; - File links accept search options, to link to specific locations.
108 ;; - Plain list items can be folded with `org-cycle'. See new option
109 ;; `org-cycle-include-plain-lists'.
110 ;; - Sparse trees for specific TODO keywords through numeric prefix
111 ;; argument to `C-c C-v'.
112 ;; - Global TODO list, also for specific keywords.
113 ;; - Matches in sparse trees are highlighted (highlights disappear with
114 ;; next buffer change due to editing).
115 ;;
116 ;; Version 3.21
117 ;; - Improved CSS support for the HTML export. Thanks to Christian Egli.
118 ;; - Editing support for hand-formatted lists
119 ;; - M-S-cursor keys handle plain list items
120 ;; - C-c C-c renumbers ordered plain lists
121 ;;
122 ;; Version 3.20
123 ;; - There is finally an option to make TAB jump over horizontal lines
124 ;; in tables instead of creating a new line before that line.
125 ;; The option is `org-table-tab-jumps-over-hlines', default nil.
126 ;; - New command for sorting tables, on `C-c ^'.
127 ;; - Changes to the HTML exporter
128 ;; - hand-formatted lists are exported correctly, similar to
129 ;; markdown lists. Nested lists are possible. See the docstring
130 ;; of the variable `org-export-plain-list-max-depth'.
131 ;; - cleaned up to produce valid HTML 4.0 (transitional).
132 ;; - support for cascading style sheets.
133 ;; - New command to cycle through all agenda files, on C-,
134 ;; - C-c [ can now also be used to change the sequence of agenda files.
135 ;;
136 ;; Version 3.19
137 ;; - Bug fixes
138 ;;
139 ;; Version 3.18
140 ;; - Export of calendar information in the standard iCalendar format.
141 ;; - Some bug fixes.
142 ;;
143 ;; Version 3.17
144 ;; - HTML export specifies character set depending on coding-system.
145 ;;
146 ;; Version 3.16
147 ;; - In tables, directly after the field motion commands like TAB and RET,
148 ;; typing a character will blank the field. Can be turned off with
149 ;; variable `org-table-auto-blank-field'.
150 ;; - Inactive timestamps with `C-c !'. These do not trigger the agenda
151 ;; and are not linked to the calendar.
152 ;; - Additional key bindings to allow Org-mode to function on a tty emacs.
153 ;; - `C-c C-h' prefix key replaced by `C-c C-x', and `C-c C-x C-h' replaced
154 ;; by `C-c C-x b' (b=Browser). This was necessary to recover the
155 ;; standard meaning of C-h after a prefix key (show prefix bindings).
156 ;;
157 ;; Version 3.15
158 ;; - QUOTE keyword at the beginning of an entry causes fixed-width export
159 ;; of unmodified entry text. `C-c :' toggles this keyword.
160 ;; - New face `org-special-keyword' which is used for COMMENT, QUOTE,
161 ;; DEADLINE and SCHEDULED, and priority cookies. Default is only a weak
162 ;; color, to reduce the amount of aggressive color in the buffer.
163 ;;
164 ;; Version 3.14
165 ;; - Formulas for individual fields in table.
166 ;; - Automatic recalculation in calculating tables.
167 ;; - Named fields and columns in tables.
168 ;; - Fixed bug with calling `org-archive' several times in a row.
169 ;;
170 ;; Version 3.13
171 ;; - Efficiency improvements: Fewer table re-alignments needed.
172 ;; - New special lines in tables, for defining names for individual cells.
173 ;;
174 ;; Version 3.12
175 ;; - Tables can store formulas (one per column) and compute fields.
176 ;; Not quite like a full spreadsheet, but very powerful.
177 ;; - table.el keybinding is now `C-c ~'.
178 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
179 ;; - Small changes to keys in agenda buffer. Affected keys:
180 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
181 ;; - Bug fixes.
182 ;;
183 ;; Version 3.11
184 ;; - Links inserted with C-c C-l are now by default enclosed in angle
185 ;; brackets. See the new variable `org-link-format'.
186 ;; - ">" terminates a link, this is a way to have several links in a line.
187 ;; Both "<" and ">" are no longer allowed as characters in a link.
188 ;; - Archiving of finished tasks.
189 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
190 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
191 ;; - Compatibility problems with viper-mode fixed.
192 ;; - Improved html export of tables.
193 ;; - Various clean-up changes.
194 ;;
195 ;; Version 3.10
196 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
197 ;;
198 ;; Version 3.09
199 ;; - Time-of-day specifications in agenda are extracted and placed
200 ;; into the prefix. Timed entries can be placed into a time grid for
201 ;; day.
202 ;;
203 ;; Version 3.08
204 ;; - "|" no longer allowed as part of a link, to allow links in tables.
205 ;; - The prefix of items in the agenda buffer can be configured.
206 ;; - Cleanup.
207 ;;
208 ;; Version 3.07
209 ;; - Some folding inconsistencies removed.
210 ;; - BBDB links to company-only entries.
211 ;; - Bug fixes and global cleanup.
212 ;;
213 ;; Version 3.06
214 ;; - M-S-RET inserts a new TODO heading.
215 ;; - New startup option `content'.
216 ;; - Better visual response when TODO items in agenda change status.
217 ;; - Window positioning after visibility state changes optimized and made
218 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
219 ;;
220 ;; Version 3.05
221 ;; - Agenda entries from the diary are linked to the diary file, so
222 ;; adding and editing diary entries can be done directly from the agenda.
223 ;; - Many calendar/diary commands available directly from agenda.
224 ;; - Field copying in tables with S-RET does increment.
225 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
226 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
227 ;;
228 ;; Version 3.04
229 ;; - Table editor optimized to need fewer realignments, and to keep
230 ;; table shape when typing in fields.
231 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
232 ;; into arbitrary major modes.
233 ;; - Fixed bug with realignment in XEmacs.
234 ;; - Startup options can be set with special #+STARTUP line.
235 ;; - Heading following a match in org-occur can be suppressed.
236 ;;
237 ;; Version 3.03
238 ;; - Copyright transfer to the FSF.
239 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
240 ;; - Timeline now always contains today, and `.' jumps to it.
241 ;; - Table editor:
242 ;; - cut and paste of rectangular regions in tables
243 ;; - command to convert org-mode table to table.el table and back
244 ;; - command to treat several cells like a paragraph and fill it
245 ;; - command to convert a buffer region to a table
246 ;; - import/export tables as tab-separated files (exchange with Excel)
247 ;; - Agenda:
248 ;; - Sorting mechanism for agenda items rewritten from scratch.
249 ;; - Sorting fully configurable.
250 ;; - Entries specifying a time are sorted together.
251 ;; - Completion also covers option keywords after `#-'.
252 ;; - Bug fixes.
253 ;;
254 ;; Version 3.01
255 ;; - New reference card, thanks to Philip Rooke for creating it.
256 ;; - Single file agenda renamed to "Timeline". It no longer shows
257 ;; warnings about upcoming deadlines/overdue scheduled items.
258 ;; That functionality is now limited to the (multifile) agenda.
259 ;; - When reading a date, the calendar can be manipulated with keys.
260 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
261 ;; - Minor bug fixes and documentation improvements.
262
263 ;;; Code:
264
265 (eval-when-compile (require 'cl) (require 'calendar))
266 (require 'outline)
267 (require 'time-date)
268 (require 'easymenu)
269
270 (defvar calc-embedded-close-formula)
271 (defvar calc-embedded-open-formula)
272 (defvar font-lock-unfontify-region-function)
273
274 ;;; Customization variables
275
276 (defvar org-version "4.01"
277 "The version number of the file org.el.")
278 (defun org-version ()
279 (interactive)
280 (message "Org-mode version %s" org-version))
281
282 ;; The following two constants are for compatibility with different Emacs
283 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
284 ;; The compatibility code in org.el is based on these two constants.
285 (defconst org-xemacs-p (featurep 'xemacs)
286 "Are we running xemacs?")
287 (defconst org-noutline-p (featurep 'noutline)
288 "Are we using the new outline mode?")
289
290 (defgroup org nil
291 "Outline-based notes management and organizer "
292 :tag "Org"
293 :group 'outlines
294 :group 'hypermedia
295 :group 'calendar)
296
297 (defgroup org-startup nil
298 "Options concerning startup of Org-mode."
299 :tag "Org Startup"
300 :group 'org)
301
302 (defcustom org-CUA-compatible nil
303 "Non-nil means use alternative key bindings for S-<cursor movement>.
304 Org-mode used S-<cursor movement> for changing timestamps and priorities.
305 S-<cursor movement> is also used for example by `CUA-mode' to select text.
306 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
307 alternative bindings. Setting this variable to t will replace the following
308 keys both in Org-mode and in the Org-agenda buffer.
309
310 S-RET -> C-S-RET
311 S-up -> M-p
312 S-down -> M-n
313 S-left -> M--
314 S-right -> M-+
315
316 If you do not like the alternative keys, take a look at the variable
317 `org-disputed-keys'.
318
319 This option is only relevant at load-time of Org-mode. Changing it requires
320 a restart of Emacs to become effective."
321 :group 'org-startup
322 :type 'boolean)
323
324 (defvar org-disputed-keys
325 '((S-up [(shift up)] [(meta ?p)])
326 (S-down [(shift down)] [(meta ?n)])
327 (S-left [(shift left)] [(meta ?-)])
328 (S-right [(shift right)] [(meta ?+)])
329 (S-return [(shift return)] [(control shift return)]))
330 "Keys for which Org-mode and other modes compete.
331 This is an alist, cars are symbols for lookup, 1st element is the default key,
332 second element will be used when `org-CUA-compatible' is t.")
333
334 (defun org-key (key)
335 "Select a key according to `org-CUA-compatible'."
336 (nth (if org-CUA-compatible 2 1)
337 (or (assq key org-disputed-keys)
338 (error "Invalid Key %s in `org-key'" key))))
339
340 (defcustom org-startup-folded t
341 "Non-nil means, entering Org-mode will switch to OVERVIEW.
342 This can also be configured on a per-file basis by adding one of
343 the following lines anywhere in the buffer:
344
345 #+STARTUP: fold
346 #+STARTUP: nofold
347 #+STARTUP: content"
348 :group 'org-startup
349 :type '(choice
350 (const :tag "nofold: show all" nil)
351 (const :tag "fold: overview" t)
352 (const :tag "content: all headlines" content)))
353
354 (defcustom org-startup-truncated t
355 "Non-nil means, entering Org-mode will set `truncate-lines'.
356 This is useful since some lines containing links can be very long and
357 uninteresting. Also tables look terrible when wrapped."
358 :group 'org-startup
359 :type 'boolean)
360
361 (defcustom org-startup-with-deadline-check nil
362 "Non-nil means, entering Org-mode will run the deadline check.
363 This means, if you start editing an org file, you will get an
364 immediate reminder of any due deadlines.
365 This can also be configured on a per-file basis by adding one of
366 the following lines anywhere in the buffer:
367
368 #+STARTUP: dlcheck
369 #+STARTUP: nodlcheck"
370 :group 'org-startup
371 :type 'boolean)
372
373 (defcustom org-insert-mode-line-in-empty-file nil
374 "Non-nil means insert the first line setting Org-mode in empty files.
375 When the function `org-mode' is called interactively in an empty file, this
376 normally means that the file name does not automatically trigger Org-mode.
377 To ensure that the file will always be in Org-mode in the future, a
378 line enforcing Org-mode will be inserted into the buffer, if this option
379 has been set."
380 :group 'org-startup
381 :type 'boolean)
382
383 (defgroup org-keywords nil
384 "Options concerning TODO items in Org-mode."
385 :tag "Org Keywords"
386 :group 'org)
387
388 (defcustom org-todo-keywords '("TODO" "DONE")
389 "List of TODO entry keywords.
390 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
391 considered to mean that the entry is \"done\". All the other mean that
392 action is required, and will make the entry show up in todo lists, diaries
393 etc.
394 The command \\[org-todo] cycles an entry through these states, and an
395 additional state where no keyword is present. For details about this
396 cycling, see also the variable `org-todo-interpretation'
397 Changes become only effective after restarting Emacs."
398 :group 'org-keywords
399 :type '(repeat (string :tag "Keyword")))
400
401 (defcustom org-todo-interpretation 'sequence
402 "Controls how TODO keywords are interpreted.
403 \\<org-mode-map>Possible values are `sequence' and `type'.
404 This variable is only relevant if `org-todo-keywords' contains more than two
405 states. There are two ways how these keywords can be used:
406
407 - As a sequence in the process of working on a TODO item, for example
408 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
409 org-todo-interpretation 'sequence)
410
411 - As different types of TODO items, for example
412 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
413 org-todo-interpretation 'type)
414
415 When the states are interpreted as a sequence, \\[org-todo] always cycles
416 to the next state, in order to walk through all different states. So with
417 \\[org-todo], you turn an empty entry into the state TODO. When you started
418 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
419 later to VERIFY and finally to DONE.
420
421 When the states are interpreted as types, \\[org-todo] still cycles through
422 when it is called several times in direct succession, in order to initially
423 select the type. However, if not called immediately after a previous
424 \\[org-todo], it switches from each type directly to DONE. So with the
425 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
426 RELAXED. If you later return to this entry and press \\[org-todo] again,
427 RELAXED will not be changed REMIND, but directly to DONE.
428
429 You can create a large number of types. To initially select a
430 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
431 type with completion. Of course, you can also type the keyword
432 directly into the buffer. M-TAB completes TODO keywords at the
433 beginning of a headline."
434 :group 'org-keywords
435 :type '(choice (const sequence)
436 (const type)))
437
438 (defcustom org-default-priority ?B
439 "The default priority of TODO items.
440 This is the priority an item get if no explicit priority is given."
441 :group 'org-keywords
442 :type 'character)
443
444 (defcustom org-lowest-priority ?C
445 "The lowest priority of TODO items. A character like ?A, ?B etc."
446 :group 'org-keywords
447 :type 'character)
448
449 (defcustom org-deadline-string "DEADLINE:"
450 "String to mark deadline entries.
451 A deadline is this string, followed by a time stamp. Should be a word,
452 terminated by a colon. You can insert a schedule keyword and
453 a timestamp with \\[org-deadline].
454 Changes become only effective after restarting Emacs."
455 :group 'org-keywords
456 :type 'string)
457
458 (defcustom org-scheduled-string "SCHEDULED:"
459 "String to mark scheduled TODO entries.
460 A schedule is this string, followed by a time stamp. Should be a word,
461 terminated by a colon. You can insert a schedule keyword and
462 a timestamp with \\[org-schedule].
463 Changes become only effective after restarting Emacs."
464 :group 'org-keywords
465 :type 'string)
466
467 (defcustom org-closed-string "CLOSED:"
468 "String ued as the prefix for timestamps logging closing a TODO entry."
469 :group 'org-keywords
470 :type 'string)
471
472 (defcustom org-comment-string "COMMENT"
473 "Entries starting with this keyword will never be exported.
474 An entry can be toggled between COMMENT and normal with
475 \\[org-toggle-comment].
476 Changes become only effective after restarting Emacs."
477 :group 'org-keywords
478 :type 'string)
479
480 (defcustom org-quote-string "QUOTE"
481 "Entries starting with this keyword will be exported in fixed-width font.
482 Quoting applies only to the text in the entry following the headline, and does
483 not extend beyond the next headline, even if that is lower level.
484 An entry can be toggled between QUOTE and normal with
485 \\[org-toggle-fixed-width-section]"
486 :group 'org-keywords
487 :type 'string)
488
489 (defcustom org-after-todo-state-change-hook nil
490 "Hook which is run after the state of a TODO item was changed.
491 The new state (a string with a todo keyword, or nil) is available in the
492 Lisp variable `state'."
493 :group 'org-keywords
494 :type 'hook)
495
496 ;; Variables for pre-computed regular expressions, all buffer local
497 (defvar org-todo-kwd-priority-p nil
498 "Do TODO items have priorities?")
499 (make-variable-buffer-local 'org-todo-kwd-priority-p)
500 (defvar org-todo-kwd-max-priority nil
501 "Maximum priority of TODO items.")
502 (make-variable-buffer-local 'org-todo-kwd-max-priority)
503 (defvar org-ds-keyword-length 12
504 "Maximum length of the Deadline and SCHEDULED keywords.")
505 (make-variable-buffer-local 'org-ds-keyword-length)
506 (defvar org-done-string nil
507 "The last string in `org-todo-keywords', indicating an item is DONE.")
508 (make-variable-buffer-local 'org-done-string)
509 (defvar org-todo-regexp nil
510 "Matches any of the TODO state keywords.")
511 (make-variable-buffer-local 'org-todo-regexp)
512 (defvar org-not-done-regexp nil
513 "Matches any of the TODO state keywords except the last one.")
514 (make-variable-buffer-local 'org-not-done-regexp)
515 (defvar org-todo-line-regexp nil
516 "Matches a headline and puts TODO state into group 2 if present.")
517 (make-variable-buffer-local 'org-todo-line-regexp)
518 (defvar org-nl-done-regexp nil
519 "Matches newline followed by a headline with the DONE keyword.")
520 (make-variable-buffer-local 'org-nl-done-regexp)
521 (defvar org-looking-at-done-regexp nil
522 "Matches the DONE keyword a point.")
523 (make-variable-buffer-local 'org-looking-at-done-regexp)
524 (defvar org-deadline-regexp nil
525 "Matches the DEADLINE keyword.")
526 (make-variable-buffer-local 'org-deadline-regexp)
527 (defvar org-deadline-time-regexp nil
528 "Matches the DEADLINE keyword together with a time stamp.")
529 (make-variable-buffer-local 'org-deadline-time-regexp)
530 (defvar org-deadline-line-regexp nil
531 "Matches the DEADLINE keyword and the rest of the line.")
532 (make-variable-buffer-local 'org-deadline-line-regexp)
533 (defvar org-scheduled-regexp nil
534 "Matches the SCHEDULED keyword.")
535 (make-variable-buffer-local 'org-scheduled-regexp)
536 (defvar org-scheduled-time-regexp nil
537 "Matches the SCHEDULED keyword together with a time stamp.")
538 (make-variable-buffer-local 'org-scheduled-time-regexp)
539
540 (defvar org-category nil
541 "Variable used by org files to set a category for agenda display.
542 Such files should use a file variable to set it, for example
543
544 -*- mode: org; org-category: \"ELisp\"
545
546 or contain a special line
547
548 #+CATEGORY: ELisp
549
550 If the file does not specify a category, then file's base name
551 is used instead.")
552 (make-variable-buffer-local 'org-category)
553
554 (defgroup org-time nil
555 "Options concerning time stamps and deadlines in Org-mode."
556 :tag "Org Time"
557 :group 'org)
558
559 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
560 "Formats for `format-time-string' which are used for time stamps.
561 It is not recommended to change this constant.")
562
563
564 (defcustom org-deadline-warning-days 30
565 "No. of days before expiration during which a deadline becomes active.
566 This variable governs the display in the org file."
567 :group 'org-time
568 :type 'number)
569
570 (defcustom org-popup-calendar-for-date-prompt t
571 "Non-nil means, pop up a calendar when prompting for a date.
572 In the calendar, the date can be selected with mouse-1. However, the
573 minibuffer will also be active, and you can simply enter the date as well.
574 When nil, only the minibuffer will be available."
575 :group 'org-time
576 :type 'number)
577
578 (defcustom org-calendar-follow-timestamp-change t
579 "Non-nil means, make the calendar window follow timestamp changes.
580 When a timestamp is modified and the calendar window is visible, it will be
581 moved to the new date."
582 :group 'org-time
583 :type 'boolean)
584
585 (defcustom org-log-done nil
586 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
587 When the state of an entry is changed from nothing to TODO, remove a previous
588 closing date."
589 :group 'org-time
590 :type 'boolean)
591
592 (defgroup org-agenda nil
593 "Options concerning agenda display Org-mode."
594 :tag "Org Agenda"
595 :group 'org)
596
597 (defcustom org-agenda-files nil
598 "A list of org files for agenda/diary display.
599 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
600 \\[org-remove-file]. You can also use customize to edit the list."
601 :group 'org-agenda
602 :type '(repeat file))
603
604 (defcustom org-agenda-custom-commands
605 '(("w" todo "WAITING")
606 ("u" tags "+WORK+URGENT-BOSS"))
607 "Custom commands for the agenda.
608 These commands will be offered on the splash screen displayed by the
609 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
610
611 key The key (as a string) to be associated with the command.
612 type The command type, either `todo' for a todo list with a specific
613 todo keyword, or `tags' for a tags search.
614 match What to search for. Either a TODO keyword, or a tags match query."
615 :group 'org-agenda
616 :type '(repeat
617 (list (string :tag "Key")
618 (choice :tag "Type" (const tags) (const todo))
619 (string :tag "Match"))))
620
621 (defcustom org-select-timeline-window t
622 "Non-nil means, after creating a timeline, move cursor into Timeline window.
623 When nil, cursor will remain in the current window."
624 :group 'org-agenda
625 :type 'boolean)
626
627 (defcustom org-select-agenda-window t
628 "Non-nil means, after creating an agenda, move cursor into Agenda window.
629 When nil, cursor will remain in the current window."
630 :group 'org-agenda
631 :type 'boolean)
632
633 (defcustom org-fit-agenda-window t
634 "Non-nil means, change window size of agenda to fit content."
635 :group 'org-agenda
636 :type 'boolean)
637
638 (defcustom org-agenda-show-all-dates t
639 "Non-nil means, `org-agenda' shows every day in the selected range.
640 When nil, only the days which actually have entries are shown."
641 :group 'org-agenda
642 :type 'boolean)
643
644 ;; FIXME: First day of month works only for current month because it would
645 ;; require a variable ndays treatment.
646 (defcustom org-agenda-start-on-weekday 1
647 "Non-nil means, start the overview always on the specified weekday.
648 0 Denotes Sunday, 1 denotes Monday etc.
649 When nil, always start on the current day."
650 :group 'org-agenda
651 :type '(choice (const :tag "Today" nil)
652 (const :tag "First day of month" t)
653 (number :tag "Weekday No.")))
654
655 (defcustom org-agenda-ndays 7
656 "Number of days to include in overview display."
657 :group 'org-agenda
658 :type 'number)
659
660 (defcustom org-agenda-include-all-todo t
661 "Non-nil means, the agenda will always contain all TODO entries.
662 When nil, date-less entries will only be shown if `org-agenda' is called
663 with a prefix argument.
664 When non-nil, the TODO entries will be listed at the top of the agenda, before
665 the entries for specific days."
666 :group 'org-agenda
667 :type 'boolean)
668
669 (defcustom org-agenda-include-diary nil
670 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
671 :group 'org-agenda
672 :type 'boolean)
673
674 (defcustom org-calendar-to-agenda-key [?c]
675 "The key to be installed in `calendar-mode-map' for switching to the agenda.
676 The command `org-calendar-goto-agenda' will be bound to this key. The
677 default is the character `c' because then`c' can be used to switch back and
678 force between agenda and calendar."
679 :group 'org-agenda
680 :type 'sexp)
681
682 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
683 "Sorting structure for the agenda items of a single day.
684 This is a list of symbols which will be used in sequence to determine
685 if an entry should be listed before another entry. The following
686 symbols are recognized.
687
688 time-up Put entries with time-of-day indications first, early first
689 time-down Put entries with time-of-day indications first, late first
690 category-keep Keep the default order of categories, corresponding to the
691 sequence in `org-agenda-files'.
692 category-up Sort alphabetically by category, A-Z.
693 category-down Sort alphabetically by category, Z-A.
694 priority-up Sort numerically by priority, high priority last.
695 priority-down Sort numerically by priority, high priority first.
696
697 The different possibilities will be tried in sequence, and testing stops
698 if one comparison returns a \"not-equal\". For example, the default
699 '(time-up category-keep priority-down)
700 means: Pull out all entries having a specified time of day and sort them,
701 in order to make a time schedule for the current day the first thing in the
702 agenda listing for the day. Of the entries without a time indication, keep
703 the grouped in categories, don't sort the categories, but keep them in
704 the sequence given in `org-agenda-files'. Within each category sort by
705 priority.
706
707 Leaving out `category-keep' would mean that items will be sorted across
708 categories by priority."
709 :group 'org-agenda
710 :type '(repeat
711 (choice
712 (const time-up)
713 (const time-down)
714 (const category-keep)
715 (const category-up)
716 (const category-down)
717 (const priority-up)
718 (const priority-down))))
719
720 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
721 "Format specification for the prefix of items in the agenda buffer.
722 This format works similar to a printf format, with the following meaning:
723
724 %c the category of the item, \"Diary\" for entries from the diary, or
725 as given by the CATEGORY keyword or derived from the file name.
726 %t the time-of-day specification if one applies to the entry, in the
727 format HH:MM
728 %s Scheduling/Deadline information, a short string
729
730 All specifiers work basically like the standard `%s' of printf, but may
731 contain two additional characters: A question mark just after the `%' and
732 a whitespace/punctuation character just before the final letter.
733
734 If the first character after `%' is a question mark, the entire field
735 will only be included if the corresponding value applies to the
736 current entry. This is useful for fields which should have fixed
737 width when present, but zero width when absent. For example,
738 \"%?-12t\" will result in a 12 character time field if a time of the
739 day is specified, but will completely disappear in entries which do
740 not contain a time.
741
742 If there is punctuation or whitespace character just before the final
743 format letter, this character will be appended to the field value if
744 the value is not empty. For example, the format \"%-12:c\" leads to
745 \"Diary: \" if the category is \"Diary\". If the category were be
746 empty, no additional colon would be interted.
747
748 The default value of this option is \" %-12:c%?-12t% s\", meaning:
749 - Indent the line with two space characters
750 - Give the category in a 12 chars wide field, padded with whitespace on
751 the right (because of `-'). Append a colon if there is a category
752 (because of `:').
753 - If there is a time-of-day, put it into a 12 chars wide field. If no
754 time, don't put in an empty field, just skip it (because of '?').
755 - Finally, put the scheduling information and append a whitespace.
756
757 As another example, if you don't want the time-of-day of entries in
758 the prefix, you could use:
759
760 (setq org-agenda-prefix-format \" %-11:c% s\")
761
762 See also the variable `org-agenda-remove-times-when-in-prefix'."
763 :type 'string
764 :group 'org-agenda)
765
766 (defcustom org-timeline-prefix-format " % s"
767 "Like `org-agenda-prefix-format', but for the timeline of a single file."
768 :type 'string
769 :group 'org-agenda)
770
771 (defvar org-prefix-format-compiled nil
772 "The compiled version of the most recently used prefix format.
773 Depending on which command was used last, this may be the compiled version
774 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
775
776 (defcustom org-agenda-use-time-grid t
777 "Non-nil means, show a time grid in the agenda schedule.
778 A time grid is a set of lines for specific times (like every two hours between
779 8:00 and 20:00. The items scheduled for a day at specific times are
780 sorted in between these lines.
781 For deails about when the grid will be shown, and what it will look like, see
782 the variable `org-agenda-time-grid'."
783 :group 'org-agenda
784 :type 'boolean)
785
786 (defcustom org-agenda-time-grid
787 '((daily today require-timed)
788 "----------------"
789 (800 1000 1200 1400 1600 1800 2000))
790
791 "The settings for time grid for agenda display.
792 This is a list of three items. The first item is again a list. It contains
793 symbols specifying conditions when the grid should be displayed:
794
795 daily if the agenda shows a single day
796 weekly if the agenda shows an entire week
797 today show grid on current date, independent of daily/weekly display
798 require-timed show grid only if at least on item has a time specification
799
800 The second item is a string which will be places behing the grid time.
801
802 The third item is a list of integers, indicating the times that should have
803 a grid line."
804 :group 'org-agenda
805 :type
806 '(list
807 (set :greedy t :tag "Grid Display Options"
808 (const :tag "Show grid in single day agenda display" daily)
809 (const :tag "Show grid in weekly agenda display" weekly)
810 (const :tag "Always show grid for today" today)
811 (const :tag "Show grid only if any timed entries are present"
812 require-timed)
813 (const :tag "Skip grid times already present in an entry"
814 remove-match))
815 (string :tag "Grid String")
816 (repeat :tag "Grid Times" (integer :tag "Time"))))
817
818 (defcustom org-agenda-remove-times-when-in-prefix t
819 "Non-nil means, remove duplicate time specifications in agenda items.
820 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
821 time-of-day specification in a headline or diary entry is extracted and
822 placed into the prefix. If this option is non-nil, the original specification
823 \(a timestamp or -range, or just a plain time(range) specification like
824 11:30-4pm) will be removed for agenda display. This makes the agenda less
825 cluttered.
826 The option can be t or nil. It may also be the symbol `beg', indicating
827 that the time should only be removed what it is located at the beginning of
828 the headline/diary entry."
829 :group 'org-agenda
830 :type '(choice
831 (const :tag "Always" t)
832 (const :tag "Never" nil)
833 (const :tag "When at beginning of entry" beg)))
834
835 (defcustom org-sort-agenda-notime-is-late t
836 "Non-nil means, items without time are considered late.
837 This is only relevant for sorting. When t, items which have no explicit
838 time like 15:30 will be considered as 24:01, i.e. later than any items which
839 do have a time. When nil, the default time is before 0:00. You can use this
840 option to decide if the schedule for today should come before or after timeless
841 agenda entries."
842 :group 'org-agenda
843 :type 'boolean)
844
845 (defgroup org-structure nil
846 "Options concerning structure editing in Org-mode."
847 :tag "Org Structure"
848 :group 'org)
849
850 (defcustom org-cycle-include-plain-lists nil
851 "Non-nil means, include plain lists into visibility cycling.
852 This means that during cycling, plain list items will *temporarily* be
853 interpreted as outline headlines with a level given by 1000+i where i is the
854 indentation of the bullet. In all other operations, plain list items are
855 not seen as headlines. For example, you cannot assign a TODO keyword to
856 such an item."
857 :group 'org-structure
858 :type 'boolean)
859
860 (defcustom org-cycle-emulate-tab t
861 "Where should `org-cycle' emulate TAB.
862 nil Never
863 white Only in completely white lines
864 t Everywhere except in headlines"
865 :group 'org-structure
866 :type '(choice (const :tag "Never" nil)
867 (const :tag "Only in completely white lines" white)
868 (const :tag "Everywhere except in headlines" t)
869 ))
870
871 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
872 "Hook that is run after `org-cycle' has changed the buffer visibility.
873 The function(s) in this hook must accept a single argument which indicates
874 the new state that was set by the most recent `org-cycle' command. The
875 argument is a symbol. After a global state change, it can have the values
876 `overview', `content', or `all'. After a local state change, it can have
877 the values `folded', `children', or `subtree'."
878 :group 'org-structure
879 :type 'hook)
880
881 (defcustom org-highlight-sparse-tree-matches t
882 "Non-nil means, highlight all matches that define a sparse tree.
883 The highlights will automatically disappear the next time the buffer is
884 changed by an edit command."
885 :group 'org-structure
886 :type 'boolean)
887
888 (defcustom org-show-hierarchy-above t
889 "Non-nil means, show full hierarchy when showing a spot in the tree.
890 Turning this off makes sparse trees more compact, but also less clear."
891 :group 'org-structure
892 :type 'boolean)
893
894 (defcustom org-show-following-heading t
895 "Non-nil means, show heading following match in `org-occur'.
896 When doing an `org-occur' it is useful to show the headline which
897 follows the match, even if they do not match the regexp. This makes it
898 easier to edit directly inside the sparse tree. However, if you use
899 org-occur mainly as an overview, the following headlines are
900 unnecessary clutter."
901 :group 'org-structure
902 :type 'boolean)
903
904 (defcustom org-occur-hook '(org-first-headline-recenter)
905 "Hook that is run after `org-occur' has constructed a sparse tree.
906 This can be used to recenter the window to show as much of the structure
907 as possible."
908 :group 'org-structure
909 :type 'hook)
910
911 (defcustom org-level-color-stars-only nil
912 "Non-nil means fontify only the stars in each headline.
913 When nil, the entire headline is fontified.
914 After changin this, requires restart of Emacs to become effective."
915 :group 'org-structure
916 :type 'boolean)
917
918 (defcustom org-adapt-indentation t
919 "Non-nil means, adapt indentation when promoting and demoting.
920 When this is set and the *entire* text in an entry is indented, the
921 indentation is increased by one space in a demotion command, and
922 decreased by one in a promotion command. If any line in the entry
923 body starts at column 0, indentation is not changed at all."
924 :group 'org-structure
925 :type 'boolean)
926
927 (defcustom org-plain-list-ordered-item-terminator t
928 "The character that makes a line with leading number an ordered list item.
929 Valid values are ?. and ?\). To get both terminators, use t. While
930 ?. may look nicer, it creates the danger that a line with leading
931 number may be incorrectly interpreted as an item. ?\) therefore is
932 the safe choice."
933 :group 'org-structure
934 :type '(choice (const :tag "dot like in \"2.\"" ?.)
935 (const :tag "paren like in \"2)\"" ?\))
936 (const :tab "both" t)))
937
938 (defcustom org-auto-renumber-ordered-lists t
939 "Non-nil means, automatically renumber ordered plain lists.
940 Renumbering happens when the sequence have been changed with
941 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
942 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
943 :group 'org-structure
944 :type 'boolean)
945
946 (defcustom org-enable-fixed-width-editor t
947 "Non-nil means, lines starting with \":\" are treated as fixed-width.
948 This currently only means, they are never auto-wrapped.
949 When nil, such lines will be treated like ordinary lines.
950 See also the QUOTE keyword."
951 :group 'org-structure
952 :type 'boolean)
953
954 (defcustom org-archive-location "%s_archive::"
955 "The location where subtrees should be archived.
956 This string consists of two parts, separated by a double-colon.
957
958 The first part is a file name - when omitted, archiving happens in the same
959 file. %s will be replaced by the current file name (without directory part).
960 Archiving to a different file is useful to keep archived entries from
961 contributing to the Org-mode Agenda.
962
963 The part after the double colon is a headline. The archived entries will be
964 filed under that headline. When omitted, the subtrees are simply filed away
965 at the end of the file, as top-level entries.
966
967 Here are a few examples:
968 \"%s_archive::\"
969 If the current file is Projects.org, archive in file
970 Projects.org_archive, as top-level trees. This is the default.
971
972 \"::* Archived Tasks\"
973 Archive in the current file, under the top-level headline
974 \"* Archived Tasks\".
975
976 \"~/org/archive.org::\"
977 Archive in file ~/org/archive.org (absolute path), as top-level trees.
978
979 \"basement::** Finished Tasks\"
980 Archive in file ./basement (relative path), as level 3 trees
981 below the level 2 heading \"** Finished Tasks\".
982
983 You may set this option on a per-file basis by adding to the buffer a
984 line like
985
986 #+ARCHIVE: basement::** Finished Tasks"
987 :group 'org-structure
988 :type 'string)
989
990 (defcustom org-archive-mark-done t
991 "Non-nil means, mark archived entries as DONE."
992 :group 'org-structure
993 :type 'boolean)
994
995 (defcustom org-archive-stamp-time t
996 "Non-nil means, add a time stamp to archived entries.
997 The time stamp will be added directly after the TODO state keyword in the
998 first line, so it is probably best to use this in combinations with
999 `org-archive-mark-done'."
1000 :group 'org-structure
1001 :type 'boolean)
1002
1003 (defgroup org-tags nil
1004 "Options concerning startup of Org-mode."
1005 :tag "Org Tags"
1006 :group 'org)
1007
1008 (defcustom org-tags-column 48
1009 "The column to which tags should be indented in a headline.
1010 If this number is positive, it specified the column. If it is negative,
1011 it means that the tags should be flushright to that column. For example,
1012 -79 works well for a normal 80 character screen."
1013 :group 'org-tags
1014 :type 'integer)
1015
1016 (defcustom org-auto-align-tags t
1017 "Non-nil means, realign tags after pro/demotion of TODO state change.
1018 These operations change the length of a headline and therefore shift
1019 the tags around. With this options turned on, after each such operation
1020 the tags are again aligned to `org-tags-column'."
1021 :group 'org-tags
1022 :type 'boolean)
1023
1024 (defcustom org-use-tag-inheritance t
1025 "Non-nil means, tags in levels apply also for sublevels.
1026 When nil, only the tags directly give in a specific line apply there.
1027 If you turn off this option, you very likely want to turn on the
1028 companion option `org-tags-match-list-sublevels'."
1029 :group 'org-tags
1030 :type 'boolean)
1031
1032 (defcustom org-tags-match-list-sublevels nil
1033 "Non-nil means list also sublevels of headlines matching tag search.
1034 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1035 the sublevels of a headline matching a tag search often also match
1036 the same search. Listing all of them can create very long lists.
1037 Setting this variable to nil causes subtrees to be skipped.
1038 This option is off by default, because inheritance in on. If you turn
1039 inheritance off, you very likely want to turn this option on."
1040 :group 'org-tags
1041 :type 'boolean)
1042
1043 (defvar org-tags-history nil
1044 "History of minibuffer reads for tags.")
1045 (defvar org-last-tags-completion-table nil
1046 "The last used completion table for tags.")
1047
1048 (defgroup org-link nil
1049 "Options concerning links in Org-mode."
1050 :tag "Org Link"
1051 :group 'org)
1052
1053 (defcustom org-tab-follows-link nil
1054 "Non-nil means, on links TAB will follow the link.
1055 Needs to be set before org.el is loaded."
1056 :group 'org-link
1057 :type 'boolean)
1058
1059 (defcustom org-return-follows-link nil
1060 "Non-nil means, on links RET will follow the link.
1061 Needs to be set before org.el is loaded."
1062 :group 'org-link
1063 :type 'boolean)
1064
1065 (defcustom org-link-format "<%s>"
1066 "Default format for linkes in the buffer.
1067 This is a format string for printf, %s will be replaced by the link text.
1068 If you want to make sure that your link is always properly terminated,
1069 include angle brackets into this format, like \"<%s>\". Some people also
1070 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
1071 :group 'org-link
1072 :type '(choice
1073 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
1074 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
1075 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
1076 (string :tag "Other" :value "<%s>")))
1077
1078 (defcustom org-allow-space-in-links t
1079 "Non-nil means, file names in links may contain space characters.
1080 When nil, it becomes possible to put several links into a line.
1081 Note that in tables, a link never extends accross fields, so in a table
1082 it is always possible to put several links into a line.
1083 Changing this varable requires a re-launch of Emacs of become effective."
1084 :group 'org-link
1085 :type 'boolean)
1086
1087 (defcustom org-context-in-file-links t
1088 "Non-nil means, file links from `org-store-link' contain context.
1089 The line number will be added to the file name with :: as separator and
1090 used to find the context when the link is activated by the command
1091 `org-open-at-point'.
1092 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1093 negates this setting for the duration of the command."
1094 :group 'org-link
1095 :type 'boolean)
1096
1097 (defcustom org-keep-stored-link-after-insertion nil
1098 "Non-nil means, keep link in list for entire session.
1099
1100 The command `org-store-link' adds a link pointing to the current
1101 location to an internal list. These links accumulate during a session.
1102 The command `org-insert-link' can be used to insert links into any
1103 Org-mode file (offering completion for all stored links). When this
1104 option is nil, every link which has been inserted once using \\[org-insert-link]
1105 will be removed from the list, to make completing the unused links
1106 more efficient."
1107 :group 'org-link
1108 :type 'boolean)
1109
1110 (defcustom org-link-frame-setup
1111 '((vm . vm-visit-folder-other-frame)
1112 (gnus . gnus-other-frame)
1113 (file . find-file-other-window))
1114 "Setup the frame configuration for following links.
1115 When following a link with Emacs, it may often be useful to display
1116 this link in another window or frame. This variable can be used to
1117 set this up for the different types of links.
1118 For VM, use any of
1119 `vm-visit-folder'
1120 `vm-visit-folder-other-frame'
1121 For Gnus, use any of
1122 `gnus'
1123 `gnus-other-frame'
1124 For FILE, use any of
1125 `find-file'
1126 `find-file-other-window'
1127 `find-file-other-frame'
1128 For the calendar, use the variable `calendar-setup'.
1129 For BBDB, it is currently only possible to display the matches in
1130 another window."
1131 :group 'org-link
1132 :type '(list
1133 (cons (const vm)
1134 (choice
1135 (const vm-visit-folder)
1136 (const vm-visit-folder-other-window)
1137 (const vm-visit-folder-other-frame)))
1138 (cons (const gnus)
1139 (choice
1140 (const gnus)
1141 (const gnus-other-frame)))
1142 (cons (const file)
1143 (choice
1144 (const find-file)
1145 (const find-file-other-window)
1146 (const find-file-other-frame)))))
1147
1148 (defcustom org-usenet-links-prefer-google nil
1149 "Non-nil means, `org-store-link' will create web links to google groups.
1150 When nil, Gnus will be used for such links.
1151 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1152 negates this setting for the duration of the command."
1153 :group 'org-link
1154 :type 'boolean)
1155
1156 (defcustom org-open-non-existing-files nil
1157 "Non-nil means, `org-open-file' will open non-existing file.
1158 When nil, an error will be generated."
1159 :group 'org-link
1160 :type 'boolean)
1161
1162 (defcustom org-confirm-shell-links t
1163 "Non-nil means, ask for confirmation before executing shell links.
1164 The default is true, to keep new users from shooting into their own foot."
1165 :group 'org-link
1166 :type 'boolean)
1167
1168 (defconst org-file-apps-defaults-gnu
1169 '((t . emacs)
1170 ("jpg" . "xv %s")
1171 ("gif" . "xv %s")
1172 ("ppm" . "xv %s")
1173 ("pgm" . "xv %s")
1174 ("pbm" . "xv %s")
1175 ("tif" . "xv %s")
1176 ("png" . "xv %s")
1177 ("ps" . "gv %s")
1178 ("ps.gz" . "gv %s")
1179 ("eps" . "gv %s")
1180 ("eps.gz" . "gv %s")
1181 ("dvi" . "xdvi %s")
1182 ("mpeg" . "plaympeg %s")
1183 ("mp3" . "plaympeg %s")
1184 ("fig" . "xfig %s")
1185 ("pdf" . "acroread %s")
1186 ("doc" . "soffice %s")
1187 ("ppt" . "soffice %s")
1188 ("pps" . "soffice %s")
1189 ("html" . "netscape -remote openURL(%s,new-window)")
1190 ("htm" . "netscape -remote openURL(%s,new-window)")
1191 ("xs" . "soffice %s"))
1192 "Default file applications on a UNIX/LINUX system.
1193 See `org-file-apps'.")
1194
1195 (defconst org-file-apps-defaults-macosx
1196 '((t . "open %s")
1197 ("ps" . "gv %s")
1198 ("ps.gz" . "gv %s")
1199 ("eps" . "gv %s")
1200 ("eps.gz" . "gv %s")
1201 ("dvi" . "xdvi %s")
1202 ("fig" . "xfig %s"))
1203 "Default file applications on a MacOS X system.
1204 The system \"open\" is known as a default, but we use X11 applications
1205 for some files for which the OS does not have a good default.
1206 See `org-file-apps'.")
1207
1208 (defconst org-file-apps-defaults-windowsnt
1209 '((t . (w32-shell-execute "open" file)))
1210 "Default file applications on a Windows NT system.
1211 The system \"open\" is used for most files.
1212 See `org-file-apps'.")
1213
1214 (defcustom org-file-apps
1215 '(
1216 ("txt" . emacs)
1217 ("tex" . emacs)
1218 ("ltx" . emacs)
1219 ("org" . emacs)
1220 ("el" . emacs)
1221 )
1222 "External applications for opening `file:path' items in a document.
1223 Org-mode uses system defaults for different file types, but
1224 you can use this variable to set the application for a given file
1225 extension. The entries in this list are cons cells with a file extension
1226 and the corresponding command. Possible values for the command are:
1227 `emacs' The file will be visited by the current Emacs process.
1228 `default' Use the default application for this file type.
1229 string A command to be executed by a shell; %s will be replaced
1230 by the path to the file.
1231 sexp A Lisp form which will be evaluated. The file path will
1232 be available in the Lisp variable `file'.
1233 For more examples, see the system specific constants
1234 `org-file-apps-defaults-macosx'
1235 `org-file-apps-defaults-windowsnt'
1236 `org-file-apps-defaults-gnu'."
1237 :group 'org-link
1238 :type '(repeat
1239 (cons (string :tag "Extension")
1240 (choice :value ""
1241 (const :tag "Visit with Emacs" 'emacs)
1242 (const :tag "Use system default" 'default)
1243 (string :tag "Command")
1244 (sexp :tag "Lisp form")))))
1245
1246
1247 (defgroup org-remember nil
1248 "Options concerning interaction with remember.el."
1249 :tag "Org Remember"
1250 :group 'org)
1251
1252 (defcustom org-directory "~/org"
1253 "Directory with org files.
1254 This directory will be used as default to prompt for org files.
1255 Used by the hooks for remember.el."
1256 :group 'org-remember
1257 :type 'directory)
1258
1259 (defcustom org-default-notes-file "~/.notes"
1260 "Default target for storing notes.
1261 Used by the hooks for remember.el. This can be a string, or nil to mean
1262 the value of `remember-data-file'."
1263 :group 'org-remember
1264 :type '(choice
1265 (const :tag "Default from remember-data-file" nil)
1266 file))
1267
1268 (defcustom org-reverse-note-order nil
1269 "Non-nil means, store new notes at the beginning of a file or entry.
1270 When nil, new notes will be filed to the end of a file or entry."
1271 :group 'org-remember
1272 :type '(choice
1273 (const :tag "Reverse always" t)
1274 (const :tag "Reverse never" nil)
1275 (repeat :tag "By file name regexp"
1276 (cons regexp boolean))))
1277
1278 (defgroup org-table nil
1279 "Options concerning tables in Org-mode."
1280 :tag "Org Table"
1281 :group 'org)
1282
1283 (defcustom org-enable-table-editor 'optimized
1284 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1285 When nil, such lines will be treated like ordinary lines.
1286
1287 When equal to the symbol `optimized', the table editor will be optimized to
1288 do the following
1289 - Use automatic overwrite mode in front of whitespace in table fields.
1290 This make the structure of the table stay in tact as long as the edited
1291 field does not exceed the column width.
1292 - Minimize the number of realigns. Normally, the table is aligned each time
1293 TAB or RET are pressed to move to another field. With optimization this
1294 happens only if changes to a field might have changed the column width.
1295 Optimization requires replacing the functions `self-insert-command',
1296 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1297 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1298 very good at guessing when a re-align will be necessary, but you can always
1299 force one with \\[org-ctrl-c-ctrl-c].
1300
1301 If you would like to use the optimized version in Org-mode, but the
1302 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1303
1304 This variable can be used to turn on and off the table editor during a session,
1305 but in order to toggle optimization, a restart is required.
1306
1307 See also the variable `org-table-auto-blank-field'."
1308 :group 'org-table
1309 :type '(choice
1310 (const :tag "off" nil)
1311 (const :tag "on" t)
1312 (const :tag "on, optimized" optimized)))
1313
1314 ;; FIXME: We could have a third option which makes it jump only over the first
1315 ;; hline in a table.
1316 (defcustom org-table-tab-jumps-over-hlines t
1317 "Non-nil means, tab in the last column of a table with jump over a hline.
1318 If a horizontal separator line is following the current line,
1319 `org-table-next-field' can either create a new row before that line, or jump
1320 over the line. When this option is nil, a new line will be created before
1321 this line."
1322 :group 'org-table
1323 :type 'boolean)
1324
1325 (defcustom org-table-auto-blank-field t
1326 "Non-nil means, automatically blank table field when starting to type into it.
1327 This only happens when typing immediately after a field motion
1328 command (TAB, S-TAB or RET).
1329 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1330 :group 'org-table
1331 :type 'boolean)
1332
1333 (defcustom org-table-default-size "5x2"
1334 "The default size for newly created tables, Columns x Rows."
1335 :group 'org-table
1336 :type 'string)
1337
1338 (defcustom org-table-automatic-realign t
1339 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1340 When nil, aligning is only done with \\[org-table-align], or after column
1341 removal/insertion."
1342 :group 'org-table
1343 :type 'boolean)
1344
1345 (defcustom org-table-spaces-around-separators '(1 . 1)
1346 "The number of spaces to be placed before and after separators."
1347 :group 'org-table
1348 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1349
1350 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1351 "The number of spaces to be placed before and after separators.
1352 This option applies when the column separators have been made invisible."
1353 :group 'org-table
1354 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1355
1356 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1357 "Regular expression for recognizing numbers in table columns.
1358 If a table column contains mostly numbers, it will be aligned to the
1359 right. If not, it will be aligned to the left.
1360
1361 The default value of this option is a regular expression which allows
1362 anything which looks remotely like a number as used in scientific
1363 context. For example, all of the following will be considered a
1364 number:
1365 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1366
1367 Other options offered by the customize interface are more restrictive."
1368 :group 'org-table
1369 :type '(choice
1370 (const :tag "Positive Integers"
1371 "^[0-9]+$")
1372 (const :tag "Integers"
1373 "^[-+]?[0-9]+$")
1374 (const :tag "Floating Point Numbers"
1375 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1376 (const :tag "Floating Point Number or Integer"
1377 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1378 (const :tag "Exponential, Floating point, Integer"
1379 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1380 (const :tag "Very General Number-Like"
1381 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1382 (string :tag "Regexp:")))
1383
1384 (defcustom org-table-number-fraction 0.5
1385 "Fraction of numbers in a column required to make the column align right.
1386 In a column all non-white fields are considered. If at least this
1387 fraction of fields is matched by `org-table-number-fraction',
1388 alignment to the right border applies."
1389 :group 'org-table
1390 :type 'number)
1391
1392 (defcustom org-export-highlight-first-table-line t
1393 "Non-nil means, highlight the first table line.
1394 In HTML export, this means use <th> instead of <td>.
1395 In tables created with table.el, this applies to the first table line.
1396 In Org-mode tables, all lines before the first horizontal separator
1397 line will be formatted with <th> tags."
1398 :group 'org-table
1399 :type 'boolean)
1400
1401 (defcustom org-table-tab-recognizes-table.el t
1402 "Non-nil means, TAB will automatically notice a table.el table.
1403 When it sees such a table, it moves point into it and - if necessary -
1404 calls `table-recognize-table'."
1405 :group 'org-table
1406 :type 'boolean)
1407
1408 (defgroup org-table-calculation nil
1409 "Options concerning tables in Org-mode."
1410 :tag "Org Table Calculation"
1411 :group 'org)
1412
1413 (defcustom org-table-copy-increment t
1414 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1415 :group 'org-table-calculation
1416 :type 'boolean)
1417
1418 (defcustom org-calc-default-modes
1419 '(calc-internal-prec 12
1420 calc-float-format (float 5)
1421 calc-angle-mode deg
1422 calc-prefer-frac nil
1423 calc-symbolic-mode nil
1424 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1425 calc-display-working-message t
1426 )
1427 "List with Calc mode settings for use in calc-eval for table formulas.
1428 The list must contain alternating symbols (calc modes variables and values.
1429 Don't remove any of the default settings, just change the values. Org-mode
1430 relies on the variables to be present in the list."
1431 :group 'org-table-calculation
1432 :type 'plist)
1433
1434 (defcustom org-table-formula-evaluate-inline t
1435 "Non-nil means, TAB and RET evaluate a formula in current table field.
1436 If the current field starts with an equal sign, it is assumed to be a formula
1437 which should be evaluated as described in the manual and in the documentation
1438 string of the command `org-table-eval-formula'. This feature requires the
1439 Emacs calc package.
1440 When this variable is nil, formula calculation is only available through
1441 the command \\[org-table-eval-formula]."
1442 :group 'org-table-calculation
1443 :type 'boolean)
1444
1445
1446 (defcustom org-table-formula-use-constants t
1447 "Non-nil means, interpret constants in formulas in tables.
1448 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1449 by the value given in `org-table-formula-constants', or by a value obtained
1450 from the `constants.el' package."
1451 :group 'org-table-calculation
1452 :type 'boolean)
1453
1454 (defcustom org-table-formula-constants nil
1455 "Alist with constant names and values, for use in table formulas.
1456 The car of each element is a name of a constant, without the `$' before it.
1457 The cdr is the value as a string. For example, if you'd like to use the
1458 speed of light in a formula, you would configure
1459
1460 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1461
1462 and then use it in an equation like `$1*$c'."
1463 :group 'org-table-calculation
1464 :type '(repeat
1465 (cons (string :tag "name")
1466 (string :tag "value"))))
1467
1468 (defcustom org-table-formula-numbers-only nil
1469 "Non-nil means, calculate only with numbers in table formulas.
1470 Then all input fields will be converted to a number, and the result
1471 must also be a number. When nil, calc's full potential is available
1472 in table calculations, including symbolics etc."
1473 :group 'org-table-calculation
1474 :type 'boolean)
1475
1476 (defcustom org-table-allow-automatic-line-recalculation t
1477 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1478 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1479 :group 'org-table-calculation
1480 :type 'boolean)
1481
1482 (defgroup org-export nil
1483 "Options for exporting org-listings."
1484 :tag "Org Export"
1485 :group 'org)
1486
1487 (defcustom org-export-language-setup
1488 '(("en" "Author" "Date" "Table of Contents")
1489 ("da" "Ophavsmand" "Dato" "Indhold")
1490 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1491 ("es" "Autor" "Fecha" "\xccndice")
1492 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1493 ("it" "Autore" "Data" "Indice")
1494 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1495 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1496 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1497 "Terms used in export text, translated to different languages.
1498 Use the variable `org-export-default-language' to set the language,
1499 or use the +OPTION lines for a per-file setting."
1500 :group 'org-export
1501 :type '(repeat
1502 (list
1503 (string :tag "HTML language tag")
1504 (string :tag "Author")
1505 (string :tag "Date")
1506 (string :tag "Table of Contents"))))
1507
1508 (defcustom org-export-default-language "en"
1509 "The default language of HTML export, as a string.
1510 This should have an association in `org-export-language-setup'."
1511 :group 'org-export
1512 :type 'string)
1513
1514 (defcustom org-export-html-style
1515 "<style type=\"text/css\">
1516 html {
1517 font-family: Times, serif;
1518 font-size: 12pt;
1519 }
1520 .title { text-align: center; }
1521 .todo, .deadline { color: red; }
1522 .done { color: green; }
1523 pre {
1524 border: 1pt solid #AEBDCC;
1525 background-color: #F3F5F7;
1526 padding: 5pt;
1527 font-family: courier, monospace;
1528 }
1529 table { border-collapse: collapse; }
1530 td, th {
1531 vertical-align: top;
1532 border: 1pt solid #ADB9CC;
1533 }
1534 </style>"
1535 "The default style specification for exported HTML files.
1536 Since there are different ways of setting style information, this variable
1537 needs to contain the full HTML structure to provide a style, including the
1538 surrounding HTML tags. The style specifications should include definiitons
1539 for new classes todo, done, title, and deadline. For example, legal values
1540 would be.
1541
1542 <style type=\"text/css\">
1543 p {font-weight: normal; color: gray; }
1544 h1 {color: black; }
1545 .title { text-align: center; }
1546 .todo, .deadline { color: red; }
1547 .done { color: green; }
1548 </style>
1549
1550 or, if you want to keep the style in a file,
1551
1552 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1553
1554 As the value of this option simply gets inserted into the HTML <head> header,
1555 you can \"misuse\" it to add arbitrary text to the header."
1556 :group 'org-export
1557 :type 'string)
1558
1559 (defcustom org-export-headline-levels 3
1560 "The last level which is still exported as a headline.
1561 Inferior levels will produce itemize lists when exported.
1562 Note that a numeric prefix argument to an exporter function overrides
1563 this setting.
1564
1565 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1566 :group 'org-export
1567 :type 'number)
1568
1569 (defcustom org-export-with-section-numbers t
1570 "Non-nil means, add section numbers to headlines when exporting.
1571
1572 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1573 :group 'org-export
1574 :type 'boolean)
1575
1576 (defcustom org-export-with-toc t
1577 "Non-nil means, create a table of contents in exported files.
1578 The TOC contains headlines with levels up to`org-export-headline-levels'.
1579
1580 Headlines which contain any TODO items will be marked with \"(*)\" in
1581 ASCII export, and with red color in HTML output.
1582
1583 In HTML output, the TOC will be clickable.
1584
1585 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1586 :group 'org-export
1587 :type 'boolean)
1588
1589 (defcustom org-export-plain-list-max-depth 20
1590 "Maximum depth of hand-formatted lists in HTML export.
1591
1592 Org-mode parses hand-formatted enumeration and bullet lists and
1593 transforms them to HTML open export. Different indentation of the
1594 bullet or number indicates different list nesting levels. To avoid
1595 confusion, only a single level is allowed by default. When this is
1596 larger than 1, deeper indentation leads to deeper list nesting. For
1597 example, the default value of 3 allows the following list to be
1598 formatted correctly in HTML:
1599
1600 * Fruit
1601 - Apple
1602 - Banana
1603 1. from Africa
1604 2. from South America
1605 - Pineapple
1606 * Bread
1607 * Dairy products"
1608 :group 'org-export
1609 :type 'integer)
1610
1611 (defcustom org-export-preserve-breaks nil
1612 "Non-nil means, preserve all line breaks when exporting.
1613 Normally, in HTML output paragraphs will be reformatted. In ASCII
1614 export, line breaks will always be preserved, regardless of this variable.
1615
1616 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1617 :group 'org-export
1618 :type 'boolean)
1619
1620 (defcustom org-export-html-inline-images t
1621 "Non-nil means, inline images into exported HTML pages.
1622 The link will still be to the original location of the image file.
1623 So if you are moving the page, lets say to your public HTML site,
1624 you will have to move the image and maybe change the link."
1625 :group 'org-export
1626 :type 'boolean)
1627
1628 (defcustom org-export-html-expand t
1629 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1630 When nil, these tags will be exported as plain text and therefore
1631 not be interpreted by a browser.
1632
1633 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1634 :group 'org-export
1635 :type 'boolean)
1636
1637 (defcustom org-export-with-fixed-width t
1638 "Non-nil means, lines starting with \":\" will be in fixed width font.
1639 This can be used to have pre-formatted text, fragments of code etc. For
1640 example
1641 : ;; Some Lisp examples
1642 : (while (defc cnt)
1643 : (ding))
1644 will be looking just like this in also HTML. In ASCII export, this option
1645 has no effect.
1646
1647 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1648 :group 'org-export
1649 :type 'boolean)
1650
1651 (defcustom org-export-with-tables t
1652 "If non-nil, lines starting with \"|\" define a table.
1653 For example:
1654
1655 | Name | Address | Birthday |
1656 |-------------+----------+-----------|
1657 | Arthur Dent | England | 29.2.2100 |
1658
1659 In ASCII export, this option has no effect.
1660
1661 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1662 :group 'org-export
1663 :type 'boolean)
1664
1665 (defcustom org-export-prefer-native-exporter-for-tables nil
1666 "Non-nil means, always export tables created with table.el natively.
1667 Natively means, use the HTML code generator in table.el.
1668 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1669 the table does not use row- or column-spanning). This has the
1670 advantage, that the automatic HTML conversions for math symbols and
1671 sub/superscripts can be applied. Org-mode's HTML generator is also
1672 much faster."
1673 :group 'org-export
1674 :type 'boolean)
1675
1676 (defcustom org-export-html-table-tag
1677 "<table border=1 cellspacing=0 cellpadding=6>"
1678 "The HTML tag used to start a table.
1679 This must be a <table> tag, but you may change the options like
1680 borders and spacing."
1681 :group 'org-export
1682 :type 'string)
1683
1684 (defcustom org-export-with-emphasize t
1685 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1686 If the export target supports emphasizing text, the word will be
1687 typeset in bold, italic, or underlined, respectively. Works only for
1688 single words, but you can say: I *really* *mean* *this*.
1689 In ASCII export, this option has no effect.
1690
1691 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1692 :group 'org-export
1693 :type 'boolean)
1694
1695 (defcustom org-match-sexp-depth 3
1696 "Number of stacked braces for sub/superscript matching.
1697 This has to be set before loading org.el to be effective."
1698 :group 'org-export
1699 :type 'integer)
1700
1701 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1702 (defcustom org-export-with-sub-superscripts t
1703 "Non-nil means, interpret \"_\" and \"^\" for export.
1704 When this option is turned on, you can use TeX-like syntax for sub- and
1705 superscripts. Several characters after \"_\" or \"^\" will be
1706 considered as a single item - so grouping with {} is normally not
1707 needed. For example, the following things will be parsed as single
1708 sub- or superscripts.
1709
1710 10^24 or 10^tau several digits will be considered 1 item
1711 10^-12 or 10^-tau a leading sign with digits or a word
1712 x^2-y^3 will be read as x^2 - y^3, because items are
1713 terminated by almost any nonword/nondigit char.
1714 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1715
1716 Still, ambiguity is possible - so when in doubt use {} to enclose the
1717 sub/superscript.
1718 In ASCII export, this option has no effect.
1719
1720 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1721 :group 'org-export
1722 :type 'boolean)
1723
1724 (defcustom org-export-with-TeX-macros t
1725 "Non-nil means, interpret simple TeX-like macros when exporting.
1726 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1727 No only real TeX macros will work here, but the standard HTML entities
1728 for math can be used as macro names as well. For a list of supported
1729 names in HTML export, see the constant `org-html-entities'.
1730 In ASCII export, this option has no effect.
1731
1732 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1733 :group 'org-export
1734 :type 'boolean)
1735
1736 (defcustom org-export-html-with-timestamp nil
1737 "If non-nil, write `org-export-html-html-helper-timestamp'
1738 into the exported html text. Otherwise, the buffer will just be saved
1739 to a file."
1740 :group 'org-export
1741 :type 'boolean)
1742
1743 (defcustom org-export-html-html-helper-timestamp
1744 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1745 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1746 :group 'org-export
1747 :type 'string)
1748
1749 (defcustom org-export-ascii-show-new-buffer t
1750 "Non-nil means, popup buffer containing the exported ASCII text.
1751 Otherwise the buffer will just be saved to a file and stay hidden."
1752 :group 'org-export
1753 :type 'boolean)
1754
1755 (defcustom org-export-html-show-new-buffer nil
1756 "Non-nil means, popup buffer containing the exported html text.
1757 Otherwise, the buffer will just be saved to a file and stay hidden."
1758 :group 'org-export
1759 :type 'boolean)
1760
1761 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1762 "The file name for the iCalendar file covering all agenda files.
1763 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1764 :group 'org-export
1765 :type 'file)
1766
1767 (defcustom org-icalendar-include-todo nil
1768 "Non-nil means, export to iCalendar files should also cover TODO items."
1769 :group 'org-export
1770 :type 'boolean)
1771
1772 (defcustom org-icalendar-combined-name "OrgMode"
1773 "Calendar name for the combined iCalendar representing all agenda files."
1774 :group 'org-export
1775 :type 'string)
1776
1777 (defgroup org-faces nil
1778 "Faces for highlighting in Org-mode."
1779 :tag "Org Faces"
1780 :group 'org)
1781
1782 (defface org-level-1 ;; font-lock-function-name-face
1783 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1784 (((class color) (background light)) (:foreground "Blue"))
1785 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1786 (t (:inverse-video t :bold t)))
1787 "Face used for level 1 headlines."
1788 :group 'org-faces)
1789
1790 (defface org-level-2 ;; font-lock-variable-name-face
1791 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1792 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1793 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1794 (t (:bold t :italic t)))
1795 "Face used for level 2 headlines."
1796 :group 'org-faces)
1797
1798 (defface org-level-3 ;; font-lock-keyword-face
1799 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1800 (((class color) (background light)) (:foreground "Purple"))
1801 (((class color) (background dark)) (:foreground "Cyan"))
1802 (t (:bold t)))
1803 "Face used for level 3 headlines."
1804 :group 'org-faces)
1805
1806 (defface org-level-4 ;; font-lock-comment-face
1807 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1808 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1809 (((class color) (background light)) (:foreground "Firebrick"))
1810 (((class color) (background dark)) (:foreground "chocolate1"))
1811 (t (:bold t :italic t)))
1812 "Face used for level 4 headlines."
1813 :group 'org-faces)
1814
1815 (defface org-level-5 ;; font-lock-type-face
1816 '((((type tty) (class color)) (:foreground "green"))
1817 (((class color) (background light)) (:foreground "ForestGreen"))
1818 (((class color) (background dark)) (:foreground "PaleGreen"))
1819 (t (:bold t :underline t)))
1820 "Face used for level 5 headlines."
1821 :group 'org-faces)
1822
1823 (defface org-level-6 ;; font-lock-constant-face
1824 '((((type tty) (class color)) (:foreground "magenta"))
1825 (((class color) (background light)) (:foreground "CadetBlue"))
1826 (((class color) (background dark)) (:foreground "Aquamarine"))
1827 (t (:bold t :underline t)))
1828 "Face used for level 6 headlines."
1829 :group 'org-faces)
1830
1831 (defface org-level-7 ;; font-lock-builtin-face
1832 '((((type tty) (class color)) (:foreground "blue" :weight light))
1833 (((class color) (background light)) (:foreground "Orchid"))
1834 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1835 (t (:bold t)))
1836 "Face used for level 7 headlines."
1837 :group 'org-faces)
1838
1839 (defface org-level-8 ;; font-lock-string-face
1840 '((((type tty) (class color)) (:foreground "green"))
1841 (((class color) (background light)) (:foreground "RosyBrown"))
1842 (((class color) (background dark)) (:foreground "LightSalmon"))
1843 (t (:italic t)))
1844 "Face used for level 8 headlines."
1845 :group 'org-faces)
1846
1847 (defface org-special-keyword ;; font-lock-string-face
1848 '((((type tty) (class color)) (:foreground "green"))
1849 (((class color) (background light)) (:foreground "RosyBrown"))
1850 (((class color) (background dark)) (:foreground "LightSalmon"))
1851 (t (:italic t)))
1852 "Face used for level 8 headlines."
1853 :group 'org-faces)
1854
1855 (defface org-warning ;; font-lock-warning-face
1856 '((((type tty) (class color)) (:foreground "red"))
1857 (((class color) (background light)) (:foreground "Red" :bold t))
1858 (((class color) (background dark)) (:foreground "Red1" :bold t))
1859 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1860 (t (:inverse-video t :bold t)))
1861 "Face for deadlines and TODO keywords."
1862 :group 'org-faces)
1863
1864 (defcustom org-fontify-done-headline nil
1865 "Non-nil means, change the face of a headline if it is marked DONE.
1866 Normally, only the TODO/DONE keyword indicates the state of a headline.
1867 When this is non-nil, the headline after the keyword is set to the
1868 `org-headline-done' as an additional indication."
1869 :group 'org-faces
1870 :type 'boolean)
1871
1872 (defface org-headline-done ;; font-lock-string-face
1873 '((((type tty) (class color)) (:foreground "green"))
1874 (((class color) (background light)) (:foreground "RosyBrown"))
1875 (((class color) (background dark)) (:foreground "LightSalmon"))
1876 (t (:italic t)))
1877 "Face used to indicate that a headline is DONE. See also the variable
1878 `org-fontify-done-headline'."
1879 :group 'org-faces)
1880
1881 ;; Inheritance does not yet work for xemacs. So we just copy...
1882
1883 (defface org-deadline-announce
1884 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1885 (((class color) (background light)) (:foreground "Blue"))
1886 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1887 (t (:inverse-video t :bold t)))
1888 "Face for upcoming deadlines."
1889 :group 'org-faces)
1890
1891 (defface org-scheduled-today
1892 '((((type tty) (class color)) (:foreground "green"))
1893 (((class color) (background light)) (:foreground "DarkGreen"))
1894 (((class color) (background dark)) (:foreground "PaleGreen"))
1895 (t (:bold t :underline t)))
1896 "Face for items scheduled for a certain day."
1897 :group 'org-faces)
1898
1899 (defface org-scheduled-previously
1900 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1901 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1902 (((class color) (background light)) (:foreground "Firebrick"))
1903 (((class color) (background dark)) (:foreground "chocolate1"))
1904 (t (:bold t :italic t)))
1905 "Face for items scheduled previously, and not yet done."
1906 :group 'org-faces)
1907
1908 (defface org-formula
1909 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1910 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1911 (((class color) (background light)) (:foreground "Firebrick"))
1912 (((class color) (background dark)) (:foreground "chocolate1"))
1913 (t (:bold t :italic t)))
1914 "Face for items scheduled previously, and not yet done."
1915 :group 'org-faces)
1916
1917 (defface org-link
1918 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1919 (((class color) (background light)) (:foreground "Purple"))
1920 (((class color) (background dark)) (:foreground "Cyan"))
1921 (t (:bold t)))
1922 "Face for links."
1923 :group 'org-faces)
1924
1925 (defface org-done ;; font-lock-type-face
1926 '((((type tty) (class color)) (:foreground "green"))
1927 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1928 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1929 (t (:bold t :underline t)))
1930 "Face used for DONE."
1931 :group 'org-faces)
1932
1933 (defface org-table ;; font-lock-function-name-face
1934 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1935 (((class color) (background light)) (:foreground "Blue"))
1936 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1937 (t (:inverse-video t :bold t)))
1938 "Face used for tables."
1939 :group 'org-faces)
1940
1941 (defface org-time-grid ;; font-lock-variable-name-face
1942 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1943 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1944 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1945 (t (:bold t :italic t)))
1946 "Face used for level 2 headlines."
1947 :group 'org-faces)
1948
1949 (defvar org-level-faces
1950 '(
1951 org-level-1
1952 org-level-2
1953 org-level-3
1954 org-level-4
1955 org-level-5
1956 org-level-6
1957 org-level-7
1958 org-level-8
1959 ))
1960 (defvar org-n-levels (length org-level-faces))
1961
1962 (defun org-set-regexps-and-options ()
1963 "Precompute regular expressions for current buffer."
1964 (when (eq major-mode 'org-mode)
1965 (let ((re (org-make-options-regexp
1966 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1967 "STARTUP" "ARCHIVE")))
1968 (splitre "[ \t]+")
1969 kwds int key value cat arch)
1970 (save-excursion
1971 (save-restriction
1972 (widen)
1973 (goto-char (point-min))
1974 (while (re-search-forward re nil t)
1975 (setq key (match-string 1) value (match-string 2))
1976 (cond
1977 ((equal key "CATEGORY")
1978 (if (string-match "[ \t]+$" value)
1979 (setq value (replace-match "" t t value)))
1980 (setq cat (intern value)))
1981 ((equal key "SEQ_TODO")
1982 (setq int 'sequence
1983 kwds (append kwds (org-split-string value splitre))))
1984 ((equal key "PRI_TODO")
1985 (setq int 'priority
1986 kwds (append kwds (org-split-string value splitre))))
1987 ((equal key "TYP_TODO")
1988 (setq int 'type
1989 kwds (append kwds (org-split-string value splitre))))
1990 ((equal key "STARTUP")
1991 (let ((opts (org-split-string value splitre))
1992 (set '(("fold" org-startup-folded t)
1993 ("nofold" org-startup-folded nil)
1994 ("content" org-startup-folded content)
1995 ("dlcheck" org-startup-with-deadline-check t)
1996 ("nodlcheck" org-startup-with-deadline-check nil)))
1997 l var val)
1998 (while (setq l (assoc (pop opts) set))
1999 (setq var (nth 1 l) val (nth 2 l))
2000 (set (make-local-variable var) val))))
2001 ((equal key "ARCHIVE")
2002 (string-match " *$" value)
2003 (setq arch (replace-match "" t t value))
2004 (remove-text-properties 0 (length arch)
2005 '(face t fontified t) arch)))
2006 )))
2007 (and cat (set (make-local-variable 'org-category) cat))
2008 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2009 (and arch (set (make-local-variable 'org-archive-location) arch))
2010 (and int (set (make-local-variable 'org-todo-interpretation) int)))
2011 ;; Compute the regular expressions and other local variables
2012 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2013 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2014 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2015 (length org-scheduled-string)))
2016 org-done-string
2017 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2018 org-todo-regexp
2019 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2020 "\\|") "\\)\\>")
2021 org-not-done-regexp
2022 (concat "\\<\\("
2023 (mapconcat 'regexp-quote
2024 (nreverse (cdr (reverse org-todo-keywords)))
2025 "\\|")
2026 "\\)\\>")
2027 org-todo-line-regexp
2028 (concat "^\\(\\*+\\)[ \t]*\\("
2029 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2030 "\\)? *\\(.*\\)")
2031 org-nl-done-regexp
2032 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2033 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2034 org-deadline-regexp (concat "\\<" org-deadline-string)
2035 org-deadline-time-regexp
2036 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2037 org-deadline-line-regexp
2038 (concat "\\<\\(" org-deadline-string "\\).*")
2039 org-scheduled-regexp
2040 (concat "\\<" org-scheduled-string)
2041 org-scheduled-time-regexp
2042 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2043 (org-set-font-lock-defaults)))
2044
2045 ;; Tell the compiler about dynamically scoped variables,
2046 ;; and variables from other packages
2047 (eval-when-compile
2048 (defvar zmacs-regions)
2049 (defvar original-date)
2050 (defvar org-transient-mark-mode)
2051 (defvar org-old-auto-fill-inhibit-regexp)
2052 (defvar orgtbl-mode-menu)
2053 (defvar org-html-entities)
2054 (defvar org-goto-start-pos)
2055 (defvar org-cursor-color)
2056 (defvar org-time-was-given)
2057 (defvar org-ts-what)
2058 (defvar mark-active)
2059 (defvar timecnt)
2060 (defvar levels-open)
2061 (defvar title)
2062 (defvar author)
2063 (defvar email)
2064 (defvar text)
2065 (defvar entry)
2066 (defvar date)
2067 (defvar language)
2068 (defvar options)
2069 (defvar ans1)
2070 (defvar ans2)
2071 (defvar starting-day)
2072 (defvar include-all-loc)
2073 (defvar vm-message-pointer)
2074 (defvar vm-folder-directory)
2075 (defvar wl-summary-buffer-elmo-folder)
2076 (defvar wl-summary-buffer-folder-name)
2077 (defvar gnus-group-name)
2078 (defvar gnus-article-current)
2079 (defvar w3m-current-url)
2080 (defvar org-selected-point)
2081 (defvar calendar-mode-map)
2082 (defvar remember-save-after-remembering)
2083 (defvar remember-data-file))
2084
2085
2086 ;;; Define the mode
2087
2088 (defvar org-mode-map (copy-keymap outline-mode-map)
2089 "Keymap for Org-mode.")
2090
2091 (defvar org-struct-menu)
2092 (defvar org-org-menu)
2093 (defvar org-tbl-menu)
2094
2095 ;; We use a before-change function to check if a table might need
2096 ;; an update.
2097 (defvar org-table-may-need-update t
2098 "Indicates of a table might need an update.
2099 This variable is set by `org-before-change-function'. `org-table-align'
2100 sets it back to nil.")
2101 (defvar org-mode-hook nil)
2102 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2103 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2104
2105
2106 ;;;###autoload
2107 (define-derived-mode org-mode outline-mode "Org"
2108 "Outline-based notes management and organizer, alias
2109 \"Carstens outline-mode for keeping track of everything.\"
2110
2111 Org-mode develops organizational tasks around a NOTES file which
2112 contains information about projects as plain text. Org-mode is
2113 implemented on top of outline-mode, which is ideal to keep the content
2114 of large files well structured. It supports ToDo items, deadlines and
2115 time stamps, which magically appear in the diary listing of the Emacs
2116 calendar. Tables are easily created with a built-in table editor.
2117 Plain text URL-like links connect to websites, emails (VM), Usenet
2118 messages (Gnus), BBDB entries, and any files related to the project.
2119 For printing and sharing of notes, an Org-mode file (or a part of it)
2120 can be exported as a structured ASCII or HTML file.
2121
2122 The following commands are available:
2123
2124 \\{org-mode-map}"
2125 (easy-menu-add org-org-menu)
2126 (easy-menu-add org-tbl-menu)
2127 (org-install-agenda-files-menu)
2128 (setq outline-regexp "\\*+")
2129 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2130 (setq outline-level 'org-outline-level)
2131 (if org-startup-truncated (setq truncate-lines t))
2132 (org-set-regexps-and-options)
2133 (set (make-local-variable 'font-lock-unfontify-region-function)
2134 'org-unfontify-region)
2135 ;; Activate before-change-function
2136 (set (make-local-variable 'org-table-may-need-update) t)
2137 (make-local-hook 'before-change-functions) ;; needed for XEmacs
2138 (add-hook 'before-change-functions 'org-before-change-function nil
2139 'local)
2140 ;; Paragraphs and auto-filling
2141 (org-set-autofill-regexps)
2142 ;; Settings for Calc embedded mode
2143 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2144 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2145 (if (and org-insert-mode-line-in-empty-file
2146 (interactive-p)
2147 (= (point-min) (point-max)))
2148 (insert " -*- mode: org -*-\n\n"))
2149
2150 ;; Get rid of Outline menus, they are not needed
2151 ;; Need to do this here because define-derived-mode sets up
2152 ;; the keymap so late.
2153 (if org-xemacs-p
2154 (progn
2155 (delete-menu-item '("Headings"))
2156 (delete-menu-item '("Show"))
2157 (delete-menu-item '("Hide"))
2158 (set-menubar-dirty-flag))
2159 (define-key org-mode-map [menu-bar headings] 'undefined)
2160 (define-key org-mode-map [menu-bar hide] 'undefined)
2161 (define-key org-mode-map [menu-bar show] 'undefined))
2162
2163 (unless org-inhibit-startup
2164 (if org-startup-with-deadline-check
2165 (call-interactively 'org-check-deadlines)
2166 (cond
2167 ((eq org-startup-folded t)
2168 (org-cycle '(4)))
2169 ((eq org-startup-folded 'content)
2170 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2171 (org-cycle '(4)) (org-cycle '(4))))))))
2172
2173 (defsubst org-current-line (&optional pos)
2174 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2175
2176 ;;; Font-Lock stuff
2177
2178 (defvar org-mouse-map (make-sparse-keymap))
2179 (define-key org-mouse-map
2180 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2181 (define-key org-mouse-map
2182 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2183 (when org-tab-follows-link
2184 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2185 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2186 (when org-return-follows-link
2187 (define-key org-mouse-map [(return)] 'org-open-at-point)
2188 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2189
2190 (require 'font-lock)
2191
2192 (defconst org-non-link-chars "\t\n\r|<>\000")
2193 (defconst org-link-regexp
2194 (if org-allow-space-in-links
2195 (concat
2196 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2197 (concat
2198 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2199 )
2200 "Regular expression for matching links.")
2201 (defconst org-link-maybe-angles-regexp
2202 (concat "<?\\(" org-link-regexp "\\)>?")
2203 "Matches a link and optionally surrounding angle brackets.")
2204 (defconst org-protected-link-regexp
2205 (concat "\000" org-link-regexp "\000")
2206 "Matches a link and optionally surrounding angle brackets.")
2207
2208 (defconst org-ts-lengths
2209 (cons (length (format-time-string (car org-time-stamp-formats)))
2210 (length (format-time-string (cdr org-time-stamp-formats))))
2211 "This holds the lengths of the two different time formats.")
2212 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2213 "Regular expression for fast time stamp matching.")
2214 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2215 "Regular expression for fast time stamp matching.")
2216 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2217 "Regular expression matching time strings for analysis.")
2218 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2219 "Regular expression matching time stamps, with groups.")
2220 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2221 "Regular expression matching a time stamp range.")
2222 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2223 org-ts-regexp "\\)?")
2224 "Regular expression matching a time stamp or time stamp range.")
2225
2226 (defun org-activate-links (limit)
2227 "Run through the buffer and add overlays to links."
2228 (if (re-search-forward org-link-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 (defun org-activate-dates (limit)
2236 "Run through the buffer and add overlays to dates."
2237 (if (re-search-forward org-tsr-regexp limit t)
2238 (progn
2239 (add-text-properties (match-beginning 0) (match-end 0)
2240 (list 'mouse-face 'highlight
2241 'keymap org-mouse-map))
2242 t)))
2243
2244 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2245 "Matches CamelCase words, possibly with a star before it.")
2246 (defun org-activate-camels (limit)
2247 "Run through the buffer and add overlays to dates."
2248 (if (re-search-forward org-camel-regexp limit t)
2249 (progn
2250 (add-text-properties (match-beginning 0) (match-end 0)
2251 (list 'mouse-face 'highlight
2252 'keymap org-mouse-map))
2253 t)))
2254
2255 (defun org-activate-tags (limit)
2256 (if (re-search-forward "[ \t]\\(:[A-Za-z_:]+:\\)[ \r\n]" limit t)
2257 (progn
2258 (add-text-properties (match-beginning 1) (match-end 1)
2259 (list 'mouse-face 'highlight
2260 'keymap org-mouse-map))
2261 t)))
2262
2263 (defun org-font-lock-level ()
2264 (save-excursion
2265 (org-back-to-heading t)
2266 (- (match-end 0) (match-beginning 0))))
2267
2268 (defun org-outline-level ()
2269 (save-excursion
2270 (looking-at outline-regexp)
2271 (if (match-beginning 1)
2272 (+ (org-get-string-indentation (match-string 1)) 1000)
2273 (- (match-end 0) (match-beginning 0)))))
2274
2275 (defvar org-font-lock-keywords nil)
2276
2277 (defun org-set-font-lock-defaults ()
2278 (let ((org-font-lock-extra-keywords
2279 (list
2280 '(org-activate-links (0 'org-link t))
2281 '(org-activate-dates (0 'org-link t))
2282 '(org-activate-camels (0 'org-link t))
2283 '(org-activate-tags (1 'org-link t))
2284 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2285 '(1 'org-warning t))
2286 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2287 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2288 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2289 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2290 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2291 ;; (3 'bold))
2292 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2293 ;; (3 'italic))
2294 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2295 ;; (3 'underline))
2296 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2297 ; '(1 'org-warning t))
2298 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2299 "\\|" org-quote-string "\\)\\>")
2300 '(1 'org-special-keyword t))
2301 '("^#.*" (0 'font-lock-comment-face t))
2302 (if org-fontify-done-headline
2303 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2304 '(1 'org-done t) '(2 'org-headline-done t))
2305 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2306 '(1 'org-done t)))
2307 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2308 (1 'org-table t))
2309 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2310 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2311 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2312 )))
2313 (set (make-local-variable 'org-font-lock-keywords)
2314 (append
2315 (if org-noutline-p ; FIXME: I am not sure if eval will work
2316 ; on XEmacs if noutline is ever ported
2317 `((eval . (list "^\\(\\*+\\).*"
2318 ,(if org-level-color-stars-only 1 0)
2319 '(nth
2320 (% (- (match-end 1) (match-beginning 1) 1)
2321 org-n-levels)
2322 org-level-faces)
2323 nil t)))
2324 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2325 (,(if org-level-color-stars-only 2 0)
2326 (nth (% (- (match-end 2) (match-beginning 2) 1)
2327 org-n-levels)
2328 org-level-faces)
2329 nil t))))
2330 org-font-lock-extra-keywords))
2331 (set (make-local-variable 'font-lock-defaults)
2332 '(org-font-lock-keywords t nil nil backward-paragraph))
2333 (kill-local-variable 'font-lock-keywords) nil))
2334
2335 (defun org-unfontify-region (beg end &optional maybe_loudly)
2336 "Remove fontification and activation overlays from links."
2337 (font-lock-default-unfontify-region beg end)
2338 (let* ((buffer-undo-list t)
2339 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2340 (inhibit-modification-hooks t)
2341 deactivate-mark buffer-file-name buffer-file-truename)
2342 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2343
2344 ;;; Visibility cycling
2345
2346 (defvar org-cycle-global-status nil)
2347 (defvar org-cycle-subtree-status nil)
2348 (defun org-cycle (&optional arg)
2349 "Visibility cycling for Org-mode.
2350
2351 - When this function is called with a prefix argument, rotate the entire
2352 buffer through 3 states (global cycling)
2353 1. OVERVIEW: Show only top-level headlines.
2354 2. CONTENTS: Show all headlines of all levels, but no body text.
2355 3. SHOW ALL: Show everything.
2356
2357 - When point is at the beginning of a headline, rotate the subtree started
2358 by this line through 3 different states (local cycling)
2359 1. FOLDED: Only the main headline is shown.
2360 2. CHILDREN: The main headline and the direct children are shown. From
2361 this state, you can move to one of the children and
2362 zoom in further.
2363 3. SUBTREE: Show the entire subtree, including body text.
2364
2365 - When there is a numeric prefix, go up to a heading with level ARG, do
2366 a `show-subtree' and return to the previous cursor position. If ARG
2367 is negative, go up that many levels.
2368
2369 - When point is not at the beginning of a headline, execute
2370 `indent-relative', like TAB normally does. See the option
2371 `org-cycle-emulate-tab' for details.
2372
2373 - Special case: if point is the the beginning of the buffer and there is
2374 no headline in line 1, this function will act as if called with prefix arg."
2375 (interactive "P")
2376
2377 (if (or (and (bobp) (not (looking-at outline-regexp)))
2378 (equal arg '(4)))
2379 ;; special case: use global cycling
2380 (setq arg t))
2381
2382 (let ((outline-regexp
2383 (if org-cycle-include-plain-lists
2384 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2385 outline-regexp)))
2386
2387 (cond
2388
2389 ((org-at-table-p 'any)
2390 ;; Enter the table or move to the next field in the table
2391 (or (org-table-recognize-table.el)
2392 (progn
2393 (org-table-justify-field-maybe)
2394 (org-table-next-field))))
2395
2396 ((eq arg t) ;; Global cycling
2397
2398 (cond
2399 ((and (eq last-command this-command)
2400 (eq org-cycle-global-status 'overview))
2401 ;; We just created the overview - now do table of contents
2402 ;; This can be slow in very large buffers, so indicate action
2403 (message "CONTENTS...")
2404 (save-excursion
2405 ;; Visit all headings and show their offspring
2406 (goto-char (point-max))
2407 (catch 'exit
2408 (while (and (progn (condition-case nil
2409 (outline-previous-visible-heading 1)
2410 (error (goto-char (point-min))))
2411 t)
2412 (looking-at outline-regexp))
2413 (show-branches)
2414 (if (bobp) (throw 'exit nil))))
2415 (message "CONTENTS...done"))
2416 (setq org-cycle-global-status 'contents)
2417 (run-hook-with-args 'org-cycle-hook 'contents))
2418
2419 ((and (eq last-command this-command)
2420 (eq org-cycle-global-status 'contents))
2421 ;; We just showed the table of contents - now show everything
2422 (show-all)
2423 (message "SHOW ALL")
2424 (setq org-cycle-global-status 'all)
2425 (run-hook-with-args 'org-cycle-hook 'all))
2426
2427 (t
2428 ;; Default action: go to overview
2429 (hide-sublevels 1)
2430 (message "OVERVIEW")
2431 (setq org-cycle-global-status 'overview)
2432 (run-hook-with-args 'org-cycle-hook 'overview))))
2433
2434 ((integerp arg)
2435 ;; Show-subtree, ARG levels up from here.
2436 (save-excursion
2437 (org-back-to-heading)
2438 (outline-up-heading (if (< arg 0) (- arg)
2439 (- (outline-level) arg)))
2440 (org-show-subtree)))
2441
2442 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2443 ;; At a heading: rotate between three different views
2444 (org-back-to-heading)
2445 (let ((goal-column 0) eoh eol eos)
2446 ;; First, some boundaries
2447 (save-excursion
2448 (org-back-to-heading)
2449 (save-excursion
2450 (beginning-of-line 2)
2451 (while (and (not (eobp)) ;; this is like `next-line'
2452 (get-char-property (1- (point)) 'invisible))
2453 (beginning-of-line 2)) (setq eol (point)))
2454 (outline-end-of-heading) (setq eoh (point))
2455 (outline-end-of-subtree) (setq eos (point))
2456 (outline-next-heading))
2457 ;; Find out what to do next and set `this-command'
2458 (cond
2459 ((= eos eoh)
2460 ;; Nothing is hidden behind this heading
2461 (message "EMPTY ENTRY")
2462 (setq org-cycle-subtree-status nil))
2463 ((>= eol eos)
2464 ;; Entire subtree is hidden in one line: open it
2465 (org-show-entry)
2466 (show-children)
2467 (message "CHILDREN")
2468 (setq org-cycle-subtree-status 'children)
2469 (run-hook-with-args 'org-cycle-hook 'children))
2470 ((and (eq last-command this-command)
2471 (eq org-cycle-subtree-status 'children))
2472 ;; We just showed the children, now show everything.
2473 (org-show-subtree)
2474 (message "SUBTREE")
2475 (setq org-cycle-subtree-status 'subtree)
2476 (run-hook-with-args 'org-cycle-hook 'subtree))
2477 (t
2478 ;; Default action: hide the subtree.
2479 (hide-subtree)
2480 (message "FOLDED")
2481 (setq org-cycle-subtree-status 'folded)
2482 (run-hook-with-args 'org-cycle-hook 'folded)))))
2483
2484 ;; TAB emulation
2485 (buffer-read-only (org-back-to-heading))
2486 ((if (and (eq org-cycle-emulate-tab 'white)
2487 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2488 t
2489 (eq org-cycle-emulate-tab t))
2490 (if (and (looking-at "[ \n\r\t]")
2491 (string-match "^[ \t]*$" (buffer-substring
2492 (point-at-bol) (point))))
2493 (progn
2494 (beginning-of-line 1)
2495 (and (looking-at "[ \t]+") (replace-match ""))))
2496 (indent-relative))
2497
2498 (t (save-excursion
2499 (org-back-to-heading)
2500 (org-cycle))))))
2501
2502 (defun org-optimize-window-after-visibility-change (state)
2503 "Adjust the window after a change in outline visibility.
2504 This function is the default value of the hook `org-cycle-hook'."
2505 (cond
2506 ((eq state 'overview) (org-first-headline-recenter 1))
2507 ((eq state 'content) nil)
2508 ((eq state 'all) nil)
2509 ((eq state 'folded) nil)
2510 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2511 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2512
2513 (defun org-subtree-end-visible-p ()
2514 "Is the end of the current subtree visible?"
2515 (pos-visible-in-window-p
2516 (save-excursion (outline-end-of-subtree) (point))))
2517
2518 (defun org-first-headline-recenter (&optional N)
2519 "Move cursor to the first headline and recenter the headline.
2520 Optional argument N means, put the headline into the Nth line of the window."
2521 (goto-char (point-min))
2522 (when (re-search-forward (concat "^" outline-regexp) nil t)
2523 (beginning-of-line)
2524 (recenter (prefix-numeric-value N))))
2525
2526 (defvar org-goto-window-configuration nil)
2527 (defvar org-goto-marker nil)
2528 (defvar org-goto-map (make-sparse-keymap))
2529 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2530 (while (setq cmd (pop cmds))
2531 (substitute-key-definition cmd cmd org-goto-map global-map)))
2532 (define-key org-goto-map "\C-m" 'org-goto-ret)
2533 (define-key org-goto-map [(left)] 'org-goto-left)
2534 (define-key org-goto-map [(right)] 'org-goto-right)
2535 (define-key org-goto-map [(?q)] 'org-goto-quit)
2536 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2537 (define-key org-goto-map "\C-i" 'org-cycle)
2538 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2539 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2540 (define-key org-goto-map "n" 'outline-next-visible-heading)
2541 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2542 (define-key org-goto-map "f" 'outline-forward-same-level)
2543 (define-key org-goto-map "b" 'outline-backward-same-level)
2544 (define-key org-goto-map "u" 'outline-up-heading)
2545 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2546 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2547 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2548 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2549 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2550 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2551 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2552
2553 (defconst org-goto-help
2554 "Select a location to jump to, press RET
2555 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2556
2557 (defun org-goto ()
2558 "Go to a different location of the document, keeping current visibility.
2559
2560 When you want to go to a different location in a document, the fastest way
2561 is often to fold the entire buffer and then dive into the tree. This
2562 method has the disadvantage, that the previous location will be folded,
2563 which may not be what you want.
2564
2565 This command works around this by showing a copy of the current buffer in
2566 overview mode. You can dive into the tree in that copy, to find the
2567 location you want to reach. When pressing RET, the command returns to the
2568 original buffer in which the visibility is still unchanged. It then jumps
2569 to the new location, making it and the headline hierarchy above it visible."
2570 (interactive)
2571 (let* ((org-goto-start-pos (point))
2572 (selected-point
2573 (org-get-location (current-buffer) org-goto-help)))
2574 (if selected-point
2575 (progn
2576 (goto-char selected-point)
2577 (if (org-invisible-p) (org-show-hierarchy-above)))
2578 (error "Quit"))))
2579
2580 (defun org-get-location (buf help)
2581 "Let the user select a location in the Org-mode buffer BUF.
2582 This function uses a recursive edit. It returns the selected position
2583 or nil."
2584 (let (org-selected-point)
2585 (save-excursion
2586 (save-window-excursion
2587 (delete-other-windows)
2588 (switch-to-buffer (get-buffer-create "*org-goto*"))
2589 (with-output-to-temp-buffer "*Help*"
2590 (princ help))
2591 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2592 (setq buffer-read-only nil)
2593 (erase-buffer)
2594 (insert-buffer-substring buf)
2595 (let ((org-startup-truncated t)
2596 (org-startup-folded t)
2597 (org-startup-with-deadline-check nil))
2598 (org-mode))
2599 (setq buffer-read-only t)
2600 (if (boundp 'org-goto-start-pos)
2601 (goto-char org-goto-start-pos)
2602 (goto-char (point-min)))
2603 (org-beginning-of-line)
2604 (message "Select location and press RET")
2605 ;; now we make sure that during selection, ony very few keys work
2606 ;; and that it is impossible to switch to another window.
2607 (let ((gm (current-global-map))
2608 (overriding-local-map org-goto-map))
2609 (unwind-protect
2610 (progn
2611 (use-global-map org-goto-map)
2612 (recursive-edit))
2613 (use-global-map gm)))))
2614 (kill-buffer "*org-goto*")
2615 org-selected-point))
2616
2617 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2618 (defun org-goto-ret (&optional arg)
2619 "Finish org-goto by going to the new location."
2620 (interactive "P")
2621 (setq org-selected-point (point)
2622 current-prefix-arg arg)
2623 (throw 'exit nil))
2624
2625 (defun org-goto-left ()
2626 "Finish org-goto by going to the new location."
2627 (interactive)
2628 (if (org-on-heading-p)
2629 (progn
2630 (beginning-of-line 1)
2631 (setq org-selected-point (point)
2632 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2633 (throw 'exit nil))
2634 (error "Not on a heading")))
2635
2636 (defun org-goto-right ()
2637 "Finish org-goto by going to the new location."
2638 (interactive)
2639 (if (org-on-heading-p)
2640 (progn
2641 (outline-end-of-subtree)
2642 (or (eobp) (forward-char 1))
2643 (setq org-selected-point (point)
2644 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2645 (throw 'exit nil))
2646 (error "Not on a heading")))
2647
2648 (defun org-goto-quit ()
2649 "Finish org-goto without cursor motion."
2650 (interactive)
2651 (setq org-selected-point nil)
2652 (throw 'exit nil))
2653
2654 ;;; Promotion, Demotion, Inserting new headlines
2655
2656 (defvar org-ignore-region nil
2657 "To temporarily disable the active region.")
2658
2659 (defun org-insert-heading (&optional force-heading)
2660 "Insert a new heading or item with same depth at point.
2661 If ARG is non-nil"
2662 (interactive "P")
2663 (when (or force-heading (not (org-insert-item)))
2664 (let* ((head (save-excursion
2665 (condition-case nil
2666 (org-back-to-heading)
2667 (error (outline-next-heading)))
2668 (prog1 (match-string 0)
2669 (funcall outline-level)))))
2670 (unless (bolp) (newline))
2671 (insert head)
2672 (unless (eolp)
2673 (save-excursion (newline-and-indent)))
2674 (unless (equal (char-before) ?\ )
2675 (insert " "))
2676 (run-hooks 'org-insert-heading-hook))))
2677
2678 (defun org-insert-item ()
2679 "Insert a new item at the current level.
2680 Return t when tings worked, nil when we are not in an item."
2681 (when (save-excursion
2682 (condition-case nil
2683 (progn
2684 (org-beginning-of-item)
2685 (org-at-item-p)
2686 t)
2687 (error nil)))
2688 (unless (bolp) (newline))
2689 (insert (match-string 0))
2690 (org-maybe-renumber-ordered-list)
2691 t))
2692
2693 (defun org-insert-todo-heading (arg)
2694 "Insert a new heading with the same level and TODO state as current heading.
2695 If the heading has no TODO state, or if the state is DONE, use the first
2696 state (TODO by default). Also with prefix arg, force first state."
2697 (interactive "P")
2698 (org-insert-heading)
2699 (save-excursion
2700 (org-back-to-heading)
2701 (outline-previous-heading)
2702 (looking-at org-todo-line-regexp))
2703 (if (or arg
2704 (not (match-beginning 2))
2705 (equal (match-string 2) org-done-string))
2706 (insert (car org-todo-keywords) " ")
2707 (insert (match-string 2) " ")))
2708
2709 (defun org-promote-subtree ()
2710 "Promote the entire subtree.
2711 See also `org-promote'."
2712 (interactive)
2713 (save-excursion
2714 (org-map-tree 'org-promote)))
2715
2716 (defun org-demote-subtree ()
2717 "Demote the entire subtree. See `org-demote'.
2718 See also `org-promote'."
2719 (interactive)
2720 (save-excursion
2721 (org-map-tree 'org-demote)))
2722
2723 (defun org-do-promote ()
2724 "Promote the current heading higher up the tree.
2725 If the region is active in `transient-mark-mode', promote all headings
2726 in the region."
2727 (interactive)
2728 (save-excursion
2729 (if (org-region-active-p)
2730 (org-map-region 'org-promote (region-beginning) (region-end))
2731 (org-promote)))
2732 (org-fix-position-after-promote))
2733
2734 (defun org-do-demote ()
2735 "Demote the current heading lower down the tree.
2736 If the region is active in `transient-mark-mode', demote all headings
2737 in the region."
2738 (interactive)
2739 (save-excursion
2740 (if (org-region-active-p)
2741 (org-map-region 'org-demote (region-beginning) (region-end))
2742 (org-demote)))
2743 (org-fix-position-after-promote))
2744
2745 (defun org-fix-position-after-promote ()
2746 "Make sure that after pro/demotion cursor position is right."
2747 (and (equal (char-after) ?\ )
2748 (equal (char-before) ?*)
2749 (forward-char 1)))
2750
2751 (defun org-promote ()
2752 "Promote the current heading higher up the tree.
2753 If the region is active in `transient-mark-mode', promote all headings
2754 in the region."
2755 (org-back-to-heading t)
2756 (let* ((level (save-match-data (funcall outline-level)))
2757 (up-head (make-string (1- level) ?*)))
2758 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2759 (replace-match up-head nil t)
2760 ;; Fixup tag positioning
2761 (and org-auto-align-tags (org-set-tags nil t))
2762 (if org-adapt-indentation
2763 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2764
2765 (defun org-demote ()
2766 "Demote the current heading lower down the tree.
2767 If the region is active in `transient-mark-mode', demote all headings
2768 in the region."
2769 (org-back-to-heading t)
2770 (let* ((level (save-match-data (funcall outline-level)))
2771 (down-head (make-string (1+ level) ?*)))
2772 (replace-match down-head nil t)
2773 ;; Fixup tag positioning
2774 (and org-auto-align-tags (org-set-tags nil t))
2775 (if org-adapt-indentation
2776 (org-fixup-indentation "^ " " " "^\\S-"))))
2777
2778 (defun org-map-tree (fun)
2779 "Call FUN for every heading underneath the current one."
2780 (org-back-to-heading)
2781 (let ((level (outline-level)))
2782 (save-excursion
2783 (funcall fun)
2784 (while (and (progn
2785 (outline-next-heading)
2786 (> (funcall outline-level) level))
2787 (not (eobp)))
2788 (funcall fun)))))
2789
2790 (defun org-map-region (fun beg end)
2791 "Call FUN for every heading between BEG and END."
2792 (let ((org-ignore-region t))
2793 (save-excursion
2794 (setq end (copy-marker end))
2795 (goto-char beg)
2796 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2797 (< (point) end))
2798 (funcall fun))
2799 (while (and (progn
2800 (outline-next-heading)
2801 (< (point) end))
2802 (not (eobp)))
2803 (funcall fun)))))
2804
2805 (defun org-fixup-indentation (from to prohibit)
2806 "Change the indentation in the current entry by re-replacing FROM with TO.
2807 However, if the regexp PROHIBIT matches at all, don't do anything.
2808 This is being used to change indentation along with the length of the
2809 heading marker. But if there are any lines which are not indented, nothing
2810 is changed at all."
2811 (save-excursion
2812 (let ((end (save-excursion (outline-next-heading)
2813 (point-marker))))
2814 (unless (save-excursion (re-search-forward prohibit end t))
2815 (while (re-search-forward from end t)
2816 (replace-match to)
2817 (beginning-of-line 2)))
2818 (move-marker end nil))))
2819
2820 ;;; Vertical tree motion, cutting and pasting of subtrees
2821
2822 (defun org-move-subtree-up (&optional arg)
2823 "Move the current subtree up past ARG headlines of the same level."
2824 (interactive "p")
2825 (org-move-subtree-down (- (prefix-numeric-value arg))))
2826
2827 (defun org-move-subtree-down (&optional arg)
2828 "Move the current subtree down past ARG headlines of the same level."
2829 (interactive "p")
2830 (setq arg (prefix-numeric-value arg))
2831 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2832 'outline-get-last-sibling))
2833 (ins-point (make-marker))
2834 (cnt (abs arg))
2835 beg end txt folded)
2836 ;; Select the tree
2837 (org-back-to-heading)
2838 (setq beg (point))
2839 (save-match-data
2840 (save-excursion (outline-end-of-heading)
2841 (setq folded (org-invisible-p)))
2842 (outline-end-of-subtree))
2843 (outline-next-heading)
2844 (setq end (point))
2845 ;; Find insertion point, with error handling
2846 (goto-char beg)
2847 (while (> cnt 0)
2848 (or (and (funcall movfunc) (looking-at outline-regexp))
2849 (progn (goto-char beg)
2850 (error "Cannot move past superior level or buffer limit")))
2851 (setq cnt (1- cnt)))
2852 (if (> arg 0)
2853 ;; Moving forward - still need to move over subtree
2854 (progn (outline-end-of-subtree)
2855 (outline-next-heading)
2856 (if (not (or (looking-at (concat "^" outline-regexp))
2857 (bolp)))
2858 (newline))))
2859 (move-marker ins-point (point))
2860 (setq txt (buffer-substring beg end))
2861 (delete-region beg end)
2862 (insert txt)
2863 (goto-char ins-point)
2864 (if folded (hide-subtree))
2865 (move-marker ins-point nil)))
2866
2867 (defvar org-subtree-clip ""
2868 "Clipboard for cut and paste of subtrees.
2869 This is actually only a copy of the kill, because we use the normal kill
2870 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2871
2872 (defvar org-subtree-clip-folded nil
2873 "Was the last copied subtree folded?
2874 This is used to fold the tree back after pasting.")
2875
2876 (defun org-cut-subtree ()
2877 "Cut the current subtree into the clipboard.
2878 This is a short-hand for marking the subtree and then cutting it."
2879 (interactive)
2880 (org-copy-subtree 'cut))
2881
2882 (defun org-copy-subtree (&optional cut)
2883 "Cut the current subtree into the clipboard.
2884 This is a short-hand for marking the subtree and then copying it.
2885 If CUT is non nil, actually cut the subtree."
2886 (interactive)
2887 (let (beg end folded)
2888 (org-back-to-heading)
2889 (setq beg (point))
2890 (save-match-data
2891 (save-excursion (outline-end-of-heading)
2892 (setq folded (org-invisible-p)))
2893 (outline-end-of-subtree))
2894 (if (equal (char-after) ?\n) (forward-char 1))
2895 (setq end (point))
2896 (goto-char beg)
2897 (when (> end beg)
2898 (setq org-subtree-clip-folded folded)
2899 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2900 (setq org-subtree-clip (current-kill 0))
2901 (message "%s: Subtree with %d characters"
2902 (if cut "Cut" "Copied")
2903 (length org-subtree-clip)))))
2904
2905 (defun org-paste-subtree (&optional level tree)
2906 "Paste the clipboard as a subtree, with modification of headline level.
2907 The entire subtree is promoted or demoted in order to match a new headline
2908 level. By default, the new level is derived from the visible headings
2909 before and after the insertion point, and taken to be the inferior headline
2910 level of the two. So if the previous visible heading is level 3 and the
2911 next is level 4 (or vice versa), level 4 will be used for insertion.
2912 This makes sure that the subtree remains an independent subtree and does
2913 not swallow low level entries.
2914
2915 You can also force a different level, either by using a numeric prefix
2916 argument, or by inserting the heading marker by hand. For example, if the
2917 cursor is after \"*****\", then the tree will be shifted to level 5.
2918
2919 If you want to insert the tree as is, just use \\[yank].
2920
2921 If optional TREE is given, use this text instead of the kill ring."
2922 (interactive "P")
2923 (unless (org-kill-is-subtree-p tree)
2924 (error
2925 (substitute-command-keys
2926 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2927 (let* ((txt (or tree (current-kill 0)))
2928 (^re (concat "^\\(" outline-regexp "\\)"))
2929 (re (concat "\\(" outline-regexp "\\)"))
2930 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2931
2932 (old-level (if (string-match ^re txt)
2933 (- (match-end 0) (match-beginning 0))
2934 -1))
2935 (force-level (cond (level (prefix-numeric-value level))
2936 ((string-match
2937 ^re_ (buffer-substring (point-at-bol) (point)))
2938 (- (match-end 0) (match-beginning 0)))
2939 (t nil)))
2940 (previous-level (save-excursion
2941 (condition-case nil
2942 (progn
2943 (outline-previous-visible-heading 1)
2944 (if (looking-at re)
2945 (- (match-end 0) (match-beginning 0))
2946 1))
2947 (error 1))))
2948 (next-level (save-excursion
2949 (condition-case nil
2950 (progn
2951 (outline-next-visible-heading 1)
2952 (if (looking-at re)
2953 (- (match-end 0) (match-beginning 0))
2954 1))
2955 (error 1))))
2956 (new-level (or force-level (max previous-level next-level)))
2957 (shift (if (or (= old-level -1)
2958 (= new-level -1)
2959 (= old-level new-level))
2960 0
2961 (- new-level old-level)))
2962 (shift1 shift)
2963 (delta (if (> shift 0) -1 1))
2964 (func (if (> shift 0) 'org-demote 'org-promote))
2965 beg end)
2966 ;; Remove the forces level indicator
2967 (if force-level
2968 (delete-region (point-at-bol) (point)))
2969 ;; Make sure we start at the beginning of an empty line
2970 (if (not (bolp)) (insert "\n"))
2971 (if (not (looking-at "[ \t]*$"))
2972 (progn (insert "\n") (backward-char 1)))
2973 ;; Paste
2974 (setq beg (point))
2975 (insert txt)
2976 (setq end (point))
2977 (goto-char beg)
2978 ;; Shift if necessary
2979 (if (= shift 0)
2980 (message "Pasted at level %d, without shift" new-level)
2981 (save-restriction
2982 (narrow-to-region beg end)
2983 (while (not (= shift 0))
2984 (org-map-region func (point-min) (point-max))
2985 (setq shift (+ delta shift)))
2986 (goto-char (point-min))
2987 (message "Pasted at level %d, with shift by %d levels"
2988 new-level shift1)))
2989 (if (and (eq org-subtree-clip (current-kill 0))
2990 org-subtree-clip-folded)
2991 ;; The tree was folded before it was killed/copied
2992 (hide-subtree))))
2993
2994 (defun org-kill-is-subtree-p (&optional txt)
2995 "Check if the current kill is an outline subtree, or a set of trees.
2996 Returns nil if kill does not start with a headline, or if the first
2997 headline level is not the largest headline level in the tree.
2998 So this will actually accept several entries of equal levels as well,
2999 which is OK for `org-paste-subtree'.
3000 If optional TXT is given, check this string instead of the current kill."
3001 (let* ((kill (or txt (current-kill 0) ""))
3002 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3003 (- (match-end 0) (match-beginning 0))))
3004 (re (concat "^" outline-regexp))
3005 (start 1))
3006 (if (not start-level)
3007 nil ;; does not even start with a heading
3008 (catch 'exit
3009 (while (setq start (string-match re kill (1+ start)))
3010 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3011 (throw 'exit nil)))
3012 t))))
3013
3014 ;;; Plain list items
3015
3016 (defun org-at-item-p ()
3017 "Is point in a line starting a hand-formatted item?"
3018 (let ((llt org-plain-list-ordered-item-terminator))
3019 (save-excursion
3020 (goto-char (point-at-bol))
3021 (looking-at
3022 (cond
3023 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3024 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3025 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3026 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3027
3028 (defun org-get-indentation ()
3029 "Get the indentation of the current line, ionterpreting tabs."
3030 (save-excursion
3031 (beginning-of-line 1)
3032 (skip-chars-forward " \t")
3033 (current-column)))
3034
3035 (defun org-beginning-of-item ()
3036 "Go to the beginning of the current hand-formatted item.
3037 If the cursor is not in an item, throw an error."
3038 (let ((pos (point))
3039 (limit (save-excursion (org-back-to-heading)
3040 (beginning-of-line 2) (point)))
3041 ind ind1)
3042 (if (org-at-item-p)
3043 (beginning-of-line 1)
3044 (beginning-of-line 1)
3045 (skip-chars-forward " \t")
3046 (setq ind (current-column))
3047 (if (catch 'exit
3048 (while t
3049 (beginning-of-line 0)
3050 (if (< (point) limit) (throw 'exit nil))
3051 (unless (looking-at " \t]*$")
3052 (skip-chars-forward " \t")
3053 (setq ind1 (current-column))
3054 (if (< ind1 ind)
3055 (throw 'exit (org-at-item-p))))))
3056 nil
3057 (goto-char pos)
3058 (error "Not in an item")))))
3059
3060 (defun org-end-of-item ()
3061 "Go to the beginning of the current hand-formatted item.
3062 If the cursor is not in an item, throw an error."
3063 (let ((pos (point))
3064 (limit (save-excursion (outline-next-heading) (point)))
3065 (ind (save-excursion
3066 (org-beginning-of-item)
3067 (skip-chars-forward " \t")
3068 (current-column)))
3069 ind1)
3070 (if (catch 'exit
3071 (while t
3072 (beginning-of-line 2)
3073 (if (>= (point) limit) (throw 'exit t))
3074 (unless (looking-at "[ \t]*$")
3075 (skip-chars-forward " \t")
3076 (setq ind1 (current-column))
3077 (if (<= ind1 ind) (throw 'exit t)))))
3078 (beginning-of-line 1)
3079 (goto-char pos)
3080 (error "Not in an item"))))
3081
3082 (defun org-move-item-down (arg)
3083 "Move the plain list item at point down, i.e. swap with following item.
3084 Subitems (items with larger indentation are considered part of the item,
3085 so this really moves item trees."
3086 (interactive "p")
3087 (let (beg end ind ind1 (pos (point)) txt)
3088 (org-beginning-of-item)
3089 (setq beg (point))
3090 (setq ind (org-get-indentation))
3091 (org-end-of-item)
3092 (setq end (point))
3093 (setq ind1 (org-get-indentation))
3094 (if (and (org-at-item-p) (= ind ind1))
3095 (progn
3096 (org-end-of-item)
3097 (setq txt (buffer-substring beg end))
3098 (save-excursion
3099 (delete-region beg end))
3100 (setq pos (point))
3101 (insert txt)
3102 (goto-char pos)
3103 (org-maybe-renumber-ordered-list))
3104 (goto-char pos)
3105 (error "Cannot move this item further down"))))
3106
3107 (defun org-move-item-up (arg)
3108 "Move the plain list item at point up, i.e. swap with previous item.
3109 Subitems (items with larger indentation are considered part of the item,
3110 so this really moves item trees."
3111 (interactive "p")
3112 (let (beg end ind ind1 (pos (point)) txt)
3113 (org-beginning-of-item)
3114 (setq beg (point))
3115 (setq ind (org-get-indentation))
3116 (org-end-of-item)
3117 (setq end (point))
3118 (goto-char beg)
3119 (catch 'exit
3120 (while t
3121 (beginning-of-line 0)
3122 (if (looking-at "[ \t]*$")
3123 nil
3124 (if (<= (setq ind1 (org-get-indentation)) ind)
3125 (throw 'exit t)))))
3126 (condition-case nil
3127 (org-beginning-of-item)
3128 (error (goto-char beg)
3129 (error "Cannot move this item further up")))
3130 (setq ind1 (org-get-indentation))
3131 (if (and (org-at-item-p) (= ind ind1))
3132 (progn
3133 (setq txt (buffer-substring beg end))
3134 (save-excursion
3135 (delete-region beg end))
3136 (setq pos (point))
3137 (insert txt)
3138 (goto-char pos)
3139 (org-maybe-renumber-ordered-list))
3140 (goto-char pos)
3141 (error "Cannot move this item further up"))))
3142
3143 (defun org-maybe-renumber-ordered-list ()
3144 "Renumber the ordered list at point if setup allows it.
3145 This tests the user option `org-auto-renumber-ordered-lists' before
3146 doing the renumbering."
3147 (and org-auto-renumber-ordered-lists
3148 (org-at-item-p)
3149 (match-beginning 3)
3150 (org-renumber-ordered-list 1)))
3151
3152 (defun org-get-string-indentation (s)
3153 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3154 (let ((n -1) (i 0) (w tab-width) c)
3155 (catch 'exit
3156 (while (< (setq n (1+ n)) (length s))
3157 (setq c (aref s n))
3158 (cond ((= c ?\ ) (setq i (1+ i)))
3159 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3160 (t (throw 'exit t)))))
3161 i))
3162
3163 (defun org-renumber-ordered-list (arg)
3164 "Renumber an ordered plain list.
3165 Cursor neext to be in the first line of an item, the line that starts
3166 with something like \"1.\" or \"2)\"."
3167 (interactive "p")
3168 (unless (and (org-at-item-p)
3169 (match-beginning 3))
3170 (error "This is not an ordered list"))
3171 (let ((line (org-current-line))
3172 (col (current-column))
3173 (ind (org-get-string-indentation
3174 (buffer-substring (point-at-bol) (match-beginning 3))))
3175 ;; (term (substring (match-string 3) -1))
3176 ind1 (n (1- arg)))
3177 ;; find where this list begins
3178 (catch 'exit
3179 (while t
3180 (catch 'next
3181 (beginning-of-line 0)
3182 (if (looking-at "[ \t]*$") (throw 'next t))
3183 (skip-chars-forward " \t") (setq ind1 (current-column))
3184 (if (or (< ind1 ind)
3185 (and (= ind1 ind)
3186 (not (org-at-item-p))))
3187 (throw 'exit t)))))
3188 ;; Walk forward and replace these numbers
3189 (catch 'exit
3190 (while t
3191 (catch 'next
3192 (beginning-of-line 2)
3193 (if (eobp) (throw 'exit nil))
3194 (if (looking-at "[ \t]*$") (throw 'next nil))
3195 (skip-chars-forward " \t") (setq ind1 (current-column))
3196 (if (> ind1 ind) (throw 'next t))
3197 (if (< ind1 ind) (throw 'exit t))
3198 (if (not (org-at-item-p)) (throw 'exit nil))
3199 (if (not (match-beginning 3))
3200 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3201 (delete-region (match-beginning 3) (1- (match-end 3)))
3202 (goto-char (match-beginning 3))
3203 (insert (format "%d" (setq n (1+ n)))))))
3204 (goto-line line)
3205 (move-to-column col)))
3206
3207 (defvar org-last-indent-begin-marker (make-marker))
3208 (defvar org-last-indent-end-marker (make-marker))
3209
3210
3211 (defun org-outdent-item (arg)
3212 "Outdent a local list item."
3213 (interactive "p")
3214 (org-indent-item (- arg)))
3215
3216 (defun org-indent-item (arg)
3217 "Indent a local list item."
3218 (interactive "p")
3219 (unless (org-at-item-p)
3220 (error "Not on an item"))
3221 (let (beg end ind ind1)
3222 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3223 (setq beg org-last-indent-begin-marker
3224 end org-last-indent-end-marker)
3225 (org-beginning-of-item)
3226 (setq beg (move-marker org-last-indent-begin-marker (point)))
3227 (org-end-of-item)
3228 (setq end (move-marker org-last-indent-end-marker (point))))
3229 (goto-char beg)
3230 (skip-chars-forward " \t") (setq ind (current-column))
3231 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3232 (while (< (point) end)
3233 (beginning-of-line 1)
3234 (skip-chars-forward " \t") (setq ind1 (current-column))
3235 (delete-region (point-at-bol) (point))
3236 (indent-to-column (+ ind1 arg))
3237 (beginning-of-line 2))
3238 (goto-char beg)))
3239
3240 ;;; Archiving
3241
3242 (defun org-archive-subtree ()
3243 "Move the current subtree to the archive.
3244 The archive can be a certain top-level heading in the current file, or in
3245 a different file. The tree will be moved to that location, the subtree
3246 heading be marked DONE, and the current time will be added."
3247 (interactive)
3248 ;; Save all relevant TODO keyword-relatex variables
3249 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3250 (tr-org-todo-keywords org-todo-keywords)
3251 (tr-org-todo-interpretation org-todo-interpretation)
3252 (tr-org-done-string org-done-string)
3253 (tr-org-todo-regexp org-todo-regexp)
3254 (tr-org-todo-line-regexp org-todo-line-regexp)
3255 (this-buffer (current-buffer))
3256 file heading buffer level newfile-p)
3257 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3258 (progn
3259 (setq file (format (match-string 1 org-archive-location)
3260 (file-name-nondirectory (buffer-file-name)))
3261 heading (match-string 2 org-archive-location)))
3262 (error "Invalid `org-archive-location'"))
3263 (if (> (length file) 0)
3264 (setq newfile-p (not (file-exists-p file))
3265 buffer (find-file-noselect file))
3266 (setq buffer (current-buffer)))
3267 (unless buffer
3268 (error "Cannot access file \"%s\"" file))
3269 (if (and (> (length heading) 0)
3270 (string-match "^\\*+" heading))
3271 (setq level (match-end 0))
3272 (setq heading nil level 0))
3273 (save-excursion
3274 ;; We first only copy, in case something goes wrong
3275 ;; we need to protect this-command, to avoid kill-region sets it,
3276 ;; which would lead to duplication of subtrees
3277 (let (this-command) (org-copy-subtree))
3278 (set-buffer buffer)
3279 ;; Enforce org-mode for the archive buffer
3280 (if (not (eq major-mode 'org-mode))
3281 ;; Force the mode for future visits.
3282 (let ((org-insert-mode-line-in-empty-file t))
3283 (call-interactively 'org-mode)))
3284 (when newfile-p
3285 (goto-char (point-max))
3286 (insert (format "\nArchived entries from file %s\n\n"
3287 (buffer-file-name this-buffer))))
3288 ;; Force the TODO keywords of the original buffer
3289 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3290 (org-todo-keywords tr-org-todo-keywords)
3291 (org-todo-interpretation tr-org-todo-interpretation)
3292 (org-done-string tr-org-done-string)
3293 (org-todo-regexp tr-org-todo-regexp)
3294 (org-todo-line-regexp tr-org-todo-line-regexp))
3295 (goto-char (point-min))
3296 (if heading
3297 (progn
3298 (if (re-search-forward
3299 (concat "\\(^\\|\r\\)"
3300 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3301 nil t)
3302 (goto-char (match-end 0))
3303 ;; Heading not found, just insert it at the end
3304 (goto-char (point-max))
3305 (or (bolp) (insert "\n"))
3306 (insert "\n" heading "\n")
3307 (end-of-line 0))
3308 ;; Make the heading visible, and the following as well
3309 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3310 (if (re-search-forward
3311 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3312 nil t)
3313 (progn (goto-char (match-beginning 0)) (insert "\n")
3314 (beginning-of-line 0))
3315 (goto-char (point-max)) (insert "\n")))
3316 (goto-char (point-max)) (insert "\n"))
3317 ;; Paste
3318 (org-paste-subtree (1+ level))
3319 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3320 (if org-archive-mark-done
3321 (org-todo (length org-todo-keywords)))
3322 ;; Move cursor to right after the TODO keyword
3323 (when org-archive-stamp-time
3324 (beginning-of-line 1)
3325 (looking-at org-todo-line-regexp)
3326 (goto-char (or (match-end 2) (match-beginning 3)))
3327 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3328 (current-time))
3329 ")"))
3330 ;; Save the buffer, if it is not the same buffer.
3331 (if (not (eq this-buffer buffer)) (save-buffer))))
3332 ;; Here we are back in the original buffer. Everything seems to have
3333 ;; worked. So now cut the tree and finish up.
3334 (let (this-command) (org-cut-subtree))
3335 (if (looking-at "[ \t]*$") (kill-line))
3336 (message "Subtree archived %s"
3337 (if (eq this-buffer buffer)
3338 (concat "under heading: " heading)
3339 (concat "in file: " (abbreviate-file-name file))))))
3340
3341 ;;; Completion
3342
3343 (defun org-complete (&optional arg)
3344 "Perform completion on word at point.
3345 At the beginning of a headline, this completes TODO keywords as given in
3346 `org-todo-keywords'.
3347 If the current word is preceded by a backslash, completes the TeX symbols
3348 that are supported for HTML support.
3349 If the current word is preceded by \"#+\", completes special words for
3350 setting file options.
3351 At all other locations, this simply calls `ispell-complete-word'."
3352 (interactive "P")
3353 (catch 'exit
3354 (let* ((end (point))
3355 (beg1 (save-excursion
3356 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3357 (skip-chars-backward "a-zA-Z_")
3358 (point)))
3359 (beg (save-excursion
3360 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3361 (skip-chars-backward "a-zA-Z0-9_:$")
3362 (point)))
3363 (camel (equal (char-before beg) ?*))
3364 (tag (equal (char-before beg1) ?:))
3365 (texp (equal (char-before beg) ?\\))
3366 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3367 beg)
3368 "#+"))
3369 (completion-ignore-case opt)
3370 (type nil)
3371 (tbl nil)
3372 (table (cond
3373 (opt
3374 (setq type :opt)
3375 (mapcar (lambda (x)
3376 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3377 (cons (match-string 2 x) (match-string 1 x)))
3378 (org-split-string (org-get-current-options) "\n")))
3379 (texp
3380 (setq type :tex)
3381 org-html-entities)
3382 ((string-match "\\`\\*+[ \t]*\\'"
3383 (buffer-substring (point-at-bol) beg))
3384 (setq type :todo)
3385 (mapcar 'list org-todo-keywords))
3386 (camel
3387 (setq type :camel)
3388 (save-excursion
3389 (goto-char (point-min))
3390 (while (re-search-forward org-todo-line-regexp nil t)
3391 (push (list (org-make-org-heading-camel (match-string 3)))
3392 tbl)))
3393 tbl)
3394 (tag (setq type :tag beg beg1)
3395 (org-get-buffer-tags))
3396 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3397 (pattern (buffer-substring-no-properties beg end))
3398 (completion (try-completion pattern table)))
3399 (cond ((eq completion t)
3400 (if (equal type :opt)
3401 (insert (substring (cdr (assoc (upcase pattern) table))
3402 (length pattern)))))
3403 ((null completion)
3404 (message "Can't find completion for \"%s\"" pattern)
3405 (ding))
3406 ((not (string= pattern completion))
3407 (delete-region beg end)
3408 (if (string-match " +$" completion)
3409 (setq completion (replace-match "" t t completion)))
3410 (insert completion)
3411 (if (get-buffer-window "*Completions*")
3412 (delete-window (get-buffer-window "*Completions*")))
3413 (if (assoc completion table)
3414 (if (eq type :todo) (insert " ")
3415 (if (eq type :tag) (insert ":"))))
3416 (if (and (equal type :opt) (assoc completion table))
3417 (message "%s" (substitute-command-keys
3418 "Press \\[org-complete] again to insert example settings"))))
3419 (t
3420 (message "Making completion list...")
3421 (let ((list (sort (all-completions pattern table) 'string<)))
3422 (with-output-to-temp-buffer "*Completions*"
3423 (display-completion-list list)))
3424 (message "Making completion list...%s" "done"))))))
3425
3426 ;;; Comments, TODO and DEADLINE
3427
3428 (defun org-toggle-comment ()
3429 "Change the COMMENT state of an entry."
3430 (interactive)
3431 (save-excursion
3432 (org-back-to-heading)
3433 (if (looking-at (concat outline-regexp
3434 "\\( +\\<" org-comment-string "\\>\\)"))
3435 (replace-match "" t t nil 1)
3436 (if (looking-at outline-regexp)
3437 (progn
3438 (goto-char (match-end 0))
3439 (insert " " org-comment-string))))))
3440
3441 (defvar org-last-todo-state-is-todo nil
3442 "This is non-nil when the last TODO state change led to a TODO state.
3443 If the last change removed the TODO tag or switched to DONE, then
3444 this is nil.")
3445
3446 (defun org-todo (&optional arg)
3447 "Change the TODO state of an item.
3448 The state of an item is given by a keyword at the start of the heading,
3449 like
3450 *** TODO Write paper
3451 *** DONE Call mom
3452
3453 The different keywords are specified in the variable `org-todo-keywords'. By
3454 default the available states are \"TODO\" and \"DONE\".
3455 So for this example: when the item starts with TODO, it is changed to DONE.
3456 When it starts with DONE, the DONE is removed. And when neither TODO nor
3457 DONE are present, add TODO at the beginning of the heading.
3458
3459 With prefix arg, use completion to determined the new state. With numeric
3460 prefix arg, switch to that state."
3461 (interactive "P")
3462 (save-excursion
3463 (org-back-to-heading)
3464 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3465 (or (looking-at (concat " +" org-todo-regexp " *"))
3466 (looking-at " *"))
3467 (let* ((this (match-string 1))
3468 (completion-ignore-case t)
3469 (member (member this org-todo-keywords))
3470 (tail (cdr member))
3471 (state (cond
3472 ((equal arg '(4))
3473 ;; Read a state with completion
3474 (completing-read "State: " (mapcar (lambda(x) (list x))
3475 org-todo-keywords)
3476 nil t))
3477 ((eq arg 'right)
3478 (if this
3479 (if tail (car tail) nil)
3480 (car org-todo-keywords)))
3481 ((eq arg 'left)
3482 (if (equal member org-todo-keywords)
3483 nil
3484 (if this
3485 (nth (- (length org-todo-keywords) (length tail) 2)
3486 org-todo-keywords)
3487 org-done-string)))
3488 (arg
3489 ;; user requests a specific state
3490 (nth (1- (prefix-numeric-value arg))
3491 org-todo-keywords))
3492 ((null member) (car org-todo-keywords))
3493 ((null tail) nil) ;; -> first entry
3494 ((eq org-todo-interpretation 'sequence)
3495 (car tail))
3496 ((memq org-todo-interpretation '(type priority))
3497 (if (eq this-command last-command)
3498 (car tail)
3499 (if (> (length tail) 0) org-done-string nil)))
3500 (t nil)))
3501 (next (if state (concat " " state " ") " ")))
3502 (replace-match next t t)
3503 (setq org-last-todo-state-is-todo
3504 (not (equal state org-done-string)))
3505 (when org-log-done
3506 (if (equal state org-done-string)
3507 (org-log-done)
3508 (if (not this)
3509 (org-log-done t))))
3510 ;; Fixup tag positioning
3511 (and org-auto-align-tags (org-set-tags nil t))
3512 (run-hooks 'org-after-todo-state-change-hook)))
3513 ;; Fixup cursor location if close to the keyword
3514 (if (and (outline-on-heading-p)
3515 (not (bolp))
3516 (save-excursion (beginning-of-line 1)
3517 (looking-at org-todo-line-regexp))
3518 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3519 (progn
3520 (goto-char (or (match-end 2) (match-end 1)))
3521 (just-one-space))))
3522
3523 (defun org-log-done (&optional undone)
3524 "Add a time stamp logging that a TODO entry has been closed.
3525 When UNDONE is non-nil, remove such a time stamg again."
3526 (interactive)
3527 (let (beg end col)
3528 (save-excursion
3529 (org-back-to-heading t)
3530 (setq beg (point))
3531 (looking-at (concat outline-regexp " *"))
3532 (goto-char (match-end 0))
3533 (setq col (current-column))
3534 (outline-next-heading)
3535 (setq end (point))
3536 (goto-char beg)
3537 (when (re-search-forward (concat
3538 "[\r\n]\\([ \t]*"
3539 (regexp-quote org-closed-string)
3540 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3541 (delete-region (match-beginning 1) (match-end 1)))
3542 (unless undone
3543 (org-back-to-heading t)
3544 (skip-chars-forward "^\n\r")
3545 (goto-char (min (1+ (point)) (point-max)))
3546 (when (not (member (char-before) '(?\r ?\n)))
3547 (insert "\n"))
3548 (indent-to col)
3549 (insert org-closed-string " "
3550 (format-time-string
3551 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3552 (current-time))
3553 "\n")))))
3554
3555 (defun org-show-todo-tree (arg)
3556 "Make a compact tree which shows all headlines marked with TODO.
3557 The tree will show the lines where the regexp matches, and all higher
3558 headlines above the match.
3559 With \\[universal-argument] prefix, also show the DONE entries.
3560 With a numeric prefix N, construct a sparse tree for the Nth element
3561 of `org-todo-keywords'."
3562 (interactive "P")
3563 (let ((case-fold-search nil)
3564 (kwd-re
3565 (cond ((null arg) org-not-done-regexp)
3566 ((equal arg '(4)) org-todo-regexp)
3567 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3568 (regexp-quote (nth (1- (prefix-numeric-value arg))
3569 org-todo-keywords)))
3570 (t (error "Invalid prefix argument: %s" arg)))))
3571 (message "%d TODO entries found"
3572 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3573
3574 (defun org-deadline ()
3575 "Insert the DEADLINE: string to make a deadline.
3576 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3577 to modify it to the correct date."
3578 (interactive)
3579 (insert
3580 org-deadline-string " "
3581 (format-time-string (car org-time-stamp-formats)
3582 (org-read-date nil 'to-time)))
3583 (message "%s" (substitute-command-keys
3584 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3585
3586 (defun org-schedule ()
3587 "Insert the SCHEDULED: string to schedule a TODO item.
3588 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3589 to modify it to the correct date."
3590 (interactive)
3591 (insert
3592 org-scheduled-string " "
3593 (format-time-string (car org-time-stamp-formats)
3594 (org-read-date nil 'to-time)))
3595 (message "%s" (substitute-command-keys
3596 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3597
3598
3599 (defun org-occur (regexp &optional callback)
3600 "Make a compact tree which shows all matches of REGEXP.
3601 The tree will show the lines where the regexp matches, and all higher
3602 headlines above the match. It will also show the heading after the match,
3603 to make sure editing the matching entry is easy.
3604 if CALLBACK is non-nil, it is a function which is called to confirm
3605 that the match should indeed be shown."
3606 (interactive "sRegexp: ")
3607 (org-remove-occur-highlights nil nil t)
3608 (setq regexp (org-check-occur-regexp regexp))
3609 (let ((cnt 0))
3610 (save-excursion
3611 (goto-char (point-min))
3612 (hide-sublevels 1)
3613 (while (re-search-forward regexp nil t)
3614 (when (or (not callback)
3615 (save-match-data (funcall callback)))
3616 (setq cnt (1+ cnt))
3617 (org-highlight-new-match (match-beginning 0) (match-end 0))
3618 (org-show-hierarchy-above))))
3619 (make-local-hook 'before-change-functions) ; needed for XEmacs
3620 (add-hook 'before-change-functions 'org-remove-occur-highlights
3621 nil 'local)
3622 (run-hooks 'org-occur-hook)
3623 (if (interactive-p)
3624 (message "%d match(es) for regexp %s" cnt regexp))
3625 cnt))
3626
3627 (defun org-show-hierarchy-above ()
3628 "Make sure point and the headings hierarchy above is visible."
3629 (if (org-on-heading-p t)
3630 (org-flag-heading nil) ; only show the heading
3631 (and (org-invisible-p) (org-show-hidden-entry))) ; show entire entry
3632 (save-excursion
3633 (and org-show-following-heading
3634 (outline-next-heading)
3635 (org-flag-heading nil))) ; show the next heading
3636 (when org-show-hierarchy-above
3637 (save-excursion ; show all higher headings
3638 (while (condition-case nil
3639 (progn (org-up-heading-all 1) t)
3640 (error nil))
3641 (org-flag-heading nil)))))
3642
3643 (defvar org-occur-highlights nil)
3644 (defun org-highlight-new-match (beg end)
3645 "Highlight from BEG to END and mark the highlight is an occur headline."
3646 (let ((ov (make-overlay beg end)))
3647 (overlay-put ov 'face 'secondary-selection)
3648 (push ov org-occur-highlights)))
3649
3650 (defun org-remove-occur-highlights (&optional beg end noremove)
3651 "Remove the occur highlights from the buffer.
3652 BEG and END are ignored. If NOREMOVE is nil, remove this function
3653 from the before-change-functions in the current buffer."
3654 (interactive)
3655 (mapc 'delete-overlay org-occur-highlights)
3656 (setq org-occur-highlights nil)
3657 (unless noremove
3658 (remove-hook 'before-change-functions
3659 'org-remove-occur-highlights 'local)))
3660
3661 ;;; Priorities
3662
3663 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3664 "Regular expression matching the priority indicator.")
3665
3666 (defvar org-remove-priority-next-time nil)
3667
3668 (defun org-priority-up ()
3669 "Increase the priority of the current item."
3670 (interactive)
3671 (org-priority 'up))
3672
3673 (defun org-priority-down ()
3674 "Decrease the priority of the current item."
3675 (interactive)
3676 (org-priority 'down))
3677
3678 (defun org-priority (&optional action)
3679 "Change the priority of an item by ARG.
3680 ACTION can be set, up, or down."
3681 (interactive)
3682 (setq action (or action 'set))
3683 (let (current new news have remove)
3684 (save-excursion
3685 (org-back-to-heading)
3686 (if (looking-at org-priority-regexp)
3687 (setq current (string-to-char (match-string 2))
3688 have t)
3689 (setq current org-default-priority))
3690 (cond
3691 ((eq action 'set)
3692 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3693 (setq new (read-char-exclusive))
3694 (cond ((equal new ?\ ) (setq remove t))
3695 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3696 (error "Priority must be between `%c' and `%c'"
3697 ?A org-lowest-priority))))
3698 ((eq action 'up)
3699 (setq new (1- current)))
3700 ((eq action 'down)
3701 (setq new (1+ current)))
3702 (t (error "Invalid action")))
3703 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3704 (setq news (format "%c" new))
3705 (if have
3706 (if remove
3707 (replace-match "" t t nil 1)
3708 (replace-match news t t nil 2))
3709 (if remove
3710 (error "No priority cookie found in line")
3711 (looking-at org-todo-line-regexp)
3712 (if (match-end 2)
3713 (progn
3714 (goto-char (match-end 2))
3715 (insert " [#" news "]"))
3716 (goto-char (match-beginning 3))
3717 (insert "[#" news "] ")))))
3718 (if remove
3719 (message "Priority removed")
3720 (message "Priority of current item set to %s" news))))
3721
3722
3723 (defun org-get-priority (s)
3724 "Find priority cookie and return priority."
3725 (save-match-data
3726 (if (not (string-match org-priority-regexp s))
3727 (* 1000 (- org-lowest-priority org-default-priority))
3728 (* 1000 (- org-lowest-priority
3729 (string-to-char (match-string 2 s)))))))
3730
3731 ;;; Timestamps
3732
3733 (defvar org-last-changed-timestamp nil)
3734
3735 (defun org-time-stamp (arg)
3736 "Prompt for a date/time and insert a time stamp.
3737 If the user specifies a time like HH:MM, or if this command is called
3738 with a prefix argument, the time stamp will contain date and time.
3739 Otherwise, only the date will be included. All parts of a date not
3740 specified by the user will be filled in from the current date/time.
3741 So if you press just return without typing anything, the time stamp
3742 will represent the current date/time. If there is already a timestamp
3743 at the cursor, it will be modified."
3744 (interactive "P")
3745 (let ((fmt (if arg (cdr org-time-stamp-formats)
3746 (car org-time-stamp-formats)))
3747 (org-time-was-given nil)
3748 time)
3749 (cond
3750 ((and (org-at-timestamp-p)
3751 (eq last-command 'org-time-stamp)
3752 (eq this-command 'org-time-stamp))
3753 (insert "--")
3754 (setq time (let ((this-command this-command))
3755 (org-read-date arg 'totime)))
3756 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3757 (insert (format-time-string fmt time)))
3758 ((org-at-timestamp-p)
3759 (setq time (let ((this-command this-command))
3760 (org-read-date arg 'totime)))
3761 (and (org-at-timestamp-p) (replace-match
3762 (setq org-last-changed-timestamp
3763 (format-time-string fmt time))
3764 t t))
3765 (message "Timestamp updated"))
3766 (t
3767 (setq time (let ((this-command this-command))
3768 (org-read-date arg 'totime)))
3769 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3770 (insert (format-time-string fmt time))))))
3771
3772 (defun org-time-stamp-inactive (&optional arg)
3773 "Insert an inactive time stamp.
3774 An inactive time stamp is enclosed in square brackets instead of angle
3775 brackets. It is inactive in the sense that it does not trigger agenda entries,
3776 does not link to the calendar and cannot be changed with the S-cursor keys.
3777 So these are more for recording a certain time/date."
3778 ;; FIXME: Would it be better not to ask for a date/time here?
3779 (interactive "P")
3780 (let ((fmt (if arg (cdr org-time-stamp-formats)
3781 (car org-time-stamp-formats)))
3782 (org-time-was-given nil)
3783 time)
3784 (setq time (org-read-date arg 'totime))
3785 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3786 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3787 (insert (format-time-string fmt time))))
3788
3789 ;;; FIXME: Make the function take "Fri" as "next friday"
3790 ;;; because these are mostly being used to record the current time.
3791 (defun org-read-date (&optional with-time to-time)
3792 "Read a date and make things smooth for the user.
3793 The prompt will suggest to enter an ISO date, but you can also enter anything
3794 which will at least partially be understood by `parse-time-string'.
3795 Unrecognized parts of the date will default to the current day, month ,year,
3796 hour and minute. For example,
3797 3-2-5 --> 2003-02-05
3798 feb 15 --> currentyear-02-15
3799 sep 12 9 --> 2009-09-12
3800 12:45 --> today 12:45
3801 22 sept 0:34 --> currentyear-09-22 0:34
3802 12 --> currentyear-currentmonth-12
3803 etc.
3804 The function understands only English month and weekday abbreviations,
3805 but this can be configured with the variables `parse-time-months' and
3806 `parse-time-weekdays'.
3807
3808 While prompting, a calendar is popped up - you can also select the
3809 date with the mouse (button 1). The calendar shows a period of three
3810 month. To scroll it to other months, use the keys `>' and `<'.
3811 If you don't like the calendar, turn it off with
3812 \(setq org-popup-calendar-for-date-prompt nil).
3813
3814 With optional argument TO-TIME, the date will immediately be converted
3815 to an internal time.
3816 With an optional argument WITH-TIME, the prompt will suggest to also
3817 insert a time. Note that when WITH-TIME is not set, you can still
3818 enter a time, and this function will inform the calling routine about
3819 this change. The calling routine may then choose to change the format
3820 used to insert the time stamp into the buffer to include the time."
3821 (let* ((default-time
3822 ;; Default time is either today, or, when entering a range,
3823 ;; the range start.
3824 (if (save-excursion
3825 (re-search-backward
3826 (concat org-ts-regexp "--\\=")
3827 (- (point) 20) t))
3828 (apply
3829 'encode-time
3830 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3831 (parse-time-string (match-string 1))))
3832 (current-time)))
3833 (calendar-move-hook nil)
3834 (view-diary-entries-initially nil)
3835 (timestr (format-time-string
3836 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3837 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3838 ans ans1 ans2
3839 second minute hour day month year tl)
3840
3841 (if org-popup-calendar-for-date-prompt
3842 ;; Also show a calendar for date selection
3843 ;; Copied (with modifications) from planner.el by John Wiegley
3844 (save-excursion
3845 (save-window-excursion
3846 (calendar)
3847 (calendar-forward-day (- (time-to-days default-time)
3848 (calendar-absolute-from-gregorian
3849 (calendar-current-date))))
3850 (let* ((old-map (current-local-map))
3851 (map (copy-keymap calendar-mode-map))
3852 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3853 (define-key map (kbd "RET") 'org-calendar-select)
3854 (define-key map (if org-xemacs-p [button1] [mouse-1])
3855 'org-calendar-select)
3856 (define-key minibuffer-local-map [(meta shift left)]
3857 (lambda () (interactive)
3858 (org-eval-in-calendar '(calendar-backward-month 1))))
3859 (define-key minibuffer-local-map [(meta shift right)]
3860 (lambda () (interactive)
3861 (org-eval-in-calendar '(calendar-forward-month 1))))
3862 (define-key minibuffer-local-map [(shift up)]
3863 (lambda () (interactive)
3864 (org-eval-in-calendar '(calendar-backward-week 1))))
3865 (define-key minibuffer-local-map [(shift down)]
3866 (lambda () (interactive)
3867 (org-eval-in-calendar '(calendar-forward-week 1))))
3868 (define-key minibuffer-local-map [(shift left)]
3869 (lambda () (interactive)
3870 (org-eval-in-calendar '(calendar-backward-day 1))))
3871 (define-key minibuffer-local-map [(shift right)]
3872 (lambda () (interactive)
3873 (org-eval-in-calendar '(calendar-forward-day 1))))
3874 (define-key minibuffer-local-map ">"
3875 (lambda () (interactive)
3876 (org-eval-in-calendar '(scroll-calendar-left 1))))
3877 (define-key minibuffer-local-map "<"
3878 (lambda () (interactive)
3879 (org-eval-in-calendar '(scroll-calendar-right 1))))
3880 (unwind-protect
3881 (progn
3882 (use-local-map map)
3883 (setq ans (read-string prompt "" nil nil))
3884 (setq ans (or ans1 ans2 ans)))
3885 (use-local-map old-map)))))
3886 ;; Naked prompt only
3887 (setq ans (read-string prompt "" nil timestr)))
3888
3889 (if (string-match
3890 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3891 (progn
3892 (setq year (if (match-end 2)
3893 (string-to-number (match-string 2 ans))
3894 (string-to-number (format-time-string "%Y")))
3895 month (string-to-number (match-string 3 ans))
3896 day (string-to-number (match-string 4 ans)))
3897 (if (< year 100) (setq year (+ 2000 year)))
3898 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3899 t t ans))))
3900 (setq tl (parse-time-string ans)
3901 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3902 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3903 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3904 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3905 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3906 second (or (nth 0 tl) 0))
3907 (if (and (boundp 'org-time-was-given)
3908 (nth 2 tl))
3909 (setq org-time-was-given t))
3910 (if (< year 100) (setq year (+ 2000 year)))
3911 (if to-time
3912 (encode-time second minute hour day month year)
3913 (if (or (nth 1 tl) (nth 2 tl))
3914 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3915 (format "%04d-%02d-%02d" year month day)))))
3916
3917 (defun org-eval-in-calendar (form)
3918 "Eval FORM in the calendar window and return to current window.
3919 Also, store the cursor date in variable ans2."
3920 (let ((sw (selected-window)))
3921 (select-window (get-buffer-window "*Calendar*"))
3922 (eval form)
3923 (when (calendar-cursor-to-date)
3924 (let* ((date (calendar-cursor-to-date))
3925 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3926 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3927 (and org-xemacs-p (sit-for .2))
3928 (select-window sw)))
3929
3930 (defun org-calendar-select ()
3931 "Return to `org-read-date' with the date currently selected.
3932 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3933 (interactive)
3934 (when (calendar-cursor-to-date)
3935 (let* ((date (calendar-cursor-to-date))
3936 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3937 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3938 (if (active-minibuffer-window) (exit-minibuffer))))
3939
3940 (defun org-check-deadlines (ndays)
3941 "Check if there are any deadlines due or past due.
3942 A deadline is considered due if it happens within `org-deadline-warning-days'
3943 days from today's date. If the deadline appears in an entry marked DONE,
3944 it is not shown. The prefix arg NDAYS can be used to test that many
3945 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3946 (interactive "P")
3947 (let* ((org-warn-days
3948 (cond
3949 ((equal ndays '(4)) 100000)
3950 (ndays (prefix-numeric-value ndays))
3951 (t org-deadline-warning-days)))
3952 (case-fold-search nil)
3953 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3954 (callback
3955 (lambda ()
3956 (and (let ((d1 (time-to-days (current-time)))
3957 (d2 (time-to-days
3958 (org-time-string-to-time (match-string 1)))))
3959 (< (- d2 d1) org-warn-days))
3960 (not (org-entry-is-done-p))))))
3961 (message "%d deadlines past-due or due within %d days"
3962 (org-occur regexp callback)
3963 org-warn-days)))
3964
3965 (defun org-evaluate-time-range (&optional to-buffer)
3966 "Evaluate a time range by computing the difference between start and end.
3967 Normally the result is just printed in the echo area, but with prefix arg
3968 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3969 If the time range is actually in a table, the result is inserted into the
3970 next column.
3971 For time difference computation, a year is assumed to be exactly 365
3972 days in order to avoid rounding problems."
3973 (interactive "P")
3974 (save-excursion
3975 (unless (org-at-date-range-p)
3976 (goto-char (point-at-bol))
3977 (re-search-forward org-tr-regexp (point-at-eol) t))
3978 (if (not (org-at-date-range-p))
3979 (error "Not at a time-stamp range, and none found in current line")))
3980 (let* ((ts1 (match-string 1))
3981 (ts2 (match-string 2))
3982 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3983 (match-end (match-end 0))
3984 (time1 (org-time-string-to-time ts1))
3985 (time2 (org-time-string-to-time ts2))
3986 (t1 (time-to-seconds time1))
3987 (t2 (time-to-seconds time2))
3988 (diff (abs (- t2 t1)))
3989 (negative (< (- t2 t1) 0))
3990 ;; (ys (floor (* 365 24 60 60)))
3991 (ds (* 24 60 60))
3992 (hs (* 60 60))
3993 (fy "%dy %dd %02d:%02d")
3994 (fy1 "%dy %dd")
3995 (fd "%dd %02d:%02d")
3996 (fd1 "%dd")
3997 (fh "%02d:%02d")
3998 y d h m align)
3999 ;; FIXME: Should I re-introduce years, make year refer to same date?
4000 ;; This would be the only useful way to have years, actually.
4001 (if havetime
4002 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4003 y 0
4004 d (floor (/ diff ds)) diff (mod diff ds)
4005 h (floor (/ diff hs)) diff (mod diff hs)
4006 m (floor (/ diff 60)))
4007 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4008 y 0
4009 d (floor (+ (/ diff ds) 0.5))
4010 h 0 m 0))
4011 (if (not to-buffer)
4012 (message (org-make-tdiff-string y d h m))
4013 (when (org-at-table-p)
4014 (goto-char match-end)
4015 (setq align t)
4016 (and (looking-at " *|") (goto-char (match-end 0))))
4017 (if (looking-at
4018 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4019 (replace-match ""))
4020 (if negative (insert " -"))
4021 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4022 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4023 (insert " " (format fh h m))))
4024 (if align (org-table-align))
4025 (message "Time difference inserted"))))
4026
4027 (defun org-make-tdiff-string (y d h m)
4028 (let ((fmt "")
4029 (l nil))
4030 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4031 l (push y l)))
4032 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4033 l (push d l)))
4034 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4035 l (push h l)))
4036 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4037 l (push m l)))
4038 (apply 'format fmt (nreverse l))))
4039
4040 (defun org-time-string-to-time (s)
4041 (apply 'encode-time (org-parse-time-string s)))
4042
4043 (defun org-parse-time-string (s &optional nodefault)
4044 "Parse the standard Org-mode time string.
4045 This should be a lot faster than the normal `parse-time-string'.
4046 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4047 hour and minute fields will be nil if not given."
4048 (if (string-match org-ts-regexp1 s)
4049 (list 0
4050 (if (or (match-beginning 8) (not nodefault))
4051 (string-to-number (or (match-string 8 s) "0")))
4052 (if (or (match-beginning 7) (not nodefault))
4053 (string-to-number (or (match-string 7 s) "0")))
4054 (string-to-number (match-string 4 s))
4055 (string-to-number (match-string 3 s))
4056 (string-to-number (match-string 2 s))
4057 nil nil nil)
4058 (make-list 9 0)))
4059
4060 (defun org-timestamp-up (&optional arg)
4061 "Increase the date item at the cursor by one.
4062 If the cursor is on the year, change the year. If it is on the month or
4063 the day, change that.
4064 With prefix ARG, change by that many units."
4065 (interactive "p")
4066 (org-timestamp-change (prefix-numeric-value arg)))
4067
4068 (defun org-timestamp-down (&optional arg)
4069 "Decrease the date item at the cursor by one.
4070 If the cursor is on the year, change the year. If it is on the month or
4071 the day, change that.
4072 With prefix ARG, change by that many units."
4073 (interactive "p")
4074 (org-timestamp-change (- (prefix-numeric-value arg))))
4075
4076 (defun org-timestamp-up-day (&optional arg)
4077 "Increase the date in the time stamp by one day.
4078 With prefix ARG, change that many days."
4079 (interactive "p")
4080 (if (and (not (org-at-timestamp-p))
4081 (org-on-heading-p))
4082 (org-todo 'up)
4083 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4084
4085 (defun org-timestamp-down-day (&optional arg)
4086 "Decrease the date in the time stamp by one day.
4087 With prefix ARG, change that many days."
4088 (interactive "p")
4089 (if (and (not (org-at-timestamp-p))
4090 (org-on-heading-p))
4091 (org-todo 'down)
4092 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4093
4094 (defsubst org-pos-in-match-range (pos n)
4095 (and (match-beginning n)
4096 (<= (match-beginning n) pos)
4097 (>= (match-end n) pos)))
4098
4099 (defun org-at-timestamp-p ()
4100 "Determine if the cursor is in or at a timestamp."
4101 (interactive)
4102 (let* ((tsr org-ts-regexp2)
4103 (pos (point))
4104 (ans (or (looking-at tsr)
4105 (save-excursion
4106 (skip-chars-backward "^<\n\r\t")
4107 (if (> (point) 1) (backward-char 1))
4108 (and (looking-at tsr)
4109 (> (- (match-end 0) pos) -1))))))
4110 (and (boundp 'org-ts-what)
4111 (setq org-ts-what
4112 (cond
4113 ((org-pos-in-match-range pos 2) 'year)
4114 ((org-pos-in-match-range pos 3) 'month)
4115 ((org-pos-in-match-range pos 7) 'hour)
4116 ((org-pos-in-match-range pos 8) 'minute)
4117 ((or (org-pos-in-match-range pos 4)
4118 (org-pos-in-match-range pos 5)) 'day)
4119 (t 'day))))
4120 ans))
4121
4122 (defun org-timestamp-change (n &optional what)
4123 "Change the date in the time stamp at point.
4124 The date will be changed by N times WHAT. WHAT can be `day', `month',
4125 `year', `minute', `second'. If WHAT is not given, the cursor position
4126 in the timestamp determines what will be changed."
4127 (let ((fmt (car org-time-stamp-formats))
4128 org-ts-what
4129 (pos (point))
4130 ts time time0)
4131 (if (not (org-at-timestamp-p))
4132 (error "Not at a timestamp"))
4133 (setq org-ts-what (or what org-ts-what))
4134 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4135 (- (match-end 0) (match-beginning 0))))
4136 1)
4137 (cdr org-time-stamp-formats)
4138 (car org-time-stamp-formats)))
4139 (setq ts (match-string 0))
4140 (replace-match "")
4141 (setq time0 (org-parse-time-string ts))
4142 (setq time
4143 (apply 'encode-time
4144 (append
4145 (list (or (car time0) 0))
4146 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4147 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4148 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4149 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4150 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4151 (nthcdr 6 time0))))
4152 (if (eq what 'calendar)
4153 (let ((cal-date
4154 (save-excursion
4155 (save-match-data
4156 (set-buffer "*Calendar*")
4157 (calendar-cursor-to-date)))))
4158 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4159 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4160 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4161 (setcar time0 (or (car time0) 0))
4162 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4163 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4164 (setq time (apply 'encode-time time0))))
4165 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4166 (goto-char pos)
4167 ;; Try to recenter the calendar window, if any
4168 (if (and org-calendar-follow-timestamp-change
4169 (get-buffer-window "*Calendar*" t)
4170 (memq org-ts-what '(day month year)))
4171 (org-recenter-calendar (time-to-days time)))))
4172
4173 (defun org-recenter-calendar (date)
4174 "If the calendar is visible, recenter it to DATE."
4175 (let* ((win (selected-window))
4176 (cwin (get-buffer-window "*Calendar*" t))
4177 (calendar-move-hook nil))
4178 (when cwin
4179 (select-window cwin)
4180 (calendar-goto-date (if (listp date) date
4181 (calendar-gregorian-from-absolute date)))
4182 (select-window win))))
4183
4184 (defun org-goto-calendar (&optional arg)
4185 "Go to the Emacs calendar at the current date.
4186 If there is a time stamp in the current line, go to that date.
4187 A prefix ARG can be used force the current date."
4188 (interactive "P")
4189 (let ((tsr org-ts-regexp) diff
4190 (calendar-move-hook nil)
4191 (view-diary-entries-initially nil))
4192 (if (or (org-at-timestamp-p)
4193 (save-excursion
4194 (beginning-of-line 1)
4195 (looking-at (concat ".*" tsr))))
4196 (let ((d1 (time-to-days (current-time)))
4197 (d2 (time-to-days
4198 (org-time-string-to-time (match-string 1)))))
4199 (setq diff (- d2 d1))))
4200 (calendar)
4201 (calendar-goto-today)
4202 (if (and diff (not arg)) (calendar-forward-day diff))))
4203
4204 (defun org-date-from-calendar ()
4205 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4206 If there is already a time stamp at the cursor position, update it."
4207 (interactive)
4208 (org-timestamp-change 0 'calendar))
4209
4210 ;;; Agenda, and Diary Integration
4211
4212 ;;; Define the mode
4213
4214 (defvar org-agenda-mode-map (make-sparse-keymap)
4215 "Keymap for `org-agenda-mode'.")
4216
4217 (defvar org-agenda-menu)
4218 (defvar org-agenda-follow-mode nil)
4219 (defvar org-agenda-show-log nil)
4220 (defvar org-agenda-buffer-name "*Org Agenda*")
4221 (defvar org-agenda-redo-command nil)
4222 (defvar org-agenda-mode-hook nil)
4223
4224 (defvar org-agenda-force-single-file nil)
4225
4226 ;;;###autoload
4227 (defun org-agenda-mode ()
4228 "Mode for time-sorted view on action items in Org-mode files.
4229
4230 The following commands are available:
4231
4232 \\{org-agenda-mode-map}"
4233 (interactive)
4234 (kill-all-local-variables)
4235 (setq major-mode 'org-agenda-mode)
4236 (setq mode-name "Org-Agenda")
4237 (use-local-map org-agenda-mode-map)
4238 (easy-menu-add org-agenda-menu)
4239 (if org-startup-truncated (setq truncate-lines t))
4240 (make-local-hook 'post-command-hook) ; Needed for XEmacs
4241 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4242 (make-local-hook 'pre-command-hook) ; Needed for XEmacs
4243 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4244 (unless org-agenda-keep-modes
4245 (setq org-agenda-follow-mode nil
4246 org-agenda-show-log nil))
4247 (easy-menu-change
4248 '("Agenda") "Agenda Files"
4249 (append
4250 (list
4251 (vector
4252 (if (get 'org-agenda-files 'org-restrict)
4253 "Restricted to single file"
4254 "Edit File List")
4255 '(customize-variable 'org-agenda-files)
4256 (not (get 'org-agenda-files 'org-restrict)))
4257 "--")
4258 (mapcar 'org-file-menu-entry (org-agenda-files))))
4259 (org-agenda-set-mode-name)
4260 (apply
4261 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4262 (list 'org-agenda-mode-hook)))
4263
4264 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4265 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4266 (define-key org-agenda-mode-map " " 'org-agenda-show)
4267 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4268 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4269 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4270 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4271 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4272 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4273 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4274 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4275 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4276 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4277 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4278 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4279
4280 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4281 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4282 (while l (define-key org-agenda-mode-map
4283 (int-to-string (pop l)) 'digit-argument)))
4284
4285 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4286 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4287 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4288 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4289 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4290 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4291 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4292 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4293 (define-key org-agenda-mode-map "n" 'next-line)
4294 (define-key org-agenda-mode-map "p" 'previous-line)
4295 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4296 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4297 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4298 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4299 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4300 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4301 (eval-after-load "calendar"
4302 '(define-key calendar-mode-map org-calendar-to-agenda-key
4303 'org-calendar-goto-agenda))
4304 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4305 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4306 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4307 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4308 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4309 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4310 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4311 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4312 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4313 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4314 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4315 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4316 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4317 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4318 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4319 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4320 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4321 "Local keymap for agenda entries from Org-mode.")
4322
4323 (define-key org-agenda-keymap
4324 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4325 (define-key org-agenda-keymap
4326 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4327
4328 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4329 '("Agenda"
4330 ("Agenda Files")
4331 "--"
4332 ["Show" org-agenda-show t]
4333 ["Go To (other window)" org-agenda-goto t]
4334 ["Go To (one window)" org-agenda-switch-to t]
4335 ["Follow Mode" org-agenda-follow-mode
4336 :style toggle :selected org-agenda-follow-mode :active t]
4337 "--"
4338 ["Cycle TODO" org-agenda-todo t]
4339 ["Set Tags" org-agenda-set-tags t]
4340 ("Reschedule"
4341 ["Reschedule +1 day" org-agenda-date-later t]
4342 ["Reschedule -1 day" org-agenda-date-earlier t]
4343 "--"
4344 ["Reschedule to ..." org-agenda-date-prompt t])
4345 ("Priority"
4346 ["Set Priority" org-agenda-priority t]
4347 ["Increase Priority" org-agenda-priority-up t]
4348 ["Decrease Priority" org-agenda-priority-down t]
4349 ["Show Priority" org-agenda-show-priority t])
4350 "--"
4351 ["Rebuild buffer" org-agenda-redo t]
4352 ["Goto Today" org-agenda-goto-today t]
4353 ["Next Dates" org-agenda-later (local-variable-p 'starting-day (current-buffer))]
4354 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day (current-buffer))]
4355 "--"
4356 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day (current-buffer))
4357 :style radio :selected (equal org-agenda-ndays 1)]
4358 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day (current-buffer))
4359 :style radio :selected (equal org-agenda-ndays 7)]
4360 "--"
4361 ["Show Logbook entries" org-agenda-log-mode
4362 :style toggle :selected org-agenda-show-log :active t]
4363 ["Include Diary" org-agenda-toggle-diary
4364 :style toggle :selected org-agenda-include-diary :active t]
4365 ["Use Time Grid" org-agenda-toggle-time-grid
4366 :style toggle :selected org-agenda-use-time-grid :active t]
4367 "--"
4368 ["New Diary Entry" org-agenda-diary-entry t]
4369 ("Calendar Commands"
4370 ["Goto Calendar" org-agenda-goto-calendar t]
4371 ["Phases of the Moon" org-agenda-phases-of-moon t]
4372 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
4373 ["Holidays" org-agenda-holidays t]
4374 ["Convert" org-agenda-convert-date t])
4375 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4376 "--"
4377 ["Quit" org-agenda-quit t]
4378 ["Exit and Release Buffers" org-agenda-exit t]
4379 ))
4380
4381 ;;;###autoload
4382 (defun org-agenda (arg)
4383 "Dispatch agenda commands to collect entries to the agenda buffer.
4384 Prompts for a character to select a command. Any prefix arg will be passed
4385 on to the selected command. The default selections are:
4386
4387 a Call `org-agenda' to display the agenda for the current day or week.
4388 t Call `org-todo-list' to display the global todo list.
4389 T Call `org-todo-list' to display the global todo list, put
4390 select only entries with a specific TODO keyword.
4391 m Call `org-tags-view' to display headlines with tags matching
4392 a condition. The tags condition is a list of positive and negative
4393 selections, like `+WORK+URGENT-WITHBOSS'.
4394 M like `m', but select only TODO entries, no ordinary headlines.
4395
4396 More commands can be added by configuring the variable
4397 `org-agenda-custom-commands'.
4398
4399 If the current buffer is in Org-mode and visiting a file, you can also
4400 first press `1' to indicate that the agenda should be temporarily
4401 restricted to the current file."
4402 (interactive "P")
4403 (catch 'exit
4404 (let ((restrict-ok (and (buffer-file-name) (eq major-mode 'org-mode)))
4405 (custom org-agenda-custom-commands)
4406 c entry key type string)
4407 (put 'org-agenda-files 'org-restrict nil)
4408 (save-window-excursion
4409 (delete-other-windows)
4410 (switch-to-buffer-other-window " *Agenda Commands*")
4411 (erase-buffer)
4412 (insert
4413 "Press key for an agenda command:
4414 --------------------------------
4415 a Agenda for current week or day
4416 t List of all TODO entries T Entries with special TODO kwd
4417 m Match a TAGS query M Like m, but only TODO entries.
4418 C Configure your own agenda commands")
4419 (while (setq entry (pop custom))
4420 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4421 (insert (format "\n%-4s%-12s: %s"
4422 key
4423 (if (eq type 'tags) "Tags query" "TODO keyword")
4424 string)))
4425 (goto-char (point-min))
4426 (fit-window-to-buffer)
4427 (message "Press key for agenda command%s"
4428 (if restrict-ok ", or [1] to restrict to current file" ""))
4429 (setq c (read-char-exclusive))
4430 (message "")
4431 (when (equal c ?1)
4432 (if restrict-ok
4433 (put 'org-agenda-files 'org-restrict (list (buffer-file-name)))
4434 (error "Cannot restrict agenda to current buffer"))
4435 (message "Press key for agenda command%s"
4436 (if restrict-ok " (restricted to current file)" ""))
4437 (setq c (read-char-exclusive))
4438 (message "")))
4439 (require 'calendar) ; FIXME: can we avoid this for some commands?
4440 (cond
4441 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4442 ((equal c ?a) (call-interactively 'org-agenda-list))
4443 ((equal c ?t) (call-interactively 'org-todo-list))
4444 ((equal c ?T)
4445 (setq current-prefix-arg (or arg '(4)))
4446 (call-interactively 'org-todo-list))
4447 ((equal c ?m) (call-interactively 'org-tags-view))
4448 ((equal c ?M)
4449 (setq current-prefix-arg (or arg '(4)))
4450 (call-interactively 'org-tags-view))
4451 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4452 (setq type (nth 1 entry) string (nth 2 entry))
4453 (cond
4454 ((eq type 'tags)
4455 (org-tags-view current-prefix-arg string))
4456 ((eq type 'todo)
4457 (org-todo-list string))
4458 (t (error "Invalid custom agenda command type %s" type))))
4459 (t (error "Invalid key"))))))
4460
4461 (defun org-fit-agenda-window ()
4462 "Fit the window to the buffer size."
4463 (and org-fit-agenda-window
4464 (fboundp 'fit-window-to-buffer)
4465 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4466 (/ (frame-height) 2))))
4467
4468 (defun org-agenda-files ()
4469 "Get the list of agenda files."
4470 (or (get 'org-agenda-files 'org-restrict)
4471 org-agenda-files))
4472
4473 (defvar org-agenda-markers nil
4474 "List of all currently active markers created by `org-agenda'.")
4475 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4476 "Creation time of the last agenda marker.")
4477
4478 (defun org-agenda-new-marker (&optional pos)
4479 "Return a new agenda marker.
4480 Org-mode keeps a list of these markers and resets them when they are
4481 no longer in use."
4482 (let ((m (copy-marker (or pos (point)))))
4483 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4484 (push m org-agenda-markers)
4485 m))
4486
4487 (defun org-agenda-maybe-reset-markers (&optional force)
4488 "Reset markers created by `org-agenda'. But only if they are old enough."
4489 (if (or force
4490 (> (- (time-to-seconds (current-time))
4491 org-agenda-last-marker-time)
4492 5))
4493 (while org-agenda-markers
4494 (move-marker (pop org-agenda-markers) nil))))
4495
4496 (defvar org-agenda-new-buffers nil
4497 "Buffers created to visit agenda files.")
4498
4499 (defun org-get-agenda-file-buffer (file)
4500 "Get a buffer visiting FILE. If the buffer needs to be created, add
4501 it to the list of buffers which might be released later."
4502 (let ((buf (find-buffer-visiting file)))
4503 (if buf
4504 buf ; just return it
4505 ;; Make a new buffer and remember it
4506 (setq buf (find-file-noselect file))
4507 (if buf (push buf org-agenda-new-buffers))
4508 buf)))
4509
4510 (defun org-release-buffers (blist)
4511 "Release all buffers in list, asking the user for confirmation when needed.
4512 When a buffer is unmodified, it is just killed. When modified, it is saved
4513 \(if the user agrees) and then killed."
4514 (let (buf file)
4515 (while (setq buf (pop blist))
4516 (setq file (buffer-file-name buf))
4517 (when (and (buffer-modified-p buf)
4518 file
4519 (y-or-n-p (format "Save file %s? " file)))
4520 (with-current-buffer buf (save-buffer)))
4521 (kill-buffer buf))))
4522
4523 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4524
4525 (defun org-timeline (&optional include-all keep-modes)
4526 "Show a time-sorted view of the entries in the current org file.
4527 Only entries with a time stamp of today or later will be listed. With
4528 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4529 under the current date.
4530 If the buffer contains an active region, only check the region for
4531 dates."
4532 (interactive "P")
4533 (require 'calendar)
4534 (org-agenda-maybe-reset-markers 'force)
4535 (org-compile-prefix-format org-timeline-prefix-format)
4536 (let* ((dopast t)
4537 (dotodo include-all)
4538 (doclosed org-agenda-show-log)
4539 (org-agenda-keep-modes keep-modes)
4540 (entry (buffer-file-name))
4541 (org-agenda-files (list (buffer-file-name)))
4542 (date (calendar-current-date))
4543 (win (selected-window))
4544 (pos1 (point))
4545 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4546 (end (if (org-region-active-p) (region-end) (point-max)))
4547 (day-numbers (org-get-all-dates beg end 'no-ranges
4548 t doclosed)) ; always include today
4549 (today (time-to-days (current-time)))
4550 (org-respect-restriction t)
4551 (past t)
4552 args
4553 s e rtn d)
4554 (setq org-agenda-redo-command
4555 (list 'progn
4556 (list 'switch-to-buffer-other-window (current-buffer))
4557 (list 'org-timeline (list 'quote include-all) t)))
4558 (if (not dopast)
4559 ;; Remove past dates from the list of dates.
4560 (setq day-numbers (delq nil (mapcar (lambda(x)
4561 (if (>= x today) x nil))
4562 day-numbers))))
4563 (switch-to-buffer-other-window
4564 (get-buffer-create org-agenda-buffer-name))
4565 (setq buffer-read-only nil)
4566 (erase-buffer)
4567 (org-agenda-mode) (setq buffer-read-only nil)
4568 (if doclosed (push :closed args))
4569 (push :timestamp args)
4570 (if dotodo (push :todo args))
4571 (while (setq d (pop day-numbers))
4572 (if (and (>= d today)
4573 dopast
4574 past)
4575 (progn
4576 (setq past nil)
4577 (insert (make-string 79 ?-) "\n")))
4578 (setq date (calendar-gregorian-from-absolute d))
4579 (setq s (point))
4580 (setq rtn (apply 'org-agenda-get-day-entries
4581 entry date args))
4582 (if (or rtn (equal d today))
4583 (progn
4584 (insert (calendar-day-name date) " "
4585 (number-to-string (extract-calendar-day date)) " "
4586 (calendar-month-name (extract-calendar-month date)) " "
4587 (number-to-string (extract-calendar-year date)) "\n")
4588 (put-text-property s (1- (point)) 'face
4589 'org-link)
4590 (if (equal d today)
4591 (put-text-property s (1- (point)) 'org-today t))
4592 (insert (org-finalize-agenda-entries rtn) "\n")
4593 (put-text-property s (1- (point)) 'day d))))
4594 (goto-char (point-min))
4595 (setq buffer-read-only t)
4596 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4597 (point-min)))
4598 (when (not org-select-timeline-window)
4599 (select-window win)
4600 (goto-char pos1))))
4601
4602 ;;;###autoload
4603 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4604 "Produce a weekly view from all files in variable `org-agenda-files'.
4605 The view will be for the current week, but from the overview buffer you
4606 will be able to go to other weeks.
4607 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4608 also be shown, under the current date.
4609 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4610 on the days are also shown. See the variable `org-log-done' for how
4611 to turn on logging.
4612 START-DAY defaults to TODAY, or to the most recent match for the weekday
4613 given in `org-agenda-start-on-weekday'.
4614 NDAYS defaults to `org-agenda-ndays'."
4615 (interactive "P")
4616 (org-agenda-maybe-reset-markers 'force)
4617 (org-compile-prefix-format org-agenda-prefix-format)
4618 (require 'calendar)
4619 (let* ((org-agenda-start-on-weekday
4620 (if (or (equal ndays 1)
4621 (and (null ndays) (equal 1 org-agenda-ndays)))
4622 nil org-agenda-start-on-weekday))
4623 (org-agenda-keep-modes keep-modes)
4624 (files (copy-sequence (org-agenda-files)))
4625 (win (selected-window))
4626 (today (time-to-days (current-time)))
4627 (sd (or start-day today))
4628 (start (if (or (null org-agenda-start-on-weekday)
4629 (< org-agenda-ndays 7))
4630 sd
4631 (let* ((nt (calendar-day-of-week
4632 (calendar-gregorian-from-absolute sd)))
4633 (n1 org-agenda-start-on-weekday)
4634 (d (- nt n1)))
4635 (- sd (+ (if (< d 0) 7 0) d)))))
4636 (day-numbers (list start))
4637 (inhibit-redisplay t)
4638 s e rtn rtnall file date d start-pos end-pos todayp nd)
4639 (setq org-agenda-redo-command
4640 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4641 ;; Make the list of days
4642 (setq ndays (or ndays org-agenda-ndays)
4643 nd ndays)
4644 (while (> ndays 1)
4645 (push (1+ (car day-numbers)) day-numbers)
4646 (setq ndays (1- ndays)))
4647 (setq day-numbers (nreverse day-numbers))
4648 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4649 (progn
4650 (delete-other-windows)
4651 (switch-to-buffer-other-window
4652 (get-buffer-create org-agenda-buffer-name))))
4653 (setq buffer-read-only nil)
4654 (erase-buffer)
4655 (org-agenda-mode) (setq buffer-read-only nil)
4656 (set (make-local-variable 'starting-day) (car day-numbers))
4657 (set (make-local-variable 'include-all-loc) include-all)
4658 (when (and (or include-all org-agenda-include-all-todo)
4659 (member today day-numbers))
4660 (setq files (org-agenda-files)
4661 rtnall nil)
4662 (while (setq file (pop files))
4663 (catch 'nextfile
4664 (org-check-agenda-file file)
4665 (setq date (calendar-gregorian-from-absolute today)
4666 rtn (org-agenda-get-day-entries
4667 file date :todo))
4668 (setq rtnall (append rtnall rtn))))
4669 (when rtnall
4670 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4671 (add-text-properties (point-min) (1- (point))
4672 (list 'face 'org-link))
4673 (insert (org-finalize-agenda-entries rtnall) "\n")))
4674 (while (setq d (pop day-numbers))
4675 (setq date (calendar-gregorian-from-absolute d)
4676 s (point))
4677 (if (or (setq todayp (= d today))
4678 (and (not start-pos) (= d sd)))
4679 (setq start-pos (point))
4680 (if (and start-pos (not end-pos))
4681 (setq end-pos (point))))
4682 (setq files (org-agenda-files)
4683 rtnall nil)
4684 (while (setq file (pop files))
4685 (catch 'nextfile
4686 (org-check-agenda-file file)
4687 (if org-agenda-show-log
4688 (setq rtn (org-agenda-get-day-entries
4689 file date
4690 :deadline :scheduled :timestamp :closed))
4691 (setq rtn (org-agenda-get-day-entries
4692 file date
4693 :deadline :scheduled :timestamp)))
4694 (setq rtnall (append rtnall rtn))))
4695 (if org-agenda-include-diary
4696 (progn
4697 (require 'diary-lib)
4698 (setq rtn (org-get-entries-from-diary date))
4699 (setq rtnall (append rtnall rtn))))
4700 (if (or rtnall org-agenda-show-all-dates)
4701 (progn
4702 (insert (format "%-9s %2d %s %4d\n"
4703 (calendar-day-name date)
4704 (extract-calendar-day date)
4705 (calendar-month-name (extract-calendar-month date))
4706 (extract-calendar-year date)))
4707 (put-text-property s (1- (point)) 'face
4708 'org-link)
4709 (if rtnall (insert
4710 (org-finalize-agenda-entries
4711 (org-agenda-add-time-grid-maybe
4712 rtnall nd todayp))
4713 "\n"))
4714 (put-text-property s (1- (point)) 'day d))))
4715 (goto-char (point-min))
4716 (setq buffer-read-only t)
4717 (org-fit-agenda-window)
4718 (unless (and (pos-visible-in-window-p (point-min))
4719 (pos-visible-in-window-p (point-max)))
4720 (goto-char (1- (point-max)))
4721 (recenter -1)
4722 (if (not (pos-visible-in-window-p (or start-pos 1)))
4723 (progn
4724 (goto-char (or start-pos 1))
4725 (recenter 1))))
4726 (goto-char (or start-pos 1))
4727 (if (not org-select-agenda-window) (select-window win))
4728 (message "")))
4729
4730 (defvar org-select-this-todo-keyword nil)
4731
4732 ;;;###autoload
4733 (defun org-todo-list (arg &optional keep-modes)
4734 "Show all TODO entries from all agenda file in a single list.
4735 The prefix arg can be used to select a specific TODO keyword and limit
4736 the list to these. When using \\[universal-argument], you will be prompted
4737 for a keyword. A numeric prefix directly selects the Nth keyword in
4738 `org-todo-keywords'."
4739 (interactive "P")
4740 (org-agenda-maybe-reset-markers 'force)
4741 (org-compile-prefix-format org-agenda-prefix-format)
4742 (let* ((org-agenda-keep-modes keep-modes)
4743 (today (time-to-days (current-time)))
4744 (date (calendar-gregorian-from-absolute today))
4745 (win (selected-window))
4746 (kwds org-todo-keywords)
4747 (completion-ignore-case t)
4748 (org-select-this-todo-keyword
4749 (if (stringp arg) arg
4750 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4751 rtn rtnall files file pos)
4752 (when (equal arg '(4))
4753 (setq org-select-this-todo-keyword
4754 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4755 nil t)))
4756 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4757 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4758 (progn
4759 (delete-other-windows)
4760 (switch-to-buffer-other-window
4761 (get-buffer-create org-agenda-buffer-name))))
4762 (setq buffer-read-only nil)
4763 (erase-buffer)
4764 (org-agenda-mode) (setq buffer-read-only nil)
4765 (set (make-local-variable 'last-arg) arg)
4766 (set (make-local-variable 'org-todo-keywords) kwds)
4767 (set (make-local-variable 'org-agenda-redo-command)
4768 '(org-todo-list (or current-prefix-arg last-arg) t))
4769 (setq files (org-agenda-files)
4770 rtnall nil)
4771 (while (setq file (pop files))
4772 (catch 'nextfile
4773 (org-check-agenda-file file)
4774 (setq rtn (org-agenda-get-day-entries file date :todo))
4775 (setq rtnall (append rtnall rtn))))
4776 (insert "Global list of TODO items of type: ")
4777 (add-text-properties (point-min) (1- (point))
4778 (list 'face 'org-link))
4779 (setq pos (point))
4780 (insert (or org-select-this-todo-keyword "ALL") "\n")
4781 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4782 (setq pos (point))
4783 (insert
4784 "Available with `N r': (0)ALL "
4785 (let ((n 0))
4786 (mapconcat (lambda (x)
4787 (format "(%d)%s" (setq n (1+ n)) x))
4788 org-todo-keywords " "))
4789 "\n")
4790 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4791 (when rtnall
4792 (insert (org-finalize-agenda-entries rtnall) "\n"))
4793 (goto-char (point-min))
4794 (setq buffer-read-only t)
4795 (org-fit-agenda-window)
4796 (if (not org-select-agenda-window) (select-window win))))
4797
4798 (defun org-check-agenda-file (file)
4799 "Make sure FILE exists. If not, ask user what to do."
4800 ;; FIXME: this does not correctly change the menus
4801 ;; Could probably be fixed by explicitly going to the buffer.
4802 (when (not (file-exists-p file))
4803 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4804 file)
4805 (let ((r (downcase (read-char-exclusive))))
4806 (cond
4807 ((equal r ?r)
4808 (org-remove-file file)
4809 (throw 'nextfile t))
4810 (t (error "Abort"))))))
4811
4812 (defun org-agenda-quit ()
4813 "Exit agenda by removing the window or the buffer."
4814 (interactive)
4815 (let ((buf (current-buffer)))
4816 (if (not (one-window-p)) (delete-window))
4817 (kill-buffer buf)
4818 (org-agenda-maybe-reset-markers 'force)))
4819
4820 (defun org-agenda-exit ()
4821 "Exit agenda by removing the window or the buffer.
4822 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4823 Org-mode buffers visited directly by the user will not be touched."
4824 (interactive)
4825 (org-release-buffers org-agenda-new-buffers)
4826 (setq org-agenda-new-buffers nil)
4827 (org-agenda-quit))
4828
4829 (defun org-agenda-redo ()
4830 "Rebuild Agenda.
4831 When this is the global TODO list, a prefix argument will be interpreted."
4832 (interactive)
4833 (eval org-agenda-redo-command))
4834
4835 (defun org-agenda-goto-today ()
4836 "Go to today."
4837 (interactive)
4838 (if (boundp 'starting-day)
4839 (let ((cmd (car org-agenda-redo-command))
4840 (iall (nth 1 org-agenda-redo-command))
4841 (nday (nth 3 org-agenda-redo-command))
4842 (keep (nth 4 org-agenda-redo-command)))
4843 (eval (list cmd iall nil nday keep)))
4844 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4845 (point-min)))))
4846
4847 (defun org-agenda-later (arg)
4848 "Go forward in time by `org-agenda-ndays' days.
4849 With prefix ARG, go forward that many times `org-agenda-ndays'."
4850 (interactive "p")
4851 (unless (boundp 'starting-day)
4852 (error "Not allowed"))
4853 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4854 (+ starting-day (* arg org-agenda-ndays)) nil t))
4855
4856 (defun org-agenda-earlier (arg)
4857 "Go back in time by `org-agenda-ndays' days.
4858 With prefix ARG, go back that many times `org-agenda-ndays'."
4859 (interactive "p")
4860 (unless (boundp 'starting-day)
4861 (error "Not allowed"))
4862 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4863 (- starting-day (* arg org-agenda-ndays)) nil t))
4864
4865 (defun org-agenda-week-view ()
4866 "Switch to weekly view for agenda."
4867 (interactive)
4868 (unless (boundp 'starting-day)
4869 (error "Not allowed"))
4870 (setq org-agenda-ndays 7)
4871 (org-agenda-list include-all-loc
4872 (or (get-text-property (point) 'day)
4873 starting-day)
4874 nil t)
4875 (org-agenda-set-mode-name)
4876 (message "Switched to week view"))
4877
4878 (defun org-agenda-day-view ()
4879 "Switch to weekly view for agenda."
4880 (interactive)
4881 (unless (boundp 'starting-day)
4882 (error "Not allowed"))
4883 (setq org-agenda-ndays 1)
4884 (org-agenda-list include-all-loc
4885 (or (get-text-property (point) 'day)
4886 starting-day)
4887 nil t)
4888 (org-agenda-set-mode-name)
4889 (message "Switched to day view"))
4890
4891 (defun org-agenda-next-date-line (&optional arg)
4892 "Jump to the next line indicating a date in agenda buffer."
4893 (interactive "p")
4894 (beginning-of-line 1)
4895 (if (looking-at "^\\S-") (forward-char 1))
4896 (if (not (re-search-forward "^\\S-" nil t arg))
4897 (progn
4898 (backward-char 1)
4899 (error "No next date after this line in this buffer")))
4900 (goto-char (match-beginning 0)))
4901
4902 (defun org-agenda-previous-date-line (&optional arg)
4903 "Jump to the next line indicating a date in agenda buffer."
4904 (interactive "p")
4905 (beginning-of-line 1)
4906 (if (not (re-search-backward "^\\S-" nil t arg))
4907 (error "No previous date before this line in this buffer")))
4908
4909 ;; Initialize the highlight
4910 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
4911 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
4912 'face 'highlight)
4913
4914 (defun org-highlight (begin end &optional buffer)
4915 "Highlight a region with overlay."
4916 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4917 org-hl begin end (or buffer (current-buffer))))
4918
4919 (defun org-unhighlight ()
4920 "Detach overlay INDEX."
4921 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4922
4923
4924 (defun org-agenda-follow-mode ()
4925 "Toggle follow mode in an agenda buffer."
4926 (interactive)
4927 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4928 (org-agenda-set-mode-name)
4929 (message "Follow mode is %s"
4930 (if org-agenda-follow-mode "on" "off")))
4931
4932 (defun org-agenda-log-mode ()
4933 "Toggle follow mode in an agenda buffer."
4934 (interactive)
4935 (setq org-agenda-show-log (not org-agenda-show-log))
4936 (org-agenda-set-mode-name)
4937 (org-agenda-redo)
4938 (message "Log mode is %s"
4939 (if org-agenda-show-log "on" "off")))
4940
4941 (defun org-agenda-toggle-diary ()
4942 "Toggle follow mode in an agenda buffer."
4943 (interactive)
4944 (setq org-agenda-include-diary (not org-agenda-include-diary))
4945 (org-agenda-redo)
4946 (org-agenda-set-mode-name)
4947 (message "Diary inclusion turned %s"
4948 (if org-agenda-include-diary "on" "off")))
4949
4950 (defun org-agenda-toggle-time-grid ()
4951 "Toggle follow mode in an agenda buffer."
4952 (interactive)
4953 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4954 (org-agenda-redo)
4955 (org-agenda-set-mode-name)
4956 (message "Time-grid turned %s"
4957 (if org-agenda-use-time-grid "on" "off")))
4958
4959 (defun org-agenda-set-mode-name ()
4960 "Set the mode name to indicate all the small mode settings."
4961 (setq mode-name
4962 (concat "Org-Agenda"
4963 (if (equal org-agenda-ndays 1) " Day" "")
4964 (if (equal org-agenda-ndays 7) " Week" "")
4965 (if org-agenda-follow-mode " Follow" "")
4966 (if org-agenda-include-diary " Diary" "")
4967 (if org-agenda-use-time-grid " Grid" "")
4968 (if org-agenda-show-log " Log" "")))
4969 (force-mode-line-update))
4970
4971 (defun org-agenda-post-command-hook ()
4972 (and (eolp) (not (bolp)) (backward-char 1))
4973 (if (and org-agenda-follow-mode
4974 (get-text-property (point) 'org-marker))
4975 (org-agenda-show)))
4976
4977 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4978
4979 (defun org-get-entries-from-diary (date)
4980 "Get the (Emacs Calendar) diary entries for DATE."
4981 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4982 (diary-display-hook '(fancy-diary-display))
4983 (list-diary-entries-hook
4984 (cons 'org-diary-default-entry list-diary-entries-hook))
4985 (diary-file-name-prefix-function nil) ; turn this feature off
4986 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4987 entries
4988 (org-disable-agenda-to-diary t))
4989 (save-excursion
4990 (save-window-excursion
4991 (list-diary-entries date 1)))
4992 (if (not (get-buffer fancy-diary-buffer))
4993 (setq entries nil)
4994 (with-current-buffer fancy-diary-buffer
4995 (setq buffer-read-only nil)
4996 (if (= (point-max) 1)
4997 ;; No entries
4998 (setq entries nil)
4999 ;; Omit the date and other unnecessary stuff
5000 (org-agenda-cleanup-fancy-diary)
5001 ;; Add prefix to each line and extend the text properties
5002 (if (= (point-max) 1)
5003 (setq entries nil)
5004 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5005 (set-buffer-modified-p nil)
5006 (kill-buffer fancy-diary-buffer)))
5007 (when entries
5008 (setq entries (org-split-string entries "\n"))
5009 (setq entries
5010 (mapcar
5011 (lambda (x)
5012 (setq x (org-format-agenda-item "" x "Diary" 'time))
5013 ;; Extend the text properties to the beginning of the line
5014 (add-text-properties
5015 0 (length x)
5016 (text-properties-at (1- (length x)) x)
5017 x)
5018 x)
5019 entries)))))
5020
5021 (defun org-agenda-cleanup-fancy-diary ()
5022 "Remove unwanted stuff in buffer created by fancy-diary-display.
5023 This gets rid of the date, the underline under the date, and
5024 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5025 date. Itt also removes lines that contain only whitespace."
5026 (goto-char (point-min))
5027 (if (looking-at ".*?:[ \t]*")
5028 (progn
5029 (replace-match "")
5030 (re-search-forward "\n=+$" nil t)
5031 (replace-match "")
5032 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5033 (re-search-forward "\n=+$" nil t)
5034 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5035 (goto-char (point-min))
5036 (while (re-search-forward "^ +\n" nil t)
5037 (replace-match ""))
5038 (goto-char (point-min))
5039 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5040 (replace-match "")))
5041
5042 ;; Make sure entries from the diary have the right text properties.
5043 (eval-after-load "diary-lib"
5044 '(if (boundp 'diary-modify-entry-list-string-function)
5045 ;; We can rely on the hook, nothing to do
5046 nil
5047 ;; Hook not avaiable, must use advice to make this work
5048 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5049 "Make the position visible."
5050 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5051 (stringp string)
5052 (buffer-file-name))
5053 (setq string (org-modify-diary-entry-string string))))))
5054
5055 (defun org-modify-diary-entry-string (string)
5056 "Add text properties to string, allowing org-mode to act on it."
5057 (add-text-properties
5058 0 (length string)
5059 (list 'mouse-face 'highlight
5060 'keymap org-agenda-keymap
5061 'help-echo
5062 (format
5063 "mouse-2 or RET jump to diary file %s"
5064 (abbreviate-file-name (buffer-file-name)))
5065 'org-agenda-diary-link t
5066 'org-marker (org-agenda-new-marker (point-at-bol)))
5067 string)
5068 string)
5069
5070 (defun org-diary-default-entry ()
5071 "Add a dummy entry to the diary.
5072 Needed to avoid empty dates which mess up holiday display."
5073 ;; Catch the error if dealing with the new add-to-diary-alist
5074 (when org-disable-agenda-to-diary
5075 (condition-case nil
5076 (add-to-diary-list original-date "Org-mode dummy" "")
5077 (error
5078 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5079
5080 (defun org-cycle-agenda-files ()
5081 "Cycle through the files in `org-agenda-files'.
5082 If the current buffer visits an agenda file, find the next one in the list.
5083 If the current buffer does not, find the first agenda file."
5084 (interactive)
5085 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5086 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
5087 file)
5088 (unless files (error "No agenda files"))
5089 (catch 'exit
5090 (while (setq file (pop files))
5091 (if (equal (file-truename file) tcf)
5092 (when (car files)
5093 (find-file (car files))
5094 (throw 'exit t))))
5095 (find-file (car org-agenda-files)))))
5096
5097 (defun org-agenda-file-to-end (&optional file)
5098 "Move/add the current file to the end of the agenda fiole list.
5099 I the file is not present in the list, it is appended ot the list. If it is
5100 present, it is moved there."
5101 (interactive)
5102 (org-agenda-file-to-front 'to-end file))
5103
5104 (defun org-agenda-file-to-front (&optional to-end file)
5105 "Move/add the current file to the top of the agenda file list.
5106 If the file is not present in the list, it is added to the front. If it is
5107 present, it is moved there. With optional argument TO-END, add/move to the
5108 end of the list."
5109 (interactive "P")
5110 (let ((file-alist (mapcar (lambda (x)
5111 (cons (file-truename x) x))
5112 org-agenda-files))
5113 (ctf (file-truename (buffer-file-name)))
5114 x had)
5115 (setq x (assoc ctf file-alist) had x)
5116
5117 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
5118 (if to-end
5119 (setq file-alist (append (delq x file-alist) (list x)))
5120 (setq file-alist (cons x (delq x file-alist))))
5121 (setq org-agenda-files (mapcar 'cdr file-alist))
5122 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5123 (customize-save-variable 'org-agenda-files org-agenda-files))
5124 (org-install-agenda-files-menu)
5125 (message "File %s to %s of agenda file list"
5126 (if had "moved" "added") (if to-end "end" "front"))))
5127
5128 (defun org-remove-file (&optional file)
5129 "Remove current file from the list of files in variable `org-agenda-files'.
5130 These are the files which are being checked for agenda entries.
5131 Optional argument FILE means, use this file instead of the current."
5132 (interactive)
5133 (let* ((file (or file (buffer-file-name)))
5134 (true-file (file-truename file))
5135 (afile (abbreviate-file-name file))
5136 (files (delq nil (mapcar
5137 (lambda (x)
5138 (if (equal true-file
5139 (file-truename x))
5140 nil x))
5141 org-agenda-files))))
5142 (if (not (= (length files) (length org-agenda-files)))
5143 (progn
5144 (setq org-agenda-files files)
5145 (customize-save-variable 'org-agenda-files org-agenda-files)
5146 (org-install-agenda-files-menu)
5147 (message "Removed file: %s" afile))
5148 (message "File was not in list: %s" afile))))
5149
5150 (defun org-file-menu-entry (file)
5151 (vector file (list 'find-file file) t))
5152 ;; FIXME: Maybe we removed a buffer visited through the menu from
5153 ;; org-agenda-new-buffers, so that the buffer will not be removed
5154 ;; when exiting the agenda????
5155
5156 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5157 "Return a list of all relevant day numbers from BEG to END buffer positions.
5158 If NO-RANGES is non-nil, include only the start and end dates of a range,
5159 not every single day in the range. If FORCE-TODAY is non-nil, make
5160 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5161 inactive time stamps (those in square brackets) are included."
5162 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5163 dates date day day1 day2 ts1 ts2)
5164 (if force-today
5165 (setq dates (list (time-to-days (current-time)))))
5166 (save-excursion
5167 (goto-char beg)
5168 (while (re-search-forward re end t)
5169 (setq day (time-to-days (org-time-string-to-time
5170 (substring (match-string 1) 0 10))))
5171 (or (memq day dates) (push day dates)))
5172 (unless no-ranges
5173 (goto-char beg)
5174 (while (re-search-forward org-tr-regexp end t)
5175 (setq ts1 (substring (match-string 1) 0 10)
5176 ts2 (substring (match-string 2) 0 10)
5177 day1 (time-to-days (org-time-string-to-time ts1))
5178 day2 (time-to-days (org-time-string-to-time ts2)))
5179 (while (< (setq day1 (1+ day1)) day2)
5180 (or (memq day1 dates) (push day1 dates)))))
5181 (sort dates '<))))
5182
5183 ;;;###autoload
5184 (defun org-diary (&rest args)
5185 "Return diary information from org-files.
5186 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5187 It accesses org files and extracts information from those files to be
5188 listed in the diary. The function accepts arguments specifying what
5189 items should be listed. The following arguments are allowed:
5190
5191 :timestamp List the headlines of items containing a date stamp or
5192 date range matching the selected date. Deadlines will
5193 also be listed, on the expiration day.
5194
5195 :deadline List any deadlines past due, or due within
5196 `org-deadline-warning-days'. The listing occurs only
5197 in the diary for *today*, not at any other date. If
5198 an entry is marked DONE, it is no longer listed.
5199
5200 :scheduled List all items which are scheduled for the given date.
5201 The diary for *today* also contains items which were
5202 scheduled earlier and are not yet marked DONE.
5203
5204 :todo List all TODO items from the org-file. This may be a
5205 long list - so this is not turned on by default.
5206 Like deadlines, these entries only show up in the
5207 diary for *today*, not at any other date.
5208
5209 The call in the diary file should look like this:
5210
5211 &%%(org-diary) ~/path/to/some/orgfile.org
5212
5213 Use a separate line for each org file to check. Or, if you omit the file name,
5214 all files listed in `org-agenda-files' will be checked automatically:
5215
5216 &%%(org-diary)
5217
5218 If you don't give any arguments (as in the example above), the default
5219 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5220 also be written as
5221
5222 &%%(org-diary :deadline :timestamp :scheduled)
5223
5224 The function expects the lisp variables `entry' and `date' to be provided
5225 by the caller, because this is how the calendar works. Don't use this
5226 function from a program - use `org-agenda-get-day-entries' instead."
5227 (org-agenda-maybe-reset-markers)
5228 (org-compile-prefix-format org-agenda-prefix-format)
5229 (setq args (or args '(:deadline :scheduled :timestamp)))
5230 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5231 (list entry)
5232 org-agenda-files))
5233 file rtn results)
5234 ;; If this is called during org-agenda, don't return any entries to
5235 ;; the calendar. Org Agenda will list these entries itself.
5236 (if org-disable-agenda-to-diary (setq files nil))
5237 (while (setq file (pop files))
5238 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5239 (setq results (append results rtn)))
5240 (if results
5241 (concat (org-finalize-agenda-entries results) "\n"))))
5242 (defvar org-category-table nil)
5243 (defun org-get-category-table ()
5244 "Get the table of categories and positions in current buffer."
5245 (let (tbl)
5246 (save-excursion
5247 (goto-char (point-min))
5248 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5249 (push (cons (point) (org-trim (match-string 2))) tbl)))
5250 tbl))
5251 (defun org-get-category (&optional pos)
5252 "Get the category applying to position POS."
5253 (if (not org-category-table)
5254 (cond
5255 ((null org-category)
5256 (setq org-category
5257 (if (buffer-file-name)
5258 (file-name-sans-extension
5259 (file-name-nondirectory (buffer-file-name)))
5260 "???")))
5261 ((symbolp org-category) (symbol-name org-category))
5262 (t org-category))
5263 (let ((tbl org-category-table)
5264 (pos (or pos (point))))
5265 (while (and tbl (> (caar tbl) pos))
5266 (pop tbl))
5267 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5268 org-category-table))))))
5269
5270 (defun org-agenda-get-day-entries (file date &rest args)
5271 "Does the work for `org-diary' and `org-agenda'.
5272 FILE is the path to a file to be checked for entries. DATE is date like
5273 the one returned by `calendar-current-date'. ARGS are symbols indicating
5274 which kind of entries should be extracted. For details about these, see
5275 the documentation of `org-diary'."
5276 (setq args (or args '(:deadline :scheduled :timestamp)))
5277 (let* ((org-startup-with-deadline-check nil)
5278 (org-startup-folded nil)
5279 (buffer (if (file-exists-p file)
5280 (org-get-agenda-file-buffer file)
5281 (error "No such file %s" file)))
5282 arg results rtn)
5283 (if (not buffer)
5284 ;; If file does not exist, make sure an error message ends up in diary
5285 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5286 (with-current-buffer buffer
5287 (unless (eq major-mode 'org-mode)
5288 (error "Agenda file %s is not in `org-mode'" file))
5289 (setq org-category-table (org-get-category-table))
5290 (let ((case-fold-search nil))
5291 (save-excursion
5292 (save-restriction
5293 (if org-respect-restriction
5294 (if (org-region-active-p)
5295 ;; Respect a region to restrict search
5296 (narrow-to-region (region-beginning) (region-end)))
5297 ;; If we work for the calendar or many files,
5298 ;; get rid of any restriction
5299 (widen))
5300 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5301 (while (setq arg (pop args))
5302 (cond
5303 ((and (eq arg :todo)
5304 (equal date (calendar-current-date)))
5305 (setq rtn (org-agenda-get-todos))
5306 (setq results (append results rtn)))
5307 ((eq arg :timestamp)
5308 (setq rtn (org-agenda-get-blocks))
5309 (setq results (append results rtn))
5310 (setq rtn (org-agenda-get-timestamps))
5311 (setq results (append results rtn)))
5312 ((eq arg :scheduled)
5313 (setq rtn (org-agenda-get-scheduled))
5314 (setq results (append results rtn)))
5315 ((eq arg :closed)
5316 (setq rtn (org-agenda-get-closed))
5317 (setq results (append results rtn)))
5318 ((and (eq arg :deadline)
5319 (equal date (calendar-current-date)))
5320 (setq rtn (org-agenda-get-deadlines))
5321 (setq results (append results rtn))))))))
5322 results))))
5323
5324 (defun org-entry-is-done-p ()
5325 "Is the current entry marked DONE?"
5326 (save-excursion
5327 (and (re-search-backward "[\r\n]\\*" nil t)
5328 (looking-at org-nl-done-regexp))))
5329
5330 (defun org-at-date-range-p ()
5331 "Is the cursor inside a date range?"
5332 (interactive)
5333 (save-excursion
5334 (catch 'exit
5335 (let ((pos (point)))
5336 (skip-chars-backward "^<\r\n")
5337 (skip-chars-backward "<")
5338 (and (looking-at org-tr-regexp)
5339 (>= (match-end 0) pos)
5340 (throw 'exit t))
5341 (skip-chars-backward "^<\r\n")
5342 (skip-chars-backward "<")
5343 (and (looking-at org-tr-regexp)
5344 (>= (match-end 0) pos)
5345 (throw 'exit t)))
5346 nil)))
5347
5348 (defun org-agenda-get-todos ()
5349 "Return the TODO information for agenda display."
5350 (let* ((props (list 'face nil
5351 'done-face 'org-done
5352 'mouse-face 'highlight
5353 'keymap org-agenda-keymap
5354 'help-echo
5355 (format "mouse-2 or RET jump to org file %s"
5356 (abbreviate-file-name (buffer-file-name)))))
5357 (regexp (concat "[\n\r]\\*+ *\\("
5358 (if org-select-this-todo-keyword
5359 (concat "\\<\\(" org-select-this-todo-keyword
5360 "\\)\\>")
5361 org-not-done-regexp)
5362 "[^\n\r]*\\)"))
5363 marker priority category
5364 ee txt)
5365 (goto-char (point-min))
5366 (while (re-search-forward regexp nil t)
5367 (goto-char (match-beginning 1))
5368 (setq marker (org-agenda-new-marker (point-at-bol))
5369 category (org-get-category)
5370 txt (org-format-agenda-item "" (match-string 1) category)
5371 priority
5372 (+ (org-get-priority txt)
5373 (if org-todo-kwd-priority-p
5374 (- org-todo-kwd-max-priority -2
5375 (length
5376 (member (match-string 2) org-todo-keywords)))
5377 1)))
5378 (add-text-properties
5379 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5380 'priority priority 'category category)
5381 props)
5382 txt)
5383 (push txt ee)
5384 (goto-char (match-end 1)))
5385 (nreverse ee)))
5386
5387 (defconst org-agenda-no-heading-message
5388 "No heading for this item in buffer or region")
5389
5390 (defun org-agenda-get-timestamps ()
5391 "Return the date stamp information for agenda display."
5392 (let* ((props (list 'face nil
5393 'mouse-face 'highlight
5394 'keymap org-agenda-keymap
5395 'help-echo
5396 (format "mouse-2 or RET jump to org file %s"
5397 (abbreviate-file-name (buffer-file-name)))))
5398 (regexp (regexp-quote
5399 (substring
5400 (format-time-string
5401 (car org-time-stamp-formats)
5402 (apply 'encode-time ; DATE bound by calendar
5403 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5404 0 11)))
5405 marker hdmarker deadlinep scheduledp donep tmp priority category
5406 ee txt timestr)
5407 (goto-char (point-min))
5408 (while (re-search-forward regexp nil t)
5409 (if (not (save-match-data (org-at-date-range-p)))
5410 (progn
5411 (setq marker (org-agenda-new-marker (match-beginning 0))
5412 category (org-get-category (match-beginning 0))
5413 tmp (buffer-substring (max (point-min)
5414 (- (match-beginning 0)
5415 org-ds-keyword-length))
5416 (match-beginning 0))
5417 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5418 deadlinep (string-match org-deadline-regexp tmp)
5419 scheduledp (string-match org-scheduled-regexp tmp)
5420 donep (org-entry-is-done-p))
5421 (if (string-match ">" timestr)
5422 ;; substring should only run to end of time stamp
5423 (setq timestr (substring timestr 0 (match-end 0))))
5424 (save-excursion
5425 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5426 (progn
5427 (goto-char (match-end 1))
5428 (setq hdmarker (org-agenda-new-marker))
5429 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5430 (setq txt (org-format-agenda-item
5431 (format "%s%s"
5432 (if deadlinep "Deadline: " "")
5433 (if scheduledp "Scheduled: " ""))
5434 (match-string 1) category timestr)))
5435 (setq txt org-agenda-no-heading-message))
5436 (setq priority (org-get-priority txt))
5437 (add-text-properties
5438 0 (length txt) (append (list 'org-marker marker
5439 'org-hd-marker hdmarker) props)
5440 txt)
5441 (if deadlinep
5442 (add-text-properties
5443 0 (length txt)
5444 (list 'face
5445 (if donep 'org-done 'org-warning)
5446 'undone-face 'org-warning
5447 'done-face 'org-done
5448 'category category
5449 'priority (+ 100 priority))
5450 txt)
5451 (if scheduledp
5452 (add-text-properties
5453 0 (length txt)
5454 (list 'face 'org-scheduled-today
5455 'undone-face 'org-scheduled-today
5456 'done-face 'org-done
5457 'category category
5458 priority (+ 99 priority))
5459 txt)
5460 (add-text-properties
5461 0 (length txt)
5462 (list 'priority priority 'category category) txt)))
5463 (push txt ee))
5464 (outline-next-heading))))
5465 (nreverse ee)))
5466
5467 (defun org-agenda-get-closed ()
5468 "Return the loggedd TODO entries for agenda display."
5469 (let* ((props (list 'mouse-face 'highlight
5470 'keymap org-agenda-keymap
5471 'help-echo
5472 (format "mouse-2 or RET jump to org file %s"
5473 (abbreviate-file-name (buffer-file-name)))))
5474 (regexp (concat
5475 "\\<" org-closed-string " *\\["
5476 (regexp-quote
5477 (substring
5478 (format-time-string
5479 (car org-time-stamp-formats)
5480 (apply 'encode-time ; DATE bound by calendar
5481 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5482 1 11))))
5483 marker hdmarker priority category
5484 ee txt timestr)
5485 (goto-char (point-min))
5486 (while (re-search-forward regexp nil t)
5487 (if (not (save-match-data (org-at-date-range-p)))
5488 (progn
5489 (setq marker (org-agenda-new-marker (match-beginning 0))
5490 category (org-get-category (match-beginning 0))
5491 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5492 ;; donep (org-entry-is-done-p)
5493 )
5494 (if (string-match "\\]" timestr)
5495 ;; substring should only run to end of time stamp
5496 (setq timestr (substring timestr 0 (match-end 0))))
5497 (save-excursion
5498 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5499 (progn
5500 (goto-char (match-end 1))
5501 (setq hdmarker (org-agenda-new-marker))
5502 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5503 (setq txt (org-format-agenda-item
5504 "Closed: "
5505 (match-string 1) category timestr)))
5506 (setq txt org-agenda-no-heading-message))
5507 (setq priority 100000)
5508 (add-text-properties
5509 0 (length txt) (append (list 'org-marker marker
5510 'org-hd-marker hdmarker
5511 'face 'org-done
5512 'priority priority
5513 'category category
5514 'undone-face 'org-warning
5515 'done-face 'org-done) props)
5516 txt)
5517 (push txt ee))
5518 (outline-next-heading))))
5519 (nreverse ee)))
5520
5521 (defun org-agenda-get-deadlines ()
5522 "Return the deadline information for agenda display."
5523 (let* ((wdays org-deadline-warning-days)
5524 (props (list 'mouse-face 'highlight
5525 'keymap org-agenda-keymap
5526 'help-echo
5527 (format "mouse-2 or RET jump to org file %s"
5528 (abbreviate-file-name (buffer-file-name)))))
5529 (regexp org-deadline-time-regexp)
5530 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5531 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5532 d2 diff pos pos1 category
5533 ee txt head)
5534 (goto-char (point-min))
5535 (while (re-search-forward regexp nil t)
5536 (setq pos (1- (match-beginning 1))
5537 d2 (time-to-days
5538 (org-time-string-to-time (match-string 1)))
5539 diff (- d2 d1))
5540 ;; When to show a deadline in the calendar:
5541 ;; If the expiration is within wdays warning time.
5542 ;; Past-due deadlines are only shown on the current date
5543 (if (and (< diff wdays) todayp (not (= diff 0)))
5544 (save-excursion
5545 (setq category (org-get-category))
5546 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5547 (progn
5548 (goto-char (match-end 0))
5549 (setq pos1 (match-end 1))
5550 (setq head (buffer-substring-no-properties
5551 (point)
5552 (progn (skip-chars-forward "^\r\n")
5553 (point))))
5554 (if (string-match org-looking-at-done-regexp head)
5555 (setq txt nil)
5556 (setq txt (org-format-agenda-item
5557 (format "In %3d d.: " diff) head category))))
5558 (setq txt org-agenda-no-heading-message))
5559 (when txt
5560 (add-text-properties
5561 0 (length txt)
5562 (append
5563 (list 'org-marker (org-agenda-new-marker pos)
5564 'org-hd-marker (org-agenda-new-marker pos1)
5565 'priority (+ (- 10 diff) (org-get-priority txt))
5566 'category category
5567 'face (cond ((<= diff 0) 'org-warning)
5568 ((<= diff 5) 'org-scheduled-previously)
5569 (t nil))
5570 'undone-face (cond
5571 ((<= diff 0) 'org-warning)
5572 ((<= diff 5) 'org-scheduled-previously)
5573 (t nil))
5574 'done-face 'org-done)
5575 props)
5576 txt)
5577 (push txt ee)))))
5578 ee))
5579
5580 (defun org-agenda-get-scheduled ()
5581 "Return the scheduled information for agenda display."
5582 (let* ((props (list 'face 'org-scheduled-previously
5583 'undone-face 'org-scheduled-previously
5584 'done-face 'org-done
5585 'mouse-face 'highlight
5586 'keymap org-agenda-keymap
5587 'help-echo
5588 (format "mouse-2 or RET jump to org file %s"
5589 (abbreviate-file-name (buffer-file-name)))))
5590 (regexp org-scheduled-time-regexp)
5591 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5592 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5593 d2 diff pos pos1 category
5594 ee txt head)
5595 (goto-char (point-min))
5596 (while (re-search-forward regexp nil t)
5597 (setq pos (1- (match-beginning 1))
5598 d2 (time-to-days
5599 (org-time-string-to-time (match-string 1)))
5600 diff (- d2 d1))
5601 ;; When to show a scheduled item in the calendar:
5602 ;; If it is on or past the date.
5603 (if (and (< diff 0) todayp)
5604 (save-excursion
5605 (setq category (org-get-category))
5606 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5607 (progn
5608 (goto-char (match-end 0))
5609 (setq pos1 (match-end 1))
5610 (setq head (buffer-substring-no-properties
5611 (point)
5612 (progn (skip-chars-forward "^\r\n") (point))))
5613 (if (string-match org-looking-at-done-regexp head)
5614 (setq txt nil)
5615 (setq txt (org-format-agenda-item
5616 (format "Sched.%2dx: " (- 1 diff)) head
5617 category))))
5618 (setq txt org-agenda-no-heading-message))
5619 (when txt
5620 (add-text-properties
5621 0 (length txt)
5622 (append (list 'org-marker (org-agenda-new-marker pos)
5623 'org-hd-marker (org-agenda-new-marker pos1)
5624 'priority (+ (- 5 diff) (org-get-priority txt))
5625 'category category)
5626 props) txt)
5627 (push txt ee)))))
5628 ee))
5629
5630 (defun org-agenda-get-blocks ()
5631 "Return the date-range information for agenda display."
5632 (let* ((props (list 'face nil
5633 'mouse-face 'highlight
5634 'keymap org-agenda-keymap
5635 'help-echo
5636 (format "mouse-2 or RET jump to org file %s"
5637 (abbreviate-file-name (buffer-file-name)))))
5638 (regexp org-tr-regexp)
5639 (d0 (calendar-absolute-from-gregorian date))
5640 marker hdmarker ee txt d1 d2 s1 s2 timestr category)
5641 (goto-char (point-min))
5642 (while (re-search-forward regexp nil t)
5643 (setq timestr (match-string 0)
5644 s1 (match-string 1)
5645 s2 (match-string 2)
5646 d1 (time-to-days (org-time-string-to-time s1))
5647 d2 (time-to-days (org-time-string-to-time s2)))
5648 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5649 ;; Only allow days between the limits, because the normal
5650 ;; date stamps will catch the limits.
5651 (save-excursion
5652 (setq marker (org-agenda-new-marker (point)))
5653 (setq category (org-get-category))
5654 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5655 (progn
5656 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5657 (goto-char (match-end 1))
5658 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5659 (setq txt (org-format-agenda-item
5660 (format (if (= d1 d2) "" "(%d/%d): ")
5661 (1+ (- d0 d1)) (1+ (- d2 d1)))
5662 (match-string 1) category
5663 (if (= d0 d1) timestr))))
5664 (setq txt org-agenda-no-heading-message))
5665 (add-text-properties
5666 0 (length txt) (append (list 'org-marker marker
5667 'org-hd-marker hdmarker
5668 'priority (org-get-priority txt)
5669 'category category)
5670 props)
5671 txt)
5672 (push txt ee)))
5673 (outline-next-heading))
5674 ;; Sort the entries by expiration date.
5675 (nreverse ee)))
5676
5677 (defconst org-plain-time-of-day-regexp
5678 (concat
5679 "\\(\\<[012]?[0-9]"
5680 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5681 "\\(--?"
5682 "\\(\\<[012]?[0-9]"
5683 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5684 "\\)?")
5685 "Regular expression to match a plain time or time range.
5686 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5687 groups carry important information:
5688 0 the full match
5689 1 the first time, range or not
5690 8 the second time, if it is a range.")
5691
5692 (defconst org-stamp-time-of-day-regexp
5693 (concat
5694 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5695 "\\([012][0-9]:[0-5][0-9]\\)>"
5696 "\\(--?"
5697 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5698 "Regular expression to match a timestamp time or time range.
5699 After a match, the following groups carry important information:
5700 0 the full match
5701 1 date plus weekday, for backreferencing to make sure both times on same day
5702 2 the first time, range or not
5703 4 the second time, if it is a range.")
5704
5705 (defvar org-prefix-has-time nil
5706 "A flag, set by `org-compile-prefix-format'.
5707 The flag is set if the currently compiled format contains a `%t'.")
5708
5709 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
5710 "Format TXT to be inserted into the agenda buffer.
5711 In particular, it adds the prefix and corresponding text properties. EXTRA
5712 must be a string and replaces the `%s' specifier in the prefix format.
5713 CATEGORY (string, symbol or nil) may be used to overule the default
5714 category taken from local variable or file name. It will replace the `%c'
5715 specifier in the format. DOTIME, when non-nil, indicates that a
5716 time-of-day should be extracted from TXT for sorting of this entry, and for
5717 the `%t' specifier in the format. When DOTIME is a string, this string is
5718 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5719 only the correctly processes TXT should be returned - this is used by
5720 `org-agenda-change-all-lines'."
5721 (save-match-data
5722 ;; Diary entries sometimes have extra whitespace at the beginning
5723 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5724 (let* ((category (or category
5725 org-category
5726 (if (buffer-file-name)
5727 (file-name-sans-extension
5728 (file-name-nondirectory (buffer-file-name)))
5729 "")))
5730 time ;; needed for the eval of the prefix format
5731 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5732 (time-of-day (and dotime (org-get-time-of-day ts)))
5733 stamp plain s0 s1 s2 rtn)
5734 (when (and dotime time-of-day org-prefix-has-time)
5735 ;; Extract starting and ending time and move them to prefix
5736 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5737 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5738 (setq s0 (match-string 0 ts)
5739 s1 (match-string (if plain 1 2) ts)
5740 s2 (match-string (if plain 8 4) ts))
5741
5742 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5743 ;; them, we might want to remove them there to avoid duplication.
5744 ;; The user can turn this off with a variable.
5745 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5746 (string-match (concat (regexp-quote s0) " *") txt)
5747 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5748 (= (match-beginning 0) 0)
5749 t))
5750 (setq txt (replace-match "" nil nil txt))))
5751 ;; Normalize the time(s) to 24 hour
5752 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5753 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5754
5755 ;; Create the final string
5756 (if noprefix
5757 (setq rtn txt)
5758 ;; Prepare the variables needed in the eval of the compiled format
5759 (setq time (cond (s2 (concat s1 "-" s2))
5760 (s1 (concat s1 "......"))
5761 (t ""))
5762 extra (or extra "")
5763 category (if (symbolp category) (symbol-name category) category))
5764 ;; Evaluate the compiled format
5765 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5766
5767 ;; And finally add the text properties
5768 (add-text-properties
5769 0 (length rtn) (list 'category (downcase category)
5770 'prefix-length (- (length rtn) (length txt))
5771 'time-of-day time-of-day
5772 'dotime dotime)
5773 rtn)
5774 rtn)))
5775
5776 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5777 (catch 'exit
5778 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5779 ((and todayp (member 'today (car org-agenda-time-grid))))
5780 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5781 ((member 'weekly (car org-agenda-time-grid)))
5782 (t (throw 'exit list)))
5783 (let* ((have (delq nil (mapcar
5784 (lambda (x) (get-text-property 1 'time-of-day x))
5785 list)))
5786 (string (nth 1 org-agenda-time-grid))
5787 (gridtimes (nth 2 org-agenda-time-grid))
5788 (req (car org-agenda-time-grid))
5789 (remove (member 'remove-match req))
5790 new time)
5791 (if (and (member 'require-timed req) (not have))
5792 ;; don't show empty grid
5793 (throw 'exit list))
5794 (while (setq time (pop gridtimes))
5795 (unless (and remove (member time have))
5796 (setq time (int-to-string time))
5797 (push (org-format-agenda-item
5798 nil string "" ;; FIXME: put a category for the grid?
5799 (concat (substring time 0 -2) ":" (substring time -2)))
5800 new)
5801 (put-text-property
5802 1 (length (car new)) 'face 'org-time-grid (car new))))
5803 (if (member 'time-up org-agenda-sorting-strategy)
5804 (append new list)
5805 (append list new)))))
5806
5807 (defun org-compile-prefix-format (format)
5808 "Compile the prefix format into a Lisp form that can be evaluated.
5809 The resulting form is returned and stored in the variable
5810 `org-prefix-format-compiled'."
5811 (setq org-prefix-has-time nil)
5812 (let ((start 0) varform vars var (s format) c f opt)
5813 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5814 s start)
5815 (setq var (cdr (assoc (match-string 4 s)
5816 '(("c" . category) ("t" . time) ("s" . extra))))
5817 c (or (match-string 3 s) "")
5818 opt (match-beginning 1)
5819 start (1+ (match-beginning 0)))
5820 (if (equal var 'time) (setq org-prefix-has-time t))
5821 (setq f (concat "%" (match-string 2 s) "s"))
5822 (if opt
5823 (setq varform
5824 `(if (equal "" ,var)
5825 ""
5826 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5827 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5828 (setq s (replace-match "%s" t nil s))
5829 (push varform vars))
5830 (setq vars (nreverse vars))
5831 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5832
5833 (defun org-get-time-of-day (s &optional string)
5834 "Check string S for a time of day.
5835 If found, return it as a military time number between 0 and 2400.
5836 If not found, return nil.
5837 The optional STRING argument forces conversion into a 5 character wide string
5838 HH:MM."
5839 (save-match-data
5840 (when
5841 (or
5842 (string-match
5843 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5844 (string-match
5845 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5846 (let* ((t0 (+ (* 100
5847 (+ (string-to-number (match-string 1 s))
5848 (if (and (match-beginning 4)
5849 (equal (downcase (match-string 4 s)) "pm"))
5850 12 0)))
5851 (if (match-beginning 3)
5852 (string-to-number (match-string 3 s))
5853 0)))
5854 (t1 (concat " " (int-to-string t0))))
5855 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
5856
5857 (defun org-finalize-agenda-entries (list)
5858 "Sort and concatenate the agenda items."
5859 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
5860
5861 (defsubst org-cmp-priority (a b)
5862 "Compare the priorities of string a and b."
5863 (let ((pa (or (get-text-property 1 'priority a) 0))
5864 (pb (or (get-text-property 1 'priority b) 0)))
5865 (cond ((> pa pb) +1)
5866 ((< pa pb) -1)
5867 (t nil))))
5868
5869 (defsubst org-cmp-category (a b)
5870 "Compare the string values of categories of strings a and b."
5871 (let ((ca (or (get-text-property 1 'category a) ""))
5872 (cb (or (get-text-property 1 'category b) "")))
5873 (cond ((string-lessp ca cb) -1)
5874 ((string-lessp cb ca) +1)
5875 (t nil))))
5876
5877 (defsubst org-cmp-time (a b)
5878 "Compare the time-of-day values of strings a and b."
5879 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
5880 (ta (or (get-text-property 1 'time-of-day a) def))
5881 (tb (or (get-text-property 1 'time-of-day b) def)))
5882 (cond ((< ta tb) -1)
5883 ((< tb ta) +1)
5884 (t nil))))
5885
5886 (defun org-entries-lessp (a b)
5887 "Predicate for sorting agenda entries."
5888 ;; The following variables will be used when the form is evaluated.
5889 (let* ((time-up (org-cmp-time a b))
5890 (time-down (if time-up (- time-up) nil))
5891 (priority-up (org-cmp-priority a b))
5892 (priority-down (if priority-up (- priority-up) nil))
5893 (category-up (org-cmp-category a b))
5894 (category-down (if category-up (- category-up) nil))
5895 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
5896 (cdr (assoc
5897 (eval (cons 'or org-agenda-sorting-strategy))
5898 '((-1 . t) (1 . nil) (nil . nil))))))
5899
5900 (defun org-agenda-show-priority ()
5901 "Show the priority of the current item.
5902 This priority is composed of the main priority given with the [#A] cookies,
5903 and by additional input from the age of a schedules or deadline entry."
5904 (interactive)
5905 (let* ((pri (get-text-property (point-at-bol) 'priority)))
5906 (message "Priority is %d" (if pri pri -1000))))
5907
5908 (defun org-agenda-goto (&optional highlight)
5909 "Go to the Org-mode file which contains the item at point."
5910 (interactive)
5911 (let* ((marker (or (get-text-property (point) 'org-marker)
5912 (org-agenda-error)))
5913 (buffer (marker-buffer marker))
5914 (pos (marker-position marker)))
5915 (switch-to-buffer-other-window buffer)
5916 (widen)
5917 (goto-char pos)
5918 (when (eq major-mode 'org-mode)
5919 (org-show-hidden-entry)
5920 (save-excursion
5921 (and (outline-next-heading)
5922 (org-flag-heading nil)))) ; show the next heading
5923 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
5924
5925 (defun org-agenda-switch-to ()
5926 "Go to the Org-mode file which contains the item at point."
5927 (interactive)
5928 (let* ((marker (or (get-text-property (point) 'org-marker)
5929 (org-agenda-error)))
5930 (buffer (marker-buffer marker))
5931 (pos (marker-position marker)))
5932 (switch-to-buffer buffer)
5933 (delete-other-windows)
5934 (widen)
5935 (goto-char pos)
5936 (when (eq major-mode 'org-mode)
5937 (org-show-hidden-entry)
5938 (save-excursion
5939 (and (outline-next-heading)
5940 (org-flag-heading nil)))))) ; show the next heading
5941
5942 (defun org-agenda-goto-mouse (ev)
5943 "Go to the Org-mode file which contains the item at the mouse click."
5944 (interactive "e")
5945 (mouse-set-point ev)
5946 (org-agenda-goto))
5947
5948 (defun org-agenda-show ()
5949 "Display the Org-mode file which contains the item at point."
5950 (interactive)
5951 (let ((win (selected-window)))
5952 (org-agenda-goto t)
5953 (select-window win)))
5954
5955 (defun org-agenda-recenter (arg)
5956 "Display the Org-mode file which contains the item at point and recenter."
5957 (interactive "P")
5958 (let ((win (selected-window)))
5959 (org-agenda-goto t)
5960 (recenter arg)
5961 (select-window win)))
5962
5963 (defun org-agenda-show-mouse (ev)
5964 "Display the Org-mode file which contains the item at the mouse click."
5965 (interactive "e")
5966 (mouse-set-point ev)
5967 (org-agenda-show))
5968
5969 (defun org-agenda-check-no-diary ()
5970 "Check if the entry is a diary link and abort if yes."
5971 (if (get-text-property (point) 'org-agenda-diary-link)
5972 (org-agenda-error)))
5973
5974 (defun org-agenda-error ()
5975 (error "Command not allowed in this line"))
5976
5977 (defvar org-last-heading-marker (make-marker)
5978 "Marker pointing to the headline that last changed its TODO state
5979 by a remote command from the agenda.")
5980
5981 (defun org-agenda-todo (&optional arg)
5982 "Cycle TODO state of line at point, also in Org-mode file.
5983 This changes the line at point, all other lines in the agenda referring to
5984 the same tree node, and the headline of the tree node in the Org-mode file."
5985 (interactive "P")
5986 (org-agenda-check-no-diary)
5987 (let* ((col (current-column))
5988 (marker (or (get-text-property (point) 'org-marker)
5989 (org-agenda-error)))
5990 (buffer (marker-buffer marker))
5991 (pos (marker-position marker))
5992 (hdmarker (get-text-property (point) 'org-hd-marker))
5993 (buffer-read-only nil)
5994 newhead)
5995 (with-current-buffer buffer
5996 (widen)
5997 (goto-char pos)
5998 (org-show-hidden-entry)
5999 (save-excursion
6000 (and (outline-next-heading)
6001 (org-flag-heading nil))) ; show the next heading
6002 (org-todo arg)
6003 (forward-char 1)
6004 (setq newhead (org-get-heading))
6005 (save-excursion
6006 (org-back-to-heading)
6007 (move-marker org-last-heading-marker (point))))
6008 (beginning-of-line 1)
6009 (save-excursion
6010 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6011 (move-to-column col)))
6012
6013 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6014 "Change all lines in the agenda buffer which match hdmarker.
6015 The new content of the line will be NEWHEAD (as modified by
6016 `org-format-agenda-item'). HDMARKER is checked with
6017 `equal' against all `org-hd-marker' text properties in the file.
6018 If FIXFACE is non-nil, the face of each item is modified acording to
6019 the new TODO state."
6020 (let* (props m pl undone-face done-face finish new dotime cat)
6021 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6022 (save-excursion
6023 (goto-char (point-max))
6024 (beginning-of-line 1)
6025 (while (not finish)
6026 (setq finish (bobp))
6027 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6028 (equal m hdmarker))
6029 (setq props (text-properties-at (point))
6030 dotime (get-text-property (point) 'dotime)
6031 cat (get-text-property (point) 'category)
6032 new (org-format-agenda-item "x" newhead cat dotime 'noprefix)
6033 pl (get-text-property (point) 'prefix-length)
6034 undone-face (get-text-property (point) 'undone-face)
6035 done-face (get-text-property (point) 'done-face))
6036 (move-to-column pl)
6037 (if (looking-at ".*")
6038 (progn
6039 (replace-match new t t)
6040 (beginning-of-line 1)
6041 (add-text-properties (point-at-bol) (point-at-eol) props)
6042 (if fixface
6043 (add-text-properties
6044 (point-at-bol) (point-at-eol)
6045 (list 'face
6046 (if org-last-todo-state-is-todo
6047 undone-face done-face))))
6048 (beginning-of-line 1))
6049 (error "Line update did not work")))
6050 (beginning-of-line 0)))))
6051
6052 (defun org-agenda-priority-up ()
6053 "Increase the priority of line at point, also in Org-mode file."
6054 (interactive)
6055 (org-agenda-priority 'up))
6056
6057 (defun org-agenda-priority-down ()
6058 "Decrease the priority of line at point, also in Org-mode file."
6059 (interactive)
6060 (org-agenda-priority 'down))
6061
6062 (defun org-agenda-priority (&optional force-direction)
6063 "Set the priority of line at point, also in Org-mode file.
6064 This changes the line at point, all other lines in the agenda referring to
6065 the same tree node, and the headline of the tree node in the Org-mode file."
6066 (interactive)
6067 (org-agenda-check-no-diary)
6068 (let* ((marker (or (get-text-property (point) 'org-marker)
6069 (org-agenda-error)))
6070 (buffer (marker-buffer marker))
6071 (pos (marker-position marker))
6072 (hdmarker (get-text-property (point) 'org-hd-marker))
6073 (buffer-read-only nil)
6074 newhead)
6075 (with-current-buffer buffer
6076 (widen)
6077 (goto-char pos)
6078 (org-show-hidden-entry)
6079 (save-excursion
6080 (and (outline-next-heading)
6081 (org-flag-heading nil))) ; show the next heading
6082 (funcall 'org-priority force-direction)
6083 (end-of-line 1)
6084 (setq newhead (org-get-heading)))
6085 (org-agenda-change-all-lines newhead hdmarker)
6086 (beginning-of-line 1)))
6087
6088 (defun org-agenda-set-tags ()
6089 "Set tags for the current headline."
6090 (interactive)
6091 (org-agenda-check-no-diary)
6092 (let* ((marker (or (get-text-property (point) 'org-marker)
6093 (org-agenda-error)))
6094 (hdmarker (get-text-property (point) 'org-hd-marker))
6095 (buffer (marker-buffer hdmarker))
6096 (pos (marker-position hdmarker))
6097 (buffer-read-only nil)
6098 newhead)
6099 (with-current-buffer buffer
6100 (widen)
6101 (goto-char pos)
6102 (org-show-hidden-entry)
6103 (save-excursion
6104 (and (outline-next-heading)
6105 (org-flag-heading nil))) ; show the next heading
6106 (call-interactively 'org-set-tags)
6107 (end-of-line 1)
6108 (setq newhead (org-get-heading)))
6109 (org-agenda-change-all-lines newhead hdmarker)
6110 (beginning-of-line 1)))
6111
6112 (defun org-agenda-date-later (arg &optional what)
6113 "Change the date of this item to one day later."
6114 (interactive "p")
6115 (org-agenda-check-no-diary)
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 (with-current-buffer buffer
6121 (widen)
6122 (goto-char pos)
6123 (if (not (org-at-timestamp-p))
6124 (error "Cannot find time stamp"))
6125 (org-timestamp-change arg (or what 'day))
6126 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6127
6128 (defun org-agenda-date-earlier (arg &optional what)
6129 "Change the date of this item to one day earlier."
6130 (interactive "p")
6131 (org-agenda-date-later (- arg) what))
6132
6133 (defun org-agenda-date-prompt (arg)
6134 "Change the date of this item. Date is prompted for, with default today.
6135 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6136 be used to request time specification in the time stamp."
6137 (interactive "P")
6138 (org-agenda-check-no-diary)
6139 (let* ((marker (or (get-text-property (point) 'org-marker)
6140 (org-agenda-error)))
6141 (buffer (marker-buffer marker))
6142 (pos (marker-position marker)))
6143 (with-current-buffer buffer
6144 (widen)
6145 (goto-char pos)
6146 (if (not (org-at-timestamp-p))
6147 (error "Cannot find time stamp"))
6148 (org-time-stamp arg)
6149 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6150
6151 (defun org-get-heading ()
6152 "Return the heading of the current entry, without the stars."
6153 (save-excursion
6154 (and (bolp) (end-of-line 1))
6155 (if (and (re-search-backward "[\r\n]\\*" nil t)
6156 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
6157 (match-string 1)
6158 "")))
6159
6160 (defun org-agenda-diary-entry ()
6161 "Make a diary entry, like the `i' command from the calendar.
6162 All the standard commands work: block, weekly etc"
6163 (interactive)
6164 (require 'diary-lib)
6165 (let* ((char (progn
6166 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6167 (read-char-exclusive)))
6168 (cmd (cdr (assoc char
6169 '((?d . insert-diary-entry)
6170 (?w . insert-weekly-diary-entry)
6171 (?m . insert-monthly-diary-entry)
6172 (?y . insert-yearly-diary-entry)
6173 (?a . insert-anniversary-diary-entry)
6174 (?b . insert-block-diary-entry)
6175 (?c . insert-cyclic-diary-entry)))))
6176 (oldf (symbol-function 'calendar-cursor-to-date))
6177 (point (point))
6178 (mark (or (mark t) (point))))
6179 (unless cmd
6180 (error "No command associated with <%c>" char))
6181 (unless (and (get-text-property point 'day)
6182 (or (not (equal ?b char))
6183 (get-text-property mark 'day)))
6184 (error "Don't know which date to use for diary entry"))
6185 ;; We implement this by hacking the `calendar-cursor-to-date' function
6186 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6187 (let ((calendar-mark-ring
6188 (list (calendar-gregorian-from-absolute
6189 (or (get-text-property mark 'day)
6190 (get-text-property point 'day))))))
6191 (unwind-protect
6192 (progn
6193 (fset 'calendar-cursor-to-date
6194 (lambda (&optional error)
6195 (calendar-gregorian-from-absolute
6196 (get-text-property point 'day))))
6197 (call-interactively cmd))
6198 (fset 'calendar-cursor-to-date oldf)))))
6199
6200
6201 (defun org-agenda-execute-calendar-command (cmd)
6202 "Execute a calendar command from the agenda, with the date associated to
6203 the cursor position."
6204 (require 'diary-lib)
6205 (unless (get-text-property (point) 'day)
6206 (error "Don't know which date to use for calendar command"))
6207 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6208 (point (point))
6209 (date (calendar-gregorian-from-absolute
6210 (get-text-property point 'day)))
6211 (displayed-day (extract-calendar-day date))
6212 (displayed-month (extract-calendar-month date))
6213 (displayed-year (extract-calendar-year date)))
6214 (unwind-protect
6215 (progn
6216 (fset 'calendar-cursor-to-date
6217 (lambda (&optional error)
6218 (calendar-gregorian-from-absolute
6219 (get-text-property point 'day))))
6220 (call-interactively cmd))
6221 (fset 'calendar-cursor-to-date oldf))))
6222
6223 (defun org-agenda-phases-of-moon ()
6224 "Display the phases of the moon for the 3 months around the cursor date."
6225 (interactive)
6226 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6227
6228 (defun org-agenda-holidays ()
6229 "Display the holidays for the 3 months around the cursor date."
6230 (interactive)
6231 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6232
6233 (defun org-agenda-sunrise-sunset (arg)
6234 "Display sunrise and sunset for the cursor date.
6235 Latitude and longitude can be specified with the variables
6236 `calendar-latitude' and `calendar-longitude'. When called with prefix
6237 argument, latitude and longitude will be prompted for."
6238 (interactive "P")
6239 (let ((calendar-longitude (if arg nil calendar-longitude))
6240 (calendar-latitude (if arg nil calendar-latitude))
6241 (calendar-location-name
6242 (if arg "the given coordinates" calendar-location-name)))
6243 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6244
6245 (defun org-agenda-goto-calendar ()
6246 "Open the Emacs calendar with the date at the cursor."
6247 (interactive)
6248 (let* ((day (or (get-text-property (point) 'day)
6249 (error "Don't know which date to open in calendar")))
6250 (date (calendar-gregorian-from-absolute day))
6251 (calendar-move-hook nil)
6252 (view-diary-entries-initially nil))
6253 (calendar)
6254 (calendar-goto-date date)))
6255
6256 (defun org-calendar-goto-agenda ()
6257 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6258 This is a command that has to be installed in `calendar-mode-map'."
6259 (interactive)
6260 (org-agenda-list nil (calendar-absolute-from-gregorian
6261 (calendar-cursor-to-date))
6262 nil t))
6263
6264 (defun org-agenda-convert-date ()
6265 (interactive)
6266 (let ((day (get-text-property (point) 'day))
6267 date s)
6268 (unless day
6269 (error "Don't know which date to convert"))
6270 (setq date (calendar-gregorian-from-absolute day))
6271 (setq s (concat
6272 "Gregorian: " (calendar-date-string date) "\n"
6273 "ISO: " (calendar-iso-date-string date) "\n"
6274 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6275 "Julian: " (calendar-julian-date-string date) "\n"
6276 "Astron. JD: " (calendar-astro-date-string date)
6277 " (Julian date number at noon UTC)\n"
6278 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6279 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6280 "French: " (calendar-french-date-string date) "\n"
6281 "Mayan: " (calendar-mayan-date-string date) "\n"
6282 "Coptic: " (calendar-coptic-date-string date) "\n"
6283 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6284 "Persian: " (calendar-persian-date-string date) "\n"
6285 "Chinese: " (calendar-chinese-date-string date) "\n"))
6286 (with-output-to-temp-buffer "*Dates*"
6287 (princ s))
6288 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
6289
6290 ;;; Tags
6291
6292 (defun org-scan-tags (action matcher &optional todo-only)
6293 "Scan headline tags with inheritance and produce output ACTION.
6294 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6295 evaluated, testing if a given set of tags qualifies a headline for
6296 inclusion. When TODO-ONLY is non-nil, only lines with a TDOD keyword
6297 d are included in the output."
6298 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6299 (mapconcat 'regexp-quote
6300 (nreverse (cdr (reverse org-todo-keywords)))
6301 "\\|")
6302 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_:]+:\\)?[ \t]*[\n\r]"))
6303 (props (list 'face nil
6304 'done-face 'org-done
6305 'undone-face nil
6306 'mouse-face 'highlight
6307 'keymap org-agenda-keymap
6308 'help-echo
6309 (format "mouse-2 or RET jump to org file %s"
6310 (abbreviate-file-name (buffer-file-name)))))
6311 tags tags-list tags-alist (llast 0) rtn level category i txt
6312 todo marker)
6313
6314 (save-excursion
6315 (goto-char (point-min))
6316 (when (eq action 'sparse-tree) (hide-sublevels 1))
6317 (while (re-search-forward re nil t)
6318 (setq todo (if (match-end 1) (match-string 2))
6319 tags (if (match-end 4) (match-string 4)))
6320 (goto-char (1+ (match-beginning 0)))
6321 (setq level (outline-level)
6322 category (org-get-category))
6323 (setq i llast llast level)
6324 ;; remove tag lists from same and sublevels
6325 (while (>= i level)
6326 (when (setq entry (assoc i tags-alist))
6327 (setq tags-alist (delete entry tags-alist)))
6328 (setq i (1- i)))
6329 ;; add the nex tags
6330 (when tags
6331 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6332 tags-alist
6333 (cons (cons level tags) tags-alist)))
6334 ;; compile tags for current headline
6335 (setq tags-list
6336 (if org-use-tag-inheritance
6337 (apply 'append (mapcar 'cdr tags-alist))
6338 tags))
6339 (when (and (or (not todo-only) todo)
6340 (eval matcher))
6341 ;; list this headline
6342 (if (eq action 'sparse-tree)
6343 (progn
6344 (org-show-hierarchy-above))
6345 (setq txt (org-format-agenda-item
6346 ""
6347 (concat
6348 (if org-tags-match-list-sublevels
6349 (make-string (1- level) ?.) "")
6350 (org-get-heading))
6351 category))
6352 (setq marker (org-agenda-new-marker))
6353 (add-text-properties
6354 0 (length txt)
6355 (append (list 'org-marker marker 'org-hd-marker marker
6356 'category category)
6357 props)
6358 txt)
6359 (push txt rtn))
6360 ;; if we are to skip sublevels, jump to end of subtree
6361 (or org-tags-match-list-sublevels (outline-end-of-subtree)))))
6362 (nreverse rtn)))
6363
6364 (defun org-tags-sparse-tree (&optional arg match)
6365 "Create a sparse tree according to tags search string MATCH.
6366 MATCH can contain positive and negative selection of tags, like
6367 \"+WORK+URGENT-WITHBOSS\"."
6368 (interactive "P")
6369 (let ((org-show-following-heading nil)
6370 (org-show-hierarchy-above nil))
6371 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6372
6373 (defun org-make-tags-matcher (match)
6374 "Create the TAGS matcher form for the tags-selecting string MATCH."
6375 (unless match
6376 ;; Get a new match request, with completion
6377 (setq org-last-tags-completion-table
6378 (or (org-get-buffer-tags)
6379 org-last-tags-completion-table))
6380 (setq match (completing-read
6381 "Tags: " 'org-tags-completion-function nil nil nil
6382 'org-tags-history)))
6383 ;; parse the string and create a lisp form
6384 (let ((match0 match) minus tag mm matcher orterms term orlist)
6385 (setq orterms (org-split-string match "|"))
6386 (while (setq term (pop orterms))
6387 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_]+\\)" term)
6388 (setq minus (and (match-end 1)
6389 (equal (match-string 1 term) "-"))
6390 tag (match-string 2 term)
6391 term (substring term (match-end 0))
6392 mm (list 'member (downcase tag) 'tags-list)
6393 mm (if minus (list 'not mm) mm))
6394 (push mm matcher))
6395 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6396 orlist)
6397 (setq matcher nil))
6398 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6399 ;; Return the string and lisp forms of the matcher
6400 (cons match0 matcher)))
6401
6402 ;;(org-make-tags-matcher "&hello&-you")
6403
6404
6405 ;;;###autoload
6406 (defun org-tags-view (&optional todo-only match keep-modes)
6407 "Show all headlines for all `org-agenda-files' matching a TAGS criterions.
6408 The prefix arg TODO-ONLY limits the search to TODO entries."
6409 (interactive "P")
6410 (org-agenda-maybe-reset-markers 'force)
6411 (org-compile-prefix-format org-agenda-prefix-format)
6412 (let* ((org-agenda-keep-modes keep-modes)
6413 (win (selected-window))
6414 (completion-ignore-case t)
6415 rtn rtnall files file pos matcher
6416 buffer)
6417 (setq matcher (org-make-tags-matcher match)
6418 match (car matcher) matcher (cdr matcher))
6419 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6420 (progn
6421 (delete-other-windows)
6422 (switch-to-buffer-other-window
6423 (get-buffer-create org-agenda-buffer-name))))
6424 (setq buffer-read-only nil)
6425 (erase-buffer)
6426 (org-agenda-mode) (setq buffer-read-only nil)
6427 (set (make-local-variable 'org-agenda-redo-command)
6428 '(call-interactively 'org-tags-view))
6429 (setq files (org-agenda-files)
6430 rtnall nil)
6431 (while (setq file (pop files))
6432 (catch 'nextfile
6433 (org-check-agenda-file file)
6434 (setq buffer (if (file-exists-p file)
6435 (org-get-agenda-file-buffer file)
6436 (error "No such file %s" file)))
6437 (if (not buffer)
6438 ;; If file does not exist, merror message to agenda
6439 (setq rtn (list
6440 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6441 rtnall (append rtnall rtn))
6442 (with-current-buffer buffer
6443 (unless (eq major-mode 'org-mode)
6444 (error "Agenda file %s is not in `org-mode'" file))
6445 (save-excursion
6446 (save-restriction
6447 (if org-respect-restriction
6448 (if (org-region-active-p)
6449 ;; Respect a region to restrict search
6450 (narrow-to-region (region-beginning) (region-end)))
6451 ;; If we work for the calendar or many files,
6452 ;; get rid of any restriction
6453 (widen))
6454 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6455 (setq rtnall (append rtnall rtn))))))))
6456 (insert "Headlines with TAGS match: ")
6457 (add-text-properties (point-min) (1- (point))
6458 (list 'face 'org-link))
6459 (setq pos (point))
6460 (insert match "\n")
6461 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6462 (when rtnall
6463 (insert (mapconcat 'identity rtnall "\n")))
6464 (goto-char (point-min))
6465 (setq buffer-read-only t)
6466 (org-fit-agenda-window)
6467 (if (not org-select-agenda-window) (select-window win))))
6468
6469 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6470 (defun org-set-tags (&optional arg just-align)
6471 "Set the tags for the current headline.
6472 With prefix ARG, realign all tags in headings in the current buffer."
6473 (interactive)
6474 (let* (;(inherit (org-get-inherited-tags))
6475 (re (concat "^" outline-regexp))
6476 (col (current-column))
6477 (current (org-get-tags))
6478 tags hd)
6479 (if arg
6480 (save-excursion
6481 (goto-char (point-min))
6482 (while (re-search-forward re nil t)
6483 (org-set-tags nil t))
6484 (message "All tags realigned to column %d" org-tags-column))
6485 (if just-align
6486 (setq tags current)
6487 (setq org-last-tags-completion-table
6488 (or (org-get-buffer-tags)
6489 org-last-tags-completion-table))
6490 (setq tags
6491 (let ((org-add-colon-after-tag-completion t))
6492 (completing-read "Tags: " 'org-tags-completion-function
6493 nil nil current 'org-tags-history)))
6494 (while (string-match "[-+&]+" tags)
6495 (setq tags (replace-match ":" t t tags)))
6496 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6497 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
6498 (if (equal current "")
6499 (end-of-line 1)
6500 (beginning-of-line 1)
6501 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6502 (setq hd (match-string 1))
6503 (delete-region (match-beginning 0) (match-end 0))
6504 (insert (org-trim hd) " "))
6505 (unless (equal tags "")
6506 (move-to-column (max (current-column)
6507 (if (> org-tags-column 0)
6508 org-tags-column
6509 (- (- org-tags-column) (length tags))))
6510 t)
6511 (insert tags))
6512 (move-to-column col))))
6513
6514 (defun org-tags-completion-function (string predicate &optional flag)
6515 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6516 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6517 (setq s1 (match-string 1 string)
6518 s2 (match-string 2 string))
6519 (setq s1 "" s2 string))
6520 (cond
6521 ((eq flag nil)
6522 ;; try completion
6523 (setq rtn (try-completion s2 ctable))
6524 (if (stringp rtn)
6525 (concat s1 s2 (substring rtn (length s2))
6526 (if (and org-add-colon-after-tag-completion
6527 (assoc rtn ctable))
6528 ":" "")))
6529 )
6530 ((eq flag t)
6531 ;; all-completions
6532 (all-completions s2 ctable)
6533 )
6534 ((eq flag 'lambda)
6535 ;; exact match?
6536 (assoc s2 ctable)))
6537 ))
6538
6539 (defun org-get-tags ()
6540 "Get the TAGS string in the current headline."
6541 (unless (org-on-heading-p)
6542 (error "Not on a heading"))
6543 (save-excursion
6544 (beginning-of-line 1)
6545 (if (looking-at ".*[ \t]\\(:[A-Za-z_:]+:\\)[ \t]*\\(\r\\|$\\)")
6546 (match-string 1)
6547 "")))
6548
6549 (defun org-get-buffer-tags ()
6550 "Get a table of all tags used in the buffer, for completion."
6551 (let (tags)
6552 (save-excursion
6553 (goto-char (point-min))
6554 (while (re-search-forward "[ \t]:\\([A-Za-z_:]+\\):[ \t\r\n]" nil t)
6555 (mapc (lambda (x) (add-to-list 'tags x))
6556 (org-split-string (match-string-no-properties 1) ":"))))
6557 (mapcar 'list tags)))
6558
6559 ;;; Link Stuff
6560
6561 (defun org-find-file-at-mouse (ev)
6562 "Open file link or URL at mouse."
6563 (interactive "e")
6564 (mouse-set-point ev)
6565 (org-open-at-point 'in-emacs))
6566
6567 (defun org-open-at-mouse (ev)
6568 "Open file link or URL at mouse."
6569 (interactive "e")
6570 (mouse-set-point ev)
6571 (org-open-at-point))
6572
6573 (defun org-open-at-point (&optional in-emacs)
6574 "Open link at or after point.
6575 If there is no link at point, this function will search forward up to
6576 the end of the current subtree.
6577 Normally, files will be opened by an appropriate application. If the
6578 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6579 (interactive "P")
6580 (org-remove-occur-highlights nil nil t)
6581 (if (org-at-timestamp-p)
6582 (org-agenda-list nil (time-to-days (org-time-string-to-time
6583 (substring (match-string 1) 0 10)))
6584 1)
6585 (let (type path line search (pos (point)))
6586 (catch 'match
6587 (save-excursion
6588 (skip-chars-backward
6589 (concat (if org-allow-space-in-links "^" "^ ")
6590 org-non-link-chars))
6591 (when (looking-at org-link-regexp)
6592 (setq type (match-string 1)
6593 path (match-string 2))
6594 (throw 'match t)))
6595 (save-excursion
6596 (skip-chars-backward "^ \t\n\r")
6597 (when (looking-at "\\(:[A-Za-z_:]+\\):[ \t\r\n]")
6598 (setq type "tags"
6599 path (match-string 1))
6600 (while (string-match ":" path)
6601 (setq path (replace-match "+" t t path)))
6602 (throw 'match t)))
6603 (save-excursion
6604 (skip-chars-backward "a-zA-Z_")
6605 (when (looking-at org-camel-regexp)
6606 (setq type "camel" path (match-string 0))
6607 (if (equal (char-before) ?*)
6608 (setq path (concat "*" path))))
6609 (throw 'match t))
6610 (save-excursion
6611 (when (re-search-forward
6612 org-link-regexp
6613 (save-excursion
6614 (condition-case nil
6615 (progn (outline-end-of-subtree) (max pos (point)))
6616 (error (end-of-line 1) (point))))
6617 t)
6618 (setq type (match-string 1)
6619 path (match-string 2)))))
6620 (unless path
6621 (error "No link found"))
6622 ;; Remove any trailing spaces in path
6623 (if (string-match " +\\'" path)
6624 (setq path (replace-match "" t t path)))
6625
6626 (cond
6627
6628 ((string= type "tags")
6629 (org-tags-view path in-emacs))
6630 ((string= type "camel")
6631 (org-link-search
6632 path
6633 (cond ((equal in-emacs '(4)) 'occur)
6634 ((equal in-emacs '(16)) 'org-occur)
6635 (t nil))))
6636
6637 ((string= type "file")
6638 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6639 (setq line (string-to-number (match-string 1 path))
6640 path (substring path 0 (match-beginning 0)))
6641 (if (string-match "::\\(.+\\)\\'" path)
6642 (setq search (match-string 1 path)
6643 path (substring path 0 (match-beginning 0)))))
6644 (org-open-file path in-emacs line search))
6645
6646 ((string= type "news")
6647 (org-follow-gnus-link path))
6648
6649 ((string= type "bbdb")
6650 (org-follow-bbdb-link path))
6651
6652 ((string= type "gnus")
6653 (let (group article)
6654 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6655 (error "Error in Gnus link"))
6656 (setq group (match-string 1 path)
6657 article (match-string 3 path))
6658 (org-follow-gnus-link group article)))
6659
6660 ((string= type "vm")
6661 (let (folder article)
6662 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6663 (error "Error in VM link"))
6664 (setq folder (match-string 1 path)
6665 article (match-string 3 path))
6666 ;; in-emacs is the prefix arg, will be interpreted as read-only
6667 (org-follow-vm-link folder article in-emacs)))
6668
6669 ((string= type "wl")
6670 (let (folder article)
6671 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6672 (error "Error in Wanderlust link"))
6673 (setq folder (match-string 1 path)
6674 article (match-string 3 path))
6675 (org-follow-wl-link folder article)))
6676
6677 ((string= type "rmail")
6678 (let (folder article)
6679 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6680 (error "Error in RMAIL link"))
6681 (setq folder (match-string 1 path)
6682 article (match-string 3 path))
6683 (org-follow-rmail-link folder article)))
6684
6685 ((string= type "shell")
6686 (let ((cmd path))
6687 (while (string-match "@{" cmd)
6688 (setq cmd (replace-match "<" t t cmd)))
6689 (while (string-match "@}" cmd)
6690 (setq cmd (replace-match ">" t t cmd)))
6691 (if (or (not org-confirm-shell-links)
6692 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6693 (shell-command cmd)
6694 (error "Abort"))))
6695
6696 (t
6697 (browse-url-at-point))))))
6698
6699 (defun org-link-search (s &optional type)
6700 "Search for a link search option.
6701 When S is a CamelCaseWord, search for a target, or for a sentence containing
6702 the words. If S is surrounded by forward slashes, it is interpreted as a
6703 regular expression. In org-mode files, this will create an `org-occur'
6704 sparse tree. In ordinary files, `occur' will be used to list matched.
6705 If the current buffer is in `dired-mode', grep will be used to search
6706 in all files."
6707 (let ((case-fold-search t)
6708 (s0 s)
6709 (pos (point))
6710 (pre "") (post "")
6711 words re0 re1 re2 re3 re4 re5 reall)
6712 (cond ((string-match "^/\\(.*\\)/$" s)
6713 ;; A regular expression
6714 (cond
6715 ((eq major-mode 'org-mode)
6716 (org-occur (match-string 1 s)))
6717 ;;((eq major-mode 'dired-mode)
6718 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6719 (t (org-do-occur (match-string 1 s)))))
6720 ((string-match (concat "^" org-camel-regexp) s)
6721 ;; A camel
6722 (if (equal (string-to-char s) ?*)
6723 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6724 post "[ \t]*$"
6725 s (substring s 1)))
6726 (remove-text-properties
6727 0 (length s)
6728 '(face nil mouse-face nil keymap nil fontified nil) s)
6729 ;; Make a series of regular expressions to find a match
6730 (setq words (org-camel-to-words s)
6731 re0 (concat "<<" (regexp-quote s0) ">>")
6732 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6733 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6734 re1 (concat pre re2 post)
6735 re3 (concat pre re4 post)
6736 re5 (concat pre ".*" re4)
6737 re2 (concat pre re2)
6738 re4 (concat pre re4)
6739 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6740 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6741 re5 "\\)"
6742 ))
6743 (cond
6744 ((eq type 'org-occur) (org-occur reall))
6745 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6746 (t (goto-char (point-min))
6747 (if (or (re-search-forward re0 nil t)
6748 (re-search-forward re1 nil t)
6749 (re-search-forward re2 nil t)
6750 (re-search-forward re3 nil t)
6751 (re-search-forward re4 nil t)
6752 (re-search-forward re5 nil t))
6753 (goto-char (match-beginning 0))
6754 (goto-char pos)
6755 (error "No match")))))
6756 (t
6757 ;; Normal string-search
6758 (goto-char (point-min))
6759 (if (search-forward s nil t)
6760 (goto-char (match-beginning 0))
6761 (error "No match"))))))
6762
6763 (defun org-do-occur (regexp &optional cleanup)
6764 "Call the Emacs command `occur'.
6765 If CLEANUP is non-nil, remove the printout of the regular expression
6766 in the *Occur* buffer. This is useful if the regex is long and not useful
6767 to read."
6768 (occur regexp)
6769 (when cleanup
6770 (let ((cwin (selected-window)) win beg end)
6771 (when (setq win (get-buffer-window "*Occur*"))
6772 (select-window win))
6773 (goto-char (point-min))
6774 (when (re-search-forward "match[a-z]+" nil t)
6775 (setq beg (match-end 0))
6776 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6777 (setq end (1- (match-beginning 0)))))
6778 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
6779 (goto-char (point-min))
6780 (select-window cwin))))
6781
6782 (defun org-camel-to-words (s)
6783 "Split \"CamelCaseWords\" to (\"Camel \" \"Case\" \"Words\")."
6784 (let ((case-fold-search nil)
6785 words)
6786 (while (string-match "[a-z][A-Z]" s)
6787 (push (substring s 0 (1+ (match-beginning 0))) words)
6788 (setq s (substring s (1+ (match-beginning 0)))))
6789 (nreverse (cons s words))))
6790
6791 (defun org-follow-bbdb-link (name)
6792 "Follow a BBDB link to NAME."
6793 (require 'bbdb)
6794 (let ((inhibit-redisplay t))
6795 (catch 'exit
6796 ;; Exact match on name
6797 (bbdb-name (concat "\\`" name "\\'") nil)
6798 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6799 ;; Exact match on name
6800 (bbdb-company (concat "\\`" name "\\'") nil)
6801 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6802 ;; Partial match on name
6803 (bbdb-name name nil)
6804 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6805 ;; Partial match on company
6806 (bbdb-company name nil)
6807 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6808 ;; General match including network address and notes
6809 (bbdb name nil)
6810 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
6811 (delete-window (get-buffer-window "*BBDB*"))
6812 (error "No matching BBDB record")))))
6813
6814 (defun org-follow-gnus-link (&optional group article)
6815 "Follow a Gnus link to GROUP and ARTICLE."
6816 (require 'gnus)
6817 (funcall (cdr (assq 'gnus org-link-frame-setup)))
6818 (if group (gnus-fetch-group group))
6819 (if article
6820 (or (gnus-summary-goto-article article nil 'force)
6821 (if (fboundp 'gnus-summary-insert-cached-articles)
6822 (progn
6823 (gnus-summary-insert-cached-articles)
6824 (gnus-summary-goto-article article nil 'force))
6825 (message "Message could not be found.")))))
6826
6827 (defun org-follow-vm-link (&optional folder article readonly)
6828 "Follow a VM link to FOLDER and ARTICLE."
6829 (require 'vm)
6830 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
6831 ;; ange-ftp or efs or tramp access
6832 (let ((user (or (match-string 1 folder) (user-login-name)))
6833 (host (match-string 2 folder))
6834 (file (match-string 3 folder)))
6835 (cond
6836 ((featurep 'tramp)
6837 ;; use tramp to access the file
6838 (if org-xemacs-p
6839 (setq folder (format "[%s@%s]%s" user host file))
6840 (setq folder (format "/%s@%s:%s" user host file))))
6841 (t
6842 ;; use ange-ftp or efs
6843 (require (if org-xemacs-p 'efs 'ange-ftp))
6844 (setq folder (format "/%s@%s:%s" user host file))))))
6845 (when folder
6846 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
6847 (sit-for 0.1)
6848 (when article
6849 (vm-select-folder-buffer)
6850 (widen)
6851 (let ((case-fold-search t))
6852 (goto-char (point-min))
6853 (if (not (re-search-forward
6854 (concat "^" "message-id: *" (regexp-quote article))))
6855 (error "Could not find the specified message in this folder"))
6856 (vm-isearch-update)
6857 (vm-isearch-narrow)
6858 (vm-beginning-of-message)
6859 (vm-summarize)))))
6860
6861 (defun org-follow-wl-link (folder article)
6862 "Follow a Wanderlust link to FOLDER and ARTICLE."
6863 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
6864 (if article (wl-summary-jump-to-msg-by-message-id article))
6865 (wl-summary-redisplay))
6866
6867 (defun org-follow-rmail-link (folder article)
6868 "Follow an RMAIL link to FOLDER and ARTICLE."
6869 (let (message-number)
6870 (save-excursion
6871 (save-window-excursion
6872 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6873 (setq message-number
6874 (save-restriction
6875 (widen)
6876 (goto-char (point-max))
6877 (if (re-search-backward
6878 (concat "^Message-ID:\\s-+" (regexp-quote
6879 (or article "")))
6880 nil t)
6881 (rmail-what-message))))))
6882 (if message-number
6883 (progn
6884 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6885 (rmail-show-message message-number)
6886 message-number)
6887 (error "Message not found"))))
6888
6889 (defun org-open-file (path &optional in-emacs line search)
6890 "Open the file at PATH.
6891 First, this expands any special file name abbreviations. Then the
6892 configuration variable `org-file-apps' is checked if it contains an
6893 entry for this file type, and if yes, the corresponding command is launched.
6894 If no application is found, Emacs simply visits the file.
6895 With optional argument IN-EMACS, Emacs will visit the file.
6896 Optional LINE specifies a line to go to, optional SEARCH a string to
6897 search for. If LINE or SEARCH is given, the file will always be
6898 openen in emacs.
6899 If the file does not exist, an error is thrown."
6900 (setq in-emacs (or in-emacs line search))
6901 (let* ((file (if (equal path "")
6902 (buffer-file-name)
6903 (convert-standard-filename (org-expand-file-name path))))
6904 (dfile (downcase file))
6905 ext cmd apps)
6906 (if (and (not (file-exists-p file))
6907 (not org-open-non-existing-files))
6908 (error "No such file: %s" file))
6909 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
6910 (setq ext (match-string 1 dfile))
6911 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
6912 (setq ext (match-string 1 dfile))))
6913 (setq apps (append org-file-apps (org-default-apps)))
6914 (if in-emacs
6915 (setq cmd 'emacs)
6916 (setq cmd (or (cdr (assoc ext apps))
6917 (cdr (assoc t apps)))))
6918 (cond
6919 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
6920 (setq cmd (format cmd (concat "\"" file "\"")))
6921 (save-window-excursion
6922 (shell-command (concat cmd " & &"))))
6923 ((or (stringp cmd)
6924 (eq cmd 'emacs))
6925 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
6926 (funcall (cdr (assq 'file org-link-frame-setup)) file))
6927 (if line (goto-line line)
6928 (if search (org-link-search search))))
6929 ((consp cmd)
6930 (eval cmd))
6931 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
6932
6933 (defun org-default-apps ()
6934 "Return the default applications for this operating system."
6935 (cond
6936 ((eq system-type 'darwin)
6937 org-file-apps-defaults-macosx)
6938 ((eq system-type 'windows-nt)
6939 org-file-apps-defaults-windowsnt)
6940 (t org-file-apps-defaults-gnu)))
6941
6942 (defun org-expand-file-name (path)
6943 "Replace special path abbreviations and expand the file name."
6944 (expand-file-name path))
6945
6946
6947 (defvar org-insert-link-history nil
6948 "Minibuffer history for links inserted with `org-insert-link'.")
6949
6950 (defvar org-stored-links nil
6951 "Contains the links stored with `org-store-link'.")
6952
6953 ;;;###autoload
6954 (defun org-store-link (arg)
6955 "\\<org-mode-map>Store an org-link to the current location.
6956 This link can later be inserted into an org-buffer with
6957 \\[org-insert-link].
6958 For some link types, a prefix arg is interpreted:
6959 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6960 For file links, arg negates `org-context-in-file-links'."
6961 (interactive "P")
6962 (let (link cpltxt)
6963 (cond
6964
6965 ((eq major-mode 'bbdb-mode)
6966 (setq cpltxt (concat
6967 "bbdb:"
6968 (or (bbdb-record-name (bbdb-current-record))
6969 (bbdb-record-company (bbdb-current-record))))
6970 link (org-make-link cpltxt)))
6971
6972 ((eq major-mode 'calendar-mode)
6973 (let ((cd (calendar-cursor-to-date)))
6974 (setq link
6975 (format-time-string
6976 (car org-time-stamp-formats)
6977 (apply 'encode-time
6978 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6979 nil nil nil))))))
6980
6981 ((or (eq major-mode 'vm-summary-mode)
6982 (eq major-mode 'vm-presentation-mode))
6983 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
6984 (vm-follow-summary-cursor)
6985 (save-excursion
6986 (vm-select-folder-buffer)
6987 (let* ((message (car vm-message-pointer))
6988 (folder (buffer-file-name))
6989 (subject (vm-su-subject message))
6990 (author (vm-su-full-name message))
6991 (message-id (vm-su-message-id message)))
6992 (setq folder (abbreviate-file-name folder))
6993 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
6994 folder)
6995 (setq folder (replace-match "" t t folder)))
6996 (setq cpltxt (concat author " on: " subject))
6997 (setq link (concat cpltxt "\n "
6998 (org-make-link
6999 "vm:" folder "#" message-id))))))
7000
7001 ((eq major-mode 'wl-summary-mode)
7002 (let* ((msgnum (wl-summary-message-number))
7003 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7004 msgnum 'message-id))
7005 (wl-message-entity (elmo-msgdb-overview-get-entity
7006 msgnum (wl-summary-buffer-msgdb)))
7007 (author (wl-summary-line-from)) ; FIXME: how to get author name?
7008 (subject "???")) ; FIXME: How to get subject of email?
7009 (setq cpltxt (concat author " on: " subject))
7010 (setq link (concat cpltxt "\n "
7011 (org-make-link
7012 "wl:" wl-summary-buffer-folder-name
7013 "#" message-id)))))
7014
7015 ((eq major-mode 'rmail-mode)
7016 (save-excursion
7017 (save-restriction
7018 (rmail-narrow-to-non-pruned-header)
7019 (let ((folder (buffer-file-name))
7020 (message-id (mail-fetch-field "message-id"))
7021 (author (mail-fetch-field "from"))
7022 (subject (mail-fetch-field "subject")))
7023 (setq cpltxt (concat author " on: " subject))
7024 (setq link (concat cpltxt "\n "
7025 (org-make-link
7026 "rmail:" folder "#" message-id)))))))
7027
7028 ((eq major-mode 'gnus-group-mode)
7029 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7030 (gnus-group-group-name)) ; version
7031 ((fboundp 'gnus-group-name)
7032 (gnus-group-name))
7033 (t "???"))))
7034 (setq cpltxt (concat
7035 (if (org-xor arg org-usenet-links-prefer-google)
7036 "http://groups.google.com/groups?group="
7037 "gnus:")
7038 group)
7039 link (org-make-link cpltxt))))
7040
7041 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7042 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7043 (gnus-summary-beginning-of-article)
7044 (let* ((group (car gnus-article-current))
7045 (article (cdr gnus-article-current))
7046 (header (gnus-summary-article-header article))
7047 (author (mail-header-from header))
7048 (message-id (mail-header-id header))
7049 (date (mail-header-date header))
7050 (subject (gnus-summary-subject-string)))
7051 (setq cpltxt (concat author " on: " subject))
7052 (if (org-xor arg org-usenet-links-prefer-google)
7053 (setq link
7054 (concat
7055 cpltxt "\n "
7056 (format "http://groups.google.com/groups?as_umsgid=%s"
7057 (org-fixup-message-id-for-http message-id))))
7058 (setq link (concat cpltxt "\n"
7059 (org-make-link
7060 "gnus:" group
7061 "#" (number-to-string article)))))))
7062
7063 ((eq major-mode 'w3-mode)
7064 (setq cpltxt (url-view-url t)
7065 link (org-make-link cpltxt)))
7066 ((eq major-mode 'w3m-mode)
7067 (setq cpltxt w3m-current-url
7068 link (org-make-link cpltxt)))
7069
7070 ((eq major-mode 'org-mode)
7071 ;; Just link to current headline
7072 (setq cpltxt (concat "file:"
7073 (abbreviate-file-name (buffer-file-name))))
7074 ;; Add a context search string
7075 (when (org-xor org-context-in-file-links arg)
7076 (if (save-excursion
7077 (skip-chars-backward "a-zA-Z<")
7078 (looking-at (concat "<<\\(" org-camel-regexp "\\)>>")))
7079 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7080 (setq cpltxt
7081 (concat cpltxt "::"
7082 (org-make-org-heading-camel
7083 (cond
7084 ((org-on-heading-p) nil)
7085 ((org-region-active-p)
7086 (buffer-substring (region-beginning) (region-end)))
7087 (t (buffer-substring (point-at-bol) (point-at-eol))))
7088 )))))
7089 (setq link (org-make-link cpltxt)))
7090
7091 ((buffer-file-name)
7092 ;; Just link to this file here.
7093 (setq cpltxt (concat "file:"
7094 (abbreviate-file-name (buffer-file-name))))
7095 ;; Add a context string
7096 (when (org-xor org-context-in-file-links arg)
7097 (setq cpltxt
7098 (concat cpltxt "::"
7099 (org-make-org-heading-camel
7100 (if (org-region-active-p)
7101 (buffer-substring (region-beginning) (region-end))
7102 (buffer-substring (point-at-bol) (point-at-eol)))))))
7103 (setq link (org-make-link cpltxt)))
7104
7105 ((interactive-p)
7106 (error "Cannot link to a buffer which is not visiting a file"))
7107
7108 (t (setq link nil)))
7109
7110 (if (and (interactive-p) link)
7111 (progn
7112 (setq org-stored-links
7113 (cons (cons (or cpltxt link) link) org-stored-links))
7114 (message "Stored: %s" (or cpltxt link)))
7115 link)))
7116
7117 (defun org-make-org-heading-camel (&optional string)
7118 "Make a CamelCase string for S or the current headline."
7119 (interactive)
7120 (let ((s (or string (org-get-heading))))
7121 (unless string
7122 ;; We are using a headline, clean up garbage in there.
7123 (if (string-match org-todo-regexp s)
7124 (setq s (replace-match "" t t s)))
7125 (setq s (org-trim s))
7126 (if (string-match (concat "^\\(" org-quote-string "\\|"
7127 org-comment-string "\\)") s)
7128 (setq s (replace-match "" t t s)))
7129 (while (string-match org-ts-regexp s)
7130 (setq s (replace-match "" t t s))))
7131 (while (string-match "[^a-zA-Z_ \t]+" s)
7132 (setq s (replace-match " " t t s)))
7133 (or string (setq s (concat "*" s))) ; Add * for headlines
7134 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7135
7136 (defun org-make-link (&rest strings)
7137 "Concatenate STRINGS, format resulting string with `org-link-format'."
7138 (format org-link-format (apply 'concat strings)))
7139
7140 (defun org-xor (a b)
7141 "Exclusive or."
7142 (if a (not b) b))
7143
7144 (defun org-get-header (header)
7145 "Find a header field in the current buffer."
7146 (save-excursion
7147 (goto-char (point-min))
7148 (let ((case-fold-search t) s)
7149 (cond
7150 ((eq header 'from)
7151 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7152 (setq s (match-string 1)))
7153 (while (string-match "\"" s)
7154 (setq s (replace-match "" t t s)))
7155 (if (string-match "[<(].*" s)
7156 (setq s (replace-match "" t t s))))
7157 ((eq header 'message-id)
7158 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7159 (setq s (match-string 1))))
7160 ((eq header 'subject)
7161 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7162 (setq s (match-string 1)))))
7163 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7164 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7165 s)))
7166
7167
7168 (defun org-fixup-message-id-for-http (s)
7169 "Replace special characters in a message id, so it can be used in an http query."
7170 (while (string-match "<" s)
7171 (setq s (replace-match "%3C" t t s)))
7172 (while (string-match ">" s)
7173 (setq s (replace-match "%3E" t t s)))
7174 (while (string-match "@" s)
7175 (setq s (replace-match "%40" t t s)))
7176 s)
7177
7178 (defun org-insert-link (&optional complete-file)
7179 "Insert a link. At the prompt, enter the link.
7180
7181 Completion can be used to select a link previously stored with
7182 `org-store-link'. When the empty string is entered (i.e. if you just
7183 press RET at the prompt), the link defaults to the most recently
7184 stored link. As SPC triggers completion in the minibuffer, you need to
7185 use M-SPC or C-q SPC to force the insertion of a space character.
7186
7187 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7188 selected using completion. The path to the file will be relative to
7189 the current directory if the file is in the current directory or a
7190 subdirectory. Otherwise, the link will be the absolute path as
7191 completed in the minibuffer (i.e. normally ~/path/to/file).
7192
7193 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7194 is in the current directory or below."
7195 (interactive "P")
7196 (let ((link (if complete-file
7197 (read-file-name "File: ")
7198 (completing-read
7199 "Link: " org-stored-links nil nil nil
7200 org-insert-link-history
7201 (or (car (car org-stored-links))))))
7202 linktxt matched)
7203 (if (or (not link) (equal link ""))
7204 (error "No links available"))
7205 (if complete-file
7206 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7207 (cond
7208 ((equal complete-file '(16))
7209 (insert
7210 (org-make-link
7211 "file:" (abbreviate-file-name (expand-file-name link)))))
7212 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7213 (expand-file-name link))
7214 (insert
7215 (org-make-link
7216 "file:" (match-string 1 (expand-file-name link)))))
7217 (t (insert (org-make-link "file:" link)))))
7218 (setq linktxt (cdr (assoc link org-stored-links)))
7219 (if (not org-keep-stored-link-after-insertion)
7220 (setq org-stored-links (delq (assoc link org-stored-links)
7221 org-stored-links)))
7222 (if (not linktxt) (setq link (org-make-link link)))
7223 (setq link (or linktxt link))
7224 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7225 (let* ((path (match-string 1 link))
7226 (case-fold-search nil)
7227 (search (match-string 2 link)))
7228 (when (save-match-data
7229 (equal (file-truename (buffer-file-name))
7230 (file-truename path)))
7231 (if (save-match-data
7232 (string-match (concat "^" org-camel-regexp "$") search))
7233 (setq link (replace-match search t t link)
7234 matched t)
7235 (setq link (replace-match (concat "<file:::" search ">")
7236 t t link))))))
7237 (let ((lines (org-split-string link "\n")))
7238 (insert (car lines))
7239 (setq matched (or matched (string-match org-link-regexp (car lines))))
7240 (setq lines (cdr lines))
7241 (while lines
7242 (insert "\n")
7243 (if (save-excursion
7244 (beginning-of-line 0)
7245 (looking-at "[ \t]+\\S-"))
7246 (indent-relative))
7247 (setq matched (or matched
7248 (string-match org-link-regexp (car lines))))
7249 (insert (car lines))
7250 (setq lines (cdr lines))))
7251 (unless matched
7252 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7253
7254 ;;; Hooks for remember.el
7255 ;;;###autoload
7256 (defun org-remember-annotation ()
7257 "Return a link to the current location as an annotation for remember.el.
7258 If you are using Org-mode files as target for data storage with
7259 remember.el, then the annotations should include a link compatible with the
7260 conventions in Org-mode. This function returns such a link."
7261 (org-store-link nil))
7262
7263 (defconst org-remember-help
7264 "Select a destination location for the note.
7265 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7266 RET at beg-of-buf -> Append to file as level 2 headline
7267 RET on headline -> Store as sublevel entry to current headline
7268 <left>/<right> -> before/after current headline, same headings level")
7269
7270 ;;;###autoload
7271 (defun org-remember-handler ()
7272 "Store stuff from remember.el into an org file.
7273 First prompts for an org file. If the user just presses return, the value
7274 of `org-default-notes-file' is used.
7275 Then the command offers the headings tree of the selected file in order to
7276 file the text at a specific location.
7277 You can either immediately press RET to get the note appended to the
7278 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
7279 find a better place. Then press RET or <left> or <right> in insert the note.
7280
7281 Key Cursor position Note gets inserted
7282 -----------------------------------------------------------------------------
7283 RET buffer-start as level 2 heading at end of file
7284 RET on headline as sublevel of the heading at cursor
7285 RET no heading at cursor position, level taken from context.
7286 Or use prefix arg to specify level manually.
7287 <left> on headline as same level, before current heading
7288 <right> on headline as same level, after current heading
7289
7290 So the fastest way to store the note is to press RET RET to append it to
7291 the default file. This way your current train of thought is not
7292 interrupted, in accordance with the principles of remember.el. But with
7293 little extra effort, you can push it directly to the correct location.
7294
7295 Before being stored away, the function ensures that the text has a
7296 headline, i.e. a first line that starts with a \"*\". If not, a headline
7297 is constructed from the current date and some additional data.
7298
7299 If the variable `org-adapt-indentation' is non-nil, the entire text is
7300 also indented so that it starts in the same column as the headline
7301 \(i.e. after the stars).
7302
7303 See also the variable `org-reverse-note-order'."
7304 (catch 'quit
7305 (let* ((txt (buffer-substring (point-min) (point-max)))
7306 (fastp current-prefix-arg)
7307 (file (if fastp org-default-notes-file (org-get-org-file)))
7308 (visiting (find-buffer-visiting file))
7309 (org-startup-with-deadline-check nil)
7310 (org-startup-folded nil)
7311 spos level indent reversed)
7312 ;; Modify text so that it becomes a nice subtree which can be inserted
7313 ;; into an org tree.
7314 (let* ((lines (split-string txt "\n"))
7315 (first (car lines))
7316 (lines (cdr lines)))
7317 (if (string-match "^\\*+" first)
7318 ;; Is already a headline
7319 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7320 -1) ?\ ))
7321 ;; We need to add a headline: Use time and first buffer line
7322 (setq lines (cons first lines)
7323 first (concat "* " (current-time-string)
7324 " (" (remember-buffer-desc) ")")
7325 indent " "))
7326 (if org-adapt-indentation
7327 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7328 (setq txt (concat first "\n"
7329 (mapconcat 'identity lines "\n"))))
7330 ;; Find the file
7331 (if (not visiting)
7332 (find-file-noselect file))
7333 (with-current-buffer (get-file-buffer file)
7334 (setq reversed (org-notes-order-reversed-p))
7335 (save-excursion
7336 (save-restriction
7337 (widen)
7338 ;; Ask the User for a location
7339 (setq spos (if fastp 1 (org-get-location
7340 (current-buffer)
7341 org-remember-help)))
7342 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7343 ; not handle this note
7344 (goto-char spos)
7345 (cond ((bobp)
7346 ;; Put it at the start or end, as level 2
7347 (save-restriction
7348 (widen)
7349 (goto-char (if reversed (point-min) (point-max)))
7350 (if (not (bolp)) (newline))
7351 (org-paste-subtree (or current-prefix-arg 2) txt)))
7352 ((and (org-on-heading-p nil) (not current-prefix-arg))
7353 ;; Put it below this entry, at the beg/end of the subtree
7354 (org-back-to-heading)
7355 (setq level (outline-level))
7356 (if reversed
7357 (outline-end-of-heading)
7358 (outline-end-of-subtree))
7359 (if (not (bolp)) (newline))
7360 (beginning-of-line 1)
7361 (org-paste-subtree (1+ level) txt))
7362 (t
7363 ;; Put it right there, with automatic level determined by
7364 ;; org-paste-subtree or from prefix arg
7365 (org-paste-subtree current-prefix-arg txt)))
7366 (when remember-save-after-remembering
7367 (save-buffer)
7368 (if (not visiting) (kill-buffer (current-buffer)))))))))
7369 t) ;; return t to indicate that we took care of this note.
7370
7371 (defun org-get-org-file ()
7372 "Read a filename, with default directory `org-directory'."
7373 (let ((default (or org-default-notes-file remember-data-file)))
7374 (read-file-name (format "File name [%s]: " default)
7375 (file-name-as-directory org-directory)
7376 default)))
7377
7378 (defun org-notes-order-reversed-p ()
7379 "Check if the current file should receive notes in reversed order."
7380 (cond
7381 ((not org-reverse-note-order) nil)
7382 ((eq t org-reverse-note-order) t)
7383 ((not (listp org-reverse-note-order)) nil)
7384 (t (catch 'exit
7385 (let ((all org-reverse-note-order)
7386 entry)
7387 (while (setq entry (pop all))
7388 (if (string-match (car entry) (buffer-file-name))
7389 (throw 'exit (cdr entry))))
7390 nil)))))
7391
7392 ;;; Tables
7393
7394 ;; Watch out: Here we are talking about two different kind of tables.
7395 ;; Most of the code is for the tables created with the Org-mode table editor.
7396 ;; Sometimes, we talk about tables created and edited with the table.el
7397 ;; Emacs package. We call the former org-type tables, and the latter
7398 ;; table.el-type tables.
7399
7400
7401 (defun org-before-change-function (beg end)
7402 "Every change indicates that a table might need an update."
7403 (setq org-table-may-need-update t))
7404
7405 (defconst org-table-line-regexp "^[ \t]*|"
7406 "Detects an org-type table line.")
7407 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7408 "Detects an org-type table line.")
7409 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7410 "Detects a table line marked for automatic recalculation.")
7411 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7412 "Detects a table line marked for automatic recalculation.")
7413 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7414 "Detects a table line marked for automatic recalculation.")
7415 (defconst org-table-hline-regexp "^[ \t]*|-"
7416 "Detects an org-type table hline.")
7417 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7418 "Detects a table-type table hline.")
7419 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7420 "Detects an org-type or table-type table.")
7421 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7422 "Searching from within a table (any type) this finds the first line
7423 outside the table.")
7424 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7425 "Searching from within a table (any type) this finds the first line
7426 outside the table.")
7427
7428 (defun org-table-create-with-table.el ()
7429 "Use the table.el package to insert a new table.
7430 If there is already a table at point, convert between Org-mode tables
7431 and table.el tables."
7432 (interactive)
7433 (require 'table)
7434 (cond
7435 ((org-at-table.el-p)
7436 (if (y-or-n-p "Convert table to Org-mode table? ")
7437 (org-table-convert)))
7438 ((org-at-table-p)
7439 (if (y-or-n-p "Convert table to table.el table? ")
7440 (org-table-convert)))
7441 (t (call-interactively 'table-insert))))
7442
7443 (defun org-table-create (&optional size)
7444 "Query for a size and insert a table skeleton.
7445 SIZE is a string Columns x Rows like for example \"3x2\"."
7446 (interactive "P")
7447 (unless size
7448 (setq size (read-string
7449 (concat "Table size Columns x Rows [e.g. "
7450 org-table-default-size "]: ")
7451 "" nil org-table-default-size)))
7452
7453 (let* ((pos (point))
7454 (indent (make-string (current-column) ?\ ))
7455 (split (org-split-string size " *x *"))
7456 (rows (string-to-number (nth 1 split)))
7457 (columns (string-to-number (car split)))
7458 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7459 "\n")))
7460 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7461 (point-at-bol) (point)))
7462 (beginning-of-line 1)
7463 (newline))
7464 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7465 (dotimes (i rows) (insert line))
7466 (goto-char pos)
7467 (if (> rows 1)
7468 ;; Insert a hline after the first row.
7469 (progn
7470 (end-of-line 1)
7471 (insert "\n|-")
7472 (goto-char pos)))
7473 (org-table-align)))
7474
7475 (defun org-table-convert-region (beg0 end0 nspace)
7476 "Convert region to a table.
7477 The region goes from BEG0 to END0, but these borders will be moved
7478 slightly, to make sure a beginning of line in the first line is included.
7479 When NSPACE is non-nil, it indicates the minimum number of spaces that
7480 separate columns (default: just one space)"
7481 (let* ((beg (min beg0 end0))
7482 (end (max beg0 end0))
7483 (tabsep t)
7484 re)
7485 (goto-char beg)
7486 (beginning-of-line 1)
7487 (setq beg (move-marker (make-marker) (point)))
7488 (goto-char end)
7489 (if (bolp) (backward-char 1) (end-of-line 1))
7490 (setq end (move-marker (make-marker) (point)))
7491 ;; Lets see if this is tab-separated material. If every nonempty line
7492 ;; contains a tab, we will assume that it is tab-separated material
7493 (if nspace
7494 (setq tabsep nil)
7495 (goto-char beg)
7496 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7497 (if nspace (setq tabsep nil))
7498 (if tabsep
7499 (setq re "^\\|\t")
7500 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7501 (max 1 (prefix-numeric-value nspace)))))
7502 (goto-char beg)
7503 (while (re-search-forward re end t)
7504 (replace-match "|" t t))
7505 (goto-char beg)
7506 (insert " ")
7507 (org-table-align)))
7508
7509 (defun org-table-import (file arg)
7510 "Import FILE as a table.
7511 The file is assumed to be tab-separated. Such files can be produced by most
7512 spreadsheet and database applications. If no tabs (at least one per line)
7513 are found, lines will be split on whitespace into fields."
7514 (interactive "f\nP")
7515 (or (bolp) (newline))
7516 (let ((beg (point))
7517 (pm (point-max)))
7518 (insert-file-contents file)
7519 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7520
7521 (defun org-table-export ()
7522 "Export table as a tab-separated file.
7523 Such a file can be imported into a spreadsheet program like Excel."
7524 (interactive)
7525 (let* ((beg (org-table-begin))
7526 (end (org-table-end))
7527 (table (buffer-substring beg end))
7528 (file (read-file-name "Export table to: "))
7529 buf)
7530 (unless (or (not (file-exists-p file))
7531 (y-or-n-p (format "Overwrite file %s? " file)))
7532 (error "Abort"))
7533 (with-current-buffer (find-file-noselect file)
7534 (setq buf (current-buffer))
7535 (erase-buffer)
7536 (fundamental-mode)
7537 (insert table)
7538 (goto-char (point-min))
7539 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7540 (replace-match "" t t)
7541 (end-of-line 1))
7542 (goto-char (point-min))
7543 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7544 (replace-match "" t t)
7545 (goto-char (min (1+ (point)) (point-max))))
7546 (goto-char (point-min))
7547 (while (re-search-forward "^-[-+]*$" nil t)
7548 (replace-match "")
7549 (if (looking-at "\n")
7550 (delete-char 1)))
7551 (goto-char (point-min))
7552 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7553 (replace-match "\t" t t))
7554 (save-buffer))
7555 (kill-buffer buf)))
7556
7557 (defvar org-table-aligned-begin-marker (make-marker)
7558 "Marker at the beginning of the table last aligned.
7559 Used to check if cursor still is in that table, to minimize realignment.")
7560 (defvar org-table-aligned-end-marker (make-marker)
7561 "Marker at the end of the table last aligned.
7562 Used to check if cursor still is in that table, to minimize realignment.")
7563 (defvar org-table-last-alignment nil
7564 "List of flags for flushright alignment, from the last re-alignment.
7565 This is being used to correctly align a single field after TAB or RET.")
7566 ;; FIXME: The following is currently not used.
7567 (defvar org-table-last-column-widths nil
7568 "List of max width of fields in each column.
7569 This is being used to correctly align a single field after TAB or RET.")
7570
7571 (defvar org-last-recalc-line nil)
7572
7573 (defun org-table-align ()
7574 "Align the table at point by aligning all vertical bars."
7575 (interactive)
7576 ;; (message "align") (sit-for 2)
7577 (let* (
7578 ;; Limits of table
7579 (beg (org-table-begin))
7580 (end (org-table-end))
7581 ;; Current cursor position
7582 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7583 (colpos (org-table-current-column))
7584 (winstart (window-start))
7585 text lines (new "") lengths l typenums ty fields maxfields i
7586 column
7587 (indent "") cnt frac
7588 rfmt hfmt
7589 (spaces (if (org-in-invisibility-spec-p '(org-table))
7590 org-table-spaces-around-invisible-separators
7591 org-table-spaces-around-separators))
7592 (sp1 (car spaces))
7593 (sp2 (cdr spaces))
7594 (rfmt1 (concat
7595 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7596 (hfmt1 (concat
7597 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7598 emptystrings)
7599 (untabify beg end)
7600 ;; (message "Aligning table...")
7601 ;; Get the rows
7602 (setq lines (org-split-string
7603 (buffer-substring-no-properties beg end) "\n"))
7604 ;; Store the indentation of the first line
7605 (if (string-match "^ *" (car lines))
7606 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7607 ;; Mark the hlines
7608 (setq lines (mapcar (lambda (l)
7609 (if (string-match "^ *|-" l)
7610 nil
7611 (if (string-match "[ \t]+$" l)
7612 (substring l 0 (match-beginning 0))
7613 l)))
7614 lines))
7615 ;; Get the data fields
7616 (setq fields (mapcar
7617 (lambda (l)
7618 (org-split-string l " *| *"))
7619 (delq nil (copy-sequence lines))))
7620 ;; How many fields in the longest line?
7621 (condition-case nil
7622 (setq maxfields (apply 'max (mapcar 'length fields)))
7623 (error
7624 (kill-region beg end)
7625 (org-table-create org-table-default-size)
7626 (error "Empty table - created default table")))
7627 ;; A list of empty string to fill any short rows on output
7628 (setq emptystrings (make-list maxfields ""))
7629 ;; Get the maximum length of a field and the most common datatype
7630 ;; for each column
7631 (setq i -1)
7632 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7633 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7634 ;; maximum length
7635 (push (apply 'max 1 (mapcar 'length column)) lengths)
7636 ;; compute the fraction stepwise, ignoring empty fields
7637 (setq cnt 0 frac 0.0)
7638 (mapcar
7639 (lambda (x)
7640 (if (equal x "")
7641 nil
7642 (setq frac ( / (+ (* frac cnt)
7643 (if (string-match org-table-number-regexp x) 1 0))
7644 (setq cnt (1+ cnt))))))
7645 column)
7646 (push (>= frac org-table-number-fraction) typenums))
7647 (setq lengths (nreverse lengths)
7648 typenums (nreverse typenums))
7649 (setq org-table-last-alignment typenums
7650 org-table-last-column-widths lengths)
7651 ;; Compute the formats needed for output of the table
7652 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7653 (while (setq l (pop lengths))
7654 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7655 (setq rfmt (concat rfmt (format rfmt1 ty l))
7656 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7657 (setq rfmt (concat rfmt "\n")
7658 hfmt (concat (substring hfmt 0 -1) "|\n"))
7659 ;; Produce the new table
7660 ;;(while lines
7661 ;; (setq l (pop lines))
7662 ;; (if l
7663 ;; (setq new (concat new (apply 'format rfmt
7664 ;; (append (pop fields) emptystrings))))
7665 ;; (setq new (concat new hfmt))))
7666 (setq new (mapconcat
7667 (lambda (l)
7668 (if l (apply 'format rfmt
7669 (append (pop fields) emptystrings))
7670 hfmt))
7671 lines ""))
7672 ;; Replace the old one
7673 (delete-region beg end)
7674 (move-marker end nil)
7675 (move-marker org-table-aligned-begin-marker (point))
7676 (insert new)
7677 (move-marker org-table-aligned-end-marker (point))
7678 ;; Try to move to the old location (approximately)
7679 (goto-line linepos)
7680 (set-window-start (selected-window) winstart 'noforce)
7681 (org-table-goto-column colpos)
7682 (setq org-table-may-need-update nil)
7683 (if (org-in-invisibility-spec-p '(org-table))
7684 (org-table-add-invisible-to-vertical-lines))
7685 ))
7686
7687 (defun org-table-begin (&optional table-type)
7688 "Find the beginning of the table and return its position.
7689 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7690 (save-excursion
7691 (if (not (re-search-backward
7692 (if table-type org-table-any-border-regexp
7693 org-table-border-regexp)
7694 nil t))
7695 (error "Can't find beginning of table")
7696 (goto-char (match-beginning 0))
7697 (beginning-of-line 2)
7698 (point))))
7699
7700 (defun org-table-end (&optional table-type)
7701 "Find the end of the table and return its position.
7702 With argument TABLE-TYPE, go to the end of a table.el-type table."
7703 (save-excursion
7704 (if (not (re-search-forward
7705 (if table-type org-table-any-border-regexp
7706 org-table-border-regexp)
7707 nil t))
7708 (goto-char (point-max))
7709 (goto-char (match-beginning 0)))
7710 (point-marker)))
7711
7712 (defun org-table-justify-field-maybe (&optional new)
7713 "Justify the current field, text to left, number to right.
7714 Optional argument NEW may specify text to replace the current field content."
7715 (cond
7716 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7717 ((org-at-table-hline-p)
7718 ;; FIXME: I used to enforce realign here, but I think this is not needed.
7719 ;; (setq org-table-may-need-update t)
7720 )
7721 ((and (not new)
7722 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7723 (current-buffer)))
7724 (< (point) org-table-aligned-begin-marker)
7725 (>= (point) org-table-aligned-end-marker)))
7726 ;; This is not the same table, force a full re-align
7727 (setq org-table-may-need-update t))
7728 (t ;; realign the current field, based on previous full realign
7729 (let* ((pos (point)) s
7730 (col (org-table-current-column))
7731 (num (nth (1- col) org-table-last-alignment))
7732 l f n o e)
7733 (when (> col 0)
7734 (skip-chars-backward "^|\n")
7735 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7736 (progn
7737 (setq s (match-string 1)
7738 o (match-string 0)
7739 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7740 e (not (= (match-beginning 2) (match-end 2))))
7741 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7742 l (if e "|" (setq org-table-may-need-update t) ""))
7743 n (format f s t t))
7744 (if new
7745 (if (<= (length new) l)
7746 (setq n (format f new t t)) ;; FIXME: why t t?????
7747 (setq n (concat new "|") org-table-may-need-update t)))
7748 (or (equal n o)
7749 (let (org-table-may-need-update)
7750 (replace-match n))))
7751 (setq org-table-may-need-update t))
7752 (goto-char pos))))))
7753
7754 (defun org-table-next-field ()
7755 "Go to the next field in the current table, creating new lines as needed.
7756 Before doing so, re-align the table if necessary."
7757 (interactive)
7758 (org-table-maybe-eval-formula)
7759 (org-table-maybe-recalculate-line)
7760 (if (and org-table-automatic-realign
7761 org-table-may-need-update)
7762 (org-table-align))
7763 (let ((end (org-table-end)))
7764 (if (org-at-table-hline-p)
7765 (end-of-line 1))
7766 (condition-case nil
7767 (progn
7768 (re-search-forward "|" end)
7769 (if (looking-at "[ \t]*$")
7770 (re-search-forward "|" end))
7771 (if (and (looking-at "-")
7772 org-table-tab-jumps-over-hlines
7773 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7774 (goto-char (match-beginning 1)))
7775 (if (looking-at "-")
7776 (progn
7777 (beginning-of-line 0)
7778 (org-table-insert-row 'below))
7779 (if (looking-at " ") (forward-char 1))))
7780 (error
7781 (org-table-insert-row 'below)))))
7782
7783 (defun org-table-previous-field ()
7784 "Go to the previous field in the table.
7785 Before doing so, re-align the table if necessary."
7786 (interactive)
7787 (org-table-justify-field-maybe)
7788 (org-table-maybe-recalculate-line)
7789 (if (and org-table-automatic-realign
7790 org-table-may-need-update)
7791 (org-table-align))
7792 (if (org-at-table-hline-p)
7793 (end-of-line 1))
7794 (re-search-backward "|" (org-table-begin))
7795 (re-search-backward "|" (org-table-begin))
7796 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7797 (re-search-backward "|" (org-table-begin)))
7798 (if (looking-at "| ?")
7799 (goto-char (match-end 0))))
7800
7801 (defun org-table-next-row ()
7802 "Go to the next row (same column) in the current table.
7803 Before doing so, re-align the table if necessary."
7804 (interactive)
7805 (org-table-maybe-eval-formula)
7806 (org-table-maybe-recalculate-line)
7807 (if (or (looking-at "[ \t]*$")
7808 (save-excursion (skip-chars-backward " \t") (bolp)))
7809 (newline)
7810 (if (and org-table-automatic-realign
7811 org-table-may-need-update)
7812 (org-table-align))
7813 (let ((col (org-table-current-column)))
7814 (beginning-of-line 2)
7815 (if (or (not (org-at-table-p))
7816 (org-at-table-hline-p))
7817 (progn
7818 (beginning-of-line 0)
7819 (org-table-insert-row 'below)))
7820 (org-table-goto-column col)
7821 (skip-chars-backward "^|\n\r")
7822 (if (looking-at " ") (forward-char 1)))))
7823
7824 (defun org-table-copy-down (n)
7825 "Copy a field down in the current column.
7826 If the field at the cursor is empty, copy into it the content of the nearest
7827 non-empty field above. With argument N, use the Nth non-empty field.
7828 If the current field is not empty, it is copied down to the next row, and
7829 the cursor is moved with it. Therefore, repeating this command causes the
7830 column to be filled row-by-row.
7831 If the variable `org-table-copy-increment' is non-nil and the field is an
7832 integer, it will be incremented while copying."
7833 (interactive "p")
7834 (let* ((colpos (org-table-current-column))
7835 (field (org-table-get-field))
7836 (non-empty (string-match "[^ \t]" field))
7837 (beg (org-table-begin))
7838 txt)
7839 (org-table-check-inside-data-field)
7840 (if non-empty
7841 (progn
7842 (setq txt (org-trim field))
7843 (org-table-next-row)
7844 (org-table-blank-field))
7845 (save-excursion
7846 (setq txt
7847 (catch 'exit
7848 (while (progn (beginning-of-line 1)
7849 (re-search-backward org-table-dataline-regexp
7850 beg t))
7851 (org-table-goto-column colpos t)
7852 (if (and (looking-at
7853 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7854 (= (setq n (1- n)) 0))
7855 (throw 'exit (match-string 1))))))))
7856 (if txt
7857 (progn
7858 (if (and org-table-copy-increment
7859 (string-match "^[0-9]+$" txt))
7860 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7861 (insert txt)
7862 (org-table-maybe-recalculate-line)
7863 (org-table-align))
7864 (error "No non-empty field found"))))
7865
7866 (defun org-table-check-inside-data-field ()
7867 "Is point inside a table data field?
7868 I.e. not on a hline or before the first or after the last column?
7869 This actually throws an error, so it aborts the current command."
7870 (if (or (not (org-at-table-p))
7871 (= (org-table-current-column) 0)
7872 (org-at-table-hline-p)
7873 (looking-at "[ \t]*$"))
7874 (error "Not in table data field")))
7875
7876 (defvar org-table-clip nil
7877 "Clipboard for table regions.")
7878
7879 (defun org-table-blank-field ()
7880 "Blank the current table field or active region."
7881 (interactive)
7882 (org-table-check-inside-data-field)
7883 (if (and (interactive-p) (org-region-active-p))
7884 (let (org-table-clip)
7885 (org-table-cut-region (region-beginning) (region-end)))
7886 (skip-chars-backward "^|")
7887 (backward-char 1)
7888 (if (looking-at "|[^|\n]+")
7889 (let* ((pos (match-beginning 0))
7890 (match (match-string 0))
7891 (len (length match)))
7892 (replace-match (concat "|" (make-string (1- len) ?\ )))
7893 (goto-char (+ 2 pos))
7894 (substring match 1)))))
7895
7896 (defun org-table-get-field (&optional n replace)
7897 "Return the value of the field in column N of current row.
7898 N defaults to current field.
7899 If REPLACE is a string, replace field with this value. The return value
7900 is always the old value."
7901 (and n (org-table-goto-column n))
7902 (skip-chars-backward "^|\n")
7903 (backward-char 1)
7904 (if (looking-at "|[^|\r\n]*")
7905 (let* ((pos (match-beginning 0))
7906 (val (buffer-substring (1+ pos) (match-end 0))))
7907 (if replace
7908 (replace-match (concat "|" replace)))
7909 (goto-char (min (point-at-eol) (+ 2 pos)))
7910 val)
7911 (forward-char 1) ""))
7912
7913 (defun org-table-current-column ()
7914 "Find out which column we are in.
7915 When called interactively, column is also displayed in echo area."
7916 (interactive)
7917 (if (interactive-p) (org-table-check-inside-data-field))
7918 (save-excursion
7919 (let ((cnt 0) (pos (point)))
7920 (beginning-of-line 1)
7921 (while (search-forward "|" pos t)
7922 (setq cnt (1+ cnt)))
7923 (if (interactive-p) (message "This is table column %d" cnt))
7924 cnt)))
7925
7926 (defun org-table-goto-column (n &optional on-delim force)
7927 "Move the cursor to the Nth column in the current table line.
7928 With optional argument ON-DELIM, stop with point before the left delimiter
7929 of the field.
7930 If there are less than N fields, just go to after the last delimiter.
7931 However, when FORCE is non-nil, create new columns if necessary."
7932 (interactive "p")
7933 (let ((pos (point-at-eol)))
7934 (beginning-of-line 1)
7935 (when (> n 0)
7936 (while (and (> (setq n (1- n)) -1)
7937 (or (search-forward "|" pos t)
7938 (and force
7939 (progn (end-of-line 1)
7940 (skip-chars-backward "^|")
7941 (insert " | "))))))
7942 ; (backward-char 2) t)))))
7943 (when (and force (not (looking-at ".*|")))
7944 (save-excursion (end-of-line 1) (insert " | ")))
7945 (if on-delim
7946 (backward-char 1)
7947 (if (looking-at " ") (forward-char 1))))))
7948
7949 (defun org-at-table-p (&optional table-type)
7950 "Return t if the cursor is inside an org-type table.
7951 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7952 (if org-enable-table-editor
7953 (save-excursion
7954 (beginning-of-line 1)
7955 (looking-at (if table-type org-table-any-line-regexp
7956 org-table-line-regexp)))
7957 nil))
7958
7959 (defun org-at-table.el-p ()
7960 "Return t if and only if we are at a table.el table."
7961 (and (org-at-table-p 'any)
7962 (save-excursion
7963 (goto-char (org-table-begin 'any))
7964 (looking-at org-table1-hline-regexp))))
7965
7966 (defun org-table-recognize-table.el ()
7967 "If there is a table.el table nearby, recognize it and move into it."
7968 (if org-table-tab-recognizes-table.el
7969 (if (org-at-table.el-p)
7970 (progn
7971 (beginning-of-line 1)
7972 (if (looking-at org-table-dataline-regexp)
7973 nil
7974 (if (looking-at org-table1-hline-regexp)
7975 (progn
7976 (beginning-of-line 2)
7977 (if (looking-at org-table-any-border-regexp)
7978 (beginning-of-line -1)))))
7979 (if (re-search-forward "|" (org-table-end t) t)
7980 (progn
7981 (require 'table)
7982 (if (table--at-cell-p (point))
7983 t
7984 (message "recognizing table.el table...")
7985 (table-recognize-table)
7986 (message "recognizing table.el table...done")))
7987 (error "This should not happen..."))
7988 t)
7989 nil)
7990 nil))
7991
7992 (defun org-at-table-hline-p ()
7993 "Return t if the cursor is inside a hline in a table."
7994 (if org-enable-table-editor
7995 (save-excursion
7996 (beginning-of-line 1)
7997 (looking-at org-table-hline-regexp))
7998 nil))
7999
8000 (defun org-table-insert-column ()
8001 "Insert a new column into the table."
8002 (interactive)
8003 (if (not (org-at-table-p))
8004 (error "Not at a table"))
8005 (org-table-find-dataline)
8006 (let* ((col (max 1 (org-table-current-column)))
8007 (beg (org-table-begin))
8008 (end (org-table-end))
8009 ;; Current cursor position
8010 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8011 (colpos col))
8012 (goto-char beg)
8013 (while (< (point) end)
8014 (if (org-at-table-hline-p)
8015 nil
8016 (org-table-goto-column col t)
8017 (insert "| "))
8018 (beginning-of-line 2))
8019 (move-marker end nil)
8020 (goto-line linepos)
8021 (org-table-goto-column colpos)
8022 (org-table-align)
8023 (org-table-modify-formulas 'insert col)))
8024
8025 (defun org-table-find-dataline ()
8026 "Find a dataline in the current table, which is needed for column commands."
8027 (if (and (org-at-table-p)
8028 (not (org-at-table-hline-p)))
8029 t
8030 (let ((col (current-column))
8031 (end (org-table-end)))
8032 (move-to-column col)
8033 (while (and (< (point) end)
8034 (or (not (= (current-column) col))
8035 (org-at-table-hline-p)))
8036 (beginning-of-line 2)
8037 (move-to-column col))
8038 (if (and (org-at-table-p)
8039 (not (org-at-table-hline-p)))
8040 t
8041 (error
8042 "Please position cursor in a data line for column operations")))))
8043
8044 (defun org-table-delete-column ()
8045 "Delete a column into the table."
8046 (interactive)
8047 (if (not (org-at-table-p))
8048 (error "Not at a table"))
8049 (org-table-find-dataline)
8050 (org-table-check-inside-data-field)
8051 (let* ((col (org-table-current-column))
8052 (beg (org-table-begin))
8053 (end (org-table-end))
8054 ;; Current cursor position
8055 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8056 (colpos col))
8057 (goto-char beg)
8058 (while (< (point) end)
8059 (if (org-at-table-hline-p)
8060 nil
8061 (org-table-goto-column col t)
8062 (and (looking-at "|[^|\n]+|")
8063 (replace-match "|")))
8064 (beginning-of-line 2))
8065 (move-marker end nil)
8066 (goto-line linepos)
8067 (org-table-goto-column colpos)
8068 (org-table-align)
8069 (org-table-modify-formulas 'remove col)))
8070
8071 (defun org-table-move-column-right ()
8072 "Move column to the right."
8073 (interactive)
8074 (org-table-move-column nil))
8075 (defun org-table-move-column-left ()
8076 "Move column to the left."
8077 (interactive)
8078 (org-table-move-column 'left))
8079
8080 (defun org-table-move-column (&optional left)
8081 "Move the current column to the right. With arg LEFT, move to the left."
8082 (interactive "P")
8083 (if (not (org-at-table-p))
8084 (error "Not at a table"))
8085 (org-table-find-dataline)
8086 (org-table-check-inside-data-field)
8087 (let* ((col (org-table-current-column))
8088 (col1 (if left (1- col) col))
8089 (beg (org-table-begin))
8090 (end (org-table-end))
8091 ;; Current cursor position
8092 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8093 (colpos (if left (1- col) (1+ col))))
8094 (if (and left (= col 1))
8095 (error "Cannot move column further left"))
8096 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8097 (error "Cannot move column further right"))
8098 (goto-char beg)
8099 (while (< (point) end)
8100 (if (org-at-table-hline-p)
8101 nil
8102 (org-table-goto-column col1 t)
8103 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8104 (replace-match "|\\2|\\1|")))
8105 (beginning-of-line 2))
8106 (move-marker end nil)
8107 (goto-line linepos)
8108 (org-table-goto-column colpos)
8109 (org-table-align)
8110 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8111
8112 (defun org-table-move-row-down ()
8113 "move table row down."
8114 (interactive)
8115 (org-table-move-row nil))
8116 (defun org-table-move-row-up ()
8117 "move table row up."
8118 (interactive)
8119 (org-table-move-row 'up))
8120
8121 (defun org-table-move-row (&optional up)
8122 "Move the current table line down. With arg UP, move it up."
8123 (interactive "P")
8124 (let ((col (current-column))
8125 (pos (point))
8126 (tonew (if up 0 2))
8127 txt)
8128 (beginning-of-line tonew)
8129 (if (not (org-at-table-p))
8130 (progn
8131 (goto-char pos)
8132 (error "Cannot move row further")))
8133 (goto-char pos)
8134 (beginning-of-line 1)
8135 (setq pos (point))
8136 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8137 (delete-region (point) (1+ (point-at-eol)))
8138 (beginning-of-line tonew)
8139 (insert txt)
8140 (beginning-of-line 0)
8141 (move-to-column col)))
8142
8143 (defun org-table-insert-row (&optional arg)
8144 "Insert a new row above the current line into the table.
8145 With prefix ARG, insert below the current line."
8146 (interactive "P")
8147 (if (not (org-at-table-p))
8148 (error "Not at a table"))
8149 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
8150 new)
8151 (if (string-match "^[ \t]*|-" line)
8152 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8153 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8154 ;; Fix the first field if necessary
8155 (setq new (concat new))
8156 (if (string-match "^[ \t]*| *[#$] *|" line)
8157 (setq new (replace-match (match-string 0 line) t t new)))
8158 (beginning-of-line (if arg 2 1))
8159 (let (org-table-may-need-update)
8160 (insert-before-markers new)
8161 (insert-before-markers "\n"))
8162 (beginning-of-line 0)
8163 (re-search-forward "| ?" (point-at-eol) t)
8164 (and org-table-may-need-update (org-table-align))))
8165
8166 (defun org-table-insert-hline (&optional arg)
8167 "Insert a horizontal-line below the current line into the table.
8168 With prefix ARG, insert above the current line."
8169 (interactive "P")
8170 (if (not (org-at-table-p))
8171 (error "Not at a table"))
8172 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
8173 (col (current-column))
8174 start)
8175 (if (string-match "^[ \t]*|-" line)
8176 (setq line
8177 (mapcar (lambda (x) (if (member x '(?| ?+))
8178 (prog1 (if start ?+ ?|) (setq start t))
8179 (if start ?- ?\ )))
8180 line))
8181 (setq line
8182 (mapcar (lambda (x) (if (equal x ?|)
8183 (prog1 (if start ?+ ?|) (setq start t))
8184 (if start ?- ?\ )))
8185 line)))
8186 (beginning-of-line (if arg 1 2))
8187 (apply 'insert line)
8188 (if (equal (char-before (point)) ?+)
8189 (progn (backward-delete-char 1) (insert "|")))
8190 (insert "\n")
8191 (beginning-of-line 0)
8192 (move-to-column col)))
8193
8194 (defun org-table-kill-row ()
8195 "Delete the current row or horizontal line from the table."
8196 (interactive)
8197 (if (not (org-at-table-p))
8198 (error "Not at a table"))
8199 (let ((col (current-column)))
8200 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8201 (if (not (org-at-table-p)) (beginning-of-line 0))
8202 (move-to-column col)))
8203
8204 (defun org-table-sort-lines (beg end numericp)
8205 "Sort table lines in region.
8206 Point and mark define the first and last line to include. Both point and
8207 mark should be in the column that is used for sorting. For example, to
8208 sort according to column 3, put the mark in the first line to sort, in
8209 table column 3. Put point into the last line to be included in the sorting,
8210 also in table column 3. The command will prompt for the sorting method (n for
8211 numerical, a for alphanumeric)."
8212 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8213 (setq numericp (string-match "[nN]" numericp))
8214 (org-table-align) ;; Just to be safe
8215 (let* (bcol ecol cmp column lns)
8216 (goto-char beg)
8217 (org-table-check-inside-data-field)
8218 (setq column (org-table-current-column)
8219 beg (move-marker (make-marker) (point-at-bol)))
8220 (goto-char end)
8221 (org-table-check-inside-data-field)
8222 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8223 (untabify beg end)
8224 (goto-char beg)
8225 (org-table-goto-column column)
8226 (skip-chars-backward "^|")
8227 (setq bcol (current-column))
8228 (org-table-goto-column (1+ column))
8229 (skip-chars-backward "^|")
8230 (setq ecol (1- (current-column)))
8231 (setq cmp (if numericp
8232 (lambda (a b) (< (car a) (car b)))
8233 (lambda (a b) (string< (car a) (car b)))))
8234 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8235 (split-string (buffer-substring beg end) "\n")))
8236 (if numericp
8237 (setq lns (mapcar (lambda(x)
8238 (cons (string-to-number (car x)) (cdr x)))
8239 lns)))
8240 (delete-region beg end)
8241 (move-marker beg nil)
8242 (move-marker end nil)
8243 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8244 (message "%d lines sorted %s based on column %d"
8245 (length lns)
8246 (if numericp "numerically" "alphabetically") column)))
8247
8248 (defun org-table-cut-region (beg end)
8249 "Copy region in table to the clipboard and blank all relevant fields."
8250 (interactive "r")
8251 (org-table-copy-region beg end 'cut))
8252
8253 (defun org-table-copy-region (beg end &optional cut)
8254 "Copy rectangular region in table to clipboard.
8255 A special clipboard is used which can only be accessed
8256 with `org-table-paste-rectangle'"
8257 (interactive "rP")
8258 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8259 region cols
8260 (rpl (if cut " " nil)))
8261 (goto-char beg)
8262 (org-table-check-inside-data-field)
8263 (setq l01 (count-lines (point-min) (point))
8264 c01 (org-table-current-column))
8265 (goto-char end)
8266 (org-table-check-inside-data-field)
8267 (setq l02 (count-lines (point-min) (point))
8268 c02 (org-table-current-column))
8269 (setq l1 (min l01 l02) l2 (max l01 l02)
8270 c1 (min c01 c02) c2 (max c01 c02))
8271 (catch 'exit
8272 (while t
8273 (catch 'nextline
8274 (if (> l1 l2) (throw 'exit t))
8275 (goto-line l1)
8276 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8277 (setq cols nil ic1 c1 ic2 c2)
8278 (while (< ic1 (1+ ic2))
8279 (push (org-table-get-field ic1 rpl) cols)
8280 (setq ic1 (1+ ic1)))
8281 (push (nreverse cols) region)
8282 (setq l1 (1+ l1)))))
8283 (setq org-table-clip (nreverse region))
8284 (if cut (org-table-align))
8285 org-table-clip))
8286
8287 (defun org-table-paste-rectangle ()
8288 "Paste a rectangular region into a table.
8289 The upper right corner ends up in the current field. All involved fields
8290 will be overwritten. If the rectangle does not fit into the present table,
8291 the table is enlarged as needed. The process ignores horizontal separator
8292 lines."
8293 (interactive)
8294 (unless (and org-table-clip (listp org-table-clip))
8295 (error "First cut/copy a region to paste!"))
8296 (org-table-check-inside-data-field)
8297 (let* ((clip org-table-clip)
8298 (line (count-lines (point-min) (point)))
8299 (col (org-table-current-column))
8300 (org-enable-table-editor t)
8301 (org-table-automatic-realign nil)
8302 c cols field)
8303 (while (setq cols (pop clip))
8304 (while (org-at-table-hline-p) (beginning-of-line 2))
8305 (if (not (org-at-table-p))
8306 (progn (end-of-line 0) (org-table-next-field)))
8307 (setq c col)
8308 (while (setq field (pop cols))
8309 (org-table-goto-column c nil 'force)
8310 (org-table-get-field nil field)
8311 (setq c (1+ c)))
8312 (beginning-of-line 2))
8313 (goto-line line)
8314 (org-table-goto-column col)
8315 (org-table-align)))
8316
8317 (defun org-table-convert ()
8318 "Convert from `org-mode' table to table.el and back.
8319 Obviously, this only works within limits. When an Org-mode table is
8320 converted to table.el, all horizontal separator lines get lost, because
8321 table.el uses these as cell boundaries and has no notion of horizontal lines.
8322 A table.el table can be converted to an Org-mode table only if it does not
8323 do row or column spanning. Multiline cells will become multiple cells.
8324 Beware, Org-mode does not test if the table can be successfully converted - it
8325 blindly applies a recipe that works for simple tables."
8326 (interactive)
8327 (require 'table)
8328 (if (org-at-table.el-p)
8329 ;; convert to Org-mode table
8330 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8331 (end (move-marker (make-marker) (org-table-end t))))
8332 (table-unrecognize-region beg end)
8333 (goto-char beg)
8334 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8335 (replace-match ""))
8336 (goto-char beg))
8337 (if (org-at-table-p)
8338 ;; convert to table.el table
8339 (let ((beg (move-marker (make-marker) (org-table-begin)))
8340 (end (move-marker (make-marker) (org-table-end))))
8341 ;; first, get rid of all horizontal lines
8342 (goto-char beg)
8343 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8344 (replace-match ""))
8345 ;; insert a hline before first
8346 (goto-char beg)
8347 (org-table-insert-hline 'above)
8348 ;; insert a hline after each line
8349 (while (progn (beginning-of-line 2) (< (point) end))
8350 (org-table-insert-hline))
8351 (goto-char beg)
8352 (setq end (move-marker end (org-table-end)))
8353 ;; replace "+" at beginning and ending of hlines
8354 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8355 (replace-match "\\1+-"))
8356 (goto-char beg)
8357 (while (re-search-forward "-|[ \t]*$" end t)
8358 (replace-match "-+"))
8359 (goto-char beg)))))
8360
8361 (defun org-table-wrap-region (arg)
8362 "Wrap several fields in a column like a paragraph.
8363 This is useful if you'd like to spread the contents of a field over several
8364 lines, in order to keep the table compact.
8365
8366 If there is an active region, and both point and mark are in the same column,
8367 the text in the column is wrapped to minimum width for the given number of
8368 lines. Generally, this makes the table more compact. A prefix ARG may be
8369 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8370 formats the selected text to two lines. If the region was longer than 2
8371 lines, the remaining lines remain empty. A negative prefix argument reduces
8372 the current number of lines by that amount. The wrapped text is pasted back
8373 into the table. If you formatted it to more lines than it was before, fields
8374 further down in the table get overwritten - so you might need to make space in
8375 the table first.
8376
8377 If there is no region, the current field is split at the cursor position and
8378 the text fragment to the right of the cursor is prepended to the field one
8379 line down.
8380
8381 If there is no region, but you specify a prefix ARG, the current field gets
8382 blank, and the content is appended to the field above."
8383 (interactive "P")
8384 (org-table-check-inside-data-field)
8385 (if (org-region-active-p)
8386 ;; There is a region: fill as a paragraph
8387 (let ((beg (region-beginning))
8388 nlines)
8389 (org-table-cut-region (region-beginning) (region-end))
8390 (if (> (length (car org-table-clip)) 1)
8391 (error "Region must be limited to single column"))
8392 (setq nlines (if arg
8393 (if (< arg 1)
8394 (+ (length org-table-clip) arg)
8395 arg)
8396 (length org-table-clip)))
8397 (setq org-table-clip
8398 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8399 nil nlines)))
8400 (goto-char beg)
8401 (org-table-paste-rectangle))
8402 ;; No region, split the current field at point
8403 (if arg
8404 ;; combine with field above
8405 (let ((s (org-table-blank-field))
8406 (col (org-table-current-column)))
8407 (beginning-of-line 0)
8408 (while (org-at-table-hline-p) (beginning-of-line 0))
8409 (org-table-goto-column col)
8410 (skip-chars-forward "^|")
8411 (skip-chars-backward " ")
8412 (insert " " (org-trim s))
8413 (org-table-align))
8414 ;; split field
8415 (when (looking-at "\\([^|]+\\)+|")
8416 (let ((s (match-string 1)))
8417 (replace-match " |")
8418 (goto-char (match-beginning 0))
8419 (org-table-next-row)
8420 (insert (org-trim s) " ")
8421 (org-table-align))))))
8422
8423 (defun org-trim (s)
8424 "Remove whitespace at beginning and end of string."
8425 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8426 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8427 s)
8428
8429 (defun org-wrap (string &optional width lines)
8430 "Wrap string to either a number of lines, or a width in characters.
8431 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8432 that costs. If there is a word longer than WIDTH, the text is actually
8433 wrapped to the length of that word.
8434 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8435 many lines, whatever width that takes.
8436 The return value is a list of lines, without newlines at the end."
8437 (let* ((words (org-split-string string "[ \t\n]+"))
8438 (maxword (apply 'max (mapcar 'length words)))
8439 w ll)
8440 (cond (width
8441 (org-do-wrap words (max maxword width)))
8442 (lines
8443 (setq w maxword)
8444 (setq ll (org-do-wrap words maxword))
8445 (if (<= (length ll) lines)
8446 ll
8447 (setq ll words)
8448 (while (> (length ll) lines)
8449 (setq w (1+ w))
8450 (setq ll (org-do-wrap words w)))
8451 ll))
8452 (t (error "Cannot wrap this")))))
8453
8454
8455 (defun org-do-wrap (words width)
8456 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8457 (let (lines line)
8458 (while words
8459 (setq line (pop words))
8460 (while (and words (< (+ (length line) (length (car words))) width))
8461 (setq line (concat line " " (pop words))))
8462 (setq lines (push line lines)))
8463 (nreverse lines)))
8464
8465 ;; FIXME: I think I can make this more efficient
8466 (defun org-split-string (string &optional separators)
8467 "Splits STRING into substrings at SEPARATORS.
8468 No empty strings are returned if there are matches at the beginning
8469 and end of string."
8470 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8471 (start 0)
8472 notfirst
8473 (list nil))
8474 (while (and (string-match rexp string
8475 (if (and notfirst
8476 (= start (match-beginning 0))
8477 (< start (length string)))
8478 (1+ start) start))
8479 (< (match-beginning 0) (length string)))
8480 (setq notfirst t)
8481 (or (eq (match-beginning 0) 0)
8482 (and (eq (match-beginning 0) (match-end 0))
8483 (eq (match-beginning 0) start))
8484 (setq list
8485 (cons (substring string start (match-beginning 0))
8486 list)))
8487 (setq start (match-end 0)))
8488 (or (eq start (length string))
8489 (setq list
8490 (cons (substring string start)
8491 list)))
8492 (nreverse list)))
8493
8494 (defun org-table-add-invisible-to-vertical-lines ()
8495 "Add an `invisible' property to vertical lines of current table."
8496 (interactive)
8497 (let* ((beg (org-table-begin))
8498 (end (org-table-end))
8499 (end1))
8500 (save-excursion
8501 (goto-char beg)
8502 (while (< (point) end)
8503 (setq end1 (point-at-eol))
8504 (if (looking-at org-table-dataline-regexp)
8505 (while (re-search-forward "|" end1 t)
8506 (add-text-properties (1- (point)) (point)
8507 '(invisible org-table)))
8508 (while (re-search-forward "[+|]" end1 t)
8509 (add-text-properties (1- (point)) (point)
8510 '(invisible org-table))))
8511 (beginning-of-line 2)))))
8512
8513 (defun org-table-toggle-vline-visibility (&optional arg)
8514 "Toggle the visibility of table vertical lines.
8515 The effect is immediate and on all tables in the file.
8516 With prefix ARG, make lines invisible when ARG is positive, make lines
8517 visible when ARG is not positive"
8518 (interactive "P")
8519 (let ((action (cond
8520 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
8521 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
8522 (t (if (org-in-invisibility-spec-p '(org-table))
8523 'off
8524 'on)))))
8525 (if (eq action 'off)
8526 (progn
8527 (org-remove-from-invisibility-spec '(org-table))
8528 (org-table-map-tables 'org-table-align)
8529 (message "Vertical table lines visible")
8530 (if (org-at-table-p)
8531 (org-table-align)))
8532 (org-add-to-invisibility-spec '(org-table))
8533 (org-table-map-tables 'org-table-align)
8534 (message "Vertical table lines invisible"))
8535 (redraw-frame (selected-frame))))
8536
8537 (defun org-table-map-tables (function)
8538 "Apply FUNCTION to the start of all tables in the buffer."
8539 (save-excursion
8540 (save-restriction
8541 (widen)
8542 (goto-char (point-min))
8543 (while (re-search-forward org-table-any-line-regexp nil t)
8544 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8545 (beginning-of-line 1)
8546 (if (looking-at org-table-line-regexp)
8547 (save-excursion (funcall function)))
8548 (re-search-forward org-table-any-border-regexp nil 1)))))
8549
8550 (defun org-table-sum (&optional beg end nlast)
8551 "Sum numbers in region of current table column.
8552 The result will be displayed in the echo area, and will be available
8553 as kill to be inserted with \\[yank].
8554
8555 If there is an active region, it is interpreted as a rectangle and all
8556 numbers in that rectangle will be summed. If there is no active
8557 region and point is located in a table column, sum all numbers in that
8558 column.
8559
8560 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8561 numbers are assumed to be times as well (in decimal hours) and the
8562 numbers are added as such.
8563
8564 If NLAST is a number, only the NLAST fields will actually be summed."
8565 (interactive)
8566 (save-excursion
8567 (let (col (timecnt 0) diff h m s org-table-clip)
8568 (cond
8569 ((and beg end)) ; beg and end given explicitly
8570 ((org-region-active-p)
8571 (setq beg (region-beginning) end (region-end)))
8572 (t
8573 (setq col (org-table-current-column))
8574 (goto-char (org-table-begin))
8575 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8576 (error "No table data"))
8577 (org-table-goto-column col)
8578 ;not needed? (skip-chars-backward "^|")
8579 (setq beg (point))
8580 (goto-char (org-table-end))
8581 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8582 (error "No table data"))
8583 (org-table-goto-column col)
8584 ;not needed? (skip-chars-forward "^|")
8585 (setq end (point))))
8586 (let* ((items (apply 'append (org-table-copy-region beg end)))
8587 (items1 (cond ((not nlast) items)
8588 ((>= nlast (length items)) items)
8589 (t (setq items (reverse items))
8590 (setcdr (nthcdr (1- nlast) items) nil)
8591 (nreverse items))))
8592 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8593 items1)))
8594 (res (apply '+ numbers))
8595 (sres (if (= timecnt 0)
8596 (format "%g" res)
8597 (setq diff (* 3600 res)
8598 h (floor (/ diff 3600)) diff (mod diff 3600)
8599 m (floor (/ diff 60)) diff (mod diff 60)
8600 s diff)
8601 (format "%d:%02d:%02d" h m s))))
8602 (kill-new sres)
8603 (if (interactive-p)
8604 (message "%s"
8605 (substitute-command-keys
8606 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8607 (length numbers) sres))))
8608 sres))))
8609
8610 (defun org-table-get-number-for-summing (s)
8611 (let (n)
8612 (if (string-match "^ *|? *" s)
8613 (setq s (replace-match "" nil nil s)))
8614 (if (string-match " *|? *$" s)
8615 (setq s (replace-match "" nil nil s)))
8616 (setq n (string-to-number s))
8617 (cond
8618 ((and (string-match "0" s)
8619 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8620 ((string-match "\\`[ \t]+\\'" s) nil)
8621 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8622 (let ((h (string-to-number (or (match-string 1 s) "0")))
8623 (m (string-to-number (or (match-string 2 s) "0")))
8624 (s (string-to-number (or (match-string 4 s) "0"))))
8625 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
8626 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8627 ((equal n 0) nil)
8628 (t n))))
8629
8630 (defun org-table-get-vertical-vector (desc &optional tbeg col)
8631 "Get a calc vector from a column, accorting to desctiptor DESC.
8632 Optional arguments TBEG and COL can give the beginning of the table and
8633 the current column, to avoid unnecessary parsing."
8634 (save-excursion
8635 (or tbeg (setq tbeg (org-table-begin)))
8636 (or col (setq col (org-table-current-column)))
8637 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
8638 (cond
8639 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
8640 (setq n1 (- (match-end 1) (match-beginning 1)))
8641 (if (match-beginning 3)
8642 (setq n2 (- (match-end 2) (match-beginning 3))))
8643 (setq n (if n2 (max n1 n2) n1))
8644 (setq n1 (if n2 (min n1 n2)))
8645 (setq nn n)
8646 (while (and (> nn 0)
8647 (re-search-backward org-table-hline-regexp tbeg t))
8648 (push (org-current-line) hline-list)
8649 (setq nn (1- nn)))
8650 (setq hline-list (nreverse hline-list))
8651 (goto-line (nth (1- n) hline-list))
8652 (when (re-search-forward org-table-dataline-regexp)
8653 (org-table-goto-column col)
8654 (setq beg (point)))
8655 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
8656 (when (re-search-backward org-table-dataline-regexp)
8657 (org-table-goto-column col)
8658 (setq end (point)))
8659 (setq l (apply 'append (org-table-copy-region beg end)))
8660 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
8661 (if (equal x "") "0" x))
8662 l ",") "]"))
8663 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
8664 (setq n1 (string-to-number (match-string 1 desc))
8665 n2 (string-to-number (match-string 2 desc)))
8666 (beginning-of-line 1)
8667 (save-excursion
8668 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
8669 (org-table-goto-column col)
8670 (setq beg (point))))
8671 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
8672 (org-table-goto-column col)
8673 (setq end (point)))
8674 (setq l (apply 'append (org-table-copy-region beg end)))
8675 (concat "[" (mapconcat
8676 (lambda (x) (setq x (org-trim x))
8677 (if (equal x "") "0" x))
8678 l ",") "]"))
8679 ((string-match "\\([0-9]+\\)" desc)
8680 (beginning-of-line 1)
8681 (when (re-search-backward org-table-dataline-regexp tbeg t
8682 (string-to-number (match-string 0 desc)))
8683 (org-table-goto-column col)
8684 (org-trim (org-table-get-field))))))))
8685
8686 (defvar org-table-formula-history nil)
8687
8688 (defvar org-table-column-names nil
8689 "Alist with column names, derived from the `!' line.")
8690 (defvar org-table-column-name-regexp nil
8691 "Regular expression matching the current column names.")
8692 (defvar org-table-local-parameters nil
8693 "Alist with parameter names, derived from the `$' line.")
8694 (defvar org-table-named-field-locations nil
8695 "Alist with locations of named fields.")
8696
8697 (defun org-table-get-formula (&optional equation named)
8698 "Read a formula from the minibuffer, offer stored formula as default."
8699 (let* ((name (car (rassoc (list (org-current-line)
8700 (org-table-current-column))
8701 org-table-named-field-locations)))
8702 (scol (if named
8703 (if name name
8704 (error "Not in a named field"))
8705 (int-to-string (org-table-current-column))))
8706 (dummy (and name (not named)
8707 (not (y-or-n-p "Replace named-field formula with column equation? " ))
8708 (error "Abort")))
8709 (org-table-may-need-update nil)
8710 (stored-list (org-table-get-stored-formulas))
8711 (stored (cdr (assoc scol stored-list)))
8712 (eq (cond
8713 ((and stored equation (string-match "^ *=? *$" equation))
8714 stored)
8715 ((stringp equation)
8716 equation)
8717 (t (read-string
8718 (format "%s formula $%s=" (if named "Field" "Column") scol)
8719 (or stored "") 'org-table-formula-history
8720 ;stored
8721 ))))
8722 mustsave)
8723 (when (not (string-match "\\S-" eq))
8724 ;; remove formula
8725 (setq stored-list (delq (assoc scol stored-list) stored-list))
8726 (org-table-store-formulas stored-list)
8727 (error "Formula removed"))
8728 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8729 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8730 (if (and name (not named))
8731 ;; We set the column equation, delete the named one.
8732 (setq stored-list (delq (assoc name stored-list) stored-list)
8733 mustsave t))
8734 (if stored
8735 (setcdr (assoc scol stored-list) eq)
8736 (setq stored-list (cons (cons scol eq) stored-list)))
8737 (if (or mustsave (not (equal stored eq)))
8738 (org-table-store-formulas stored-list))
8739 eq))
8740
8741 (defun org-table-store-formulas (alist)
8742 "Store the list of formulas below the current table."
8743 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
8744 (save-excursion
8745 (goto-char (org-table-end))
8746 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
8747 (delete-region (point) (match-end 0)))
8748 (insert "#+TBLFM: "
8749 (mapconcat (lambda (x)
8750 (concat "$" (car x) "=" (cdr x)))
8751 alist "::")
8752 "\n")))
8753
8754 (defun org-table-get-stored-formulas ()
8755 "Return an alist with the t=stored formulas directly after current table."
8756 (interactive)
8757 (let (scol eq eq-alist strings string seen)
8758 (save-excursion
8759 (goto-char (org-table-end))
8760 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8761 (setq strings (org-split-string (match-string 2) " *:: *"))
8762 (while (setq string (pop strings))
8763 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
8764 (setq scol (match-string 1 string)
8765 eq (match-string 2 string)
8766 eq-alist (cons (cons scol eq) eq-alist))
8767 (if (member scol seen)
8768 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8769 (push scol seen))))))
8770 (nreverse eq-alist)))
8771
8772 (defun org-table-modify-formulas (action &rest columns)
8773 "Modify the formulas stored below the current table.
8774 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
8775 expected, for the other action only a single column number is needed."
8776 (let ((list (org-table-get-stored-formulas))
8777 (nmax (length (org-split-string
8778 (buffer-substring (point-at-bol) (point-at-eol))
8779 "|")))
8780 col col1 col2 scol si sc1 sc2)
8781 (cond
8782 ((null list)) ; No action needed if there are no stored formulas
8783 ((eq action 'remove)
8784 (setq col (car columns)
8785 scol (int-to-string col))
8786 (org-table-replace-in-formulas list scol "INVALID")
8787 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
8788 (loop for i from (1+ col) upto nmax by 1 do
8789 (setq si (int-to-string i))
8790 (org-table-replace-in-formulas list si (int-to-string (1- i)))
8791 (if (assoc si list) (setcar (assoc si list)
8792 (int-to-string (1- i))))))
8793 ((eq action 'insert)
8794 (setq col (car columns))
8795 (loop for i from nmax downto col by 1 do
8796 (setq si (int-to-string i))
8797 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
8798 (if (assoc si list) (setcar (assoc si list)
8799 (int-to-string (1+ i))))))
8800 ((eq action 'swap)
8801 (setq col1 (car columns) col2 (nth 1 columns)
8802 sc1 (int-to-string col1) sc2 (int-to-string col2))
8803 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
8804 (org-table-replace-in-formulas list sc1 "ZqZ")
8805 (org-table-replace-in-formulas list sc2 sc1)
8806 (org-table-replace-in-formulas list "ZqZ" sc2)
8807 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
8808 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
8809 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
8810 (t (error "Invalid action in `org-table-modify-formulas'")))
8811 (if list (org-table-store-formulas list))))
8812
8813 (defun org-table-replace-in-formulas (list s1 s2)
8814 (let (elt re s)
8815 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
8816 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
8817 re (concat (regexp-quote s1) "\\>"))
8818 (while (setq elt (pop list))
8819 (setq s (cdr elt))
8820 (while (string-match re s)
8821 (setq s (replace-match s2 t t s)))
8822 (setcdr elt s))))
8823
8824 (defun org-table-get-specials ()
8825 "Get the column nmaes and local parameters for this table."
8826 (save-excursion
8827 (let ((beg (org-table-begin)) (end (org-table-end))
8828 names name fields fields1 field cnt c v line col)
8829 (setq org-table-column-names nil
8830 org-table-local-parameters nil
8831 org-table-named-field-locations nil)
8832 (goto-char beg)
8833 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8834 (setq names (org-split-string (match-string 1) " *| *")
8835 cnt 1)
8836 (while (setq name (pop names))
8837 (setq cnt (1+ cnt))
8838 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8839 (push (cons name (int-to-string cnt)) org-table-column-names))))
8840 (setq org-table-column-names (nreverse org-table-column-names))
8841 (setq org-table-column-name-regexp
8842 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8843 (goto-char beg)
8844 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8845 (setq fields (org-split-string (match-string 1) " *| *"))
8846 (while (setq field (pop fields))
8847 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8848 (push (cons (match-string 1 field) (match-string 2 field))
8849 org-table-local-parameters))))
8850 (goto-char beg)
8851 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8852 (setq c (match-string 1)
8853 fields (org-split-string (match-string 2) " *| *"))
8854 (save-excursion
8855 (beginning-of-line (if (equal c "_") 2 0))
8856 (setq line (org-current-line) col 1)
8857 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8858 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8859 (while (and fields1 (setq field (pop fields)))
8860 (setq v (pop fields1) col (1+ col))
8861 (when (and (stringp field) (stringp v)
8862 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8863 (push (cons field v) org-table-local-parameters)
8864 (push (list field line col) org-table-named-field-locations)))))))
8865
8866 (defun org-this-word ()
8867 ;; Get the current word
8868 (save-excursion
8869 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
8870 (end (progn (skip-chars-forward "^ \t\n") (point))))
8871 (buffer-substring-no-properties beg end))))
8872
8873 (defun org-table-maybe-eval-formula ()
8874 "Check if the current field starts with \"=\" or \":=\".
8875 If yes, store the formula and apply it."
8876 ;; We already know we are in a table. Get field will only return a formula
8877 ;; when appropriate. It might return a separator line, but no problem.
8878 (when org-table-formula-evaluate-inline
8879 (let* ((field (org-trim (or (org-table-get-field) "")))
8880 named eq)
8881 (when (string-match "^:?=\\(.*\\)" field)
8882 (setq named (equal (string-to-char field) ?:)
8883 eq (match-string 1 field))
8884 (if (fboundp 'calc-eval)
8885 (org-table-eval-formula (if named '(4) nil) eq))))))
8886
8887 (defvar org-recalc-commands nil
8888 "List of commands triggering the reccalculation of a line.
8889 Will be filled automatically during use.")
8890
8891 (defvar org-recalc-marks
8892 '((" " . "Unmarked: no special line, no automatic recalculation")
8893 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8894 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8895 ("!" . "Column name definition line. Reference in formula as $name.")
8896 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8897 ("_" . "Names for values in row below this one.")
8898 ("^" . "Names for values in row above this one.")))
8899
8900 (defun org-table-rotate-recalc-marks (&optional newchar)
8901 "Rotate the recalculation mark in the first column.
8902 If in any row, the first field is not consistent with a mark,
8903 insert a new column for the makers.
8904 When there is an active region, change all the lines in the region,
8905 after prompting for the marking character.
8906 After each change, a message will be displayed indication the meaning
8907 of the new mark."
8908 (interactive)
8909 (unless (org-at-table-p) (error "Not at a table"))
8910 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8911 (beg (org-table-begin))
8912 (end (org-table-end))
8913 (l (org-current-line))
8914 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8915 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8916 (have-col
8917 (save-excursion
8918 (goto-char beg)
8919 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8920 (col (org-table-current-column))
8921 (forcenew (car (assoc newchar org-recalc-marks)))
8922 epos new)
8923 (when l1
8924 (message "Change region to what mark? Type # * ! $ or SPC: ")
8925 (setq newchar (char-to-string (read-char-exclusive))
8926 forcenew (car (assoc newchar org-recalc-marks))))
8927 (if (and newchar (not forcenew))
8928 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8929 newchar))
8930 (if l1 (goto-line l1))
8931 (save-excursion
8932 (beginning-of-line 1)
8933 (unless (looking-at org-table-dataline-regexp)
8934 (error "Not at a table data line")))
8935 (unless have-col
8936 (org-table-goto-column 1)
8937 (org-table-insert-column)
8938 (org-table-goto-column (1+ col)))
8939 (setq epos (point-at-eol))
8940 (save-excursion
8941 (beginning-of-line 1)
8942 (org-table-get-field
8943 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8944 (concat " "
8945 (setq new (or forcenew
8946 (cadr (member (match-string 1) marks))))
8947 " ")
8948 " # ")))
8949 (if (and l1 l2)
8950 (progn
8951 (goto-line l1)
8952 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8953 (and (looking-at org-table-dataline-regexp)
8954 (org-table-get-field 1 (concat " " new " "))))
8955 (goto-line l1)))
8956 (if (not (= epos (point-at-eol))) (org-table-align))
8957 (goto-line l)
8958 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8959
8960 (defun org-table-maybe-recalculate-line ()
8961 "Recompute the current line if marked for it, and if we haven't just done it."
8962 (interactive)
8963 (and org-table-allow-automatic-line-recalculation
8964 (not (and (memq last-command org-recalc-commands)
8965 (equal org-last-recalc-line (org-current-line))))
8966 (save-excursion (beginning-of-line 1)
8967 (looking-at org-table-auto-recalculate-regexp))
8968 (fboundp 'calc-eval)
8969 (org-table-recalculate) t))
8970
8971 (defvar org-table-formula-debug nil
8972 "Non-nil means, debug table formulas.
8973 When nil, simply write \"#ERROR\" in corrupted fields.")
8974
8975 (defvar modes)
8976 (defsubst org-set-calc-mode (var &optional value)
8977 (if (stringp var)
8978 (setq var (assoc var '(("D" calc-angle-mode deg)
8979 ("R" calc-angle-mode rad)
8980 ("F" calc-prefer-frac t)
8981 ("S" calc-symbolic-mode t)))
8982 value (nth 2 var) var (nth 1 var)))
8983 (if (memq var modes)
8984 (setcar (cdr (memq var modes)) value)
8985 (cons var (cons value modes)))
8986 modes)
8987
8988 (defun org-table-eval-formula (&optional arg equation
8989 suppress-align suppress-const
8990 suppress-store)
8991 "Replace the table field value at the cursor by the result of a calculation.
8992
8993 This function makes use of Dave Gillespie's calc package, in my view the
8994 most exciting program ever written for GNU Emacs. So you need to have calc
8995 installed in order to use this function.
8996
8997 In a table, this command replaces the value in the current field with the
8998 result of a formula. It also installes the formula as the \"current\" column
8999 formula, by storing it in a special line below the table. When called
9000 with a `C-u' prefix, the current field must ba a named field, and the
9001 formula is installed as valid in only this specific field.
9002
9003 When called, the command first prompts for a formula, which is read in
9004 the minibuffer. Previously entered formulas are available through the
9005 history list, and the last used formula is offered as a default.
9006 These stored formulas are adapted correctly when moving, inserting, or
9007 deleting columns with the corresponding commands.
9008
9009 The formula can be any algebraic expression understood by the calc package.
9010 For details, see the Org-mode manual.
9011
9012 This function can also be called from Lisp programs and offers
9013 additional Arguments: EQUATION can be the formula to apply. If this
9014 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9015 used to speed-up recursive calls by by-passing unnecessary aligns.
9016 SUPPRESS-CONST suppresses the interpretation of constants in the
9017 formula, assuming that this has been done already outside the fuction.
9018 SUPPRESS-STORE means the formula should not be stored, either because
9019 it is already stored, or because it is a modified equation that should
9020 not overwrite the stored one."
9021 (interactive "P")
9022 (require 'calc)
9023 (org-table-check-inside-data-field)
9024 (org-table-get-specials)
9025 (let* (fields
9026 (ndown (if (integerp arg) arg 1))
9027 (org-table-automatic-realign nil)
9028 (case-fold-search nil)
9029 (down (> ndown 1))
9030 (formula (if (and equation suppress-store)
9031 equation
9032 (org-table-get-formula equation (equal arg '(4)))))
9033 (n0 (org-table-current-column))
9034 (modes (copy-sequence org-calc-default-modes))
9035 n form fmt x ev orig c)
9036 ;; Parse the format string. Since we have a lot of modes, this is
9037 ;; a lot of work. However, I think calc still uses most of the time.
9038 (if (string-match ";" formula)
9039 (let ((tmp (org-split-string formula ";")))
9040 (setq formula (car tmp)
9041 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9042 (nth 1 tmp)))
9043 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9044 (setq c (string-to-char (match-string 1 fmt))
9045 n (string-to-number (or (match-string 1 fmt) "")))
9046 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9047 (setq modes (org-set-calc-mode
9048 'calc-float-format
9049 (list (cdr (assoc c '((?n. float) (?f. fix)
9050 (?s. sci) (?e. eng))))
9051 n))))
9052 (setq fmt (replace-match "" t t fmt)))
9053 (while (string-match "[DRFS]" fmt)
9054 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9055 (setq fmt (replace-match "" t t fmt)))
9056 (unless (string-match "\\S-" fmt)
9057 (setq fmt nil))))
9058 (if (and (not suppress-const) org-table-formula-use-constants)
9059 (setq formula (org-table-formula-substitute-names formula)))
9060 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9061 (while (> ndown 0)
9062 (setq fields (org-split-string
9063 (buffer-substring
9064 (point-at-bol) (point-at-eol)) " *| *"))
9065 (if org-table-formula-numbers-only
9066 (setq fields (mapcar
9067 (lambda (x) (number-to-string (string-to-number x)))
9068 fields)))
9069 (setq ndown (1- ndown))
9070 (setq form (copy-sequence formula))
9071 ;; Insert the references to fields in same row
9072 (while (string-match "\\$\\([0-9]+\\)?" form)
9073 (setq n (if (match-beginning 1)
9074 (string-to-number (match-string 1 form))
9075 n0)
9076 x (nth (1- n) fields))
9077 (unless x (error "Invalid field specifier \"%s\""
9078 (match-string 0 form)))
9079 (if (equal x "") (setq x "0"))
9080 (setq form (replace-match (concat "(" x ")") t t form)))
9081 ;; Insert ranges in current column
9082 (while (string-match "\\&[-I0-9]+" form)
9083 (setq form (replace-match
9084 (save-match-data
9085 (org-table-get-vertical-vector (match-string 0 form)
9086 nil n0))
9087 t t form)))
9088 (setq ev (calc-eval (cons form modes)
9089 (if org-table-formula-numbers-only 'num)))
9090
9091 (when org-table-formula-debug
9092 (with-output-to-temp-buffer "*Help*"
9093 (princ (format "Substitution history of formula
9094 Orig: %s
9095 $xyz-> %s
9096 $1-> %s\n" orig formula form))
9097 (if (listp ev)
9098 (princ (format " %s^\nError: %s"
9099 (make-string (car ev) ?\-) (nth 1 ev)))
9100 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9101 ev (or fmt "NONE")
9102 (if fmt (format fmt (string-to-number ev)) ev)))))
9103 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9104 (unless (and (interactive-p) (not ndown))
9105 (unless (let (inhibit-redisplay)
9106 (y-or-n-p "Debugging Formula. Continue to next? "))
9107 (org-table-align)
9108 (error "Abort"))
9109 (delete-window (get-buffer-window "*Help*"))
9110 (message "")))
9111 (if (listp ev) (setq fmt nil ev "#ERROR"))
9112 (org-table-justify-field-maybe
9113 (if fmt (format fmt (string-to-number ev)) ev))
9114 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9115 (call-interactively 'org-return)
9116 (setq ndown 0)))
9117 (and down (org-table-maybe-recalculate-line))
9118 (or suppress-align (and org-table-may-need-update
9119 (org-table-align)))))
9120
9121 (defun org-table-recalculate (&optional all noalign)
9122 "Recalculate the current table line by applying all stored formulas."
9123 (interactive "P")
9124 (or (memq this-command org-recalc-commands)
9125 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9126 (unless (org-at-table-p) (error "Not at a table"))
9127 (org-table-get-specials)
9128 (let* ((eqlist (sort (org-table-get-stored-formulas)
9129 (lambda (a b) (string< (car a) (car b)))))
9130 (inhibit-redisplay t)
9131 (line-re org-table-dataline-regexp)
9132 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9133 (thiscol (org-table-current-column))
9134 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9135 ;; Insert constants in all formulas
9136 (setq eqlist
9137 (mapcar (lambda (x)
9138 (setcdr x (org-table-formula-substitute-names (cdr x)))
9139 x)
9140 eqlist))
9141 ;; Split the equation list
9142 (while (setq eq (pop eqlist))
9143 (if (<= (string-to-char (car eq)) ?9)
9144 (push eq eqlnum)
9145 (push eq eqlname)))
9146 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9147 (if all
9148 (progn
9149 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9150 (goto-char (setq beg (org-table-begin)))
9151 (if (re-search-forward org-table-calculate-mark-regexp end t)
9152 ;; This is a table with marked lines, only compute selected lines
9153 (setq line-re org-table-recalculate-regexp)
9154 ;; Move forward to the first non-header line
9155 (if (and (re-search-forward org-table-dataline-regexp end t)
9156 (re-search-forward org-table-hline-regexp end t)
9157 (re-search-forward org-table-dataline-regexp end t))
9158 (setq beg (match-beginning 0))
9159 nil))) ;; just leave beg where it is
9160 (setq beg (point-at-bol)
9161 end (move-marker (make-marker) (1+ (point-at-eol)))))
9162 (goto-char beg)
9163 (and all (message "Re-applying formulas to full table..."))
9164 (while (re-search-forward line-re end t)
9165 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9166 ;; Unprotected line, recalculate
9167 (and all (message "Re-applying formulas to full table...(line %d)"
9168 (setq cnt (1+ cnt))))
9169 (setq org-last-recalc-line (org-current-line))
9170 (setq eql eqlnum)
9171 (while (setq entry (pop eql))
9172 (goto-line org-last-recalc-line)
9173 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9174 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9175 (goto-line thisline)
9176 (org-table-goto-column thiscol)
9177 (or noalign (and org-table-may-need-update (org-table-align))
9178 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9179 ;; Now do the names fields
9180 (while (setq eq (pop eqlname))
9181 (setq name (car eq)
9182 a (assoc name org-table-named-field-locations))
9183 (when a
9184 (message "Re-applying formula to named field: %s" name)
9185 (goto-line (nth 1 a))
9186 (org-table-goto-column (nth 2 a))
9187 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9188 ;; back to initial position
9189 (goto-line thisline)
9190 (org-table-goto-column thiscol)
9191 (or noalign (and org-table-may-need-update (org-table-align))
9192 (and all (message "Re-applying formulas...done")))))
9193
9194 (defun org-table-formula-substitute-names (f)
9195 "Replace $const with values in string F."
9196 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9197 ;; First, check for column names
9198 (while (setq start (string-match org-table-column-name-regexp f start))
9199 (setq start (1+ start))
9200 (setq a (assoc (match-string 1 f) org-table-column-names))
9201 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9202 ;; Expand ranges to vectors
9203 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9204 (setq n1 (string-to-number (match-string 1 f))
9205 n2 (string-to-number (match-string 2 f))
9206 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9207 s (concat "[($" (number-to-string (1- nn1)) ")"))
9208 (loop for i from nn1 upto nn2 do
9209 (setq s (concat s ",($" (int-to-string i) ")")))
9210 (setq s (concat s "]"))
9211 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9212 (setq f (replace-match s t t f)))
9213 ;; Parameters and constants
9214 (setq start 0)
9215 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9216 (setq start (1+ start))
9217 (if (setq a (save-match-data
9218 (org-table-get-constant (match-string 1 f))))
9219 (setq f (replace-match (concat "(" a ")") t t f))))
9220 (if org-table-formula-debug
9221 (put-text-property 0 (length f) :orig-formula f1 f))
9222 f))
9223
9224 (defun org-table-get-constant (const)
9225 "Find the value for a parameter or constant in a formula.
9226 Parameters get priority."
9227 (or (cdr (assoc const org-table-local-parameters))
9228 (cdr (assoc const org-table-formula-constants))
9229 (and (fboundp 'constants-get) (constants-get const))
9230 "#UNDEFINED_NAME"))
9231
9232 (defvar org-edit-formulas-map (make-sparse-keymap))
9233 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9234 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9235 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9236
9237 (defvar org-pos)
9238 (defvar org-window-configuration)
9239
9240 (defun org-table-edit-formulas ()
9241 "Edit the formulas of the current table in a separate buffer."
9242 (interactive)
9243 (unless (org-at-table-p)
9244 (error "Not at a table"))
9245 (org-table-get-specials)
9246 (let ((eql (org-table-get-stored-formulas))
9247 (pos (move-marker (make-marker) (point)))
9248 (wc (current-window-configuration))
9249 entry loc s)
9250 (switch-to-buffer-other-window "*Edit Formulas*")
9251 (erase-buffer)
9252 (fundamental-mode)
9253 (set (make-local-variable 'org-pos) pos)
9254 (set (make-local-variable 'org-window-configuration) wc)
9255 (use-local-map org-edit-formulas-map)
9256 (setq s "# Edit formulas and finish with `C-c C-c'.
9257 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9258 # Use `C-c ?' to get information about $name at point.
9259 # To cancel editing, press `C-c C-q'.\n")
9260 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9261 (insert s)
9262 (while (setq entry (pop eql))
9263 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9264 (setq s (format "# Named formula, referring to column %d in line %d\n"
9265 (nth 2 loc) (nth 1 loc)))
9266 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9267 (insert s))
9268 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9269 (remove-text-properties 0 (length s) '(face nil) s)
9270 (insert s))
9271 (goto-char (point-min))
9272 (message "Edit formulas and finish with `C-c C-c'.")))
9273
9274 (defun org-show-variable ()
9275 "Show the location/value of the $ expression at point."
9276 (interactive)
9277 (let (var (pos org-pos) (win (selected-window)) e)
9278 (save-excursion
9279 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9280 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9281 (setq var (match-string 1))
9282 (error "No variable at point")))
9283 (cond
9284 ((setq e (assoc var org-table-named-field-locations))
9285 (switch-to-buffer-other-window (marker-buffer pos))
9286 (goto-line (nth 1 e))
9287 (org-table-goto-column (nth 2 e))
9288 (select-window win)
9289 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9290 ((setq e (assoc var org-table-column-names))
9291 (switch-to-buffer-other-window (marker-buffer pos))
9292 (goto-char pos)
9293 (goto-char (org-table-begin))
9294 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9295 (org-table-end) t)
9296 (progn
9297 (goto-char (match-beginning 1))
9298 (message "Named column (column %s)" (cdr e)))
9299 (error "Column name not found"))
9300 (select-window win))
9301 ((string-match "^[0-9]$" var)
9302 ;; column number
9303 (switch-to-buffer-other-window (marker-buffer pos))
9304 (goto-char pos)
9305 (goto-char (org-table-begin))
9306 (recenter 1)
9307 (if (re-search-forward org-table-dataline-regexp
9308 (org-table-end) t)
9309 (progn
9310 (goto-char (match-beginning 0))
9311 (org-table-goto-column (string-to-number var))
9312 (message "Column %s" var))
9313 (error "Column name not found"))
9314 (select-window win))
9315 ((setq e (assoc var org-table-local-parameters))
9316 (switch-to-buffer-other-window (marker-buffer pos))
9317 (goto-char pos)
9318 (goto-char (org-table-begin))
9319 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9320 (progn
9321 (goto-char (match-beginning 1))
9322 (message "Local parameter."))
9323 (error "Parameter not found"))
9324 (select-window win))
9325 (t
9326 (cond
9327 ((setq e (assoc var org-table-formula-constants))
9328 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9329 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9330 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9331 (t (error "Undefined name $%s" var)))))))
9332
9333 (defun org-finish-edit-formulas (&optional arg)
9334 "Parse the buffer for formula definitions and install them.
9335 With prefix ARG, apply the new formulas to the table."
9336 (interactive "P")
9337 (let ((pos org-pos) eql)
9338 (goto-char (point-min))
9339 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9340 (push (cons (match-string 1) (match-string 2)) eql))
9341 (set-window-configuration org-window-configuration)
9342 (select-window (get-buffer-window (marker-buffer pos)))
9343 (goto-char pos)
9344 (unless (org-at-table-p)
9345 (error "Lost table position - cannot install formulae"))
9346 (org-table-store-formulas eql)
9347 (move-marker pos nil)
9348 (kill-buffer "*Edit Formulas*")
9349 (if arg
9350 (org-table-recalculate 'all)
9351 (message "New formulas installed - press C-u C-c C-c to apply."))))
9352
9353 (defun org-abort-edit-formulas ()
9354 "Abort editing formulas, without installing the changes."
9355 (interactive)
9356 (let ((pos org-pos))
9357 (set-window-configuration org-window-configuration)
9358 (select-window (get-buffer-window (marker-buffer pos)))
9359 (goto-char pos)
9360 (message "Formula editing aborted without installing changes")))
9361
9362 ;;; The orgtbl minor mode
9363
9364 ;; Define a minor mode which can be used in other modes in order to
9365 ;; integrate the org-mode table editor.
9366
9367 ;; This is really a hack, because the org-mode table editor uses several
9368 ;; keys which normally belong to the major mode, for example the TAB and
9369 ;; RET keys. Here is how it works: The minor mode defines all the keys
9370 ;; necessary to operate the table editor, but wraps the commands into a
9371 ;; function which tests if the cursor is currently inside a table. If that
9372 ;; is the case, the table editor command is executed. However, when any of
9373 ;; those keys is used outside a table, the function uses `key-binding' to
9374 ;; look up if the key has an associated command in another currently active
9375 ;; keymap (minor modes, major mode, global), and executes that command.
9376 ;; There might be problems if any of the keys used by the table editor is
9377 ;; otherwise used as a prefix key.
9378
9379 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9380 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9381 ;; addresses this by checking explicitly for both bindings.
9382
9383 ;; The optimized version (see variable `orgtbl-optimized') takes over
9384 ;; all keys which are bound to `self-insert-command' in the *global map*.
9385 ;; Some modes bind other commands to simple characters, for example
9386 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9387 ;; active, this binding is ignored inside tables and replaced with a
9388 ;; modified self-insert.
9389
9390 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9391 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9392 In the optimized version, the table editor takes over all simple keys that
9393 normally just insert a character. In tables, the characters are inserted
9394 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9395 for empty fields). Outside tables, the correct binding of the keys is
9396 restored.
9397
9398 The default for this option is t if the optimized version is also used in
9399 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9400 this variable requires a restart of Emacs to become effective."
9401 :group 'org-table
9402 :type 'boolean)
9403
9404 (defvar orgtbl-mode nil
9405 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9406 table editor in arbitrary modes.")
9407 (make-variable-buffer-local 'orgtbl-mode)
9408
9409 (defvar orgtbl-mode-map (make-keymap)
9410 "Keymap for `orgtbl-mode'.")
9411
9412 ;;;###autoload
9413 (defun turn-on-orgtbl ()
9414 "Unconditionally turn on `orgtbl-mode'."
9415 (orgtbl-mode 1))
9416
9417 ;;;###autoload
9418 (defun orgtbl-mode (&optional arg)
9419 "The `org-mode' table editor as a minor mode for use in other modes."
9420 (interactive)
9421 (if (eq major-mode 'org-mode)
9422 ;; Exit without error, in case some hook functions calls this
9423 ;; by accident in org-mode.
9424 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9425 (setq orgtbl-mode
9426 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9427 (if orgtbl-mode
9428 (progn
9429 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9430 ;; Make sure we are first in minor-mode-map-alist
9431 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9432 (and c (setq minor-mode-map-alist
9433 (cons c (delq c minor-mode-map-alist)))))
9434 (set (make-local-variable (quote org-table-may-need-update)) t)
9435 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
9436 (add-hook 'before-change-functions 'org-before-change-function
9437 nil 'local)
9438 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
9439 auto-fill-inhibit-regexp)
9440 (set (make-local-variable 'auto-fill-inhibit-regexp)
9441 (if auto-fill-inhibit-regexp
9442 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
9443 "[ \t]*|"))
9444 (easy-menu-add orgtbl-mode-menu)
9445 (run-hooks 'orgtbl-mode-hook))
9446 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9447 (remove-hook 'before-change-functions 'org-before-change-function t)
9448 (easy-menu-remove orgtbl-mode-menu)
9449 (force-mode-line-update 'all))))
9450
9451 ;; Install it as a minor mode.
9452 (put 'orgtbl-mode :included t)
9453 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9454 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9455
9456 (defun orgtbl-make-binding (fun n &rest keys)
9457 "Create a function for binding in the table minor mode.
9458 FUN is the command to call inside a table. N is used to create a unique
9459 command name. KEYS are keys that should be checked in for a command
9460 to execute outside of tables."
9461 (eval
9462 (list 'defun
9463 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9464 '(arg)
9465 (concat "In tables, run `" (symbol-name fun) "'.\n"
9466 "Outside of tables, run the binding of `"
9467 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9468 "'.")
9469 '(interactive "p")
9470 (list 'if
9471 '(org-at-table-p)
9472 (list 'call-interactively (list 'quote fun))
9473 (list 'let '(orgtbl-mode)
9474 (list 'call-interactively
9475 (append '(or)
9476 (mapcar (lambda (k)
9477 (list 'key-binding k))
9478 keys)
9479 '('orgtbl-error))))))))
9480
9481 (defun orgtbl-error ()
9482 "Error when there is no default binding for a table key."
9483 (interactive)
9484 (error "This key is has no function outside tables"))
9485
9486 (defun orgtbl-setup ()
9487 "Setup orgtbl keymaps."
9488 (let ((nfunc 0)
9489 (bindings
9490 (list
9491 '([(meta shift left)] org-table-delete-column)
9492 '([(meta left)] org-table-move-column-left)
9493 '([(meta right)] org-table-move-column-right)
9494 '([(meta shift right)] org-table-insert-column)
9495 '([(meta shift up)] org-table-kill-row)
9496 '([(meta shift down)] org-table-insert-row)
9497 '([(meta up)] org-table-move-row-up)
9498 '([(meta down)] org-table-move-row-down)
9499 '("\C-c\C-w" org-table-cut-region)
9500 '("\C-c\M-w" org-table-copy-region)
9501 '("\C-c\C-y" org-table-paste-rectangle)
9502 '("\C-c-" org-table-insert-hline)
9503 ; '([(shift tab)] org-table-previous-field)
9504 '("\C-m" org-table-next-row)
9505 (list (org-key 'S-return) 'org-table-copy-down)
9506 '([(meta return)] org-table-wrap-region)
9507 '("\C-c\C-q" org-table-wrap-region)
9508 '("\C-c?" org-table-current-column)
9509 '("\C-c " org-table-blank-field)
9510 '("\C-c+" org-table-sum)
9511 '("\C-c|" org-table-toggle-vline-visibility)
9512 '("\C-c=" org-table-eval-formula)
9513 '("\C-c'" org-table-edit-formulas)
9514 '("\C-c*" org-table-recalculate)
9515 '("\C-c^" org-table-sort-lines)
9516 '([(control ?#)] org-table-rotate-recalc-marks)))
9517 elt key fun cmd)
9518 (while (setq elt (pop bindings))
9519 (setq nfunc (1+ nfunc))
9520 (setq key (car elt)
9521 fun (nth 1 elt)
9522 cmd (orgtbl-make-binding fun nfunc key))
9523 (define-key orgtbl-mode-map key cmd))
9524 ;; Special treatment needed for TAB and RET
9525 (define-key orgtbl-mode-map [(return)]
9526 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9527 (define-key orgtbl-mode-map "\C-m"
9528 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9529 (define-key orgtbl-mode-map [(tab)]
9530 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9531 (define-key orgtbl-mode-map "\C-i"
9532 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
9533 (define-key orgtbl-mode-map "\C-i"
9534 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
9535 (define-key orgtbl-mode-map "\C-c\C-c"
9536 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
9537 (when orgtbl-optimized
9538 ;; If the user wants maximum table support, we need to hijack
9539 ;; some standard editing functions
9540 (org-remap orgtbl-mode-map
9541 'self-insert-command 'orgtbl-self-insert-command
9542 'delete-char 'orgtbl-delete-char
9543 'delete-backward-char 'orgtbl-delete-backward-char)
9544 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
9545 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
9546 '("OrgTbl"
9547 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
9548 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
9549 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
9550 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
9551 "--"
9552 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
9553 ["Copy Field from Above"
9554 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
9555 "--"
9556 ("Column"
9557 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
9558 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
9559 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
9560 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
9561 ("Row"
9562 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
9563 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
9564 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
9565 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
9566 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
9567 "--"
9568 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
9569 ("Rectangle"
9570 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
9571 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
9572 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
9573 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
9574 "--"
9575 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
9576 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9577 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
9578 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
9579 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
9580 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
9581 ["Sum Column/Rectangle" org-table-sum
9582 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
9583 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
9584 ["Debug Formulas"
9585 (setq org-table-formula-debug (not org-table-formula-debug))
9586 :style toggle :selected org-table-formula-debug]
9587 ))
9588 t)
9589
9590 (defun orgtbl-tab ()
9591 "Justification and field motion for `orgtbl-mode'."
9592 (interactive)
9593 (org-table-justify-field-maybe)
9594 (org-table-next-field))
9595
9596 (defun orgtbl-ret ()
9597 "Justification and field motion for `orgtbl-mode'."
9598 (interactive)
9599 (org-table-justify-field-maybe)
9600 (org-table-next-row))
9601
9602 (defun orgtbl-self-insert-command (N)
9603 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9604 If the cursor is in a table looking at whitespace, the whitespace is
9605 overwritten, and the table is not marked as requiring realignment."
9606 (interactive "p")
9607 (if (and (org-at-table-p)
9608 (or
9609 (and org-table-auto-blank-field
9610 (member last-command
9611 '(orgtbl-hijacker-command-100
9612 orgtbl-hijacker-command-101
9613 orgtbl-hijacker-command-102
9614 orgtbl-hijacker-command-103
9615 orgtbl-hijacker-command-104
9616 orgtbl-hijacker-command-105))
9617 (org-table-blank-field))
9618 t)
9619 (eq N 1)
9620 (looking-at "[^|\n]* +|"))
9621 (let (org-table-may-need-update)
9622 (goto-char (1- (match-end 0)))
9623 (delete-backward-char 1)
9624 (goto-char (match-beginning 0))
9625 (self-insert-command N))
9626 (setq org-table-may-need-update t)
9627 (let (orgtbl-mode)
9628 (call-interactively (key-binding (vector last-input-event))))))
9629
9630 (defun org-force-self-insert (N)
9631 "Needed to enforce self-insert under remapping."
9632 (interactive "p")
9633 (self-insert-command N))
9634
9635 (defun orgtbl-delete-backward-char (N)
9636 "Like `delete-backward-char', insert whitespace at field end in tables.
9637 When deleting backwards, in tables this function will insert whitespace in
9638 front of the next \"|\" separator, to keep the table aligned. The table will
9639 still be marked for re-alignment, because a narrow field may lead to a
9640 reduced column width."
9641 (interactive "p")
9642 (if (and (org-at-table-p)
9643 (eq N 1)
9644 (string-match "|" (buffer-substring (point-at-bol) (point)))
9645 (looking-at ".*?|"))
9646 (let ((pos (point)))
9647 (backward-delete-char N)
9648 (skip-chars-forward "^|")
9649 (insert " ")
9650 (goto-char (1- pos)))
9651 (delete-backward-char N)))
9652
9653 (defun orgtbl-delete-char (N)
9654 "Like `delete-char', but insert whitespace at field end in tables.
9655 When deleting characters, in tables this function will insert whitespace in
9656 front of the next \"|\" separator, to keep the table aligned. The table
9657 will still be marked for re-alignment, because a narrow field may lead to
9658 a reduced column width."
9659 (interactive "p")
9660 (if (and (org-at-table-p)
9661 (not (bolp))
9662 (not (= (char-after) ?|))
9663 (eq N 1))
9664 (if (looking-at ".*?|")
9665 (let ((pos (point)))
9666 (replace-match (concat
9667 (substring (match-string 0) 1 -1)
9668 " |"))
9669 (goto-char pos)))
9670 (delete-char N)))
9671
9672 ;;; Exporting
9673
9674 (defconst org-level-max 20)
9675
9676 (defun org-export-find-first-heading-line (list)
9677 "Remove all lines from LIST which are before the first headline."
9678 (let ((orig-list list)
9679 (re (concat "^" outline-regexp)))
9680 (while (and list
9681 (not (string-match re (car list))))
9682 (pop list))
9683 (or list orig-list)))
9684
9685 (defun org-skip-comments (lines)
9686 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
9687 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
9688 (re2 "^\\(\\*+\\)[ \t\n\r]")
9689 rtn line level)
9690 (while (setq line (pop lines))
9691 (cond
9692 ((and (string-match re1 line)
9693 (setq level (- (match-end 1) (match-beginning 1))))
9694 ;; Beginning of a COMMENT subtree. Skip it.
9695 (while (and (setq line (pop lines))
9696 (or (not (string-match re2 line))
9697 (> (- (match-end 1) (match-beginning 1)) level))))
9698 (setq lines (cons line lines)))
9699 ((string-match "^#" line)
9700 ;; an ordinary comment line
9701 )
9702 (t (setq rtn (cons line rtn)))))
9703 (nreverse rtn)))
9704
9705 ;; ASCII
9706
9707 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
9708 "Characters for underlining headings in ASCII export.")
9709
9710 (defconst org-html-entities
9711 '(("nbsp")
9712 ("iexcl")
9713 ("cent")
9714 ("pound")
9715 ("curren")
9716 ("yen")
9717 ("brvbar")
9718 ("sect")
9719 ("uml")
9720 ("copy")
9721 ("ordf")
9722 ("laquo")
9723 ("not")
9724 ("shy")
9725 ("reg")
9726 ("macr")
9727 ("deg")
9728 ("plusmn")
9729 ("sup2")
9730 ("sup3")
9731 ("acute")
9732 ("micro")
9733 ("para")
9734 ("middot")
9735 ("odot"."o")
9736 ("star"."*")
9737 ("cedil")
9738 ("sup1")
9739 ("ordm")
9740 ("raquo")
9741 ("frac14")
9742 ("frac12")
9743 ("frac34")
9744 ("iquest")
9745 ("Agrave")
9746 ("Aacute")
9747 ("Acirc")
9748 ("Atilde")
9749 ("Auml")
9750 ("Aring") ("AA"."&Aring;")
9751 ("AElig")
9752 ("Ccedil")
9753 ("Egrave")
9754 ("Eacute")
9755 ("Ecirc")
9756 ("Euml")
9757 ("Igrave")
9758 ("Iacute")
9759 ("Icirc")
9760 ("Iuml")
9761 ("ETH")
9762 ("Ntilde")
9763 ("Ograve")
9764 ("Oacute")
9765 ("Ocirc")
9766 ("Otilde")
9767 ("Ouml")
9768 ("times")
9769 ("Oslash")
9770 ("Ugrave")
9771 ("Uacute")
9772 ("Ucirc")
9773 ("Uuml")
9774 ("Yacute")
9775 ("THORN")
9776 ("szlig")
9777 ("agrave")
9778 ("aacute")
9779 ("acirc")
9780 ("atilde")
9781 ("auml")
9782 ("aring")
9783 ("aelig")
9784 ("ccedil")
9785 ("egrave")
9786 ("eacute")
9787 ("ecirc")
9788 ("euml")
9789 ("igrave")
9790 ("iacute")
9791 ("icirc")
9792 ("iuml")
9793 ("eth")
9794 ("ntilde")
9795 ("ograve")
9796 ("oacute")
9797 ("ocirc")
9798 ("otilde")
9799 ("ouml")
9800 ("divide")
9801 ("oslash")
9802 ("ugrave")
9803 ("uacute")
9804 ("ucirc")
9805 ("uuml")
9806 ("yacute")
9807 ("thorn")
9808 ("yuml")
9809 ("fnof")
9810 ("Alpha")
9811 ("Beta")
9812 ("Gamma")
9813 ("Delta")
9814 ("Epsilon")
9815 ("Zeta")
9816 ("Eta")
9817 ("Theta")
9818 ("Iota")
9819 ("Kappa")
9820 ("Lambda")
9821 ("Mu")
9822 ("Nu")
9823 ("Xi")
9824 ("Omicron")
9825 ("Pi")
9826 ("Rho")
9827 ("Sigma")
9828 ("Tau")
9829 ("Upsilon")
9830 ("Phi")
9831 ("Chi")
9832 ("Psi")
9833 ("Omega")
9834 ("alpha")
9835 ("beta")
9836 ("gamma")
9837 ("delta")
9838 ("epsilon")
9839 ("varepsilon"."&epsilon;")
9840 ("zeta")
9841 ("eta")
9842 ("theta")
9843 ("iota")
9844 ("kappa")
9845 ("lambda")
9846 ("mu")
9847 ("nu")
9848 ("xi")
9849 ("omicron")
9850 ("pi")
9851 ("rho")
9852 ("sigmaf") ("varsigma"."&sigmaf;")
9853 ("sigma")
9854 ("tau")
9855 ("upsilon")
9856 ("phi")
9857 ("chi")
9858 ("psi")
9859 ("omega")
9860 ("thetasym") ("vartheta"."&thetasym;")
9861 ("upsih")
9862 ("piv")
9863 ("bull") ("bullet"."&bull;")
9864 ("hellip") ("dots"."&hellip;")
9865 ("prime")
9866 ("Prime")
9867 ("oline")
9868 ("frasl")
9869 ("weierp")
9870 ("image")
9871 ("real")
9872 ("trade")
9873 ("alefsym")
9874 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
9875 ("uarr") ("uparrow"."&uarr;")
9876 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
9877 ("darr")("downarrow"."&darr;")
9878 ("harr") ("leftrightarrow"."&harr;")
9879 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
9880 ("lArr") ("Leftarrow"."&lArr;")
9881 ("uArr") ("Uparrow"."&uArr;")
9882 ("rArr") ("Rightarrow"."&rArr;")
9883 ("dArr") ("Downarrow"."&dArr;")
9884 ("hArr") ("Leftrightarrow"."&hArr;")
9885 ("forall")
9886 ("part") ("partial"."&part;")
9887 ("exist") ("exists"."&exist;")
9888 ("empty") ("emptyset"."&empty;")
9889 ("nabla")
9890 ("isin") ("in"."&isin;")
9891 ("notin")
9892 ("ni")
9893 ("prod")
9894 ("sum")
9895 ("minus")
9896 ("lowast") ("ast"."&lowast;")
9897 ("radic")
9898 ("prop") ("proptp"."&prop;")
9899 ("infin") ("infty"."&infin;")
9900 ("ang") ("angle"."&ang;")
9901 ("and") ("vee"."&and;")
9902 ("or") ("wedge"."&or;")
9903 ("cap")
9904 ("cup")
9905 ("int")
9906 ("there4")
9907 ("sim")
9908 ("cong") ("simeq"."&cong;")
9909 ("asymp")("approx"."&asymp;")
9910 ("ne") ("neq"."&ne;")
9911 ("equiv")
9912 ("le")
9913 ("ge")
9914 ("sub") ("subset"."&sub;")
9915 ("sup") ("supset"."&sup;")
9916 ("nsub")
9917 ("sube")
9918 ("supe")
9919 ("oplus")
9920 ("otimes")
9921 ("perp")
9922 ("sdot") ("cdot"."&sdot;")
9923 ("lceil")
9924 ("rceil")
9925 ("lfloor")
9926 ("rfloor")
9927 ("lang")
9928 ("rang")
9929 ("loz") ("Diamond"."&loz;")
9930 ("spades") ("spadesuit"."&spades;")
9931 ("clubs") ("clubsuit"."&clubs;")
9932 ("hearts") ("diamondsuit"."&hearts;")
9933 ("diams") ("diamondsuit"."&diams;")
9934 ("quot")
9935 ("amp")
9936 ("lt")
9937 ("gt")
9938 ("OElig")
9939 ("oelig")
9940 ("Scaron")
9941 ("scaron")
9942 ("Yuml")
9943 ("circ")
9944 ("tilde")
9945 ("ensp")
9946 ("emsp")
9947 ("thinsp")
9948 ("zwnj")
9949 ("zwj")
9950 ("lrm")
9951 ("rlm")
9952 ("ndash")
9953 ("mdash")
9954 ("lsquo")
9955 ("rsquo")
9956 ("sbquo")
9957 ("ldquo")
9958 ("rdquo")
9959 ("bdquo")
9960 ("dagger")
9961 ("Dagger")
9962 ("permil")
9963 ("lsaquo")
9964 ("rsaquo")
9965 ("euro")
9966
9967 ("arccos"."arccos")
9968 ("arcsin"."arcsin")
9969 ("arctan"."arctan")
9970 ("arg"."arg")
9971 ("cos"."cos")
9972 ("cosh"."cosh")
9973 ("cot"."cot")
9974 ("coth"."coth")
9975 ("csc"."csc")
9976 ("deg"."deg")
9977 ("det"."det")
9978 ("dim"."dim")
9979 ("exp"."exp")
9980 ("gcd"."gcd")
9981 ("hom"."hom")
9982 ("inf"."inf")
9983 ("ker"."ker")
9984 ("lg"."lg")
9985 ("lim"."lim")
9986 ("liminf"."liminf")
9987 ("limsup"."limsup")
9988 ("ln"."ln")
9989 ("log"."log")
9990 ("max"."max")
9991 ("min"."min")
9992 ("Pr"."Pr")
9993 ("sec"."sec")
9994 ("sin"."sin")
9995 ("sinh"."sinh")
9996 ("sup"."sup")
9997 ("tan"."tan")
9998 ("tanh"."tanh")
9999 )
10000 "Entities for TeX->HTML translation.
10001 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
10002 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
10003 In that case, \"\\ent\" will be translated to \"&other;\".
10004 The list contains HTML entities for Latin-1, Greek and other symbols.
10005 It is supplemented by a number of commonly used TeX macros with appropriate
10006 translations. There is currently no way for users to extend this.")
10007
10008 (defvar org-last-level nil) ; dynamically scoped variable
10009
10010 (defun org-export-as-ascii (arg)
10011 "Export the outline as a pretty ASCII file.
10012 If there is an active region, export only the region.
10013 The prefix ARG specifies how many levels of the outline should become
10014 underlined headlines. The default is 3."
10015 (interactive "P")
10016 (setq-default org-todo-line-regexp org-todo-line-regexp)
10017 (let* ((region
10018 (buffer-substring
10019 (if (org-region-active-p) (region-beginning) (point-min))
10020 (if (org-region-active-p) (region-end) (point-max))))
10021 (lines (org-export-find-first-heading-line
10022 (org-skip-comments (org-split-string region "[\r\n]"))))
10023 (org-startup-with-deadline-check nil)
10024 (level 0) line txt
10025 (umax nil)
10026 (case-fold-search nil)
10027 (filename (concat (file-name-sans-extension (buffer-file-name))
10028 ".txt"))
10029 (buffer (find-file-noselect filename))
10030 (levels-open (make-vector org-level-max nil))
10031 (date (format-time-string "%Y/%m/%d" (current-time)))
10032 (time (format-time-string "%X" (current-time)))
10033 (author user-full-name)
10034 (title (buffer-name))
10035 (options nil)
10036 (email user-mail-address)
10037 (language org-export-default-language)
10038 (text nil)
10039 (todo nil)
10040 (lang-words nil))
10041
10042 (setq org-last-level 1)
10043 (org-init-section-numbers)
10044
10045 (find-file-noselect filename)
10046
10047 ;; Search for the export key lines
10048 (org-parse-key-lines)
10049
10050 (setq lang-words (or (assoc language org-export-language-setup)
10051 (assoc "en" org-export-language-setup)))
10052 (if org-export-ascii-show-new-buffer
10053 (switch-to-buffer-other-window buffer)
10054 (set-buffer buffer))
10055 (erase-buffer)
10056 (fundamental-mode)
10057 (if options (org-parse-export-options options))
10058 (setq umax (if arg (prefix-numeric-value arg)
10059 org-export-headline-levels))
10060
10061 ;; File header
10062 (if title (org-insert-centered title ?=))
10063 (insert "\n")
10064 (if (or author email)
10065 (insert (concat (nth 1 lang-words) ": " (or author "")
10066 (if email (concat " <" email ">") "")
10067 "\n")))
10068 (if (and date time)
10069 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10070 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10071
10072 (insert "\n\n")
10073
10074 (if org-export-with-toc
10075 (progn
10076 (insert (nth 3 lang-words) "\n"
10077 (make-string (length (nth 3 lang-words)) ?=) "\n")
10078 (mapcar '(lambda (line)
10079 (if (string-match org-todo-line-regexp
10080 line)
10081 ;; This is a headline
10082 (progn
10083 (setq level (- (match-end 1) (match-beginning 1))
10084 txt (match-string 3 line)
10085 todo
10086 (or (and (match-beginning 2)
10087 (not (equal (match-string 2 line)
10088 org-done-string)))
10089 ; TODO, not DONE
10090 (and (= level umax)
10091 (org-search-todo-below
10092 line lines level))))
10093 (setq txt (org-html-expand-for-ascii txt))
10094
10095 (if org-export-with-section-numbers
10096 (setq txt (concat (org-section-number level)
10097 " " txt)))
10098 (if (<= level umax)
10099 (progn
10100 (insert
10101 (make-string (* (1- level) 4) ?\ )
10102 (format (if todo "%s (*)\n" "%s\n") txt))
10103 (setq org-last-level level))
10104 ))))
10105 lines)))
10106
10107 (org-init-section-numbers)
10108 (while (setq line (pop lines))
10109 ;; Remove the quoted HTML tags.
10110 (setq line (org-html-expand-for-ascii line))
10111 (cond
10112 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10113 ;; a Headline
10114 (setq level (- (match-end 1) (match-beginning 1))
10115 txt (match-string 2 line))
10116 (org-ascii-level-start level txt umax))
10117 (t (insert line "\n"))))
10118 (normal-mode)
10119 (save-buffer)
10120 (goto-char (point-min))))
10121
10122 (defun org-search-todo-below (line lines level)
10123 "Search the subtree below LINE for any TODO entries."
10124 (let ((rest (cdr (memq line lines)))
10125 (re org-todo-line-regexp)
10126 line lv todo)
10127 (catch 'exit
10128 (while (setq line (pop rest))
10129 (if (string-match re line)
10130 (progn
10131 (setq lv (- (match-end 1) (match-beginning 1))
10132 todo (and (match-beginning 2)
10133 (not (equal (match-string 2 line)
10134 org-done-string))))
10135 ; TODO, not DONE
10136 (if (<= lv level) (throw 'exit nil))
10137 (if todo (throw 'exit t))))))))
10138
10139 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10140 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10141 (defun org-html-expand-for-ascii (line)
10142 "Handle quoted HTML for ASCII export."
10143 (if org-export-html-expand
10144 (while (string-match "@<[^<>\n]*>" line)
10145 ;; We just remove the tags for now.
10146 (setq line (replace-match "" nil nil line))))
10147 line)
10148
10149 (defun org-insert-centered (s &optional underline)
10150 "Insert the string S centered and underline it with character UNDERLINE."
10151 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
10152 (insert (make-string ind ?\ ) s "\n")
10153 (if underline
10154 (insert (make-string ind ?\ )
10155 (make-string (length s) underline)
10156 "\n"))))
10157
10158 (defun org-ascii-level-start (level title umax)
10159 "Insert a new level in ASCII export."
10160 (let (char)
10161 (if (> level umax)
10162 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10163 (if (or (not (equal (char-before) ?\n))
10164 (not (equal (char-before (1- (point))) ?\n)))
10165 (insert "\n"))
10166 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10167 (if org-export-with-section-numbers
10168 (setq title (concat (org-section-number level) " " title)))
10169 (insert title "\n" (make-string (string-width title) char) "\n"))))
10170
10171 (defun org-export-copy-visible ()
10172 "Copy the visible part of the buffer to another buffer, for printing.
10173 Also removes the first line of the buffer if it specifies a mode,
10174 and all options lines."
10175 (interactive)
10176 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
10177 ".txt"))
10178 (buffer (find-file-noselect filename))
10179 (ore (concat
10180 (org-make-options-regexp
10181 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10182 "STARTUP" "ARCHIVE"
10183 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10184 (if org-noutline-p "\\(\n\\|$\\)" "")))
10185 s e)
10186 (with-current-buffer buffer
10187 (erase-buffer)
10188 (text-mode))
10189 (save-excursion
10190 (setq s (goto-char (point-min)))
10191 (while (not (= (point) (point-max)))
10192 (goto-char (org-find-invisible))
10193 (append-to-buffer buffer s (point))
10194 (setq s (goto-char (org-find-visible)))))
10195 (switch-to-buffer-other-window buffer)
10196 (newline)
10197 (goto-char (point-min))
10198 (if (looking-at ".*-\\*- mode:.*\n")
10199 (replace-match ""))
10200 (while (re-search-forward ore nil t)
10201 (replace-match ""))
10202 (goto-char (point-min))))
10203
10204 (defun org-find-visible ()
10205 (if (featurep 'noutline)
10206 (let ((s (point)))
10207 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10208 (get-char-property s 'invisible)))
10209 s)
10210 (skip-chars-forward "^\n")
10211 (point)))
10212 (defun org-find-invisible ()
10213 (if (featurep 'noutline)
10214 (let ((s (point)))
10215 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10216 (not (get-char-property s 'invisible))))
10217 s)
10218 (skip-chars-forward "^\r")
10219 (point)))
10220
10221 ;; HTML
10222
10223 (defun org-get-current-options ()
10224 "Return a string with current options as keyword options.
10225 Does include HTML export options as well as TODO and CATEGORY stuff."
10226 (format
10227 "#+TITLE: %s
10228 #+AUTHOR: %s
10229 #+EMAIL: %s
10230 #+LANGUAGE: %s
10231 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10232 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10233 #+CATEGORY: %s
10234 #+SEQ_TODO: %s
10235 #+TYP_TODO: %s
10236 #+STARTUP: %s %s
10237 #+ARCHIVE: %s
10238 "
10239 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10240 org-export-headline-levels
10241 org-export-with-section-numbers
10242 org-export-with-toc
10243 org-export-preserve-breaks
10244 org-export-html-expand
10245 org-export-with-fixed-width
10246 org-export-with-tables
10247 org-export-with-sub-superscripts
10248 org-export-with-emphasize
10249 org-export-with-TeX-macros
10250 (file-name-nondirectory (buffer-file-name))
10251 (if (equal org-todo-interpretation 'sequence)
10252 (mapconcat 'identity org-todo-keywords " ")
10253 "TODO FEEDBACK VERIFY DONE")
10254 (if (equal org-todo-interpretation 'type)
10255 (mapconcat 'identity org-todo-keywords " ")
10256 "Me Jason Marie DONE")
10257 (cdr (assoc org-startup-folded
10258 '((nil . "nofold")(t . "fold")(content . "content"))))
10259 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10260 org-archive-location
10261 ))
10262
10263 (defun org-insert-export-options-template ()
10264 "Insert into the buffer a template with information for exporting."
10265 (interactive)
10266 (if (not (bolp)) (newline))
10267 (let ((s (org-get-current-options)))
10268 (and (string-match "#\\+CATEGORY" s)
10269 (setq s (substring s 0 (match-beginning 0))))
10270 (insert s)))
10271
10272 (defun org-toggle-fixed-width-section (arg)
10273 "Toggle the fixed-width export.
10274 If there is no active region, the QUOTE keyword at the current headline is
10275 inserted or removed. When present, it causes the text between this headline
10276 and the next to be exported as fixed-width text, and unmodified.
10277 If there is an active region, this command adds or removes a colon as the
10278 first character of this line. If the first character of a line is a colon,
10279 this line is also exported in fixed-width font."
10280 (interactive "P")
10281 (let* ((cc 0)
10282 (regionp (org-region-active-p))
10283 (beg (if regionp (region-beginning) (point)))
10284 (end (if regionp (region-end)))
10285 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10286 (re "[ \t]*\\(:\\)")
10287 off)
10288 (if regionp
10289 (save-excursion
10290 (goto-char beg)
10291 (setq cc (current-column))
10292 (beginning-of-line 1)
10293 (setq off (looking-at re))
10294 (while (> nlines 0)
10295 (setq nlines (1- nlines))
10296 (beginning-of-line 1)
10297 (cond
10298 (arg
10299 (move-to-column cc t)
10300 (insert ":\n")
10301 (forward-line -1))
10302 ((and off (looking-at re))
10303 (replace-match "" t t nil 1))
10304 ((not off) (move-to-column cc t) (insert ":")))
10305 (forward-line 1)))
10306 (save-excursion
10307 (org-back-to-heading)
10308 (if (looking-at (concat outline-regexp
10309 "\\( +\\<" org-quote-string "\\>\\)"))
10310 (replace-match "" t t nil 1)
10311 (if (looking-at outline-regexp)
10312 (progn
10313 (goto-char (match-end 0))
10314 (insert " " org-quote-string))))))))
10315
10316 (defun org-export-as-html-and-open (arg)
10317 "Export the outline as HTML and immediately open it with a browser.
10318 If there is an active region, export only the region.
10319 The prefix ARG specifies how many levels of the outline should become
10320 headlines. The default is 3. Lower levels will become bulleted lists."
10321 (interactive "P")
10322 (org-export-as-html arg 'hidden)
10323 (org-open-file (buffer-file-name)))
10324
10325 (defun org-export-as-html-batch ()
10326 "Call `org-export-as-html', may be used in batch processing as
10327 emacs --batch
10328 --load=$HOME/lib/emacs/org.el
10329 --eval \"(setq org-export-headline-levels 2)\"
10330 --visit=MyFile --funcall org-export-as-html-batch"
10331 (org-export-as-html org-export-headline-levels 'hidden))
10332
10333 (defun org-export-as-html (arg &optional hidden)
10334 "Export the outline as a pretty HTML file.
10335 If there is an active region, export only the region.
10336 The prefix ARG specifies how many levels of the outline should become
10337 headlines. The default is 3. Lower levels will become bulleted lists."
10338 (interactive "P")
10339 (setq-default org-todo-line-regexp org-todo-line-regexp)
10340 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
10341 (setq-default org-done-string org-done-string)
10342 (let* ((style org-export-html-style)
10343 (region-p (org-region-active-p))
10344 (region
10345 (buffer-substring
10346 (if region-p (region-beginning) (point-min))
10347 (if region-p (region-end) (point-max))))
10348 (all_lines
10349 (org-skip-comments (org-split-string region "[\r\n]")))
10350 (lines (org-export-find-first-heading-line all_lines))
10351 (level 0) (line "") (origline "") txt todo
10352 (umax nil)
10353 (filename (concat (file-name-sans-extension (buffer-file-name))
10354 ".html"))
10355 (buffer (find-file-noselect filename))
10356 (levels-open (make-vector org-level-max nil))
10357 (date (format-time-string "%Y/%m/%d" (current-time)))
10358 (time (format-time-string "%X" (current-time)))
10359 (author user-full-name)
10360 (title (buffer-name))
10361 (options nil)
10362 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
10363 (inquote nil)
10364 (infixed nil)
10365 (in-local-list nil)
10366 (local-list-num nil)
10367 (local-list-indent nil)
10368 (llt org-plain-list-ordered-item-terminator)
10369 (email user-mail-address)
10370 (language org-export-default-language)
10371 (text nil)
10372 (lang-words nil)
10373 (head-count 0) cnt
10374 (start 0)
10375 ;; FIXME: The following returns always nil under XEmacs
10376 (coding-system (and (fboundp 'coding-system-get)
10377 (boundp 'buffer-file-coding-system)
10378 buffer-file-coding-system))
10379 (coding-system-for-write (or coding-system coding-system-for-write))
10380 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
10381 (charset (and coding-system
10382 (coding-system-get coding-system 'mime-charset)))
10383 table-open type
10384 table-buffer table-orig-buffer
10385 ind start-is-num starter
10386 )
10387 (message "Exporting...")
10388
10389 (setq org-last-level 1)
10390 (org-init-section-numbers)
10391
10392 ;; Search for the export key lines
10393 (org-parse-key-lines)
10394 (setq lang-words (or (assoc language org-export-language-setup)
10395 (assoc "en" org-export-language-setup)))
10396
10397 ;; Switch to the output buffer
10398 (if (or hidden (not org-export-html-show-new-buffer))
10399 (set-buffer buffer)
10400 (switch-to-buffer-other-window buffer))
10401 (erase-buffer)
10402 (fundamental-mode)
10403 (let ((case-fold-search nil))
10404 (if options (org-parse-export-options options))
10405 (setq umax (if arg (prefix-numeric-value arg)
10406 org-export-headline-levels))
10407
10408 ;; File header
10409 (insert (format
10410 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
10411 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
10412 <html lang=\"%s\"><head>
10413 <title>%s</title>
10414 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
10415 <meta name=generator content=\"Org-mode\">
10416 <meta name=generated content=\"%s %s\">
10417 <meta name=author content=\"%s\">
10418 %s
10419 </head><body>
10420 "
10421 language (org-html-expand title) (or charset "iso-8859-1")
10422 date time author style))
10423 (if title (insert (concat "<H1 class=\"title\">"
10424 (org-html-expand title) "</H1>\n")))
10425 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
10426 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
10427 email "&gt;</a>\n")))
10428 (if (or author email) (insert "<br>\n"))
10429 (if (and date time) (insert (concat (nth 2 lang-words) ": "
10430 date " " time "<br>\n")))
10431 (if text (insert (concat "<p>\n" (org-html-expand text))))
10432 (if org-export-with-toc
10433 (progn
10434 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
10435 (insert "<ul>\n")
10436 (mapcar '(lambda (line)
10437 (if (string-match org-todo-line-regexp line)
10438 ;; This is a headline
10439 (progn
10440 (setq level (- (match-end 1) (match-beginning 1))
10441 txt (save-match-data
10442 (org-html-expand
10443 (match-string 3 line)))
10444 todo
10445 (or (and (match-beginning 2)
10446 (not (equal (match-string 2 line)
10447 org-done-string)))
10448 ; TODO, not DONE
10449 (and (= level umax)
10450 (org-search-todo-below
10451 line lines level))))
10452 (if org-export-with-section-numbers
10453 (setq txt (concat (org-section-number level)
10454 " " txt)))
10455 (if (<= level umax)
10456 (progn
10457 (setq head-count (+ head-count 1))
10458 (if (> level org-last-level)
10459 (progn
10460 (setq cnt (- level org-last-level))
10461 (while (>= (setq cnt (1- cnt)) 0)
10462 (insert "<ul>"))
10463 (insert "\n")))
10464 (if (< level org-last-level)
10465 (progn
10466 (setq cnt (- org-last-level level))
10467 (while (>= (setq cnt (1- cnt)) 0)
10468 (insert "</ul>"))
10469 (insert "\n")))
10470 (insert
10471 (format
10472 (if todo
10473 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
10474 "<li><a href=\"#sec-%d\">%s</a>\n")
10475 head-count txt))
10476 (setq org-last-level level))
10477 ))))
10478 lines)
10479 (while (> org-last-level 0)
10480 (setq org-last-level (1- org-last-level))
10481 (insert "</ul>\n"))
10482 ))
10483 (setq head-count 0)
10484 (org-init-section-numbers)
10485
10486 (while (setq line (pop lines) origline line)
10487 (catch 'nextline
10488
10489 ;; end of quote section?
10490 (when (and inquote (string-match "^\\*+" line))
10491 (insert "</pre>\n")
10492 (setq inquote nil))
10493 ;; inside a quote section?
10494 (when inquote
10495 (insert (org-html-protect line) "\n")
10496 (throw 'nextline nil))
10497
10498 ;; verbatim lines
10499 (when (and org-export-with-fixed-width
10500 (string-match "^[ \t]*:\\(.*\\)" line))
10501 (when (not infixed)
10502 (setq infixed t)
10503 (insert "<pre>\n"))
10504 (insert (org-html-protect (match-string 1 line)) "\n")
10505 (when (and lines
10506 (not (string-match "^[ \t]*\\(:.*\\)"
10507 (car lines))))
10508 (setq infixed nil)
10509 (insert "</pre>\n"))
10510 (throw 'nextline nil))
10511
10512 ;; Protect the links
10513 (setq start 0)
10514 (while (string-match org-link-maybe-angles-regexp line start)
10515 (setq start (match-end 0))
10516 (setq line (replace-match
10517 (concat "\000" (match-string 1 line) "\000")
10518 t t line)))
10519
10520 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
10521 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
10522 (setq line (org-html-expand line))
10523
10524 ;; Format the links
10525 (setq start 0)
10526 (while (string-match org-protected-link-regexp line start)
10527 (setq start (- (match-end 0) 2))
10528 (setq type (match-string 1 line))
10529 (cond
10530 ((member type '("http" "https" "ftp" "mailto" "news"))
10531 ;; standard URL
10532 (setq line (replace-match
10533 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
10534 "<a href=\"\\1:\\2\">\\1:\\2</a>"
10535 nil nil line)))
10536 ((string= type "file")
10537 ;; FILE link
10538 (let* ((filename (match-string 2 line))
10539 (abs-p (file-name-absolute-p filename))
10540 (thefile (if abs-p (expand-file-name filename) filename))
10541 (thefile (save-match-data
10542 (if (string-match ":[0-9]+$" thefile)
10543 (replace-match "" t t thefile)
10544 thefile)))
10545 (file-is-image-p
10546 (save-match-data
10547 (string-match (org-image-file-name-regexp) thefile))))
10548 (setq line (replace-match
10549 (if (and org-export-html-inline-images
10550 file-is-image-p)
10551 (concat "<img src=\"" thefile "\"/>")
10552 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
10553 nil nil line))))
10554
10555 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
10556 (setq line (replace-match
10557 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
10558
10559 ;; TODO items
10560 (if (and (string-match org-todo-line-regexp line)
10561 (match-beginning 2))
10562 (if (equal (match-string 2 line) org-done-string)
10563 (setq line (replace-match
10564 "<span class=\"done\">\\2</span>"
10565 nil nil line 2))
10566 (setq line (replace-match "<span class=\"todo\">\\2</span>"
10567 nil nil line 2))))
10568
10569 ;; DEADLINES
10570 (if (string-match org-deadline-line-regexp line)
10571 (progn
10572 (if (save-match-data
10573 (string-match "<a href"
10574 (substring line 0 (match-beginning 0))))
10575 nil ; Don't do the replacement - it is inside a link
10576 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
10577 nil nil line 1)))))
10578 (cond
10579 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10580 ;; This is a headline
10581 (setq level (- (match-end 1) (match-beginning 1))
10582 txt (match-string 2 line))
10583 (if (<= level umax) (setq head-count (+ head-count 1)))
10584 (when in-local-list
10585 ;; Close any local lists before inserting a new header line
10586 (while local-list-num
10587 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10588 (pop local-list-num))
10589 (setq local-list-indent nil
10590 in-local-list nil))
10591 (org-html-level-start level txt umax
10592 (and org-export-with-toc (<= level umax))
10593 head-count)
10594 ;; QUOTES
10595 (when (string-match quote-re line)
10596 (insert "<pre>")
10597 (setq inquote t)))
10598
10599 ((and org-export-with-tables
10600 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
10601 (if (not table-open)
10602 ;; New table starts
10603 (setq table-open t table-buffer nil table-orig-buffer nil))
10604 ;; Accumulate lines
10605 (setq table-buffer (cons line table-buffer)
10606 table-orig-buffer (cons origline table-orig-buffer))
10607 (when (or (not lines)
10608 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
10609 (car lines))))
10610 (setq table-open nil
10611 table-buffer (nreverse table-buffer)
10612 table-orig-buffer (nreverse table-orig-buffer))
10613 (insert (org-format-table-html table-buffer table-orig-buffer))))
10614 (t
10615 ;; Normal lines
10616 (when (and (> org-export-plain-list-max-depth 0)
10617 (string-match
10618 (cond
10619 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10620 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10621 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10622 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
10623 line))
10624 (setq ind (org-get-string-indentation line)
10625 start-is-num (match-beginning 4)
10626 starter (if (match-beginning 2) (match-string 2 line))
10627 line (substring line (match-beginning 5)))
10628 (unless (string-match "[^ \t]" line)
10629 ;; empty line. Pretend indentation is large.
10630 (setq ind (1+ (or (car local-list-indent) 1))))
10631 (while (and in-local-list
10632 (or (and (= ind (car local-list-indent))
10633 (not starter))
10634 (< ind (car local-list-indent))))
10635 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10636 (pop local-list-num) (pop local-list-indent)
10637 (setq in-local-list local-list-indent))
10638 (cond
10639 ((and starter
10640 (or (not in-local-list)
10641 (> ind (car local-list-indent)))
10642 (< (length local-list-indent)
10643 org-export-plain-list-max-depth))
10644 ;; Start new (level of ) list
10645 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
10646 (push start-is-num local-list-num)
10647 (push ind local-list-indent)
10648 (setq in-local-list t))
10649 (starter
10650 ;; continue current list
10651 (insert "<li>\n"))))
10652 ;; Empty lines start a new paragraph. If hand-formatted lists
10653 ;; are not fully interpreted, lines starting with "-", "+", "*"
10654 ;; also start a new paragraph.
10655 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
10656 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
10657 ))
10658 (if org-export-html-with-timestamp
10659 (insert org-export-html-html-helper-timestamp))
10660 (insert "</body>\n</html>\n")
10661 (normal-mode)
10662 (save-buffer)
10663 (goto-char (point-min)))))
10664
10665 (defun org-format-table-html (lines olines)
10666 "Find out which HTML converter to use and return the HTML code."
10667 (if (string-match "^[ \t]*|" (car lines))
10668 ;; A normal org table
10669 (org-format-org-table-html lines)
10670 ;; Table made by table.el - test for spanning
10671 (let* ((hlines (delq nil (mapcar
10672 (lambda (x)
10673 (if (string-match "^[ \t]*\\+-" x) x
10674 nil))
10675 lines)))
10676 (first (car hlines))
10677 (ll (and (string-match "\\S-+" first)
10678 (match-string 0 first)))
10679 (re (concat "^[ \t]*" (regexp-quote ll)))
10680 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
10681 hlines))))
10682 (if (and (not spanning)
10683 (not org-export-prefer-native-exporter-for-tables))
10684 ;; We can use my own converter with HTML conversions
10685 (org-format-table-table-html lines)
10686 ;; Need to use the code generator in table.el, with the original text.
10687 (org-format-table-table-html-using-table-generate-source olines)))))
10688
10689 (defun org-format-org-table-html (lines)
10690 "Format a table into html."
10691 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10692 (setq lines (nreverse lines))
10693 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10694 (setq lines (nreverse lines))
10695 (let ((head (and org-export-highlight-first-table-line
10696 (delq nil (mapcar
10697 (lambda (x) (string-match "^[ \t]*|-" x))
10698 (cdr lines)))))
10699 line fields html)
10700 (setq html (concat org-export-html-table-tag "\n"))
10701 (while (setq line (pop lines))
10702 (catch 'next-line
10703 (if (string-match "^[ \t]*|-" line)
10704 (progn
10705 (setq head nil) ;; head ends here, first time around
10706 ;; ignore this line
10707 (throw 'next-line t)))
10708 ;; Break the line into fields
10709 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10710 (setq html (concat
10711 html
10712 "<tr>"
10713 (mapconcat (lambda (x)
10714 (if head
10715 (concat "<th>" x "</th>")
10716 (concat "<td>" x "</td>")))
10717 fields "")
10718 "</tr>\n"))))
10719 (setq html (concat html "</table>\n"))
10720 html))
10721
10722 (defun org-fake-empty-table-line (line)
10723 "Replace everything except \"|\" with spaces."
10724 (let ((i (length line))
10725 (newstr (copy-sequence line)))
10726 (while (> i 0)
10727 (setq i (1- i))
10728 (if (not (eq (aref newstr i) ?|))
10729 (aset newstr i ?\ )))
10730 newstr))
10731
10732 (defun org-format-table-table-html (lines)
10733 "Format a table generated by table.el into html.
10734 This conversion does *not* use `table-generate-source' from table.el.
10735 This has the advantage that Org-mode's HTML conversions can be used.
10736 But it has the disadvantage, that no cell- or row-spanning is allowed."
10737 (let (line field-buffer
10738 (head org-export-highlight-first-table-line)
10739 fields html empty)
10740 (setq html (concat org-export-html-table-tag "\n"))
10741 (while (setq line (pop lines))
10742 (setq empty "&nbsp")
10743 (catch 'next-line
10744 (if (string-match "^[ \t]*\\+-" line)
10745 (progn
10746 (if field-buffer
10747 (progn
10748 (setq html (concat
10749 html
10750 "<tr>"
10751 (mapconcat
10752 (lambda (x)
10753 (if (equal x "") (setq x empty))
10754 (if head
10755 (concat "<th>" x "</th>\n")
10756 (concat "<td>" x "</td>\n")))
10757 field-buffer "\n")
10758 "</tr>\n"))
10759 (setq head nil)
10760 (setq field-buffer nil)))
10761 ;; Ignore this line
10762 (throw 'next-line t)))
10763 ;; Break the line into fields and store the fields
10764 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10765 (if field-buffer
10766 (setq field-buffer (mapcar
10767 (lambda (x)
10768 (concat x "<br>" (pop fields)))
10769 field-buffer))
10770 (setq field-buffer fields))))
10771 (setq html (concat html "</table>\n"))
10772 html))
10773
10774 (defun org-format-table-table-html-using-table-generate-source (lines)
10775 "Format a table into html, using `table-generate-source' from table.el.
10776 This has the advantage that cell- or row-spanning is allowed.
10777 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
10778 (require 'table)
10779 (with-current-buffer (get-buffer-create " org-tmp1 ")
10780 (erase-buffer)
10781 (insert (mapconcat 'identity lines "\n"))
10782 (goto-char (point-min))
10783 (if (not (re-search-forward "|[^+]" nil t))
10784 (error "Error processing table"))
10785 (table-recognize-table)
10786 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
10787 (table-generate-source 'html " org-tmp2 ")
10788 (set-buffer " org-tmp2 ")
10789 (buffer-substring (point-min) (point-max))))
10790
10791 (defun org-html-protect (s)
10792 ;; convert & to &amp;, < to &lt; and > to &gt;
10793 (let ((start 0))
10794 (while (string-match "&" s start)
10795 (setq s (replace-match "&amp;" t t s)
10796 start (1+ (match-beginning 0))))
10797 (while (string-match "<" s)
10798 (setq s (replace-match "&lt;" t t s)))
10799 (while (string-match ">" s)
10800 (setq s (replace-match "&gt;" t t s))))
10801 s)
10802
10803 (defun org-html-expand (string)
10804 "Prepare STRING for HTML export. Applies all active conversions."
10805 ;; First check if there is a link in the line - if yes, apply conversions
10806 ;; only before the start of the link.
10807 ;; FIXME: This is no longer correct, because links now have an end.
10808 (let* ((m (string-match org-link-regexp string))
10809 (s (if m (substring string 0 m) string))
10810 (r (if m (substring string m) "")))
10811 ;; convert & to &amp;, < to &lt; and > to &gt;
10812 (setq s (org-html-protect s))
10813 (if org-export-html-expand
10814 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
10815 (setq s (replace-match "<\\1>" nil nil s))))
10816 (if org-export-with-emphasize
10817 (setq s (org-export-html-convert-emphasize s)))
10818 (if org-export-with-sub-superscripts
10819 (setq s (org-export-html-convert-sub-super s)))
10820 (if org-export-with-TeX-macros
10821 (let ((start 0) wd ass)
10822 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
10823 (setq wd (match-string 1 s))
10824 (if (setq ass (assoc wd org-html-entities))
10825 (setq s (replace-match (or (cdr ass)
10826 (concat "&" (car ass) ";"))
10827 t t s))
10828 (setq start (+ start (length wd)))))))
10829 (concat s r)))
10830
10831 (defun org-create-multibrace-regexp (left right n)
10832 "Create a regular expression which will match a balanced sexp.
10833 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
10834 as single character strings.
10835 The regexp returned will match the entire expression including the
10836 delimiters. It will also define a single group which contains the
10837 match except for the outermost delimiters. The maximum depth of
10838 stacked delimiters is N. Escaping delimiters is not possible."
10839 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
10840 (or "\\|")
10841 (re nothing)
10842 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
10843 (while (> n 1)
10844 (setq n (1- n)
10845 re (concat re or next)
10846 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
10847 (concat left "\\(" re "\\)" right)))
10848
10849 (defvar org-match-substring-regexp
10850 (concat
10851 "\\([^\\]\\)\\([_^]\\)\\("
10852 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
10853 "\\|"
10854 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
10855 "\\|"
10856 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
10857 "The regular expression matching a sub- or superscript.")
10858
10859 (defun org-export-html-convert-sub-super (string)
10860 "Convert sub- and superscripts in STRING to HTML."
10861 (let (key c)
10862 (while (string-match org-match-substring-regexp string)
10863 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
10864 (setq c (or (match-string 8 string)
10865 (match-string 6 string)
10866 (match-string 5 string)))
10867 (setq string (replace-match
10868 (concat (match-string 1 string)
10869 "<" key ">" c "</" key ">")
10870 t t string)))
10871 (while (string-match "\\\\\\([_^]\\)" string)
10872 (setq string (replace-match (match-string 1 string) t t string))))
10873 string)
10874
10875 (defun org-export-html-convert-emphasize (string)
10876 (while (string-match
10877 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
10878 string)
10879 (setq string (replace-match
10880 (concat "<b>" (match-string 3 string) "</b>")
10881 t t string 2)))
10882 (while (string-match
10883 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
10884 string)
10885 (setq string (replace-match
10886 (concat "<i>" (match-string 3 string) "</i>")
10887 t t string 2)))
10888 (while (string-match
10889 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
10890 string)
10891 (setq string (replace-match
10892 (concat "<u>" (match-string 3 string) "</u>")
10893 t t string 2)))
10894 string)
10895
10896 (defun org-parse-key-lines ()
10897 "Find the special key lines with the information for exporters."
10898 (save-excursion
10899 (goto-char 0)
10900 (let ((re (org-make-options-regexp
10901 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
10902 key)
10903 (while (re-search-forward re nil t)
10904 (setq key (match-string 1))
10905 (cond ((string-equal key "TITLE")
10906 (setq title (match-string 2)))
10907 ((string-equal key "AUTHOR")
10908 (setq author (match-string 2)))
10909 ((string-equal key "EMAIL")
10910 (setq email (match-string 2)))
10911 ((string-equal key "LANGUAGE")
10912 (setq language (match-string 2)))
10913 ((string-equal key "TEXT")
10914 (setq text (concat text "\n" (match-string 2))))
10915 ((string-equal key "OPTIONS")
10916 (setq options (match-string 2))))))))
10917
10918 (defun org-parse-export-options (s)
10919 "Parse the export options line."
10920 (let ((op '(("H" . org-export-headline-levels)
10921 ("num" . org-export-with-section-numbers)
10922 ("toc" . org-export-with-toc)
10923 ("\\n" . org-export-preserve-breaks)
10924 ("@" . org-export-html-expand)
10925 (":" . org-export-with-fixed-width)
10926 ("|" . org-export-with-tables)
10927 ("^" . org-export-with-sub-superscripts)
10928 ("*" . org-export-with-emphasize)
10929 ("TeX" . org-export-with-TeX-macros)))
10930 o)
10931 (while (setq o (pop op))
10932 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
10933 s)
10934 (set (make-local-variable (cdr o))
10935 (car (read-from-string (match-string 1 s))))))))
10936
10937 (defun org-html-level-start (level title umax with-toc head-count)
10938 "Insert a new level in HTML export."
10939 (let ((l (1+ (max level umax))))
10940 (while (<= l org-level-max)
10941 (if (aref levels-open (1- l))
10942 (progn
10943 (org-html-level-close l)
10944 (aset levels-open (1- l) nil)))
10945 (setq l (1+ l)))
10946 (if (> level umax)
10947 (progn
10948 (if (aref levels-open (1- level))
10949 (insert "<li>" title "<p>\n")
10950 (aset levels-open (1- level) t)
10951 (insert "<ul><li>" title "<p>\n")))
10952 (if org-export-with-section-numbers
10953 (setq title (concat (org-section-number level) " " title)))
10954 (setq level (+ level 1))
10955 (if with-toc
10956 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
10957 level head-count title level))
10958 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
10959
10960 (defun org-html-level-close (&rest args)
10961 "Terminate one level in HTML export."
10962 (insert "</ul>"))
10963
10964 ;; Variable holding the vector with section numbers
10965 (defvar org-section-numbers (make-vector org-level-max 0))
10966
10967 (defun org-init-section-numbers ()
10968 "Initialize the vector for the section numbers."
10969 (let* ((level -1)
10970 (numbers (nreverse (org-split-string "" "\\.")))
10971 (depth (1- (length org-section-numbers)))
10972 (i depth) number-string)
10973 (while (>= i 0)
10974 (if (> i level)
10975 (aset org-section-numbers i 0)
10976 (setq number-string (or (car numbers) "0"))
10977 (if (string-match "\\`[A-Z]\\'" number-string)
10978 (aset org-section-numbers i
10979 (- (string-to-char number-string) ?A -1))
10980 (aset org-section-numbers i (string-to-number number-string)))
10981 (pop numbers))
10982 (setq i (1- i)))))
10983
10984 (defun org-section-number (&optional level)
10985 "Return a string with the current section number.
10986 When LEVEL is non-nil, increase section numbers on that level."
10987 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
10988 (when level
10989 (when (> level -1)
10990 (aset org-section-numbers
10991 level (1+ (aref org-section-numbers level))))
10992 (setq idx (1+ level))
10993 (while (<= idx depth)
10994 (if (not (= idx 1))
10995 (aset org-section-numbers idx 0))
10996 (setq idx (1+ idx))))
10997 (setq idx 0)
10998 (while (<= idx depth)
10999 (setq n (aref org-section-numbers idx))
11000 (setq string (concat string (if (not (string= string "")) "." "")
11001 (int-to-string n)))
11002 (setq idx (1+ idx)))
11003 (save-match-data
11004 (if (string-match "\\`\\([@0]\\.\\)+" string)
11005 (setq string (replace-match "" nil nil string)))
11006 (if (string-match "\\(\\.0\\)+\\'" string)
11007 (setq string (replace-match "" nil nil string))))
11008 string))
11009
11010
11011 (defun org-export-icalendar-this-file ()
11012 "Export current file as an iCalendar file.
11013 The iCalendar file will be located in the same directory as the Org-mode
11014 file, but with extension `.ics'."
11015 (interactive)
11016 (org-export-icalendar nil (buffer-file-name)))
11017
11018 ;;;###autoload
11019 (defun org-export-icalendar-all-agenda-files ()
11020 "Export all files in `org-agenda-files' to iCalendar .ics files.
11021 Each iCalendar file will be located in the same directory as the Org-mode
11022 file, but with extension `.ics'."
11023 (interactive)
11024 (apply 'org-export-icalendar nil org-agenda-files))
11025
11026 ;;;###autoload
11027 (defun org-export-icalendar-combine-agenda-files ()
11028 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11029 The file is stored under the name `org-combined-agenda-icalendar-file'."
11030 (interactive)
11031 (apply 'org-export-icalendar t org-agenda-files))
11032
11033 (defun org-export-icalendar (combine &rest files)
11034 "Create iCalendar files for all elements of FILES.
11035 If COMBINE is non-nil, combine all calendar entries into a single large
11036 file and store it under the name `org-combined-agenda-icalendar-file'."
11037 (save-excursion
11038 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11039 (when combine
11040 (setq ical-file org-combined-agenda-icalendar-file
11041 ical-buffer (org-get-agenda-file-buffer ical-file))
11042 (set-buffer ical-buffer) (erase-buffer))
11043 (while (setq file (pop files))
11044 (catch 'nextfile
11045 (org-check-agenda-file file)
11046 (unless combine
11047 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11048 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11049 (set-buffer ical-buffer) (erase-buffer))
11050 (set-buffer (org-get-agenda-file-buffer file))
11051 (setq category (or org-category
11052 (file-name-sans-extension
11053 (file-name-nondirectory (buffer-file-name)))))
11054 (if (symbolp category) (setq category (symbol-name category)))
11055 (let ((standard-output ical-buffer))
11056 (if combine
11057 (and (not started) (setq started t)
11058 (org-start-icalendar-file org-icalendar-combined-name))
11059 (org-start-icalendar-file category))
11060 (org-print-icalendar-entries combine category)
11061 (when (or (and combine (not files)) (not combine))
11062 (org-finish-icalendar-file)
11063 (set-buffer ical-buffer)
11064 (save-buffer)
11065 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11066 (org-release-buffers org-agenda-new-buffers))))
11067
11068 (defvar org-after-save-iCalendar-file-hook nil
11069 "Hook run after an iCalendar file has been saved.
11070 The iCalendar buffer is still current when this hook is run.
11071 A good way to use this is to tell a desktop calenndar application to re-read
11072 the iCalendar file.")
11073
11074 (defun org-print-icalendar-entries (&optional combine category)
11075 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11076 When COMBINE is non nil, add the category to each line."
11077 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11078 (dts (org-ical-ts-to-string
11079 (format-time-string (cdr org-time-stamp-formats) (current-time))
11080 "DTSTART"))
11081 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11082 (save-excursion
11083 (goto-char (point-min))
11084 (while (re-search-forward org-ts-regexp nil t)
11085 (setq pos (match-beginning 0)
11086 ts (match-string 0)
11087 inc t
11088 hd (org-get-heading))
11089 (if (looking-at re2)
11090 (progn
11091 (goto-char (match-end 0))
11092 (setq ts2 (match-string 1) inc nil))
11093 (setq ts2 ts
11094 tmp (buffer-substring (max (point-min)
11095 (- pos org-ds-keyword-length))
11096 pos)
11097 deadlinep (string-match org-deadline-regexp tmp)
11098 scheduledp (string-match org-scheduled-regexp tmp)
11099 ;; donep (org-entry-is-done-p)
11100 ))
11101 (if (or (string-match org-tr-regexp hd)
11102 (string-match org-ts-regexp hd))
11103 (setq hd (replace-match "" t t hd)))
11104 (if combine
11105 (setq hd (concat hd " (category " category ")")))
11106 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11107 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11108 (princ (format "BEGIN:VEVENT
11109 %s
11110 %s
11111 SUMMARY:%s
11112 END:VEVENT\n"
11113 (org-ical-ts-to-string ts "DTSTART")
11114 (org-ical-ts-to-string ts2 "DTEND" inc)
11115 hd)))
11116 (when org-icalendar-include-todo
11117 (goto-char (point-min))
11118 (while (re-search-forward org-todo-line-regexp nil t)
11119 (setq state (match-string 1))
11120 (unless (equal state org-done-string)
11121 (setq hd (match-string 3))
11122 (if (string-match org-priority-regexp hd)
11123 (setq pri (string-to-char (match-string 2 hd))
11124 hd (concat (substring hd 0 (match-beginning 1))
11125 (substring hd (- (match-end 1)))))
11126 (setq pri org-default-priority))
11127 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11128 (- org-lowest-priority ?A))))))
11129
11130 (princ (format "BEGIN:VTODO
11131 %s
11132 SUMMARY:%s
11133 SEQUENCE:1
11134 PRIORITY:%d
11135 END:VTODO\n"
11136 dts hd pri))))))))
11137
11138 (defun org-start-icalendar-file (name)
11139 "Start an iCalendar file by inserting the header."
11140 (let ((user user-full-name)
11141 (name (or name "unknown"))
11142 (timezone (cadr (current-time-zone))))
11143 (princ
11144 (format "BEGIN:VCALENDAR
11145 VERSION:2.0
11146 X-WR-CALNAME:%s
11147 PRODID:-//%s//Emacs with Org-mode//EN
11148 X-WR-TIMEZONE:%s
11149 CALSCALE:GREGORIAN\n" name user timezone))))
11150
11151 (defun org-finish-icalendar-file ()
11152 "Finish an iCalendar file by inserting the END statement."
11153 (princ "END:VCALENDAR\n"))
11154
11155 (defun org-ical-ts-to-string (s keyword &optional inc)
11156 "Take a time string S and convert it to iCalendar format.
11157 KEYWORD is added in front, to make a complete line like DTSTART....
11158 When INC is non-nil, increase the hour by two (if time string contains
11159 a time), or the day by one (if it does not contain a time)."
11160 (let ((t1 (org-parse-time-string s 'nodefault))
11161 t2 fmt have-time time)
11162 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11163 (setq t2 t1 have-time t)
11164 (setq t2 (org-parse-time-string s)))
11165 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11166 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11167 (when inc
11168 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11169 (setq time (encode-time s mi h d m y)))
11170 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11171 (concat keyword (format-time-string fmt time))))
11172
11173
11174 ;;; Key bindings
11175
11176 ;; - Bindings in Org-mode map are currently
11177 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11178 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
11179 ;; e (?) useful from outline-mode
11180 ;; i k @ expendable from outline-mode
11181 ;; 0123456789 ! %^& ()_{} " `' free
11182
11183 ;; Make `C-c C-x' a prefix key
11184 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11185
11186 ;; TAB key with modifiers
11187 (define-key org-mode-map "\C-i" 'org-cycle)
11188 (define-key org-mode-map [(meta tab)] 'org-complete)
11189 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11190 ;; The following line is necessary under Suse GNU/Linux
11191 (unless org-xemacs-p
11192 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11193 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11194
11195 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11196 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11197 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11198 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11199 (define-key org-mode-map [(meta return)] 'org-meta-return)
11200 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11201 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11202
11203 ;; Cursor keys with modifiers
11204 (define-key org-mode-map [(meta left)] 'org-metaleft)
11205 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11206 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11207 (define-key org-mode-map [(meta right)] 'org-metaright)
11208 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11209 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11210 (define-key org-mode-map [(meta up)] 'org-metaup)
11211 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11212 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11213 (define-key org-mode-map [(meta down)] 'org-metadown)
11214 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11215 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11216
11217 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11218 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11219 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11220 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11221 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11222 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11223 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11224 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11225 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11226 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11227 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11228 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11229 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11230 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11231 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11232 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11233
11234 ;; All the other keys
11235 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11236 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11237 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11238 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11239 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11240 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11241 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11242 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11243 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11244 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11245 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11246 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11247 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11248 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11249 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11250 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11251 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11252 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11253 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11254 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11255 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11256 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11257 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
11258 (define-key org-mode-map "\C-c]" 'org-remove-file)
11259 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
11260 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
11261 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
11262 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11263 (define-key org-mode-map "\C-m" 'org-return)
11264 (define-key org-mode-map "\C-c?" 'org-table-current-column)
11265 (define-key org-mode-map "\C-c " 'org-table-blank-field)
11266 (define-key org-mode-map "\C-c+" 'org-table-sum)
11267 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
11268 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
11269 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
11270 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
11271 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11272 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
11273 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11274 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
11275 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
11276 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
11277 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
11278 ;; OPML support is only an option for the future
11279 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
11280 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
11281 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
11282 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
11283 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
11284 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11285 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
11286 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11287 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
11288 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
11289 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
11290
11291 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11292 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11293 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11294
11295 (defsubst org-table-p () (org-at-table-p))
11296
11297 (defun org-self-insert-command (N)
11298 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11299 If the cursor is in a table looking at whitespace, the whitespace is
11300 overwritten, and the table is not marked as requiring realignment."
11301 (interactive "p")
11302 (if (and (org-table-p)
11303 (or
11304 (and org-table-auto-blank-field
11305 (member last-command
11306 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11307 (org-table-blank-field))
11308 t)
11309 (eq N 1)
11310 (looking-at "[^|\n]* +|"))
11311 (let (org-table-may-need-update)
11312 (goto-char (1- (match-end 0)))
11313 (delete-backward-char 1)
11314 (goto-char (match-beginning 0))
11315 (self-insert-command N))
11316 (setq org-table-may-need-update t)
11317 (self-insert-command N)))
11318
11319 ;; FIXME:
11320 ;; The following two functions might still be optimized to trigger
11321 ;; re-alignment less frequently.
11322
11323 (defun org-delete-backward-char (N)
11324 "Like `delete-backward-char', insert whitespace at field end in tables.
11325 When deleting backwards, in tables this function will insert whitespace in
11326 front of the next \"|\" separator, to keep the table aligned. The table will
11327 still be marked for re-alignment, because a narrow field may lead to a
11328 reduced column width."
11329 (interactive "p")
11330 (if (and (org-table-p)
11331 (eq N 1)
11332 (string-match "|" (buffer-substring (point-at-bol) (point)))
11333 (looking-at ".*?|"))
11334 (let ((pos (point)))
11335 (backward-delete-char N)
11336 (skip-chars-forward "^|")
11337 (insert " ")
11338 (goto-char (1- pos)))
11339 (backward-delete-char N)))
11340
11341 (defun org-delete-char (N)
11342 "Like `delete-char', but insert whitespace at field end in tables.
11343 When deleting characters, in tables this function will insert whitespace in
11344 front of the next \"|\" separator, to keep the table aligned. The table
11345 will still be marked for re-alignment, because a narrow field may lead to
11346 a reduced column width."
11347 (interactive "p")
11348 (if (and (org-table-p)
11349 (not (bolp))
11350 (not (= (char-after) ?|))
11351 (eq N 1))
11352 (if (looking-at ".*?|")
11353 (let ((pos (point)))
11354 (replace-match (concat
11355 (substring (match-string 0) 1 -1)
11356 " |"))
11357 (goto-char pos)))
11358 (delete-char N)))
11359
11360 ;; How to do this: Measure non-white length of current string
11361 ;; If equal to column width, we should realign.
11362
11363 (defun org-remap (map &rest commands)
11364 "In MAP, remap the functions given in COMMANDS.
11365 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11366 (let (new old)
11367 (while commands
11368 (setq old (pop commands) new (pop commands))
11369 (if (fboundp 'command-remapping)
11370 (define-key map (vector 'remap old) new)
11371 (substitute-key-definition old new map global-map)))))
11372
11373 (when (eq org-enable-table-editor 'optimized)
11374 ;; If the user wants maximum table support, we need to hijack
11375 ;; some standard editing functions
11376 (org-remap org-mode-map
11377 'self-insert-command 'org-self-insert-command
11378 'delete-char 'org-delete-char
11379 'delete-backward-char 'org-delete-backward-char)
11380 (define-key org-mode-map "|" 'org-force-self-insert))
11381
11382 (defun org-shiftcursor-error ()
11383 "Throw an error because Shift-Cursor command was applied in wrong context."
11384 (error "This command is active in special context like tables, headlines or timestamps"))
11385
11386 (defun org-shifttab ()
11387 "Global visibility cycling or move to previous table field.
11388 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
11389 See the individual commands for more information."
11390 (interactive)
11391 (cond
11392 ((org-at-table-p) (org-table-previous-field))
11393 (t (org-cycle '(4)))))
11394
11395 (defun org-shiftmetaleft ()
11396 "Promote subtree or delete table column.
11397 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
11398 See the individual commands for more information."
11399 (interactive)
11400 (cond
11401 ((org-at-table-p) (org-table-delete-column))
11402 ((org-on-heading-p) (org-promote-subtree))
11403 ((org-at-item-p) (call-interactively 'org-outdent-item))
11404 (t (org-shiftcursor-error))))
11405
11406 (defun org-shiftmetaright ()
11407 "Demote subtree or insert table column.
11408 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
11409 See the individual commands for more information."
11410 (interactive)
11411 (cond
11412 ((org-at-table-p) (org-table-insert-column))
11413 ((org-on-heading-p) (org-demote-subtree))
11414 ((org-at-item-p) (call-interactively 'org-indent-item))
11415 (t (org-shiftcursor-error))))
11416
11417 (defun org-shiftmetaup (&optional arg)
11418 "Move subtree up or kill table row.
11419 Calls `org-move-subtree-up' or `org-table-kill-row' or
11420 `org-move-item-up' depending on context. See the individual commands
11421 for more information."
11422 (interactive "P")
11423 (cond
11424 ((org-at-table-p) (org-table-kill-row))
11425 ((org-on-heading-p) (org-move-subtree-up arg))
11426 ((org-at-item-p) (org-move-item-up arg))
11427 (t (org-shiftcursor-error))))
11428 (defun org-shiftmetadown (&optional arg)
11429 "Move subtree down or insert table row.
11430 Calls `org-move-subtree-down' or `org-table-insert-row' or
11431 `org-move-item-down', depending on context. See the individual
11432 commands for more information."
11433 (interactive "P")
11434 (cond
11435 ((org-at-table-p) (org-table-insert-row arg))
11436 ((org-on-heading-p) (org-move-subtree-down arg))
11437 ((org-at-item-p) (org-move-item-down arg))
11438 (t (org-shiftcursor-error))))
11439
11440 (defun org-metaleft (&optional arg)
11441 "Promote heading or move table column to left.
11442 Calls `org-do-promote' or `org-table-move-column', depending on context.
11443 With no specific context, calls the Emacs default `backward-word'.
11444 See the individual commands for more information."
11445 (interactive "P")
11446 (cond
11447 ((org-at-table-p) (org-table-move-column 'left))
11448 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
11449 (t (backward-word (prefix-numeric-value arg)))))
11450
11451 (defun org-metaright (&optional arg)
11452 "Demote subtree or move table column to right.
11453 Calls `org-do-demote' or `org-table-move-column', depending on context.
11454 With no specific context, calls the Emacs default `forward-word'.
11455 See the individual commands for more information."
11456 (interactive "P")
11457 (cond
11458 ((org-at-table-p) (org-table-move-column nil))
11459 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
11460 (t (forward-word (prefix-numeric-value arg)))))
11461
11462 (defun org-metaup (&optional arg)
11463 "Move subtree up or move table row up.
11464 Calls `org-move-subtree-up' or `org-table-move-row' or
11465 `org-move-item-up', depending on context. See the individual commands
11466 for more information."
11467 (interactive "P")
11468 (cond
11469 ((org-at-table-p) (org-table-move-row 'up))
11470 ((org-on-heading-p) (org-move-subtree-up arg))
11471 ((org-at-item-p) (org-move-item-up arg))
11472 (t (org-shiftcursor-error))))
11473
11474 (defun org-metadown (&optional arg)
11475 "Move subtree down or move table row down.
11476 Calls `org-move-subtree-down' or `org-table-move-row' or
11477 `org-move-item-down', depending on context. See the individual
11478 commands for more information."
11479 (interactive "P")
11480 (cond
11481 ((org-at-table-p) (org-table-move-row nil))
11482 ((org-on-heading-p) (org-move-subtree-down arg))
11483 ((org-at-item-p) (org-move-item-down arg))
11484 (t (org-shiftcursor-error))))
11485
11486 (defun org-shiftup (&optional arg)
11487 "Increase item in timestamp or increase priority of current item.
11488 Calls `org-timestamp-up' or `org-priority-up', depending on context.
11489 See the individual commands for more information."
11490 (interactive "P")
11491 (cond
11492 ((org-at-timestamp-p) (org-timestamp-up arg))
11493 (t (org-priority-up))))
11494
11495 (defun org-shiftdown (&optional arg)
11496 "Decrease item in timestamp or decrease priority of current item.
11497 Calls `org-timestamp-down' or `org-priority-down', depending on context.
11498 See the individual commands for more information."
11499 (interactive "P")
11500 (cond
11501 ((org-at-timestamp-p) (org-timestamp-down arg))
11502 (t (org-priority-down))))
11503
11504 (defun org-shiftright ()
11505 "Next TODO keyword or timestamp one day later, depending on context."
11506 (interactive)
11507 (cond
11508 ((org-at-timestamp-p) (org-timestamp-up-day))
11509 ((org-on-heading-p) (org-todo 'right))
11510 (t (org-shiftcursor-error))))
11511
11512 (defun org-shiftleft ()
11513 "Previous TODO keyword or timestamp one day earlier, depending on context."
11514 (interactive)
11515 (cond
11516 ((org-at-timestamp-p) (org-timestamp-down-day))
11517 ((org-on-heading-p) (org-todo 'left))
11518 (t (org-shiftcursor-error))))
11519
11520 (defun org-copy-special ()
11521 "Copy region in table or copy current subtree.
11522 Calls `org-table-copy' or `org-copy-subtree', depending on context.
11523 See the individual commands for more information."
11524 (interactive)
11525 (call-interactively
11526 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
11527
11528 (defun org-cut-special ()
11529 "Cut region in table or cut current subtree.
11530 Calls `org-table-copy' or `org-cut-subtree', depending on context.
11531 See the individual commands for more information."
11532 (interactive)
11533 (call-interactively
11534 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
11535
11536 (defun org-paste-special (arg)
11537 "Paste rectangular region into table, or past subtree relative to level.
11538 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
11539 See the individual commands for more information."
11540 (interactive "P")
11541 (if (org-at-table-p)
11542 (org-table-paste-rectangle)
11543 (org-paste-subtree arg)))
11544
11545 ;; FIXME: document tags
11546 (defun org-ctrl-c-ctrl-c (&optional arg)
11547 "Call realign table, or recognize a table.el table, or update keywords.
11548 When the cursor is inside a table created by the table.el package,
11549 activate that table. Otherwise, if the cursor is at a normal table
11550 created with org.el, re-align that table. This command works even if
11551 the automatic table editor has been turned off.
11552 If the cursor is in one of the special #+KEYWORD lines, this triggers
11553 scanning the buffer for these lines and updating the information.
11554 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
11555 (interactive "P")
11556 (let ((org-enable-table-editor t))
11557 (cond
11558 ((org-on-heading-p) (org-set-tags arg))
11559 ((org-at-table.el-p)
11560 (require 'table)
11561 (beginning-of-line 1)
11562 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
11563 (table-recognize-table))
11564 ((org-at-table-p)
11565 (org-table-maybe-eval-formula)
11566 (if arg
11567 (org-table-recalculate t)
11568 (org-table-maybe-recalculate-line))
11569 (org-table-align))
11570 ((org-at-item-p)
11571 (org-renumber-ordered-list (prefix-numeric-value arg)))
11572 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
11573 (cond
11574 ((equal (match-string 1) "TBLFM")
11575 ;; Recalculate the table before this line
11576 (save-excursion
11577 (beginning-of-line 1)
11578 (skip-chars-backward " \r\n\t")
11579 (if (org-at-table-p) (org-table-recalculate t))))
11580 (t
11581 (org-mode-restart))))
11582 ((org-region-active-p)
11583 (org-table-convert-region (region-beginning) (region-end) arg))
11584 ((condition-case nil
11585 (and (region-beginning) (region-end))
11586 (error nil))
11587 (if (y-or-n-p "Convert inactive region to table? ")
11588 (org-table-convert-region (region-beginning) (region-end) arg)
11589 (error "Abort")))
11590 (t (error "C-c C-c can do nothing useful at this location.")))))
11591
11592 (defun org-mode-restart ()
11593 "Restart Org-mode, to scan again for special lines.
11594 Also updates the keyword regular expressions."
11595 (interactive)
11596 (let ((org-inhibit-startup t)) (org-mode))
11597 (message "Org-mode restarted to refresh keyword and special line setup"))
11598
11599 (defun org-return ()
11600 "Goto next table row or insert a newline.
11601 Calls `org-table-next-row' or `newline', depending on context.
11602 See the individual commands for more information."
11603 (interactive)
11604 (cond
11605 ((org-at-table-p)
11606 (org-table-justify-field-maybe)
11607 (org-table-next-row))
11608 (t (newline))))
11609
11610 (defun org-meta-return (&optional arg)
11611 "Insert a new heading or wrap a region in a table.
11612 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
11613 See the individual commands for more information."
11614 (interactive "P")
11615 (cond
11616 ((org-at-table-p)
11617 (org-table-wrap-region arg))
11618 (t (org-insert-heading arg))))
11619
11620 ;;; Menu entries
11621
11622 ;; Define the Org-mode menus
11623 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
11624 '("Tbl"
11625 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
11626 ["Next Field" org-cycle (org-at-table-p)]
11627 ["Previous Field" org-shifttab (org-at-table-p)]
11628 ["Next Row" org-return (org-at-table-p)]
11629 "--"
11630 ["Blank Field" org-table-blank-field (org-at-table-p)]
11631 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
11632 "--"
11633 ("Column"
11634 ["Move Column Left" org-metaleft (org-at-table-p)]
11635 ["Move Column Right" org-metaright (org-at-table-p)]
11636 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
11637 ["Insert Column" org-shiftmetaright (org-at-table-p)])
11638 ("Row"
11639 ["Move Row Up" org-metaup (org-at-table-p)]
11640 ["Move Row Down" org-metadown (org-at-table-p)]
11641 ["Delete Row" org-shiftmetaup (org-at-table-p)]
11642 ["Insert Row" org-shiftmetadown (org-at-table-p)]
11643 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
11644 "--"
11645 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
11646 ("Rectangle"
11647 ["Copy Rectangle" org-copy-special (org-at-table-p)]
11648 ["Cut Rectangle" org-cut-special (org-at-table-p)]
11649 ["Paste Rectangle" org-paste-special (org-at-table-p)]
11650 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
11651 "--"
11652 ("Calculate"
11653 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
11654 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11655 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
11656 "--"
11657 ["Recalculate line" org-table-recalculate (org-at-table-p)]
11658 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
11659 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
11660 "--"
11661 ["Sum Column/Rectangle" org-table-sum
11662 (or (org-at-table-p) (org-region-active-p))]
11663 ["Which Column?" org-table-current-column (org-at-table-p)])
11664 ["Debug Formulas"
11665 (setq org-table-formula-debug (not org-table-formula-debug))
11666 :style toggle :selected org-table-formula-debug]
11667 "--"
11668 ["Invisible Vlines" org-table-toggle-vline-visibility
11669 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
11670 "--"
11671 ["Create" org-table-create (and (not (org-at-table-p))
11672 org-enable-table-editor)]
11673 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
11674 ["Import from File" org-table-import (not (org-at-table-p))]
11675 ["Export to File" org-table-export (org-at-table-p)]
11676 "--"
11677 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
11678
11679 (easy-menu-define org-org-menu org-mode-map "Org menu"
11680 '("Org"
11681 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
11682 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
11683 ["Sparse Tree" org-occur t]
11684 ["Show All" show-all t]
11685 "--"
11686 ["New Heading" org-insert-heading t]
11687 ("Navigate Headings"
11688 ["Up" outline-up-heading t]
11689 ["Next" outline-next-visible-heading t]
11690 ["Previous" outline-previous-visible-heading t]
11691 ["Next Same Level" outline-forward-same-level t]
11692 ["Previous Same Level" outline-backward-same-level t]
11693 "--"
11694 ["Jump" org-goto t])
11695 ("Edit Structure"
11696 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
11697 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
11698 "--"
11699 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
11700 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
11701 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
11702 "--"
11703 ["Promote Heading" org-metaleft (not (org-at-table-p))]
11704 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
11705 ["Demote Heading" org-metaright (not (org-at-table-p))]
11706 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
11707 "--"
11708 ["Archive Subtree" org-archive-subtree t])
11709 "--"
11710 ("TODO Lists"
11711 ["TODO/DONE/-" org-todo t]
11712 ["Show TODO Tree" org-show-todo-tree t]
11713 ["Global TODO list" org-todo-list t]
11714 "--"
11715 ["Set Priority" org-priority t]
11716 ["Priority Up" org-shiftup t]
11717 ["Priority Down" org-shiftdown t])
11718 ("Dates and Scheduling"
11719 ["Timestamp" org-time-stamp t]
11720 ["Timestamp (inactive)" org-time-stamp-inactive t]
11721 ("Change Date"
11722 ["1 Day Later" org-timestamp-up-day t]
11723 ["1 Day Earlier" org-timestamp-down-day t]
11724 ["1 ... Later" org-shiftup t]
11725 ["1 ... Earlier" org-shiftdown t])
11726 ["Compute Time Range" org-evaluate-time-range t]
11727 ["Schedule Item" org-schedule t]
11728 ["Deadline" org-deadline t]
11729 "--"
11730 ["Goto Calendar" org-goto-calendar t]
11731 ["Date from Calendar" org-date-from-calendar t])
11732 "--"
11733 ["Agenda Command" org-agenda t]
11734 ("File List for Agenda")
11735 ("Special views current file"
11736 ["TODO Tree" org-show-todo-tree t]
11737 ["Check Deadlines" org-check-deadlines t]
11738 ["Timeline" org-timeline t]
11739 ["Tags Tree" org-tags-sparse-tree t])
11740 "--"
11741 ("Hyperlinks"
11742 ["Store Link (Global)" org-store-link t]
11743 ["Insert Link" org-insert-link t]
11744 ["Follow Link" org-open-at-point t])
11745 "--"
11746 ("Export"
11747 ["ASCII" org-export-as-ascii t]
11748 ["Extract Visible Text" org-export-copy-visible t]
11749 ["HTML" org-export-as-html t]
11750 ["HTML and Open" org-export-as-html-and-open t]
11751 ; ["OPML" org-export-as-opml nil]
11752 "--"
11753 ["iCalendar this file" org-export-icalendar-this-file t]
11754 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
11755 :active t :keys "C-c C-x C-i"]
11756 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
11757 "--"
11758 ["Option Template" org-insert-export-options-template t]
11759 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
11760 "--"
11761 ("Documentation"
11762 ["Show Version" org-version t]
11763 ["Info Documentation" org-info t])
11764 ("Customize"
11765 ["Browse Org Group" org-customize t]
11766 "--"
11767 ["Build Full Customize Menu" org-create-customize-menu
11768 (fboundp 'customize-menu-create)])
11769 "--"
11770 ["Refresh setup" org-mode-restart t]
11771 ))
11772
11773 (defun org-info (&optional node)
11774 "Read documentation for Org-mode in the info system.
11775 With optional NODE, go directly to that node."
11776 (interactive)
11777 (require 'info)
11778 (Info-goto-node (format "(org)%s" (or node ""))))
11779
11780 (defun org-install-agenda-files-menu ()
11781 (easy-menu-change
11782 '("Org") "File List for Agenda"
11783 (append
11784 (list
11785 ["Edit File List" (customize-variable 'org-agenda-files) t]
11786 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
11787 ["Remove Current File from List" org-remove-file t]
11788 ["Cycle through agenda files" org-cycle-agenda-files t]
11789 "--")
11790 (mapcar 'org-file-menu-entry org-agenda-files))))
11791
11792 ;;; Documentation
11793
11794 (defun org-customize ()
11795 "Call the customize function with org as argument."
11796 (interactive)
11797 (customize-browse 'org))
11798
11799 (defun org-create-customize-menu ()
11800 "Create a full customization menu for Org-mode, insert it into the menu."
11801 (interactive)
11802 (if (fboundp 'customize-menu-create)
11803 (progn
11804 (easy-menu-change
11805 '("Org") "Customize"
11806 `(["Browse Org group" org-customize t]
11807 "--"
11808 ,(customize-menu-create 'org)
11809 ["Set" Custom-set t]
11810 ["Save" Custom-save t]
11811 ["Reset to Current" Custom-reset-current t]
11812 ["Reset to Saved" Custom-reset-saved t]
11813 ["Reset to Standard Settings" Custom-reset-standard t]))
11814 (message "\"Org\"-menu now contains full customization menu"))
11815 (error "Cannot expand menu (outdated version of cus-edit.el)")))
11816
11817 ;;; Miscellaneous stuff
11818
11819 (defun org-move-line-down (arg)
11820 "Move the current line down. With prefix argument, move it past ARG lines."
11821 (interactive "p")
11822 (let ((col (current-column))
11823 beg end pos)
11824 (beginning-of-line 1) (setq beg (point))
11825 (beginning-of-line 2) (setq end (point))
11826 (beginning-of-line (+ 1 arg))
11827 (setq pos (move-marker (make-marker) (point)))
11828 (insert (delete-and-extract-region beg end))
11829 (goto-char pos)
11830 (move-to-column col)))
11831
11832 (defun org-move-line-up (arg)
11833 "Move the current line up. With prefix argument, move it past ARG lines."
11834 (interactive "p")
11835 (let ((col (current-column))
11836 beg end pos)
11837 (beginning-of-line 1) (setq beg (point))
11838 (beginning-of-line 2) (setq end (point))
11839 (beginning-of-line (- arg))
11840 (setq pos (move-marker (make-marker) (point)))
11841 (insert (delete-and-extract-region beg end))
11842 (goto-char pos)
11843 (move-to-column col)))
11844
11845 ;; Paragraph filling stuff.
11846 ;; We want this to be just right, so use the full arsenal.
11847 ;; FIXME: This very likely does not work correctly for XEmacs, because the
11848 ;; filladapt package works slightly differently.
11849
11850 (defun org-set-autofill-regexps ()
11851 (interactive)
11852 ;; In the paragraph separator we include headlines, because filling
11853 ;; text in a line directly attached to a headline would otherwise
11854 ;; fill the headline as well.
11855 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
11856 ;; The paragraph starter includes hand-formatted lists.
11857 (set (make-local-variable 'paragraph-start)
11858 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
11859 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
11860 ;; But only if the user has not turned off tables or fixed-width regions
11861 (set (make-local-variable 'auto-fill-inhibit-regexp)
11862 (concat "\\*\\|#"
11863 (if (or org-enable-table-editor org-enable-fixed-width-editor)
11864 (concat
11865 "\\|[ \t]*["
11866 (if org-enable-table-editor "|" "")
11867 (if org-enable-fixed-width-editor ":" "")
11868 "]"))))
11869 ;; We use our own fill-paragraph function, to make sure that tables
11870 ;; and fixed-width regions are not wrapped. That function will pass
11871 ;; through to `fill-paragraph' when appropriate.
11872 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
11873 ;; Adaptive filling: To get full control, first make sure that
11874 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
11875 (setq adaptive-fill-regexp "\000")
11876 (setq adaptive-fill-function 'org-adaptive-fill-function))
11877
11878 (defun org-fill-paragraph (&optional justify)
11879 "Re-align a table, pass through to fill-paragraph if no table."
11880 (let ((table-p (org-at-table-p))
11881 (table.el-p (org-at-table.el-p)))
11882 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
11883 (table.el-p t) ; skip table.el tables
11884 (table-p (org-table-align) t) ; align org-mode tables
11885 (t nil)))) ; call paragraph-fill
11886
11887 ;; For reference, this is the default value of adaptive-fill-regexp
11888 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
11889
11890 (defun org-adaptive-fill-function ()
11891 "Return a fill prefix for org-mode files.
11892 In particular, this makes sure hanging paragraphs for hand-formatted lists
11893 work correctly."
11894 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
11895 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11896
11897 ;; Functions needed for Emacs/XEmacs region compatibility
11898
11899 (defun org-region-active-p ()
11900 "Is `transient-mark-mode' on and the region active?
11901 Works on both Emacs and XEmacs."
11902 (if org-ignore-region
11903 nil
11904 (if org-xemacs-p
11905 (and zmacs-regions (region-active-p))
11906 (and transient-mark-mode mark-active))))
11907
11908 (defun org-add-to-invisibility-spec (arg)
11909 "Add elements to `buffer-invisibility-spec'.
11910 See documentation for `buffer-invisibility-spec' for the kind of elements
11911 that can be added."
11912 (cond
11913 ((fboundp 'add-to-invisibility-spec)
11914 (add-to-invisibility-spec arg))
11915 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
11916 (setq buffer-invisibility-spec (list arg)))
11917 (t
11918 (setq buffer-invisibility-spec
11919 (cons arg buffer-invisibility-spec)))))
11920
11921 (defun org-remove-from-invisibility-spec (arg)
11922 "Remove elements from `buffer-invisibility-spec'."
11923 (if (fboundp 'remove-from-invisibility-spec)
11924 (remove-from-invisibility-spec arg)
11925 (if (consp buffer-invisibility-spec)
11926 (setq buffer-invisibility-spec
11927 (delete arg buffer-invisibility-spec)))))
11928
11929 (defun org-in-invisibility-spec-p (arg)
11930 "Is ARG a member of `buffer-invisibility-spec'?."
11931 (if (consp buffer-invisibility-spec)
11932 (member arg buffer-invisibility-spec)
11933 nil))
11934
11935 (defun org-image-file-name-regexp ()
11936 "Return regexp matching the file names of images."
11937 (if (fboundp 'image-file-name-regexp)
11938 (image-file-name-regexp)
11939 (let ((image-file-name-extensions
11940 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
11941 "xbm" "xpm" "pbm" "pgm" "ppm")))
11942 (concat "\\."
11943 (regexp-opt (nconc (mapcar 'upcase
11944 image-file-name-extensions)
11945 image-file-name-extensions)
11946 t)
11947 "\\'"))))
11948
11949 ;; Functions needed for compatibility with old outline.el
11950
11951 ;; The following functions capture almost the entire compatibility code
11952 ;; between the different versions of outline-mode. The only other place
11953 ;; where this is important are the font-lock-keywords. Search for
11954 ;; `org-noutline-p' to find it.
11955
11956 ;; C-a should go to the beginning of a *visible* line, also in the
11957 ;; new outline.el. I guess this should be patched into Emacs?
11958 (defun org-beginning-of-line ()
11959 "Go to the beginning of the current line. If that is invisible, continue
11960 to a visible line beginning. This makes the function of C-a more intuitive."
11961 (interactive)
11962 (beginning-of-line 1)
11963 (if (bobp)
11964 nil
11965 (backward-char 1)
11966 (if (org-invisible-p)
11967 (while (and (not (bobp)) (org-invisible-p))
11968 (backward-char 1)
11969 (beginning-of-line 1))
11970 (forward-char 1))))
11971 (when org-noutline-p
11972 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
11973
11974 (defun org-invisible-p ()
11975 "Check if point is at a character currently not visible."
11976 (if org-noutline-p
11977 ;; Early versions of noutline don't have `outline-invisible-p'.
11978 (if (fboundp 'outline-invisible-p)
11979 (outline-invisible-p)
11980 (get-char-property (point) 'invisible))
11981 (save-excursion
11982 (skip-chars-backward "^\r\n")
11983 (equal (char-before) ?\r))))
11984
11985 (defun org-back-to-heading (&optional invisible-ok)
11986 "Move to previous heading line, or beg of this line if it's a heading.
11987 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
11988 (if org-noutline-p
11989 (outline-back-to-heading invisible-ok)
11990 (if (looking-at outline-regexp)
11991 t
11992 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
11993 outline-regexp)
11994 nil t)
11995 (if invisible-ok
11996 (progn (goto-char (match-end 1))
11997 (looking-at outline-regexp)))
11998 (error "Before first heading")))))
11999
12000 (defun org-on-heading-p (&optional invisible-ok)
12001 "Return t if point is on a (visible) heading line.
12002 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12003 (if org-noutline-p
12004 (outline-on-heading-p 'invisible-ok)
12005 (save-excursion
12006 (skip-chars-backward "^\n\r")
12007 (and (looking-at outline-regexp)
12008 (or invisible-ok
12009 (bobp)
12010 (equal (char-before) ?\n))))))
12011
12012 (defun org-up-heading-all (arg)
12013 "Move to the heading line of which the present line is a subheading.
12014 This function considers both visible and invisible heading lines.
12015 With argument, move up ARG levels."
12016 (if org-noutline-p
12017 (if (fboundp 'outline-up-heading-all)
12018 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12019 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12020 (org-back-to-heading t)
12021 (looking-at outline-regexp)
12022 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12023 (error "Cannot move up %d levels" arg)
12024 (re-search-backward
12025 (concat "[\n\r]" (regexp-quote
12026 (make-string (- (match-end 0) (match-beginning 0) arg)
12027 ?*))
12028 "[^*]"))
12029 (forward-char 1))))
12030
12031 (defun org-show-hidden-entry ()
12032 "Show an entry where even the heading is hidden."
12033 (save-excursion
12034 (if (not org-noutline-p)
12035 (progn
12036 (org-back-to-heading t)
12037 (org-flag-heading nil)))
12038 (org-show-entry)))
12039
12040 (defun org-check-occur-regexp (regexp)
12041 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12042 Of course, only for the old outline mode."
12043 (if org-noutline-p
12044 regexp
12045 (if (string-match "^\\^" regexp)
12046 (concat "[\n\r]" (substring regexp 1))
12047 regexp)))
12048
12049 (defun org-flag-heading (flag &optional entry)
12050 "Flag the current heading. FLAG non-nil means make invisible.
12051 When ENTRY is non-nil, show the entire entry."
12052 (save-excursion
12053 (org-back-to-heading t)
12054 (if (not org-noutline-p)
12055 ;; Make the current headline visible
12056 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12057 ;; Check if we should show the entire entry
12058 (if entry
12059 (progn
12060 (org-show-entry)
12061 (save-excursion ;; FIXME: Is this the fix for points in the -|
12062 ;; middle of text? |
12063 (and (outline-next-heading) ;; |
12064 (org-flag-heading nil)))) ; show the next heading _|
12065 (outline-flag-region (max 1 (1- (point)))
12066 (save-excursion (outline-end-of-heading) (point))
12067 (if org-noutline-p
12068 flag
12069 (if flag ?\r ?\n))))))
12070
12071 (defun org-show-subtree ()
12072 "Show everything after this heading at deeper levels."
12073 (outline-flag-region
12074 (point)
12075 (save-excursion
12076 (outline-end-of-subtree) (outline-next-heading) (point))
12077 (if org-noutline-p nil ?\n)))
12078
12079 (defun org-show-entry ()
12080 "Show the body directly following this heading.
12081 Show the heading too, if it is currently invisible."
12082 (interactive)
12083 (save-excursion
12084 (org-back-to-heading t)
12085 (outline-flag-region
12086 (1- (point))
12087 (save-excursion
12088 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12089 (or (match-beginning 1) (point-max)))
12090 (if org-noutline-p nil ?\n))))
12091
12092
12093 (defun org-make-options-regexp (kwds)
12094 "Make a regular expression for keyword lines."
12095 (concat
12096 (if org-noutline-p "^" "[\n\r]")
12097 "#?[ \t]*\\+\\("
12098 (mapconcat 'regexp-quote kwds "\\|")
12099 "\\):[ \t]*"
12100 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12101
12102 ;; Make `bookmark-jump' show the jump location if it was hidden.
12103 (eval-after-load "bookmark"
12104 '(if (boundp 'bookmark-after-jump-hook)
12105 ;; We can use the hook
12106 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12107 ;; Hook not available, use advice
12108 (defadvice bookmark-jump (after org-make-visible activate)
12109 "Make the position visible."
12110 (org-bookmark-jump-unhide))))
12111
12112 (defun org-bookmark-jump-unhide ()
12113 "Unhide the current position, to show the bookmark location."
12114 (and (eq major-mode 'org-mode)
12115 (or (org-invisible-p)
12116 (save-excursion (goto-char (max (point-min) (1- (point))))
12117 (org-invisible-p)))
12118 (org-show-hierarchy-above)))
12119
12120 ;;; Finish up
12121
12122 (provide 'org)
12123
12124 (run-hooks 'org-load-hook)
12125
12126 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12127 ;;; org.el ends here