]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
*** empty log message ***
[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
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 3.24
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-todo-list "org" "Multi-file todo list from Org mode" t)
63 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
64 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
65 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
66 ;;
67 ;; This setup will put all files with extension ".org" into Org-mode. As
68 ;; an alternative, make the first line of a file look like this:
69 ;;
70 ;; MY PROJECTS -*- mode: org; -*-
71 ;;
72 ;; which will select Org-mode for this buffer no matter what the file's
73 ;; name is.
74 ;;
75 ;; Documentation
76 ;; -------------
77 ;; The documentation of Org-mode can be found in the TeXInfo file. The
78 ;; distribution also contains a PDF version of it. At the homepage of
79 ;; Org-mode, you can read the same text online as HTML. There is also an
80 ;; excellent reference card made by Philip Rooke. This card can be found
81 ;; in the etc/ directory of Emacs 22.
82 ;;
83 ;; Changes:
84 ;; -------
85 ;; Version 3.24
86 ;; - Switching and item to DONE records a time stamp when the variable
87 ;; `org-log-done' is turned on. Default is off.
88 ;;
89 ;; Version 3.23
90 ;; - M-RET makes new items as well as new headings.
91 ;; - Various small bug fixes
92 ;;
93 ;; Version 3.22
94 ;; - CamelCase words link to other locations in the same file.
95 ;; - File links accept search options, to link to specific locations.
96 ;; - Plain list items can be folded with `org-cycle'. See new option
97 ;; `org-cycle-include-plain-lists'.
98 ;; - Sparse trees for specific TODO keywords through numeric prefix
99 ;; argument to `C-c C-v'.
100 ;; - Global TODO list, also for specific keywords.
101 ;; - Matches in sparse trees are highlighted (highlights disappear with
102 ;; next buffer change due to editing).
103 ;;
104 ;; Version 3.21
105 ;; - Improved CSS support for the HTML export. Thanks to Christian Egli.
106 ;; - Editing support for hand-formatted lists
107 ;; - M-S-cursor keys handle plain list items
108 ;; - C-c C-c renumbers ordered plain lists
109 ;;
110 ;; Version 3.20
111 ;; - There is finally an option to make TAB jump over horizontal lines
112 ;; in tables instead of creating a new line before that line.
113 ;; The option is `org-table-tab-jumps-over-hlines', default nil.
114 ;; - New command for sorting tables, on `C-c ^'.
115 ;; - Changes to the HTML exporter
116 ;; - hand-formatted lists are exported correctly, similar to
117 ;; markdown lists. Nested lists are possible. See the docstring
118 ;; of the variable `org-export-plain-list-max-depth'.
119 ;; - cleaned up to produce valid HTML 4.0 (transitional).
120 ;; - support for cascading style sheets.
121 ;; - New command to cycle through all agenda files, on C-,
122 ;; - C-c [ can now also be used to change the sequence of agenda files.
123 ;;
124 ;; Version 3.19
125 ;; - Bug fixes
126 ;;
127 ;; Version 3.18
128 ;; - Export of calendar information in the standard iCalendar format.
129 ;; - Some bug fixes.
130 ;;
131 ;; Version 3.17
132 ;; - HTML export specifies character set depending on coding-system.
133 ;;
134 ;; Version 3.16
135 ;; - In tables, directly after the field motion commands like TAB and RET,
136 ;; typing a character will blank the field. Can be turned off with
137 ;; variable `org-table-auto-blank-field'.
138 ;; - Inactive timestamps with `C-c !'. These do not trigger the agenda
139 ;; and are not linked to the calendar.
140 ;; - Additional key bindings to allow Org-mode to function on a tty emacs.
141 ;; - `C-c C-h' prefix key replaced by `C-c C-x', and `C-c C-x C-h' replaced
142 ;; by `C-c C-x b' (b=Browser). This was necessary to recover the
143 ;; standard meaning of C-h after a prefix key (show prefix bindings).
144 ;;
145 ;; Version 3.15
146 ;; - QUOTE keyword at the beginning of an entry causes fixed-width export
147 ;; of unmodified entry text. `C-c :' toggles this keyword.
148 ;; - New face `org-special-keyword' which is used for COMMENT, QUOTE,
149 ;; DEADLINE and SCHEDULED, and priority cookies. Default is only a weak
150 ;; color, to reduce the amount of aggressive color in the buffer.
151 ;;
152 ;; Version 3.14
153 ;; - Formulas for individual fields in table.
154 ;; - Automatic recalculation in calculating tables.
155 ;; - Named fields and columns in tables.
156 ;; - Fixed bug with calling `org-archive' several times in a row.
157 ;;
158 ;; Version 3.13
159 ;; - Efficiency improvements: Fewer table re-alignments needed.
160 ;; - New special lines in tables, for defining names for individual cells.
161 ;;
162 ;; Version 3.12
163 ;; - Tables can store formulas (one per column) and compute fields.
164 ;; Not quite like a full spreadsheet, but very powerful.
165 ;; - table.el keybinding is now `C-c ~'.
166 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
167 ;; - Small changes to keys in agenda buffer. Affected keys:
168 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
169 ;; - Bug fixes.
170 ;;
171 ;; Version 3.11
172 ;; - Links inserted with C-c C-l are now by default enclosed in angle
173 ;; brackets. See the new variable `org-link-format'.
174 ;; - ">" terminates a link, this is a way to have several links in a line.
175 ;; Both "<" and ">" are no longer allowed as characters in a link.
176 ;; - Archiving of finished tasks.
177 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
178 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
179 ;; - Compatibility problems with viper-mode fixed.
180 ;; - Improved html export of tables.
181 ;; - Various clean-up changes.
182 ;;
183 ;; Version 3.10
184 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
185 ;;
186 ;; Version 3.09
187 ;; - Time-of-day specifications in agenda are extracted and placed
188 ;; into the prefix. Timed entries can be placed into a time grid for
189 ;; day.
190 ;;
191 ;; Version 3.08
192 ;; - "|" no longer allowed as part of a link, to allow links in tables.
193 ;; - The prefix of items in the agenda buffer can be configured.
194 ;; - Cleanup.
195 ;;
196 ;; Version 3.07
197 ;; - Some folding incinsistencies removed.
198 ;; - BBDB links to company-only entries.
199 ;; - Bug fixes and global cleanup.
200 ;;
201 ;; Version 3.06
202 ;; - M-S-RET inserts a new TODO heading.
203 ;; - New startup option `content'.
204 ;; - Better visual response when TODO items in agenda change status.
205 ;; - Window positioning after visibility state changes optimized and made
206 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
207 ;;
208 ;; Version 3.05
209 ;; - Agenda entries from the diary are linked to the diary file, so
210 ;; adding and editing diary entries can be done directly from the agenda.
211 ;; - Many calendar/diary commands available directly from agenda.
212 ;; - Field copying in tables with S-RET does increment.
213 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
214 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
215 ;;
216 ;; Version 3.04
217 ;; - Table editor optimized to need fewer realignments, and to keep
218 ;; table shape when typing in fields.
219 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
220 ;; into arbitrary major modes.
221 ;; - Fixed bug with realignment in XEmacs.
222 ;; - Startup options can be set with special #+STARTUP line.
223 ;; - Heading following a match in org-occur can be suppressed.
224 ;;
225 ;; Version 3.03
226 ;; - Copyright transfer to the FSF.
227 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
228 ;; - Timeline now always contains today, and `.' jumps to it.
229 ;; - Table editor:
230 ;; - cut and paste of rectangular regions in tables
231 ;; - command to convert org-mode table to table.el table and back
232 ;; - command to treat several cells like a paragraph and fill it
233 ;; - command to convert a buffer region to a table
234 ;; - import/export tables as tab-separated files (exchange with Excel)
235 ;; - Agenda:
236 ;; - Sorting mechanism for agenda items rewritten from scratch.
237 ;; - Sorting fully configurable.
238 ;; - Entries specifying a time are sorted together.
239 ;; - Completion also covers option keywords after `#-'.
240 ;; - Bug fixes.
241 ;;
242 ;; Version 3.01
243 ;; - New reference card, thanks to Philip Rooke for creating it.
244 ;; - Single file agenda renamed to "Timeline". It no longer shows
245 ;; warnings about upcoming deadlines/overdue scheduled items.
246 ;; That functionality is now limited to the (multifile) agenda.
247 ;; - When reading a date, the calendar can be manipulated with keys.
248 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
249 ;; - Minor bug fixes and documentation improvements.
250
251 ;;; Code:
252
253 (eval-when-compile (require 'cl) (require 'calendar))
254 (require 'outline)
255 (require 'time-date)
256 (require 'easymenu)
257
258 (defvar calc-embedded-close-formula)
259 (defvar calc-embedded-open-formula)
260 (defvar font-lock-unfontify-region-function)
261
262 ;;; Customization variables
263
264 (defvar org-version "3.24"
265 "The version number of the file org.el.")
266 (defun org-version ()
267 (interactive)
268 (message "Org-mode version %s" org-version))
269
270 ;; The following two constants are for compatibility with different Emacs
271 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
272 ;; The compatibility code in org.el is based on these two constants.
273 (defconst org-xemacs-p (featurep 'xemacs)
274 "Are we running xemacs?")
275 (defconst org-noutline-p (featurep 'noutline)
276 "Are we using the new outline mode?")
277
278 (defgroup org nil
279 "Outline-based notes management and organizer "
280 :tag "Org"
281 :group 'outlines
282 :group 'hypermedia
283 :group 'calendar)
284
285 (defgroup org-startup nil
286 "Options concerning startup of Org-mode."
287 :tag "Org Startup"
288 :group 'org)
289
290 (defcustom org-CUA-compatible nil
291 "Non-nil means use alternative key bindings for S-<cursor movement>.
292 Org-mode used S-<cursor movement> for changing timestamps and priorities.
293 S-<cursor movement> is also used for example by `CUA-mode' to select text.
294 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
295 alternative bindings. Setting this variable to t will replace the following
296 keys both in Org-mode and in the Org-agenda buffer.
297
298 S-RET -> C-S-RET
299 S-up -> M-p
300 S-down -> M-n
301 S-left -> M--
302 S-right -> M-+
303
304 If you do not like the alternative keys, take a look at the variable
305 `org-disputed-keys'.
306
307 This option is only relevant at load-time of Org-mode. Changing it requires
308 a restart of Emacs to become effective."
309 :group 'org-startup
310 :type 'boolean)
311
312 (defvar org-disputed-keys
313 '((S-up [(shift up)] [(meta ?p)])
314 (S-down [(shift down)] [(meta ?n)])
315 (S-left [(shift left)] [(meta ?-)])
316 (S-right [(shift right)] [(meta ?+)])
317 (S-return [(shift return)] [(control shift return)]))
318 "Keys for which Org-mode and other modes compete.
319 This is an alist, cars are symbols for lookup, 1st element is the default key,
320 second element will be used when `org-CUA-compatible' is t.")
321
322 (defun org-key (key)
323 "Select a key according to `org-CUA-compatible'."
324 (nth (if org-CUA-compatible 2 1)
325 (or (assq key org-disputed-keys)
326 (error "Invalid Key %s in `org-key'" key))))
327
328 (defcustom org-startup-folded t
329 "Non-nil means, entering Org-mode will switch to OVERVIEW.
330 This can also be configured on a per-file basis by adding one of
331 the following lines anywhere in the buffer:
332
333 #+STARTUP: fold
334 #+STARTUP: nofold
335 #+STARTUP: content"
336 :group 'org-startup
337 :type '(choice
338 (const :tag "nofold: show all" nil)
339 (const :tag "fold: overview" t)
340 (const :tag "content: all headlines" content)))
341
342 (defcustom org-startup-truncated t
343 "Non-nil means, entering Org-mode will set `truncate-lines'.
344 This is useful since some lines containing links can be very long and
345 uninteresting. Also tables look terrible when wrapped."
346 :group 'org-startup
347 :type 'boolean)
348
349 (defcustom org-startup-with-deadline-check nil
350 "Non-nil means, entering Org-mode will run the deadline check.
351 This means, if you start editing an org file, you will get an
352 immediate reminder of any due deadlines.
353 This can also be configured on a per-file basis by adding one of
354 the following lines anywhere in the buffer:
355
356 #+STARTUP: dlcheck
357 #+STARTUP: nodlcheck"
358 :group 'org-startup
359 :type 'boolean)
360
361 (defcustom org-insert-mode-line-in-empty-file nil
362 "Non-nil means insert the first line setting Org-mode in empty files.
363 When the function `org-mode' is called interactively in an empty file, this
364 normally means that the file name does not automatically trigger Org-mode.
365 To ensure that the file will always be in Org-mode in the future, a
366 line enforcing Org-mode will be inserted into the buffer, if this option
367 has been set."
368 :group 'org-startup
369 :type 'boolean)
370
371 (defgroup org-keywords nil
372 "Options concerning TODO items in Org-mode."
373 :tag "Org Keywords"
374 :group 'org)
375
376 (defcustom org-todo-keywords '("TODO" "DONE")
377 "List of TODO entry keywords.
378 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
379 considered to mean that the entry is \"done\". All the other mean that
380 action is required, and will make the entry show up in todo lists, diaries
381 etc.
382 The command \\[org-todo] cycles an entry through these states, and an
383 additional state where no keyword is present. For details about this
384 cycling, see also the variable `org-todo-interpretation'
385 Changes become only effective after restarting Emacs."
386 :group 'org-keywords
387 :type '(repeat (string :tag "Keyword")))
388
389 (defcustom org-todo-interpretation 'sequence
390 "Controls how TODO keywords are interpreted.
391 \\<org-mode-map>Possible values are `sequence' and `type'.
392 This variable is only relevant if `org-todo-keywords' contains more than two
393 states. There are two ways how these keywords can be used:
394
395 - As a sequence in the process of working on a TODO item, for example
396 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
397 org-todo-interpretation 'sequence)
398
399 - As different types of TODO items, for example
400 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
401 org-todo-interpretation 'type)
402
403 When the states are interpreted as a sequence, \\[org-todo] always cycles
404 to the next state, in order to walk through all different states. So with
405 \\[org-todo], you turn an empty entry into the state TODO. When you started
406 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
407 later to VERIFY and finally to DONE.
408
409 When the states are interpreted as types, \\[org-todo] still cycles through
410 when it is called several times in direct succession, in order to initially
411 select the type. However, if not called immediately after a previous
412 \\[org-todo], it switches from each type directly to DONE. So with the
413 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
414 RELAXED. If you later return to this entry and press \\[org-todo] again,
415 RELAXED will not be changed REMIND, but directly to DONE.
416
417 You can create a large number of types. To initially select a
418 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
419 type with completion. Of course, you can also type the keyword
420 directly into the buffer. M-TAB completes TODO keywords at the
421 beginning of a headline."
422 :group 'org-keywords
423 :type '(choice (const sequence)
424 (const type)))
425
426 (defcustom org-default-priority ?B
427 "The default priority of TODO items.
428 This is the priority an item get if no explicit priority is given."
429 :group 'org-keywords
430 :type 'character)
431
432 (defcustom org-lowest-priority ?C
433 "The lowest priority of TODO items. A character like ?A, ?B etc."
434 :group 'org-keywords
435 :type 'character)
436
437 (defcustom org-deadline-string "DEADLINE:"
438 "String to mark deadline entries.
439 A deadline is this string, followed by a time stamp. Should be a word,
440 terminated by a colon. You can insert a schedule keyword and
441 a timestamp with \\[org-deadline].
442 Changes become only effective after restarting Emacs."
443 :group 'org-keywords
444 :type 'string)
445
446 (defcustom org-scheduled-string "SCHEDULED:"
447 "String to mark scheduled TODO entries.
448 A schedule is this string, followed by a time stamp. Should be a word,
449 terminated by a colon. You can insert a schedule keyword and
450 a timestamp with \\[org-schedule].
451 Changes become only effective after restarting Emacs."
452 :group 'org-keywords
453 :type 'string)
454
455 (defcustom org-closed-string "CLOSED:"
456 "String ued as the prefix for timestamps logging closing a TODO entry."
457 :group 'org-keywords
458 :type 'string)
459
460 (defcustom org-comment-string "COMMENT"
461 "Entries starting with this keyword will never be exported.
462 An entry can be toggled between COMMENT and normal with
463 \\[org-toggle-comment].
464 Changes become only effective after restarting Emacs."
465 :group 'org-keywords
466 :type 'string)
467
468 (defcustom org-quote-string "QUOTE"
469 "Entries starting with this keyword will be exported in fixed-width font.
470 Quoting applies only to the text in the entry following the headline, and does
471 not extend beyond the next headline, even if that is lower level.
472 An entry can be toggled between QUOTE and normal with
473 \\[org-toggle-fixed-width-section]"
474 :group 'org-keywords
475 :type 'string)
476
477 (defcustom org-after-todo-state-change-hook nil
478 "Hook which is run after the state of a TODO item was changed.
479 The new state (a string with a todo keyword, or nil) is available in the
480 Lisp variable `state'."
481 :group 'org-keywords
482 :type 'hook)
483
484 ;; Variables for pre-computed regular expressions, all buffer local
485 (defvar org-todo-kwd-priority-p nil
486 "Do TODO items have priorities?")
487 (make-variable-buffer-local 'org-todo-kwd-priority-p)
488 (defvar org-todo-kwd-max-priority nil
489 "Maximum priority of TODO items.")
490 (make-variable-buffer-local 'org-todo-kwd-max-priority)
491 (defvar org-ds-keyword-length 12
492 "Maximum length of the Deadline and SCHEDULED keywords.")
493 (make-variable-buffer-local 'org-ds-keyword-length)
494 (defvar org-done-string nil
495 "The last string in `org-todo-keywords', indicating an item is DONE.")
496 (make-variable-buffer-local 'org-done-string)
497 (defvar org-todo-regexp nil
498 "Matches any of the TODO state keywords.")
499 (make-variable-buffer-local 'org-todo-regexp)
500 (defvar org-not-done-regexp nil
501 "Matches any of the TODO state keywords except the last one.")
502 (make-variable-buffer-local 'org-not-done-regexp)
503 (defvar org-todo-line-regexp nil
504 "Matches a headline and puts TODO state into group 2 if present.")
505 (make-variable-buffer-local 'org-todo-line-regexp)
506 (defvar org-nl-done-regexp nil
507 "Matches newline followed by a headline with the DONE keyword.")
508 (make-variable-buffer-local 'org-nl-done-regexp)
509 (defvar org-looking-at-done-regexp nil
510 "Matches the DONE keyword a point.")
511 (make-variable-buffer-local 'org-looking-at-done-regexp)
512 (defvar org-deadline-regexp nil
513 "Matches the DEADLINE keyword.")
514 (make-variable-buffer-local 'org-deadline-regexp)
515 (defvar org-deadline-time-regexp nil
516 "Matches the DEADLINE keyword together with a time stamp.")
517 (make-variable-buffer-local 'org-deadline-time-regexp)
518 (defvar org-deadline-line-regexp nil
519 "Matches the DEADLINE keyword and the rest of the line.")
520 (make-variable-buffer-local 'org-deadline-line-regexp)
521 (defvar org-scheduled-regexp nil
522 "Matches the SCHEDULED keyword.")
523 (make-variable-buffer-local 'org-scheduled-regexp)
524 (defvar org-scheduled-time-regexp nil
525 "Matches the SCHEDULED keyword together with a time stamp.")
526 (make-variable-buffer-local 'org-scheduled-time-regexp)
527
528 (defvar org-category nil
529 "Variable used by org files to set a category for agenda display.
530 Such files should use a file variable to set it, for example
531
532 -*- mode: org; org-category: \"ELisp\"
533
534 or contain a special line
535
536 #+CATEGORY: ELisp
537
538 If the file does not specify a category, then file's base name
539 is used instead.")
540 (make-variable-buffer-local 'org-category)
541
542 (defgroup org-time nil
543 "Options concerning time stamps and deadlines in Org-mode."
544 :tag "Org Time"
545 :group 'org)
546
547 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
548 "Formats for `format-time-string' which are used for time stamps.
549 It is not recommended to change this constant.")
550
551
552 (defcustom org-deadline-warning-days 30
553 "No. of days before expiration during which a deadline becomes active.
554 This variable governs the display in the org file."
555 :group 'org-time
556 :type 'number)
557
558 (defcustom org-popup-calendar-for-date-prompt t
559 "Non-nil means, pop up a calendar when prompting for a date.
560 In the calendar, the date can be selected with mouse-1. However, the
561 minibuffer will also be active, and you can simply enter the date as well.
562 When nil, only the minibuffer will be available."
563 :group 'org-time
564 :type 'number)
565
566 (defcustom org-calendar-follow-timestamp-change t
567 "Non-nil means, make the calendar window follow timestamp changes.
568 When a timestamp is modified and the calendar window is visible, it will be
569 moved to the new date."
570 :group 'org-time
571 :type 'boolean)
572
573 (defcustom org-log-done nil
574 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
575 When the state of an entry is changed from nothing to TODO, remove a previous
576 closing date."
577 :group 'org-time
578 :type 'boolean)
579
580 (defgroup org-agenda nil
581 "Options concerning agenda display Org-mode."
582 :tag "Org Agenda"
583 :group 'org)
584
585 (defcustom org-agenda-files nil
586 "A list of org files for agenda/diary display.
587 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
588 \\[org-remove-file]. You can also use customize to edit the list."
589 :group 'org-agenda
590 :type '(repeat file))
591
592 (defcustom org-select-timeline-window t
593 "Non-nil means, after creating a timeline, move cursor into Timeline window.
594 When nil, cursor will remain in the current window."
595 :group 'org-agenda
596 :type 'boolean)
597
598 (defcustom org-select-agenda-window t
599 "Non-nil means, after creating an agenda, move cursor into Agenda window.
600 When nil, cursor will remain in the current window."
601 :group 'org-agenda
602 :type 'boolean)
603
604 (defcustom org-fit-agenda-window t
605 "Non-nil means, change window size of agenda to fit content."
606 :group 'org-agenda
607 :type 'boolean)
608
609 (defcustom org-agenda-show-all-dates t
610 "Non-nil means, `org-agenda' shows every day in the selected range.
611 When nil, only the days which actually have entries are shown."
612 :group 'org-agenda
613 :type 'boolean)
614
615 ;; FIXME: First day of month works only for current month because it would
616 ;; require a variable ndays treatment.
617 (defcustom org-agenda-start-on-weekday 1
618 "Non-nil means, start the overview always on the specified weekday.
619 0 Denotes Sunday, 1 denotes Monday etc.
620 When nil, always start on the current day."
621 :group 'org-agenda
622 :type '(choice (const :tag "Today" nil)
623 (const :tag "First day of month" t)
624 (number :tag "Weekday No.")))
625
626 (defcustom org-agenda-ndays 7
627 "Number of days to include in overview display."
628 :group 'org-agenda
629 :type 'number)
630
631 (defcustom org-agenda-include-all-todo t
632 "Non-nil means, the agenda will always contain all TODO entries.
633 When nil, date-less entries will only be shown if `org-agenda' is called
634 with a prefix argument.
635 When non-nil, the TODO entries will be listed at the top of the agenda, before
636 the entries for specific days."
637 :group 'org-agenda
638 :type 'boolean)
639
640 (defcustom org-agenda-include-diary nil
641 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
642 :group 'org-agenda
643 :type 'boolean)
644
645 (defcustom org-calendar-to-agenda-key [?c]
646 "The key to be installed in `calendar-mode-map' for switching to the agenda.
647 The command `org-calendar-goto-agenda' will be bound to this key. The
648 default is the character `c' because then`c' can be used to switch back and
649 force between agenda and calendar."
650 :group 'org-agenda
651 :type 'sexp)
652
653 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
654 "Sorting structure for the agenda items of a single day.
655 This is a list of symbols which will be used in sequence to determine
656 if an entry should be listed before another entry. The following
657 symbols are recognized.
658
659 time-up Put entries with time-of-day indications first, early first
660 time-down Put entries with time-of-day indications first, late first
661 category-keep Keep the default order of categories, corresponding to the
662 sequence in `org-agenda-files'.
663 category-up Sort alphabetically by category, A-Z.
664 category-down Sort alphabetically by category, Z-A.
665 priority-up Sort numerically by priority, high priority last.
666 priority-down Sort numerically by priority, high priority first.
667
668 The different possibilities will be tried in sequence, and testing stops
669 if one comparison returns a \"not-equal\". For example, the default
670 '(time-up category-keep priority-down)
671 means: Pull out all entries having a specified time of day and sort them,
672 in order to make a time schedule for the current day the first thing in the
673 agenda listing for the day. Of the entries without a time indication, keep
674 the grouped in categories, don't sort the categories, but keep them in
675 the sequence given in `org-agenda-files'. Within each category sort by
676 priority.
677
678 Leaving out `category-keep' would mean that items will be sorted across
679 categories by priority."
680 :group 'org-agenda
681 :type '(repeat
682 (choice
683 (const time-up)
684 (const time-down)
685 (const category-keep)
686 (const category-up)
687 (const category-down)
688 (const priority-up)
689 (const priority-down))))
690
691 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
692 "Format specification for the prefix of items in the agenda buffer.
693 This format works similar to a printf format, with the following meaning:
694
695 %c the category of the item, \"Diary\" for entries from the diary, or
696 as given by the CATEGORY keyword or derived from the file name.
697 %t the time-of-day specification if one applies to the entry, in the
698 format HH:MM
699 %s Scheduling/Deadline information, a short string
700
701 All specifiers work basically like the standard `%s' of printf, but may
702 contain two additional characters: A question mark just after the `%' and
703 a whitespace/punctuation character just before the final letter.
704
705 If the first character after `%' is a question mark, the entire field
706 will only be included if the corresponding value applies to the
707 current entry. This is useful for fields which should have fixed
708 width when present, but zero width when absent. For example,
709 \"%?-12t\" will result in a 12 character time field if a time of the
710 day is specified, but will completely disappear in entries which do
711 not contain a time.
712
713 If there is punctuation or whitespace character just before the final
714 format letter, this character will be appended to the field value if
715 the value is not empty. For example, the format \"%-12:c\" leads to
716 \"Diary: \" if the category is \"Diary\". If the category were be
717 empty, no additional colon would be interted.
718
719 The default value of this option is \" %-12:c%?-12t% s\", meaning:
720 - Indent the line with two space characters
721 - Give the category in a 12 chars wide field, padded with whitespace on
722 the right (because of `-'). Append a colon if there is a category
723 (because of `:').
724 - If there is a time-of-day, put it into a 12 chars wide field. If no
725 time, don't put in an empty field, just skip it (because of '?').
726 - Finally, put the scheduling information and append a whitespace.
727
728 As another example, if you don't want the time-of-day of entries in
729 the prefix, you could use:
730
731 (setq org-agenda-prefix-format \" %-11:c% s\")
732
733 See also the variable `org-agenda-remove-times-when-in-prefix'."
734 :type 'string
735 :group 'org-agenda)
736
737 (defcustom org-timeline-prefix-format " % s"
738 "Like `org-agenda-prefix-format', but for the timeline of a single file."
739 :type 'string
740 :group 'org-agenda)
741
742 (defvar org-prefix-format-compiled nil
743 "The compiled version of the most recently used prefix format.
744 Depending on which command was used last, this may be the compiled version
745 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
746
747 (defcustom org-agenda-use-time-grid t
748 "Non-nil means, show a time grid in the agenda schedule.
749 A time grid is a set of lines for specific times (like every two hours between
750 8:00 and 20:00. The items scheduled for a day at specific times are
751 sorted in between these lines.
752 For deails about when the grid will be shown, and what it will look like, see
753 the variable `org-agenda-time-grid'."
754 :group 'org-agenda
755 :type 'boolean)
756
757 (defcustom org-agenda-time-grid
758 '((daily today require-timed)
759 "----------------"
760 (800 1000 1200 1400 1600 1800 2000))
761
762 "The settings for time grid for agenda display.
763 This is a list of three items. The first item is again a list. It contains
764 symbols specifying conditions when the grid should be displayed:
765
766 daily if the agenda shows a single day
767 weekly if the agenda shows an entire week
768 today show grid on current date, independent of daily/weekly display
769 require-timed show grid only if at least on item has a time specification
770
771 The second item is a string which will be places behing the grid time.
772
773 The third item is a list of integers, indicating the times that should have
774 a grid line."
775 :group 'org-agenda
776 :type
777 '(list
778 (set :greedy t :tag "Grid Display Options"
779 (const :tag "Show grid in single day agenda display" daily)
780 (const :tag "Show grid in weekly agenda display" weekly)
781 (const :tag "Always show grid for today" today)
782 (const :tag "Show grid only if any timed entries are present"
783 require-timed)
784 (const :tag "Skip grid times already present in an entry"
785 remove-match))
786 (string :tag "Grid String")
787 (repeat :tag "Grid Times" (integer :tag "Time"))))
788
789 (defcustom org-agenda-remove-times-when-in-prefix t
790 "Non-nil means, remove duplicate time specifications in agenda items.
791 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
792 time-of-day specification in a headline or diary entry is extracted and
793 placed into the prefix. If this option is non-nil, the original specification
794 \(a timestamp or -range, or just a plain time(range) specification like
795 11:30-4pm) will be removed for agenda display. This makes the agenda less
796 cluttered.
797 The option can be t or nil. It may also be the symbol `beg', indicating
798 that the time should only be removed what it is located at the beginning of
799 the headline/diary entry."
800 :group 'org-agenda
801 :type '(choice
802 (const :tag "Always" t)
803 (const :tag "Never" nil)
804 (const :tag "When at beginning of entry" beg)))
805
806 (defcustom org-sort-agenda-notime-is-late t
807 "Non-nil means, items without time are considered late.
808 This is only relevant for sorting. When t, items which have no explicit
809 time like 15:30 will be considered as 24:01, i.e. later than any items which
810 do have a time. When nil, the default time is before 0:00. You can use this
811 option to decide if the schedule for today should come before or after timeless
812 agenda entries."
813 :group 'org-agenda
814 :type 'boolean)
815
816 (defgroup org-structure nil
817 "Options concerning structure editing in Org-mode."
818 :tag "Org Structure"
819 :group 'org)
820
821 (defcustom org-cycle-include-plain-lists nil
822 "Non-nil means, include plain lists into visibility cycling.
823 This means that during cycling, plain list items will *temporarily* be
824 interpreted as outline headlines with a level given by 1000+i where i is the
825 indentation of the bullet. In all other operations, plain list items are
826 not seen as headlines. For example, you cannot assign a TODO keyword to
827 such an item."
828 :group 'org-structure
829 :type 'boolean)
830
831 (defcustom org-cycle-emulate-tab t
832 "Where should `org-cycle' emulate TAB.
833 nil Never
834 white Only in completely white lines
835 t Everywhere except in headlines"
836 :group 'org-structure
837 :type '(choice (const :tag "Never" nil)
838 (const :tag "Only in completely white lines" white)
839 (const :tag "Everywhere except in headlines" t)
840 ))
841
842 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
843 "Hook that is run after `org-cycle' has changed the buffer visibility.
844 The function(s) in this hook must accept a single argument which indicates
845 the new state that was set by the most recent `org-cycle' command. The
846 argument is a symbol. After a global state change, it can have the values
847 `overview', `content', or `all'. After a local state change, it can have
848 the values `folded', `children', or `subtree'."
849 :group 'org-structure
850 :type 'hook)
851
852 (defcustom org-highlight-sparse-tree-matches t
853 "Non-nil means, highlight all matches that define a sparse tree.
854 The highlights will automatically disappear the next time the buffer is
855 changed by an edit command."
856 :group 'org-structure
857 :type 'boolean)
858
859 (defcustom org-show-hierarchy-above t
860 "Non-nil means, show full hierarchy when showing a spot in the tree.
861 Turning this off makes sparse trees more compact, but also less clear."
862 :group 'org-structure
863 :type 'boolean)
864
865 (defcustom org-show-following-heading t
866 "Non-nil means, show heading following match in `org-occur'.
867 When doing an `org-occur' it is useful to show the headline which
868 follows the match, even if they do not match the regexp. This makes it
869 easier to edit directly inside the sparse tree. However, if you use
870 org-occur mainly as an overview, the following headlines are
871 unnecessary clutter."
872 :group 'org-structure
873 :type 'boolean)
874
875 (defcustom org-occur-hook '(org-first-headline-recenter)
876 "Hook that is run after `org-occur' has constructed a sparse tree.
877 This can be used to recenter the window to show as much of the structure
878 as possible."
879 :group 'org-structure
880 :type 'hook)
881
882 (defcustom org-level-color-stars-only nil
883 "Non-nil means fontify only the stars in each headline.
884 When nil, the entire headline is fontified.
885 After changin this, requires restart of Emacs to become effective."
886 :group 'org-structure
887 :type 'boolean)
888
889 (defcustom org-adapt-indentation t
890 "Non-nil means, adapt indentation when promoting and demoting.
891 When this is set and the *entire* text in an entry is indented, the
892 indentation is increased by one space in a demotion command, and
893 decreased by one in a promotion command. If any line in the entry
894 body starts at column 0, indentation is not changed at all."
895 :group 'org-structure
896 :type 'boolean)
897
898 (defcustom org-plain-list-ordered-item-terminator t
899 "The character that makes a line with leading number an ordered list item.
900 Valid values are ?. and ?\). To get both terminators, use t. While
901 ?. may look nicer, it creates the danger that a line with leading
902 number may be incorrectly interpreted as an item. ?\) therefore is
903 the safe choice."
904 :group 'org-structure
905 :type '(choice (const :tag "dot like in \"2.\"" ?.)
906 (const :tag "paren like in \"2)\"" ?\))
907 (const :tab "both" t)))
908
909 (defcustom org-auto-renumber-ordered-lists t
910 "Non-nil means, automatically renumber ordered plain lists.
911 Renumbering happens when the sequence have been changed with
912 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
913 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
914 :group 'org-structure
915 :type 'boolean)
916
917 (defcustom org-enable-fixed-width-editor t
918 "Non-nil means, lines starting with \":\" are treated as fixed-width.
919 This currently only means, they are never auto-wrapped.
920 When nil, such lines will be treated like ordinary lines.
921 See also the QUOTE keyword."
922 :group 'org-structure
923 :type 'boolean)
924
925 (defcustom org-archive-location "%s_archive::"
926 "The location where subtrees should be archived.
927 This string consists of two parts, separated by a double-colon.
928
929 The first part is a file name - when omitted, archiving happens in the same
930 file. %s will be replaced by the current file name (without directory part).
931 Archiving to a different file is useful to keep archived entries from
932 contributing to the Org-mode Agenda.
933
934 The part after the double colon is a headline. The archived entries will be
935 filed under that headline. When omitted, the subtrees are simply filed away
936 at the end of the file, as top-level entries.
937
938 Here are a few examples:
939 \"%s_archive::\"
940 If the current file is Projects.org, archive in file
941 Projects.org_archive, as top-level trees. This is the default.
942
943 \"::* Archived Tasks\"
944 Archive in the current file, under the top-level headline
945 \"* Archived Tasks\".
946
947 \"~/org/archive.org::\"
948 Archive in file ~/org/archive.org (absolute path), as top-level trees.
949
950 \"basement::** Finished Tasks\"
951 Archive in file ./basement (relative path), as level 3 trees
952 below the level 2 heading \"** Finished Tasks\".
953
954 You may set this option on a per-file basis by adding to the buffer a
955 line like
956
957 #+ARCHIVE: basement::** Finished Tasks"
958 :group 'org-structure
959 :type 'string)
960
961 (defcustom org-archive-mark-done t
962 "Non-nil means, mark archived entries as DONE."
963 :group 'org-structure
964 :type 'boolean)
965
966 (defcustom org-archive-stamp-time t
967 "Non-nil means, add a time stamp to archived entries.
968 The time stamp will be added directly after the TODO state keyword in the
969 first line, so it is probably best to use this in combinations with
970 `org-archive-mark-done'."
971 :group 'org-structure
972 :type 'boolean)
973
974 (defgroup org-link nil
975 "Options concerning links in Org-mode."
976 :tag "Org Link"
977 :group 'org)
978
979 (defcustom org-link-format "<%s>"
980 "Default format for linkes in the buffer.
981 This is a format string for printf, %s will be replaced by the link text.
982 If you want to make sure that your link is always properly terminated,
983 include angle brackets into this format, like \"<%s>\". Some people also
984 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
985 :group 'org-link
986 :type '(choice
987 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
988 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
989 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
990 (string :tag "Other" :value "<%s>")))
991
992 (defcustom org-allow-space-in-links t
993 "Non-nil means, file names in links may contain space characters.
994 When nil, it becomes possible to put several links into a line.
995 Note that in tables, a link never extends accross fields, so in a table
996 it is always possible to put several links into a line.
997 Changing this varable requires a re-launch of Emacs of become effective."
998 :group 'org-link
999 :type 'boolean)
1000
1001 (defcustom org-context-in-file-links t
1002 "Non-nil means, file links from `org-store-link' contain context.
1003 The line number will be added to the file name with :: as separator and
1004 used to find the context when the link is activated by the command
1005 `org-open-at-point'.
1006 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1007 negates this setting for the duration of the command."
1008 :group 'org-link
1009 :type 'boolean)
1010
1011 (defcustom org-keep-stored-link-after-insertion nil
1012 "Non-nil means, keep link in list for entire session.
1013
1014 The command `org-store-link' adds a link pointing to the current
1015 location to an internal list. These links accumulate during a session.
1016 The command `org-insert-link' can be used to insert links into any
1017 Org-mode file (offering completion for all stored links). When this
1018 option is nil, every link which has been inserted once using \\[org-insert-link]
1019 will be removed from the list, to make completing the unused links
1020 more efficient."
1021 :group 'org-link
1022 :type 'boolean)
1023
1024 (defcustom org-link-frame-setup
1025 '((vm . vm-visit-folder-other-frame)
1026 (gnus . gnus-other-frame)
1027 (file . find-file-other-window))
1028 "Setup the frame configuration for following links.
1029 When following a link with Emacs, it may often be useful to display
1030 this link in another window or frame. This variable can be used to
1031 set this up for the different types of links.
1032 For VM, use any of
1033 `vm-visit-folder'
1034 `vm-visit-folder-other-frame'
1035 For Gnus, use any of
1036 `gnus'
1037 `gnus-other-frame'
1038 For FILE, use any of
1039 `find-file'
1040 `find-file-other-window'
1041 `find-file-other-frame'
1042 For the calendar, use the variable `calendar-setup'.
1043 For BBDB, it is currently only possible to display the matches in
1044 another window."
1045 :group 'org-link
1046 :type '(list
1047 (cons (const vm)
1048 (choice
1049 (const vm-visit-folder)
1050 (const vm-visit-folder-other-window)
1051 (const vm-visit-folder-other-frame)))
1052 (cons (const gnus)
1053 (choice
1054 (const gnus)
1055 (const gnus-other-frame)))
1056 (cons (const file)
1057 (choice
1058 (const find-file)
1059 (const find-file-other-window)
1060 (const find-file-other-frame)))))
1061
1062 (defcustom org-usenet-links-prefer-google nil
1063 "Non-nil means, `org-store-link' will create web links to google groups.
1064 When nil, Gnus will be used for such links.
1065 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1066 negates this setting for the duration of the command."
1067 :group 'org-link
1068 :type 'boolean)
1069
1070 (defcustom org-open-non-existing-files nil
1071 "Non-nil means, `org-open-file' will open non-existing file.
1072 When nil, an error will be generated."
1073 :group 'org-link
1074 :type 'boolean)
1075
1076 (defcustom org-confirm-shell-links t
1077 "Non-nil means, ask for confirmation before executing shell links.
1078 The default is true, to keep new users from shooting into their own foot."
1079 :group 'org-link
1080 :type 'boolean)
1081
1082 (defconst org-file-apps-defaults-gnu
1083 '((t . emacs)
1084 ("jpg" . "xv %s")
1085 ("gif" . "xv %s")
1086 ("ppm" . "xv %s")
1087 ("pgm" . "xv %s")
1088 ("pbm" . "xv %s")
1089 ("tif" . "xv %s")
1090 ("png" . "xv %s")
1091 ("ps" . "gv %s")
1092 ("ps.gz" . "gv %s")
1093 ("eps" . "gv %s")
1094 ("eps.gz" . "gv %s")
1095 ("dvi" . "xdvi %s")
1096 ("mpeg" . "plaympeg %s")
1097 ("mp3" . "plaympeg %s")
1098 ("fig" . "xfig %s")
1099 ("pdf" . "acroread %s")
1100 ("doc" . "soffice %s")
1101 ("ppt" . "soffice %s")
1102 ("pps" . "soffice %s")
1103 ("html" . "netscape -remote openURL(%s,new-window)")
1104 ("htm" . "netscape -remote openURL(%s,new-window)")
1105 ("xs" . "soffice %s"))
1106 "Default file applications on a UNIX/LINUX system.
1107 See `org-file-apps'.")
1108
1109 (defconst org-file-apps-defaults-macosx
1110 '((t . "open %s")
1111 ("ps" . "gv %s")
1112 ("ps.gz" . "gv %s")
1113 ("eps" . "gv %s")
1114 ("eps.gz" . "gv %s")
1115 ("dvi" . "xdvi %s")
1116 ("fig" . "xfig %s"))
1117 "Default file applications on a MacOS X system.
1118 The system \"open\" is known as a default, but we use X11 applications
1119 for some files for which the OS does not have a good default.
1120 See `org-file-apps'.")
1121
1122 (defconst org-file-apps-defaults-windowsnt
1123 '((t . (w32-shell-execute "open" file)))
1124 "Default file applications on a Windows NT system.
1125 The system \"open\" is used for most files.
1126 See `org-file-apps'.")
1127
1128 (defcustom org-file-apps
1129 '(
1130 ("txt" . emacs)
1131 ("tex" . emacs)
1132 ("ltx" . emacs)
1133 ("org" . emacs)
1134 ("el" . emacs)
1135 )
1136 "External applications for opening `file:path' items in a document.
1137 Org-mode uses system defaults for different file types, but
1138 you can use this variable to set the application for a given file
1139 extension. The entries in this list are cons cells with a file extension
1140 and the corresponding command. Possible values for the command are:
1141 `emacs' The file will be visited by the current Emacs process.
1142 `default' Use the default application for this file type.
1143 string A command to be executed by a shell; %s will be replaced
1144 by the path to the file.
1145 sexp A Lisp form which will be evaluated. The file path will
1146 be available in the Lisp variable `file'.
1147 For more examples, see the system specific constants
1148 `org-file-apps-defaults-macosx'
1149 `org-file-apps-defaults-windowsnt'
1150 `org-file-apps-defaults-gnu'."
1151 :group 'org-link
1152 :type '(repeat
1153 (cons (string :tag "Extension")
1154 (choice :value ""
1155 (const :tag "Visit with Emacs" 'emacs)
1156 (const :tag "Use system default" 'default)
1157 (string :tag "Command")
1158 (sexp :tag "Lisp form")))))
1159
1160
1161 (defgroup org-remember nil
1162 "Options concerning interaction with remember.el."
1163 :tag "Org Remember"
1164 :group 'org)
1165
1166 (defcustom org-directory "~/org"
1167 "Directory with org files.
1168 This directory will be used as default to prompt for org files.
1169 Used by the hooks for remember.el."
1170 :group 'org-remember
1171 :type 'directory)
1172
1173 (defcustom org-default-notes-file "~/.notes"
1174 "Default target for storing notes.
1175 Used by the hooks for remember.el. This can be a string, or nil to mean
1176 the value of `remember-data-file'."
1177 :group 'org-remember
1178 :type '(choice
1179 (const :tag "Default from remember-data-file" nil)
1180 file))
1181
1182 (defcustom org-reverse-note-order nil
1183 "Non-nil means, store new notes at the beginning of a file or entry.
1184 When nil, new notes will be filed to the end of a file or entry."
1185 :group 'org-remember
1186 :type '(choice
1187 (const :tag "Reverse always" t)
1188 (const :tag "Reverse never" nil)
1189 (repeat :tag "By file name regexp"
1190 (cons regexp boolean))))
1191
1192 (defgroup org-table nil
1193 "Options concerning tables in Org-mode."
1194 :tag "Org Table"
1195 :group 'org)
1196
1197 (defcustom org-enable-table-editor 'optimized
1198 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1199 When nil, such lines will be treated like ordinary lines.
1200
1201 When equal to the symbol `optimized', the table editor will be optimized to
1202 do the following
1203 - Use automatic overwrite mode in front of whitespace in table fields.
1204 This make the structure of the table stay in tact as long as the edited
1205 field does not exceed the column width.
1206 - Minimize the number of realigns. Normally, the table is aligned each time
1207 TAB or RET are pressed to move to another field. With optimization this
1208 happens only if changes to a field might have changed the column width.
1209 Optimization requires replacing the functions `self-insert-command',
1210 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1211 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1212 very good at guessing when a re-align will be necessary, but you can always
1213 force one with \\[org-ctrl-c-ctrl-c].
1214
1215 If you would like to use the optimized version in Org-mode, but the
1216 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1217
1218 This variable can be used to turn on and off the table editor during a session,
1219 but in order to toggle optimization, a restart is required.
1220
1221 See also the variable `org-table-auto-blank-field'."
1222 :group 'org-table
1223 :type '(choice
1224 (const :tag "off" nil)
1225 (const :tag "on" t)
1226 (const :tag "on, optimized" optimized)))
1227
1228 ;; FIXME: We could have a third option which makes it jump only over the first
1229 ;; hline in a table.
1230 (defcustom org-table-tab-jumps-over-hlines t
1231 "Non-nil means, tab in the last column of a table with jump over a hline.
1232 If a horizontal separator line is following the current line,
1233 `org-table-next-field' can either create a new row before that line, or jump
1234 over the line. When this option is nil, a new line will be created before
1235 this line."
1236 :group 'org-table
1237 :type 'boolean)
1238
1239 (defcustom org-table-auto-blank-field t
1240 "Non-nil means, automatically blank table field when starting to type into it.
1241 This only happens when typing immediately after a field motion
1242 command (TAB, S-TAB or RET).
1243 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1244 :group 'org-table
1245 :type 'boolean)
1246
1247 (defcustom org-table-default-size "5x2"
1248 "The default size for newly created tables, Columns x Rows."
1249 :group 'org-table
1250 :type 'string)
1251
1252 (defcustom org-table-automatic-realign t
1253 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1254 When nil, aligning is only done with \\[org-table-align], or after column
1255 removal/insertion."
1256 :group 'org-table
1257 :type 'boolean)
1258
1259 (defcustom org-table-spaces-around-separators '(1 . 1)
1260 "The number of spaces to be placed before and after separators."
1261 :group 'org-table
1262 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1263
1264 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1265 "The number of spaces to be placed before and after separators.
1266 This option applies when the column separators have been made invisible."
1267 :group 'org-table
1268 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1269
1270 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1271 "Regular expression for recognizing numbers in table columns.
1272 If a table column contains mostly numbers, it will be aligned to the
1273 right. If not, it will be aligned to the left.
1274
1275 The default value of this option is a regular expression which allows
1276 anything which looks remotely like a number as used in scientific
1277 context. For example, all of the following will be considered a
1278 number:
1279 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1280
1281 Other options offered by the customize interface are more restrictive."
1282 :group 'org-table
1283 :type '(choice
1284 (const :tag "Positive Integers"
1285 "^[0-9]+$")
1286 (const :tag "Integers"
1287 "^[-+]?[0-9]+$")
1288 (const :tag "Floating Point Numbers"
1289 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1290 (const :tag "Floating Point Number or Integer"
1291 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1292 (const :tag "Exponential, Floating point, Integer"
1293 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1294 (const :tag "Very General Number-Like"
1295 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1296 (string :tag "Regexp:")))
1297
1298 (defcustom org-table-number-fraction 0.5
1299 "Fraction of numbers in a column required to make the column align right.
1300 In a column all non-white fields are considered. If at least this
1301 fraction of fields is matched by `org-table-number-fraction',
1302 alignment to the right border applies."
1303 :group 'org-table
1304 :type 'number)
1305
1306 (defcustom org-export-highlight-first-table-line t
1307 "Non-nil means, highlight the first table line.
1308 In HTML export, this means use <th> instead of <td>.
1309 In tables created with table.el, this applies to the first table line.
1310 In Org-mode tables, all lines before the first horizontal separator
1311 line will be formatted with <th> tags."
1312 :group 'org-table
1313 :type 'boolean)
1314
1315 (defcustom org-table-tab-recognizes-table.el t
1316 "Non-nil means, TAB will automatically notice a table.el table.
1317 When it sees such a table, it moves point into it and - if necessary -
1318 calls `table-recognize-table'."
1319 :group 'org-table
1320 :type 'boolean)
1321
1322 (defgroup org-table-calculation nil
1323 "Options concerning tables in Org-mode."
1324 :tag "Org Table Calculation"
1325 :group 'org)
1326
1327 (defcustom org-table-copy-increment t
1328 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1329 :group 'org-table-calculation
1330 :type 'boolean)
1331
1332 (defcustom org-calc-default-modes
1333 '(calc-internal-prec 12
1334 calc-float-format (float 5)
1335 calc-angle-mode deg
1336 calc-prefer-frac nil
1337 calc-symbolic-mode nil
1338 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1339 calc-display-working-message t
1340 )
1341 "List with Calc mode settings for use in calc-eval for table formulas.
1342 The list must contain alternating symbols (calc modes variables and values.
1343 Don't remove any of the default settings, just change the values. Org-mode
1344 relies on the variables to be present in the list."
1345 :group 'org-table-calculation
1346 :type 'plist)
1347
1348 (defcustom org-table-formula-evaluate-inline t
1349 "Non-nil means, TAB and RET evaluate a formula in current table field.
1350 If the current field starts with an equal sign, it is assumed to be a formula
1351 which should be evaluated as described in the manual and in the documentation
1352 string of the command `org-table-eval-formula'. This feature requires the
1353 Emacs calc package.
1354 When this variable is nil, formula calculation is only available through
1355 the command \\[org-table-eval-formula]."
1356 :group 'org-table-calculation
1357 :type 'boolean)
1358
1359
1360 (defcustom org-table-formula-use-constants t
1361 "Non-nil means, interpret constants in formulas in tables.
1362 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1363 by the value given in `org-table-formula-constants', or by a value obtained
1364 from the `constants.el' package."
1365 :group 'org-table-calculation
1366 :type 'boolean)
1367
1368 (defcustom org-table-formula-constants nil
1369 "Alist with constant names and values, for use in table formulas.
1370 The car of each element is a name of a constant, without the `$' before it.
1371 The cdr is the value as a string. For example, if you'd like to use the
1372 speed of light in a formula, you would configure
1373
1374 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1375
1376 and then use it in an equation like `$1*$c'."
1377 :group 'org-table-calculation
1378 :type '(repeat
1379 (cons (string :tag "name")
1380 (string :tag "value"))))
1381
1382 (defcustom org-table-formula-numbers-only nil
1383 "Non-nil means, calculate only with numbers in table formulas.
1384 Then all input fields will be converted to a number, and the result
1385 must also be a number. When nil, calc's full potential is available
1386 in table calculations, including symbolics etc."
1387 :group 'org-table-calculation
1388 :type 'boolean)
1389
1390 (defcustom org-table-allow-automatic-line-recalculation t
1391 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1392 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1393 :group 'org-table-calculation
1394 :type 'boolean)
1395
1396 (defgroup org-export nil
1397 "Options for exporting org-listings."
1398 :tag "Org Export"
1399 :group 'org)
1400
1401 (defcustom org-export-language-setup
1402 '(("en" "Author" "Date" "Table of Contents")
1403 ("da" "Ophavsmand" "Dato" "Indhold")
1404 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1405 ("es" "Autor" "Fecha" "\xccndice")
1406 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1407 ("it" "Autore" "Data" "Indice")
1408 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1409 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1410 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1411 "Terms used in export text, translated to different languages.
1412 Use the variable `org-export-default-language' to set the language,
1413 or use the +OPTION lines for a per-file setting."
1414 :group 'org-export
1415 :type '(repeat
1416 (list
1417 (string :tag "HTML language tag")
1418 (string :tag "Author")
1419 (string :tag "Date")
1420 (string :tag "Table of Contents"))))
1421
1422 (defcustom org-export-default-language "en"
1423 "The default language of HTML export, as a string.
1424 This should have an association in `org-export-language-setup'."
1425 :group 'org-export
1426 :type 'string)
1427
1428 (defcustom org-export-html-style
1429 "<style type=\"text/css\">
1430 html {
1431 font-family: Times, serif;
1432 font-size: 12pt;
1433 }
1434 .title { text-align: center; }
1435 .todo, .deadline { color: red; }
1436 .done { color: green; }
1437 pre {
1438 border: 1pt solid #AEBDCC;
1439 background-color: #F3F5F7;
1440 padding: 5pt;
1441 font-family: courier, monospace;
1442 }
1443 table { border-collapse: collapse; }
1444 td, th {
1445 vertical-align: top;
1446 border: 1pt solid #ADB9CC;
1447 }
1448 </style>"
1449 "The default style specification for exported HTML files.
1450 Since there are different ways of setting style information, this variable
1451 needs to contain the full HTML structure to provide a style, including the
1452 surrounding HTML tags. The style specifications should include definiitons
1453 for new classes todo, done, title, and deadline. For example, legal values
1454 would be.
1455
1456 <style type=\"text/css\">
1457 p {font-weight: normal; color: gray; }
1458 h1 {color: black; }
1459 .title { text-align: center; }
1460 .todo, .deadline { color: red; }
1461 .done { color: green; }
1462 </style>
1463
1464 or, if you want to keep the style in a file,
1465
1466 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1467
1468 As the value of this option simply gets inserted into the HTML <head> header,
1469 you can \"misuse\" it to add arbitrary text to the header."
1470 :group 'org-export
1471 :type 'string)
1472
1473 (defcustom org-export-headline-levels 3
1474 "The last level which is still exported as a headline.
1475 Inferior levels will produce itemize lists when exported.
1476 Note that a numeric prefix argument to an exporter function overrides
1477 this setting.
1478
1479 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1480 :group 'org-export
1481 :type 'number)
1482
1483 (defcustom org-export-with-section-numbers t
1484 "Non-nil means, add section numbers to headlines when exporting.
1485
1486 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1487 :group 'org-export
1488 :type 'boolean)
1489
1490 (defcustom org-export-with-toc t
1491 "Non-nil means, create a table of contents in exported files.
1492 The TOC contains headlines with levels up to`org-export-headline-levels'.
1493
1494 Headlines which contain any TODO items will be marked with \"(*)\" in
1495 ASCII export, and with red color in HTML output.
1496
1497 In HTML output, the TOC will be clickable.
1498
1499 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1500 :group 'org-export
1501 :type 'boolean)
1502
1503 (defcustom org-export-plain-list-max-depth 20
1504 "Maximum depth of hand-formatted lists in HTML export.
1505
1506 Org-mode parses hand-formatted enumeration and bullet lists and
1507 transforms them to HTML open export. Different indentation of the
1508 bullet or number indicates different list nesting levels. To avoid
1509 confusion, only a single level is allowed by default. When this is
1510 larger than 1, deeper indentation leads to deeper list nesting. For
1511 example, the default value of 3 allows the following list to be
1512 formatted correctly in HTML:
1513
1514 * Fruit
1515 - Apple
1516 - Banana
1517 1. from Africa
1518 2. from South America
1519 - Pineapple
1520 * Bread
1521 * Dairy products"
1522 :group 'org-export
1523 :type 'integer)
1524
1525 (defcustom org-export-preserve-breaks nil
1526 "Non-nil means, preserve all line breaks when exporting.
1527 Normally, in HTML output paragraphs will be reformatted. In ASCII
1528 export, line breaks will always be preserved, regardless of this variable.
1529
1530 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1531 :group 'org-export
1532 :type 'boolean)
1533
1534 (defcustom org-export-html-inline-images t
1535 "Non-nil means, inline images into exported HTML pages.
1536 The link will still be to the original location of the image file.
1537 So if you are moving the page, lets say to your public HTML site,
1538 you will have to move the image and maybe change the link."
1539 :group 'org-export
1540 :type 'boolean)
1541
1542 (defcustom org-export-html-expand t
1543 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1544 When nil, these tags will be exported as plain text and therefore
1545 not be interpreted by a browser.
1546
1547 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1548 :group 'org-export
1549 :type 'boolean)
1550
1551 (defcustom org-export-with-fixed-width t
1552 "Non-nil means, lines starting with \":\" will be in fixed width font.
1553 This can be used to have pre-formatted text, fragments of code etc. For
1554 example
1555 : ;; Some Lisp examples
1556 : (while (defc cnt)
1557 : (ding))
1558 will be looking just like this in also HTML. In ASCII export, this option
1559 has no effect.
1560
1561 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1562 :group 'org-export
1563 :type 'boolean)
1564
1565 (defcustom org-export-with-tables t
1566 "If non-nil, lines starting with \"|\" define a table.
1567 For example:
1568
1569 | Name | Address | Birthday |
1570 |-------------+----------+-----------|
1571 | Arthur Dent | England | 29.2.2100 |
1572
1573 In ASCII export, this option has no effect.
1574
1575 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1576 :group 'org-export
1577 :type 'boolean)
1578
1579 (defcustom org-export-prefer-native-exporter-for-tables nil
1580 "Non-nil means, always export tables created with table.el natively.
1581 Natively means, use the HTML code generator in table.el.
1582 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1583 the table does not use row- or column-spanning). This has the
1584 advantage, that the automatic HTML conversions for math symbols and
1585 sub/superscripts can be applied. Org-mode's HTML generator is also
1586 much faster."
1587 :group 'org-export
1588 :type 'boolean)
1589
1590 (defcustom org-export-html-table-tag
1591 "<table border=1 cellspacing=0 cellpadding=6>"
1592 "The HTML tag used to start a table.
1593 This must be a <table> tag, but you may change the options like
1594 borders and spacing."
1595 :group 'org-export
1596 :type 'string)
1597
1598 (defcustom org-export-with-emphasize t
1599 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1600 If the export target supports emphasizing text, the word will be
1601 typeset in bold, italic, or underlined, respectively. Works only for
1602 single words, but you can say: I *really* *mean* *this*.
1603 In ASCII export, this option has no effect.
1604
1605 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1606 :group 'org-export
1607 :type 'boolean)
1608
1609 (defcustom org-match-sexp-depth 3
1610 "Number of stacked braces for sub/superscript matching.
1611 This has to be set before loading org.el to be effective."
1612 :group 'org-export
1613 :type 'integer)
1614
1615 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1616 (defcustom org-export-with-sub-superscripts t
1617 "Non-nil means, interpret \"_\" and \"^\" for export.
1618 When this option is turned on, you can use TeX-like syntax for sub- and
1619 superscripts. Several characters after \"_\" or \"^\" will be
1620 considered as a single item - so grouping with {} is normally not
1621 needed. For example, the following things will be parsed as single
1622 sub- or superscripts.
1623
1624 10^24 or 10^tau several digits will be considered 1 item
1625 10^-12 or 10^-tau a leading sign with digits or a word
1626 x^2-y^3 will be read as x^2 - y^3, because items are
1627 terminated by almost any nonword/nondigit char.
1628 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1629
1630 Still, ambiguity is possible - so when in doubt use {} to enclose the
1631 sub/superscript.
1632 In ASCII export, this option has no effect.
1633
1634 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1635 :group 'org-export
1636 :type 'boolean)
1637
1638 (defcustom org-export-with-TeX-macros t
1639 "Non-nil means, interpret simple TeX-like macros when exporting.
1640 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1641 No only real TeX macros will work here, but the standard HTML entities
1642 for math can be used as macro names as well. For a list of supported
1643 names in HTML export, see the constant `org-html-entities'.
1644 In ASCII export, this option has no effect.
1645
1646 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1647 :group 'org-export
1648 :type 'boolean)
1649
1650 (defcustom org-export-html-with-timestamp nil
1651 "If non-nil, write `org-export-html-html-helper-timestamp'
1652 into the exported html text. Otherwise, the buffer will just be saved
1653 to a file."
1654 :group 'org-export
1655 :type 'boolean)
1656
1657 (defcustom org-export-html-html-helper-timestamp
1658 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1659 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1660 :group 'org-export
1661 :type 'string)
1662
1663 (defcustom org-export-ascii-show-new-buffer t
1664 "Non-nil means, popup buffer containing the exported ASCII text.
1665 Otherwise the buffer will just be saved to a file and stay hidden."
1666 :group 'org-export
1667 :type 'boolean)
1668
1669 (defcustom org-export-html-show-new-buffer nil
1670 "Non-nil means, popup buffer containing the exported html text.
1671 Otherwise, the buffer will just be saved to a file and stay hidden."
1672 :group 'org-export
1673 :type 'boolean)
1674
1675 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1676 "The file name for the iCalendar file covering all agenda files.
1677 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1678 :group 'org-export
1679 :type 'file)
1680
1681 (defcustom org-icalendar-include-todo nil
1682 "Non-nil means, export to iCalendar files should also cover TODO items."
1683 :group 'org-export
1684 :type 'boolean)
1685
1686 (defcustom org-icalendar-combined-name "OrgMode"
1687 "Calendar name for the combined iCalendar representing all agenda files."
1688 :group 'org-export
1689 :type 'string)
1690
1691 (defgroup org-faces nil
1692 "Faces for highlighting in Org-mode."
1693 :tag "Org Faces"
1694 :group 'org)
1695
1696 (defface org-level-1 ;; font-lock-function-name-face
1697 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1698 (((class color) (background light)) (:foreground "Blue"))
1699 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1700 (t (:inverse-video t :bold t)))
1701 "Face used for level 1 headlines."
1702 :group 'org-faces)
1703
1704 (defface org-level-2 ;; font-lock-variable-name-face
1705 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1706 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1707 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1708 (t (:bold t :italic t)))
1709 "Face used for level 2 headlines."
1710 :group 'org-faces)
1711
1712 (defface org-level-3 ;; font-lock-keyword-face
1713 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1714 (((class color) (background light)) (:foreground "Purple"))
1715 (((class color) (background dark)) (:foreground "Cyan"))
1716 (t (:bold t)))
1717 "Face used for level 3 headlines."
1718 :group 'org-faces)
1719
1720 (defface org-level-4 ;; font-lock-comment-face
1721 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1722 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1723 (((class color) (background light)) (:foreground "Firebrick"))
1724 (((class color) (background dark)) (:foreground "chocolate1"))
1725 (t (:bold t :italic t)))
1726 "Face used for level 4 headlines."
1727 :group 'org-faces)
1728
1729 (defface org-level-5 ;; font-lock-type-face
1730 '((((type tty) (class color)) (:foreground "green"))
1731 (((class color) (background light)) (:foreground "ForestGreen"))
1732 (((class color) (background dark)) (:foreground "PaleGreen"))
1733 (t (:bold t :underline t)))
1734 "Face used for level 5 headlines."
1735 :group 'org-faces)
1736
1737 (defface org-level-6 ;; font-lock-constant-face
1738 '((((type tty) (class color)) (:foreground "magenta"))
1739 (((class color) (background light)) (:foreground "CadetBlue"))
1740 (((class color) (background dark)) (:foreground "Aquamarine"))
1741 (t (:bold t :underline t)))
1742 "Face used for level 6 headlines."
1743 :group 'org-faces)
1744
1745 (defface org-level-7 ;; font-lock-builtin-face
1746 '((((type tty) (class color)) (:foreground "blue" :weight light))
1747 (((class color) (background light)) (:foreground "Orchid"))
1748 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1749 (t (:bold t)))
1750 "Face used for level 7 headlines."
1751 :group 'org-faces)
1752
1753 (defface org-level-8 ;; font-lock-string-face
1754 '((((type tty) (class color)) (:foreground "green"))
1755 (((class color) (background light)) (:foreground "RosyBrown"))
1756 (((class color) (background dark)) (:foreground "LightSalmon"))
1757 (t (:italic t)))
1758 "Face used for level 8 headlines."
1759 :group 'org-faces)
1760
1761 (defface org-special-keyword ;; font-lock-string-face
1762 '((((type tty) (class color)) (:foreground "green"))
1763 (((class color) (background light)) (:foreground "RosyBrown"))
1764 (((class color) (background dark)) (:foreground "LightSalmon"))
1765 (t (:italic t)))
1766 "Face used for level 8 headlines."
1767 :group 'org-faces)
1768
1769 (defface org-warning ;; font-lock-warning-face
1770 '((((type tty) (class color)) (:foreground "red"))
1771 (((class color) (background light)) (:foreground "Red" :bold t))
1772 (((class color) (background dark)) (:foreground "Red1" :bold t))
1773 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1774 (t (:inverse-video t :bold t)))
1775 "Face for deadlines and TODO keywords."
1776 :group 'org-faces)
1777
1778 (defcustom org-fontify-done-headline nil
1779 "Non-nil means, change the face of a headline if it is marked DONE.
1780 Normally, only the TODO/DONE keyword indicates the state of a headline.
1781 When this is non-nil, the headline after the keyword is set to the
1782 `org-headline-done' as an additional indication."
1783 :group 'org-faces
1784 :type 'boolean)
1785
1786 (defface org-headline-done ;; font-lock-string-face
1787 '((((type tty) (class color)) (:foreground "green"))
1788 (((class color) (background light)) (:foreground "RosyBrown"))
1789 (((class color) (background dark)) (:foreground "LightSalmon"))
1790 (t (:italic t)))
1791 "Face used to indicate that a headline is DONE. See also the variable
1792 `org-fontify-done-headline'."
1793 :group 'org-faces)
1794
1795 ;; Inheritance does not yet work for xemacs. So we just copy...
1796
1797 (defface org-deadline-announce
1798 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1799 (((class color) (background light)) (:foreground "Blue"))
1800 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1801 (t (:inverse-video t :bold t)))
1802 "Face for upcoming deadlines."
1803 :group 'org-faces)
1804
1805 (defface org-scheduled-today
1806 '((((type tty) (class color)) (:foreground "green"))
1807 (((class color) (background light)) (:foreground "DarkGreen"))
1808 (((class color) (background dark)) (:foreground "PaleGreen"))
1809 (t (:bold t :underline t)))
1810 "Face for items scheduled for a certain day."
1811 :group 'org-faces)
1812
1813 (defface org-scheduled-previously
1814 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1815 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1816 (((class color) (background light)) (:foreground "Firebrick"))
1817 (((class color) (background dark)) (:foreground "chocolate1"))
1818 (t (:bold t :italic t)))
1819 "Face for items scheduled previously, and not yet done."
1820 :group 'org-faces)
1821
1822 (defface org-formula
1823 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1824 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1825 (((class color) (background light)) (:foreground "Firebrick"))
1826 (((class color) (background dark)) (:foreground "chocolate1"))
1827 (t (:bold t :italic t)))
1828 "Face for items scheduled previously, and not yet done."
1829 :group 'org-faces)
1830
1831 (defface org-link
1832 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1833 (((class color) (background light)) (:foreground "Purple"))
1834 (((class color) (background dark)) (:foreground "Cyan"))
1835 (t (:bold t)))
1836 "Face for links."
1837 :group 'org-faces)
1838
1839 (defface org-done ;; font-lock-type-face
1840 '((((type tty) (class color)) (:foreground "green"))
1841 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1842 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1843 (t (:bold t :underline t)))
1844 "Face used for DONE."
1845 :group 'org-faces)
1846
1847 (defface org-table ;; font-lock-function-name-face
1848 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1849 (((class color) (background light)) (:foreground "Blue"))
1850 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1851 (t (:inverse-video t :bold t)))
1852 "Face used for tables."
1853 :group 'org-faces)
1854
1855 (defface org-time-grid ;; font-lock-variable-name-face
1856 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1857 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1858 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1859 (t (:bold t :italic t)))
1860 "Face used for level 2 headlines."
1861 :group 'org-faces)
1862
1863 (defvar org-level-faces
1864 '(
1865 org-level-1
1866 org-level-2
1867 org-level-3
1868 org-level-4
1869 org-level-5
1870 org-level-6
1871 org-level-7
1872 org-level-8
1873 ))
1874 (defvar org-n-levels (length org-level-faces))
1875
1876 (defun org-set-regexps-and-options ()
1877 "Precompute regular expressions for current buffer."
1878 (when (eq major-mode 'org-mode)
1879 (let ((re (org-make-options-regexp
1880 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1881 "STARTUP" "ARCHIVE")))
1882 (splitre "[ \t]+")
1883 kwds int key value cat arch)
1884 (save-excursion
1885 (save-restriction
1886 (widen)
1887 (goto-char (point-min))
1888 (while (re-search-forward re nil t)
1889 (setq key (match-string 1) value (match-string 2))
1890 (cond
1891 ((equal key "CATEGORY")
1892 (if (string-match "[ \t]+$" value)
1893 (setq value (replace-match "" t t value)))
1894 (setq cat (intern value)))
1895 ((equal key "SEQ_TODO")
1896 (setq int 'sequence
1897 kwds (append kwds (org-split-string value splitre))))
1898 ((equal key "PRI_TODO")
1899 (setq int 'priority
1900 kwds (append kwds (org-split-string value splitre))))
1901 ((equal key "TYP_TODO")
1902 (setq int 'type
1903 kwds (append kwds (org-split-string value splitre))))
1904 ((equal key "STARTUP")
1905 (let ((opts (org-split-string value splitre))
1906 (set '(("fold" org-startup-folded t)
1907 ("nofold" org-startup-folded nil)
1908 ("content" org-startup-folded content)
1909 ("dlcheck" org-startup-with-deadline-check t)
1910 ("nodlcheck" org-startup-with-deadline-check nil)))
1911 l var val)
1912 (while (setq l (assoc (pop opts) set))
1913 (setq var (nth 1 l) val (nth 2 l))
1914 (set (make-local-variable var) val))))
1915 ((equal key "ARCHIVE")
1916 (string-match " *$" value)
1917 (setq arch (replace-match "" t t value))
1918 (remove-text-properties 0 (length arch)
1919 '(face t fontified t) arch)))
1920 )))
1921 (and cat (set (make-local-variable 'org-category) cat))
1922 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1923 (and arch (set (make-local-variable 'org-archive-location) arch))
1924 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1925 ;; Compute the regular expressions and other local variables
1926 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1927 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1928 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1929 (length org-scheduled-string)))
1930 org-done-string
1931 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1932 org-todo-regexp
1933 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1934 "\\|") "\\)\\>")
1935 org-not-done-regexp
1936 (concat "\\<\\("
1937 (mapconcat 'regexp-quote
1938 (nreverse (cdr (reverse org-todo-keywords)))
1939 "\\|")
1940 "\\)\\>")
1941 org-todo-line-regexp
1942 (concat "^\\(\\*+\\)[ \t]*\\("
1943 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1944 "\\)? *\\(.*\\)")
1945 org-nl-done-regexp
1946 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1947 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1948 org-deadline-regexp (concat "\\<" org-deadline-string)
1949 org-deadline-time-regexp
1950 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1951 org-deadline-line-regexp
1952 (concat "\\<\\(" org-deadline-string "\\).*")
1953 org-scheduled-regexp
1954 (concat "\\<" org-scheduled-string)
1955 org-scheduled-time-regexp
1956 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1957 (org-set-font-lock-defaults)))
1958
1959 ;; Tell the compiler about dynamically scoped variables,
1960 ;; and variables from other packages
1961 (eval-when-compile
1962 (defvar zmacs-regions)
1963 (defvar original-date)
1964 (defvar org-transient-mark-mode)
1965 (defvar org-old-auto-fill-inhibit-regexp)
1966 (defvar orgtbl-mode-menu)
1967 (defvar org-html-entities)
1968 (defvar org-goto-start-pos)
1969 (defvar org-cursor-color)
1970 (defvar org-time-was-given)
1971 (defvar org-ts-what)
1972 (defvar mark-active)
1973 (defvar timecnt)
1974 (defvar levels-open)
1975 (defvar title)
1976 (defvar author)
1977 (defvar email)
1978 (defvar text)
1979 (defvar entry)
1980 (defvar date)
1981 (defvar language)
1982 (defvar options)
1983 (defvar ans1)
1984 (defvar ans2)
1985 (defvar starting-day)
1986 (defvar include-all-loc)
1987 (defvar vm-message-pointer)
1988 (defvar vm-folder-directory)
1989 (defvar wl-summary-buffer-elmo-folder)
1990 (defvar wl-summary-buffer-folder-name)
1991 (defvar gnus-group-name)
1992 (defvar gnus-article-current)
1993 (defvar w3m-current-url)
1994 (defvar org-selected-point)
1995 (defvar calendar-mode-map)
1996 (defvar remember-save-after-remembering)
1997 (defvar remember-data-file))
1998
1999
2000 ;;; Define the mode
2001
2002 (defvar org-mode-map (copy-keymap outline-mode-map)
2003 "Keymap for Org-mode.")
2004
2005 (defvar org-struct-menu)
2006 (defvar org-org-menu)
2007 (defvar org-tbl-menu)
2008
2009 ;; We use a before-change function to check if a table might need
2010 ;; an update.
2011 (defvar org-table-may-need-update t
2012 "Indicates of a table might need an update.
2013 This variable is set by `org-before-change-function'. `org-table-align'
2014 sets it back to nil.")
2015 (defvar org-mode-hook nil)
2016 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2017 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2018
2019
2020 ;;;###autoload
2021 (define-derived-mode org-mode outline-mode "Org"
2022 "Outline-based notes management and organizer, alias
2023 \"Carstens outline-mode for keeping track of everything.\"
2024
2025 Org-mode develops organizational tasks around a NOTES file which
2026 contains information about projects as plain text. Org-mode is
2027 implemented on top of outline-mode, which is ideal to keep the content
2028 of large files well structured. It supports ToDo items, deadlines and
2029 time stamps, which magically appear in the diary listing of the Emacs
2030 calendar. Tables are easily created with a built-in table editor.
2031 Plain text URL-like links connect to websites, emails (VM), Usenet
2032 messages (Gnus), BBDB entries, and any files related to the project.
2033 For printing and sharing of notes, an Org-mode file (or a part of it)
2034 can be exported as a structured ASCII or HTML file.
2035
2036 The following commands are available:
2037
2038 \\{org-mode-map}"
2039 (easy-menu-add org-org-menu)
2040 (easy-menu-add org-tbl-menu)
2041 (org-install-agenda-files-menu)
2042 (setq outline-regexp "\\*+")
2043 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2044 (setq outline-level 'org-outline-level)
2045 (if org-startup-truncated (setq truncate-lines t))
2046 (org-set-regexps-and-options)
2047 (set (make-local-variable 'font-lock-unfontify-region-function)
2048 'org-unfontify-region)
2049 ;; Activate before-change-function
2050 (set (make-local-variable 'org-table-may-need-update) t)
2051 (make-local-hook 'before-change-functions) ;; needed for XEmacs
2052 (add-hook 'before-change-functions 'org-before-change-function nil
2053 'local)
2054 ;; Paragraphs and auto-filling
2055 (org-set-autofill-regexps)
2056 ;; Settings for Calc embedded mode
2057 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2058 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2059 (if (and org-insert-mode-line-in-empty-file
2060 (interactive-p)
2061 (= (point-min) (point-max)))
2062 (insert " -*- mode: org -*-\n\n"))
2063
2064 ;; Get rid of Outline menus, they are not needed
2065 ;; Need to do this here because define-derived-mode sets up
2066 ;; the keymap so late.
2067 (if org-xemacs-p
2068 (progn
2069 (delete-menu-item '("Headings"))
2070 (delete-menu-item '("Show"))
2071 (delete-menu-item '("Hide"))
2072 (set-menubar-dirty-flag))
2073 (define-key org-mode-map [menu-bar headings] 'undefined)
2074 (define-key org-mode-map [menu-bar hide] 'undefined)
2075 (define-key org-mode-map [menu-bar show] 'undefined))
2076
2077 (unless org-inhibit-startup
2078 (if org-startup-with-deadline-check
2079 (call-interactively 'org-check-deadlines)
2080 (cond
2081 ((eq org-startup-folded t)
2082 (org-cycle '(4)))
2083 ((eq org-startup-folded 'content)
2084 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2085 (org-cycle '(4)) (org-cycle '(4))))))))
2086
2087 (defsubst org-current-line (&optional pos)
2088 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2089
2090 ;;; Font-Lock stuff
2091
2092 (defvar org-mouse-map (make-sparse-keymap))
2093 (define-key org-mouse-map
2094 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2095 (define-key org-mouse-map
2096 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2097
2098 (require 'font-lock)
2099
2100 (defconst org-non-link-chars "\t\n\r|<>\000")
2101 (defconst org-link-regexp
2102 (if org-allow-space-in-links
2103 (concat
2104 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2105 (concat
2106 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2107 )
2108 "Regular expression for matching links.")
2109 (defconst org-link-maybe-angles-regexp
2110 (concat "<?\\(" org-link-regexp "\\)>?")
2111 "Matches a link and optionally surrounding angle brackets.")
2112 (defconst org-protected-link-regexp
2113 (concat "\000" org-link-regexp "\000")
2114 "Matches a link and optionally surrounding angle brackets.")
2115
2116 (defconst org-ts-lengths
2117 (cons (length (format-time-string (car org-time-stamp-formats)))
2118 (length (format-time-string (cdr org-time-stamp-formats))))
2119 "This holds the lengths of the two different time formats.")
2120 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2121 "Regular expression for fast time stamp matching.")
2122 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2123 "Regular expression for fast time stamp matching.")
2124 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2125 "Regular expression matching time strings for analysis.")
2126 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2127 "Regular expression matching time stamps, with groups.")
2128 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2129 "Regular expression matching a time stamp range.")
2130 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2131 org-ts-regexp "\\)?")
2132 "Regular expression matching a time stamp or time stamp range.")
2133
2134 (defun org-activate-links (limit)
2135 "Run through the buffer and add overlays to links."
2136 (if (re-search-forward org-link-regexp limit t)
2137 (progn
2138 (add-text-properties (match-beginning 0) (match-end 0)
2139 (list 'mouse-face 'highlight
2140 'keymap org-mouse-map))
2141 t)))
2142
2143 (defun org-activate-dates (limit)
2144 "Run through the buffer and add overlays to dates."
2145 (if (re-search-forward org-tsr-regexp limit t)
2146 (progn
2147 (add-text-properties (match-beginning 0) (match-end 0)
2148 (list 'mouse-face 'highlight
2149 'keymap org-mouse-map))
2150 t)))
2151
2152 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2153 "Matches CamelCase words, possibly with a star before it.")
2154 (defun org-activate-camels (limit)
2155 "Run through the buffer and add overlays to dates."
2156 (if (re-search-forward org-camel-regexp limit t)
2157 (progn
2158 (add-text-properties (match-beginning 0) (match-end 0)
2159 (list 'mouse-face 'highlight
2160 'keymap org-mouse-map))
2161 t)))
2162
2163 (defun org-font-lock-level ()
2164 (save-excursion
2165 (org-back-to-heading t)
2166 (- (match-end 0) (match-beginning 0))))
2167
2168 (defun org-outline-level ()
2169 (save-excursion
2170 (looking-at outline-regexp)
2171 (if (match-beginning 1)
2172 (+ (org-get-string-indentation (match-string 1)) 1000)
2173 (- (match-end 0) (match-beginning 0)))))
2174
2175 (defvar org-font-lock-keywords nil)
2176
2177 (defun org-set-font-lock-defaults ()
2178 (let ((org-font-lock-extra-keywords
2179 (list
2180 '(org-activate-links (0 'org-link))
2181 '(org-activate-dates (0 'org-link))
2182 '(org-activate-camels (0 'org-link))
2183 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2184 '(1 'org-warning t))
2185 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2186 ; (list (concat "\\<" org-deadline-string) '(0 'org-warning t))
2187 ; (list (concat "\\<" org-scheduled-string) '(0 'org-warning t))
2188 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2189 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2190 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2191 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2192 ;; (3 'bold))
2193 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2194 ;; (3 'italic))
2195 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2196 ;; (3 'underline))
2197 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2198 ; '(1 'org-warning t))
2199 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2200 "\\|" org-quote-string "\\)\\>")
2201 '(1 'org-special-keyword t))
2202 '("^#.*" (0 'font-lock-comment-face t))
2203 (if org-fontify-done-headline
2204 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2205 '(1 'org-done t) '(2 'org-headline-done t))
2206 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2207 '(1 'org-done t)))
2208 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2209 (1 'org-table t))
2210 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2211 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2212 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2213 )))
2214 (set (make-local-variable 'org-font-lock-keywords)
2215 (append
2216 (if org-noutline-p ; FIXME: I am not sure if eval will work
2217 ; on XEmacs if noutline is ever ported
2218 `((eval . (list "^\\(\\*+\\).*"
2219 ,(if org-level-color-stars-only 1 0)
2220 '(nth ;; FIXME: 1<->0 ????
2221 (% (- (match-end 1) (match-beginning 1) 1)
2222 org-n-levels)
2223 org-level-faces)
2224 nil t)))
2225 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2226 (,(if org-level-color-stars-only 2 0)
2227 (nth (% (- (match-end 2) (match-beginning 2) 1)
2228 org-n-levels)
2229 org-level-faces)
2230 nil t))))
2231 org-font-lock-extra-keywords))
2232 (set (make-local-variable 'font-lock-defaults)
2233 '(org-font-lock-keywords t nil nil backward-paragraph))
2234 (kill-local-variable 'font-lock-keywords) nil))
2235
2236 (defun org-unfontify-region (beg end &optional maybe_loudly)
2237 "Remove fontification and activation overlays from links."
2238 (font-lock-default-unfontify-region beg end)
2239 (let* ((buffer-undo-list t)
2240 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2241 (inhibit-modification-hooks t)
2242 deactivate-mark buffer-file-name buffer-file-truename)
2243 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2244
2245 ;;; Visibility cycling
2246
2247 (defvar org-cycle-global-status nil)
2248 (defvar org-cycle-subtree-status nil)
2249 (defun org-cycle (&optional arg)
2250 "Visibility cycling for Org-mode.
2251
2252 - When this function is called with a prefix argument, rotate the entire
2253 buffer through 3 states (global cycling)
2254 1. OVERVIEW: Show only top-level headlines.
2255 2. CONTENTS: Show all headlines of all levels, but no body text.
2256 3. SHOW ALL: Show everything.
2257
2258 - When point is at the beginning of a headline, rotate the subtree started
2259 by this line through 3 different states (local cycling)
2260 1. FOLDED: Only the main headline is shown.
2261 2. CHILDREN: The main headline and the direct children are shown. From
2262 this state, you can move to one of the children and
2263 zoom in further.
2264 3. SUBTREE: Show the entire subtree, including body text.
2265
2266 - When there is a numeric prefix, go up to a heading with level ARG, do
2267 a `show-subtree' and return to the previous cursor position. If ARG
2268 is negative, go up that many levels.
2269
2270 - When point is not at the beginning of a headline, execute
2271 `indent-relative', like TAB normally does. See the option
2272 `org-cycle-emulate-tab' for details.
2273
2274 - Special case: if point is the the beginning of the buffer and there is
2275 no headline in line 1, this function will act as if called with prefix arg."
2276 (interactive "P")
2277
2278 (if (or (and (bobp) (not (looking-at outline-regexp)))
2279 (equal arg '(4)))
2280 ;; special case: use global cycling
2281 (setq arg t))
2282
2283 (let ((outline-regexp
2284 (if org-cycle-include-plain-lists
2285 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2286 outline-regexp)))
2287
2288 (cond
2289
2290 ((org-at-table-p 'any)
2291 ;; Enter the table or move to the next field in the table
2292 (or (org-table-recognize-table.el)
2293 (progn
2294 (org-table-justify-field-maybe)
2295 (org-table-next-field))))
2296
2297 ((eq arg t) ;; Global cycling
2298
2299 (cond
2300 ((and (eq last-command this-command)
2301 (eq org-cycle-global-status 'overview))
2302 ;; We just created the overview - now do table of contents
2303 ;; This can be slow in very large buffers, so indicate action
2304 (message "CONTENTS...")
2305 (save-excursion
2306 ;; Visit all headings and show their offspring
2307 (goto-char (point-max))
2308 (catch 'exit
2309 (while (and (progn (condition-case nil
2310 (outline-previous-visible-heading 1)
2311 (error (goto-char (point-min))))
2312 t)
2313 (looking-at outline-regexp))
2314 (show-branches)
2315 (if (bobp) (throw 'exit nil))))
2316 (message "CONTENTS...done"))
2317 (setq org-cycle-global-status 'contents)
2318 (run-hook-with-args 'org-cycle-hook 'contents))
2319
2320 ((and (eq last-command this-command)
2321 (eq org-cycle-global-status 'contents))
2322 ;; We just showed the table of contents - now show everything
2323 (show-all)
2324 (message "SHOW ALL")
2325 (setq org-cycle-global-status 'all)
2326 (run-hook-with-args 'org-cycle-hook 'all))
2327
2328 (t
2329 ;; Default action: go to overview
2330 (hide-sublevels 1)
2331 (message "OVERVIEW")
2332 (setq org-cycle-global-status 'overview)
2333 (run-hook-with-args 'org-cycle-hook 'overview))))
2334
2335 ((integerp arg)
2336 ;; Show-subtree, ARG levels up from here.
2337 (save-excursion
2338 (org-back-to-heading)
2339 (outline-up-heading (if (< arg 0) (- arg)
2340 (- (outline-level) arg)))
2341 (org-show-subtree)))
2342
2343 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2344 ;; At a heading: rotate between three different views
2345 (org-back-to-heading)
2346 (let ((goal-column 0) eoh eol eos)
2347 ;; First, some boundaries
2348 (save-excursion
2349 (org-back-to-heading)
2350 (save-excursion
2351 (beginning-of-line 2)
2352 (while (and (not (eobp)) ;; this is like `next-line'
2353 (get-char-property (1- (point)) 'invisible))
2354 (beginning-of-line 2)) (setq eol (point)))
2355 (outline-end-of-heading) (setq eoh (point))
2356 (outline-end-of-subtree) (setq eos (point))
2357 (outline-next-heading))
2358 ;; Find out what to do next and set `this-command'
2359 (cond
2360 ((= eos eoh)
2361 ;; Nothing is hidden behind this heading
2362 (message "EMPTY ENTRY")
2363 (setq org-cycle-subtree-status nil))
2364 ((>= eol eos)
2365 ;; Entire subtree is hidden in one line: open it
2366 (org-show-entry)
2367 (show-children)
2368 (message "CHILDREN")
2369 (setq org-cycle-subtree-status 'children)
2370 (run-hook-with-args 'org-cycle-hook 'children))
2371 ((and (eq last-command this-command)
2372 (eq org-cycle-subtree-status 'children))
2373 ;; We just showed the children, now show everything.
2374 (org-show-subtree)
2375 (message "SUBTREE")
2376 (setq org-cycle-subtree-status 'subtree)
2377 (run-hook-with-args 'org-cycle-hook 'subtree))
2378 (t
2379 ;; Default action: hide the subtree.
2380 (hide-subtree)
2381 (message "FOLDED")
2382 (setq org-cycle-subtree-status 'folded)
2383 (run-hook-with-args 'org-cycle-hook 'folded)))))
2384
2385 ;; TAB emulation
2386 (buffer-read-only (org-back-to-heading))
2387 ((if (and (eq org-cycle-emulate-tab 'white)
2388 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2389 t
2390 (eq org-cycle-emulate-tab t))
2391 (if (and (looking-at "[ \n\r\t]")
2392 (string-match "^[ \t]*$" (buffer-substring
2393 (point-at-bol) (point))))
2394 (progn
2395 (beginning-of-line 1)
2396 (and (looking-at "[ \t]+") (replace-match ""))))
2397 (indent-relative))
2398
2399 (t (save-excursion
2400 (org-back-to-heading)
2401 (org-cycle))))))
2402
2403 (defun org-optimize-window-after-visibility-change (state)
2404 "Adjust the window after a change in outline visibility.
2405 This function is the default value of the hook `org-cycle-hook'."
2406 (cond
2407 ((eq state 'overview) (org-first-headline-recenter 1))
2408 ((eq state 'content) nil)
2409 ((eq state 'all) nil)
2410 ((eq state 'folded) nil)
2411 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2412 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2413
2414 (defun org-subtree-end-visible-p ()
2415 "Is the end of the current subtree visible?"
2416 (pos-visible-in-window-p
2417 (save-excursion (outline-end-of-subtree) (point))))
2418
2419 (defun org-first-headline-recenter (&optional N)
2420 "Move cursor to the first headline and recenter the headline.
2421 Optional argument N means, put the headline into the Nth line of the window."
2422 (goto-char (point-min))
2423 (when (re-search-forward (concat "^" outline-regexp) nil t)
2424 (beginning-of-line)
2425 (recenter (prefix-numeric-value N))))
2426
2427 (defvar org-goto-window-configuration nil)
2428 (defvar org-goto-marker nil)
2429 (defvar org-goto-map (make-sparse-keymap))
2430 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2431 (while (setq cmd (pop cmds))
2432 (substitute-key-definition cmd cmd org-goto-map global-map)))
2433 (define-key org-goto-map "\C-m" 'org-goto-ret)
2434 (define-key org-goto-map [(left)] 'org-goto-left)
2435 (define-key org-goto-map [(right)] 'org-goto-right)
2436 (define-key org-goto-map [(?q)] 'org-goto-quit)
2437 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2438 (define-key org-goto-map "\C-i" 'org-cycle)
2439 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2440 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2441 (define-key org-goto-map "n" 'outline-next-visible-heading)
2442 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2443 (define-key org-goto-map "f" 'outline-forward-same-level)
2444 (define-key org-goto-map "b" 'outline-backward-same-level)
2445 (define-key org-goto-map "u" 'outline-up-heading)
2446 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2447 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2448 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2449 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2450 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2451 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2452 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2453
2454 (defconst org-goto-help
2455 "Select a location to jump to, press RET
2456 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2457
2458 (defun org-goto ()
2459 "Go to a different location of the document, keeping current visibility.
2460
2461 When you want to go to a different location in a document, the fastest way
2462 is often to fold the entire buffer and then dive into the tree. This
2463 method has the disadvantage, that the previous location will be folded,
2464 which may not be what you want.
2465
2466 This command works around this by showing a copy of the current buffer in
2467 overview mode. You can dive into the tree in that copy, to find the
2468 location you want to reach. When pressing RET, the command returns to the
2469 original buffer in which the visibility is still unchanged. It then jumps
2470 to the new location, making it and the headline hierarchy above it visible."
2471 (interactive)
2472 (let* ((org-goto-start-pos (point))
2473 (selected-point
2474 (org-get-location (current-buffer) org-goto-help)))
2475 (if selected-point
2476 (progn
2477 (goto-char selected-point)
2478 (if (org-invisible-p) (org-show-hierarchy-above)))
2479 (error "Quit"))))
2480
2481 (defun org-get-location (buf help)
2482 "Let the user select a location in the Org-mode buffer BUF.
2483 This function uses a recursive edit. It returns the selected position
2484 or nil."
2485 (let (org-selected-point)
2486 (save-excursion
2487 (save-window-excursion
2488 (delete-other-windows)
2489 (switch-to-buffer (get-buffer-create "*org-goto*"))
2490 (with-output-to-temp-buffer "*Help*"
2491 (princ help))
2492 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2493 (setq buffer-read-only nil)
2494 (erase-buffer)
2495 (insert-buffer-substring buf)
2496 (let ((org-startup-truncated t)
2497 (org-startup-folded t)
2498 (org-startup-with-deadline-check nil))
2499 (org-mode))
2500 (setq buffer-read-only t)
2501 (if (boundp 'org-goto-start-pos)
2502 (goto-char org-goto-start-pos)
2503 (goto-char (point-min)))
2504 (org-beginning-of-line)
2505 (message "Select location and press RET")
2506 ;; now we make sure that during selection, ony very few keys work
2507 ;; and that it is impossible to switch to another window.
2508 (let ((gm (current-global-map))
2509 (overriding-local-map org-goto-map))
2510 (unwind-protect
2511 (progn
2512 (use-global-map org-goto-map)
2513 (recursive-edit))
2514 (use-global-map gm)))))
2515 (kill-buffer "*org-goto*")
2516 org-selected-point))
2517
2518 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2519 (defun org-goto-ret (&optional arg)
2520 "Finish org-goto by going to the new location."
2521 (interactive "P")
2522 (setq org-selected-point (point)
2523 current-prefix-arg arg)
2524 (throw 'exit nil))
2525
2526 (defun org-goto-left ()
2527 "Finish org-goto by going to the new location."
2528 (interactive)
2529 (if (org-on-heading-p)
2530 (progn
2531 (beginning-of-line 1)
2532 (setq org-selected-point (point)
2533 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2534 (throw 'exit nil))
2535 (error "Not on a heading")))
2536
2537 (defun org-goto-right ()
2538 "Finish org-goto by going to the new location."
2539 (interactive)
2540 (if (org-on-heading-p)
2541 (progn
2542 (outline-end-of-subtree)
2543 (or (eobp) (forward-char 1))
2544 (setq org-selected-point (point)
2545 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2546 (throw 'exit nil))
2547 (error "Not on a heading")))
2548
2549 (defun org-goto-quit ()
2550 "Finish org-goto without cursor motion."
2551 (interactive)
2552 (setq org-selected-point nil)
2553 (throw 'exit nil))
2554
2555 ;;; Promotion, Demotion, Inserting new headlines
2556
2557 (defvar org-ignore-region nil
2558 "To temporarily disable the active region.")
2559
2560 (defun org-insert-heading (&optional force-heading)
2561 "Insert a new heading or item with same depth at point.
2562 If ARG is non-nil"
2563 (interactive "P")
2564 (when (or force-heading (not (org-insert-item)))
2565 (let* ((head (save-excursion
2566 (condition-case nil
2567 (org-back-to-heading)
2568 (error (outline-next-heading)))
2569 (prog1 (match-string 0)
2570 (funcall outline-level)))))
2571 (unless (bolp) (newline))
2572 (insert head)
2573 (unless (eolp)
2574 (save-excursion (newline-and-indent)))
2575 (unless (equal (char-before) ?\ )
2576 (insert " "))
2577 (run-hooks 'org-insert-heading-hook))))
2578
2579 (defun org-insert-item ()
2580 "Insert a new item at the current level.
2581 Return t when tings worked, nil when we are not in an item."
2582 (when (save-excursion
2583 (condition-case nil
2584 (progn
2585 (org-beginning-of-item)
2586 (org-at-item-p)
2587 t)
2588 (error nil)))
2589 (unless (bolp) (newline))
2590 (insert (match-string 0))
2591 (org-maybe-renumber-ordered-list)
2592 t))
2593
2594 (defun org-insert-todo-heading (arg)
2595 "Insert a new heading with the same level and TODO state as current heading.
2596 If the heading has no TODO state, or if the state is DONE, use the first
2597 state (TODO by default). Also with prefix arg, force first state."
2598 (interactive "P")
2599 (org-insert-heading)
2600 (save-excursion
2601 (org-back-to-heading)
2602 (outline-previous-heading)
2603 (looking-at org-todo-line-regexp))
2604 (if (or arg
2605 (not (match-beginning 2))
2606 (equal (match-string 2) org-done-string))
2607 (insert (car org-todo-keywords) " ")
2608 (insert (match-string 2) " ")))
2609
2610 (defun org-promote-subtree ()
2611 "Promote the entire subtree.
2612 See also `org-promote'."
2613 (interactive)
2614 (save-excursion
2615 (org-map-tree 'org-promote)))
2616
2617 (defun org-demote-subtree ()
2618 "Demote the entire subtree. See `org-demote'.
2619 See also `org-promote'."
2620 (interactive)
2621 (save-excursion
2622 (org-map-tree 'org-demote)))
2623
2624 (defun org-do-promote ()
2625 "Promote the current heading higher up the tree.
2626 If the region is active in `transient-mark-mode', promote all headings
2627 in the region."
2628 (interactive)
2629 (save-excursion
2630 (if (org-region-active-p)
2631 (org-map-region 'org-promote (region-beginning) (region-end))
2632 (org-promote)))
2633 (org-fix-position-after-promote))
2634
2635 (defun org-do-demote ()
2636 "Demote the current heading lower down the tree.
2637 If the region is active in `transient-mark-mode', demote all headings
2638 in the region."
2639 (interactive)
2640 (save-excursion
2641 (if (org-region-active-p)
2642 (org-map-region 'org-demote (region-beginning) (region-end))
2643 (org-demote)))
2644 (org-fix-position-after-promote))
2645
2646 (defun org-fix-position-after-promote ()
2647 "Make sure that after pro/demotion cursor position is right."
2648 (and (equal (char-after) ?\ )
2649 (equal (char-before) ?*)
2650 (forward-char 1)))
2651
2652 (defun org-promote ()
2653 "Promote the current heading higher up the tree.
2654 If the region is active in `transient-mark-mode', promote all headings
2655 in the region."
2656 (org-back-to-heading t)
2657 (let* ((level (save-match-data (funcall outline-level)))
2658 (up-head (make-string (1- level) ?*)))
2659 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2660 (replace-match up-head nil t)
2661 (if org-adapt-indentation
2662 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2663
2664 (defun org-demote ()
2665 "Demote the current heading lower down the tree.
2666 If the region is active in `transient-mark-mode', demote all headings
2667 in the region."
2668 (org-back-to-heading t)
2669 (let* ((level (save-match-data (funcall outline-level)))
2670 (down-head (make-string (1+ level) ?*)))
2671 (replace-match down-head nil t)
2672 (if org-adapt-indentation
2673 (org-fixup-indentation "^ " " " "^\\S-"))))
2674
2675 (defun org-map-tree (fun)
2676 "Call FUN for every heading underneath the current one."
2677 (org-back-to-heading)
2678 (let ((level (outline-level)))
2679 (save-excursion
2680 (funcall fun)
2681 (while (and (progn
2682 (outline-next-heading)
2683 (> (funcall outline-level) level))
2684 (not (eobp)))
2685 (funcall fun)))))
2686
2687 (defun org-map-region (fun beg end)
2688 "Call FUN for every heading between BEG and END."
2689 (let ((org-ignore-region t))
2690 (save-excursion
2691 (setq end (copy-marker end))
2692 (goto-char beg)
2693 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2694 (< (point) end))
2695 (funcall fun))
2696 (while (and (progn
2697 (outline-next-heading)
2698 (< (point) end))
2699 (not (eobp)))
2700 (funcall fun)))))
2701
2702 (defun org-fixup-indentation (from to prohibit)
2703 "Change the indentation in the current entry by re-replacing FROM with TO.
2704 However, if the regexp PROHIBIT matches at all, don't do anything.
2705 This is being used to change indentation along with the length of the
2706 heading marker. But if there are any lines which are not indented, nothing
2707 is changed at all."
2708 (save-excursion
2709 (let ((end (save-excursion (outline-next-heading)
2710 (point-marker))))
2711 (unless (save-excursion (re-search-forward prohibit end t))
2712 (while (re-search-forward from end t)
2713 (replace-match to)
2714 (beginning-of-line 2)))
2715 (move-marker end nil))))
2716
2717 ;;; Vertical tree motion, cutting and pasting of subtrees
2718
2719 (defun org-move-subtree-up (&optional arg)
2720 "Move the current subtree up past ARG headlines of the same level."
2721 (interactive "p")
2722 (org-move-subtree-down (- (prefix-numeric-value arg))))
2723
2724 (defun org-move-subtree-down (&optional arg)
2725 "Move the current subtree down past ARG headlines of the same level."
2726 (interactive "p")
2727 (setq arg (prefix-numeric-value arg))
2728 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2729 'outline-get-last-sibling))
2730 (ins-point (make-marker))
2731 (cnt (abs arg))
2732 beg end txt folded)
2733 ;; Select the tree
2734 (org-back-to-heading)
2735 (setq beg (point))
2736 (save-match-data
2737 (save-excursion (outline-end-of-heading)
2738 (setq folded (org-invisible-p)))
2739 (outline-end-of-subtree))
2740 (outline-next-heading)
2741 (setq end (point))
2742 ;; Find insertion point, with error handling
2743 (goto-char beg)
2744 (while (> cnt 0)
2745 (or (and (funcall movfunc) (looking-at outline-regexp))
2746 (progn (goto-char beg)
2747 (error "Cannot move past superior level or buffer limit")))
2748 (setq cnt (1- cnt)))
2749 (if (> arg 0)
2750 ;; Moving forward - still need to move over subtree
2751 (progn (outline-end-of-subtree)
2752 (outline-next-heading)
2753 (if (not (or (looking-at (concat "^" outline-regexp))
2754 (bolp)))
2755 (newline))))
2756 (move-marker ins-point (point))
2757 (setq txt (buffer-substring beg end))
2758 (delete-region beg end)
2759 (insert txt)
2760 (goto-char ins-point)
2761 (if folded (hide-subtree))
2762 (move-marker ins-point nil)))
2763
2764 (defvar org-subtree-clip ""
2765 "Clipboard for cut and paste of subtrees.
2766 This is actually only a copy of the kill, because we use the normal kill
2767 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2768
2769 (defvar org-subtree-clip-folded nil
2770 "Was the last copied subtree folded?
2771 This is used to fold the tree back after pasting.")
2772
2773 (defun org-cut-subtree ()
2774 "Cut the current subtree into the clipboard.
2775 This is a short-hand for marking the subtree and then cutting it."
2776 (interactive)
2777 (org-copy-subtree 'cut))
2778
2779 (defun org-copy-subtree (&optional cut)
2780 "Cut the current subtree into the clipboard.
2781 This is a short-hand for marking the subtree and then copying it.
2782 If CUT is non nil, actually cut the subtree."
2783 (interactive)
2784 (let (beg end folded)
2785 (org-back-to-heading)
2786 (setq beg (point))
2787 (save-match-data
2788 (save-excursion (outline-end-of-heading)
2789 (setq folded (org-invisible-p)))
2790 (outline-end-of-subtree))
2791 (if (equal (char-after) ?\n) (forward-char 1))
2792 (setq end (point))
2793 (goto-char beg)
2794 (when (> end beg)
2795 (setq org-subtree-clip-folded folded)
2796 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2797 (setq org-subtree-clip (current-kill 0))
2798 (message "%s: Subtree with %d characters"
2799 (if cut "Cut" "Copied")
2800 (length org-subtree-clip)))))
2801
2802 (defun org-paste-subtree (&optional level tree)
2803 "Paste the clipboard as a subtree, with modification of headline level.
2804 The entire subtree is promoted or demoted in order to match a new headline
2805 level. By default, the new level is derived from the visible headings
2806 before and after the insertion point, and taken to be the inferior headline
2807 level of the two. So if the previous visible heading is level 3 and the
2808 next is level 4 (or vice versa), level 4 will be used for insertion.
2809 This makes sure that the subtree remains an independent subtree and does
2810 not swallow low level entries.
2811
2812 You can also force a different level, either by using a numeric prefix
2813 argument, or by inserting the heading marker by hand. For example, if the
2814 cursor is after \"*****\", then the tree will be shifted to level 5.
2815
2816 If you want to insert the tree as is, just use \\[yank].
2817
2818 If optional TREE is given, use this text instead of the kill ring."
2819 (interactive "P")
2820 (unless (org-kill-is-subtree-p tree)
2821 (error
2822 (substitute-command-keys
2823 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2824 (let* ((txt (or tree (current-kill 0)))
2825 (^re (concat "^\\(" outline-regexp "\\)"))
2826 (re (concat "\\(" outline-regexp "\\)"))
2827 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2828
2829 (old-level (if (string-match ^re txt)
2830 (- (match-end 0) (match-beginning 0))
2831 -1))
2832 (force-level (cond (level (prefix-numeric-value level))
2833 ((string-match
2834 ^re_ (buffer-substring (point-at-bol) (point)))
2835 (- (match-end 0) (match-beginning 0)))
2836 (t nil)))
2837 (previous-level (save-excursion
2838 (condition-case nil
2839 (progn
2840 (outline-previous-visible-heading 1)
2841 (if (looking-at re)
2842 (- (match-end 0) (match-beginning 0))
2843 1))
2844 (error 1))))
2845 (next-level (save-excursion
2846 (condition-case nil
2847 (progn
2848 (outline-next-visible-heading 1)
2849 (if (looking-at re)
2850 (- (match-end 0) (match-beginning 0))
2851 1))
2852 (error 1))))
2853 (new-level (or force-level (max previous-level next-level)))
2854 (shift (if (or (= old-level -1)
2855 (= new-level -1)
2856 (= old-level new-level))
2857 0
2858 (- new-level old-level)))
2859 (shift1 shift)
2860 (delta (if (> shift 0) -1 1))
2861 (func (if (> shift 0) 'org-demote 'org-promote))
2862 beg end)
2863 ;; Remove the forces level indicator
2864 (if force-level
2865 (delete-region (point-at-bol) (point)))
2866 ;; Make sure we start at the beginning of an empty line
2867 (if (not (bolp)) (insert "\n"))
2868 (if (not (looking-at "[ \t]*$"))
2869 (progn (insert "\n") (backward-char 1)))
2870 ;; Paste
2871 (setq beg (point))
2872 (insert txt)
2873 (setq end (point))
2874 (goto-char beg)
2875 ;; Shift if necessary
2876 (if (= shift 0)
2877 (message "Pasted at level %d, without shift" new-level)
2878 (save-restriction
2879 (narrow-to-region beg end)
2880 (while (not (= shift 0))
2881 (org-map-region func (point-min) (point-max))
2882 (setq shift (+ delta shift)))
2883 (goto-char (point-min))
2884 (message "Pasted at level %d, with shift by %d levels"
2885 new-level shift1)))
2886 (if (and (eq org-subtree-clip (current-kill 0))
2887 org-subtree-clip-folded)
2888 ;; The tree was folded before it was killed/copied
2889 (hide-subtree))))
2890
2891 (defun org-kill-is-subtree-p (&optional txt)
2892 "Check if the current kill is an outline subtree, or a set of trees.
2893 Returns nil if kill does not start with a headline, or if the first
2894 headline level is not the largest headline level in the tree.
2895 So this will actually accept several entries of equal levels as well,
2896 which is OK for `org-paste-subtree'.
2897 If optional TXT is given, check this string instead of the current kill."
2898 (let* ((kill (or txt (current-kill 0) ""))
2899 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2900 (- (match-end 0) (match-beginning 0))))
2901 (re (concat "^" outline-regexp))
2902 (start 1))
2903 (if (not start-level)
2904 nil ;; does not even start with a heading
2905 (catch 'exit
2906 (while (setq start (string-match re kill (1+ start)))
2907 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2908 (throw 'exit nil)))
2909 t))))
2910
2911 ;;; Plain list item
2912
2913 (defun org-at-item-p ()
2914 "Is point in a line starting a hand-formatted item?"
2915 (let ((llt org-plain-list-ordered-item-terminator))
2916 (save-excursion
2917 (goto-char (point-at-bol))
2918 (looking-at
2919 (cond
2920 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2921 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2922 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2923 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
2924
2925 (defun org-get-indentation ()
2926 "Get the indentation of the current line, ionterpreting tabs."
2927 (save-excursion
2928 (beginning-of-line 1)
2929 (skip-chars-forward " \t")
2930 (current-column)))
2931
2932 (defun org-beginning-of-item ()
2933 "Go to the beginning of the current hand-formatted item.
2934 If the cursor is not in an item, throw an error."
2935 (let ((pos (point))
2936 (limit (save-excursion (org-back-to-heading)
2937 (beginning-of-line 2) (point)))
2938 ind ind1)
2939 (if (org-at-item-p)
2940 (beginning-of-line 1)
2941 (beginning-of-line 1)
2942 (skip-chars-forward " \t")
2943 (setq ind (current-column))
2944 (if (catch 'exit
2945 (while t
2946 (beginning-of-line 0)
2947 (if (< (point) limit) (throw 'exit nil))
2948 (unless (looking-at " \t]*$")
2949 (skip-chars-forward " \t")
2950 (setq ind1 (current-column))
2951 (if (< ind1 ind)
2952 (throw 'exit (org-at-item-p))))))
2953 nil
2954 (goto-char pos)
2955 (error "Not in an item")))))
2956
2957 (defun org-end-of-item ()
2958 "Go to the beginning of the current hand-formatted item.
2959 If the cursor is not in an item, throw an error."
2960 (let ((pos (point))
2961 (limit (save-excursion (outline-next-heading) (point)))
2962 (ind (save-excursion
2963 (org-beginning-of-item)
2964 (skip-chars-forward " \t")
2965 (current-column)))
2966 ind1)
2967 (if (catch 'exit
2968 (while t
2969 (beginning-of-line 2)
2970 (if (>= (point) limit) (throw 'exit t))
2971 (unless (looking-at "[ \t]*$")
2972 (skip-chars-forward " \t")
2973 (setq ind1 (current-column))
2974 (if (<= ind1 ind) (throw 'exit t)))))
2975 (beginning-of-line 1)
2976 (goto-char pos)
2977 (error "Not in an item"))))
2978
2979 (defun org-move-item-down (arg)
2980 "Move the plain list item at point down, i.e. swap with following item.
2981 Subitems (items with larger indentation are considered part of the item,
2982 so this really moves item trees."
2983 (interactive "p")
2984 (let (beg end ind ind1 (pos (point)) txt)
2985 (org-beginning-of-item)
2986 (setq beg (point))
2987 (setq ind (org-get-indentation))
2988 (org-end-of-item)
2989 (setq end (point))
2990 (setq ind1 (org-get-indentation))
2991 (if (and (org-at-item-p) (= ind ind1))
2992 (progn
2993 (org-end-of-item)
2994 (setq txt (buffer-substring beg end))
2995 (save-excursion
2996 (delete-region beg end))
2997 (setq pos (point))
2998 (insert txt)
2999 (goto-char pos)
3000 (org-maybe-renumber-ordered-list))
3001 (goto-char pos)
3002 (error "Cannot move this item further down"))))
3003
3004 (defun org-move-item-up (arg)
3005 "Move the plain list item at point up, i.e. swap with previous item.
3006 Subitems (items with larger indentation are considered part of the item,
3007 so this really moves item trees."
3008 (interactive "p")
3009 (let (beg end ind ind1 (pos (point)) txt)
3010 (org-beginning-of-item)
3011 (setq beg (point))
3012 (setq ind (org-get-indentation))
3013 (org-end-of-item)
3014 (setq end (point))
3015 (goto-char beg)
3016 (catch 'exit
3017 (while t
3018 (beginning-of-line 0)
3019 (if (looking-at "[ \t]*$")
3020 nil
3021 (if (<= (setq ind1 (org-get-indentation)) ind)
3022 (throw 'exit t)))))
3023 (condition-case nil
3024 (org-beginning-of-item)
3025 (error (goto-char beg)
3026 (error "Cannot move this item further up")))
3027 (setq ind1 (org-get-indentation))
3028 (if (and (org-at-item-p) (= ind ind1))
3029 (progn
3030 (setq txt (buffer-substring beg end))
3031 (save-excursion
3032 (delete-region beg end))
3033 (setq pos (point))
3034 (insert txt)
3035 (goto-char pos)
3036 (org-maybe-renumber-ordered-list))
3037 (goto-char pos)
3038 (error "Cannot move this item further up"))))
3039
3040 (defun org-maybe-renumber-ordered-list ()
3041 "Renumber the ordered list at point if setup allows it.
3042 This tests the user option `org-auto-renumber-ordered-lists' before
3043 doing the renumbering."
3044 (and org-auto-renumber-ordered-lists
3045 (org-at-item-p)
3046 (match-beginning 3)
3047 (org-renumber-ordered-list 1)))
3048
3049 (defun org-get-string-indentation (s)
3050 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3051 (let ((n -1) (i 0) (w tab-width) c)
3052 (catch 'exit
3053 (while (< (setq n (1+ n)) (length s))
3054 (setq c (aref s n))
3055 (cond ((= c ?\ ) (setq i (1+ i)))
3056 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3057 (t (throw 'exit t)))))
3058 i))
3059
3060 (defun org-renumber-ordered-list (arg)
3061 "Renumber an ordered plain list.
3062 Cursor neext to be in the first line of an item, the line that starts
3063 with something like \"1.\" or \"2)\"."
3064 (interactive "p")
3065 (unless (and (org-at-item-p)
3066 (match-beginning 3))
3067 (error "This is not an ordered list"))
3068 (let ((line (org-current-line))
3069 (col (current-column))
3070 (ind (org-get-string-indentation
3071 (buffer-substring (point-at-bol) (match-beginning 3))))
3072 (term (substring (match-string 3) -1))
3073 ind1 (n (1- arg)))
3074 ;; find where this list begins
3075 (catch 'exit
3076 (while t
3077 (catch 'next
3078 (beginning-of-line 0)
3079 (if (looking-at "[ \t]*$") (throw 'next t))
3080 (skip-chars-forward " \t") (setq ind1 (current-column))
3081 (if (or (< ind1 ind)
3082 (and (= ind1 ind)
3083 (not (org-at-item-p))))
3084 (throw 'exit t)))))
3085 ;; Walk forward and replace these numbers
3086 (catch 'exit
3087 (while t
3088 (catch 'next
3089 (beginning-of-line 2)
3090 (if (eobp) (throw 'exit nil))
3091 (if (looking-at "[ \t]*$") (throw 'next nil))
3092 (skip-chars-forward " \t") (setq ind1 (current-column))
3093 (if (> ind1 ind) (throw 'next t))
3094 (if (< ind1 ind) (throw 'exit t))
3095 (if (not (org-at-item-p)) (throw 'exit nil))
3096 (if (not (match-beginning 3))
3097 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3098 (delete-region (match-beginning 3) (1- (match-end 3)))
3099 (goto-char (match-beginning 3))
3100 (insert (format "%d" (setq n (1+ n)))))))
3101 (goto-line line)
3102 (move-to-column col)))
3103
3104 (defvar org-last-indent-begin-marker (make-marker))
3105 (defvar org-last-indent-end-marker (make-marker))
3106
3107
3108 (defun org-outdent-item (arg)
3109 "Outdent a local list item."
3110 (interactive "p")
3111 (org-indent-item (- arg)))
3112
3113 (defun org-indent-item (arg)
3114 "Indent a local list item."
3115 (interactive "p")
3116 (unless (org-at-item-p)
3117 (error "Not on an item"))
3118 (let (beg end ind ind1)
3119 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3120 (setq beg org-last-indent-begin-marker
3121 end org-last-indent-end-marker)
3122 (org-beginning-of-item)
3123 (setq beg (move-marker org-last-indent-begin-marker (point)))
3124 (org-end-of-item)
3125 (setq end (move-marker org-last-indent-end-marker (point))))
3126 (goto-char beg)
3127 (skip-chars-forward " \t") (setq ind (current-column))
3128 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3129 (while (< (point) end)
3130 (beginning-of-line 1)
3131 (skip-chars-forward " \t") (setq ind1 (current-column))
3132 (delete-region (point-at-bol) (point))
3133 (indent-to-column (+ ind1 arg))
3134 (beginning-of-line 2))
3135 (goto-char beg)))
3136
3137
3138 ;;; Archiving
3139
3140 (defun org-archive-subtree ()
3141 "Move the current subtree to the archive.
3142 The archive can be a certain top-level heading in the current file, or in
3143 a different file. The tree will be moved to that location, the subtree
3144 heading be marked DONE, and the current time will be added."
3145 (interactive)
3146 ;; Save all relevant TODO keyword-relatex variables
3147 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3148 (tr-org-todo-keywords org-todo-keywords)
3149 (tr-org-todo-interpretation org-todo-interpretation)
3150 (tr-org-done-string org-done-string)
3151 (tr-org-todo-regexp org-todo-regexp)
3152 (tr-org-todo-line-regexp org-todo-line-regexp)
3153 (this-buffer (current-buffer))
3154 file heading buffer level newfile-p)
3155 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3156 (progn
3157 (setq file (format (match-string 1 org-archive-location)
3158 (file-name-nondirectory (buffer-file-name)))
3159 heading (match-string 2 org-archive-location)))
3160 (error "Invalid `org-archive-location'"))
3161 (if (> (length file) 0)
3162 (setq newfile-p (not (file-exists-p file))
3163 buffer (find-file-noselect file))
3164 (setq buffer (current-buffer)))
3165 (unless buffer
3166 (error "Cannot access file \"%s\"" file))
3167 (if (and (> (length heading) 0)
3168 (string-match "^\\*+" heading))
3169 (setq level (match-end 0))
3170 (setq heading nil level 0))
3171 (save-excursion
3172 ;; We first only copy, in case something goes wrong
3173 ;; we need to protect this-command, to avoid kill-region sets it,
3174 ;; which would lead to duplication of subtrees
3175 (let (this-command) (org-copy-subtree))
3176 (set-buffer buffer)
3177 ;; Enforce org-mode for the archive buffer
3178 (if (not (eq major-mode 'org-mode))
3179 ;; Force the mode for future visits.
3180 (let ((org-insert-mode-line-in-empty-file t))
3181 (call-interactively 'org-mode)))
3182 (when newfile-p
3183 (goto-char (point-max))
3184 (insert (format "\nArchived entries from file %s\n\n"
3185 (buffer-file-name this-buffer))))
3186 ;; Force the TODO keywords of the original buffer
3187 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3188 (org-todo-keywords tr-org-todo-keywords)
3189 (org-todo-interpretation tr-org-todo-interpretation)
3190 (org-done-string tr-org-done-string)
3191 (org-todo-regexp tr-org-todo-regexp)
3192 (org-todo-line-regexp tr-org-todo-line-regexp))
3193 (goto-char (point-min))
3194 (if heading
3195 (progn
3196 (if (re-search-forward
3197 (concat "\\(^\\|\r\\)"
3198 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3199 nil t)
3200 (goto-char (match-end 0))
3201 ;; Heading not found, just insert it at the end
3202 (goto-char (point-max))
3203 (or (bolp) (insert "\n"))
3204 (insert "\n" heading "\n")
3205 (end-of-line 0))
3206 ;; Make the heading visible, and the following as well
3207 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3208 (if (re-search-forward
3209 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3210 nil t)
3211 (progn (goto-char (match-beginning 0)) (insert "\n")
3212 (beginning-of-line 0))
3213 (goto-char (point-max)) (insert "\n")))
3214 (goto-char (point-max)) (insert "\n"))
3215 ;; Paste
3216 (org-paste-subtree (1+ level))
3217 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3218 (if org-archive-mark-done
3219 (org-todo (length org-todo-keywords)))
3220 ;; Move cursor to right after the TODO keyword
3221 (when org-archive-stamp-time
3222 (beginning-of-line 1)
3223 (looking-at org-todo-line-regexp)
3224 (goto-char (or (match-end 2) (match-beginning 3)))
3225 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3226 (current-time))
3227 ")"))
3228 ;; Save the buffer, if it is not the same buffer.
3229 (if (not (eq this-buffer buffer)) (save-buffer))))
3230 ;; Here we are back in the original buffer. Everything seems to have
3231 ;; worked. So now cut the tree and finish up.
3232 (let (this-command) (org-cut-subtree))
3233 (if (looking-at "[ \t]*$") (kill-line))
3234 (message "Subtree archived %s"
3235 (if (eq this-buffer buffer)
3236 (concat "under heading: " heading)
3237 (concat "in file: " (abbreviate-file-name file))))))
3238
3239 ;;; Completion
3240
3241 (defun org-complete (&optional arg)
3242 "Perform completion on word at point.
3243 At the beginning of a headline, this completes TODO keywords as given in
3244 `org-todo-keywords'.
3245 If the current word is preceded by a backslash, completes the TeX symbols
3246 that are supported for HTML support.
3247 If the current word is preceded by \"#+\", completes special words for
3248 setting file options.
3249 At all other locations, this simply calls `ispell-complete-word'."
3250 (interactive "P")
3251 (catch 'exit
3252 (let* ((end (point))
3253 (beg (save-excursion
3254 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3255 (skip-chars-backward "a-zA-Z0-9_:$")
3256 (point)))
3257 (camel (equal (char-before beg) ?*))
3258 (texp (equal (char-before beg) ?\\))
3259 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3260 beg)
3261 "#+"))
3262 (pattern (buffer-substring-no-properties beg end))
3263 (completion-ignore-case opt)
3264 (type nil)
3265 (tbl nil)
3266 (table (cond
3267 (opt
3268 (setq type :opt)
3269 (mapcar (lambda (x)
3270 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3271 (cons (match-string 2 x) (match-string 1 x)))
3272 (org-split-string (org-get-current-options) "\n")))
3273 (texp
3274 (setq type :tex)
3275 org-html-entities)
3276 ((string-match "\\`\\*+[ \t]*\\'"
3277 (buffer-substring (point-at-bol) beg))
3278 (setq type :todo)
3279 (mapcar 'list org-todo-keywords))
3280 (camel
3281 (setq type :camel)
3282 (save-excursion
3283 (goto-char (point-min))
3284 (while (re-search-forward org-todo-line-regexp nil t)
3285 (push (list (org-make-org-heading-camel (match-string 3)))
3286 tbl)))
3287 tbl)
3288 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3289 (completion (try-completion pattern table)))
3290 (cond ((eq completion t)
3291 (if (equal type :opt)
3292 (insert (substring (cdr (assoc (upcase pattern) table))
3293 (length pattern)))))
3294 ((null completion)
3295 (message "Can't find completion for \"%s\"" pattern)
3296 (ding))
3297 ((not (string= pattern completion))
3298 (delete-region beg end)
3299 (if (string-match " +$" completion)
3300 (setq completion (replace-match "" t t completion)))
3301 (insert completion)
3302 (if (get-buffer-window "*Completions*")
3303 (delete-window (get-buffer-window "*Completions*")))
3304 (if (and (eq type :todo)
3305 (assoc completion table))
3306 (insert " "))
3307 (if (and (equal type :opt) (assoc completion table))
3308 (message "%s" (substitute-command-keys
3309 "Press \\[org-complete] again to insert example settings"))))
3310 (t
3311 (message "Making completion list...")
3312 (let ((list (sort (all-completions pattern table) 'string<)))
3313 (with-output-to-temp-buffer "*Completions*"
3314 (display-completion-list list)))
3315 (message "Making completion list...%s" "done"))))))
3316
3317 ;;; Comments, TODO and DEADLINE
3318
3319 (defun org-toggle-comment ()
3320 "Change the COMMENT state of an entry."
3321 (interactive)
3322 (save-excursion
3323 (org-back-to-heading)
3324 (if (looking-at (concat outline-regexp
3325 "\\( +\\<" org-comment-string "\\>\\)"))
3326 (replace-match "" t t nil 1)
3327 (if (looking-at outline-regexp)
3328 (progn
3329 (goto-char (match-end 0))
3330 (insert " " org-comment-string))))))
3331
3332 (defvar org-last-todo-state-is-todo nil
3333 "This is non-nil when the last TODO state change led to a TODO state.
3334 If the last change removed the TODO tag or switched to DONE, then
3335 this is nil.")
3336
3337 (defun org-todo (&optional arg)
3338 "Change the TODO state of an item.
3339 The state of an item is given by a keyword at the start of the heading,
3340 like
3341 *** TODO Write paper
3342 *** DONE Call mom
3343
3344 The different keywords are specified in the variable `org-todo-keywords'. By
3345 default the available states are \"TODO\" and \"DONE\".
3346 So for this example: when the item starts with TODO, it is changed to DONE.
3347 When it starts with DONE, the DONE is removed. And when neither TODO nor
3348 DONE are present, add TODO at the beginning of the heading.
3349
3350 With prefix arg, use completion to determined the new state. With numeric
3351 prefix arg, switch to that state."
3352 (interactive "P")
3353 (save-excursion
3354 (org-back-to-heading)
3355 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3356 (or (looking-at (concat " +" org-todo-regexp " *"))
3357 (looking-at " *"))
3358 (let* ((this (match-string 1))
3359 (completion-ignore-case t)
3360 (member (member this org-todo-keywords))
3361 (tail (cdr member))
3362 (state (cond
3363 ((equal arg '(4))
3364 ;; Read a state with completion
3365 (completing-read "State: " (mapcar (lambda(x) (list x))
3366 org-todo-keywords)
3367 nil t))
3368 ((eq arg 'right)
3369 (if this
3370 (if tail (car tail) nil)
3371 (car org-todo-keywords)))
3372 ((eq arg 'left)
3373 (if (equal member org-todo-keywords)
3374 nil
3375 (if this
3376 (nth (- (length org-todo-keywords) (length tail) 2)
3377 org-todo-keywords)
3378 org-done-string)))
3379 (arg
3380 ;; user requests a specific state
3381 (nth (1- (prefix-numeric-value arg))
3382 org-todo-keywords))
3383 ((null member) (car org-todo-keywords))
3384 ((null tail) nil) ;; -> first entry
3385 ((eq org-todo-interpretation 'sequence)
3386 (car tail))
3387 ((memq org-todo-interpretation '(type priority))
3388 (if (eq this-command last-command)
3389 (car tail)
3390 (if (> (length tail) 0) org-done-string nil)))
3391 (t nil)))
3392 (next (if state (concat " " state " ") " ")))
3393 (replace-match next t t)
3394 (setq org-last-todo-state-is-todo
3395 (not (equal state org-done-string)))
3396 (when org-log-done
3397 (if (equal state org-done-string)
3398 (org-log-done)
3399 (if (not this)
3400 (org-log-done t))))
3401 (run-hooks 'org-after-todo-state-change-hook)))
3402 ;; Fixup cursor location if close to the keyword
3403 (if (and (outline-on-heading-p)
3404 (not (bolp))
3405 (save-excursion (beginning-of-line 1)
3406 (looking-at org-todo-line-regexp))
3407 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3408 (progn
3409 (goto-char (or (match-end 2) (match-end 1)))
3410 (just-one-space))))
3411
3412 (defun org-log-done (&optional undone)
3413 "Add a time stamp logging that a TODO entry has been closed.
3414 When UNDONE is non-nil, remove such a time stamg again."
3415 (interactive)
3416 (let (beg end col)
3417 (save-excursion
3418 (org-back-to-heading t)
3419 (setq beg (point))
3420 (looking-at (concat outline-regexp " *"))
3421 (goto-char (match-end 0))
3422 (setq col (current-column))
3423 (outline-next-heading)
3424 (setq end (point))
3425 (goto-char beg)
3426 (when (re-search-forward (concat
3427 "[\r\n]\\([ \t]*"
3428 (regexp-quote org-closed-string)
3429 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3430 (delete-region (match-beginning 1) (match-end 1)))
3431 (unless undone
3432 (org-back-to-heading t)
3433 (skip-chars-forward "^\n\r")
3434 (goto-char (min (1+ (point)) (point-max)))
3435 (when (not (member (char-before) '(?\r ?\n)))
3436 (insert "\n"))
3437 (indent-to col)
3438 (insert org-closed-string " "
3439 (format-time-string
3440 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3441 (current-time))
3442 "\n")))))
3443
3444 (defun org-show-todo-tree (arg)
3445 "Make a compact tree which shows all headlines marked with TODO.
3446 The tree will show the lines where the regexp matches, and all higher
3447 headlines above the match.
3448 With \\[universal-argument] prefix, also show the DONE entries.
3449 With a numeric prefix N, construct a sparse tree for the Nth element
3450 of `org-todo-keywords'."
3451 (interactive "P")
3452 (let ((case-fold-search nil)
3453 (kwd-re
3454 (cond ((null arg) org-not-done-regexp)
3455 ((equal arg '(4)) org-todo-regexp)
3456 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3457 (regexp-quote (nth (1- (prefix-numeric-value arg))
3458 org-todo-keywords)))
3459 (t (error "Invalid prefix argument: %s" arg)))))
3460 (message "%d TODO entries found"
3461 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3462
3463 (defun org-deadline ()
3464 "Insert the DEADLINE: string to make a deadline.
3465 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3466 to modify it to the correct date."
3467 (interactive)
3468 (insert
3469 org-deadline-string " "
3470 (format-time-string (car org-time-stamp-formats)
3471 (org-read-date nil 'to-time)))
3472 (message "%s" (substitute-command-keys
3473 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3474
3475 (defun org-schedule ()
3476 "Insert the SCHEDULED: string to schedule a TODO item.
3477 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3478 to modify it to the correct date."
3479 (interactive)
3480 (insert
3481 org-scheduled-string " "
3482 (format-time-string (car org-time-stamp-formats)
3483 (org-read-date nil 'to-time)))
3484 (message "%s" (substitute-command-keys
3485 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3486
3487
3488 (defun org-occur (regexp &optional callback)
3489 "Make a compact tree which shows all matches of REGEXP.
3490 The tree will show the lines where the regexp matches, and all higher
3491 headlines above the match. It will also show the heading after the match,
3492 to make sure editing the matching entry is easy.
3493 if CALLBACK is non-nil, it is a function which is called to confirm
3494 that the match should indeed be shown."
3495 (interactive "sRegexp: ")
3496 (org-remove-occur-highlights nil nil t)
3497 (setq regexp (org-check-occur-regexp regexp))
3498 (let ((cnt 0))
3499 (save-excursion
3500 (goto-char (point-min))
3501 (hide-sublevels 1)
3502 (while (re-search-forward regexp nil t)
3503 (when (or (not callback)
3504 (save-match-data (funcall callback)))
3505 (setq cnt (1+ cnt))
3506 (org-highlight-new-match (match-beginning 0) (match-end 0))
3507 (org-show-hierarchy-above))))
3508 (make-local-hook 'before-change-functions) ; needed for XEmacs
3509 (add-hook 'before-change-functions 'org-remove-occur-highlights
3510 nil 'local)
3511 (run-hooks 'org-occur-hook)
3512 (if (interactive-p)
3513 (message "%d match(es) for regexp %s" cnt regexp))
3514 cnt))
3515
3516 (defun org-show-hierarchy-above ()
3517 "Make sure point and the headings hierarchy above is visible."
3518 (if (org-on-heading-p t)
3519 (org-flag-heading nil) ; only show the heading
3520 (and (org-invisible-p) (org-show-hidden-entry))) ; show entire entry
3521 (save-excursion
3522 (and org-show-following-heading
3523 (outline-next-heading)
3524 (org-flag-heading nil))) ; show the next heading
3525 (when org-show-hierarchy-above
3526 (save-excursion ; show all higher headings
3527 (while (condition-case nil
3528 (progn (org-up-heading-all 1) t)
3529 (error nil))
3530 (org-flag-heading nil)))))
3531
3532 (defvar org-occur-highlights nil)
3533 (defun org-highlight-new-match (beg end)
3534 "Highlight from BEG to END and mark the highlight is an occur headline."
3535 (let ((ov (make-overlay beg end)))
3536 (overlay-put ov 'face 'secondary-selection)
3537 (push ov org-occur-highlights)))
3538
3539 (defun org-remove-occur-highlights (&optional beg end noremove)
3540 "Remove the occur highlights from the buffer.
3541 BEG and END are ignored. If NOREMOVE is nil, remove this function
3542 from the before-change-functions in the current buffer."
3543 (interactive)
3544 (mapc 'delete-overlay org-occur-highlights)
3545 (setq org-occur-highlights nil)
3546 (unless noremove
3547 (remove-hook 'before-change-functions
3548 'org-remove-occur-highlights 'local)))
3549
3550 ;;; Priorities
3551
3552 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3553 "Regular expression matching the priority indicator.")
3554
3555 (defvar org-remove-priority-next-time nil)
3556
3557 (defun org-priority-up ()
3558 "Increase the priority of the current item."
3559 (interactive)
3560 (org-priority 'up))
3561
3562 (defun org-priority-down ()
3563 "Decrease the priority of the current item."
3564 (interactive)
3565 (org-priority 'down))
3566
3567 (defun org-priority (&optional action)
3568 "Change the priority of an item by ARG.
3569 ACTION can be set, up, or down."
3570 (interactive)
3571 (setq action (or action 'set))
3572 (let (current new news have remove)
3573 (save-excursion
3574 (org-back-to-heading)
3575 (if (looking-at org-priority-regexp)
3576 (setq current (string-to-char (match-string 2))
3577 have t)
3578 (setq current org-default-priority))
3579 (cond
3580 ((eq action 'set)
3581 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3582 (setq new (read-char-exclusive))
3583 (cond ((equal new ?\ ) (setq remove t))
3584 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3585 (error "Priority must be between `%c' and `%c'"
3586 ?A org-lowest-priority))))
3587 ((eq action 'up)
3588 (setq new (1- current)))
3589 ((eq action 'down)
3590 (setq new (1+ current)))
3591 (t (error "Invalid action")))
3592 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3593 (setq news (format "%c" new))
3594 (if have
3595 (if remove
3596 (replace-match "" t t nil 1)
3597 (replace-match news t t nil 2))
3598 (if remove
3599 (error "No priority cookie found in line")
3600 (looking-at org-todo-line-regexp)
3601 (if (match-end 2)
3602 (progn
3603 (goto-char (match-end 2))
3604 (insert " [#" news "]"))
3605 (goto-char (match-beginning 3))
3606 (insert "[#" news "] ")))))
3607 (if remove
3608 (message "Priority removed")
3609 (message "Priority of current item set to %s" news))))
3610
3611
3612 (defun org-get-priority (s)
3613 "Find priority cookie and return priority."
3614 (save-match-data
3615 (if (not (string-match org-priority-regexp s))
3616 (* 1000 (- org-lowest-priority org-default-priority))
3617 (* 1000 (- org-lowest-priority
3618 (string-to-char (match-string 2 s)))))))
3619
3620 ;;; Timestamps
3621
3622 (defvar org-last-changed-timestamp nil)
3623
3624 (defun org-time-stamp (arg)
3625 "Prompt for a date/time and insert a time stamp.
3626 If the user specifies a time like HH:MM, or if this command is called
3627 with a prefix argument, the time stamp will contain date and time.
3628 Otherwise, only the date will be included. All parts of a date not
3629 specified by the user will be filled in from the current date/time.
3630 So if you press just return without typing anything, the time stamp
3631 will represent the current date/time. If there is already a timestamp
3632 at the cursor, it will be modified."
3633 (interactive "P")
3634 (let ((fmt (if arg (cdr org-time-stamp-formats)
3635 (car org-time-stamp-formats)))
3636 (org-time-was-given nil)
3637 time)
3638 (cond
3639 ((and (org-at-timestamp-p)
3640 (eq last-command 'org-time-stamp)
3641 (eq this-command 'org-time-stamp))
3642 (insert "--")
3643 (setq time (let ((this-command this-command))
3644 (org-read-date arg 'totime)))
3645 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3646 (insert (format-time-string fmt time)))
3647 ((org-at-timestamp-p)
3648 (setq time (let ((this-command this-command))
3649 (org-read-date arg 'totime)))
3650 (and (org-at-timestamp-p) (replace-match
3651 (setq org-last-changed-timestamp
3652 (format-time-string fmt time))
3653 t t))
3654 (message "Timestamp updated"))
3655 (t
3656 (setq time (let ((this-command this-command))
3657 (org-read-date arg 'totime)))
3658 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3659 (insert (format-time-string fmt time))))))
3660
3661 (defun org-time-stamp-inactive (&optional arg)
3662 "Insert an inactive time stamp.
3663 An inactive time stamp is enclosed in square brackets instead of angle
3664 brackets. It is inactive in the sense that it does not trigger agenda entries,
3665 does not link to the calendar and cannot be changed with the S-cursor keys.
3666 So these are more for recording a certain time/date."
3667 ;; FIXME: Would it be better not to ask for a date/time here?
3668 (interactive "P")
3669 (let ((fmt (if arg (cdr org-time-stamp-formats)
3670 (car org-time-stamp-formats)))
3671 (org-time-was-given nil)
3672 time)
3673 (setq time (org-read-date arg 'totime))
3674 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3675 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3676 (insert (format-time-string fmt time))))
3677
3678 ;;; FIXME: Make the function take "Fri" as "next friday"
3679 (defun org-read-date (&optional with-time to-time)
3680 "Read a date and make things smooth for the user.
3681 The prompt will suggest to enter an ISO date, but you can also enter anything
3682 which will at least partially be understood by `parse-time-string'.
3683 Unrecognized parts of the date will default to the current day, month ,year,
3684 hour and minute. For example,
3685 3-2-5 --> 2003-02-05
3686 feb 15 --> currentyear-02-15
3687 sep 12 9 --> 2009-09-12
3688 12:45 --> today 12:45
3689 22 sept 0:34 --> currentyear-09-22 0:34
3690 12 --> currentyear-currentmonth-12
3691 etc.
3692 The function understands only English month and weekday abbreviations,
3693 but this can be configured with the variables `parse-time-months' and
3694 `parse-time-weekdays'.
3695
3696 While prompting, a calendar is popped up - you can also select the
3697 date with the mouse (button 1). The calendar shows a period of three
3698 month. To scroll it to other months, use the keys `>' and `<'.
3699 If you don't like the calendar, turn it off with
3700 \(setq org-popup-calendar-for-date-prompt nil).
3701
3702 With optional argument TO-TIME, the date will immediately be converted
3703 to an internal time.
3704 With an optional argument WITH-TIME, the prompt will suggest to also
3705 insert a time. Note that when WITH-TIME is not set, you can still
3706 enter a time, and this function will inform the calling routine about
3707 this change. The calling routine may then choose to change the format
3708 used to insert the time stamp into the buffer to include the time."
3709 (let* ((default-time
3710 ;; Default time is either today, or, when entering a range,
3711 ;; the range start.
3712 (if (save-excursion
3713 (re-search-backward
3714 (concat org-ts-regexp "--\\=")
3715 (- (point) 20) t))
3716 (apply
3717 'encode-time
3718 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3719 (parse-time-string (match-string 1))))
3720 (current-time)))
3721 (calendar-move-hook nil)
3722 (view-diary-entries-initially nil)
3723 (timestr (format-time-string
3724 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3725 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3726 ans ans1 ans2
3727 second minute hour day month year tl)
3728
3729 (if org-popup-calendar-for-date-prompt
3730 ;; Also show a calendar for date selection
3731 ;; Copied (with modifications) from planner.el by John Wiegley
3732 (save-excursion
3733 (save-window-excursion
3734 (calendar)
3735 (calendar-forward-day (- (time-to-days default-time)
3736 (calendar-absolute-from-gregorian
3737 (calendar-current-date))))
3738 (let* ((old-map (current-local-map))
3739 (map (copy-keymap calendar-mode-map))
3740 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3741 (define-key map (kbd "RET") 'org-calendar-select)
3742 (define-key map (if org-xemacs-p [button1] [mouse-1])
3743 'org-calendar-select)
3744 (define-key minibuffer-local-map [(meta shift left)]
3745 (lambda () (interactive)
3746 (org-eval-in-calendar '(calendar-backward-month 1))))
3747 (define-key minibuffer-local-map [(meta shift right)]
3748 (lambda () (interactive)
3749 (org-eval-in-calendar '(calendar-forward-month 1))))
3750 (define-key minibuffer-local-map [(shift up)]
3751 (lambda () (interactive)
3752 (org-eval-in-calendar '(calendar-backward-week 1))))
3753 (define-key minibuffer-local-map [(shift down)]
3754 (lambda () (interactive)
3755 (org-eval-in-calendar '(calendar-forward-week 1))))
3756 (define-key minibuffer-local-map [(shift left)]
3757 (lambda () (interactive)
3758 (org-eval-in-calendar '(calendar-backward-day 1))))
3759 (define-key minibuffer-local-map [(shift right)]
3760 (lambda () (interactive)
3761 (org-eval-in-calendar '(calendar-forward-day 1))))
3762 (define-key minibuffer-local-map ">"
3763 (lambda () (interactive)
3764 (org-eval-in-calendar '(scroll-calendar-left 1))))
3765 (define-key minibuffer-local-map "<"
3766 (lambda () (interactive)
3767 (org-eval-in-calendar '(scroll-calendar-right 1))))
3768 (unwind-protect
3769 (progn
3770 (use-local-map map)
3771 (setq ans (read-string prompt "" nil nil))
3772 (setq ans (or ans1 ans2 ans)))
3773 (use-local-map old-map)))))
3774 ;; Naked prompt only
3775 (setq ans (read-string prompt "" nil timestr)))
3776
3777 (if (string-match
3778 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3779 (progn
3780 (setq year (if (match-end 2)
3781 (string-to-number (match-string 2 ans))
3782 (string-to-number (format-time-string "%Y")))
3783 month (string-to-number (match-string 3 ans))
3784 day (string-to-number (match-string 4 ans)))
3785 (if (< year 100) (setq year (+ 2000 year)))
3786 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3787 t t ans))))
3788 (setq tl (parse-time-string ans)
3789 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3790 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3791 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3792 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3793 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3794 second (or (nth 0 tl) 0))
3795 (if (and (boundp 'org-time-was-given)
3796 (nth 2 tl))
3797 (setq org-time-was-given t))
3798 (if (< year 100) (setq year (+ 2000 year)))
3799 (if to-time
3800 (encode-time second minute hour day month year)
3801 (if (or (nth 1 tl) (nth 2 tl))
3802 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3803 (format "%04d-%02d-%02d" year month day)))))
3804
3805 (defun org-eval-in-calendar (form)
3806 "Eval FORM in the calendar window and return to current window.
3807 Also, store the cursor date in variable ans2."
3808 (let ((sw (selected-window)))
3809 (select-window (get-buffer-window "*Calendar*"))
3810 (eval form)
3811 (when (calendar-cursor-to-date)
3812 (let* ((date (calendar-cursor-to-date))
3813 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3814 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3815 (select-window sw)))
3816
3817 (defun org-calendar-select ()
3818 "Return to `org-read-date' with the date currently selected.
3819 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3820 (interactive)
3821 (when (calendar-cursor-to-date)
3822 (let* ((date (calendar-cursor-to-date))
3823 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3824 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3825 (if (active-minibuffer-window) (exit-minibuffer))))
3826
3827 (defun org-check-deadlines (ndays)
3828 "Check if there are any deadlines due or past due.
3829 A deadline is considered due if it happens within `org-deadline-warning-days'
3830 days from today's date. If the deadline appears in an entry marked DONE,
3831 it is not shown. The prefix arg NDAYS can be used to test that many
3832 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3833 (interactive "P")
3834 (let* ((org-warn-days
3835 (cond
3836 ((equal ndays '(4)) 100000)
3837 (ndays (prefix-numeric-value ndays))
3838 (t org-deadline-warning-days)))
3839 (case-fold-search nil)
3840 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3841 (callback
3842 (lambda ()
3843 (and (let ((d1 (time-to-days (current-time)))
3844 (d2 (time-to-days
3845 (org-time-string-to-time (match-string 1)))))
3846 (< (- d2 d1) org-warn-days))
3847 (not (org-entry-is-done-p))))))
3848 (message "%d deadlines past-due or due within %d days"
3849 (org-occur regexp callback)
3850 org-warn-days)))
3851
3852 (defun org-evaluate-time-range (&optional to-buffer)
3853 "Evaluate a time range by computing the difference between start and end.
3854 Normally the result is just printed in the echo area, but with prefix arg
3855 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3856 If the time range is actually in a table, the result is inserted into the
3857 next column.
3858 For time difference computation, a year is assumed to be exactly 365
3859 days in order to avoid rounding problems."
3860 (interactive "P")
3861 (save-excursion
3862 (unless (org-at-date-range-p)
3863 (goto-char (point-at-bol))
3864 (re-search-forward org-tr-regexp (point-at-eol) t))
3865 (if (not (org-at-date-range-p))
3866 (error "Not at a time-stamp range, and none found in current line")))
3867 (let* ((ts1 (match-string 1))
3868 (ts2 (match-string 2))
3869 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3870 (match-end (match-end 0))
3871 (time1 (org-time-string-to-time ts1))
3872 (time2 (org-time-string-to-time ts2))
3873 (t1 (time-to-seconds time1))
3874 (t2 (time-to-seconds time2))
3875 (diff (abs (- t2 t1)))
3876 (negative (< (- t2 t1) 0))
3877 ;; (ys (floor (* 365 24 60 60)))
3878 (ds (* 24 60 60))
3879 (hs (* 60 60))
3880 (fy "%dy %dd %02d:%02d")
3881 (fy1 "%dy %dd")
3882 (fd "%dd %02d:%02d")
3883 (fd1 "%dd")
3884 (fh "%02d:%02d")
3885 y d h m align)
3886 ;; FIXME: Should I re-introduce years, make year refer to same date?
3887 ;; This would be the only useful way to have years, actually.
3888 (if havetime
3889 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3890 y 0
3891 d (floor (/ diff ds)) diff (mod diff ds)
3892 h (floor (/ diff hs)) diff (mod diff hs)
3893 m (floor (/ diff 60)))
3894 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3895 y 0
3896 d (floor (+ (/ diff ds) 0.5))
3897 h 0 m 0))
3898 (if (not to-buffer)
3899 (message (org-make-tdiff-string y d h m))
3900 (when (org-at-table-p)
3901 (goto-char match-end)
3902 (setq align t)
3903 (and (looking-at " *|") (goto-char (match-end 0))))
3904 (if (looking-at
3905 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3906 (replace-match ""))
3907 (if negative (insert " -"))
3908 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3909 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3910 (insert " " (format fh h m))))
3911 (if align (org-table-align))
3912 (message "Time difference inserted"))))
3913
3914 (defun org-make-tdiff-string (y d h m)
3915 (let ((fmt "")
3916 (l nil))
3917 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3918 l (push y l)))
3919 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3920 l (push d l)))
3921 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3922 l (push h l)))
3923 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3924 l (push m l)))
3925 (apply 'format fmt (nreverse l))))
3926
3927 (defun org-time-string-to-time (s)
3928 (apply 'encode-time (org-parse-time-string s)))
3929
3930 (defun org-parse-time-string (s &optional nodefault)
3931 "Parse the standard Org-mode time string.
3932 This should be a lot faster than the normal `parse-time-string'.
3933 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3934 hour and minute fields will be nil if not given."
3935 (if (string-match org-ts-regexp1 s)
3936 (list 0
3937 (if (or (match-beginning 8) (not nodefault))
3938 (string-to-number (or (match-string 8 s) "0")))
3939 (if (or (match-beginning 7) (not nodefault))
3940 (string-to-number (or (match-string 7 s) "0")))
3941 (string-to-number (match-string 4 s))
3942 (string-to-number (match-string 3 s))
3943 (string-to-number (match-string 2 s))
3944 nil nil nil)
3945 (make-list 9 0)))
3946
3947 (defun org-timestamp-up (&optional arg)
3948 "Increase the date item at the cursor by one.
3949 If the cursor is on the year, change the year. If it is on the month or
3950 the day, change that.
3951 With prefix ARG, change by that many units."
3952 (interactive "p")
3953 (org-timestamp-change (prefix-numeric-value arg)))
3954
3955 (defun org-timestamp-down (&optional arg)
3956 "Decrease the date item at the cursor by one.
3957 If the cursor is on the year, change the year. If it is on the month or
3958 the day, change that.
3959 With prefix ARG, change by that many units."
3960 (interactive "p")
3961 (org-timestamp-change (- (prefix-numeric-value arg))))
3962
3963 (defun org-timestamp-up-day (&optional arg)
3964 "Increase the date in the time stamp by one day.
3965 With prefix ARG, change that many days."
3966 (interactive "p")
3967 (if (and (not (org-at-timestamp-p))
3968 (org-on-heading-p))
3969 (org-todo 'up)
3970 (org-timestamp-change (prefix-numeric-value arg) 'day)))
3971
3972 (defun org-timestamp-down-day (&optional arg)
3973 "Decrease the date in the time stamp by one day.
3974 With prefix ARG, change that many days."
3975 (interactive "p")
3976 (if (and (not (org-at-timestamp-p))
3977 (org-on-heading-p))
3978 (org-todo 'down)
3979 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
3980
3981 (defsubst org-pos-in-match-range (pos n)
3982 (and (match-beginning n)
3983 (<= (match-beginning n) pos)
3984 (>= (match-end n) pos)))
3985
3986 (defun org-at-timestamp-p ()
3987 "Determine if the cursor is in or at a timestamp."
3988 (interactive)
3989 (let* ((tsr org-ts-regexp2)
3990 (pos (point))
3991 (ans (or (looking-at tsr)
3992 (save-excursion
3993 (skip-chars-backward "^<\n\r\t")
3994 (if (> (point) 1) (backward-char 1))
3995 (and (looking-at tsr)
3996 (> (- (match-end 0) pos) -1))))))
3997 (and (boundp 'org-ts-what)
3998 (setq org-ts-what
3999 (cond
4000 ((org-pos-in-match-range pos 2) 'year)
4001 ((org-pos-in-match-range pos 3) 'month)
4002 ((org-pos-in-match-range pos 7) 'hour)
4003 ((org-pos-in-match-range pos 8) 'minute)
4004 ((or (org-pos-in-match-range pos 4)
4005 (org-pos-in-match-range pos 5)) 'day)
4006 (t 'day))))
4007 ans))
4008
4009 (defun org-timestamp-change (n &optional what)
4010 "Change the date in the time stamp at point.
4011 The date will be changed by N times WHAT. WHAT can be `day', `month',
4012 `year', `minute', `second'. If WHAT is not given, the cursor position
4013 in the timestamp determines what will be changed."
4014 (let ((fmt (car org-time-stamp-formats))
4015 org-ts-what
4016 (pos (point))
4017 ts time time0)
4018 (if (not (org-at-timestamp-p))
4019 (error "Not at a timestamp"))
4020 (setq org-ts-what (or what org-ts-what))
4021 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4022 (- (match-end 0) (match-beginning 0))))
4023 1)
4024 (cdr org-time-stamp-formats)
4025 (car org-time-stamp-formats)))
4026 (setq ts (match-string 0))
4027 (replace-match "")
4028 (setq time0 (org-parse-time-string ts))
4029 (setq time
4030 (apply 'encode-time
4031 (append
4032 (list (or (car time0) 0))
4033 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4034 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4035 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4036 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4037 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4038 (nthcdr 6 time0))))
4039 (if (eq what 'calendar)
4040 (let ((cal-date
4041 (save-excursion
4042 (save-match-data
4043 (set-buffer "*Calendar*")
4044 (calendar-cursor-to-date)))))
4045 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4046 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4047 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4048 (setcar time0 (or (car time0) 0))
4049 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4050 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4051 (setq time (apply 'encode-time time0))))
4052 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4053 (goto-char pos)
4054 ;; Try to recenter the calendar window, if any
4055 (if (and org-calendar-follow-timestamp-change
4056 (get-buffer-window "*Calendar*" t)
4057 (memq org-ts-what '(day month year)))
4058 (org-recenter-calendar (time-to-days time)))))
4059
4060 (defun org-recenter-calendar (date)
4061 "If the calendar is visible, recenter it to DATE."
4062 (let* ((win (selected-window))
4063 (cwin (get-buffer-window "*Calendar*" t))
4064 (calendar-move-hook nil))
4065 (when cwin
4066 (select-window cwin)
4067 (calendar-goto-date (if (listp date) date
4068 (calendar-gregorian-from-absolute date)))
4069 (select-window win))))
4070
4071 (defun org-goto-calendar (&optional arg)
4072 "Go to the Emacs calendar at the current date.
4073 If there is a time stamp in the current line, go to that date.
4074 A prefix ARG can be used force the current date."
4075 (interactive "P")
4076 (let ((tsr org-ts-regexp) diff
4077 (calendar-move-hook nil)
4078 (view-diary-entries-initially nil))
4079 (if (or (org-at-timestamp-p)
4080 (save-excursion
4081 (beginning-of-line 1)
4082 (looking-at (concat ".*" tsr))))
4083 (let ((d1 (time-to-days (current-time)))
4084 (d2 (time-to-days
4085 (org-time-string-to-time (match-string 1)))))
4086 (setq diff (- d2 d1))))
4087 (calendar)
4088 (calendar-goto-today)
4089 (if (and diff (not arg)) (calendar-forward-day diff))))
4090
4091 (defun org-date-from-calendar ()
4092 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4093 If there is already a time stamp at the cursor position, update it."
4094 (interactive)
4095 (org-timestamp-change 0 'calendar))
4096
4097 ;;; Agenda, and Diary Integration
4098
4099 ;;; Define the mode
4100
4101 (defvar org-agenda-mode-map (make-sparse-keymap)
4102 "Keymap for `org-agenda-mode'.")
4103
4104 (defvar org-agenda-menu)
4105 (defvar org-agenda-follow-mode nil)
4106 (defvar org-agenda-show-log nil)
4107 (defvar org-agenda-buffer-name "*Org Agenda*")
4108 (defvar org-agenda-redo-command nil)
4109 (defvar org-agenda-mode-hook nil)
4110
4111 ;;;###autoload
4112 (defun org-agenda-mode ()
4113 "Mode for time-sorted view on action items in Org-mode files.
4114
4115 The following commands are available:
4116
4117 \\{org-agenda-mode-map}"
4118 (interactive)
4119 (kill-all-local-variables)
4120 (setq major-mode 'org-agenda-mode)
4121 (setq mode-name "Org-Agenda")
4122 (use-local-map org-agenda-mode-map)
4123 (easy-menu-add org-agenda-menu)
4124 (if org-startup-truncated (setq truncate-lines t))
4125 (make-local-hook 'post-command-hook) ; Needed for XEmacs
4126 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4127 (make-local-hook 'pre-command-hook) ; Needed for XEmacs
4128 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4129 (unless org-agenda-keep-modes
4130 (setq org-agenda-follow-mode nil
4131 org-agenda-show-log nil))
4132 (easy-menu-change
4133 '("Agenda") "Agenda Files"
4134 (append
4135 (list
4136 ["Edit File List" (customize-variable 'org-agenda-files) t]
4137 "--")
4138 (mapcar 'org-file-menu-entry org-agenda-files)))
4139 (org-agenda-set-mode-name)
4140 (apply
4141 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4142 (list 'org-agenda-mode-hook)))
4143
4144 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4145 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4146 (define-key org-agenda-mode-map " " 'org-agenda-show)
4147 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4148 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4149 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
4150 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4151 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4152 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4153 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4154 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4155 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4156 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4157 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4158
4159 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4160 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4161 (while l (define-key org-agenda-mode-map
4162 (int-to-string (pop l)) 'digit-argument)))
4163
4164 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4165 (define-key org-agenda-mode-map "L" 'org-agenda-log-mode)
4166 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4167 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4168 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4169 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4170 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4171 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4172 (define-key org-agenda-mode-map "n" 'next-line)
4173 (define-key org-agenda-mode-map "p" 'previous-line)
4174 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4175 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4176 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4177 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4178 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4179 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4180 (eval-after-load "calendar"
4181 '(define-key calendar-mode-map org-calendar-to-agenda-key
4182 'org-calendar-goto-agenda))
4183 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4184 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4185 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4186 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4187 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4188 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4189 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4190 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4191 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4192 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4193 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4194 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4195 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4196 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4197 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4198 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4199 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4200 "Local keymap for agenda entries from Org-mode.")
4201
4202 (define-key org-agenda-keymap
4203 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4204 (define-key org-agenda-keymap
4205 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4206
4207 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4208 '("Agenda"
4209 ("Agenda Files")
4210 "--"
4211 ["Show" org-agenda-show t]
4212 ["Go To (other window)" org-agenda-goto t]
4213 ["Go To (one window)" org-agenda-switch-to t]
4214 ["Follow Mode" org-agenda-follow-mode
4215 :style toggle :selected org-agenda-follow-mode :active t]
4216 "--"
4217 ["Cycle TODO" org-agenda-todo t]
4218 ("Reschedule"
4219 ["Reschedule +1 day" org-agenda-date-later t]
4220 ["Reschedule -1 day" org-agenda-date-earlier t]
4221 "--"
4222 ["Reschedule to ..." org-agenda-date-prompt t])
4223 ("Priority"
4224 ["Set Priority" org-agenda-priority t]
4225 ["Increase Priority" org-agenda-priority-up t]
4226 ["Decrease Priority" org-agenda-priority-down t]
4227 ["Show Priority" org-agenda-show-priority t])
4228 "--"
4229 ["Rebuild buffer" org-agenda-redo t]
4230 ["Goto Today" org-agenda-goto-today t]
4231 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
4232 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
4233 "--"
4234 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day)
4235 :style radio :selected (equal org-agenda-ndays 1)]
4236 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day)
4237 :style radio :selected (equal org-agenda-ndays 7)]
4238 "--"
4239 ["Show Logbook entries" org-agenda-log-mode
4240 :style toggle :selected org-agenda-show-log :active t]
4241 ["Include Diary" org-agenda-toggle-diary
4242 :style toggle :selected org-agenda-include-diary :active t]
4243 ["Use Time Grid" org-agenda-toggle-time-grid
4244 :style toggle :selected org-agenda-use-time-grid :active t]
4245 "--"
4246 ["New Diary Entry" org-agenda-diary-entry t]
4247 ("Calendar Commands"
4248 ["Goto Calendar" org-agenda-goto-calendar t]
4249 ["Phases of the Moon" org-agenda-phases-of-moon t]
4250 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
4251 ["Holidays" org-agenda-holidays t]
4252 ["Convert" org-agenda-convert-date t])
4253 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4254 "--"
4255 ["Quit" org-agenda-quit t]
4256 ["Exit and Release Buffers" org-agenda-exit t]
4257 ))
4258
4259 (defvar org-agenda-markers nil
4260 "List of all currently active markers created by `org-agenda'.")
4261 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4262 "Creation time of the last agenda marker.")
4263
4264 (defun org-agenda-new-marker (&optional pos)
4265 "Return a new agenda marker.
4266 Org-mode keeps a list of these markers and resets them when they are
4267 no longer in use."
4268 (let ((m (copy-marker (or pos (point)))))
4269 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4270 (push m org-agenda-markers)
4271 m))
4272
4273 (defun org-agenda-maybe-reset-markers (&optional force)
4274 "Reset markers created by `org-agenda'. But only if they are old enough."
4275 (if (or force
4276 (> (- (time-to-seconds (current-time))
4277 org-agenda-last-marker-time)
4278 5))
4279 (while org-agenda-markers
4280 (move-marker (pop org-agenda-markers) nil))))
4281
4282 (defvar org-agenda-new-buffers nil
4283 "Buffers created to visit agenda files.")
4284
4285 (defun org-get-agenda-file-buffer (file)
4286 "Get a buffer visiting FILE. If the buffer needs to be created, add
4287 it to the list of buffers which might be released later."
4288 (let ((buf (find-buffer-visiting file)))
4289 (if buf
4290 buf ; just return it
4291 ;; Make a new buffer and remember it
4292 (setq buf (find-file-noselect file))
4293 (if buf (push buf org-agenda-new-buffers))
4294 buf)))
4295
4296 (defun org-release-buffers (blist)
4297 "Release all buffers in list, asking the user for confirmation when needed.
4298 When a buffer is unmodified, it is just killed. When modified, it is saved
4299 \(if the user agrees) and then killed."
4300 (let (buf file)
4301 (while (setq buf (pop blist))
4302 (setq file (buffer-file-name buf))
4303 (when (and (buffer-modified-p buf)
4304 file
4305 (y-or-n-p (format "Save file %s? " file)))
4306 (with-current-buffer buf (save-buffer)))
4307 (kill-buffer buf))))
4308
4309 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4310
4311 (defun org-timeline (&optional include-all keep-modes)
4312 "Show a time-sorted view of the entries in the current org file.
4313 Only entries with a time stamp of today or later will be listed. With
4314 one \\[universal-argument] prefix argument, past entries will also be listed.
4315 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
4316 under the current date.
4317 If the buffer contains an active region, only check the region for
4318 dates."
4319 (interactive "P")
4320 (require 'calendar)
4321 (org-agenda-maybe-reset-markers 'force)
4322 (org-compile-prefix-format org-timeline-prefix-format)
4323 (let* ((dopast (or include-all org-agenda-show-log))
4324 (dotodo (member include-all '((16))))
4325 (doclosed org-agenda-show-log)
4326 (org-agenda-keep-modes keep-modes)
4327 (entry (buffer-file-name))
4328 (org-agenda-files (list (buffer-file-name)))
4329 (date (calendar-current-date))
4330 (win (selected-window))
4331 (pos1 (point))
4332 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4333 (end (if (org-region-active-p) (region-end) (point-max)))
4334 (day-numbers (org-get-all-dates beg end 'no-ranges
4335 t doclosed)) ; always include today
4336 (today (time-to-days (current-time)))
4337 (org-respect-restriction t)
4338 (past t)
4339 args
4340 s e rtn d)
4341 (setq org-agenda-redo-command
4342 (list 'progn
4343 (list 'switch-to-buffer-other-window (current-buffer))
4344 (list 'org-timeline (list 'quote include-all) t)))
4345 (if (not dopast)
4346 ;; Remove past dates from the list of dates.
4347 (setq day-numbers (delq nil (mapcar (lambda(x)
4348 (if (>= x today) x nil))
4349 day-numbers))))
4350 (switch-to-buffer-other-window
4351 (get-buffer-create org-agenda-buffer-name))
4352 (setq buffer-read-only nil)
4353 (erase-buffer)
4354 (org-agenda-mode) (setq buffer-read-only nil)
4355 (if doclosed (push :closed args))
4356 (push :timestamp args)
4357 (if dotodo (push :todo args))
4358 (while (setq d (pop day-numbers))
4359 (if (and (>= d today)
4360 dopast
4361 past)
4362 (progn
4363 (setq past nil)
4364 (insert (make-string 79 ?-) "\n")))
4365 (setq date (calendar-gregorian-from-absolute d))
4366 (setq s (point))
4367 (setq rtn (apply 'org-agenda-get-day-entries
4368 entry date args))
4369 (if (or rtn (equal d today))
4370 (progn
4371 (insert (calendar-day-name date) " "
4372 (number-to-string (extract-calendar-day date)) " "
4373 (calendar-month-name (extract-calendar-month date)) " "
4374 (number-to-string (extract-calendar-year date)) "\n")
4375 (put-text-property s (1- (point)) 'face
4376 'org-link)
4377 (if (equal d today)
4378 (put-text-property s (1- (point)) 'org-today t))
4379 (insert (org-finalize-agenda-entries rtn) "\n")
4380 (put-text-property s (1- (point)) 'day d))))
4381 (goto-char (point-min))
4382 (setq buffer-read-only t)
4383 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4384 (point-min)))
4385 (when (not org-select-timeline-window)
4386 (select-window win)
4387 (goto-char pos1))))
4388
4389 ;;;###autoload
4390 (defun org-agenda (&optional include-all start-day ndays keep-modes)
4391 "Produce a weekly view from all files in variable `org-agenda-files'.
4392 The view will be for the current week, but from the overview buffer you
4393 will be able to go to other weeks.
4394 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4395 also be shown, under the current date.
4396 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4397 on the days are also shown. See the variable `org-log-done' for how
4398 to turn on logging.
4399 START-DAY defaults to TODAY, or to the most recent match for the weekday
4400 given in `org-agenda-start-on-weekday'.
4401 NDAYS defaults to `org-agenda-ndays'."
4402 (interactive "P")
4403 (org-agenda-maybe-reset-markers 'force)
4404 (org-compile-prefix-format org-agenda-prefix-format)
4405 (require 'calendar)
4406 (let* ((org-agenda-start-on-weekday
4407 (if (or (equal ndays 1)
4408 (and (null ndays) (equal 1 org-agenda-ndays)))
4409 nil org-agenda-start-on-weekday))
4410 (org-agenda-keep-modes keep-modes)
4411 (files (copy-sequence org-agenda-files))
4412 (win (selected-window))
4413 (today (time-to-days (current-time)))
4414 (sd (or start-day today))
4415 (start (if (or (null org-agenda-start-on-weekday)
4416 (< org-agenda-ndays 7))
4417 sd
4418 (let* ((nt (calendar-day-of-week
4419 (calendar-gregorian-from-absolute sd)))
4420 (n1 org-agenda-start-on-weekday)
4421 (d (- nt n1)))
4422 (- sd (+ (if (< d 0) 7 0) d)))))
4423 (day-numbers (list start))
4424 (inhibit-redisplay t)
4425 s e rtn rtnall file date d start-pos end-pos todayp nd)
4426 (setq org-agenda-redo-command
4427 (list 'org-agenda (list 'quote include-all) start-day ndays t))
4428 ;; Make the list of days
4429 (setq ndays (or ndays org-agenda-ndays)
4430 nd ndays)
4431 (while (> ndays 1)
4432 (push (1+ (car day-numbers)) day-numbers)
4433 (setq ndays (1- ndays)))
4434 (setq day-numbers (nreverse day-numbers))
4435 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4436 (progn
4437 (delete-other-windows)
4438 (switch-to-buffer-other-window
4439 (get-buffer-create org-agenda-buffer-name))))
4440 (setq buffer-read-only nil)
4441 (erase-buffer)
4442 (org-agenda-mode) (setq buffer-read-only nil)
4443 (set (make-local-variable 'starting-day) (car day-numbers))
4444 (set (make-local-variable 'include-all-loc) include-all)
4445 (when (and (or include-all org-agenda-include-all-todo)
4446 (member today day-numbers))
4447 (setq files org-agenda-files
4448 rtnall nil)
4449 (while (setq file (pop files))
4450 (catch 'nextfile
4451 (org-check-agenda-file file)
4452 (setq date (calendar-gregorian-from-absolute today)
4453 rtn (org-agenda-get-day-entries
4454 file date :todo))
4455 (setq rtnall (append rtnall rtn))))
4456 (when rtnall
4457 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4458 (add-text-properties (point-min) (1- (point))
4459 (list 'face 'org-link))
4460 (insert (org-finalize-agenda-entries rtnall) "\n")))
4461 (while (setq d (pop day-numbers))
4462 (setq date (calendar-gregorian-from-absolute d)
4463 s (point))
4464 (if (or (setq todayp (= d today))
4465 (and (not start-pos) (= d sd)))
4466 (setq start-pos (point))
4467 (if (and start-pos (not end-pos))
4468 (setq end-pos (point))))
4469 (setq files org-agenda-files
4470 rtnall nil)
4471 (while (setq file (pop files))
4472 (catch 'nextfile
4473 (org-check-agenda-file file)
4474 (if org-agenda-show-log
4475 (setq rtn (org-agenda-get-day-entries
4476 file date
4477 :deadline :scheduled :timestamp :closed))
4478 (setq rtn (org-agenda-get-day-entries
4479 file date
4480 :deadline :scheduled :timestamp)))
4481 (setq rtnall (append rtnall rtn))))
4482 (if org-agenda-include-diary
4483 (progn
4484 (require 'diary-lib)
4485 (setq rtn (org-get-entries-from-diary date))
4486 (setq rtnall (append rtnall rtn))))
4487 (if (or rtnall org-agenda-show-all-dates)
4488 (progn
4489 (insert (format "%-9s %2d %s %4d\n"
4490 (calendar-day-name date)
4491 (extract-calendar-day date)
4492 (calendar-month-name (extract-calendar-month date))
4493 (extract-calendar-year date)))
4494 (put-text-property s (1- (point)) 'face
4495 'org-link)
4496 (if rtnall (insert
4497 (org-finalize-agenda-entries
4498 (org-agenda-add-time-grid-maybe
4499 rtnall nd todayp))
4500 "\n"))
4501 (put-text-property s (1- (point)) 'day d))))
4502 (goto-char (point-min))
4503 (setq buffer-read-only t)
4504 (if org-fit-agenda-window
4505 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4506 (/ (frame-height) 2)))
4507 (unless (and (pos-visible-in-window-p (point-min))
4508 (pos-visible-in-window-p (point-max)))
4509 (goto-char (1- (point-max)))
4510 (recenter -1)
4511 (if (not (pos-visible-in-window-p (or start-pos 1)))
4512 (progn
4513 (goto-char (or start-pos 1))
4514 (recenter 1))))
4515 (goto-char (or start-pos 1))
4516 (if (not org-select-agenda-window) (select-window win))
4517 (message "")))
4518
4519 (defvar org-select-this-todo-keyword nil)
4520
4521 ;;;###autoload
4522 (defun org-todo-list (arg &optional keep-modes)
4523 "Show all TODO entries from all agenda file in a single list.
4524 The prefix arg can be used to select a specific TODO keyword and limit
4525 the list to these. When using \\[universal-argument], you will be prompted
4526 for a keyword. A numeric prefix directly selects the Nth keyword in
4527 `org-todo-keywords'."
4528 (interactive "P")
4529 (org-agenda-maybe-reset-markers 'force)
4530 (org-compile-prefix-format org-agenda-prefix-format)
4531 (let* ((org-agenda-keep-modes keep-modes)
4532 (today (time-to-days (current-time)))
4533 (date (calendar-gregorian-from-absolute today))
4534 (win (selected-window))
4535 (kwds org-todo-keywords)
4536 (completion-ignore-case t)
4537 (org-select-this-todo-keyword
4538 (and arg (integerp arg) (nth (1- arg) org-todo-keywords)))
4539 rtn rtnall files file pos)
4540 (when (equal arg '(4))
4541 (setq org-select-this-todo-keyword
4542 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4543 nil t)))
4544 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4545 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4546 (progn
4547 (delete-other-windows)
4548 (switch-to-buffer-other-window
4549 (get-buffer-create org-agenda-buffer-name))))
4550 (setq buffer-read-only nil)
4551 (erase-buffer)
4552 (org-agenda-mode) (setq buffer-read-only nil)
4553 (set (make-local-variable 'last-arg) arg)
4554 (set (make-local-variable 'org-todo-keywords) kwds)
4555 (set (make-local-variable 'org-agenda-redo-command)
4556 '(org-todo-list (or current-prefix-arg last-arg) t))
4557 (setq files org-agenda-files
4558 rtnall nil)
4559 (while (setq file (pop files))
4560 (catch 'nextfile
4561 (org-check-agenda-file file)
4562 (setq rtn (org-agenda-get-day-entries file date :todo))
4563 (setq rtnall (append rtnall rtn))))
4564 (insert "Global list of TODO items of type: ")
4565 (add-text-properties (point-min) (1- (point))
4566 (list 'face 'org-link))
4567 (setq pos (point))
4568 (insert (or org-select-this-todo-keyword "ALL") "\n")
4569 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4570 (setq pos (point))
4571 (insert
4572 "Available with `N r': (0)ALL "
4573 (let ((n 0))
4574 (mapconcat (lambda (x)
4575 (format "(%d)%s" (setq n (1+ n)) x))
4576 org-todo-keywords " "))
4577 "\n")
4578 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4579 (when rtnall
4580 (insert (org-finalize-agenda-entries rtnall) "\n"))
4581 (goto-char (point-min))
4582 (setq buffer-read-only t)
4583 (if org-fit-agenda-window
4584 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4585 (/ (frame-height) 2)))
4586 (if (not org-select-agenda-window) (select-window win))))
4587
4588 (defun org-check-agenda-file (file)
4589 "Make sure FILE exists. If not, ask user what to do."
4590 ;; FIXME: this does not correctly change the menus
4591 ;; Could probably be fixed by explicitly going to the buffer.
4592 (when (not (file-exists-p file))
4593 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4594 file)
4595 (let ((r (downcase (read-char-exclusive))))
4596 (cond
4597 ((equal r ?r)
4598 (org-remove-file file)
4599 (throw 'nextfile t))
4600 (t (error "Abort"))))))
4601
4602 (defun org-agenda-quit ()
4603 "Exit agenda by removing the window or the buffer."
4604 (interactive)
4605 (let ((buf (current-buffer)))
4606 (if (not (one-window-p)) (delete-window))
4607 (kill-buffer buf)
4608 (org-agenda-maybe-reset-markers 'force)))
4609
4610 (defun org-agenda-exit ()
4611 "Exit agenda by removing the window or the buffer.
4612 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4613 Org-mode buffers visited directly by the user will not be touched."
4614 (interactive)
4615 (org-release-buffers org-agenda-new-buffers)
4616 (setq org-agenda-new-buffers nil)
4617 (org-agenda-quit))
4618
4619 (defun org-agenda-redo ()
4620 "Rebuild Agenda.
4621 When this is the global TODO list, a prefix argument will be interpreted."
4622 (interactive)
4623 (eval org-agenda-redo-command))
4624
4625 (defun org-agenda-goto-today ()
4626 "Go to today."
4627 (interactive)
4628 (if (boundp 'starting-day)
4629 (let ((cmd (car org-agenda-redo-command))
4630 (iall (nth 1 org-agenda-redo-command))
4631 (nday (nth 3 org-agenda-redo-command))
4632 (keep (nth 4 org-agenda-redo-command)))
4633 (eval (list cmd iall nil nday keep)))
4634 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4635 (point-min)))))
4636
4637 (defun org-agenda-later (arg)
4638 "Go forward in time by `org-agenda-ndays' days.
4639 With prefix ARG, go forward that many times `org-agenda-ndays'."
4640 (interactive "p")
4641 (unless (boundp 'starting-day)
4642 (error "Not allowed"))
4643 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
4644 (+ starting-day (* arg org-agenda-ndays)) nil t))
4645
4646 (defun org-agenda-earlier (arg)
4647 "Go back in time by `org-agenda-ndays' days.
4648 With prefix ARG, go back that many times `org-agenda-ndays'."
4649 (interactive "p")
4650 (unless (boundp 'starting-day)
4651 (error "Not allowed"))
4652 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
4653 (- starting-day (* arg org-agenda-ndays)) nil t))
4654
4655 (defun org-agenda-week-view ()
4656 "Switch to weekly view for agenda."
4657 (interactive)
4658 (unless (boundp 'starting-day)
4659 (error "Not allowed"))
4660 (setq org-agenda-ndays 7)
4661 (org-agenda include-all-loc
4662 (or (get-text-property (point) 'day)
4663 starting-day)
4664 nil t)
4665 (org-agenda-set-mode-name)
4666 (message "Switched to week view"))
4667
4668 (defun org-agenda-day-view ()
4669 "Switch to weekly view for agenda."
4670 (interactive)
4671 (unless (boundp 'starting-day)
4672 (error "Not allowed"))
4673 (setq org-agenda-ndays 1)
4674 (org-agenda include-all-loc
4675 (or (get-text-property (point) 'day)
4676 starting-day)
4677 nil t)
4678 (org-agenda-set-mode-name)
4679 (message "Switched to day view"))
4680
4681 (defun org-agenda-next-date-line (&optional arg)
4682 "Jump to the next line indicating a date in agenda buffer."
4683 (interactive "p")
4684 (beginning-of-line 1)
4685 (if (looking-at "^\\S-") (forward-char 1))
4686 (if (not (re-search-forward "^\\S-" nil t arg))
4687 (progn
4688 (backward-char 1)
4689 (error "No next date after this line in this buffer")))
4690 (goto-char (match-beginning 0)))
4691
4692 (defun org-agenda-previous-date-line (&optional arg)
4693 "Jump to the next line indicating a date in agenda buffer."
4694 (interactive "p")
4695 (beginning-of-line 1)
4696 (if (not (re-search-backward "^\\S-" nil t arg))
4697 (error "No previous date before this line in this buffer")))
4698
4699 ;; Initialize the highlight
4700 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
4701 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
4702 'face 'highlight)
4703
4704 (defun org-highlight (begin end &optional buffer)
4705 "Highlight a region with overlay."
4706 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4707 org-hl begin end (or buffer (current-buffer))))
4708
4709 (defun org-unhighlight ()
4710 "Detach overlay INDEX."
4711 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4712
4713
4714 (defun org-agenda-follow-mode ()
4715 "Toggle follow mode in an agenda buffer."
4716 (interactive)
4717 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4718 (org-agenda-set-mode-name)
4719 (message "Follow mode is %s"
4720 (if org-agenda-follow-mode "on" "off")))
4721
4722 (defun org-agenda-log-mode ()
4723 "Toggle follow mode in an agenda buffer."
4724 (interactive)
4725 (setq org-agenda-show-log (not org-agenda-show-log))
4726 (org-agenda-set-mode-name)
4727 (org-agenda-redo)
4728 (message "Log mode is %s"
4729 (if org-agenda-show-log "on" "off")))
4730
4731 (defun org-agenda-toggle-diary ()
4732 "Toggle follow mode in an agenda buffer."
4733 (interactive)
4734 (setq org-agenda-include-diary (not org-agenda-include-diary))
4735 (org-agenda-redo)
4736 (org-agenda-set-mode-name)
4737 (message "Diary inclusion turned %s"
4738 (if org-agenda-include-diary "on" "off")))
4739
4740 (defun org-agenda-toggle-time-grid ()
4741 "Toggle follow mode in an agenda buffer."
4742 (interactive)
4743 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4744 (org-agenda-redo)
4745 (org-agenda-set-mode-name)
4746 (message "Time-grid turned %s"
4747 (if org-agenda-use-time-grid "on" "off")))
4748
4749 (defun org-agenda-set-mode-name ()
4750 "Set the mode name to indicate all the small mode settings."
4751 (setq mode-name
4752 (concat "Org-Agenda"
4753 (if (equal org-agenda-ndays 1) " Day" "")
4754 (if (equal org-agenda-ndays 7) " Week" "")
4755 (if org-agenda-follow-mode " Follow" "")
4756 (if org-agenda-include-diary " Diary" "")
4757 (if org-agenda-use-time-grid " Grid" "")
4758 (if org-agenda-show-log " Log" "")))
4759 (force-mode-line-update))
4760
4761 (defun org-agenda-post-command-hook ()
4762 (and (eolp) (not (bolp)) (backward-char 1))
4763 (if (and org-agenda-follow-mode
4764 (get-text-property (point) 'org-marker))
4765 (org-agenda-show)))
4766
4767 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4768
4769 (defun org-get-entries-from-diary (date)
4770 "Get the (Emacs Calendar) diary entries for DATE."
4771 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4772 (diary-display-hook '(fancy-diary-display))
4773 (list-diary-entries-hook
4774 (cons 'org-diary-default-entry list-diary-entries-hook))
4775 (diary-file-name-prefix-function nil) ; turn this feature off
4776 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4777 entries
4778 (org-disable-agenda-to-diary t))
4779 (save-excursion
4780 (save-window-excursion
4781 (list-diary-entries date 1)))
4782 (if (not (get-buffer fancy-diary-buffer))
4783 (setq entries nil)
4784 (with-current-buffer fancy-diary-buffer
4785 (setq buffer-read-only nil)
4786 (if (= (point-max) 1)
4787 ;; No entries
4788 (setq entries nil)
4789 ;; Omit the date and other unnecessary stuff
4790 (org-agenda-cleanup-fancy-diary)
4791 ;; Add prefix to each line and extend the text properties
4792 (if (= (point-max) 1)
4793 (setq entries nil)
4794 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4795 (set-buffer-modified-p nil)
4796 (kill-buffer fancy-diary-buffer)))
4797 (when entries
4798 (setq entries (org-split-string entries "\n"))
4799 (setq entries
4800 (mapcar
4801 (lambda (x)
4802 (setq x (org-format-agenda-item "" x "Diary" 'time))
4803 ;; Extend the text properties to the beginning of the line
4804 (add-text-properties
4805 0 (length x)
4806 (text-properties-at (1- (length x)) x)
4807 x)
4808 x)
4809 entries)))))
4810
4811 (defun org-agenda-cleanup-fancy-diary ()
4812 "Remove unwanted stuff in buffer created by fancy-diary-display.
4813 This gets rid of the date, the underline under the date, and
4814 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4815 date. Itt also removes lines that contain only whitespace."
4816 (goto-char (point-min))
4817 (if (looking-at ".*?:[ \t]*")
4818 (progn
4819 (replace-match "")
4820 (re-search-forward "\n=+$" nil t)
4821 (replace-match "")
4822 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4823 (re-search-forward "\n=+$" nil t)
4824 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4825 (goto-char (point-min))
4826 (while (re-search-forward "^ +\n" nil t)
4827 (replace-match ""))
4828 (goto-char (point-min))
4829 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4830 (replace-match "")))
4831
4832 ;; Make sure entries from the diary have the right text properties.
4833 (eval-after-load "diary-lib"
4834 '(if (boundp 'diary-modify-entry-list-string-function)
4835 ;; We can rely on the hook, nothing to do
4836 nil
4837 ;; Hook not avaiable, must use advice to make this work
4838 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4839 "Make the position visible."
4840 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4841 (stringp string)
4842 (buffer-file-name))
4843 (setq string (org-modify-diary-entry-string string))))))
4844
4845 (defun org-modify-diary-entry-string (string)
4846 "Add text properties to string, allowing org-mode to act on it."
4847 (add-text-properties
4848 0 (length string)
4849 (list 'mouse-face 'highlight
4850 'keymap org-agenda-keymap
4851 'help-echo
4852 (format
4853 "mouse-2 or RET jump to diary file %s"
4854 (abbreviate-file-name (buffer-file-name)))
4855 'org-agenda-diary-link t
4856 'org-marker (org-agenda-new-marker (point-at-bol)))
4857 string)
4858 string)
4859
4860 (defun org-diary-default-entry ()
4861 "Add a dummy entry to the diary.
4862 Needed to avoid empty dates which mess up holiday display."
4863 ;; Catch the error if dealing with the new add-to-diary-alist
4864 (when org-disable-agenda-to-diary
4865 (condition-case nil
4866 (add-to-diary-list original-date "Org-mode dummy" "")
4867 (error
4868 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
4869
4870 (defun org-cycle-agenda-files ()
4871 "Cycle through the files in `org-agenda-files'.
4872 If the current buffer visits an agenda file, find the next one in the list.
4873 If the current buffer does not, find the first agenda file."
4874 (interactive)
4875 (let ((files (append org-agenda-files (list (car org-agenda-files))))
4876 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
4877 file)
4878 (unless files (error "No agenda files"))
4879 (catch 'exit
4880 (while (setq file (pop files))
4881 (if (equal (file-truename file) tcf)
4882 (when (car files)
4883 (find-file (car files))
4884 (throw 'exit t))))
4885 (find-file (car org-agenda-files)))))
4886
4887 (defun org-agenda-file-to-end (&optional file)
4888 "Move/add the current file to the end of the agenda fiole list.
4889 I the file is not present in the list, it is appended ot the list. If it is
4890 present, it is moved there."
4891 (interactive)
4892 (org-agenda-file-to-front 'to-end file))
4893
4894 (defun org-agenda-file-to-front (&optional to-end file)
4895 "Move/add the current file to the top of the agenda file list.
4896 If the file is not present in the list, it is added to the front. If it is
4897 present, it is moved there. With optional argument TO-END, add/move to the
4898 end of the list."
4899 (interactive "P")
4900 (let ((file-alist (mapcar (lambda (x)
4901 (cons (file-truename x) x))
4902 org-agenda-files))
4903 (ctf (file-truename (buffer-file-name)))
4904 x had)
4905 (setq x (assoc ctf file-alist) had x)
4906
4907 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
4908 (if to-end
4909 (setq file-alist (append (delq x file-alist) (list x)))
4910 (setq file-alist (cons x (delq x file-alist))))
4911 (setq org-agenda-files (mapcar 'cdr file-alist))
4912 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4913 (customize-save-variable 'org-agenda-files org-agenda-files))
4914 (org-install-agenda-files-menu)
4915 (message "File %s to %s of agenda file list"
4916 (if had "moved" "added") (if to-end "end" "front"))))
4917
4918 (defun org-remove-file (&optional file)
4919 "Remove current file from the list of files in variable `org-agenda-files'.
4920 These are the files which are being checked for agenda entries.
4921 Optional argument FILE means, use this file instead of the current."
4922 (interactive)
4923 (let* ((file (or file (buffer-file-name)))
4924 (true-file (file-truename file))
4925 (afile (abbreviate-file-name file))
4926 (files (delq nil (mapcar
4927 (lambda (x)
4928 (if (equal true-file
4929 (file-truename x))
4930 nil x))
4931 org-agenda-files))))
4932 (if (not (= (length files) (length org-agenda-files)))
4933 (progn
4934 (setq org-agenda-files files)
4935 (customize-save-variable 'org-agenda-files org-agenda-files)
4936 (org-install-agenda-files-menu)
4937 (message "Removed file: %s" afile))
4938 (message "File was not in list: %s" afile))))
4939
4940 (defun org-file-menu-entry (file)
4941 (vector file (list 'find-file file) t))
4942 ;; FIXME: Maybe removed a buffer visited through the menu from
4943 ;; org-agenda-new-buffers, so that the buffer will not be removed
4944 ;; when exiting the agenda????
4945
4946 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
4947 "Return a list of all relevant day numbers from BEG to END buffer positions.
4948 If NO-RANGES is non-nil, include only the start and end dates of a range,
4949 not every single day in the range. If FORCE-TODAY is non-nil, make
4950 sure that TODAY is included in the list. If INACTIVE is non-nil, also
4951 inactive time stamps (those in square brackets) are included."
4952 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
4953 dates date day day1 day2 ts1 ts2)
4954 (if force-today
4955 (setq dates (list (time-to-days (current-time)))))
4956 (save-excursion
4957 (goto-char beg)
4958 (while (re-search-forward re end t)
4959 (setq day (time-to-days (org-time-string-to-time
4960 (substring (match-string 1) 0 10))))
4961 (or (memq day dates) (push day dates)))
4962 (unless no-ranges
4963 (goto-char beg)
4964 (while (re-search-forward org-tr-regexp end t)
4965 (setq ts1 (substring (match-string 1) 0 10)
4966 ts2 (substring (match-string 2) 0 10)
4967 day1 (time-to-days (org-time-string-to-time ts1))
4968 day2 (time-to-days (org-time-string-to-time ts2)))
4969 (while (< (setq day1 (1+ day1)) day2)
4970 (or (memq day1 dates) (push day1 dates)))))
4971 (sort dates '<))))
4972
4973 ;;;###autoload
4974 (defun org-diary (&rest args)
4975 "Return diary information from org-files.
4976 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
4977 It accesses org files and extracts information from those files to be
4978 listed in the diary. The function accepts arguments specifying what
4979 items should be listed. The following arguments are allowed:
4980
4981 :timestamp List the headlines of items containing a date stamp or
4982 date range matching the selected date. Deadlines will
4983 also be listed, on the expiration day.
4984
4985 :deadline List any deadlines past due, or due within
4986 `org-deadline-warning-days'. The listing occurs only
4987 in the diary for *today*, not at any other date. If
4988 an entry is marked DONE, it is no longer listed.
4989
4990 :scheduled List all items which are scheduled for the given date.
4991 The diary for *today* also contains items which were
4992 scheduled earlier and are not yet marked DONE.
4993
4994 :todo List all TODO items from the org-file. This may be a
4995 long list - so this is not turned on by default.
4996 Like deadlines, these entries only show up in the
4997 diary for *today*, not at any other date.
4998
4999 The call in the diary file should look like this:
5000
5001 &%%(org-diary) ~/path/to/some/orgfile.org
5002
5003 Use a separate line for each org file to check. Or, if you omit the file name,
5004 all files listed in `org-agenda-files' will be checked automatically:
5005
5006 &%%(org-diary)
5007
5008 If you don't give any arguments (as in the example above), the default
5009 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5010 also be written as
5011
5012 &%%(org-diary :deadline :timestamp :scheduled)
5013
5014 The function expects the lisp variables `entry' and `date' to be provided
5015 by the caller, because this is how the calendar works. Don't use this
5016 function from a program - use `org-agenda-get-day-entries' instead."
5017 (org-agenda-maybe-reset-markers)
5018 (org-compile-prefix-format org-agenda-prefix-format)
5019 (setq args (or args '(:deadline :scheduled :timestamp)))
5020 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5021 (list entry)
5022 org-agenda-files))
5023 file rtn results)
5024 ;; If this is called during org-agenda, don't return any entries to
5025 ;; the calendar. Org Agenda will list these entries itself.
5026 (if org-disable-agenda-to-diary (setq files nil))
5027 (while (setq file (pop files))
5028 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5029 (setq results (append results rtn)))
5030 (if results
5031 (concat (org-finalize-agenda-entries results) "\n"))))
5032 (defvar org-category-table nil)
5033 (defun org-get-category-table ()
5034 "Get the table of categories and positions in current buffer."
5035 (let (tbl)
5036 (save-excursion
5037 (goto-char (point-min))
5038 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5039 (push (cons (point) (org-trim (match-string 2))) tbl)))
5040 tbl))
5041 (defun org-get-category (&optional pos)
5042 "Get the category applying to position POS."
5043 (if (not org-category-table)
5044 (cond
5045 ((null org-category)
5046 (setq org-category
5047 (if (buffer-file-name)
5048 (file-name-sans-extension
5049 (file-name-nondirectory (buffer-file-name)))
5050 "???")))
5051 ((symbolp org-category) (symbol-name org-category))
5052 (t org-category))
5053 (let ((tbl org-category-table)
5054 (pos (or pos (point))))
5055 (while (and tbl (> (caar tbl) pos))
5056 (pop tbl))
5057 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5058 org-category-table))))))
5059
5060 (defun org-agenda-get-day-entries (file date &rest args)
5061 "Does the work for `org-diary' and `org-agenda'.
5062 FILE is the path to a file to be checked for entries. DATE is date like
5063 the one returned by `calendar-current-date'. ARGS are symbols indicating
5064 which kind of entries should be extracted. For details about these, see
5065 the documentation of `org-diary'."
5066 (setq args (or args '(:deadline :scheduled :timestamp)))
5067 (let* ((org-startup-with-deadline-check nil)
5068 (org-startup-folded nil)
5069 (buffer (if (file-exists-p file)
5070 (org-get-agenda-file-buffer file)
5071 (error "No such file %s" file)))
5072 arg results rtn)
5073 (if (not buffer)
5074 ;; If file does not exist, make sure an error message ends up in diary
5075 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5076 (with-current-buffer buffer
5077 (unless (eq major-mode 'org-mode)
5078 (error "Agenda file %s is not in `org-mode'" file))
5079 (setq org-category-table (org-get-category-table))
5080 (let ((case-fold-search nil))
5081 (save-excursion
5082 (save-restriction
5083 (if org-respect-restriction
5084 (if (org-region-active-p)
5085 ;; Respect a region to restrict search
5086 (narrow-to-region (region-beginning) (region-end)))
5087 ;; If we work for the calendar or many files,
5088 ;; get rid of any restriction
5089 (widen))
5090 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5091 (while (setq arg (pop args))
5092 (cond
5093 ((and (eq arg :todo)
5094 (equal date (calendar-current-date)))
5095 (setq rtn (org-agenda-get-todos))
5096 (setq results (append results rtn)))
5097 ((eq arg :timestamp)
5098 (setq rtn (org-agenda-get-blocks))
5099 (setq results (append results rtn))
5100 (setq rtn (org-agenda-get-timestamps))
5101 (setq results (append results rtn)))
5102 ((eq arg :scheduled)
5103 (setq rtn (org-agenda-get-scheduled))
5104 (setq results (append results rtn)))
5105 ((eq arg :closed)
5106 (setq rtn (org-agenda-get-closed))
5107 (setq results (append results rtn)))
5108 ((and (eq arg :deadline)
5109 (equal date (calendar-current-date)))
5110 (setq rtn (org-agenda-get-deadlines))
5111 (setq results (append results rtn))))))))
5112 results))))
5113
5114 (defun org-entry-is-done-p ()
5115 "Is the current entry marked DONE?"
5116 (save-excursion
5117 (and (re-search-backward "[\r\n]\\*" nil t)
5118 (looking-at org-nl-done-regexp))))
5119
5120 (defun org-at-date-range-p ()
5121 "Is the cursor inside a date range?"
5122 (interactive)
5123 (save-excursion
5124 (catch 'exit
5125 (let ((pos (point)))
5126 (skip-chars-backward "^<\r\n")
5127 (skip-chars-backward "<")
5128 (and (looking-at org-tr-regexp)
5129 (>= (match-end 0) pos)
5130 (throw 'exit t))
5131 (skip-chars-backward "^<\r\n")
5132 (skip-chars-backward "<")
5133 (and (looking-at org-tr-regexp)
5134 (>= (match-end 0) pos)
5135 (throw 'exit t)))
5136 nil)))
5137
5138 (defun org-agenda-get-todos ()
5139 "Return the TODO information for agenda display."
5140 (let* ((props (list 'face nil
5141 'done-face 'org-done
5142 'mouse-face 'highlight
5143 'keymap org-agenda-keymap
5144 'help-echo
5145 (format "mouse-2 or RET jump to org file %s"
5146 (abbreviate-file-name (buffer-file-name)))))
5147 (regexp (concat "[\n\r]\\*+ *\\("
5148 (if org-select-this-todo-keyword
5149 (concat "\\<\\(" org-select-this-todo-keyword
5150 "\\)\\>")
5151 org-not-done-regexp)
5152 "[^\n\r]*\\)"))
5153 marker priority category
5154 ee txt)
5155 (goto-char (point-min))
5156 (while (re-search-forward regexp nil t)
5157 (goto-char (match-beginning 1))
5158 (setq marker (org-agenda-new-marker (point-at-bol))
5159 category (org-get-category)
5160 txt (org-format-agenda-item "" (match-string 1) category)
5161 priority
5162 (+ (org-get-priority txt)
5163 (if org-todo-kwd-priority-p
5164 (- org-todo-kwd-max-priority -2
5165 (length
5166 (member (match-string 2) org-todo-keywords)))
5167 1)))
5168 (add-text-properties
5169 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5170 'priority priority 'category category)
5171 props)
5172 txt)
5173 (push txt ee)
5174 (goto-char (match-end 1)))
5175 (nreverse ee)))
5176
5177 (defconst org-agenda-no-heading-message
5178 "No heading for this item in buffer or region")
5179
5180 (defun org-agenda-get-timestamps ()
5181 "Return the date stamp information for agenda display."
5182 (let* ((props (list 'face nil
5183 'mouse-face 'highlight
5184 'keymap org-agenda-keymap
5185 'help-echo
5186 (format "mouse-2 or RET jump to org file %s"
5187 (abbreviate-file-name (buffer-file-name)))))
5188 (regexp (regexp-quote
5189 (substring
5190 (format-time-string
5191 (car org-time-stamp-formats)
5192 (apply 'encode-time ; DATE bound by calendar
5193 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5194 0 11)))
5195 marker hdmarker deadlinep scheduledp donep tmp priority category
5196 ee txt timestr)
5197 (goto-char (point-min))
5198 (while (re-search-forward regexp nil t)
5199 (if (not (save-match-data (org-at-date-range-p)))
5200 (progn
5201 (setq marker (org-agenda-new-marker (match-beginning 0))
5202 category (org-get-category (match-beginning 0))
5203 tmp (buffer-substring (max (point-min)
5204 (- (match-beginning 0)
5205 org-ds-keyword-length))
5206 (match-beginning 0))
5207 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5208 deadlinep (string-match org-deadline-regexp tmp)
5209 scheduledp (string-match org-scheduled-regexp tmp)
5210 donep (org-entry-is-done-p))
5211 (if (string-match ">" timestr)
5212 ;; substring should only run to end of time stamp
5213 (setq timestr (substring timestr 0 (match-end 0))))
5214 (save-excursion
5215 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5216 (progn
5217 (goto-char (match-end 1))
5218 (setq hdmarker (org-agenda-new-marker))
5219 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5220 (setq txt (org-format-agenda-item
5221 (format "%s%s"
5222 (if deadlinep "Deadline: " "")
5223 (if scheduledp "Scheduled: " ""))
5224 (match-string 1) category timestr)))
5225 (setq txt org-agenda-no-heading-message))
5226 (setq priority (org-get-priority txt))
5227 (add-text-properties
5228 0 (length txt) (append (list 'org-marker marker
5229 'org-hd-marker hdmarker) props)
5230 txt)
5231 (if deadlinep
5232 (add-text-properties
5233 0 (length txt)
5234 (list 'face
5235 (if donep 'org-done 'org-warning)
5236 'undone-face 'org-warning
5237 'done-face 'org-done
5238 'category category
5239 'priority (+ 100 priority))
5240 txt)
5241 (if scheduledp
5242 (add-text-properties
5243 0 (length txt)
5244 (list 'face 'org-scheduled-today
5245 'undone-face 'org-scheduled-today
5246 'done-face 'org-done
5247 'category category
5248 priority (+ 99 priority))
5249 txt)
5250 (add-text-properties
5251 0 (length txt)
5252 (list 'priority priority 'category category) txt)))
5253 (push txt ee))
5254 (outline-next-heading))))
5255 (nreverse ee)))
5256
5257 (defun org-agenda-get-closed ()
5258 "Return the loggedd TODO entries for agenda display."
5259 (let* ((props (list 'mouse-face 'highlight
5260 'keymap org-agenda-keymap
5261 'help-echo
5262 (format "mouse-2 or RET jump to org file %s"
5263 (abbreviate-file-name (buffer-file-name)))))
5264 (regexp (concat
5265 "\\<" org-closed-string " *\\["
5266 (regexp-quote
5267 (substring
5268 (format-time-string
5269 (car org-time-stamp-formats)
5270 (apply 'encode-time ; DATE bound by calendar
5271 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5272 1 11))))
5273 marker hdmarker deadlinep scheduledp donep tmp priority category
5274 ee txt timestr)
5275 (goto-char (point-min))
5276 (while (re-search-forward regexp nil t)
5277 (if (not (save-match-data (org-at-date-range-p)))
5278 (progn
5279 (setq marker (org-agenda-new-marker (match-beginning 0))
5280 category (org-get-category (match-beginning 0))
5281 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5282 donep (org-entry-is-done-p))
5283 (if (string-match "\\]" timestr)
5284 ;; substring should only run to end of time stamp
5285 (setq timestr (substring timestr 0 (match-end 0))))
5286 (save-excursion
5287 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5288 (progn
5289 (goto-char (match-end 1))
5290 (setq hdmarker (org-agenda-new-marker))
5291 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5292 (setq txt (org-format-agenda-item
5293 "Closed: "
5294 (match-string 1) category timestr)))
5295 (setq txt org-agenda-no-heading-message))
5296 (setq priority 100000)
5297 (add-text-properties
5298 0 (length txt) (append (list 'org-marker marker
5299 'org-hd-marker hdmarker
5300 'face 'org-done
5301 'priority priority
5302 'category category
5303 'undone-face 'org-warning
5304 'done-face 'org-done) props)
5305 txt)
5306 (push txt ee))
5307 (outline-next-heading))))
5308 (nreverse ee)))
5309
5310 (defun org-agenda-get-deadlines ()
5311 "Return the deadline information for agenda display."
5312 (let* ((wdays org-deadline-warning-days)
5313 (props (list 'mouse-face 'highlight
5314 'keymap org-agenda-keymap
5315 'help-echo
5316 (format "mouse-2 or RET jump to org file %s"
5317 (abbreviate-file-name (buffer-file-name)))))
5318 (regexp org-deadline-time-regexp)
5319 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5320 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5321 d2 diff pos pos1 category
5322 ee txt head)
5323 (goto-char (point-min))
5324 (while (re-search-forward regexp nil t)
5325 (setq pos (1- (match-beginning 1))
5326 d2 (time-to-days
5327 (org-time-string-to-time (match-string 1)))
5328 diff (- d2 d1))
5329 ;; When to show a deadline in the calendar:
5330 ;; If the expiration is within wdays warning time.
5331 ;; Past-due deadlines are only shown on the current date
5332 (if (and (< diff wdays) todayp (not (= diff 0)))
5333 (save-excursion
5334 (setq category (org-get-category))
5335 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5336 (progn
5337 (goto-char (match-end 0))
5338 (setq pos1 (match-end 1))
5339 (setq head (buffer-substring-no-properties
5340 (point)
5341 (progn (skip-chars-forward "^\r\n")
5342 (point))))
5343 (if (string-match org-looking-at-done-regexp head)
5344 (setq txt nil)
5345 (setq txt (org-format-agenda-item
5346 (format "In %3d d.: " diff) head category))))
5347 (setq txt org-agenda-no-heading-message))
5348 (when txt
5349 (add-text-properties
5350 0 (length txt)
5351 (append
5352 (list 'org-marker (org-agenda-new-marker pos)
5353 'org-hd-marker (org-agenda-new-marker pos1)
5354 'priority (+ (- 10 diff) (org-get-priority txt))
5355 'category category
5356 'face (cond ((<= diff 0) 'org-warning)
5357 ((<= diff 5) 'org-scheduled-previously)
5358 (t nil))
5359 'undone-face (cond
5360 ((<= diff 0) 'org-warning)
5361 ((<= diff 5) 'org-scheduled-previously)
5362 (t nil))
5363 'done-face 'org-done)
5364 props)
5365 txt)
5366 (push txt ee)))))
5367 ee))
5368
5369 (defun org-agenda-get-scheduled ()
5370 "Return the scheduled information for agenda display."
5371 (let* ((props (list 'face 'org-scheduled-previously
5372 'undone-face 'org-scheduled-previously
5373 'done-face 'org-done
5374 'mouse-face 'highlight
5375 'keymap org-agenda-keymap
5376 'help-echo
5377 (format "mouse-2 or RET jump to org file %s"
5378 (abbreviate-file-name (buffer-file-name)))))
5379 (regexp org-scheduled-time-regexp)
5380 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5381 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5382 d2 diff pos pos1 category
5383 ee txt head)
5384 (goto-char (point-min))
5385 (while (re-search-forward regexp nil t)
5386 (setq pos (1- (match-beginning 1))
5387 d2 (time-to-days
5388 (org-time-string-to-time (match-string 1)))
5389 diff (- d2 d1))
5390 ;; When to show a scheduled item in the calendar:
5391 ;; If it is on or past the date.
5392 (if (and (< diff 0) todayp)
5393 (save-excursion
5394 (setq category (org-get-category))
5395 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5396 (progn
5397 (goto-char (match-end 0))
5398 (setq pos1 (match-end 1))
5399 (setq head (buffer-substring-no-properties
5400 (point)
5401 (progn (skip-chars-forward "^\r\n") (point))))
5402 (if (string-match org-looking-at-done-regexp head)
5403 (setq txt nil)
5404 (setq txt (org-format-agenda-item
5405 (format "Sched.%2dx: " (- 1 diff)) head
5406 category))))
5407 (setq txt org-agenda-no-heading-message))
5408 (when txt
5409 (add-text-properties
5410 0 (length txt)
5411 (append (list 'org-marker (org-agenda-new-marker pos)
5412 'org-hd-marker (org-agenda-new-marker pos1)
5413 'priority (+ (- 5 diff) (org-get-priority txt))
5414 'category category)
5415 props) txt)
5416 (push txt ee)))))
5417 ee))
5418
5419 (defun org-agenda-get-blocks ()
5420 "Return the date-range information for agenda display."
5421 (let* ((props (list 'face nil
5422 'mouse-face 'highlight
5423 'keymap org-agenda-keymap
5424 'help-echo
5425 (format "mouse-2 or RET jump to org file %s"
5426 (abbreviate-file-name (buffer-file-name)))))
5427 (regexp org-tr-regexp)
5428 (d0 (calendar-absolute-from-gregorian date))
5429 marker hdmarker ee txt d1 d2 s1 s2 timestr category)
5430 (goto-char (point-min))
5431 (while (re-search-forward regexp nil t)
5432 (setq timestr (match-string 0)
5433 s1 (match-string 1)
5434 s2 (match-string 2)
5435 d1 (time-to-days (org-time-string-to-time s1))
5436 d2 (time-to-days (org-time-string-to-time s2)))
5437 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5438 ;; Only allow days between the limits, because the normal
5439 ;; date stamps will catch the limits.
5440 (save-excursion
5441 (setq marker (org-agenda-new-marker (point)))
5442 (setq category (org-get-category))
5443 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5444 (progn
5445 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5446 (goto-char (match-end 1))
5447 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5448 (setq txt (org-format-agenda-item
5449 (format (if (= d1 d2) "" "(%d/%d): ")
5450 (1+ (- d0 d1)) (1+ (- d2 d1)))
5451 (match-string 1) category
5452 (if (= d0 d1) timestr))))
5453 (setq txt org-agenda-no-heading-message))
5454 (add-text-properties
5455 0 (length txt) (append (list 'org-marker marker
5456 'org-hd-marker hdmarker
5457 'priority (org-get-priority txt)
5458 'category category)
5459 props)
5460 txt)
5461 (push txt ee)))
5462 (outline-next-heading))
5463 ;; Sort the entries by expiration date.
5464 (nreverse ee)))
5465
5466 (defconst org-plain-time-of-day-regexp
5467 (concat
5468 "\\(\\<[012]?[0-9]"
5469 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5470 "\\(--?"
5471 "\\(\\<[012]?[0-9]"
5472 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5473 "\\)?")
5474 "Regular expression to match a plain time or time range.
5475 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5476 groups carry important information:
5477 0 the full match
5478 1 the first time, range or not
5479 8 the second time, if it is a range.")
5480
5481 (defconst org-stamp-time-of-day-regexp
5482 (concat
5483 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5484 "\\([012][0-9]:[0-5][0-9]\\)>"
5485 "\\(--?"
5486 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5487 "Regular expression to match a timestamp time or time range.
5488 After a match, the following groups carry important information:
5489 0 the full match
5490 1 date plus weekday, for backreferencing to make sure both times on same day
5491 2 the first time, range or not
5492 4 the second time, if it is a range.")
5493
5494 (defvar org-prefix-has-time nil
5495 "A flag, set by `org-compile-prefix-format'.
5496 The flag is set if the currently compiled format contains a `%t'.")
5497
5498 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
5499 "Format TXT to be inserted into the agenda buffer.
5500 In particular, it adds the prefix and corresponding text properties. EXTRA
5501 must be a string and replaces the `%s' specifier in the prefix format.
5502 CATEGORY (string, symbol or nil) may be used to overule the default
5503 category taken from local variable or file name. It will replace the `%c'
5504 specifier in the format. DOTIME, when non-nil, indicates that a
5505 time-of-day should be extracted from TXT for sorting of this entry, and for
5506 the `%t' specifier in the format. When DOTIME is a string, this string is
5507 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5508 only the correctly processes TXT should be returned - this is used by
5509 `org-agenda-change-all-lines'."
5510 (save-match-data
5511 ;; Diary entries sometimes have extra whitespace at the beginning
5512 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5513 (let* ((category (or category
5514 org-category
5515 (if (buffer-file-name)
5516 (file-name-sans-extension
5517 (file-name-nondirectory (buffer-file-name)))
5518 "")))
5519 time ;; needed for the eval of the prefix format
5520 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5521 (time-of-day (and dotime (org-get-time-of-day ts)))
5522 stamp plain s0 s1 s2 rtn)
5523 (when (and dotime time-of-day org-prefix-has-time)
5524 ;; Extract starting and ending time and move them to prefix
5525 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5526 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5527 (setq s0 (match-string 0 ts)
5528 s1 (match-string (if plain 1 2) ts)
5529 s2 (match-string (if plain 8 4) ts))
5530
5531 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5532 ;; them, we might want to remove them there to avoid duplication.
5533 ;; The user can turn this off with a variable.
5534 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5535 (string-match (concat (regexp-quote s0) " *") txt)
5536 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5537 (= (match-beginning 0) 0)
5538 t))
5539 (setq txt (replace-match "" nil nil txt))))
5540 ;; Normalize the time(s) to 24 hour
5541 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5542 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5543
5544 ;; Create the final string
5545 (if noprefix
5546 (setq rtn txt)
5547 ;; Prepare the variables needed in the eval of the compiled format
5548 (setq time (cond (s2 (concat s1 "-" s2))
5549 (s1 (concat s1 "......"))
5550 (t ""))
5551 extra (or extra "")
5552 category (if (symbolp category) (symbol-name category) category))
5553 ;; Evaluate the compiled format
5554 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5555
5556 ;; And finally add the text properties
5557 (add-text-properties
5558 0 (length rtn) (list 'category (downcase category)
5559 'prefix-length (- (length rtn) (length txt))
5560 'time-of-day time-of-day
5561 'dotime dotime)
5562 rtn)
5563 rtn)))
5564
5565 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5566 (catch 'exit
5567 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5568 ((and todayp (member 'today (car org-agenda-time-grid))))
5569 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5570 ((member 'weekly (car org-agenda-time-grid)))
5571 (t (throw 'exit list)))
5572 (let* ((have (delq nil (mapcar
5573 (lambda (x) (get-text-property 1 'time-of-day x))
5574 list)))
5575 (string (nth 1 org-agenda-time-grid))
5576 (gridtimes (nth 2 org-agenda-time-grid))
5577 (req (car org-agenda-time-grid))
5578 (remove (member 'remove-match req))
5579 new time)
5580 (if (and (member 'require-timed req) (not have))
5581 ;; don't show empty grid
5582 (throw 'exit list))
5583 (while (setq time (pop gridtimes))
5584 (unless (and remove (member time have))
5585 (setq time (int-to-string time))
5586 (push (org-format-agenda-item
5587 nil string "" ;; FIXME: put a category?
5588 (concat (substring time 0 -2) ":" (substring time -2)))
5589 new)
5590 (put-text-property
5591 1 (length (car new)) 'face 'org-time-grid (car new))))
5592 (if (member 'time-up org-agenda-sorting-strategy)
5593 (append new list)
5594 (append list new)))))
5595
5596 (defun org-compile-prefix-format (format)
5597 "Compile the prefix format into a Lisp form that can be evaluated.
5598 The resulting form is returned and stored in the variable
5599 `org-prefix-format-compiled'."
5600 (setq org-prefix-has-time nil)
5601 (let ((start 0) varform vars var (s format) c f opt)
5602 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5603 s start)
5604 (setq var (cdr (assoc (match-string 4 s)
5605 '(("c" . category) ("t" . time) ("s" . extra))))
5606 c (or (match-string 3 s) "")
5607 opt (match-beginning 1)
5608 start (1+ (match-beginning 0)))
5609 (if (equal var 'time) (setq org-prefix-has-time t))
5610 (setq f (concat "%" (match-string 2 s) "s"))
5611 (if opt
5612 (setq varform
5613 `(if (equal "" ,var)
5614 ""
5615 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5616 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5617 (setq s (replace-match "%s" t nil s))
5618 (push varform vars))
5619 (setq vars (nreverse vars))
5620 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5621
5622 (defun org-get-time-of-day (s &optional string)
5623 "Check string S for a time of day.
5624 If found, return it as a military time number between 0 and 2400.
5625 If not found, return nil.
5626 The optional STRING argument forces conversion into a 5 character wide string
5627 HH:MM."
5628 (save-match-data
5629 (when
5630 (or
5631 (string-match
5632 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5633 (string-match
5634 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5635 (let* ((t0 (+ (* 100
5636 (+ (string-to-number (match-string 1 s))
5637 (if (and (match-beginning 4)
5638 (equal (downcase (match-string 4 s)) "pm"))
5639 12 0)))
5640 (if (match-beginning 3)
5641 (string-to-number (match-string 3 s))
5642 0)))
5643 (t1 (concat " " (int-to-string t0))))
5644 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
5645
5646 (defun org-finalize-agenda-entries (list)
5647 "Sort and concatenate the agenda items."
5648 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
5649
5650 (defsubst org-cmp-priority (a b)
5651 "Compare the priorities of string a and b."
5652 (let ((pa (or (get-text-property 1 'priority a) 0))
5653 (pb (or (get-text-property 1 'priority b) 0)))
5654 (cond ((> pa pb) +1)
5655 ((< pa pb) -1)
5656 (t nil))))
5657
5658 (defsubst org-cmp-category (a b)
5659 "Compare the string values of categories of strings a and b."
5660 (let ((ca (or (get-text-property 1 'category a) ""))
5661 (cb (or (get-text-property 1 'category b) "")))
5662 (cond ((string-lessp ca cb) -1)
5663 ((string-lessp cb ca) +1)
5664 (t nil))))
5665
5666 (defsubst org-cmp-time (a b)
5667 "Compare the time-of-day values of strings a and b."
5668 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
5669 (ta (or (get-text-property 1 'time-of-day a) def))
5670 (tb (or (get-text-property 1 'time-of-day b) def)))
5671 (cond ((< ta tb) -1)
5672 ((< tb ta) +1)
5673 (t nil))))
5674
5675 (defun org-entries-lessp (a b)
5676 "Predicate for sorting agenda entries."
5677 ;; The following variables will be used when the form is evaluated.
5678 (let* ((time-up (org-cmp-time a b))
5679 (time-down (if time-up (- time-up) nil))
5680 (priority-up (org-cmp-priority a b))
5681 (priority-down (if priority-up (- priority-up) nil))
5682 (category-up (org-cmp-category a b))
5683 (category-down (if category-up (- category-up) nil))
5684 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
5685 (cdr (assoc
5686 (eval (cons 'or org-agenda-sorting-strategy))
5687 '((-1 . t) (1 . nil) (nil . nil))))))
5688
5689 (defun org-agenda-show-priority ()
5690 "Show the priority of the current item.
5691 This priority is composed of the main priority given with the [#A] cookies,
5692 and by additional input from the age of a schedules or deadline entry."
5693 (interactive)
5694 (let* ((pri (get-text-property (point-at-bol) 'priority)))
5695 (message "Priority is %d" (if pri pri -1000))))
5696
5697 (defun org-agenda-goto (&optional highlight)
5698 "Go to the Org-mode file which contains the item at point."
5699 (interactive)
5700 (let* ((marker (or (get-text-property (point) 'org-marker)
5701 (org-agenda-error)))
5702 (buffer (marker-buffer marker))
5703 (pos (marker-position marker)))
5704 (switch-to-buffer-other-window buffer)
5705 (widen)
5706 (goto-char pos)
5707 (when (eq major-mode 'org-mode)
5708 (org-show-hidden-entry)
5709 (save-excursion
5710 (and (outline-next-heading)
5711 (org-flag-heading nil)))) ; show the next heading
5712 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
5713
5714 (defun org-agenda-switch-to ()
5715 "Go to the Org-mode file which contains the item at point."
5716 (interactive)
5717 (let* ((marker (or (get-text-property (point) 'org-marker)
5718 (org-agenda-error)))
5719 (buffer (marker-buffer marker))
5720 (pos (marker-position marker)))
5721 (switch-to-buffer buffer)
5722 (delete-other-windows)
5723 (widen)
5724 (goto-char pos)
5725 (when (eq major-mode 'org-mode)
5726 (org-show-hidden-entry)
5727 (save-excursion
5728 (and (outline-next-heading)
5729 (org-flag-heading nil)))))) ; show the next heading
5730
5731 (defun org-agenda-goto-mouse (ev)
5732 "Go to the Org-mode file which contains the item at the mouse click."
5733 (interactive "e")
5734 (mouse-set-point ev)
5735 (org-agenda-goto))
5736
5737 (defun org-agenda-show ()
5738 "Display the Org-mode file which contains the item at point."
5739 (interactive)
5740 (let ((win (selected-window)))
5741 (org-agenda-goto t)
5742 (select-window win)))
5743
5744 (defun org-agenda-recenter (arg)
5745 "Display the Org-mode file which contains the item at point and recenter."
5746 (interactive "P")
5747 (let ((win (selected-window)))
5748 (org-agenda-goto t)
5749 (recenter arg)
5750 (select-window win)))
5751
5752 (defun org-agenda-show-mouse (ev)
5753 "Display the Org-mode file which contains the item at the mouse click."
5754 (interactive "e")
5755 (mouse-set-point ev)
5756 (org-agenda-show))
5757
5758 (defun org-agenda-check-no-diary ()
5759 "Check if the entry is a diary link and abort if yes."
5760 (if (get-text-property (point) 'org-agenda-diary-link)
5761 (org-agenda-error)))
5762
5763 (defun org-agenda-error ()
5764 (error "Command not allowed in this line"))
5765
5766 (defvar org-last-heading-marker (make-marker)
5767 "Marker pointing to the headline that last changed its TODO state
5768 by a remote command from the agenda.")
5769
5770 (defun org-agenda-todo (&optional arg)
5771 "Cycle TODO state of line at point, also in Org-mode file.
5772 This changes the line at point, all other lines in the agenda referring to
5773 the same tree node, and the headline of the tree node in the Org-mode file."
5774 (interactive "P")
5775 (org-agenda-check-no-diary)
5776 (let* ((col (current-column))
5777 (marker (or (get-text-property (point) 'org-marker)
5778 (org-agenda-error)))
5779 (buffer (marker-buffer marker))
5780 (pos (marker-position marker))
5781 (hdmarker (get-text-property (point) 'org-hd-marker))
5782 (buffer-read-only nil)
5783 newhead)
5784 (with-current-buffer buffer
5785 (widen)
5786 (goto-char pos)
5787 (org-show-hidden-entry)
5788 (save-excursion
5789 (and (outline-next-heading)
5790 (org-flag-heading nil))) ; show the next heading
5791 (org-todo arg)
5792 (forward-char 1)
5793 (setq newhead (org-get-heading))
5794 (save-excursion
5795 (org-back-to-heading)
5796 (move-marker org-last-heading-marker (point))))
5797 (beginning-of-line 1)
5798 (save-excursion
5799 (org-agenda-change-all-lines newhead hdmarker 'fixface))
5800 (move-to-column col)))
5801
5802 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
5803 "Change all lines in the agenda buffer which match hdmarker.
5804 The new content of the line will be NEWHEAD (as modified by
5805 `org-format-agenda-item'). HDMARKER is checked with
5806 `equal' against all `org-hd-marker' text properties in the file.
5807 If FIXFACE is non-nil, the face of each item is modified acording to
5808 the new TODO state."
5809 (let* (props m pl undone-face done-face finish new dotime cat)
5810 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
5811 (save-excursion
5812 (goto-char (point-max))
5813 (beginning-of-line 1)
5814 (while (not finish)
5815 (setq finish (bobp))
5816 (when (and (setq m (get-text-property (point) 'org-hd-marker))
5817 (equal m hdmarker))
5818 (setq props (text-properties-at (point))
5819 dotime (get-text-property (point) 'dotime)
5820 cat (get-text-property (point) 'category)
5821 new (org-format-agenda-item "x" newhead cat dotime 'noprefix)
5822 pl (get-text-property (point) 'prefix-length)
5823 undone-face (get-text-property (point) 'undone-face)
5824 done-face (get-text-property (point) 'done-face))
5825 (move-to-column pl)
5826 (if (looking-at ".*")
5827 (progn
5828 (replace-match new t t)
5829 (beginning-of-line 1)
5830 (add-text-properties (point-at-bol) (point-at-eol) props)
5831 (if fixface
5832 (add-text-properties
5833 (point-at-bol) (point-at-eol)
5834 (list 'face
5835 (if org-last-todo-state-is-todo
5836 undone-face done-face))))
5837 (beginning-of-line 1))
5838 (error "Line update did not work")))
5839 (beginning-of-line 0)))))
5840
5841 (defun org-agenda-priority-up ()
5842 "Increase the priority of line at point, also in Org-mode file."
5843 (interactive)
5844 (org-agenda-priority 'up))
5845
5846 (defun org-agenda-priority-down ()
5847 "Decrease the priority of line at point, also in Org-mode file."
5848 (interactive)
5849 (org-agenda-priority 'down))
5850
5851 (defun org-agenda-priority (&optional force-direction)
5852 "Set the priority of line at point, also in Org-mode file.
5853 This changes the line at point, all other lines in the agenda referring to
5854 the same tree node, and the headline of the tree node in the Org-mode file."
5855 (interactive)
5856 (org-agenda-check-no-diary)
5857 (let* ((marker (or (get-text-property (point) 'org-marker)
5858 (org-agenda-error)))
5859 (buffer (marker-buffer marker))
5860 (pos (marker-position marker))
5861 (hdmarker (get-text-property (point) 'org-hd-marker))
5862 (buffer-read-only nil)
5863 newhead)
5864 (with-current-buffer buffer
5865 (widen)
5866 (goto-char pos)
5867 (org-show-hidden-entry)
5868 (save-excursion
5869 (and (outline-next-heading)
5870 (org-flag-heading nil))) ; show the next heading
5871 (funcall 'org-priority force-direction)
5872 (end-of-line 1)
5873 (setq newhead (org-get-heading)))
5874 (org-agenda-change-all-lines newhead hdmarker)
5875 (beginning-of-line 1)))
5876
5877 (defun org-agenda-date-later (arg &optional what)
5878 "Change the date of this item to one day later."
5879 (interactive "p")
5880 (org-agenda-check-no-diary)
5881 (let* ((marker (or (get-text-property (point) 'org-marker)
5882 (org-agenda-error)))
5883 (buffer (marker-buffer marker))
5884 (pos (marker-position marker)))
5885 (with-current-buffer buffer
5886 (widen)
5887 (goto-char pos)
5888 (if (not (org-at-timestamp-p))
5889 (error "Cannot find time stamp"))
5890 (org-timestamp-change arg (or what 'day))
5891 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5892
5893 (defun org-agenda-date-earlier (arg &optional what)
5894 "Change the date of this item to one day earlier."
5895 (interactive "p")
5896 (org-agenda-date-later (- arg) what))
5897
5898 (defun org-agenda-date-prompt (arg)
5899 "Change the date of this item. Date is prompted for, with default today.
5900 The prefix ARG is passed to the `org-time-stamp' command and can therefore
5901 be used to request time specification in the time stamp."
5902 (interactive "P")
5903 (org-agenda-check-no-diary)
5904 (let* ((marker (or (get-text-property (point) 'org-marker)
5905 (org-agenda-error)))
5906 (buffer (marker-buffer marker))
5907 (pos (marker-position marker)))
5908 (with-current-buffer buffer
5909 (widen)
5910 (goto-char pos)
5911 (if (not (org-at-timestamp-p))
5912 (error "Cannot find time stamp"))
5913 (org-time-stamp arg)
5914 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5915
5916 (defun org-get-heading ()
5917 "Return the heading of the current entry, without the stars."
5918 (save-excursion
5919 (and (bolp) (end-of-line 1))
5920 (if (and (re-search-backward "[\r\n]\\*" nil t)
5921 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5922 (match-string 1)
5923 "")))
5924
5925 (defun org-agenda-diary-entry ()
5926 "Make a diary entry, like the `i' command from the calendar.
5927 All the standard commands work: block, weekly etc"
5928 (interactive)
5929 (require 'diary-lib)
5930 (let* ((char (progn
5931 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5932 (read-char-exclusive)))
5933 (cmd (cdr (assoc char
5934 '((?d . insert-diary-entry)
5935 (?w . insert-weekly-diary-entry)
5936 (?m . insert-monthly-diary-entry)
5937 (?y . insert-yearly-diary-entry)
5938 (?a . insert-anniversary-diary-entry)
5939 (?b . insert-block-diary-entry)
5940 (?c . insert-cyclic-diary-entry)))))
5941 (oldf (symbol-function 'calendar-cursor-to-date))
5942 (point (point))
5943 (mark (or (mark t) (point))))
5944 (unless cmd
5945 (error "No command associated with <%c>" char))
5946 (unless (and (get-text-property point 'day)
5947 (or (not (equal ?b char))
5948 (get-text-property mark 'day)))
5949 (error "Don't know which date to use for diary entry"))
5950 ;; We implement this by hacking the `calendar-cursor-to-date' function
5951 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5952 (let ((calendar-mark-ring
5953 (list (calendar-gregorian-from-absolute
5954 (or (get-text-property mark 'day)
5955 (get-text-property point 'day))))))
5956 (unwind-protect
5957 (progn
5958 (fset 'calendar-cursor-to-date
5959 (lambda (&optional error)
5960 (calendar-gregorian-from-absolute
5961 (get-text-property point 'day))))
5962 (call-interactively cmd))
5963 (fset 'calendar-cursor-to-date oldf)))))
5964
5965
5966 (defun org-agenda-execute-calendar-command (cmd)
5967 "Execute a calendar command from the agenda, with the date associated to
5968 the cursor position."
5969 (require 'diary-lib)
5970 (unless (get-text-property (point) 'day)
5971 (error "Don't know which date to use for calendar command"))
5972 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5973 (point (point))
5974 (date (calendar-gregorian-from-absolute
5975 (get-text-property point 'day)))
5976 (displayed-day (extract-calendar-day date))
5977 (displayed-month (extract-calendar-month date))
5978 (displayed-year (extract-calendar-year date)))
5979 (unwind-protect
5980 (progn
5981 (fset 'calendar-cursor-to-date
5982 (lambda (&optional error)
5983 (calendar-gregorian-from-absolute
5984 (get-text-property point 'day))))
5985 (call-interactively cmd))
5986 (fset 'calendar-cursor-to-date oldf))))
5987
5988 (defun org-agenda-phases-of-moon ()
5989 "Display the phases of the moon for the 3 months around the cursor date."
5990 (interactive)
5991 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5992
5993 (defun org-agenda-holidays ()
5994 "Display the holidays for the 3 months around the cursor date."
5995 (interactive)
5996 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5997
5998 (defun org-agenda-sunrise-sunset (arg)
5999 "Display sunrise and sunset for the cursor date.
6000 Latitude and longitude can be specified with the variables
6001 `calendar-latitude' and `calendar-longitude'. When called with prefix
6002 argument, latitude and longitude will be prompted for."
6003 (interactive "P")
6004 (let ((calendar-longitude (if arg nil calendar-longitude))
6005 (calendar-latitude (if arg nil calendar-latitude))
6006 (calendar-location-name
6007 (if arg "the given coordinates" calendar-location-name)))
6008 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6009
6010 (defun org-agenda-goto-calendar ()
6011 "Open the Emacs calendar with the date at the cursor."
6012 (interactive)
6013 (let* ((day (or (get-text-property (point) 'day)
6014 (error "Don't know which date to open in calendar")))
6015 (date (calendar-gregorian-from-absolute day))
6016 (calendar-move-hook nil)
6017 (view-diary-entries-initially nil))
6018 (calendar)
6019 (calendar-goto-date date)))
6020
6021 (defun org-calendar-goto-agenda ()
6022 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6023 This is a command that has to be installed in `calendar-mode-map'."
6024 (interactive)
6025 (org-agenda nil (calendar-absolute-from-gregorian
6026 (calendar-cursor-to-date))
6027 nil t))
6028
6029 (defun org-agenda-convert-date ()
6030 (interactive)
6031 (let ((day (get-text-property (point) 'day))
6032 date s)
6033 (unless day
6034 (error "Don't know which date to convert"))
6035 (setq date (calendar-gregorian-from-absolute day))
6036 (setq s (concat
6037 "Gregorian: " (calendar-date-string date) "\n"
6038 "ISO: " (calendar-iso-date-string date) "\n"
6039 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6040 "Julian: " (calendar-julian-date-string date) "\n"
6041 "Astron. JD: " (calendar-astro-date-string date)
6042 " (Julian date number at noon UTC)\n"
6043 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6044 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6045 "French: " (calendar-french-date-string date) "\n"
6046 "Mayan: " (calendar-mayan-date-string date) "\n"
6047 "Coptic: " (calendar-coptic-date-string date) "\n"
6048 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6049 "Persian: " (calendar-persian-date-string date) "\n"
6050 "Chinese: " (calendar-chinese-date-string date) "\n"))
6051 (with-output-to-temp-buffer "*Dates*"
6052 (princ s))
6053 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
6054
6055 ;;; Link Stuff
6056
6057 (defun org-find-file-at-mouse (ev)
6058 "Open file link or URL at mouse."
6059 (interactive "e")
6060 (mouse-set-point ev)
6061 (org-open-at-point 'in-emacs))
6062
6063 (defun org-open-at-mouse (ev)
6064 "Open file link or URL at mouse."
6065 (interactive "e")
6066 (mouse-set-point ev)
6067 (org-open-at-point))
6068
6069 (defun org-open-at-point (&optional in-emacs)
6070 "Open link at or after point.
6071 If there is no link at point, this function will search forward up to
6072 the end of the current subtree.
6073 Normally, files will be opened by an appropriate application. If the
6074 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6075 (interactive "P")
6076 (org-remove-occur-highlights nil nil t)
6077 (if (org-at-timestamp-p)
6078 (org-agenda nil (time-to-days (org-time-string-to-time
6079 (substring (match-string 1) 0 10)))
6080 1)
6081 (let (type path line search (pos (point)))
6082 (catch 'match
6083 (save-excursion
6084 (skip-chars-backward
6085 (concat (if org-allow-space-in-links "^" "^ ")
6086 org-non-link-chars))
6087 (when (looking-at org-link-regexp)
6088 (setq type (match-string 1)
6089 path (match-string 2))
6090 (throw 'match t)))
6091 (save-excursion
6092 (skip-chars-backward "a-zA-Z_")
6093 (when (looking-at org-camel-regexp)
6094 (setq type "camel" path (match-string 0))
6095 (if (equal (char-before) ?*)
6096 (setq path (concat "*" path))))
6097 (throw 'match t))
6098 (save-excursion
6099 (when (re-search-forward
6100 org-link-regexp
6101 (save-excursion
6102 (condition-case nil
6103 (progn (outline-end-of-subtree) (max pos (point)))
6104 (error (end-of-line 1) (point))))
6105 t)
6106 (setq type (match-string 1)
6107 path (match-string 2)))))
6108 (unless path
6109 (error "No link found"))
6110 ;; Remove any trailing spaces in path
6111 (if (string-match " +\\'" path)
6112 (setq path (replace-match "" t t path)))
6113
6114 (cond
6115
6116 ((string= type "camel")
6117 (org-link-search
6118 path
6119 (cond ((equal in-emacs '(4)) 'occur)
6120 ((equal in-emacs '(16)) 'org-occur)
6121 (t nil))))
6122
6123 ((string= type "file")
6124 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6125 (setq line (string-to-number (match-string 1 path))
6126 path (substring path 0 (match-beginning 0)))
6127 (if (string-match "::\\(.+\\)\\'" path)
6128 (setq search (match-string 1 path)
6129 path (substring path 0 (match-beginning 0)))))
6130 (org-open-file path in-emacs line search))
6131
6132 ((string= type "news")
6133 (org-follow-gnus-link path))
6134
6135 ((string= type "bbdb")
6136 (org-follow-bbdb-link path))
6137
6138 ((string= type "gnus")
6139 (let (group article)
6140 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6141 (error "Error in Gnus link"))
6142 (setq group (match-string 1 path)
6143 article (match-string 3 path))
6144 (org-follow-gnus-link group article)))
6145
6146 ((string= type "vm")
6147 (let (folder article)
6148 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6149 (error "Error in VM link"))
6150 (setq folder (match-string 1 path)
6151 article (match-string 3 path))
6152 ;; in-emacs is the prefix arg, will be interpreted as read-only
6153 (org-follow-vm-link folder article in-emacs)))
6154
6155 ((string= type "wl")
6156 (let (folder article)
6157 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6158 (error "Error in Wanderlust link"))
6159 (setq folder (match-string 1 path)
6160 article (match-string 3 path))
6161 (org-follow-wl-link folder article)))
6162
6163 ((string= type "rmail")
6164 (let (folder article)
6165 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6166 (error "Error in RMAIL link"))
6167 (setq folder (match-string 1 path)
6168 article (match-string 3 path))
6169 (org-follow-rmail-link folder article)))
6170
6171 ((string= type "shell")
6172 (let ((cmd path))
6173 (while (string-match "@{" cmd)
6174 (setq cmd (replace-match "<" t t cmd)))
6175 (while (string-match "@}" cmd)
6176 (setq cmd (replace-match ">" t t cmd)))
6177 (if (or (not org-confirm-shell-links)
6178 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6179 (shell-command cmd)
6180 (error "Abort"))))
6181
6182 (t
6183 (browse-url-at-point))))))
6184
6185 (defun org-link-search (s &optional type)
6186 "Search for a link search option.
6187 When S is a CamelCaseWord, search for a target, or for a sentence containing
6188 the words. If S is surrounded by forward slashes, it is interpreted as a
6189 regular expression. In org-mode files, this will create an `org-occur'
6190 sparse tree. In ordinary files, `occur' will be used to list matched.
6191 If the current buffer is in `dired-mode', grep will be used to search
6192 in all files."
6193 (let ((case-fold-search t)
6194 (s0 s)
6195 (pos (point))
6196 (pre "") (post "")
6197 words re0 re1 re2 re3 re4 re5 reall)
6198 (cond ((string-match "^/\\(.*\\)/$" s)
6199 ;; A regular expression
6200 (cond
6201 ((eq major-mode 'org-mode)
6202 (org-occur (match-string 1 s)))
6203 ;;((eq major-mode 'dired-mode)
6204 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6205 (t (org-do-occur (match-string 1 s)))))
6206 ((string-match (concat "^" org-camel-regexp) s)
6207 ;; A camel
6208 (if (equal (string-to-char s) ?*)
6209 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6210 post "[ \t]*$"
6211 s (substring s 1)))
6212 (remove-text-properties
6213 0 (length s)
6214 '(face nil mouse-face nil keymap nil fontified nil) s)
6215 ;; Make a series of regular expressions to find a match
6216 (setq words (org-camel-to-words s)
6217 re0 (concat "<<" (regexp-quote s0) ">>")
6218 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6219 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6220 re1 (concat pre re2 post)
6221 re3 (concat pre re4 post)
6222 re5 (concat pre ".*" re4)
6223 re2 (concat pre re2)
6224 re4 (concat pre re4)
6225 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6226 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6227 re5 "\\)"
6228 ))
6229 (cond
6230 ((eq type 'org-occur) (org-occur reall))
6231 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6232 (t (goto-char (point-min))
6233 (if (or (re-search-forward re0 nil t)
6234 (re-search-forward re1 nil t)
6235 (re-search-forward re2 nil t)
6236 (re-search-forward re3 nil t)
6237 (re-search-forward re4 nil t)
6238 (re-search-forward re5 nil t))
6239 (goto-char (match-beginning 0))
6240 (goto-char pos)
6241 (error "No match")))))
6242 (t
6243 ;; Normal string-search
6244 (goto-char (point-min))
6245 (if (search-forward s nil t)
6246 (goto-char (match-beginning 0))
6247 (error "No match"))))))
6248
6249 (defun org-do-occur (regexp &optional cleanup)
6250 "Call the Emacs command `occur'.
6251 If CLEANUP is non-nil, remove the printout of the regular expression
6252 in the *Occur* buffer. This is useful if the regex is long and not useful
6253 to read."
6254 (occur regexp)
6255 (when cleanup
6256 (let ((cwin (selected-window)) win beg end)
6257 (when (setq win (get-buffer-window "*Occur*"))
6258 (select-window win))
6259 (goto-char (point-min))
6260 (when (re-search-forward "match[a-z]+" nil t)
6261 (setq beg (match-end 0))
6262 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6263 (setq end (1- (match-beginning 0)))))
6264 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
6265 (goto-char (point-min))
6266 (select-window cwin))))
6267
6268 (defun org-camel-to-words (s)
6269 "Split \"CamelCaseWords\" to (\"Camel \" \"Case\" \"Words\")."
6270 (let ((case-fold-search nil)
6271 words)
6272 (while (string-match "[a-z][A-Z]" s)
6273 (push (substring s 0 (1+ (match-beginning 0))) words)
6274 (setq s (substring s (1+ (match-beginning 0)))))
6275 (nreverse (cons s words))))
6276
6277 (defun org-follow-bbdb-link (name)
6278 "Follow a BBDB link to NAME."
6279 (require 'bbdb)
6280 (let ((inhibit-redisplay t))
6281 (catch 'exit
6282 ;; Exact match on name
6283 (bbdb-name (concat "\\`" name "\\'") nil)
6284 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6285 ;; Exact match on name
6286 (bbdb-company (concat "\\`" name "\\'") nil)
6287 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6288 ;; Partial match on name
6289 (bbdb-name name nil)
6290 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6291 ;; Partial match on company
6292 (bbdb-company name nil)
6293 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6294 ;; General match including network address and notes
6295 (bbdb name nil)
6296 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
6297 (delete-window (get-buffer-window "*BBDB*"))
6298 (error "No matching BBDB record")))))
6299
6300 (defun org-follow-gnus-link (&optional group article)
6301 "Follow a Gnus link to GROUP and ARTICLE."
6302 (require 'gnus)
6303 (funcall (cdr (assq 'gnus org-link-frame-setup)))
6304 (if group (gnus-fetch-group group))
6305 (if article
6306 (or (gnus-summary-goto-article article nil 'force)
6307 (if (fboundp 'gnus-summary-insert-cached-articles)
6308 (progn
6309 (gnus-summary-insert-cached-articles)
6310 (gnus-summary-goto-article article nil 'force))
6311 (message "Message could not be found.")))))
6312
6313 (defun org-follow-vm-link (&optional folder article readonly)
6314 "Follow a VM link to FOLDER and ARTICLE."
6315 (require 'vm)
6316 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
6317 ;; ange-ftp or efs or tramp access
6318 (let ((user (or (match-string 1 folder) (user-login-name)))
6319 (host (match-string 2 folder))
6320 (file (match-string 3 folder)))
6321 (cond
6322 ((featurep 'tramp)
6323 ;; use tramp to access the file
6324 (if org-xemacs-p
6325 (setq folder (format "[%s@%s]%s" user host file))
6326 (setq folder (format "/%s@%s:%s" user host file))))
6327 (t
6328 ;; use ange-ftp or efs
6329 (require (if org-xemacs-p 'efs 'ange-ftp))
6330 (setq folder (format "/%s@%s:%s" user host file))))))
6331 (when folder
6332 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
6333 (sit-for 0.1)
6334 (when article
6335 (vm-select-folder-buffer)
6336 (widen)
6337 (let ((case-fold-search t))
6338 (goto-char (point-min))
6339 (if (not (re-search-forward
6340 (concat "^" "message-id: *" (regexp-quote article))))
6341 (error "Could not find the specified message in this folder"))
6342 (vm-isearch-update)
6343 (vm-isearch-narrow)
6344 (vm-beginning-of-message)
6345 (vm-summarize)))))
6346
6347 (defun org-follow-wl-link (folder article)
6348 "Follow a Wanderlust link to FOLDER and ARTICLE."
6349 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
6350 (if article (wl-summary-jump-to-msg-by-message-id article))
6351 (wl-summary-redisplay))
6352
6353 (defun org-follow-rmail-link (folder article)
6354 "Follow an RMAIL link to FOLDER and ARTICLE."
6355 (let (message-number)
6356 (save-excursion
6357 (save-window-excursion
6358 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6359 (setq message-number
6360 (save-restriction
6361 (widen)
6362 (goto-char (point-max))
6363 (if (re-search-backward
6364 (concat "^Message-ID:\\s-+" (regexp-quote
6365 (or article "")))
6366 nil t)
6367 (rmail-what-message))))))
6368 (if message-number
6369 (progn
6370 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6371 (rmail-show-message message-number)
6372 message-number)
6373 (error "Message not found"))))
6374
6375 (defun org-open-file (path &optional in-emacs line search)
6376 "Open the file at PATH.
6377 First, this expands any special file name abbreviations. Then the
6378 configuration variable `org-file-apps' is checked if it contains an
6379 entry for this file type, and if yes, the corresponding command is launched.
6380 If no application is found, Emacs simply visits the file.
6381 With optional argument IN-EMACS, Emacs will visit the file.
6382 Optional LINE specifies a line to go to, optional SEARCH a string to
6383 search for. If LINE or SEARCH is given, the file will always be
6384 openen in emacs.
6385 If the file does not exist, an error is thrown."
6386 (setq in-emacs (or in-emacs line search))
6387 (let* ((file (if (equal path "")
6388 (buffer-file-name)
6389 (convert-standard-filename (org-expand-file-name path))))
6390 (dfile (downcase file))
6391 ext cmd apps)
6392 (if (and (not (file-exists-p file))
6393 (not org-open-non-existing-files))
6394 (error "No such file: %s" file))
6395 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
6396 (setq ext (match-string 1 dfile))
6397 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
6398 (setq ext (match-string 1 dfile))))
6399 (setq apps (append org-file-apps (org-default-apps)))
6400 (if in-emacs
6401 (setq cmd 'emacs)
6402 (setq cmd (or (cdr (assoc ext apps))
6403 (cdr (assoc t apps)))))
6404 (cond
6405 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
6406 (setq cmd (format cmd (concat "\"" file "\"")))
6407 (save-window-excursion
6408 (shell-command (concat cmd " & &"))))
6409 ((or (stringp cmd)
6410 (eq cmd 'emacs))
6411 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
6412 (funcall (cdr (assq 'file org-link-frame-setup)) file))
6413 (if line (goto-line line)
6414 (if search (org-link-search search))))
6415 ((consp cmd)
6416 (eval cmd))
6417 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
6418
6419 (defun org-default-apps ()
6420 "Return the default applications for this operating system."
6421 (cond
6422 ((eq system-type 'darwin)
6423 org-file-apps-defaults-macosx)
6424 ((eq system-type 'windows-nt)
6425 org-file-apps-defaults-windowsnt)
6426 (t org-file-apps-defaults-gnu)))
6427
6428 (defun org-expand-file-name (path)
6429 "Replace special path abbreviations and expand the file name."
6430 (expand-file-name path))
6431
6432
6433 (defvar org-insert-link-history nil
6434 "Minibuffer history for links inserted with `org-insert-link'.")
6435
6436 (defvar org-stored-links nil
6437 "Contains the links stored with `org-store-link'.")
6438
6439 ;;;###autoload
6440 (defun org-store-link (arg)
6441 "\\<org-mode-map>Store an org-link to the current location.
6442 This link can later be inserted into an org-buffer with
6443 \\[org-insert-link].
6444 For some link types, a prefix arg is interpreted:
6445 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6446 For file links, arg negates `org-context-in-file-links'."
6447 (interactive "P")
6448 (let (link cpltxt)
6449 (cond
6450
6451 ((eq major-mode 'bbdb-mode)
6452 (setq cpltxt (concat
6453 "bbdb:"
6454 (or (bbdb-record-name (bbdb-current-record))
6455 (bbdb-record-company (bbdb-current-record))))
6456 link (org-make-link cpltxt)))
6457
6458 ((eq major-mode 'calendar-mode)
6459 (let ((cd (calendar-cursor-to-date)))
6460 (setq link
6461 (format-time-string
6462 (car org-time-stamp-formats)
6463 (apply 'encode-time
6464 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6465 nil nil nil))))))
6466
6467 ((or (eq major-mode 'vm-summary-mode)
6468 (eq major-mode 'vm-presentation-mode))
6469 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
6470 (vm-follow-summary-cursor)
6471 (save-excursion
6472 (vm-select-folder-buffer)
6473 (let* ((message (car vm-message-pointer))
6474 (folder (buffer-file-name))
6475 (subject (vm-su-subject message))
6476 (author (vm-su-full-name message))
6477 (message-id (vm-su-message-id message)))
6478 (setq folder (abbreviate-file-name folder))
6479 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
6480 folder)
6481 (setq folder (replace-match "" t t folder)))
6482 (setq cpltxt (concat author " on: " subject))
6483 (setq link (concat cpltxt "\n "
6484 (org-make-link
6485 "vm:" folder "#" message-id))))))
6486
6487 ((eq major-mode 'wl-summary-mode)
6488 (let* ((msgnum (wl-summary-message-number))
6489 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
6490 msgnum 'message-id))
6491 (wl-message-entity (elmo-msgdb-overview-get-entity
6492 msgnum (wl-summary-buffer-msgdb)))
6493 (author (wl-summary-line-from)) ; FIXME: how to get author name?
6494 (subject "???")) ; FIXME: How to get subject of email?
6495 (setq cpltxt (concat author " on: " subject))
6496 (setq link (concat cpltxt "\n "
6497 (org-make-link
6498 "wl:" wl-summary-buffer-folder-name
6499 "#" message-id)))))
6500
6501 ((eq major-mode 'rmail-mode)
6502 (save-excursion
6503 (save-restriction
6504 (rmail-narrow-to-non-pruned-header)
6505 (let ((folder (buffer-file-name))
6506 (message-id (mail-fetch-field "message-id"))
6507 (author (mail-fetch-field "from"))
6508 (subject (mail-fetch-field "subject")))
6509 (setq cpltxt (concat author " on: " subject))
6510 (setq link (concat cpltxt "\n "
6511 (org-make-link
6512 "rmail:" folder "#" message-id)))))))
6513
6514 ((eq major-mode 'gnus-group-mode)
6515 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
6516 (gnus-group-group-name)) ; version
6517 ((fboundp 'gnus-group-name)
6518 (gnus-group-name))
6519 (t "???"))))
6520 (setq cpltxt (concat
6521 (if (org-xor arg org-usenet-links-prefer-google)
6522 "http://groups.google.com/groups?group="
6523 "gnus:")
6524 group)
6525 link (org-make-link cpltxt))))
6526
6527 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
6528 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
6529 (gnus-summary-beginning-of-article)
6530 (let* ((group (car gnus-article-current))
6531 (article (cdr gnus-article-current))
6532 (header (gnus-summary-article-header article))
6533 (author (mail-header-from header))
6534 (message-id (mail-header-id header))
6535 (date (mail-header-date header))
6536 (subject (gnus-summary-subject-string)))
6537 (setq cpltxt (concat author " on: " subject))
6538 (if (org-xor arg org-usenet-links-prefer-google)
6539 (setq link
6540 (concat
6541 cpltxt "\n "
6542 (format "http://groups.google.com/groups?as_umsgid=%s"
6543 (org-fixup-message-id-for-http message-id))))
6544 (setq link (concat cpltxt "\n"
6545 (org-make-link
6546 "gnus:" group
6547 "#" (number-to-string article)))))))
6548
6549 ((eq major-mode 'w3-mode)
6550 (setq cpltxt (url-view-url t)
6551 link (org-make-link cpltxt)))
6552 ((eq major-mode 'w3m-mode)
6553 (setq cpltxt w3m-current-url
6554 link (org-make-link cpltxt)))
6555
6556 ((eq major-mode 'org-mode)
6557 ;; Just link to current headline
6558 (setq cpltxt (concat "file:"
6559 (abbreviate-file-name (buffer-file-name))))
6560 ;; Add a context search string
6561 (when (org-xor org-context-in-file-links arg)
6562 (if (save-excursion
6563 (skip-chars-backward "a-zA-Z<")
6564 (looking-at (concat "<<\\(" org-camel-regexp "\\)>>")))
6565 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6566 (setq cpltxt
6567 (concat cpltxt "::"
6568 (org-make-org-heading-camel
6569 (cond
6570 ((org-on-heading-p) nil)
6571 ((org-region-active-p)
6572 (buffer-substring (region-beginning) (region-end)))
6573 (t (buffer-substring (point-at-bol) (point-at-eol))))
6574 )))))
6575 (setq link (org-make-link cpltxt)))
6576
6577 ((buffer-file-name)
6578 ;; Just link to this file here.
6579 (setq cpltxt (concat "file:"
6580 (abbreviate-file-name (buffer-file-name))))
6581 ;; Add a context string
6582 (when (org-xor org-context-in-file-links arg)
6583 (setq cpltxt
6584 (concat cpltxt "::"
6585 (org-make-org-heading-camel
6586 (if (org-region-active-p)
6587 (buffer-substring (region-beginning) (region-end))
6588 (buffer-substring (point-at-bol) (point-at-eol)))))))
6589 (setq link (org-make-link cpltxt)))
6590
6591 ((interactive-p)
6592 (error "Cannot link to a buffer which is not visiting a file"))
6593
6594 (t (setq link nil)))
6595
6596 (if (and (interactive-p) link)
6597 (progn
6598 (setq org-stored-links
6599 (cons (cons (or cpltxt link) link) org-stored-links))
6600 (message "Stored: %s" (or cpltxt link)))
6601 link)))
6602
6603 (defun org-make-org-heading-camel (&optional string)
6604 "Make a CamelCase string for S or the current headline."
6605 (interactive)
6606 (let ((s (or string (org-get-heading))))
6607 (unless string
6608 ;; We are using a headline, clean up garbage in there.
6609 (if (string-match org-todo-regexp s)
6610 (setq s (replace-match "" t t s)))
6611 (setq s (org-trim s))
6612 (if (string-match (concat "^\\(" org-quote-string "\\|"
6613 org-comment-string "\\)") s)
6614 (setq s (replace-match "" t t s)))
6615 (while (string-match org-ts-regexp s)
6616 (setq s (replace-match "" t t s))))
6617 (while (string-match "[^a-zA-Z_ \t]+" s)
6618 (setq s (replace-match " " t t s)))
6619 (or string (setq s (concat "*" s))) ; Add * for headlines
6620 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
6621
6622 (defun org-make-link (&rest strings)
6623 "Concatenate STRINGS, format resulting string with `org-link-format'."
6624 (format org-link-format (apply 'concat strings)))
6625
6626 (defun org-xor (a b)
6627 "Exclusive or."
6628 (if a (not b) b))
6629
6630 (defun org-get-header (header)
6631 "Find a header field in the current buffer."
6632 (save-excursion
6633 (goto-char (point-min))
6634 (let ((case-fold-search t) s)
6635 (cond
6636 ((eq header 'from)
6637 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6638 (setq s (match-string 1)))
6639 (while (string-match "\"" s)
6640 (setq s (replace-match "" t t s)))
6641 (if (string-match "[<(].*" s)
6642 (setq s (replace-match "" t t s))))
6643 ((eq header 'message-id)
6644 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6645 (setq s (match-string 1))))
6646 ((eq header 'subject)
6647 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6648 (setq s (match-string 1)))))
6649 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6650 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6651 s)))
6652
6653
6654 (defun org-fixup-message-id-for-http (s)
6655 "Replace special characters in a message id, so it can be used in an http query."
6656 (while (string-match "<" s)
6657 (setq s (replace-match "%3C" t t s)))
6658 (while (string-match ">" s)
6659 (setq s (replace-match "%3E" t t s)))
6660 (while (string-match "@" s)
6661 (setq s (replace-match "%40" t t s)))
6662 s)
6663
6664 (defun org-insert-link (&optional complete-file)
6665 "Insert a link. At the prompt, enter the link.
6666
6667 Completion can be used to select a link previously stored with
6668 `org-store-link'. When the empty string is entered (i.e. if you just
6669 press RET at the prompt), the link defaults to the most recently
6670 stored link. As SPC triggers completion in the minibuffer, you need to
6671 use M-SPC or C-q SPC to force the insertion of a space character.
6672
6673 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
6674 selected using completion. The path to the file will be relative to
6675 the current directory if the file is in the current directory or a
6676 subdirectory. Otherwise, the link will be the absolute path as
6677 completed in the minibuffer (i.e. normally ~/path/to/file).
6678
6679 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
6680 is in the current directory or below."
6681 (interactive "P")
6682 (let ((link (if complete-file
6683 (read-file-name "File: ")
6684 (completing-read
6685 "Link: " org-stored-links nil nil nil
6686 org-insert-link-history
6687 (or (car (car org-stored-links))))))
6688 linktxt matched)
6689 (if (or (not link) (equal link ""))
6690 (error "No links available"))
6691 (if complete-file
6692 (let ((pwd (file-name-as-directory (expand-file-name "."))))
6693 (cond
6694 ((equal complete-file '(16))
6695 (insert
6696 (org-make-link
6697 "file:" (abbreviate-file-name (expand-file-name link)))))
6698 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6699 (expand-file-name link))
6700 (insert
6701 (org-make-link
6702 "file:" (match-string 1 (expand-file-name link)))))
6703 (t (insert (org-make-link "file:" link)))))
6704 (setq linktxt (cdr (assoc link org-stored-links)))
6705 (if (not org-keep-stored-link-after-insertion)
6706 (setq org-stored-links (delq (assoc link org-stored-links)
6707 org-stored-links)))
6708 (if (not linktxt) (setq link (org-make-link link)))
6709 (setq link (or linktxt link))
6710 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
6711 (let* ((path (match-string 1 link))
6712 (case-fold-search nil)
6713 (search (match-string 2 link)))
6714 (when (save-match-data
6715 (equal (file-truename (buffer-file-name))
6716 (file-truename path)))
6717 (if (save-match-data
6718 (string-match (concat "^" org-camel-regexp "$") search))
6719 (setq link (replace-match search t t link)
6720 matched t)
6721 (setq link (replace-match (concat "<file:::" search ">")
6722 t t link))))))
6723 (let ((lines (org-split-string link "\n")))
6724 (insert (car lines))
6725 (setq matched (or matched (string-match org-link-regexp (car lines))))
6726 (setq lines (cdr lines))
6727 (while lines
6728 (insert "\n")
6729 (if (save-excursion
6730 (beginning-of-line 0)
6731 (looking-at "[ \t]+\\S-"))
6732 (indent-relative))
6733 (setq matched (or matched
6734 (string-match org-link-regexp (car lines))))
6735 (insert (car lines))
6736 (setq lines (cdr lines))))
6737 (unless matched
6738 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
6739
6740 ;;; Hooks for remember.el
6741 ;;;###autoload
6742 (defun org-remember-annotation ()
6743 "Return a link to the current location as an annotation for remember.el.
6744 If you are using Org-mode files as target for data storage with
6745 remember.el, then the annotations should include a link compatible with the
6746 conventions in Org-mode. This function returns such a link."
6747 (org-store-link nil))
6748
6749 (defconst org-remember-help
6750 "Select a destination location for the note.
6751 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
6752 RET at beg-of-buf -> Append to file as level 2 headline
6753 RET on headline -> Store as sublevel entry to current headline
6754 <left>/<right> -> before/after current headline, same headings level")
6755
6756 ;;;###autoload
6757 (defun org-remember-handler ()
6758 "Store stuff from remember.el into an org file.
6759 First prompts for an org file. If the user just presses return, the value
6760 of `org-default-notes-file' is used.
6761 Then the command offers the headings tree of the selected file in order to
6762 file the text at a specific location.
6763 You can either immediately press RET to get the note appended to the
6764 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
6765 find a better place. Then press RET or <left> or <right> in insert the note.
6766
6767 Key Cursor position Note gets inserted
6768 -----------------------------------------------------------------------------
6769 RET buffer-start as level 2 heading at end of file
6770 RET on headline as sublevel of the heading at cursor
6771 RET no heading at cursor position, level taken from context.
6772 Or use prefix arg to specify level manually.
6773 <left> on headline as same level, before current heading
6774 <right> on headline as same level, after current heading
6775
6776 So the fastest way to store the note is to press RET RET to append it to
6777 the default file. This way your current train of thought is not
6778 interrupted, in accordance with the principles of remember.el. But with
6779 little extra effort, you can push it directly to the correct location.
6780
6781 Before being stored away, the function ensures that the text has a
6782 headline, i.e. a first line that starts with a \"*\". If not, a headline
6783 is constructed from the current date and some additional data.
6784
6785 If the variable `org-adapt-indentation' is non-nil, the entire text is
6786 also indented so that it starts in the same column as the headline
6787 \(i.e. after the stars).
6788
6789 See also the variable `org-reverse-note-order'."
6790 (catch 'quit
6791 (let* ((txt (buffer-substring (point-min) (point-max)))
6792 (fastp current-prefix-arg)
6793 (file (if fastp org-default-notes-file (org-get-org-file)))
6794 (visiting (find-buffer-visiting file))
6795 (org-startup-with-deadline-check nil)
6796 (org-startup-folded nil)
6797 spos level indent reversed)
6798 ;; Modify text so that it becomes a nice subtree which can be inserted
6799 ;; into an org tree.
6800 (let* ((lines (split-string txt "\n"))
6801 (first (car lines))
6802 (lines (cdr lines)))
6803 (if (string-match "^\\*+" first)
6804 ;; Is already a headline
6805 (setq indent (make-string (- (match-end 0) (match-beginning 0)
6806 -1) ?\ ))
6807 ;; We need to add a headline: Use time and first buffer line
6808 (setq lines (cons first lines)
6809 first (concat "* " (current-time-string)
6810 " (" (remember-buffer-desc) ")")
6811 indent " "))
6812 (if org-adapt-indentation
6813 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
6814 (setq txt (concat first "\n"
6815 (mapconcat 'identity lines "\n"))))
6816 ;; Find the file
6817 (if (not visiting)
6818 (find-file-noselect file))
6819 (with-current-buffer (get-file-buffer file)
6820 (setq reversed (org-notes-order-reversed-p))
6821 (save-excursion
6822 (save-restriction
6823 (widen)
6824 ;; Ask the User for a location
6825 (setq spos (if fastp 1 (org-get-location
6826 (current-buffer)
6827 org-remember-help)))
6828 (if (not spos) (throw 'quit nil)) ; return nil to show we did
6829 ; not handle this note
6830 (goto-char spos)
6831 (cond ((bobp)
6832 ;; Put it at the start or end, as level 2
6833 (save-restriction
6834 (widen)
6835 (goto-char (if reversed (point-min) (point-max)))
6836 (if (not (bolp)) (newline))
6837 (org-paste-subtree (or current-prefix-arg 2) txt)))
6838 ((and (org-on-heading-p nil) (not current-prefix-arg))
6839 ;; Put it below this entry, at the beg/end of the subtree
6840 (org-back-to-heading)
6841 (setq level (outline-level))
6842 (if reversed
6843 (outline-end-of-heading)
6844 (outline-end-of-subtree))
6845 (if (not (bolp)) (newline))
6846 (beginning-of-line 1)
6847 (org-paste-subtree (1+ level) txt))
6848 (t
6849 ;; Put it right there, with automatic level determined by
6850 ;; org-paste-subtree or from prefix arg
6851 (org-paste-subtree current-prefix-arg txt)))
6852 (when remember-save-after-remembering
6853 (save-buffer)
6854 (if (not visiting) (kill-buffer (current-buffer)))))))))
6855 t) ;; return t to indicate that we took care of this note.
6856
6857 (defun org-get-org-file ()
6858 "Read a filename, with default directory `org-directory'."
6859 (let ((default (or org-default-notes-file remember-data-file)))
6860 (read-file-name (format "File name [%s]: " default)
6861 (file-name-as-directory org-directory)
6862 default)))
6863
6864 (defun org-notes-order-reversed-p ()
6865 "Check if the current file should receive notes in reversed order."
6866 (cond
6867 ((not org-reverse-note-order) nil)
6868 ((eq t org-reverse-note-order) t)
6869 ((not (listp org-reverse-note-order)) nil)
6870 (t (catch 'exit
6871 (let ((all org-reverse-note-order)
6872 entry)
6873 (while (setq entry (pop all))
6874 (if (string-match (car entry) (buffer-file-name))
6875 (throw 'exit (cdr entry))))
6876 nil)))))
6877
6878 ;;; Tables
6879
6880 ;; Watch out: Here we are talking about two different kind of tables.
6881 ;; Most of the code is for the tables created with the Org-mode table editor.
6882 ;; Sometimes, we talk about tables created and edited with the table.el
6883 ;; Emacs package. We call the former org-type tables, and the latter
6884 ;; table.el-type tables.
6885
6886
6887 (defun org-before-change-function (beg end)
6888 "Every change indicates that a table might need an update."
6889 (setq org-table-may-need-update t))
6890
6891 (defconst org-table-line-regexp "^[ \t]*|"
6892 "Detects an org-type table line.")
6893 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
6894 "Detects an org-type table line.")
6895 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
6896 "Detects a table line marked for automatic recalculation.")
6897 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
6898 "Detects a table line marked for automatic recalculation.")
6899 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
6900 "Detects a table line marked for automatic recalculation.")
6901 (defconst org-table-hline-regexp "^[ \t]*|-"
6902 "Detects an org-type table hline.")
6903 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
6904 "Detects a table-type table hline.")
6905 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
6906 "Detects an org-type or table-type table.")
6907 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
6908 "Searching from within a table (any type) this finds the first line
6909 outside the table.")
6910 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
6911 "Searching from within a table (any type) this finds the first line
6912 outside the table.")
6913
6914 (defun org-table-create-with-table.el ()
6915 "Use the table.el package to insert a new table.
6916 If there is already a table at point, convert between Org-mode tables
6917 and table.el tables."
6918 (interactive)
6919 (require 'table)
6920 (cond
6921 ((org-at-table.el-p)
6922 (if (y-or-n-p "Convert table to Org-mode table? ")
6923 (org-table-convert)))
6924 ((org-at-table-p)
6925 (if (y-or-n-p "Convert table to table.el table? ")
6926 (org-table-convert)))
6927 (t (call-interactively 'table-insert))))
6928
6929 (defun org-table-create (&optional size)
6930 "Query for a size and insert a table skeleton.
6931 SIZE is a string Columns x Rows like for example \"3x2\"."
6932 (interactive "P")
6933 (unless size
6934 (setq size (read-string
6935 (concat "Table size Columns x Rows [e.g. "
6936 org-table-default-size "]: ")
6937 "" nil org-table-default-size)))
6938
6939 (let* ((pos (point))
6940 (indent (make-string (current-column) ?\ ))
6941 (split (org-split-string size " *x *"))
6942 (rows (string-to-number (nth 1 split)))
6943 (columns (string-to-number (car split)))
6944 (line (concat (apply 'concat indent "|" (make-list columns " |"))
6945 "\n")))
6946 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
6947 (point-at-bol) (point)))
6948 (beginning-of-line 1)
6949 (newline))
6950 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
6951 (dotimes (i rows) (insert line))
6952 (goto-char pos)
6953 (if (> rows 1)
6954 ;; Insert a hline after the first row.
6955 (progn
6956 (end-of-line 1)
6957 (insert "\n|-")
6958 (goto-char pos)))
6959 (org-table-align)))
6960
6961 (defun org-table-convert-region (beg0 end0 nspace)
6962 "Convert region to a table.
6963 The region goes from BEG0 to END0, but these borders will be moved
6964 slightly, to make sure a beginning of line in the first line is included.
6965 When NSPACE is non-nil, it indicates the minimum number of spaces that
6966 separate columns (default: just one space)"
6967 (let* ((beg (min beg0 end0))
6968 (end (max beg0 end0))
6969 (tabsep t)
6970 re)
6971 (goto-char beg)
6972 (beginning-of-line 1)
6973 (setq beg (move-marker (make-marker) (point)))
6974 (goto-char end)
6975 (if (bolp) (backward-char 1) (end-of-line 1))
6976 (setq end (move-marker (make-marker) (point)))
6977 ;; Lets see if this is tab-separated material. If every nonempty line
6978 ;; contains a tab, we will assume that it is tab-separated material
6979 (if nspace
6980 (setq tabsep nil)
6981 (goto-char beg)
6982 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
6983 (if nspace (setq tabsep nil))
6984 (if tabsep
6985 (setq re "^\\|\t")
6986 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
6987 (max 1 (prefix-numeric-value nspace)))))
6988 (goto-char beg)
6989 (while (re-search-forward re end t)
6990 (replace-match "|" t t))
6991 (goto-char beg)
6992 (insert " ")
6993 (org-table-align)))
6994
6995 (defun org-table-import (file arg)
6996 "Import FILE as a table.
6997 The file is assumed to be tab-separated. Such files can be produced by most
6998 spreadsheet and database applications. If no tabs (at least one per line)
6999 are found, lines will be split on whitespace into fields."
7000 (interactive "f\nP")
7001 (or (bolp) (newline))
7002 (let ((beg (point))
7003 (pm (point-max)))
7004 (insert-file-contents file)
7005 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7006
7007 (defun org-table-export ()
7008 "Export table as a tab-separated file.
7009 Such a file can be imported into a spreadsheet program like Excel."
7010 (interactive)
7011 (let* ((beg (org-table-begin))
7012 (end (org-table-end))
7013 (table (buffer-substring beg end))
7014 (file (read-file-name "Export table to: "))
7015 buf)
7016 (unless (or (not (file-exists-p file))
7017 (y-or-n-p (format "Overwrite file %s? " file)))
7018 (error "Abort"))
7019 (with-current-buffer (find-file-noselect file)
7020 (setq buf (current-buffer))
7021 (erase-buffer)
7022 (fundamental-mode)
7023 (insert table)
7024 (goto-char (point-min))
7025 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7026 (replace-match "" t t)
7027 (end-of-line 1))
7028 (goto-char (point-min))
7029 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7030 (replace-match "" t t)
7031 (goto-char (min (1+ (point)) (point-max))))
7032 (goto-char (point-min))
7033 (while (re-search-forward "^-[-+]*$" nil t)
7034 (replace-match "")
7035 (if (looking-at "\n")
7036 (delete-char 1)))
7037 (goto-char (point-min))
7038 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7039 (replace-match "\t" t t))
7040 (save-buffer))
7041 (kill-buffer buf)))
7042
7043 (defvar org-table-aligned-begin-marker (make-marker)
7044 "Marker at the beginning of the table last aligned.
7045 Used to check if cursor still is in that table, to minimize realignment.")
7046 (defvar org-table-aligned-end-marker (make-marker)
7047 "Marker at the end of the table last aligned.
7048 Used to check if cursor still is in that table, to minimize realignment.")
7049 (defvar org-table-last-alignment nil
7050 "List of flags for flushright alignment, from the last re-alignment.
7051 This is being used to correctly align a single field after TAB or RET.")
7052 ;; FIXME: The following is currently not used.
7053 (defvar org-table-last-column-widths nil
7054 "List of max width of fields in each column.
7055 This is being used to correctly align a single field after TAB or RET.")
7056
7057 (defvar org-last-recalc-line nil)
7058
7059 (defun org-table-align ()
7060 "Align the table at point by aligning all vertical bars."
7061 (interactive)
7062 ;; (message "align") (sit-for 2)
7063 (let* (
7064 ;; Limits of table
7065 (beg (org-table-begin))
7066 (end (org-table-end))
7067 ;; Current cursor position
7068 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7069 (colpos (org-table-current-column))
7070 (winstart (window-start))
7071 text lines (new "") lengths l typenums ty fields maxfields i
7072 column
7073 (indent "") cnt frac
7074 rfmt hfmt
7075 (spaces (if (org-in-invisibility-spec-p '(org-table))
7076 org-table-spaces-around-invisible-separators
7077 org-table-spaces-around-separators))
7078 (sp1 (car spaces))
7079 (sp2 (cdr spaces))
7080 (rfmt1 (concat
7081 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7082 (hfmt1 (concat
7083 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7084 emptystrings)
7085 (untabify beg end)
7086 ;; (message "Aligning table...")
7087 ;; Get the rows
7088 (setq lines (org-split-string
7089 (buffer-substring-no-properties beg end) "\n"))
7090 ;; Store the indentation of the first line
7091 (if (string-match "^ *" (car lines))
7092 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7093 ;; Mark the hlines
7094 (setq lines (mapcar (lambda (l)
7095 (if (string-match "^ *|-" l)
7096 nil
7097 (if (string-match "[ \t]+$" l)
7098 (substring l 0 (match-beginning 0))
7099 l)))
7100 lines))
7101 ;; Get the data fields
7102 (setq fields (mapcar
7103 (lambda (l)
7104 (org-split-string l " *| *"))
7105 (delq nil (copy-sequence lines))))
7106 ;; How many fields in the longest line?
7107 (condition-case nil
7108 (setq maxfields (apply 'max (mapcar 'length fields)))
7109 (error
7110 (kill-region beg end)
7111 (org-table-create org-table-default-size)
7112 (error "Empty table - created default table")))
7113 ;; A list of empty string to fill any short rows on output
7114 (setq emptystrings (make-list maxfields ""))
7115 ;; Get the maximum length of a field and the most common datatype
7116 ;; for each column
7117 (setq i -1)
7118 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7119 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7120 ;; maximum length
7121 (push (apply 'max 1 (mapcar 'length column)) lengths)
7122 ;; compute the fraction stepwise, ignoring empty fields
7123 (setq cnt 0 frac 0.0)
7124 (mapcar
7125 (lambda (x)
7126 (if (equal x "")
7127 nil
7128 (setq frac ( / (+ (* frac cnt)
7129 (if (string-match org-table-number-regexp x) 1 0))
7130 (setq cnt (1+ cnt))))))
7131 column)
7132 (push (>= frac org-table-number-fraction) typenums))
7133 (setq lengths (nreverse lengths)
7134 typenums (nreverse typenums))
7135 (setq org-table-last-alignment typenums
7136 org-table-last-column-widths lengths)
7137 ;; Compute the formats needed for output of the table
7138 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7139 (while (setq l (pop lengths))
7140 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7141 (setq rfmt (concat rfmt (format rfmt1 ty l))
7142 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7143 (setq rfmt (concat rfmt "\n")
7144 hfmt (concat (substring hfmt 0 -1) "|\n"))
7145 ;; Produce the new table
7146 ;;(while lines
7147 ;; (setq l (pop lines))
7148 ;; (if l
7149 ;; (setq new (concat new (apply 'format rfmt
7150 ;; (append (pop fields) emptystrings))))
7151 ;; (setq new (concat new hfmt))))
7152 (setq new (mapconcat
7153 (lambda (l)
7154 (if l (apply 'format rfmt
7155 (append (pop fields) emptystrings))
7156 hfmt))
7157 lines ""))
7158 ;; Replace the old one
7159 (delete-region beg end)
7160 (move-marker end nil)
7161 (move-marker org-table-aligned-begin-marker (point))
7162 (insert new)
7163 (move-marker org-table-aligned-end-marker (point))
7164 ;; Try to move to the old location (approximately)
7165 (goto-line linepos)
7166 (set-window-start (selected-window) winstart 'noforce)
7167 (org-table-goto-column colpos)
7168 (setq org-table-may-need-update nil)
7169 (if (org-in-invisibility-spec-p '(org-table))
7170 (org-table-add-invisible-to-vertical-lines))
7171 ))
7172
7173 (defun org-table-begin (&optional table-type)
7174 "Find the beginning of the table and return its position.
7175 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7176 (save-excursion
7177 (if (not (re-search-backward
7178 (if table-type org-table-any-border-regexp
7179 org-table-border-regexp)
7180 nil t))
7181 (error "Can't find beginning of table")
7182 (goto-char (match-beginning 0))
7183 (beginning-of-line 2)
7184 (point))))
7185
7186 (defun org-table-end (&optional table-type)
7187 "Find the end of the table and return its position.
7188 With argument TABLE-TYPE, go to the end of a table.el-type table."
7189 (save-excursion
7190 (if (not (re-search-forward
7191 (if table-type org-table-any-border-regexp
7192 org-table-border-regexp)
7193 nil t))
7194 (goto-char (point-max))
7195 (goto-char (match-beginning 0)))
7196 (point-marker)))
7197
7198 (defun org-table-justify-field-maybe (&optional new)
7199 "Justify the current field, text to left, number to right.
7200 Optional argument NEW may specify text to replace the current field content."
7201 (cond
7202 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7203 ((org-at-table-hline-p)
7204 ;; FIXME: I used to enforce realign here, but I think this is not needed.
7205 ;; (setq org-table-may-need-update t)
7206 )
7207 ((and (not new)
7208 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7209 (current-buffer)))
7210 (< (point) org-table-aligned-begin-marker)
7211 (>= (point) org-table-aligned-end-marker)))
7212 ;; This is not the same table, force a full re-align
7213 (setq org-table-may-need-update t))
7214 (t ;; realign the current field, based on previous full realign
7215 (let* ((pos (point)) s
7216 (col (org-table-current-column))
7217 (num (nth (1- col) org-table-last-alignment))
7218 l f n o e)
7219 (when (> col 0)
7220 (skip-chars-backward "^|\n")
7221 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7222 (progn
7223 (setq s (match-string 1)
7224 o (match-string 0)
7225 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7226 e (not (= (match-beginning 2) (match-end 2))))
7227 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7228 l (if e "|" (setq org-table-may-need-update t) ""))
7229 n (format f s t t))
7230 (if new
7231 (if (<= (length new) l)
7232 (setq n (format f new t t)) ;; FIXME: why t t?????
7233 (setq n (concat new "|") org-table-may-need-update t)))
7234 (or (equal n o)
7235 (let (org-table-may-need-update)
7236 (replace-match n))))
7237 (setq org-table-may-need-update t))
7238 (goto-char pos))))))
7239
7240 (defun org-table-next-field ()
7241 "Go to the next field in the current table, creating new lines as needed.
7242 Before doing so, re-align the table if necessary."
7243 (interactive)
7244 (org-table-maybe-eval-formula)
7245 (org-table-maybe-recalculate-line)
7246 (if (and org-table-automatic-realign
7247 org-table-may-need-update)
7248 (org-table-align))
7249 (let ((end (org-table-end)))
7250 (if (org-at-table-hline-p)
7251 (end-of-line 1))
7252 (condition-case nil
7253 (progn
7254 (re-search-forward "|" end)
7255 (if (looking-at "[ \t]*$")
7256 (re-search-forward "|" end))
7257 (if (and (looking-at "-")
7258 org-table-tab-jumps-over-hlines
7259 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7260 (goto-char (match-beginning 1)))
7261 (if (looking-at "-")
7262 (progn
7263 (beginning-of-line 0)
7264 (org-table-insert-row 'below))
7265 (if (looking-at " ") (forward-char 1))))
7266 (error
7267 (org-table-insert-row 'below)))))
7268
7269 (defun org-table-previous-field ()
7270 "Go to the previous field in the table.
7271 Before doing so, re-align the table if necessary."
7272 (interactive)
7273 (org-table-justify-field-maybe)
7274 (org-table-maybe-recalculate-line)
7275 (if (and org-table-automatic-realign
7276 org-table-may-need-update)
7277 (org-table-align))
7278 (if (org-at-table-hline-p)
7279 (end-of-line 1))
7280 (re-search-backward "|" (org-table-begin))
7281 (re-search-backward "|" (org-table-begin))
7282 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7283 (re-search-backward "|" (org-table-begin)))
7284 (if (looking-at "| ?")
7285 (goto-char (match-end 0))))
7286
7287 (defun org-table-next-row ()
7288 "Go to the next row (same column) in the current table.
7289 Before doing so, re-align the table if necessary."
7290 (interactive)
7291 (org-table-maybe-eval-formula)
7292 (org-table-maybe-recalculate-line)
7293 (if (or (looking-at "[ \t]*$")
7294 (save-excursion (skip-chars-backward " \t") (bolp)))
7295 (newline)
7296 (if (and org-table-automatic-realign
7297 org-table-may-need-update)
7298 (org-table-align))
7299 (let ((col (org-table-current-column)))
7300 (beginning-of-line 2)
7301 (if (or (not (org-at-table-p))
7302 (org-at-table-hline-p))
7303 (progn
7304 (beginning-of-line 0)
7305 (org-table-insert-row 'below)))
7306 (org-table-goto-column col)
7307 (skip-chars-backward "^|\n\r")
7308 (if (looking-at " ") (forward-char 1)))))
7309
7310 (defun org-table-copy-down (n)
7311 "Copy a field down in the current column.
7312 If the field at the cursor is empty, copy into it the content of the nearest
7313 non-empty field above. With argument N, use the Nth non-empty field.
7314 If the current field is not empty, it is copied down to the next row, and
7315 the cursor is moved with it. Therefore, repeating this command causes the
7316 column to be filled row-by-row.
7317 If the variable `org-table-copy-increment' is non-nil and the field is an
7318 integer, it will be incremented while copying."
7319 (interactive "p")
7320 (let* ((colpos (org-table-current-column))
7321 (field (org-table-get-field))
7322 (non-empty (string-match "[^ \t]" field))
7323 (beg (org-table-begin))
7324 txt)
7325 (org-table-check-inside-data-field)
7326 (if non-empty
7327 (progn
7328 (setq txt (org-trim field))
7329 (org-table-next-row)
7330 (org-table-blank-field))
7331 (save-excursion
7332 (setq txt
7333 (catch 'exit
7334 (while (progn (beginning-of-line 1)
7335 (re-search-backward org-table-dataline-regexp
7336 beg t))
7337 (org-table-goto-column colpos t)
7338 (if (and (looking-at
7339 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7340 (= (setq n (1- n)) 0))
7341 (throw 'exit (match-string 1))))))))
7342 (if txt
7343 (progn
7344 (if (and org-table-copy-increment
7345 (string-match "^[0-9]+$" txt))
7346 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7347 (insert txt)
7348 (org-table-maybe-recalculate-line)
7349 (org-table-align))
7350 (error "No non-empty field found"))))
7351
7352 (defun org-table-check-inside-data-field ()
7353 "Is point inside a table data field?
7354 I.e. not on a hline or before the first or after the last column?
7355 This actually throws an error, so it aborts the current command."
7356 (if (or (not (org-at-table-p))
7357 (= (org-table-current-column) 0)
7358 (org-at-table-hline-p)
7359 (looking-at "[ \t]*$"))
7360 (error "Not in table data field")))
7361
7362 (defvar org-table-clip nil
7363 "Clipboard for table regions.")
7364
7365 (defun org-table-blank-field ()
7366 "Blank the current table field or active region."
7367 (interactive)
7368 (org-table-check-inside-data-field)
7369 (if (and (interactive-p) (org-region-active-p))
7370 (let (org-table-clip)
7371 (org-table-cut-region (region-beginning) (region-end)))
7372 (skip-chars-backward "^|")
7373 (backward-char 1)
7374 (if (looking-at "|[^|\n]+")
7375 (let* ((pos (match-beginning 0))
7376 (match (match-string 0))
7377 (len (length match)))
7378 (replace-match (concat "|" (make-string (1- len) ?\ )))
7379 (goto-char (+ 2 pos))
7380 (substring match 1)))))
7381
7382 (defun org-table-get-field (&optional n replace)
7383 "Return the value of the field in column N of current row.
7384 N defaults to current field.
7385 If REPLACE is a string, replace field with this value. The return value
7386 is always the old value."
7387 (and n (org-table-goto-column n))
7388 (skip-chars-backward "^|\n")
7389 (backward-char 1)
7390 (if (looking-at "|[^|\r\n]*")
7391 (let* ((pos (match-beginning 0))
7392 (val (buffer-substring (1+ pos) (match-end 0))))
7393 (if replace
7394 (replace-match (concat "|" replace)))
7395 (goto-char (min (point-at-eol) (+ 2 pos)))
7396 val)
7397 (forward-char 1) ""))
7398
7399 (defun org-table-current-column ()
7400 "Find out which column we are in.
7401 When called interactively, column is also displayed in echo area."
7402 (interactive)
7403 (if (interactive-p) (org-table-check-inside-data-field))
7404 (save-excursion
7405 (let ((cnt 0) (pos (point)))
7406 (beginning-of-line 1)
7407 (while (search-forward "|" pos t)
7408 (setq cnt (1+ cnt)))
7409 (if (interactive-p) (message "This is table column %d" cnt))
7410 cnt)))
7411
7412 (defun org-table-goto-column (n &optional on-delim force)
7413 "Move the cursor to the Nth column in the current table line.
7414 With optional argument ON-DELIM, stop with point before the left delimiter
7415 of the field.
7416 If there are less than N fields, just go to after the last delimiter.
7417 However, when FORCE is non-nil, create new columns if necessary."
7418 (interactive "p")
7419 (let ((pos (point-at-eol)))
7420 (beginning-of-line 1)
7421 (when (> n 0)
7422 (while (and (> (setq n (1- n)) -1)
7423 (or (search-forward "|" pos t)
7424 (and force
7425 (progn (end-of-line 1)
7426 (skip-chars-backward "^|")
7427 (insert " | "))))))
7428 ; (backward-char 2) t)))))
7429 (when (and force (not (looking-at ".*|")))
7430 (save-excursion (end-of-line 1) (insert " | ")))
7431 (if on-delim
7432 (backward-char 1)
7433 (if (looking-at " ") (forward-char 1))))))
7434
7435 (defun org-at-table-p (&optional table-type)
7436 "Return t if the cursor is inside an org-type table.
7437 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7438 (if org-enable-table-editor
7439 (save-excursion
7440 (beginning-of-line 1)
7441 (looking-at (if table-type org-table-any-line-regexp
7442 org-table-line-regexp)))
7443 nil))
7444
7445 (defun org-at-table.el-p ()
7446 "Return t if and only if we are at a table.el table."
7447 (and (org-at-table-p 'any)
7448 (save-excursion
7449 (goto-char (org-table-begin 'any))
7450 (looking-at org-table1-hline-regexp))))
7451
7452 (defun org-table-recognize-table.el ()
7453 "If there is a table.el table nearby, recognize it and move into it."
7454 (if org-table-tab-recognizes-table.el
7455 (if (org-at-table.el-p)
7456 (progn
7457 (beginning-of-line 1)
7458 (if (looking-at org-table-dataline-regexp)
7459 nil
7460 (if (looking-at org-table1-hline-regexp)
7461 (progn
7462 (beginning-of-line 2)
7463 (if (looking-at org-table-any-border-regexp)
7464 (beginning-of-line -1)))))
7465 (if (re-search-forward "|" (org-table-end t) t)
7466 (progn
7467 (require 'table)
7468 (if (table--at-cell-p (point))
7469 t
7470 (message "recognizing table.el table...")
7471 (table-recognize-table)
7472 (message "recognizing table.el table...done")))
7473 (error "This should not happen..."))
7474 t)
7475 nil)
7476 nil))
7477
7478 (defun org-at-table-hline-p ()
7479 "Return t if the cursor is inside a hline in a table."
7480 (if org-enable-table-editor
7481 (save-excursion
7482 (beginning-of-line 1)
7483 (looking-at org-table-hline-regexp))
7484 nil))
7485
7486 (defun org-table-insert-column ()
7487 "Insert a new column into the table."
7488 (interactive)
7489 (if (not (org-at-table-p))
7490 (error "Not at a table"))
7491 (org-table-find-dataline)
7492 (let* ((col (max 1 (org-table-current-column)))
7493 (beg (org-table-begin))
7494 (end (org-table-end))
7495 ;; Current cursor position
7496 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7497 (colpos col))
7498 (goto-char beg)
7499 (while (< (point) end)
7500 (if (org-at-table-hline-p)
7501 nil
7502 (org-table-goto-column col t)
7503 (insert "| "))
7504 (beginning-of-line 2))
7505 (move-marker end nil)
7506 (goto-line linepos)
7507 (org-table-goto-column colpos)
7508 (org-table-align)
7509 (org-table-modify-formulas 'insert col)))
7510
7511 (defun org-table-find-dataline ()
7512 "Find a dataline in the current table, which is needed for column commands."
7513 (if (and (org-at-table-p)
7514 (not (org-at-table-hline-p)))
7515 t
7516 (let ((col (current-column))
7517 (end (org-table-end)))
7518 (move-to-column col)
7519 (while (and (< (point) end)
7520 (or (not (= (current-column) col))
7521 (org-at-table-hline-p)))
7522 (beginning-of-line 2)
7523 (move-to-column col))
7524 (if (and (org-at-table-p)
7525 (not (org-at-table-hline-p)))
7526 t
7527 (error
7528 "Please position cursor in a data line for column operations")))))
7529
7530 (defun org-table-delete-column ()
7531 "Delete a column into the table."
7532 (interactive)
7533 (if (not (org-at-table-p))
7534 (error "Not at a table"))
7535 (org-table-find-dataline)
7536 (org-table-check-inside-data-field)
7537 (let* ((col (org-table-current-column))
7538 (beg (org-table-begin))
7539 (end (org-table-end))
7540 ;; Current cursor position
7541 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7542 (colpos col))
7543 (goto-char beg)
7544 (while (< (point) end)
7545 (if (org-at-table-hline-p)
7546 nil
7547 (org-table-goto-column col t)
7548 (and (looking-at "|[^|\n]+|")
7549 (replace-match "|")))
7550 (beginning-of-line 2))
7551 (move-marker end nil)
7552 (goto-line linepos)
7553 (org-table-goto-column colpos)
7554 (org-table-align)
7555 (org-table-modify-formulas 'remove col)))
7556
7557 (defun org-table-move-column-right ()
7558 "Move column to the right."
7559 (interactive)
7560 (org-table-move-column nil))
7561 (defun org-table-move-column-left ()
7562 "Move column to the left."
7563 (interactive)
7564 (org-table-move-column 'left))
7565
7566 (defun org-table-move-column (&optional left)
7567 "Move the current column to the right. With arg LEFT, move to the left."
7568 (interactive "P")
7569 (if (not (org-at-table-p))
7570 (error "Not at a table"))
7571 (org-table-find-dataline)
7572 (org-table-check-inside-data-field)
7573 (let* ((col (org-table-current-column))
7574 (col1 (if left (1- col) col))
7575 (beg (org-table-begin))
7576 (end (org-table-end))
7577 ;; Current cursor position
7578 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7579 (colpos (if left (1- col) (1+ col))))
7580 (if (and left (= col 1))
7581 (error "Cannot move column further left"))
7582 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
7583 (error "Cannot move column further right"))
7584 (goto-char beg)
7585 (while (< (point) end)
7586 (if (org-at-table-hline-p)
7587 nil
7588 (org-table-goto-column col1 t)
7589 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
7590 (replace-match "|\\2|\\1|")))
7591 (beginning-of-line 2))
7592 (move-marker end nil)
7593 (goto-line linepos)
7594 (org-table-goto-column colpos)
7595 (org-table-align)
7596 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
7597
7598 (defun org-table-move-row-down ()
7599 "move table row down."
7600 (interactive)
7601 (org-table-move-row nil))
7602 (defun org-table-move-row-up ()
7603 "move table row up."
7604 (interactive)
7605 (org-table-move-row 'up))
7606
7607 (defun org-table-move-row (&optional up)
7608 "Move the current table line down. With arg UP, move it up."
7609 (interactive "P")
7610 (let ((col (current-column))
7611 (pos (point))
7612 (tonew (if up 0 2))
7613 txt)
7614 (beginning-of-line tonew)
7615 (if (not (org-at-table-p))
7616 (progn
7617 (goto-char pos)
7618 (error "Cannot move row further")))
7619 (goto-char pos)
7620 (beginning-of-line 1)
7621 (setq pos (point))
7622 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
7623 (delete-region (point) (1+ (point-at-eol)))
7624 (beginning-of-line tonew)
7625 (insert txt)
7626 (beginning-of-line 0)
7627 (move-to-column col)))
7628
7629 (defun org-table-insert-row (&optional arg)
7630 "Insert a new row above the current line into the table.
7631 With prefix ARG, insert below the current line."
7632 (interactive "P")
7633 (if (not (org-at-table-p))
7634 (error "Not at a table"))
7635 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
7636 new)
7637 (if (string-match "^[ \t]*|-" line)
7638 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
7639 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
7640 ;; Fix the first field if necessary
7641 (setq new (concat new))
7642 (if (string-match "^[ \t]*| *[#$] *|" line)
7643 (setq new (replace-match (match-string 0 line) t t new)))
7644 (beginning-of-line (if arg 2 1))
7645 (let (org-table-may-need-update)
7646 (insert-before-markers new)
7647 (insert-before-markers "\n"))
7648 (beginning-of-line 0)
7649 (re-search-forward "| ?" (point-at-eol) t)
7650 (and org-table-may-need-update (org-table-align))))
7651
7652 (defun org-table-insert-hline (&optional arg)
7653 "Insert a horizontal-line below the current line into the table.
7654 With prefix ARG, insert above the current line."
7655 (interactive "P")
7656 (if (not (org-at-table-p))
7657 (error "Not at a table"))
7658 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
7659 (col (current-column))
7660 start)
7661 (if (string-match "^[ \t]*|-" line)
7662 (setq line
7663 (mapcar (lambda (x) (if (member x '(?| ?+))
7664 (prog1 (if start ?+ ?|) (setq start t))
7665 (if start ?- ?\ )))
7666 line))
7667 (setq line
7668 (mapcar (lambda (x) (if (equal x ?|)
7669 (prog1 (if start ?+ ?|) (setq start t))
7670 (if start ?- ?\ )))
7671 line)))
7672 (beginning-of-line (if arg 1 2))
7673 (apply 'insert line)
7674 (if (equal (char-before (point)) ?+)
7675 (progn (backward-delete-char 1) (insert "|")))
7676 (insert "\n")
7677 (beginning-of-line 0)
7678 (move-to-column col)))
7679
7680 (defun org-table-kill-row ()
7681 "Delete the current row or horizontal line from the table."
7682 (interactive)
7683 (if (not (org-at-table-p))
7684 (error "Not at a table"))
7685 (let ((col (current-column)))
7686 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
7687 (if (not (org-at-table-p)) (beginning-of-line 0))
7688 (move-to-column col)))
7689
7690 (defun org-table-sort-lines (beg end numericp)
7691 "Sort table lines in region.
7692 Point and mark define the first and last line to include. Both point and
7693 mark should be in the column that is used for sorting. For example, to
7694 sort according to column 3, put the mark in the first line to sort, in
7695 table column 3. Put point into the last line to be included in the sorting,
7696 also in table column 3. The command will prompt for the sorting method (n for
7697 numerical, a for alphanumeric)."
7698 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
7699 (setq numericp (string-match "[nN]" numericp))
7700 (org-table-align) ;; Just to be safe
7701 (let* (bcol ecol cmp column lns)
7702 (goto-char beg)
7703 (org-table-check-inside-data-field)
7704 (setq column (org-table-current-column)
7705 beg (move-marker (make-marker) (point-at-bol)))
7706 (goto-char end)
7707 (org-table-check-inside-data-field)
7708 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
7709 (untabify beg end)
7710 (goto-char beg)
7711 (org-table-goto-column column)
7712 (skip-chars-backward "^|")
7713 (setq bcol (current-column))
7714 (org-table-goto-column (1+ column))
7715 (skip-chars-backward "^|")
7716 (setq ecol (1- (current-column)))
7717 (setq cmp (if numericp
7718 (lambda (a b) (< (car a) (car b)))
7719 (lambda (a b) (string< (car a) (car b)))))
7720 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
7721 (split-string (buffer-substring beg end) "\n")))
7722 (if numericp
7723 (setq lns (mapcar (lambda(x)
7724 (cons (string-to-number (car x)) (cdr x)))
7725 lns)))
7726 (delete-region beg end)
7727 (move-marker beg nil)
7728 (move-marker end nil)
7729 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
7730 (message "%d lines sorted %s based on column %d"
7731 (length lns)
7732 (if numericp "numerically" "alphabetically") column)))
7733
7734 (defun org-table-cut-region (beg end)
7735 "Copy region in table to the clipboard and blank all relevant fields."
7736 (interactive "r")
7737 (org-table-copy-region beg end 'cut))
7738
7739 (defun org-table-copy-region (beg end &optional cut)
7740 "Copy rectangular region in table to clipboard.
7741 A special clipboard is used which can only be accessed
7742 with `org-table-paste-rectangle'"
7743 (interactive "rP")
7744 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
7745 region cols
7746 (rpl (if cut " " nil)))
7747 (goto-char beg)
7748 (org-table-check-inside-data-field)
7749 (setq l01 (count-lines (point-min) (point))
7750 c01 (org-table-current-column))
7751 (goto-char end)
7752 (org-table-check-inside-data-field)
7753 (setq l02 (count-lines (point-min) (point))
7754 c02 (org-table-current-column))
7755 (setq l1 (min l01 l02) l2 (max l01 l02)
7756 c1 (min c01 c02) c2 (max c01 c02))
7757 (catch 'exit
7758 (while t
7759 (catch 'nextline
7760 (if (> l1 l2) (throw 'exit t))
7761 (goto-line l1)
7762 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
7763 (setq cols nil ic1 c1 ic2 c2)
7764 (while (< ic1 (1+ ic2))
7765 (push (org-table-get-field ic1 rpl) cols)
7766 (setq ic1 (1+ ic1)))
7767 (push (nreverse cols) region)
7768 (setq l1 (1+ l1)))))
7769 (setq org-table-clip (nreverse region))
7770 (if cut (org-table-align))
7771 org-table-clip))
7772
7773 (defun org-table-paste-rectangle ()
7774 "Paste a rectangular region into a table.
7775 The upper right corner ends up in the current field. All involved fields
7776 will be overwritten. If the rectangle does not fit into the present table,
7777 the table is enlarged as needed. The process ignores horizontal separator
7778 lines."
7779 (interactive)
7780 (unless (and org-table-clip (listp org-table-clip))
7781 (error "First cut/copy a region to paste!"))
7782 (org-table-check-inside-data-field)
7783 (let* ((clip org-table-clip)
7784 (line (count-lines (point-min) (point)))
7785 (col (org-table-current-column))
7786 (org-enable-table-editor t)
7787 (org-table-automatic-realign nil)
7788 c cols field)
7789 (while (setq cols (pop clip))
7790 (while (org-at-table-hline-p) (beginning-of-line 2))
7791 (if (not (org-at-table-p))
7792 (progn (end-of-line 0) (org-table-next-field)))
7793 (setq c col)
7794 (while (setq field (pop cols))
7795 (org-table-goto-column c nil 'force)
7796 (org-table-get-field nil field)
7797 (setq c (1+ c)))
7798 (beginning-of-line 2))
7799 (goto-line line)
7800 (org-table-goto-column col)
7801 (org-table-align)))
7802
7803 (defun org-table-convert ()
7804 "Convert from `org-mode' table to table.el and back.
7805 Obviously, this only works within limits. When an Org-mode table is
7806 converted to table.el, all horizontal separator lines get lost, because
7807 table.el uses these as cell boundaries and has no notion of horizontal lines.
7808 A table.el table can be converted to an Org-mode table only if it does not
7809 do row or column spanning. Multiline cells will become multiple cells.
7810 Beware, Org-mode does not test if the table can be successfully converted - it
7811 blindly applies a recipe that works for simple tables."
7812 (interactive)
7813 (require 'table)
7814 (if (org-at-table.el-p)
7815 ;; convert to Org-mode table
7816 (let ((beg (move-marker (make-marker) (org-table-begin t)))
7817 (end (move-marker (make-marker) (org-table-end t))))
7818 (table-unrecognize-region beg end)
7819 (goto-char beg)
7820 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
7821 (replace-match ""))
7822 (goto-char beg))
7823 (if (org-at-table-p)
7824 ;; convert to table.el table
7825 (let ((beg (move-marker (make-marker) (org-table-begin)))
7826 (end (move-marker (make-marker) (org-table-end))))
7827 ;; first, get rid of all horizontal lines
7828 (goto-char beg)
7829 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
7830 (replace-match ""))
7831 ;; insert a hline before first
7832 (goto-char beg)
7833 (org-table-insert-hline 'above)
7834 ;; insert a hline after each line
7835 (while (progn (beginning-of-line 2) (< (point) end))
7836 (org-table-insert-hline))
7837 (goto-char beg)
7838 (setq end (move-marker end (org-table-end)))
7839 ;; replace "+" at beginning and ending of hlines
7840 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
7841 (replace-match "\\1+-"))
7842 (goto-char beg)
7843 (while (re-search-forward "-|[ \t]*$" end t)
7844 (replace-match "-+"))
7845 (goto-char beg)))))
7846
7847 (defun org-table-wrap-region (arg)
7848 "Wrap several fields in a column like a paragraph.
7849 This is useful if you'd like to spread the contents of a field over several
7850 lines, in order to keep the table compact.
7851
7852 If there is an active region, and both point and mark are in the same column,
7853 the text in the column is wrapped to minimum width for the given number of
7854 lines. Generally, this makes the table more compact. A prefix ARG may be
7855 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
7856 formats the selected text to two lines. If the region was longer than 2
7857 lines, the remaining lines remain empty. A negative prefix argument reduces
7858 the current number of lines by that amount. The wrapped text is pasted back
7859 into the table. If you formatted it to more lines than it was before, fields
7860 further down in the table get overwritten - so you might need to make space in
7861 the table first.
7862
7863 If there is no region, the current field is split at the cursor position and
7864 the text fragment to the right of the cursor is prepended to the field one
7865 line down.
7866
7867 If there is no region, but you specify a prefix ARG, the current field gets
7868 blank, and the content is appended to the field above."
7869 (interactive "P")
7870 (org-table-check-inside-data-field)
7871 (if (org-region-active-p)
7872 ;; There is a region: fill as a paragraph
7873 (let ((beg (region-beginning))
7874 nlines)
7875 (org-table-cut-region (region-beginning) (region-end))
7876 (if (> (length (car org-table-clip)) 1)
7877 (error "Region must be limited to single column"))
7878 (setq nlines (if arg
7879 (if (< arg 1)
7880 (+ (length org-table-clip) arg)
7881 arg)
7882 (length org-table-clip)))
7883 (setq org-table-clip
7884 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
7885 nil nlines)))
7886 (goto-char beg)
7887 (org-table-paste-rectangle))
7888 ;; No region, split the current field at point
7889 (if arg
7890 ;; combine with field above
7891 (let ((s (org-table-blank-field))
7892 (col (org-table-current-column)))
7893 (beginning-of-line 0)
7894 (while (org-at-table-hline-p) (beginning-of-line 0))
7895 (org-table-goto-column col)
7896 (skip-chars-forward "^|")
7897 (skip-chars-backward " ")
7898 (insert " " (org-trim s))
7899 (org-table-align))
7900 ;; split field
7901 (when (looking-at "\\([^|]+\\)+|")
7902 (let ((s (match-string 1)))
7903 (replace-match " |")
7904 (goto-char (match-beginning 0))
7905 (org-table-next-row)
7906 (insert (org-trim s) " ")
7907 (org-table-align))))))
7908
7909 (defun org-trim (s)
7910 "Remove whitespace at beginning and end of string."
7911 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
7912 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
7913 s)
7914
7915 (defun org-wrap (string &optional width lines)
7916 "Wrap string to either a number of lines, or a width in characters.
7917 If WIDTH is non-nil, the string is wrapped to that width, however many lines
7918 that costs. If there is a word longer than WIDTH, the text is actually
7919 wrapped to the length of that word.
7920 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
7921 many lines, whatever width that takes.
7922 The return value is a list of lines, without newlines at the end."
7923 (let* ((words (org-split-string string "[ \t\n]+"))
7924 (maxword (apply 'max (mapcar 'length words)))
7925 w ll)
7926 (cond (width
7927 (org-do-wrap words (max maxword width)))
7928 (lines
7929 (setq w maxword)
7930 (setq ll (org-do-wrap words maxword))
7931 (if (<= (length ll) lines)
7932 ll
7933 (setq ll words)
7934 (while (> (length ll) lines)
7935 (setq w (1+ w))
7936 (setq ll (org-do-wrap words w)))
7937 ll))
7938 (t (error "Cannot wrap this")))))
7939
7940
7941 (defun org-do-wrap (words width)
7942 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
7943 (let (lines line)
7944 (while words
7945 (setq line (pop words))
7946 (while (and words (< (+ (length line) (length (car words))) width))
7947 (setq line (concat line " " (pop words))))
7948 (setq lines (push line lines)))
7949 (nreverse lines)))
7950
7951 ;; FIXME: I think I can make this more efficient
7952 (defun org-split-string (string &optional separators)
7953 "Splits STRING into substrings at SEPARATORS.
7954 No empty strings are returned if there are matches at the beginning
7955 and end of string."
7956 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
7957 (start 0)
7958 notfirst
7959 (list nil))
7960 (while (and (string-match rexp string
7961 (if (and notfirst
7962 (= start (match-beginning 0))
7963 (< start (length string)))
7964 (1+ start) start))
7965 (< (match-beginning 0) (length string)))
7966 (setq notfirst t)
7967 (or (eq (match-beginning 0) 0)
7968 (and (eq (match-beginning 0) (match-end 0))
7969 (eq (match-beginning 0) start))
7970 (setq list
7971 (cons (substring string start (match-beginning 0))
7972 list)))
7973 (setq start (match-end 0)))
7974 (or (eq start (length string))
7975 (setq list
7976 (cons (substring string start)
7977 list)))
7978 (nreverse list)))
7979
7980 (defun org-table-add-invisible-to-vertical-lines ()
7981 "Add an `invisible' property to vertical lines of current table."
7982 (interactive)
7983 (let* ((beg (org-table-begin))
7984 (end (org-table-end))
7985 (end1))
7986 (save-excursion
7987 (goto-char beg)
7988 (while (< (point) end)
7989 (setq end1 (point-at-eol))
7990 (if (looking-at org-table-dataline-regexp)
7991 (while (re-search-forward "|" end1 t)
7992 (add-text-properties (1- (point)) (point)
7993 '(invisible org-table)))
7994 (while (re-search-forward "[+|]" end1 t)
7995 (add-text-properties (1- (point)) (point)
7996 '(invisible org-table))))
7997 (beginning-of-line 2)))))
7998
7999 (defun org-table-toggle-vline-visibility (&optional arg)
8000 "Toggle the visibility of table vertical lines.
8001 The effect is immediate and on all tables in the file.
8002 With prefix ARG, make lines invisible when ARG is positive, make lines
8003 visible when ARG is not positive"
8004 (interactive "P")
8005 (let ((action (cond
8006 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
8007 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
8008 (t (if (org-in-invisibility-spec-p '(org-table))
8009 'off
8010 'on)))))
8011 (if (eq action 'off)
8012 (progn
8013 (org-remove-from-invisibility-spec '(org-table))
8014 (org-table-map-tables 'org-table-align)
8015 (message "Vertical table lines visible")
8016 (if (org-at-table-p)
8017 (org-table-align)))
8018 (org-add-to-invisibility-spec '(org-table))
8019 (org-table-map-tables 'org-table-align)
8020 (message "Vertical table lines invisible"))
8021 (redraw-frame (selected-frame))))
8022
8023 (defun org-table-map-tables (function)
8024 "Apply FUNCTION to the start of all tables in the buffer."
8025 (save-excursion
8026 (save-restriction
8027 (widen)
8028 (goto-char (point-min))
8029 (while (re-search-forward org-table-any-line-regexp nil t)
8030 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8031 (beginning-of-line 1)
8032 (if (looking-at org-table-line-regexp)
8033 (save-excursion (funcall function)))
8034 (re-search-forward org-table-any-border-regexp nil 1)))))
8035
8036 (defun org-table-sum (&optional beg end nlast)
8037 "Sum numbers in region of current table column.
8038 The result will be displayed in the echo area, and will be available
8039 as kill to be inserted with \\[yank].
8040
8041 If there is an active region, it is interpreted as a rectangle and all
8042 numbers in that rectangle will be summed. If there is no active
8043 region and point is located in a table column, sum all numbers in that
8044 column.
8045
8046 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8047 numbers are assumed to be times as well (in decimal hours) and the
8048 numbers are added as such.
8049
8050 If NLAST is a number, only the NLAST fields will actually be summed."
8051 (interactive)
8052 (save-excursion
8053 (let (col (timecnt 0) diff h m s org-table-clip)
8054 (cond
8055 ((and beg end)) ; beg and end given explicitly
8056 ((org-region-active-p)
8057 (setq beg (region-beginning) end (region-end)))
8058 (t
8059 (setq col (org-table-current-column))
8060 (goto-char (org-table-begin))
8061 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8062 (error "No table data"))
8063 (org-table-goto-column col)
8064 ;not needed? (skip-chars-backward "^|")
8065 (setq beg (point))
8066 (goto-char (org-table-end))
8067 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8068 (error "No table data"))
8069 (org-table-goto-column col)
8070 ;not needed? (skip-chars-forward "^|")
8071 (setq end (point))))
8072 (let* ((items (apply 'append (org-table-copy-region beg end)))
8073 (items1 (cond ((not nlast) items)
8074 ((>= nlast (length items)) items)
8075 (t (setq items (reverse items))
8076 (setcdr (nthcdr (1- nlast) items) nil)
8077 (nreverse items))))
8078 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8079 items1)))
8080 (res (apply '+ numbers))
8081 (sres (if (= timecnt 0)
8082 (format "%g" res)
8083 (setq diff (* 3600 res)
8084 h (floor (/ diff 3600)) diff (mod diff 3600)
8085 m (floor (/ diff 60)) diff (mod diff 60)
8086 s diff)
8087 (format "%d:%02d:%02d" h m s))))
8088 (kill-new sres)
8089 (if (interactive-p)
8090 (message "%s"
8091 (substitute-command-keys
8092 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8093 (length numbers) sres))))
8094 sres))))
8095
8096 (defun org-table-get-number-for-summing (s)
8097 (let (n)
8098 (if (string-match "^ *|? *" s)
8099 (setq s (replace-match "" nil nil s)))
8100 (if (string-match " *|? *$" s)
8101 (setq s (replace-match "" nil nil s)))
8102 (setq n (string-to-number s))
8103 (cond
8104 ((and (string-match "0" s)
8105 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8106 ((string-match "\\`[ \t]+\\'" s) nil)
8107 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8108 (let ((h (string-to-number (or (match-string 1 s) "0")))
8109 (m (string-to-number (or (match-string 2 s) "0")))
8110 (s (string-to-number (or (match-string 4 s) "0"))))
8111 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
8112 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8113 ((equal n 0) nil)
8114 (t n))))
8115
8116 (defun org-table-get-vertical-vector (desc &optional tbeg col)
8117 "Get a calc vector from a column, accorting to desctiptor DESC.
8118 Optional arguments TBEG and COL can give the beginning of the table and
8119 the current column, to avoid unnecessary parsing."
8120 (save-excursion
8121 (or tbeg (setq tbeg (org-table-begin)))
8122 (or col (setq col (org-table-current-column)))
8123 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
8124 (cond
8125 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
8126 (setq n1 (- (match-end 1) (match-beginning 1)))
8127 (if (match-beginning 3)
8128 (setq n2 (- (match-end 2) (match-beginning 3))))
8129 (setq n (if n2 (max n1 n2) n1))
8130 (setq n1 (if n2 (min n1 n2)))
8131 (setq nn n)
8132 (while (and (> nn 0)
8133 (re-search-backward org-table-hline-regexp tbeg t))
8134 (push (org-current-line) hline-list)
8135 (setq nn (1- nn)))
8136 (setq hline-list (nreverse hline-list))
8137 (goto-line (nth (1- n) hline-list))
8138 (when (re-search-forward org-table-dataline-regexp)
8139 (org-table-goto-column col)
8140 (setq beg (point)))
8141 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
8142 (when (re-search-backward org-table-dataline-regexp)
8143 (org-table-goto-column col)
8144 (setq end (point)))
8145 (setq l (apply 'append (org-table-copy-region beg end)))
8146 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
8147 (if (equal x "") "0" x))
8148 l ",") "]"))
8149 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
8150 (setq n1 (string-to-number (match-string 1 desc))
8151 n2 (string-to-number (match-string 2 desc)))
8152 (beginning-of-line 1)
8153 (save-excursion
8154 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
8155 (org-table-goto-column col)
8156 (setq beg (point))))
8157 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
8158 (org-table-goto-column col)
8159 (setq end (point)))
8160 (setq l (apply 'append (org-table-copy-region beg end)))
8161 (concat "[" (mapconcat
8162 (lambda (x) (setq x (org-trim x))
8163 (if (equal x "") "0" x))
8164 l ",") "]"))
8165 ((string-match "\\([0-9]+\\)" desc)
8166 (beginning-of-line 1)
8167 (when (re-search-backward org-table-dataline-regexp tbeg t
8168 (string-to-number (match-string 0 desc)))
8169 (org-table-goto-column col)
8170 (org-trim (org-table-get-field))))))))
8171
8172 (defvar org-table-formula-history nil)
8173
8174 (defvar org-table-column-names nil
8175 "Alist with column names, derived from the `!' line.")
8176 (defvar org-table-column-name-regexp nil
8177 "Regular expression matching the current column names.")
8178 (defvar org-table-local-parameters nil
8179 "Alist with parameter names, derived from the `$' line.")
8180 (defvar org-table-named-field-locations nil
8181 "Alist with locations of named fields.")
8182
8183 (defun org-table-get-formula (&optional equation named)
8184 "Read a formula from the minibuffer, offer stored formula as default."
8185 (let* ((name (car (rassoc (list (org-current-line)
8186 (org-table-current-column))
8187 org-table-named-field-locations)))
8188 (scol (if named
8189 (if name name
8190 (error "Not in a named field"))
8191 (int-to-string (org-table-current-column))))
8192 (dummy (and name (not named)
8193 (not (y-or-n-p "Replace named-field formula with column equation? " ))
8194 (error "Abort")))
8195 (org-table-may-need-update nil)
8196 (stored-list (org-table-get-stored-formulas))
8197 (stored (cdr (assoc scol stored-list)))
8198 (eq (cond
8199 ((and stored equation (string-match "^ *=? *$" equation))
8200 stored)
8201 ((stringp equation)
8202 equation)
8203 (t (read-string
8204 (format "%s formula $%s=" (if named "Field" "Column") scol)
8205 (or stored "") 'org-table-formula-history
8206 ;stored
8207 ))))
8208 mustsave)
8209 (when (not (string-match "\\S-" eq))
8210 ;; remove formula
8211 (setq stored-list (delq (assoc scol stored-list) stored-list))
8212 (org-table-store-formulas stored-list)
8213 (error "Formula removed"))
8214 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8215 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8216 (if (and name (not named))
8217 ;; We set the column equation, delete the named one.
8218 (setq stored-list (delq (assoc name stored-list) stored-list)
8219 mustsave t))
8220 (if stored
8221 (setcdr (assoc scol stored-list) eq)
8222 (setq stored-list (cons (cons scol eq) stored-list)))
8223 (if (or mustsave (not (equal stored eq)))
8224 (org-table-store-formulas stored-list))
8225 eq))
8226
8227 (defun org-table-store-formulas (alist)
8228 "Store the list of formulas below the current table."
8229 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
8230 (save-excursion
8231 (goto-char (org-table-end))
8232 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
8233 (delete-region (point) (match-end 0)))
8234 (insert "#+TBLFM: "
8235 (mapconcat (lambda (x)
8236 (concat "$" (car x) "=" (cdr x)))
8237 alist "::")
8238 "\n")))
8239
8240 (defun org-table-get-stored-formulas ()
8241 "Return an alist with the t=stored formulas directly after current table."
8242 (interactive)
8243 (let (scol eq eq-alist strings string seen)
8244 (save-excursion
8245 (goto-char (org-table-end))
8246 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8247 (setq strings (org-split-string (match-string 2) " *:: *"))
8248 (while (setq string (pop strings))
8249 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
8250 (setq scol (match-string 1 string)
8251 eq (match-string 2 string)
8252 eq-alist (cons (cons scol eq) eq-alist))
8253 (if (member scol seen)
8254 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8255 (push scol seen))))))
8256 (nreverse eq-alist)))
8257
8258 (defun org-table-modify-formulas (action &rest columns)
8259 "Modify the formulas stored below the current table.
8260 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
8261 expected, for the other action only a single column number is needed."
8262 (let ((list (org-table-get-stored-formulas))
8263 (nmax (length (org-split-string
8264 (buffer-substring (point-at-bol) (point-at-eol))
8265 "|")))
8266 col col1 col2 scol si sc1 sc2)
8267 (cond
8268 ((null list)) ; No action needed if there are no stored formulas
8269 ((eq action 'remove)
8270 (setq col (car columns)
8271 scol (int-to-string col))
8272 (org-table-replace-in-formulas list scol "INVALID")
8273 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
8274 (loop for i from (1+ col) upto nmax by 1 do
8275 (setq si (int-to-string i))
8276 (org-table-replace-in-formulas list si (int-to-string (1- i)))
8277 (if (assoc si list) (setcar (assoc si list)
8278 (int-to-string (1- i))))))
8279 ((eq action 'insert)
8280 (setq col (car columns))
8281 (loop for i from nmax downto col by 1 do
8282 (setq si (int-to-string i))
8283 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
8284 (if (assoc si list) (setcar (assoc si list)
8285 (int-to-string (1+ i))))))
8286 ((eq action 'swap)
8287 (setq col1 (car columns) col2 (nth 1 columns)
8288 sc1 (int-to-string col1) sc2 (int-to-string col2))
8289 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
8290 (org-table-replace-in-formulas list sc1 "ZqZ")
8291 (org-table-replace-in-formulas list sc2 sc1)
8292 (org-table-replace-in-formulas list "ZqZ" sc2)
8293 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
8294 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
8295 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
8296 (t (error "Invalid action in `org-table-modify-formulas'")))
8297 (if list (org-table-store-formulas list))))
8298
8299 (defun org-table-replace-in-formulas (list s1 s2)
8300 (let (elt re s)
8301 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
8302 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
8303 re (concat (regexp-quote s1) "\\>"))
8304 (while (setq elt (pop list))
8305 (setq s (cdr elt))
8306 (while (string-match re s)
8307 (setq s (replace-match s2 t t s)))
8308 (setcdr elt s))))
8309
8310 (defun org-table-get-specials ()
8311 "Get the column nmaes and local parameters for this table."
8312 (save-excursion
8313 (let ((beg (org-table-begin)) (end (org-table-end))
8314 names name fields fields1 field cnt c v line col)
8315 (setq org-table-column-names nil
8316 org-table-local-parameters nil
8317 org-table-named-field-locations nil)
8318 (goto-char beg)
8319 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8320 (setq names (org-split-string (match-string 1) " *| *")
8321 cnt 1)
8322 (while (setq name (pop names))
8323 (setq cnt (1+ cnt))
8324 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8325 (push (cons name (int-to-string cnt)) org-table-column-names))))
8326 (setq org-table-column-names (nreverse org-table-column-names))
8327 (setq org-table-column-name-regexp
8328 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8329 (goto-char beg)
8330 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8331 (setq fields (org-split-string (match-string 1) " *| *"))
8332 (while (setq field (pop fields))
8333 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8334 (push (cons (match-string 1 field) (match-string 2 field))
8335 org-table-local-parameters))))
8336 (goto-char beg)
8337 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8338 (setq c (match-string 1)
8339 fields (org-split-string (match-string 2) " *| *"))
8340 (save-excursion
8341 (beginning-of-line (if (equal c "_") 2 0))
8342 (setq line (org-current-line) col 1)
8343 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8344 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8345 (while (and fields1 (setq field (pop fields)))
8346 (setq v (pop fields1) col (1+ col))
8347 (when (and (stringp field) (stringp v)
8348 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8349 (push (cons field v) org-table-local-parameters)
8350 (push (list field line col) org-table-named-field-locations)))))))
8351
8352 (defun org-this-word ()
8353 ;; Get the current word
8354 (save-excursion
8355 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
8356 (end (progn (skip-chars-forward "^ \t\n") (point))))
8357 (buffer-substring-no-properties beg end))))
8358
8359 (defun org-table-maybe-eval-formula ()
8360 "Check if the current field starts with \"=\" or \":=\".
8361 If yes, store the formula and apply it."
8362 ;; We already know we are in a table. Get field will only return a formula
8363 ;; when appropriate. It might return a separator line, but no problem.
8364 (when org-table-formula-evaluate-inline
8365 (let* ((field (org-trim (or (org-table-get-field) "")))
8366 named eq)
8367 (when (string-match "^:?=\\(.*\\)" field)
8368 (setq named (equal (string-to-char field) ?:)
8369 eq (match-string 1 field))
8370 (if (fboundp 'calc-eval)
8371 (org-table-eval-formula (if named '(4) nil) eq))))))
8372
8373 (defvar org-recalc-commands nil
8374 "List of commands triggering the reccalculation of a line.
8375 Will be filled automatically during use.")
8376
8377 (defvar org-recalc-marks
8378 '((" " . "Unmarked: no special line, no automatic recalculation")
8379 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8380 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8381 ("!" . "Column name definition line. Reference in formula as $name.")
8382 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8383 ("_" . "Names for values in row below this one.")
8384 ("^" . "Names for values in row above this one.")))
8385
8386 (defun org-table-rotate-recalc-marks (&optional newchar)
8387 "Rotate the recalculation mark in the first column.
8388 If in any row, the first field is not consistent with a mark,
8389 insert a new column for the makers.
8390 When there is an active region, change all the lines in the region,
8391 after prompting for the marking character.
8392 After each change, a message will be displayed indication the meaning
8393 of the new mark."
8394 (interactive)
8395 (unless (org-at-table-p) (error "Not at a table"))
8396 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8397 (beg (org-table-begin))
8398 (end (org-table-end))
8399 (l (org-current-line))
8400 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8401 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8402 (have-col
8403 (save-excursion
8404 (goto-char beg)
8405 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8406 (col (org-table-current-column))
8407 (forcenew (car (assoc newchar org-recalc-marks)))
8408 epos new)
8409 (when l1
8410 (message "Change region to what mark? Type # * ! $ or SPC: ")
8411 (setq newchar (char-to-string (read-char-exclusive))
8412 forcenew (car (assoc newchar org-recalc-marks))))
8413 (if (and newchar (not forcenew))
8414 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8415 newchar))
8416 (if l1 (goto-line l1))
8417 (save-excursion
8418 (beginning-of-line 1)
8419 (unless (looking-at org-table-dataline-regexp)
8420 (error "Not at a table data line")))
8421 (unless have-col
8422 (org-table-goto-column 1)
8423 (org-table-insert-column)
8424 (org-table-goto-column (1+ col)))
8425 (setq epos (point-at-eol))
8426 (save-excursion
8427 (beginning-of-line 1)
8428 (org-table-get-field
8429 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8430 (concat " "
8431 (setq new (or forcenew
8432 (cadr (member (match-string 1) marks))))
8433 " ")
8434 " # ")))
8435 (if (and l1 l2)
8436 (progn
8437 (goto-line l1)
8438 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8439 (and (looking-at org-table-dataline-regexp)
8440 (org-table-get-field 1 (concat " " new " "))))
8441 (goto-line l1)))
8442 (if (not (= epos (point-at-eol))) (org-table-align))
8443 (goto-line l)
8444 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8445
8446 (defun org-table-maybe-recalculate-line ()
8447 "Recompute the current line if marked for it, and if we haven't just done it."
8448 (interactive)
8449 (and org-table-allow-automatic-line-recalculation
8450 (not (and (memq last-command org-recalc-commands)
8451 (equal org-last-recalc-line (org-current-line))))
8452 (save-excursion (beginning-of-line 1)
8453 (looking-at org-table-auto-recalculate-regexp))
8454 (fboundp 'calc-eval)
8455 (org-table-recalculate) t))
8456
8457 (defvar org-table-formula-debug nil
8458 "Non-nil means, debug table formulas.
8459 When nil, simply write \"#ERROR\" in corrupted fields.")
8460
8461 (defvar modes)
8462 (defsubst org-set-calc-mode (var &optional value)
8463 (if (stringp var)
8464 (setq var (assoc var '(("D" calc-angle-mode deg)
8465 ("R" calc-angle-mode rad)
8466 ("F" calc-prefer-frac t)
8467 ("S" calc-symbolic-mode t)))
8468 value (nth 2 var) var (nth 1 var)))
8469 (if (memq var modes)
8470 (setcar (cdr (memq var modes)) value)
8471 (cons var (cons value modes)))
8472 modes)
8473
8474 (defun org-table-eval-formula (&optional arg equation
8475 suppress-align suppress-const
8476 suppress-store)
8477 "Replace the table field value at the cursor by the result of a calculation.
8478
8479 This function makes use of Dave Gillespie's calc package, in my view the
8480 most exciting program ever written for GNU Emacs. So you need to have calc
8481 installed in order to use this function.
8482
8483 In a table, this command replaces the value in the current field with the
8484 result of a formula. It also installes the formula as the \"current\" column
8485 formula, by storing it in a special line below the table. When called
8486 with a `C-u' prefix, the current field must ba a named field, and the
8487 formula is installed as valid in only this specific field.
8488
8489 When called, the command first prompts for a formula, which is read in
8490 the minibuffer. Previously entered formulas are available through the
8491 history list, and the last used formula is offered as a default.
8492 These stored formulas are adapted correctly when moving, inserting, or
8493 deleting columns with the corresponding commands.
8494
8495 The formula can be any algebraic expression understood by the calc package.
8496 For details, see the Org-mode manual.
8497
8498 This function can also be called from Lisp programs and offers
8499 additional Arguments: EQUATION can be the formula to apply. If this
8500 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
8501 used to speed-up recursive calls by by-passing unnecessary aligns.
8502 SUPPRESS-CONST suppresses the interpretation of constants in the
8503 formula, assuming that this has been done already outside the fuction.
8504 SUPPRESS-STORE means the formula should not be stored, either because
8505 it is already stored, or because it is a modified equation that should
8506 not overwrite the stored one."
8507 (interactive "P")
8508 (require 'calc)
8509 (org-table-check-inside-data-field)
8510 (org-table-get-specials)
8511 (let* (fields
8512 (ndown (if (integerp arg) arg 1))
8513 (org-table-automatic-realign nil)
8514 (case-fold-search nil)
8515 (down (> ndown 1))
8516 (formula (if (and equation suppress-store)
8517 equation
8518 (org-table-get-formula equation (equal arg '(4)))))
8519 (n0 (org-table-current-column))
8520 (modes (copy-sequence org-calc-default-modes))
8521 n form fmt x ev orig c)
8522 ;; Parse the format string. Since we have a lot of modes, this is
8523 ;; a lot of work. However, I think calc still uses most of the time.
8524 (if (string-match ";" formula)
8525 (let ((tmp (org-split-string formula ";")))
8526 (setq formula (car tmp)
8527 fmt (concat (cdr (assoc "%" org-table-local-parameters))
8528 (nth 1 tmp)))
8529 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
8530 (setq c (string-to-char (match-string 1 fmt))
8531 n (string-to-number (or (match-string 1 fmt) "")))
8532 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
8533 (setq modes (org-set-calc-mode
8534 'calc-float-format
8535 (list (cdr (assoc c '((?n. float) (?f. fix)
8536 (?s. sci) (?e. eng))))
8537 n))))
8538 (setq fmt (replace-match "" t t fmt)))
8539 (while (string-match "[DRFS]" fmt)
8540 (setq modes (org-set-calc-mode (match-string 0 fmt)))
8541 (setq fmt (replace-match "" t t fmt)))
8542 (unless (string-match "\\S-" fmt)
8543 (setq fmt nil))))
8544 (if (and (not suppress-const) org-table-formula-use-constants)
8545 (setq formula (org-table-formula-substitute-names formula)))
8546 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
8547 (while (> ndown 0)
8548 (setq fields (org-split-string
8549 (buffer-substring
8550 (point-at-bol) (point-at-eol)) " *| *"))
8551 (if org-table-formula-numbers-only
8552 (setq fields (mapcar
8553 (lambda (x) (number-to-string (string-to-number x)))
8554 fields)))
8555 (setq ndown (1- ndown))
8556 (setq form (copy-sequence formula))
8557 ;; Insert the references to fields in same row
8558 (while (string-match "\\$\\([0-9]+\\)?" form)
8559 (setq n (if (match-beginning 1)
8560 (string-to-number (match-string 1 form))
8561 n0)
8562 x (nth (1- n) fields))
8563 (unless x (error "Invalid field specifier \"%s\""
8564 (match-string 0 form)))
8565 (if (equal x "") (setq x "0"))
8566 (setq form (replace-match (concat "(" x ")") t t form)))
8567 ;; Insert ranges in current column
8568 (while (string-match "\\&[-I0-9]+" form)
8569 (setq form (replace-match
8570 (save-match-data
8571 (org-table-get-vertical-vector (match-string 0 form)
8572 nil n0))
8573 t t form)))
8574 (setq ev (calc-eval (cons form modes)
8575 (if org-table-formula-numbers-only 'num)))
8576
8577 (when org-table-formula-debug
8578 (with-output-to-temp-buffer "*Help*"
8579 (princ (format "Substitution history of formula
8580 Orig: %s
8581 $xyz-> %s
8582 $1-> %s\n" orig formula form))
8583 (if (listp ev)
8584 (princ (format " %s^\nError: %s"
8585 (make-string (car ev) ?\-) (nth 1 ev)))
8586 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
8587 ev (or fmt "NONE")
8588 (if fmt (format fmt (string-to-number ev)) ev)))))
8589 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
8590 (unless (and (interactive-p) (not ndown))
8591 (unless (let (inhibit-redisplay)
8592 (y-or-n-p "Debugging Formula. Continue to next? "))
8593 (org-table-align)
8594 (error "Abort"))
8595 (delete-window (get-buffer-window "*Help*"))
8596 (message "")))
8597 (if (listp ev) (setq fmt nil ev "#ERROR"))
8598 (org-table-justify-field-maybe
8599 (if fmt (format fmt (string-to-number ev)) ev))
8600 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
8601 (call-interactively 'org-return)
8602 (setq ndown 0)))
8603 (and down (org-table-maybe-recalculate-line))
8604 (or suppress-align (and org-table-may-need-update
8605 (org-table-align)))))
8606
8607 (defun org-table-recalculate (&optional all noalign)
8608 "Recalculate the current table line by applying all stored formulas."
8609 (interactive "P")
8610 (or (memq this-command org-recalc-commands)
8611 (setq org-recalc-commands (cons this-command org-recalc-commands)))
8612 (unless (org-at-table-p) (error "Not at a table"))
8613 (org-table-get-specials)
8614 (let* ((eqlist (sort (org-table-get-stored-formulas)
8615 (lambda (a b) (string< (car a) (car b)))))
8616 (inhibit-redisplay t)
8617 (line-re org-table-dataline-regexp)
8618 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8619 (thiscol (org-table-current-column))
8620 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
8621 ;; Insert constants in all formulas
8622 (setq eqlist
8623 (mapcar (lambda (x)
8624 (setcdr x (org-table-formula-substitute-names (cdr x)))
8625 x)
8626 eqlist))
8627 ;; Split the equation list
8628 (while (setq eq (pop eqlist))
8629 (if (<= (string-to-char (car eq)) ?9)
8630 (push eq eqlnum)
8631 (push eq eqlname)))
8632 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
8633 (if all
8634 (progn
8635 (setq end (move-marker (make-marker) (1+ (org-table-end))))
8636 (goto-char (setq beg (org-table-begin)))
8637 (if (re-search-forward org-table-calculate-mark-regexp end t)
8638 ;; This is a table with marked lines, only compute selected lines
8639 (setq line-re org-table-recalculate-regexp)
8640 ;; Move forward to the first non-header line
8641 (if (and (re-search-forward org-table-dataline-regexp end t)
8642 (re-search-forward org-table-hline-regexp end t)
8643 (re-search-forward org-table-dataline-regexp end t))
8644 (setq beg (match-beginning 0))
8645 nil))) ;; just leave beg where it is
8646 (setq beg (point-at-bol)
8647 end (move-marker (make-marker) (1+ (point-at-eol)))))
8648 (goto-char beg)
8649 (and all (message "Re-applying formulas to full table..."))
8650 (while (re-search-forward line-re end t)
8651 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
8652 ;; Unprotected line, recalculate
8653 (and all (message "Re-applying formulas to full table...(line %d)"
8654 (setq cnt (1+ cnt))))
8655 (setq org-last-recalc-line (org-current-line))
8656 (setq eql eqlnum)
8657 (while (setq entry (pop eql))
8658 (goto-line org-last-recalc-line)
8659 (org-table-goto-column (string-to-number (car entry)) nil 'force)
8660 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
8661 (goto-line thisline)
8662 (org-table-goto-column thiscol)
8663 (or noalign (and org-table-may-need-update (org-table-align))
8664 (and all (message "Re-applying formulas to %d lines...done" cnt)))
8665 ;; Now do the names fields
8666 (while (setq eq (pop eqlname))
8667 (setq name (car eq)
8668 a (assoc name org-table-named-field-locations))
8669 (when a
8670 (message "Re-applying formula to named field: %s" name)
8671 (goto-line (nth 1 a))
8672 (org-table-goto-column (nth 2 a))
8673 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
8674 ;; back to initial position
8675 (goto-line thisline)
8676 (org-table-goto-column thiscol)
8677 (or noalign (and org-table-may-need-update (org-table-align))
8678 (and all (message "Re-applying formulas...done")))))
8679
8680 (defun org-table-formula-substitute-names (f)
8681 "Replace $const with values in string F."
8682 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
8683 ;; First, check for column names
8684 (while (setq start (string-match org-table-column-name-regexp f start))
8685 (setq start (1+ start))
8686 (setq a (assoc (match-string 1 f) org-table-column-names))
8687 (setq f (replace-match (concat "$" (cdr a)) t t f)))
8688 ;; Expand ranges to vectors
8689 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
8690 (setq n1 (string-to-number (match-string 1 f))
8691 n2 (string-to-number (match-string 2 f))
8692 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
8693 s (concat "[($" (number-to-string (1- nn1)) ")"))
8694 (loop for i from nn1 upto nn2 do
8695 (setq s (concat s ",($" (int-to-string i) ")")))
8696 (setq s (concat s "]"))
8697 (if (< n2 n1) (setq s (concat "rev(" s ")")))
8698 (setq f (replace-match s t t f)))
8699 ;; Parameters and constants
8700 (setq start 0)
8701 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
8702 (setq start (1+ start))
8703 (if (setq a (save-match-data
8704 (org-table-get-constant (match-string 1 f))))
8705 (setq f (replace-match (concat "(" a ")") t t f))))
8706 (if org-table-formula-debug
8707 (put-text-property 0 (length f) :orig-formula f1 f))
8708 f))
8709
8710 (defun org-table-get-constant (const)
8711 "Find the value for a parameter or constant in a formula.
8712 Parameters get priority."
8713 (or (cdr (assoc const org-table-local-parameters))
8714 (cdr (assoc const org-table-formula-constants))
8715 (and (fboundp 'constants-get) (constants-get const))
8716 "#UNDEFINED_NAME"))
8717
8718 (defvar org-edit-formulas-map (make-sparse-keymap))
8719 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
8720 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
8721 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
8722
8723 (defvar org-pos)
8724 (defvar org-window-configuration)
8725
8726 (defun org-table-edit-formulas ()
8727 "Edit the formulas of the current table in a separate buffer."
8728 (interactive)
8729 (unless (org-at-table-p)
8730 (error "Not at a table"))
8731 (org-table-get-specials)
8732 (let ((eql (org-table-get-stored-formulas))
8733 (pos (move-marker (make-marker) (point)))
8734 (wc (current-window-configuration))
8735 entry loc s)
8736 (switch-to-buffer-other-window "*Edit Formulas*")
8737 (erase-buffer)
8738 (fundamental-mode)
8739 (set (make-local-variable 'org-pos) pos)
8740 (set (make-local-variable 'org-window-configuration) wc)
8741 (use-local-map org-edit-formulas-map)
8742 (setq s "# Edit formulas and finish with `C-c C-c'.
8743 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
8744 # Use `C-c ?' to get information about $name at point.
8745 # To cancel editing, press `C-c C-q'.\n")
8746 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
8747 (insert s)
8748 (while (setq entry (pop eql))
8749 (when (setq loc (assoc (car entry) org-table-named-field-locations))
8750 (setq s (format "# Named formula, referring to column %d in line %d\n"
8751 (nth 2 loc) (nth 1 loc)))
8752 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
8753 (insert s))
8754 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
8755 (remove-text-properties 0 (length s) '(face nil) s)
8756 (insert s))
8757 (goto-char (point-min))
8758 (message "Edit formulas and finish with `C-c C-c'.")))
8759
8760 (defun org-show-variable ()
8761 "Show the location/value of the $ expression at point."
8762 (interactive)
8763 (let (var (pos org-pos) (win (selected-window)) e)
8764 (save-excursion
8765 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
8766 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
8767 (setq var (match-string 1))
8768 (error "No variable at point")))
8769 (cond
8770 ((setq e (assoc var org-table-named-field-locations))
8771 (switch-to-buffer-other-window (marker-buffer pos))
8772 (goto-line (nth 1 e))
8773 (org-table-goto-column (nth 2 e))
8774 (select-window win)
8775 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
8776 ((setq e (assoc var org-table-column-names))
8777 (switch-to-buffer-other-window (marker-buffer pos))
8778 (goto-char pos)
8779 (goto-char (org-table-begin))
8780 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
8781 (org-table-end) t)
8782 (progn
8783 (goto-char (match-beginning 1))
8784 (message "Named column (column %s)" (cdr e)))
8785 (error "Column name not found"))
8786 (select-window win))
8787 ((string-match "^[0-9]$" var)
8788 ;; column number
8789 (switch-to-buffer-other-window (marker-buffer pos))
8790 (goto-char pos)
8791 (goto-char (org-table-begin))
8792 (recenter 1)
8793 (if (re-search-forward org-table-dataline-regexp
8794 (org-table-end) t)
8795 (progn
8796 (goto-char (match-beginning 0))
8797 (org-table-goto-column (string-to-number var))
8798 (message "Column %s" var))
8799 (error "Column name not found"))
8800 (select-window win))
8801 ((setq e (assoc var org-table-local-parameters))
8802 (switch-to-buffer-other-window (marker-buffer pos))
8803 (goto-char pos)
8804 (goto-char (org-table-begin))
8805 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
8806 (progn
8807 (goto-char (match-beginning 1))
8808 (message "Local parameter."))
8809 (error "Parameter not found"))
8810 (select-window win))
8811 (t
8812 (cond
8813 ((setq e (assoc var org-table-formula-constants))
8814 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
8815 ((setq e (and (fboundp 'constants-get) (constants-get var)))
8816 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
8817 (t (error "Undefined name $%s" var)))))))
8818
8819 (defun org-finish-edit-formulas (&optional arg)
8820 "Parse the buffer for formula definitions and install them.
8821 With prefix ARG, apply the new formulas to the table."
8822 (interactive "P")
8823 (let ((pos org-pos) eql)
8824 (goto-char (point-min))
8825 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
8826 (push (cons (match-string 1) (match-string 2)) eql))
8827 (set-window-configuration org-window-configuration)
8828 (select-window (get-buffer-window (marker-buffer pos)))
8829 (goto-char pos)
8830 (unless (org-at-table-p)
8831 (error "Lost table position - cannot install formulae"))
8832 (org-table-store-formulas eql)
8833 (move-marker pos nil)
8834 (kill-buffer "*Edit Formulas*")
8835 (if arg
8836 (org-table-recalculate 'all)
8837 (message "New formulas installed - press C-u C-c C-c to apply."))))
8838
8839 (defun org-abort-edit-formulas ()
8840 "Abort editing formulas, without installing the changes."
8841 (interactive)
8842 (let ((pos org-pos))
8843 (set-window-configuration org-window-configuration)
8844 (select-window (get-buffer-window (marker-buffer pos)))
8845 (goto-char pos)
8846 (message "Formula editing aborted without installing changes")))
8847
8848 ;;; The orgtbl minor mode
8849
8850 ;; Define a minor mode which can be used in other modes in order to
8851 ;; integrate the org-mode table editor.
8852
8853 ;; This is really a hack, because the org-mode table editor uses several
8854 ;; keys which normally belong to the major mode, for example the TAB and
8855 ;; RET keys. Here is how it works: The minor mode defines all the keys
8856 ;; necessary to operate the table editor, but wraps the commands into a
8857 ;; function which tests if the cursor is currently inside a table. If that
8858 ;; is the case, the table editor command is executed. However, when any of
8859 ;; those keys is used outside a table, the function uses `key-binding' to
8860 ;; look up if the key has an associated command in another currently active
8861 ;; keymap (minor modes, major mode, global), and executes that command.
8862 ;; There might be problems if any of the keys used by the table editor is
8863 ;; otherwise used as a prefix key.
8864
8865 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8866 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8867 ;; addresses this by checking explicitly for both bindings.
8868
8869 ;; The optimized version (see variable `orgtbl-optimized') takes over
8870 ;; all keys which are bound to `self-insert-command' in the *global map*.
8871 ;; Some modes bind other commands to simple characters, for example
8872 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
8873 ;; active, this binding is ignored inside tables and replaced with a
8874 ;; modified self-insert.
8875
8876 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
8877 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
8878 In the optimized version, the table editor takes over all simple keys that
8879 normally just insert a character. In tables, the characters are inserted
8880 in a way to minimize disturbing the table structure (i.e. in overwrite mode
8881 for empty fields). Outside tables, the correct binding of the keys is
8882 restored.
8883
8884 The default for this option is t if the optimized version is also used in
8885 Org-mode. See the variable `org-enable-table-editor' for details. Changing
8886 this variable requires a restart of Emacs to become effective."
8887 :group 'org-table
8888 :type 'boolean)
8889
8890 (defvar orgtbl-mode nil
8891 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
8892 table editor in arbitrary modes.")
8893 (make-variable-buffer-local 'orgtbl-mode)
8894
8895 (defvar orgtbl-mode-map (make-keymap)
8896 "Keymap for `orgtbl-mode'.")
8897
8898 ;;;###autoload
8899 (defun turn-on-orgtbl ()
8900 "Unconditionally turn on `orgtbl-mode'."
8901 (orgtbl-mode 1))
8902
8903 ;;;###autoload
8904 (defun orgtbl-mode (&optional arg)
8905 "The `org-mode' table editor as a minor mode for use in other modes."
8906 (interactive)
8907 (if (eq major-mode 'org-mode)
8908 ;; Exit without error, in case some hook functions calls this
8909 ;; by accident in org-mode.
8910 (message "Orgtbl-mode is not useful in org-mode, command ignored")
8911 (setq orgtbl-mode
8912 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
8913 (if orgtbl-mode
8914 (progn
8915 (and (orgtbl-setup) (defun orgtbl-setup () nil))
8916 ;; Make sure we are first in minor-mode-map-alist
8917 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
8918 (and c (setq minor-mode-map-alist
8919 (cons c (delq c minor-mode-map-alist)))))
8920 (set (make-local-variable (quote org-table-may-need-update)) t)
8921 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
8922 (add-hook 'before-change-functions 'org-before-change-function
8923 nil 'local)
8924 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
8925 auto-fill-inhibit-regexp)
8926 (set (make-local-variable 'auto-fill-inhibit-regexp)
8927 (if auto-fill-inhibit-regexp
8928 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
8929 "[ \t]*|"))
8930 (easy-menu-add orgtbl-mode-menu)
8931 (run-hooks 'orgtbl-mode-hook))
8932 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
8933 (remove-hook 'before-change-functions 'org-before-change-function t)
8934 (easy-menu-remove orgtbl-mode-menu)
8935 (force-mode-line-update 'all))))
8936
8937 ;; Install it as a minor mode.
8938 (put 'orgtbl-mode :included t)
8939 (put 'orgtbl-mode :menu-tag "Org Table Mode")
8940 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
8941
8942 (defun orgtbl-make-binding (fun n &rest keys)
8943 "Create a function for binding in the table minor mode.
8944 FUN is the command to call inside a table. N is used to create a unique
8945 command name. KEYS are keys that should be checked in for a command
8946 to execute outside of tables."
8947 (eval
8948 (list 'defun
8949 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
8950 '(arg)
8951 (concat "In tables, run `" (symbol-name fun) "'.\n"
8952 "Outside of tables, run the binding of `"
8953 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8954 "'.")
8955 '(interactive "p")
8956 (list 'if
8957 '(org-at-table-p)
8958 (list 'call-interactively (list 'quote fun))
8959 (list 'let '(orgtbl-mode)
8960 (list 'call-interactively
8961 (append '(or)
8962 (mapcar (lambda (k)
8963 (list 'key-binding k))
8964 keys)
8965 '('orgtbl-error))))))))
8966
8967 (defun orgtbl-error ()
8968 "Error when there is no default binding for a table key."
8969 (interactive)
8970 (error "This key is has no function outside tables"))
8971
8972 (defun orgtbl-setup ()
8973 "Setup orgtbl keymaps."
8974 (let ((nfunc 0)
8975 (bindings
8976 (list
8977 '([(meta shift left)] org-table-delete-column)
8978 '([(meta left)] org-table-move-column-left)
8979 '([(meta right)] org-table-move-column-right)
8980 '([(meta shift right)] org-table-insert-column)
8981 '([(meta shift up)] org-table-kill-row)
8982 '([(meta shift down)] org-table-insert-row)
8983 '([(meta up)] org-table-move-row-up)
8984 '([(meta down)] org-table-move-row-down)
8985 '("\C-c\C-w" org-table-cut-region)
8986 '("\C-c\M-w" org-table-copy-region)
8987 '("\C-c\C-y" org-table-paste-rectangle)
8988 '("\C-c-" org-table-insert-hline)
8989 ; '([(shift tab)] org-table-previous-field)
8990 '("\C-m" org-table-next-row)
8991 (list (org-key 'S-return) 'org-table-copy-down)
8992 '([(meta return)] org-table-wrap-region)
8993 '("\C-c\C-q" org-table-wrap-region)
8994 '("\C-c?" org-table-current-column)
8995 '("\C-c " org-table-blank-field)
8996 '("\C-c+" org-table-sum)
8997 '("\C-c|" org-table-toggle-vline-visibility)
8998 '("\C-c=" org-table-eval-formula)
8999 '("\C-c'" org-table-edit-formulas)
9000 '("\C-c*" org-table-recalculate)
9001 '("\C-c^" org-table-sort-lines)
9002 '([(control ?#)] org-table-rotate-recalc-marks)))
9003 elt key fun cmd)
9004 (while (setq elt (pop bindings))
9005 (setq nfunc (1+ nfunc))
9006 (setq key (car elt)
9007 fun (nth 1 elt)
9008 cmd (orgtbl-make-binding fun nfunc key))
9009 (define-key orgtbl-mode-map key cmd))
9010 ;; Special treatment needed for TAB and RET
9011 (define-key orgtbl-mode-map [(return)]
9012 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9013 (define-key orgtbl-mode-map "\C-m"
9014 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9015 (define-key orgtbl-mode-map [(tab)]
9016 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9017 (define-key orgtbl-mode-map "\C-i"
9018 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
9019 (define-key orgtbl-mode-map "\C-i"
9020 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
9021 (define-key orgtbl-mode-map "\C-c\C-c"
9022 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
9023 (when orgtbl-optimized
9024 ;; If the user wants maximum table support, we need to hijack
9025 ;; some standard editing functions
9026 (org-remap orgtbl-mode-map
9027 'self-insert-command 'orgtbl-self-insert-command
9028 'delete-char 'orgtbl-delete-char
9029 'delete-backward-char 'orgtbl-delete-backward-char)
9030 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
9031 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
9032 '("OrgTbl"
9033 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
9034 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
9035 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
9036 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
9037 "--"
9038 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
9039 ["Copy Field from Above"
9040 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
9041 "--"
9042 ("Column"
9043 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
9044 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
9045 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
9046 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
9047 ("Row"
9048 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
9049 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
9050 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
9051 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
9052 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
9053 "--"
9054 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
9055 ("Rectangle"
9056 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
9057 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
9058 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
9059 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
9060 "--"
9061 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
9062 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9063 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
9064 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
9065 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
9066 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
9067 ["Sum Column/Rectangle" org-table-sum
9068 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
9069 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
9070 ["Debug Formulas"
9071 (setq org-table-formula-debug (not org-table-formula-debug))
9072 :style toggle :selected org-table-formula-debug]
9073 ))
9074 t)
9075
9076 (defun orgtbl-tab ()
9077 "Justification and field motion for `orgtbl-mode'."
9078 (interactive)
9079 (org-table-justify-field-maybe)
9080 (org-table-next-field))
9081
9082 (defun orgtbl-ret ()
9083 "Justification and field motion for `orgtbl-mode'."
9084 (interactive)
9085 (org-table-justify-field-maybe)
9086 (org-table-next-row))
9087
9088 (defun orgtbl-self-insert-command (N)
9089 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9090 If the cursor is in a table looking at whitespace, the whitespace is
9091 overwritten, and the table is not marked as requiring realignment."
9092 (interactive "p")
9093 (if (and (org-at-table-p)
9094 (or
9095 (and org-table-auto-blank-field
9096 (member last-command
9097 '(orgtbl-hijacker-command-100
9098 orgtbl-hijacker-command-101
9099 orgtbl-hijacker-command-102
9100 orgtbl-hijacker-command-103
9101 orgtbl-hijacker-command-104
9102 orgtbl-hijacker-command-105))
9103 (org-table-blank-field))
9104 t)
9105 (eq N 1)
9106 (looking-at "[^|\n]* +|"))
9107 (let (org-table-may-need-update)
9108 (goto-char (1- (match-end 0)))
9109 (delete-backward-char 1)
9110 (goto-char (match-beginning 0))
9111 (self-insert-command N))
9112 (setq org-table-may-need-update t)
9113 (let (orgtbl-mode)
9114 (call-interactively (key-binding (vector last-input-event))))))
9115
9116 (defun org-force-self-insert (N)
9117 "Needed to enforce self-insert under remapping."
9118 (interactive "p")
9119 (self-insert-command N))
9120
9121 (defun orgtbl-delete-backward-char (N)
9122 "Like `delete-backward-char', insert whitespace at field end in tables.
9123 When deleting backwards, in tables this function will insert whitespace in
9124 front of the next \"|\" separator, to keep the table aligned. The table will
9125 still be marked for re-alignment, because a narrow field may lead to a
9126 reduced column width."
9127 (interactive "p")
9128 (if (and (org-at-table-p)
9129 (eq N 1)
9130 (string-match "|" (buffer-substring (point-at-bol) (point)))
9131 (looking-at ".*?|"))
9132 (let ((pos (point)))
9133 (backward-delete-char N)
9134 (skip-chars-forward "^|")
9135 (insert " ")
9136 (goto-char (1- pos)))
9137 (delete-backward-char N)))
9138
9139 (defun orgtbl-delete-char (N)
9140 "Like `delete-char', but insert whitespace at field end in tables.
9141 When deleting characters, in tables this function will insert whitespace in
9142 front of the next \"|\" separator, to keep the table aligned. The table
9143 will still be marked for re-alignment, because a narrow field may lead to
9144 a reduced column width."
9145 (interactive "p")
9146 (if (and (org-at-table-p)
9147 (not (bolp))
9148 (not (= (char-after) ?|))
9149 (eq N 1))
9150 (if (looking-at ".*?|")
9151 (let ((pos (point)))
9152 (replace-match (concat
9153 (substring (match-string 0) 1 -1)
9154 " |"))
9155 (goto-char pos)))
9156 (delete-char N)))
9157
9158 ;;; Exporting
9159
9160 (defconst org-level-max 20)
9161
9162 (defun org-export-find-first-heading-line (list)
9163 "Remove all lines from LIST which are before the first headline."
9164 (let ((orig-list list)
9165 (re (concat "^" outline-regexp)))
9166 (while (and list
9167 (not (string-match re (car list))))
9168 (pop list))
9169 (or list orig-list)))
9170
9171 (defun org-skip-comments (lines)
9172 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
9173 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
9174 (re2 "^\\(\\*+\\)[ \t\n\r]")
9175 rtn line level)
9176 (while (setq line (pop lines))
9177 (cond
9178 ((and (string-match re1 line)
9179 (setq level (- (match-end 1) (match-beginning 1))))
9180 ;; Beginning of a COMMENT subtree. Skip it.
9181 (while (and (setq line (pop lines))
9182 (or (not (string-match re2 line))
9183 (> (- (match-end 1) (match-beginning 1)) level))))
9184 (setq lines (cons line lines)))
9185 ((string-match "^#" line)
9186 ;; an ordinary comment line
9187 )
9188 (t (setq rtn (cons line rtn)))))
9189 (nreverse rtn)))
9190
9191 ;; ASCII
9192
9193 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
9194 "Characters for underlining headings in ASCII export.")
9195
9196 (defconst org-html-entities
9197 '(("nbsp")
9198 ("iexcl")
9199 ("cent")
9200 ("pound")
9201 ("curren")
9202 ("yen")
9203 ("brvbar")
9204 ("sect")
9205 ("uml")
9206 ("copy")
9207 ("ordf")
9208 ("laquo")
9209 ("not")
9210 ("shy")
9211 ("reg")
9212 ("macr")
9213 ("deg")
9214 ("plusmn")
9215 ("sup2")
9216 ("sup3")
9217 ("acute")
9218 ("micro")
9219 ("para")
9220 ("middot")
9221 ("odot"."o")
9222 ("star"."*")
9223 ("cedil")
9224 ("sup1")
9225 ("ordm")
9226 ("raquo")
9227 ("frac14")
9228 ("frac12")
9229 ("frac34")
9230 ("iquest")
9231 ("Agrave")
9232 ("Aacute")
9233 ("Acirc")
9234 ("Atilde")
9235 ("Auml")
9236 ("Aring") ("AA"."&Aring;")
9237 ("AElig")
9238 ("Ccedil")
9239 ("Egrave")
9240 ("Eacute")
9241 ("Ecirc")
9242 ("Euml")
9243 ("Igrave")
9244 ("Iacute")
9245 ("Icirc")
9246 ("Iuml")
9247 ("ETH")
9248 ("Ntilde")
9249 ("Ograve")
9250 ("Oacute")
9251 ("Ocirc")
9252 ("Otilde")
9253 ("Ouml")
9254 ("times")
9255 ("Oslash")
9256 ("Ugrave")
9257 ("Uacute")
9258 ("Ucirc")
9259 ("Uuml")
9260 ("Yacute")
9261 ("THORN")
9262 ("szlig")
9263 ("agrave")
9264 ("aacute")
9265 ("acirc")
9266 ("atilde")
9267 ("auml")
9268 ("aring")
9269 ("aelig")
9270 ("ccedil")
9271 ("egrave")
9272 ("eacute")
9273 ("ecirc")
9274 ("euml")
9275 ("igrave")
9276 ("iacute")
9277 ("icirc")
9278 ("iuml")
9279 ("eth")
9280 ("ntilde")
9281 ("ograve")
9282 ("oacute")
9283 ("ocirc")
9284 ("otilde")
9285 ("ouml")
9286 ("divide")
9287 ("oslash")
9288 ("ugrave")
9289 ("uacute")
9290 ("ucirc")
9291 ("uuml")
9292 ("yacute")
9293 ("thorn")
9294 ("yuml")
9295 ("fnof")
9296 ("Alpha")
9297 ("Beta")
9298 ("Gamma")
9299 ("Delta")
9300 ("Epsilon")
9301 ("Zeta")
9302 ("Eta")
9303 ("Theta")
9304 ("Iota")
9305 ("Kappa")
9306 ("Lambda")
9307 ("Mu")
9308 ("Nu")
9309 ("Xi")
9310 ("Omicron")
9311 ("Pi")
9312 ("Rho")
9313 ("Sigma")
9314 ("Tau")
9315 ("Upsilon")
9316 ("Phi")
9317 ("Chi")
9318 ("Psi")
9319 ("Omega")
9320 ("alpha")
9321 ("beta")
9322 ("gamma")
9323 ("delta")
9324 ("epsilon")
9325 ("varepsilon"."&epsilon;")
9326 ("zeta")
9327 ("eta")
9328 ("theta")
9329 ("iota")
9330 ("kappa")
9331 ("lambda")
9332 ("mu")
9333 ("nu")
9334 ("xi")
9335 ("omicron")
9336 ("pi")
9337 ("rho")
9338 ("sigmaf") ("varsigma"."&sigmaf;")
9339 ("sigma")
9340 ("tau")
9341 ("upsilon")
9342 ("phi")
9343 ("chi")
9344 ("psi")
9345 ("omega")
9346 ("thetasym") ("vartheta"."&thetasym;")
9347 ("upsih")
9348 ("piv")
9349 ("bull") ("bullet"."&bull;")
9350 ("hellip") ("dots"."&hellip;")
9351 ("prime")
9352 ("Prime")
9353 ("oline")
9354 ("frasl")
9355 ("weierp")
9356 ("image")
9357 ("real")
9358 ("trade")
9359 ("alefsym")
9360 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
9361 ("uarr") ("uparrow"."&uarr;")
9362 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
9363 ("darr")("downarrow"."&darr;")
9364 ("harr") ("leftrightarrow"."&harr;")
9365 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
9366 ("lArr") ("Leftarrow"."&lArr;")
9367 ("uArr") ("Uparrow"."&uArr;")
9368 ("rArr") ("Rightarrow"."&rArr;")
9369 ("dArr") ("Downarrow"."&dArr;")
9370 ("hArr") ("Leftrightarrow"."&hArr;")
9371 ("forall")
9372 ("part") ("partial"."&part;")
9373 ("exist") ("exists"."&exist;")
9374 ("empty") ("emptyset"."&empty;")
9375 ("nabla")
9376 ("isin") ("in"."&isin;")
9377 ("notin")
9378 ("ni")
9379 ("prod")
9380 ("sum")
9381 ("minus")
9382 ("lowast") ("ast"."&lowast;")
9383 ("radic")
9384 ("prop") ("proptp"."&prop;")
9385 ("infin") ("infty"."&infin;")
9386 ("ang") ("angle"."&ang;")
9387 ("and") ("vee"."&and;")
9388 ("or") ("wedge"."&or;")
9389 ("cap")
9390 ("cup")
9391 ("int")
9392 ("there4")
9393 ("sim")
9394 ("cong") ("simeq"."&cong;")
9395 ("asymp")("approx"."&asymp;")
9396 ("ne") ("neq"."&ne;")
9397 ("equiv")
9398 ("le")
9399 ("ge")
9400 ("sub") ("subset"."&sub;")
9401 ("sup") ("supset"."&sup;")
9402 ("nsub")
9403 ("sube")
9404 ("supe")
9405 ("oplus")
9406 ("otimes")
9407 ("perp")
9408 ("sdot") ("cdot"."&sdot;")
9409 ("lceil")
9410 ("rceil")
9411 ("lfloor")
9412 ("rfloor")
9413 ("lang")
9414 ("rang")
9415 ("loz") ("Diamond"."&loz;")
9416 ("spades") ("spadesuit"."&spades;")
9417 ("clubs") ("clubsuit"."&clubs;")
9418 ("hearts") ("diamondsuit"."&hearts;")
9419 ("diams") ("diamondsuit"."&diams;")
9420 ("quot")
9421 ("amp")
9422 ("lt")
9423 ("gt")
9424 ("OElig")
9425 ("oelig")
9426 ("Scaron")
9427 ("scaron")
9428 ("Yuml")
9429 ("circ")
9430 ("tilde")
9431 ("ensp")
9432 ("emsp")
9433 ("thinsp")
9434 ("zwnj")
9435 ("zwj")
9436 ("lrm")
9437 ("rlm")
9438 ("ndash")
9439 ("mdash")
9440 ("lsquo")
9441 ("rsquo")
9442 ("sbquo")
9443 ("ldquo")
9444 ("rdquo")
9445 ("bdquo")
9446 ("dagger")
9447 ("Dagger")
9448 ("permil")
9449 ("lsaquo")
9450 ("rsaquo")
9451 ("euro")
9452
9453 ("arccos"."arccos")
9454 ("arcsin"."arcsin")
9455 ("arctan"."arctan")
9456 ("arg"."arg")
9457 ("cos"."cos")
9458 ("cosh"."cosh")
9459 ("cot"."cot")
9460 ("coth"."coth")
9461 ("csc"."csc")
9462 ("deg"."deg")
9463 ("det"."det")
9464 ("dim"."dim")
9465 ("exp"."exp")
9466 ("gcd"."gcd")
9467 ("hom"."hom")
9468 ("inf"."inf")
9469 ("ker"."ker")
9470 ("lg"."lg")
9471 ("lim"."lim")
9472 ("liminf"."liminf")
9473 ("limsup"."limsup")
9474 ("ln"."ln")
9475 ("log"."log")
9476 ("max"."max")
9477 ("min"."min")
9478 ("Pr"."Pr")
9479 ("sec"."sec")
9480 ("sin"."sin")
9481 ("sinh"."sinh")
9482 ("sup"."sup")
9483 ("tan"."tan")
9484 ("tanh"."tanh")
9485 )
9486 "Entities for TeX->HTML translation.
9487 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
9488 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
9489 In that case, \"\\ent\" will be translated to \"&other;\".
9490 The list contains HTML entities for Latin-1, Greek and other symbols.
9491 It is supplemented by a number of commonly used TeX macros with appropriate
9492 translations. There is currently no way for users to extend this.")
9493
9494 (defvar org-last-level nil) ; dynamically scoped variable
9495
9496 (defun org-export-as-ascii (arg)
9497 "Export the outline as a pretty ASCII file.
9498 If there is an active region, export only the region.
9499 The prefix ARG specifies how many levels of the outline should become
9500 underlined headlines. The default is 3."
9501 (interactive "P")
9502 (setq-default org-todo-line-regexp org-todo-line-regexp)
9503 (let* ((region
9504 (buffer-substring
9505 (if (org-region-active-p) (region-beginning) (point-min))
9506 (if (org-region-active-p) (region-end) (point-max))))
9507 (lines (org-export-find-first-heading-line
9508 (org-skip-comments (org-split-string region "[\r\n]"))))
9509 (org-startup-with-deadline-check nil)
9510 (level 0) line txt
9511 (umax nil)
9512 (case-fold-search nil)
9513 (filename (concat (file-name-sans-extension (buffer-file-name))
9514 ".txt"))
9515 (buffer (find-file-noselect filename))
9516 (levels-open (make-vector org-level-max nil))
9517 (date (format-time-string "%Y/%m/%d" (current-time)))
9518 (time (format-time-string "%X" (current-time)))
9519 (author user-full-name)
9520 (title (buffer-name))
9521 (options nil)
9522 (email user-mail-address)
9523 (language org-export-default-language)
9524 (text nil)
9525 (todo nil)
9526 (lang-words nil))
9527
9528 (setq org-last-level 1)
9529 (org-init-section-numbers)
9530
9531 (find-file-noselect filename)
9532
9533 ;; Search for the export key lines
9534 (org-parse-key-lines)
9535
9536 (setq lang-words (or (assoc language org-export-language-setup)
9537 (assoc "en" org-export-language-setup)))
9538 (if org-export-ascii-show-new-buffer
9539 (switch-to-buffer-other-window buffer)
9540 (set-buffer buffer))
9541 (erase-buffer)
9542 (fundamental-mode)
9543 (if options (org-parse-export-options options))
9544 (setq umax (if arg (prefix-numeric-value arg)
9545 org-export-headline-levels))
9546
9547 ;; File header
9548 (if title (org-insert-centered title ?=))
9549 (insert "\n")
9550 (if (or author email)
9551 (insert (concat (nth 1 lang-words) ": " (or author "")
9552 (if email (concat " <" email ">") "")
9553 "\n")))
9554 (if (and date time)
9555 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
9556 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
9557
9558 (insert "\n\n")
9559
9560 (if org-export-with-toc
9561 (progn
9562 (insert (nth 3 lang-words) "\n"
9563 (make-string (length (nth 3 lang-words)) ?=) "\n")
9564 (mapcar '(lambda (line)
9565 (if (string-match org-todo-line-regexp
9566 line)
9567 ;; This is a headline
9568 (progn
9569 (setq level (- (match-end 1) (match-beginning 1))
9570 txt (match-string 3 line)
9571 todo
9572 (or (and (match-beginning 2)
9573 (not (equal (match-string 2 line)
9574 org-done-string)))
9575 ; TODO, not DONE
9576 (and (= level umax)
9577 (org-search-todo-below
9578 line lines level))))
9579 (setq txt (org-html-expand-for-ascii txt))
9580
9581 (if org-export-with-section-numbers
9582 (setq txt (concat (org-section-number level)
9583 " " txt)))
9584 (if (<= level umax)
9585 (progn
9586 (insert
9587 (make-string (* (1- level) 4) ?\ )
9588 (format (if todo "%s (*)\n" "%s\n") txt))
9589 (setq org-last-level level))
9590 ))))
9591 lines)))
9592
9593 (org-init-section-numbers)
9594 (while (setq line (pop lines))
9595 ;; Remove the quoted HTML tags.
9596 (setq line (org-html-expand-for-ascii line))
9597 (cond
9598 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
9599 ;; a Headline
9600 (setq level (- (match-end 1) (match-beginning 1))
9601 txt (match-string 2 line))
9602 (org-ascii-level-start level txt umax))
9603 (t (insert line "\n"))))
9604 (normal-mode)
9605 (save-buffer)
9606 (goto-char (point-min))))
9607
9608 (defun org-search-todo-below (line lines level)
9609 "Search the subtree below LINE for any TODO entries."
9610 (let ((rest (cdr (memq line lines)))
9611 (re org-todo-line-regexp)
9612 line lv todo)
9613 (catch 'exit
9614 (while (setq line (pop rest))
9615 (if (string-match re line)
9616 (progn
9617 (setq lv (- (match-end 1) (match-beginning 1))
9618 todo (and (match-beginning 2)
9619 (not (equal (match-string 2 line)
9620 org-done-string))))
9621 ; TODO, not DONE
9622 (if (<= lv level) (throw 'exit nil))
9623 (if todo (throw 'exit t))))))))
9624
9625 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
9626 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
9627 (defun org-html-expand-for-ascii (line)
9628 "Handle quoted HTML for ASCII export."
9629 (if org-export-html-expand
9630 (while (string-match "@<[^<>\n]*>" line)
9631 ;; We just remove the tags for now.
9632 (setq line (replace-match "" nil nil line))))
9633 line)
9634
9635 (defun org-insert-centered (s &optional underline)
9636 "Insert the string S centered and underline it with character UNDERLINE."
9637 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
9638 (insert (make-string ind ?\ ) s "\n")
9639 (if underline
9640 (insert (make-string ind ?\ )
9641 (make-string (length s) underline)
9642 "\n"))))
9643
9644 (defun org-ascii-level-start (level title umax)
9645 "Insert a new level in ASCII export."
9646 (let (char)
9647 (if (> level umax)
9648 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
9649 (if (or (not (equal (char-before) ?\n))
9650 (not (equal (char-before (1- (point))) ?\n)))
9651 (insert "\n"))
9652 (setq char (nth (- umax level) (reverse org-ascii-underline)))
9653 (if org-export-with-section-numbers
9654 (setq title (concat (org-section-number level) " " title)))
9655 (insert title "\n" (make-string (string-width title) char) "\n"))))
9656
9657 (defun org-export-copy-visible ()
9658 "Copy the visible part of the buffer to another buffer, for printing.
9659 Also removes the first line of the buffer if it specifies a mode,
9660 and all options lines."
9661 (interactive)
9662 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
9663 ".txt"))
9664 (buffer (find-file-noselect filename))
9665 (ore (concat
9666 (org-make-options-regexp
9667 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
9668 "STARTUP" "ARCHIVE"
9669 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
9670 (if org-noutline-p "\\(\n\\|$\\)" "")))
9671 s e)
9672 (with-current-buffer buffer
9673 (erase-buffer)
9674 (text-mode))
9675 (save-excursion
9676 (setq s (goto-char (point-min)))
9677 (while (not (= (point) (point-max)))
9678 (goto-char (org-find-invisible))
9679 (append-to-buffer buffer s (point))
9680 (setq s (goto-char (org-find-visible)))))
9681 (switch-to-buffer-other-window buffer)
9682 (newline)
9683 (goto-char (point-min))
9684 (if (looking-at ".*-\\*- mode:.*\n")
9685 (replace-match ""))
9686 (while (re-search-forward ore nil t)
9687 (replace-match ""))
9688 (goto-char (point-min))))
9689
9690 (defun org-find-visible ()
9691 (if (featurep 'noutline)
9692 (let ((s (point)))
9693 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
9694 (get-char-property s 'invisible)))
9695 s)
9696 (skip-chars-forward "^\n")
9697 (point)))
9698 (defun org-find-invisible ()
9699 (if (featurep 'noutline)
9700 (let ((s (point)))
9701 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
9702 (not (get-char-property s 'invisible))))
9703 s)
9704 (skip-chars-forward "^\r")
9705 (point)))
9706
9707 ;; HTML
9708
9709 (defun org-get-current-options ()
9710 "Return a string with current options as keyword options.
9711 Does include HTML export options as well as TODO and CATEGORY stuff."
9712 (format
9713 "#+TITLE: %s
9714 #+AUTHOR: %s
9715 #+EMAIL: %s
9716 #+LANGUAGE: %s
9717 #+TEXT: Some descriptive text to be emitted. Several lines OK.
9718 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
9719 #+CATEGORY: %s
9720 #+SEQ_TODO: %s
9721 #+TYP_TODO: %s
9722 #+STARTUP: %s %s
9723 #+ARCHIVE: %s
9724 "
9725 (buffer-name) (user-full-name) user-mail-address org-export-default-language
9726 org-export-headline-levels
9727 org-export-with-section-numbers
9728 org-export-with-toc
9729 org-export-preserve-breaks
9730 org-export-html-expand
9731 org-export-with-fixed-width
9732 org-export-with-tables
9733 org-export-with-sub-superscripts
9734 org-export-with-emphasize
9735 org-export-with-TeX-macros
9736 (file-name-nondirectory (buffer-file-name))
9737 (if (equal org-todo-interpretation 'sequence)
9738 (mapconcat 'identity org-todo-keywords " ")
9739 "TODO FEEDBACK VERIFY DONE")
9740 (if (equal org-todo-interpretation 'type)
9741 (mapconcat 'identity org-todo-keywords " ")
9742 "Me Jason Marie DONE")
9743 (cdr (assoc org-startup-folded
9744 '((nil . "nofold")(t . "fold")(content . "content"))))
9745 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
9746 org-archive-location
9747 ))
9748
9749 (defun org-insert-export-options-template ()
9750 "Insert into the buffer a template with information for exporting."
9751 (interactive)
9752 (if (not (bolp)) (newline))
9753 (let ((s (org-get-current-options)))
9754 (and (string-match "#\\+CATEGORY" s)
9755 (setq s (substring s 0 (match-beginning 0))))
9756 (insert s)))
9757
9758 (defun org-toggle-fixed-width-section (arg)
9759 "Toggle the fixed-width export.
9760 If there is no active region, the QUOTE keyword at the current headline is
9761 inserted or removed. When present, it causes the text between this headline
9762 and the next to be exported as fixed-width text, and unmodified.
9763 If there is an active region, this command adds or removes a colon as the
9764 first character of this line. If the first character of a line is a colon,
9765 this line is also exported in fixed-width font."
9766 (interactive "P")
9767 (let* ((cc 0)
9768 (regionp (org-region-active-p))
9769 (beg (if regionp (region-beginning) (point)))
9770 (end (if regionp (region-end)))
9771 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
9772 (re "[ \t]*\\(:\\)")
9773 off)
9774 (if regionp
9775 (save-excursion
9776 (goto-char beg)
9777 (setq cc (current-column))
9778 (beginning-of-line 1)
9779 (setq off (looking-at re))
9780 (while (> nlines 0)
9781 (setq nlines (1- nlines))
9782 (beginning-of-line 1)
9783 (cond
9784 (arg
9785 (move-to-column cc t)
9786 (insert ":\n")
9787 (forward-line -1))
9788 ((and off (looking-at re))
9789 (replace-match "" t t nil 1))
9790 ((not off) (move-to-column cc t) (insert ":")))
9791 (forward-line 1)))
9792 (save-excursion
9793 (org-back-to-heading)
9794 (if (looking-at (concat outline-regexp
9795 "\\( +\\<" org-quote-string "\\>\\)"))
9796 (replace-match "" t t nil 1)
9797 (if (looking-at outline-regexp)
9798 (progn
9799 (goto-char (match-end 0))
9800 (insert " " org-quote-string))))))))
9801
9802 (defun org-export-as-html-and-open (arg)
9803 "Export the outline as HTML and immediately open it with a browser.
9804 If there is an active region, export only the region.
9805 The prefix ARG specifies how many levels of the outline should become
9806 headlines. The default is 3. Lower levels will become bulleted lists."
9807 (interactive "P")
9808 (org-export-as-html arg 'hidden)
9809 (org-open-file (buffer-file-name)))
9810
9811 (defun org-export-as-html-batch ()
9812 "Call `org-export-as-html', may be used in batch processing as
9813 emacs --batch
9814 --load=$HOME/lib/emacs/org.el
9815 --eval \"(setq org-export-headline-levels 2)\"
9816 --visit=MyFile --funcall org-export-as-html-batch"
9817 (org-export-as-html org-export-headline-levels 'hidden))
9818
9819 (defun org-export-as-html (arg &optional hidden)
9820 "Export the outline as a pretty HTML file.
9821 If there is an active region, export only the region.
9822 The prefix ARG specifies how many levels of the outline should become
9823 headlines. The default is 3. Lower levels will become bulleted lists."
9824 (interactive "P")
9825 (setq-default org-todo-line-regexp org-todo-line-regexp)
9826 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
9827 (setq-default org-done-string org-done-string)
9828 (let* ((style org-export-html-style)
9829 (region-p (org-region-active-p))
9830 (region
9831 (buffer-substring
9832 (if region-p (region-beginning) (point-min))
9833 (if region-p (region-end) (point-max))))
9834 (all_lines
9835 (org-skip-comments (org-split-string region "[\r\n]")))
9836 (lines (org-export-find-first-heading-line all_lines))
9837 (level 0) (line "") (origline "") txt todo
9838 (umax nil)
9839 (filename (concat (file-name-sans-extension (buffer-file-name))
9840 ".html"))
9841 (buffer (find-file-noselect filename))
9842 (levels-open (make-vector org-level-max nil))
9843 (date (format-time-string "%Y/%m/%d" (current-time)))
9844 (time (format-time-string "%X" (current-time)))
9845 (author user-full-name)
9846 (title (buffer-name))
9847 (options nil)
9848 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
9849 (inquote nil)
9850 (infixed nil)
9851 (in-local-list nil)
9852 (local-list-num nil)
9853 (local-list-indent nil)
9854 (llt org-plain-list-ordered-item-terminator)
9855 (email user-mail-address)
9856 (language org-export-default-language)
9857 (text nil)
9858 (lang-words nil)
9859 (head-count 0) cnt
9860 (start 0)
9861 ;; FIXME: The following returns always nil under XEmacs
9862 (coding-system (and (fboundp 'coding-system-get)
9863 (boundp 'buffer-file-coding-system)
9864 buffer-file-coding-system))
9865 (coding-system-for-write (or coding-system coding-system-for-write))
9866 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
9867 (charset (and coding-system
9868 (coding-system-get coding-system 'mime-charset)))
9869 table-open type
9870 table-buffer table-orig-buffer
9871 ind start-is-num starter
9872 )
9873 (message "Exporting...")
9874
9875 (setq org-last-level 1)
9876 (org-init-section-numbers)
9877
9878 ;; Search for the export key lines
9879 (org-parse-key-lines)
9880 (setq lang-words (or (assoc language org-export-language-setup)
9881 (assoc "en" org-export-language-setup)))
9882
9883 ;; Switch to the output buffer
9884 (if (or hidden (not org-export-html-show-new-buffer))
9885 (set-buffer buffer)
9886 (switch-to-buffer-other-window buffer))
9887 (erase-buffer)
9888 (fundamental-mode)
9889 (let ((case-fold-search nil))
9890 (if options (org-parse-export-options options))
9891 (setq umax (if arg (prefix-numeric-value arg)
9892 org-export-headline-levels))
9893
9894 ;; File header
9895 (insert (format
9896 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
9897 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
9898 <html lang=\"%s\"><head>
9899 <title>%s</title>
9900 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
9901 <meta name=generator content=\"Org-mode\">
9902 <meta name=generated content=\"%s %s\">
9903 <meta name=author content=\"%s\">
9904 %s
9905 </head><body>
9906 "
9907 language (org-html-expand title) (or charset "iso-8859-1")
9908 date time author style))
9909 (if title (insert (concat "<H1 class=\"title\">"
9910 (org-html-expand title) "</H1>\n")))
9911 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
9912 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
9913 email "&gt;</a>\n")))
9914 (if (or author email) (insert "<br>\n"))
9915 (if (and date time) (insert (concat (nth 2 lang-words) ": "
9916 date " " time "<br>\n")))
9917 (if text (insert (concat "<p>\n" (org-html-expand text))))
9918 (if org-export-with-toc
9919 (progn
9920 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
9921 (insert "<ul>\n")
9922 (mapcar '(lambda (line)
9923 (if (string-match org-todo-line-regexp line)
9924 ;; This is a headline
9925 (progn
9926 (setq level (- (match-end 1) (match-beginning 1))
9927 txt (save-match-data
9928 (org-html-expand
9929 (match-string 3 line)))
9930 todo
9931 (or (and (match-beginning 2)
9932 (not (equal (match-string 2 line)
9933 org-done-string)))
9934 ; TODO, not DONE
9935 (and (= level umax)
9936 (org-search-todo-below
9937 line lines level))))
9938 (if org-export-with-section-numbers
9939 (setq txt (concat (org-section-number level)
9940 " " txt)))
9941 (if (<= level umax)
9942 (progn
9943 (setq head-count (+ head-count 1))
9944 (if (> level org-last-level)
9945 (progn
9946 (setq cnt (- level org-last-level))
9947 (while (>= (setq cnt (1- cnt)) 0)
9948 (insert "<ul>"))
9949 (insert "\n")))
9950 (if (< level org-last-level)
9951 (progn
9952 (setq cnt (- org-last-level level))
9953 (while (>= (setq cnt (1- cnt)) 0)
9954 (insert "</ul>"))
9955 (insert "\n")))
9956 (insert
9957 (format
9958 (if todo
9959 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
9960 "<li><a href=\"#sec-%d\">%s</a>\n")
9961 head-count txt))
9962 (setq org-last-level level))
9963 ))))
9964 lines)
9965 (while (> org-last-level 0)
9966 (setq org-last-level (1- org-last-level))
9967 (insert "</ul>\n"))
9968 ))
9969 (setq head-count 0)
9970 (org-init-section-numbers)
9971
9972 (while (setq line (pop lines) origline line)
9973 (catch 'nextline
9974
9975 ;; end of quote section?
9976 (when (and inquote (string-match "^\\*+" line))
9977 (insert "</pre>\n")
9978 (setq inquote nil))
9979 ;; inside a quote section?
9980 (when inquote
9981 (insert (org-html-protect line) "\n")
9982 (throw 'nextline nil))
9983
9984 ;; verbatim lines
9985 (when (and org-export-with-fixed-width
9986 (string-match "^[ \t]*:\\(.*\\)" line))
9987 (when (not infixed)
9988 (setq infixed t)
9989 (insert "<pre>\n"))
9990 (insert (org-html-protect (match-string 1 line)) "\n")
9991 (when (and lines
9992 (not (string-match "^[ \t]*\\(:.*\\)"
9993 (car lines))))
9994 (setq infixed nil)
9995 (insert "</pre>\n"))
9996 (throw 'nextline nil))
9997
9998 ;; Protect the links
9999 (setq start 0)
10000 (while (string-match org-link-maybe-angles-regexp line start)
10001 (setq start (match-end 0))
10002 (setq line (replace-match
10003 (concat "\000" (match-string 1 line) "\000")
10004 t t line)))
10005
10006 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
10007 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
10008 (setq line (org-html-expand line))
10009
10010 ;; Format the links
10011 (setq start 0)
10012 (while (string-match org-protected-link-regexp line start)
10013 (setq start (- (match-end 0) 2))
10014 (setq type (match-string 1 line))
10015 (cond
10016 ((member type '("http" "https" "ftp" "mailto" "news"))
10017 ;; standard URL
10018 (setq line (replace-match
10019 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
10020 "<a href=\"\\1:\\2\">\\1:\\2</a>"
10021 nil nil line)))
10022 ((string= type "file")
10023 ;; FILE link
10024 (let* ((filename (match-string 2 line))
10025 (abs-p (file-name-absolute-p filename))
10026 (thefile (if abs-p (expand-file-name filename) filename))
10027 (thefile (save-match-data
10028 (if (string-match ":[0-9]+$" thefile)
10029 (replace-match "" t t thefile)
10030 thefile)))
10031 (file-is-image-p
10032 (save-match-data
10033 (string-match (org-image-file-name-regexp) thefile))))
10034 (setq line (replace-match
10035 (if (and org-export-html-inline-images
10036 file-is-image-p)
10037 (concat "<img src=\"" thefile "\"/>")
10038 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
10039 nil nil line))))
10040
10041 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
10042 (setq line (replace-match
10043 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
10044
10045 ;; TODO items
10046 (if (and (string-match org-todo-line-regexp line)
10047 (match-beginning 2))
10048 (if (equal (match-string 2 line) org-done-string)
10049 (setq line (replace-match
10050 "<span class=\"done\">\\2</span>"
10051 nil nil line 2))
10052 (setq line (replace-match "<span class=\"todo\">\\2</span>"
10053 nil nil line 2))))
10054
10055 ;; DEADLINES
10056 (if (string-match org-deadline-line-regexp line)
10057 (progn
10058 (if (save-match-data
10059 (string-match "<a href"
10060 (substring line 0 (match-beginning 0))))
10061 nil ; Don't do the replacement - it is inside a link
10062 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
10063 nil nil line 1)))))
10064 (cond
10065 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10066 ;; This is a headline
10067 (setq level (- (match-end 1) (match-beginning 1))
10068 txt (match-string 2 line))
10069 (if (<= level umax) (setq head-count (+ head-count 1)))
10070 (when in-local-list
10071 ;; Close any local lists before inserting a new header line
10072 (while local-list-num
10073 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10074 (pop local-list-num))
10075 (setq local-list-indent nil
10076 in-local-list nil))
10077 (org-html-level-start level txt umax
10078 (and org-export-with-toc (<= level umax))
10079 head-count)
10080 ;; QUOTES
10081 (when (string-match quote-re line)
10082 (insert "<pre>")
10083 (setq inquote t)))
10084
10085 ((and org-export-with-tables
10086 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
10087 (if (not table-open)
10088 ;; New table starts
10089 (setq table-open t table-buffer nil table-orig-buffer nil))
10090 ;; Accumulate lines
10091 (setq table-buffer (cons line table-buffer)
10092 table-orig-buffer (cons origline table-orig-buffer))
10093 (when (or (not lines)
10094 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
10095 (car lines))))
10096 (setq table-open nil
10097 table-buffer (nreverse table-buffer)
10098 table-orig-buffer (nreverse table-orig-buffer))
10099 (insert (org-format-table-html table-buffer table-orig-buffer))))
10100 (t
10101 ;; Normal lines
10102 (when (and (> org-export-plain-list-max-depth 0)
10103 (string-match
10104 (cond
10105 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10106 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10107 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10108 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
10109 line))
10110 (setq ind (org-get-string-indentation line)
10111 start-is-num (match-beginning 4)
10112 starter (if (match-beginning 2) (match-string 2 line))
10113 line (substring line (match-beginning 5)))
10114 (unless (string-match "[^ \t]" line)
10115 ;; empty line. Pretend indentation is large.
10116 (setq ind (1+ (or (car local-list-indent) 1))))
10117 (while (and in-local-list
10118 (or (and (= ind (car local-list-indent))
10119 (not starter))
10120 (< ind (car local-list-indent))))
10121 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10122 (pop local-list-num) (pop local-list-indent)
10123 (setq in-local-list local-list-indent))
10124 (cond
10125 ((and starter
10126 (or (not in-local-list)
10127 (> ind (car local-list-indent)))
10128 (< (length local-list-indent)
10129 org-export-plain-list-max-depth))
10130 ;; Start new (level of ) list
10131 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
10132 (push start-is-num local-list-num)
10133 (push ind local-list-indent)
10134 (setq in-local-list t))
10135 (starter
10136 ;; continue current list
10137 (insert "<li>\n"))))
10138 ;; Empty lines start a new paragraph. If hand-formatted lists
10139 ;; are not fully interpreted, lines starting with "-", "+", "*"
10140 ;; also start a new paragraph.
10141 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
10142 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
10143 ))
10144 (if org-export-html-with-timestamp
10145 (insert org-export-html-html-helper-timestamp))
10146 (insert "</body>\n</html>\n")
10147 (normal-mode)
10148 (save-buffer)
10149 (goto-char (point-min)))))
10150
10151 (defun org-format-table-html (lines olines)
10152 "Find out which HTML converter to use and return the HTML code."
10153 (if (string-match "^[ \t]*|" (car lines))
10154 ;; A normal org table
10155 (org-format-org-table-html lines)
10156 ;; Table made by table.el - test for spanning
10157 (let* ((hlines (delq nil (mapcar
10158 (lambda (x)
10159 (if (string-match "^[ \t]*\\+-" x) x
10160 nil))
10161 lines)))
10162 (first (car hlines))
10163 (ll (and (string-match "\\S-+" first)
10164 (match-string 0 first)))
10165 (re (concat "^[ \t]*" (regexp-quote ll)))
10166 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
10167 hlines))))
10168 (if (and (not spanning)
10169 (not org-export-prefer-native-exporter-for-tables))
10170 ;; We can use my own converter with HTML conversions
10171 (org-format-table-table-html lines)
10172 ;; Need to use the code generator in table.el, with the original text.
10173 (org-format-table-table-html-using-table-generate-source olines)))))
10174
10175 (defun org-format-org-table-html (lines)
10176 "Format a table into html."
10177 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10178 (setq lines (nreverse lines))
10179 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10180 (setq lines (nreverse lines))
10181 (let ((head (and org-export-highlight-first-table-line
10182 (delq nil (mapcar
10183 (lambda (x) (string-match "^[ \t]*|-" x))
10184 (cdr lines)))))
10185 line fields html)
10186 (setq html (concat org-export-html-table-tag "\n"))
10187 (while (setq line (pop lines))
10188 (catch 'next-line
10189 (if (string-match "^[ \t]*|-" line)
10190 (progn
10191 (setq head nil) ;; head ends here, first time around
10192 ;; ignore this line
10193 (throw 'next-line t)))
10194 ;; Break the line into fields
10195 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10196 (setq html (concat
10197 html
10198 "<tr>"
10199 (mapconcat (lambda (x)
10200 (if head
10201 (concat "<th>" x "</th>")
10202 (concat "<td>" x "</td>")))
10203 fields "")
10204 "</tr>\n"))))
10205 (setq html (concat html "</table>\n"))
10206 html))
10207
10208 (defun org-fake-empty-table-line (line)
10209 "Replace everything except \"|\" with spaces."
10210 (let ((i (length line))
10211 (newstr (copy-sequence line)))
10212 (while (> i 0)
10213 (setq i (1- i))
10214 (if (not (eq (aref newstr i) ?|))
10215 (aset newstr i ?\ )))
10216 newstr))
10217
10218 (defun org-format-table-table-html (lines)
10219 "Format a table generated by table.el into html.
10220 This conversion does *not* use `table-generate-source' from table.el.
10221 This has the advantage that Org-mode's HTML conversions can be used.
10222 But it has the disadvantage, that no cell- or row-spanning is allowed."
10223 (let (line field-buffer
10224 (head org-export-highlight-first-table-line)
10225 fields html empty)
10226 (setq html (concat org-export-html-table-tag "\n"))
10227 (while (setq line (pop lines))
10228 (setq empty "&nbsp")
10229 (catch 'next-line
10230 (if (string-match "^[ \t]*\\+-" line)
10231 (progn
10232 (if field-buffer
10233 (progn
10234 (setq html (concat
10235 html
10236 "<tr>"
10237 (mapconcat
10238 (lambda (x)
10239 (if (equal x "") (setq x empty))
10240 (if head
10241 (concat "<th>" x "</th>\n")
10242 (concat "<td>" x "</td>\n")))
10243 field-buffer "\n")
10244 "</tr>\n"))
10245 (setq head nil)
10246 (setq field-buffer nil)))
10247 ;; Ignore this line
10248 (throw 'next-line t)))
10249 ;; Break the line into fields and store the fields
10250 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10251 (if field-buffer
10252 (setq field-buffer (mapcar
10253 (lambda (x)
10254 (concat x "<br>" (pop fields)))
10255 field-buffer))
10256 (setq field-buffer fields))))
10257 (setq html (concat html "</table>\n"))
10258 html))
10259
10260 (defun org-format-table-table-html-using-table-generate-source (lines)
10261 "Format a table into html, using `table-generate-source' from table.el.
10262 This has the advantage that cell- or row-spanning is allowed.
10263 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
10264 (require 'table)
10265 (with-current-buffer (get-buffer-create " org-tmp1 ")
10266 (erase-buffer)
10267 (insert (mapconcat 'identity lines "\n"))
10268 (goto-char (point-min))
10269 (if (not (re-search-forward "|[^+]" nil t))
10270 (error "Error processing table"))
10271 (table-recognize-table)
10272 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
10273 (table-generate-source 'html " org-tmp2 ")
10274 (set-buffer " org-tmp2 ")
10275 (buffer-substring (point-min) (point-max))))
10276
10277 (defun org-html-protect (s)
10278 ;; convert & to &amp;, < to &lt; and > to &gt;
10279 (let ((start 0))
10280 (while (string-match "&" s start)
10281 (setq s (replace-match "&amp;" t t s)
10282 start (1+ (match-beginning 0))))
10283 (while (string-match "<" s)
10284 (setq s (replace-match "&lt;" t t s)))
10285 (while (string-match ">" s)
10286 (setq s (replace-match "&gt;" t t s))))
10287 s)
10288
10289 (defun org-html-expand (string)
10290 "Prepare STRING for HTML export. Applies all active conversions."
10291 ;; First check if there is a link in the line - if yes, apply conversions
10292 ;; only before the start of the link.
10293 ;; FIXME: This is no longer correct, because links now have an end.
10294 (let* ((m (string-match org-link-regexp string))
10295 (s (if m (substring string 0 m) string))
10296 (r (if m (substring string m) "")))
10297 ;; convert & to &amp;, < to &lt; and > to &gt;
10298 (setq s (org-html-protect s))
10299 (if org-export-html-expand
10300 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
10301 (setq s (replace-match "<\\1>" nil nil s))))
10302 (if org-export-with-emphasize
10303 (setq s (org-export-html-convert-emphasize s)))
10304 (if org-export-with-sub-superscripts
10305 (setq s (org-export-html-convert-sub-super s)))
10306 (if org-export-with-TeX-macros
10307 (let ((start 0) wd ass)
10308 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
10309 (setq wd (match-string 1 s))
10310 (if (setq ass (assoc wd org-html-entities))
10311 (setq s (replace-match (or (cdr ass)
10312 (concat "&" (car ass) ";"))
10313 t t s))
10314 (setq start (+ start (length wd)))))))
10315 (concat s r)))
10316
10317 (defun org-create-multibrace-regexp (left right n)
10318 "Create a regular expression which will match a balanced sexp.
10319 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
10320 as single character strings.
10321 The regexp returned will match the entire expression including the
10322 delimiters. It will also define a single group which contains the
10323 match except for the outermost delimiters. The maximum depth of
10324 stacked delimiters is N. Escaping delimiters is not possible."
10325 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
10326 (or "\\|")
10327 (re nothing)
10328 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
10329 (while (> n 1)
10330 (setq n (1- n)
10331 re (concat re or next)
10332 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
10333 (concat left "\\(" re "\\)" right)))
10334
10335 (defvar org-match-substring-regexp
10336 (concat
10337 "\\([^\\]\\)\\([_^]\\)\\("
10338 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
10339 "\\|"
10340 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
10341 "\\|"
10342 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
10343 "The regular expression matching a sub- or superscript.")
10344
10345 (defun org-export-html-convert-sub-super (string)
10346 "Convert sub- and superscripts in STRING to HTML."
10347 (let (key c)
10348 (while (string-match org-match-substring-regexp string)
10349 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
10350 (setq c (or (match-string 8 string)
10351 (match-string 6 string)
10352 (match-string 5 string)))
10353 (setq string (replace-match
10354 (concat (match-string 1 string)
10355 "<" key ">" c "</" key ">")
10356 t t string)))
10357 (while (string-match "\\\\\\([_^]\\)" string)
10358 (setq string (replace-match (match-string 1 string) t t string))))
10359 string)
10360
10361 (defun org-export-html-convert-emphasize (string)
10362 (while (string-match
10363 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
10364 string)
10365 (setq string (replace-match
10366 (concat "<b>" (match-string 3 string) "</b>")
10367 t t string 2)))
10368 (while (string-match
10369 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
10370 string)
10371 (setq string (replace-match
10372 (concat "<i>" (match-string 3 string) "</i>")
10373 t t string 2)))
10374 (while (string-match
10375 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
10376 string)
10377 (setq string (replace-match
10378 (concat "<u>" (match-string 3 string) "</u>")
10379 t t string 2)))
10380 string)
10381
10382 (defun org-parse-key-lines ()
10383 "Find the special key lines with the information for exporters."
10384 (save-excursion
10385 (goto-char 0)
10386 (let ((re (org-make-options-regexp
10387 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
10388 key)
10389 (while (re-search-forward re nil t)
10390 (setq key (match-string 1))
10391 (cond ((string-equal key "TITLE")
10392 (setq title (match-string 2)))
10393 ((string-equal key "AUTHOR")
10394 (setq author (match-string 2)))
10395 ((string-equal key "EMAIL")
10396 (setq email (match-string 2)))
10397 ((string-equal key "LANGUAGE")
10398 (setq language (match-string 2)))
10399 ((string-equal key "TEXT")
10400 (setq text (concat text "\n" (match-string 2))))
10401 ((string-equal key "OPTIONS")
10402 (setq options (match-string 2))))))))
10403
10404 (defun org-parse-export-options (s)
10405 "Parse the export options line."
10406 (let ((op '(("H" . org-export-headline-levels)
10407 ("num" . org-export-with-section-numbers)
10408 ("toc" . org-export-with-toc)
10409 ("\\n" . org-export-preserve-breaks)
10410 ("@" . org-export-html-expand)
10411 (":" . org-export-with-fixed-width)
10412 ("|" . org-export-with-tables)
10413 ("^" . org-export-with-sub-superscripts)
10414 ("*" . org-export-with-emphasize)
10415 ("TeX" . org-export-with-TeX-macros)))
10416 o)
10417 (while (setq o (pop op))
10418 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
10419 s)
10420 (set (make-local-variable (cdr o))
10421 (car (read-from-string (match-string 1 s))))))))
10422
10423 (defun org-html-level-start (level title umax with-toc head-count)
10424 "Insert a new level in HTML export."
10425 (let ((l (1+ (max level umax))))
10426 (while (<= l org-level-max)
10427 (if (aref levels-open (1- l))
10428 (progn
10429 (org-html-level-close l)
10430 (aset levels-open (1- l) nil)))
10431 (setq l (1+ l)))
10432 (if (> level umax)
10433 (progn
10434 (if (aref levels-open (1- level))
10435 (insert "<li>" title "<p>\n")
10436 (aset levels-open (1- level) t)
10437 (insert "<ul><li>" title "<p>\n")))
10438 (if org-export-with-section-numbers
10439 (setq title (concat (org-section-number level) " " title)))
10440 (setq level (+ level 1))
10441 (if with-toc
10442 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
10443 level head-count title level))
10444 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
10445
10446 (defun org-html-level-close (&rest args)
10447 "Terminate one level in HTML export."
10448 (insert "</ul>"))
10449
10450 ;; Variable holding the vector with section numbers
10451 (defvar org-section-numbers (make-vector org-level-max 0))
10452
10453 (defun org-init-section-numbers ()
10454 "Initialize the vector for the section numbers."
10455 (let* ((level -1)
10456 (numbers (nreverse (org-split-string "" "\\.")))
10457 (depth (1- (length org-section-numbers)))
10458 (i depth) number-string)
10459 (while (>= i 0)
10460 (if (> i level)
10461 (aset org-section-numbers i 0)
10462 (setq number-string (or (car numbers) "0"))
10463 (if (string-match "\\`[A-Z]\\'" number-string)
10464 (aset org-section-numbers i
10465 (- (string-to-char number-string) ?A -1))
10466 (aset org-section-numbers i (string-to-number number-string)))
10467 (pop numbers))
10468 (setq i (1- i)))))
10469
10470 (defun org-section-number (&optional level)
10471 "Return a string with the current section number.
10472 When LEVEL is non-nil, increase section numbers on that level."
10473 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
10474 (when level
10475 (when (> level -1)
10476 (aset org-section-numbers
10477 level (1+ (aref org-section-numbers level))))
10478 (setq idx (1+ level))
10479 (while (<= idx depth)
10480 (if (not (= idx 1))
10481 (aset org-section-numbers idx 0))
10482 (setq idx (1+ idx))))
10483 (setq idx 0)
10484 (while (<= idx depth)
10485 (setq n (aref org-section-numbers idx))
10486 (setq string (concat string (if (not (string= string "")) "." "")
10487 (int-to-string n)))
10488 (setq idx (1+ idx)))
10489 (save-match-data
10490 (if (string-match "\\`\\([@0]\\.\\)+" string)
10491 (setq string (replace-match "" nil nil string)))
10492 (if (string-match "\\(\\.0\\)+\\'" string)
10493 (setq string (replace-match "" nil nil string))))
10494 string))
10495
10496
10497 (defun org-export-icalendar-this-file ()
10498 "Export current file as an iCalendar file.
10499 The iCalendar file will be located in the same directory as the Org-mode
10500 file, but with extension `.ics'."
10501 (interactive)
10502 (org-export-icalendar nil (buffer-file-name)))
10503
10504 ;;;###autoload
10505 (defun org-export-icalendar-all-agenda-files ()
10506 "Export all files in `org-agenda-files' to iCalendar .ics files.
10507 Each iCalendar file will be located in the same directory as the Org-mode
10508 file, but with extension `.ics'."
10509 (interactive)
10510 (apply 'org-export-icalendar nil org-agenda-files))
10511
10512 ;;;###autoload
10513 (defun org-export-icalendar-combine-agenda-files ()
10514 "Export all files in `org-agenda-files' to a single combined iCalendar file.
10515 The file is stored under the name `org-combined-agenda-icalendar-file'."
10516 (interactive)
10517 (apply 'org-export-icalendar t org-agenda-files))
10518
10519 (defun org-export-icalendar (combine &rest files)
10520 "Create iCalendar files for all elements of FILES.
10521 If COMBINE is non-nil, combine all calendar entries into a single large
10522 file and store it under the name `org-combined-agenda-icalendar-file'."
10523 (save-excursion
10524 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
10525 (when combine
10526 (setq ical-file org-combined-agenda-icalendar-file
10527 ical-buffer (org-get-agenda-file-buffer ical-file))
10528 (set-buffer ical-buffer) (erase-buffer))
10529 (while (setq file (pop files))
10530 (catch 'nextfile
10531 (org-check-agenda-file file)
10532 (unless combine
10533 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
10534 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
10535 (set-buffer ical-buffer) (erase-buffer))
10536 (set-buffer (org-get-agenda-file-buffer file))
10537 (setq category (or org-category
10538 (file-name-sans-extension
10539 (file-name-nondirectory (buffer-file-name)))))
10540 (if (symbolp category) (setq category (symbol-name category)))
10541 (let ((standard-output ical-buffer))
10542 (if combine
10543 (and (not started) (setq started t)
10544 (org-start-icalendar-file org-icalendar-combined-name))
10545 (org-start-icalendar-file category))
10546 (org-print-icalendar-entries combine category)
10547 (when (or (and combine (not files)) (not combine))
10548 (org-finish-icalendar-file)
10549 (set-buffer ical-buffer)
10550 (save-buffer)
10551 (run-hooks 'org-after-save-iCalendar-file-hook)))))
10552 (org-release-buffers org-agenda-new-buffers))))
10553
10554 (defvar org-after-save-iCalendar-file-hook nil
10555 "Hook run after an iCalendar file has been saved.
10556 The iCalendar buffer is still current when this hook is run.
10557 A good way to use this is to tell a desktop calenndar application to re-read
10558 the iCalendar file.")
10559
10560 (defun org-print-icalendar-entries (&optional combine category)
10561 "Print iCalendar entries for the current Org-mode file to `standard-output'.
10562 When COMBINE is non nil, add the category to each line."
10563 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
10564 (dts (org-ical-ts-to-string
10565 (format-time-string (cdr org-time-stamp-formats) (current-time))
10566 "DTSTART"))
10567 hd ts ts2 state (inc t) pos scheduledp deadlinep donep tmp pri)
10568 (save-excursion
10569 (goto-char (point-min))
10570 (while (re-search-forward org-ts-regexp nil t)
10571 (setq pos (match-beginning 0)
10572 ts (match-string 0)
10573 inc t
10574 hd (org-get-heading))
10575 (if (looking-at re2)
10576 (progn
10577 (goto-char (match-end 0))
10578 (setq ts2 (match-string 1) inc nil))
10579 (setq ts2 ts
10580 tmp (buffer-substring (max (point-min)
10581 (- pos org-ds-keyword-length))
10582 pos)
10583 deadlinep (string-match org-deadline-regexp tmp)
10584 scheduledp (string-match org-scheduled-regexp tmp)
10585 donep (org-entry-is-done-p)))
10586 (if (or (string-match org-tr-regexp hd)
10587 (string-match org-ts-regexp hd))
10588 (setq hd (replace-match "" t t hd)))
10589 (if combine
10590 (setq hd (concat hd " (category " category ")")))
10591 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
10592 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
10593 (princ (format "BEGIN:VEVENT
10594 %s
10595 %s
10596 SUMMARY:%s
10597 END:VEVENT\n"
10598 (org-ical-ts-to-string ts "DTSTART")
10599 (org-ical-ts-to-string ts2 "DTEND" inc)
10600 hd)))
10601 (when org-icalendar-include-todo
10602 (goto-char (point-min))
10603 (while (re-search-forward org-todo-line-regexp nil t)
10604 (setq state (match-string 1))
10605 (unless (equal state org-done-string)
10606 (setq hd (match-string 3))
10607 (if (string-match org-priority-regexp hd)
10608 (setq pri (string-to-char (match-string 2 hd))
10609 hd (concat (substring hd 0 (match-beginning 1))
10610 (substring hd (- (match-end 1)))))
10611 (setq pri org-default-priority))
10612 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
10613 (- org-lowest-priority ?A))))))
10614
10615 (princ (format "BEGIN:VTODO
10616 %s
10617 SUMMARY:%s
10618 SEQUENCE:1
10619 PRIORITY:%d
10620 END:VTODO\n"
10621 dts hd pri))))))))
10622
10623 (defun org-start-icalendar-file (name)
10624 "Start an iCalendar file by inserting the header."
10625 (let ((user user-full-name)
10626 (calname "something")
10627 (name (or name "unknown"))
10628 (timezone "Europe/Amsterdam")) ;; FIXME: How can I get the real timezone?
10629 (princ
10630 (format "BEGIN:VCALENDAR
10631 VERSION:2.0
10632 X-WR-CALNAME:%s
10633 PRODID:-//%s//Emacs with Org-mode//EN
10634 X-WR-TIMEZONE:%s
10635 CALSCALE:GREGORIAN\n" name user timezone))))
10636
10637 (defun org-finish-icalendar-file ()
10638 "Finish an iCalendar file by inserting the END statement."
10639 (princ "END:VCALENDAR\n"))
10640
10641 (defun org-ical-ts-to-string (s keyword &optional inc)
10642 "Take a time string S and convert it to iCalendar format.
10643 KEYWORD is added in front, to make a complete line like DTSTART....
10644 When INC is non-nil, increase the hour by two (if time string contains
10645 a time), or the day by one (if it does not contain a time)."
10646 (let ((t1 (org-parse-time-string s 'nodefault))
10647 t2 fmt have-time time)
10648 (if (and (car t1) (nth 1 t1) (nth 2 t1))
10649 (setq t2 t1 have-time t)
10650 (setq t2 (org-parse-time-string s)))
10651 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
10652 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
10653 (when inc
10654 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
10655 (setq time (encode-time s mi h d m y)))
10656 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
10657 (concat keyword (format-time-string fmt time))))
10658
10659
10660 ;;; Key bindings
10661
10662 ;; - Bindings in Org-mode map are currently
10663 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
10664 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
10665 ;; e (?) useful from outline-mode
10666 ;; i k @ expendable from outline-mode
10667 ;; 0123456789 ! %^& ()_{} " `' free
10668
10669 ;; Make `C-c C-x' a prefix key
10670 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
10671
10672 ;; TAB key with modifiers
10673 (define-key org-mode-map "\C-i" 'org-cycle)
10674 (define-key org-mode-map [(meta tab)] 'org-complete)
10675 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
10676 ;; The following line is necessary under Suse GNU/Linux
10677 (unless org-xemacs-p
10678 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
10679 (define-key org-mode-map [(shift tab)] 'org-shifttab)
10680
10681 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
10682 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
10683 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
10684 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
10685 (define-key org-mode-map [(meta return)] 'org-meta-return)
10686 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
10687 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
10688
10689 ;; Cursor keys with modifiers
10690 (define-key org-mode-map [(meta left)] 'org-metaleft)
10691 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
10692 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
10693 (define-key org-mode-map [(meta right)] 'org-metaright)
10694 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
10695 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
10696 (define-key org-mode-map [(meta up)] 'org-metaup)
10697 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
10698 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
10699 (define-key org-mode-map [(meta down)] 'org-metadown)
10700 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
10701 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
10702
10703 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
10704 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
10705 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
10706 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
10707 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
10708 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
10709 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
10710 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
10711 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
10712 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
10713 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
10714 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
10715 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
10716 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
10717 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
10718 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
10719
10720 ;; All the other keys
10721 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
10722 (define-key org-mode-map "\C-c\C-j" 'org-goto)
10723 (define-key org-mode-map "\C-c\C-t" 'org-todo)
10724 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
10725 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
10726 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
10727 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
10728 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
10729 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
10730 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
10731 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
10732 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
10733 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
10734 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
10735 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
10736 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
10737 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
10738 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
10739 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
10740 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
10741 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
10742 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
10743 (define-key org-mode-map "\C-c]" 'org-remove-file)
10744 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
10745 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
10746 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
10747 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
10748 (define-key org-mode-map "\C-m" 'org-return)
10749 (define-key org-mode-map "\C-c?" 'org-table-current-column)
10750 (define-key org-mode-map "\C-c " 'org-table-blank-field)
10751 (define-key org-mode-map "\C-c+" 'org-table-sum)
10752 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
10753 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
10754 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
10755 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
10756 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
10757 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
10758 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
10759 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
10760 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
10761 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
10762 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
10763 ;; OPML support is only an option for the future
10764 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
10765 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
10766 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
10767 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
10768 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
10769 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
10770 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
10771 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
10772 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
10773 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
10774 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
10775
10776 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
10777 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
10778 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
10779
10780 (defsubst org-table-p () (org-at-table-p))
10781
10782 (defun org-self-insert-command (N)
10783 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10784 If the cursor is in a table looking at whitespace, the whitespace is
10785 overwritten, and the table is not marked as requiring realignment."
10786 (interactive "p")
10787 (if (and (org-table-p)
10788 (or
10789 (and org-table-auto-blank-field
10790 (member last-command
10791 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
10792 (org-table-blank-field))
10793 t)
10794 (eq N 1)
10795 (looking-at "[^|\n]* +|"))
10796 (let (org-table-may-need-update)
10797 (goto-char (1- (match-end 0)))
10798 (delete-backward-char 1)
10799 (goto-char (match-beginning 0))
10800 (self-insert-command N))
10801 (setq org-table-may-need-update t)
10802 (self-insert-command N)))
10803
10804 ;; FIXME:
10805 ;; The following two functions might still be optimized to trigger
10806 ;; re-alignment less frequently.
10807
10808 (defun org-delete-backward-char (N)
10809 "Like `delete-backward-char', insert whitespace at field end in tables.
10810 When deleting backwards, in tables this function will insert whitespace in
10811 front of the next \"|\" separator, to keep the table aligned. The table will
10812 still be marked for re-alignment, because a narrow field may lead to a
10813 reduced column width."
10814 (interactive "p")
10815 (if (and (org-table-p)
10816 (eq N 1)
10817 (string-match "|" (buffer-substring (point-at-bol) (point)))
10818 (looking-at ".*?|"))
10819 (let ((pos (point)))
10820 (backward-delete-char N)
10821 (skip-chars-forward "^|")
10822 (insert " ")
10823 (goto-char (1- pos)))
10824 (backward-delete-char N)))
10825
10826 (defun org-delete-char (N)
10827 "Like `delete-char', but insert whitespace at field end in tables.
10828 When deleting characters, in tables this function will insert whitespace in
10829 front of the next \"|\" separator, to keep the table aligned. The table
10830 will still be marked for re-alignment, because a narrow field may lead to
10831 a reduced column width."
10832 (interactive "p")
10833 (if (and (org-table-p)
10834 (not (bolp))
10835 (not (= (char-after) ?|))
10836 (eq N 1))
10837 (if (looking-at ".*?|")
10838 (let ((pos (point)))
10839 (replace-match (concat
10840 (substring (match-string 0) 1 -1)
10841 " |"))
10842 (goto-char pos)))
10843 (delete-char N)))
10844
10845 ;; How to do this: Measure non-white length of current string
10846 ;; If equal to column width, we should realign.
10847
10848 (defun org-remap (map &rest commands)
10849 "In MAP, remap the functions given in COMMANDS.
10850 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
10851 (let (new old)
10852 (while commands
10853 (setq old (pop commands) new (pop commands))
10854 (if (fboundp 'command-remapping)
10855 (define-key map (vector 'remap old) new)
10856 (substitute-key-definition old new map global-map)))))
10857
10858 (when (eq org-enable-table-editor 'optimized)
10859 ;; If the user wants maximum table support, we need to hijack
10860 ;; some standard editing functions
10861 (org-remap org-mode-map
10862 'self-insert-command 'org-self-insert-command
10863 'delete-char 'org-delete-char
10864 'delete-backward-char 'org-delete-backward-char)
10865 (define-key org-mode-map "|" 'org-force-self-insert))
10866
10867 (defun org-shiftcursor-error ()
10868 "Throw an error because Shift-Cursor command was applied in wrong context."
10869 (error "This command is active in special context like tables, headlines or timestamps"))
10870
10871 (defun org-shifttab ()
10872 "Global visibility cycling or move to previous table field.
10873 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
10874 See the individual commands for more information."
10875 (interactive)
10876 (cond
10877 ((org-at-table-p) (org-table-previous-field))
10878 (t (org-cycle '(4)))))
10879
10880 (defun org-shiftmetaleft ()
10881 "Promote subtree or delete table column.
10882 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
10883 See the individual commands for more information."
10884 (interactive)
10885 (cond
10886 ((org-at-table-p) (org-table-delete-column))
10887 ((org-on-heading-p) (org-promote-subtree))
10888 ((org-at-item-p) (call-interactively 'org-outdent-item))
10889 (t (org-shiftcursor-error))))
10890
10891 (defun org-shiftmetaright ()
10892 "Demote subtree or insert table column.
10893 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
10894 See the individual commands for more information."
10895 (interactive)
10896 (cond
10897 ((org-at-table-p) (org-table-insert-column))
10898 ((org-on-heading-p) (org-demote-subtree))
10899 ((org-at-item-p) (call-interactively 'org-indent-item))
10900 (t (org-shiftcursor-error))))
10901
10902 (defun org-shiftmetaup (&optional arg)
10903 "Move subtree up or kill table row.
10904 Calls `org-move-subtree-up' or `org-table-kill-row' or
10905 `org-move-item-up' depending on context. See the individual commands
10906 for more information."
10907 (interactive "P")
10908 (cond
10909 ((org-at-table-p) (org-table-kill-row))
10910 ((org-on-heading-p) (org-move-subtree-up arg))
10911 ((org-at-item-p) (org-move-item-up arg))
10912 (t (org-shiftcursor-error))))
10913 (defun org-shiftmetadown (&optional arg)
10914 "Move subtree down or insert table row.
10915 Calls `org-move-subtree-down' or `org-table-insert-row' or
10916 `org-move-item-down', depending on context. See the individual
10917 commands for more information."
10918 (interactive "P")
10919 (cond
10920 ((org-at-table-p) (org-table-insert-row arg))
10921 ((org-on-heading-p) (org-move-subtree-down arg))
10922 ((org-at-item-p) (org-move-item-down arg))
10923 (t (org-shiftcursor-error))))
10924
10925 (defun org-metaleft (&optional arg)
10926 "Promote heading or move table column to left.
10927 Calls `org-do-promote' or `org-table-move-column', depending on context.
10928 With no specific context, calls the Emacs default `backward-word'.
10929 See the individual commands for more information."
10930 (interactive "P")
10931 (cond
10932 ((org-at-table-p) (org-table-move-column 'left))
10933 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
10934 (t (backward-word (prefix-numeric-value arg)))))
10935
10936 (defun org-metaright (&optional arg)
10937 "Demote subtree or move table column to right.
10938 Calls `org-do-demote' or `org-table-move-column', depending on context.
10939 With no specific context, calls the Emacs default `forward-word'.
10940 See the individual commands for more information."
10941 (interactive "P")
10942 (cond
10943 ((org-at-table-p) (org-table-move-column nil))
10944 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
10945 (t (forward-word (prefix-numeric-value arg)))))
10946
10947 (defun org-metaup (&optional arg)
10948 "Move subtree up or move table row up.
10949 Calls `org-move-subtree-up' or `org-table-move-row' or
10950 `org-move-item-up', depending on context. See the individual commands
10951 for more information."
10952 (interactive "P")
10953 (cond
10954 ((org-at-table-p) (org-table-move-row 'up))
10955 ((org-on-heading-p) (org-move-subtree-up arg))
10956 ((org-at-item-p) (org-move-item-up arg))
10957 (t (org-shiftcursor-error))))
10958
10959 (defun org-metadown (&optional arg)
10960 "Move subtree down or move table row down.
10961 Calls `org-move-subtree-down' or `org-table-move-row' or
10962 `org-move-item-down', depending on context. See the individual
10963 commands for more information."
10964 (interactive "P")
10965 (cond
10966 ((org-at-table-p) (org-table-move-row nil))
10967 ((org-on-heading-p) (org-move-subtree-down arg))
10968 ((org-at-item-p) (org-move-item-down arg))
10969 (t (org-shiftcursor-error))))
10970
10971 (defun org-shiftup (&optional arg)
10972 "Increase item in timestamp or increase priority of current item.
10973 Calls `org-timestamp-up' or `org-priority-up', depending on context.
10974 See the individual commands for more information."
10975 (interactive "P")
10976 (cond
10977 ((org-at-timestamp-p) (org-timestamp-up arg))
10978 (t (org-priority-up))))
10979
10980 (defun org-shiftdown (&optional arg)
10981 "Decrease item in timestamp or decrease priority of current item.
10982 Calls `org-timestamp-down' or `org-priority-down', depending on context.
10983 See the individual commands for more information."
10984 (interactive "P")
10985 (cond
10986 ((org-at-timestamp-p) (org-timestamp-down arg))
10987 (t (org-priority-down))))
10988
10989 (defun org-shiftright ()
10990 "Next TODO keyword or timestamp one day later, depending on context."
10991 (interactive)
10992 (cond
10993 ((org-at-timestamp-p) (org-timestamp-up-day))
10994 ((org-on-heading-p) (org-todo 'right))
10995 (t (org-shiftcursor-error))))
10996
10997 (defun org-shiftleft ()
10998 "Previous TODO keyword or timestamp one day earlier, depending on context."
10999 (interactive)
11000 (cond
11001 ((org-at-timestamp-p) (org-timestamp-down-day))
11002 ((org-on-heading-p) (org-todo 'left))
11003 (t (org-shiftcursor-error))))
11004
11005 (defun org-copy-special ()
11006 "Copy region in table or copy current subtree.
11007 Calls `org-table-copy' or `org-copy-subtree', depending on context.
11008 See the individual commands for more information."
11009 (interactive)
11010 (call-interactively
11011 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
11012
11013 (defun org-cut-special ()
11014 "Cut region in table or cut current subtree.
11015 Calls `org-table-copy' or `org-cut-subtree', depending on context.
11016 See the individual commands for more information."
11017 (interactive)
11018 (call-interactively
11019 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
11020
11021 (defun org-paste-special (arg)
11022 "Paste rectangular region into table, or past subtree relative to level.
11023 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
11024 See the individual commands for more information."
11025 (interactive "P")
11026 (if (org-at-table-p)
11027 (org-table-paste-rectangle)
11028 (org-paste-subtree arg)))
11029
11030 (defun org-ctrl-c-ctrl-c (&optional arg)
11031 "Call realign table, or recognize a table.el table, or update keywords.
11032 When the cursor is inside a table created by the table.el package,
11033 activate that table. Otherwise, if the cursor is at a normal table
11034 created with org.el, re-align that table. This command works even if
11035 the automatic table editor has been turned off.
11036 If the cursor is in one of the special #+KEYWORD lines, this triggers
11037 scanning the buffer for these lines and updating the information.
11038 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
11039 (interactive "P")
11040 (let ((org-enable-table-editor t))
11041 (cond
11042 ((org-at-table.el-p)
11043 (require 'table)
11044 (beginning-of-line 1)
11045 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
11046 (table-recognize-table))
11047 ((org-at-table-p)
11048 (org-table-maybe-eval-formula)
11049 (if arg
11050 (org-table-recalculate t)
11051 (org-table-maybe-recalculate-line))
11052 (org-table-align))
11053 ((org-at-item-p)
11054 (org-renumber-ordered-list (prefix-numeric-value arg)))
11055 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
11056 (cond
11057 ((equal (match-string 1) "TBLFM")
11058 ;; Recalculate the table before this line
11059 (save-excursion
11060 (beginning-of-line 1)
11061 (skip-chars-backward " \r\n\t")
11062 (if (org-at-table-p) (org-table-recalculate t))))
11063 (t
11064 (org-mode-restart))))
11065 ((org-region-active-p)
11066 (org-table-convert-region (region-beginning) (region-end) arg))
11067 ((condition-case nil
11068 (and (region-beginning) (region-end))
11069 (error nil))
11070 (if (y-or-n-p "Convert inactive region to table? ")
11071 (org-table-convert-region (region-beginning) (region-end) arg)
11072 (error "Abort")))
11073 (t (error "C-c C-c can do nothing useful at this location.")))))
11074
11075 (defun org-mode-restart ()
11076 "Restart Org-mode, to scan again for special lines.
11077 Also updates the keyword regular expressions."
11078 (interactive)
11079 (let ((org-inhibit-startup t)) (org-mode))
11080 (message "Org-mode restarted to refresh keyword and special line setup"))
11081
11082 (defun org-return ()
11083 "Goto next table row or insert a newline.
11084 Calls `org-table-next-row' or `newline', depending on context.
11085 See the individual commands for more information."
11086 (interactive)
11087 (cond
11088 ((org-at-table-p)
11089 (org-table-justify-field-maybe)
11090 (org-table-next-row))
11091 (t (newline))))
11092
11093 (defun org-meta-return (&optional arg)
11094 "Insert a new heading or wrap a region in a table.
11095 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
11096 See the individual commands for more information."
11097 (interactive "P")
11098 (cond
11099 ((org-at-table-p)
11100 (org-table-wrap-region arg))
11101 (t (org-insert-heading arg))))
11102
11103 ;;; Menu entries
11104
11105 ;; Define the Org-mode menus
11106 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
11107 '("Tbl"
11108 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
11109 ["Next Field" org-cycle (org-at-table-p)]
11110 ["Previous Field" org-shifttab (org-at-table-p)]
11111 ["Next Row" org-return (org-at-table-p)]
11112 "--"
11113 ["Blank Field" org-table-blank-field (org-at-table-p)]
11114 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
11115 "--"
11116 ("Column"
11117 ["Move Column Left" org-metaleft (org-at-table-p)]
11118 ["Move Column Right" org-metaright (org-at-table-p)]
11119 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
11120 ["Insert Column" org-shiftmetaright (org-at-table-p)])
11121 ("Row"
11122 ["Move Row Up" org-metaup (org-at-table-p)]
11123 ["Move Row Down" org-metadown (org-at-table-p)]
11124 ["Delete Row" org-shiftmetaup (org-at-table-p)]
11125 ["Insert Row" org-shiftmetadown (org-at-table-p)]
11126 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
11127 "--"
11128 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
11129 ("Rectangle"
11130 ["Copy Rectangle" org-copy-special (org-at-table-p)]
11131 ["Cut Rectangle" org-cut-special (org-at-table-p)]
11132 ["Paste Rectangle" org-paste-special (org-at-table-p)]
11133 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
11134 "--"
11135 ("Calculate"
11136 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
11137 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11138 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
11139 "--"
11140 ["Recalculate line" org-table-recalculate (org-at-table-p)]
11141 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
11142 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
11143 "--"
11144 ["Sum Column/Rectangle" org-table-sum
11145 (or (org-at-table-p) (org-region-active-p))]
11146 ["Which Column?" org-table-current-column (org-at-table-p)])
11147 ["Debug Formulas"
11148 (setq org-table-formula-debug (not org-table-formula-debug))
11149 :style toggle :selected org-table-formula-debug]
11150 "--"
11151 ["Invisible Vlines" org-table-toggle-vline-visibility
11152 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
11153 "--"
11154 ["Create" org-table-create (and (not (org-at-table-p))
11155 org-enable-table-editor)]
11156 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
11157 ["Import from File" org-table-import (not (org-at-table-p))]
11158 ["Export to File" org-table-export (org-at-table-p)]
11159 "--"
11160 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
11161
11162 (easy-menu-define org-org-menu org-mode-map "Org menu"
11163 '("Org"
11164 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
11165 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
11166 ["Sparse Tree" org-occur t]
11167 ["Show All" show-all t]
11168 "--"
11169 ["New Heading" org-insert-heading t]
11170 ("Navigate Headings"
11171 ["Up" outline-up-heading t]
11172 ["Next" outline-next-visible-heading t]
11173 ["Previous" outline-previous-visible-heading t]
11174 ["Next Same Level" outline-forward-same-level t]
11175 ["Previous Same Level" outline-backward-same-level t]
11176 "--"
11177 ["Jump" org-goto t])
11178 ("Edit Structure"
11179 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
11180 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
11181 "--"
11182 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
11183 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
11184 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
11185 "--"
11186 ["Promote Heading" org-metaleft (not (org-at-table-p))]
11187 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
11188 ["Demote Heading" org-metaright (not (org-at-table-p))]
11189 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
11190 "--"
11191 ["Archive Subtree" org-archive-subtree t])
11192 "--"
11193 ("TODO Lists"
11194 ["TODO/DONE/-" org-todo t]
11195 ["Show TODO Tree" org-show-todo-tree t]
11196 ["Global TODO list" org-todo-list t]
11197 "--"
11198 ["Set Priority" org-priority t]
11199 ["Priority Up" org-shiftup t]
11200 ["Priority Down" org-shiftdown t])
11201 ("Dates and Scheduling"
11202 ["Timestamp" org-time-stamp t]
11203 ["Timestamp (inactive)" org-time-stamp-inactive t]
11204 ("Change Date"
11205 ["1 Day Later" org-timestamp-up-day t]
11206 ["1 Day Earlier" org-timestamp-down-day t]
11207 ["1 ... Later" org-shiftup t]
11208 ["1 ... Earlier" org-shiftdown t])
11209 ["Compute Time Range" org-evaluate-time-range t]
11210 ["Schedule Item" org-schedule t]
11211 ["Deadline" org-deadline t]
11212 "--"
11213 ["Goto Calendar" org-goto-calendar t]
11214 ["Date from Calendar" org-date-from-calendar t])
11215 "--"
11216 ("Timeline/Agenda"
11217 ["Show TODO Tree this File" org-show-todo-tree t]
11218 ["Check Deadlines this File" org-check-deadlines t]
11219 ["Timeline Current File" org-timeline t]
11220 "--"
11221 ["Agenda" org-agenda t])
11222 ("File List for Agenda")
11223 "--"
11224 ("Hyperlinks"
11225 ["Store Link (Global)" org-store-link t]
11226 ["Insert Link" org-insert-link t]
11227 ["Follow Link" org-open-at-point t])
11228 "--"
11229 ("Export"
11230 ["ASCII" org-export-as-ascii t]
11231 ["Extract Visible Text" org-export-copy-visible t]
11232 ["HTML" org-export-as-html t]
11233 ["HTML and Open" org-export-as-html-and-open t]
11234 ; ["OPML" org-export-as-opml nil]
11235 "--"
11236 ["iCalendar this file" org-export-icalendar-this-file t]
11237 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
11238 :active t :keys "C-c C-x C-i"]
11239 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
11240 "--"
11241 ["Option Template" org-insert-export-options-template t]
11242 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
11243 "--"
11244 ("Documentation"
11245 ["Show Version" org-version t]
11246 ["Info Documentation" org-info t])
11247 ("Customize"
11248 ["Browse Org Group" org-customize t]
11249 "--"
11250 ["Build Full Customize Menu" org-create-customize-menu
11251 (fboundp 'customize-menu-create)])
11252 "--"
11253 ["Refresh setup" org-mode-restart t]
11254 ))
11255
11256 (defun org-info (&optional node)
11257 "Read documentation for Org-mode in the info system.
11258 With optional NODE, go directly to that node."
11259 (interactive)
11260 (require 'info)
11261 (Info-goto-node (format "(org)%s" (or node ""))))
11262
11263 (defun org-install-agenda-files-menu ()
11264 (easy-menu-change
11265 '("Org") "File List for Agenda"
11266 (append
11267 (list
11268 ["Edit File List" (customize-variable 'org-agenda-files) t]
11269 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
11270 ["Remove Current File from List" org-remove-file t]
11271 ["Cycle through agenda files" org-cycle-agenda-files t]
11272 "--")
11273 (mapcar 'org-file-menu-entry org-agenda-files))))
11274
11275 ;;; Documentation
11276
11277 (defun org-customize ()
11278 "Call the customize function with org as argument."
11279 (interactive)
11280 (customize-browse 'org))
11281
11282 (defun org-create-customize-menu ()
11283 "Create a full customization menu for Org-mode, insert it into the menu."
11284 (interactive)
11285 (if (fboundp 'customize-menu-create)
11286 (progn
11287 (easy-menu-change
11288 '("Org") "Customize"
11289 `(["Browse Org group" org-customize t]
11290 "--"
11291 ,(customize-menu-create 'org)
11292 ["Set" Custom-set t]
11293 ["Save" Custom-save t]
11294 ["Reset to Current" Custom-reset-current t]
11295 ["Reset to Saved" Custom-reset-saved t]
11296 ["Reset to Standard Settings" Custom-reset-standard t]))
11297 (message "\"Org\"-menu now contains full customization menu"))
11298 (error "Cannot expand menu (outdated version of cus-edit.el)")))
11299
11300 ;;; Miscellaneous stuff
11301
11302 (defun org-move-line-down (arg)
11303 "Move the current line down. With prefix argument, move it past ARG lines."
11304 (interactive "p")
11305 (let ((col (current-column))
11306 beg end pos)
11307 (beginning-of-line 1) (setq beg (point))
11308 (beginning-of-line 2) (setq end (point))
11309 (beginning-of-line (+ 1 arg))
11310 (setq pos (move-marker (make-marker) (point)))
11311 (insert (delete-and-extract-region beg end))
11312 (goto-char pos)
11313 (move-to-column col)))
11314
11315 (defun org-move-line-up (arg)
11316 "Move the current line up. With prefix argument, move it past ARG lines."
11317 (interactive "p")
11318 (let ((col (current-column))
11319 beg end pos)
11320 (beginning-of-line 1) (setq beg (point))
11321 (beginning-of-line 2) (setq end (point))
11322 (beginning-of-line (- arg))
11323 (setq pos (move-marker (make-marker) (point)))
11324 (insert (delete-and-extract-region beg end))
11325 (goto-char pos)
11326 (move-to-column col)))
11327
11328 ;; Paragraph filling stuff.
11329 ;; We want this to be just right, so use the full arsenal.
11330 ;; FIXME: This very likely does not work correctly for XEmacs, because the
11331 ;; filladapt package works slightly differently.
11332
11333 (defun org-set-autofill-regexps ()
11334 (interactive)
11335 ;; In the paragraph separator we include headlines, because filling
11336 ;; text in a line directly attached to a headline would otherwise
11337 ;; fill the headline as well.
11338 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
11339 ;; The paragraph starter includes hand-formatted lists.
11340 (set (make-local-variable 'paragraph-start)
11341 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
11342 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
11343 ;; But only if the user has not turned off tables or fixed-width regions
11344 (set (make-local-variable 'auto-fill-inhibit-regexp)
11345 (concat "\\*\\|#"
11346 (if (or org-enable-table-editor org-enable-fixed-width-editor)
11347 (concat
11348 "\\|[ \t]*["
11349 (if org-enable-table-editor "|" "")
11350 (if org-enable-fixed-width-editor ":" "")
11351 "]"))))
11352 ;; We use our own fill-paragraph function, to make sure that tables
11353 ;; and fixed-width regions are not wrapped. That function will pass
11354 ;; through to `fill-paragraph' when appropriate.
11355 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
11356 ;; Adaptive filling: To get full control, first make sure that
11357 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
11358 (setq adaptive-fill-regexp "\000")
11359 (setq adaptive-fill-function 'org-adaptive-fill-function))
11360
11361 (defun org-fill-paragraph (&optional justify)
11362 "Re-align a table, pass through to fill-paragraph if no table."
11363 (let ((table-p (org-at-table-p))
11364 (table.el-p (org-at-table.el-p)))
11365 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
11366 (table.el-p t) ; skip table.el tables
11367 (table-p (org-table-align) t) ; align org-mode tables
11368 (t nil)))) ; call paragraph-fill
11369
11370 ;; For reference, this is the default value of adaptive-fill-regexp
11371 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
11372
11373 (defun org-adaptive-fill-function ()
11374 "Return a fill prefix for org-mode files.
11375 In particular, this makes sure hanging paragraphs for hand-formatted lists
11376 work correctly."
11377 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
11378 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11379
11380 ;; Functions needed for Emacs/XEmacs region compatibility
11381
11382 (defun org-region-active-p ()
11383 "Is `transient-mark-mode' on and the region active?
11384 Works on both Emacs and XEmacs."
11385 (if org-ignore-region
11386 nil
11387 (if org-xemacs-p
11388 (and zmacs-regions (region-active-p))
11389 (and transient-mark-mode mark-active))))
11390
11391 (defun org-add-to-invisibility-spec (arg)
11392 "Add elements to `buffer-invisibility-spec'.
11393 See documentation for `buffer-invisibility-spec' for the kind of elements
11394 that can be added."
11395 (cond
11396 ((fboundp 'add-to-invisibility-spec)
11397 (add-to-invisibility-spec arg))
11398 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
11399 (setq buffer-invisibility-spec (list arg)))
11400 (t
11401 (setq buffer-invisibility-spec
11402 (cons arg buffer-invisibility-spec)))))
11403
11404 (defun org-remove-from-invisibility-spec (arg)
11405 "Remove elements from `buffer-invisibility-spec'."
11406 (if (fboundp 'remove-from-invisibility-spec)
11407 (remove-from-invisibility-spec arg)
11408 (if (consp buffer-invisibility-spec)
11409 (setq buffer-invisibility-spec
11410 (delete arg buffer-invisibility-spec)))))
11411
11412 (defun org-in-invisibility-spec-p (arg)
11413 "Is ARG a member of `buffer-invisibility-spec'?."
11414 (if (consp buffer-invisibility-spec)
11415 (member arg buffer-invisibility-spec)
11416 nil))
11417
11418 (defun org-image-file-name-regexp ()
11419 "Return regexp matching the file names of images."
11420 (if (fboundp 'image-file-name-regexp)
11421 (image-file-name-regexp)
11422 (let ((image-file-name-extensions
11423 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
11424 "xbm" "xpm" "pbm" "pgm" "ppm")))
11425 (concat "\\."
11426 (regexp-opt (nconc (mapcar 'upcase
11427 image-file-name-extensions)
11428 image-file-name-extensions)
11429 t)
11430 "\\'"))))
11431
11432 ;; Functions needed for compatibility with old outline.el
11433
11434 ;; The following functions capture almost the entire compatibility code
11435 ;; between the different versions of outline-mode. The only other place
11436 ;; where this is important are the font-lock-keywords. Search for
11437 ;; `org-noutline-p' to find it.
11438
11439 ;; C-a should go to the beginning of a *visible* line, also in the
11440 ;; new outline.el. I guess this should be patched into Emacs?
11441 (defun org-beginning-of-line ()
11442 "Go to the beginning of the current line. If that is invisible, continue
11443 to a visible line beginning. This makes the function of C-a more intuitive."
11444 (interactive)
11445 (beginning-of-line 1)
11446 (if (bobp)
11447 nil
11448 (backward-char 1)
11449 (if (org-invisible-p)
11450 (while (and (not (bobp)) (org-invisible-p))
11451 (backward-char 1)
11452 (beginning-of-line 1))
11453 (forward-char 1))))
11454 (when org-noutline-p
11455 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
11456
11457 (defun org-invisible-p ()
11458 "Check if point is at a character currently not visible."
11459 (if org-noutline-p
11460 ;; Early versions of noutline don't have `outline-invisible-p'.
11461 (if (fboundp 'outline-invisible-p)
11462 (outline-invisible-p)
11463 (get-char-property (point) 'invisible))
11464 (save-excursion
11465 (skip-chars-backward "^\r\n")
11466 (equal (char-before) ?\r))))
11467
11468 (defun org-back-to-heading (&optional invisible-ok)
11469 "Move to previous heading line, or beg of this line if it's a heading.
11470 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
11471 (if org-noutline-p
11472 (outline-back-to-heading invisible-ok)
11473 (if (looking-at outline-regexp)
11474 t
11475 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
11476 outline-regexp)
11477 nil t)
11478 (if invisible-ok
11479 (progn (goto-char (match-end 1))
11480 (looking-at outline-regexp)))
11481 (error "Before first heading")))))
11482
11483 (defun org-on-heading-p (&optional invisible-ok)
11484 "Return t if point is on a (visible) heading line.
11485 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
11486 (if org-noutline-p
11487 (outline-on-heading-p 'invisible-ok)
11488 (save-excursion
11489 (skip-chars-backward "^\n\r")
11490 (and (looking-at outline-regexp)
11491 (or invisible-ok
11492 (bobp)
11493 (equal (char-before) ?\n))))))
11494
11495 (defun org-up-heading-all (arg)
11496 "Move to the heading line of which the present line is a subheading.
11497 This function considers both visible and invisible heading lines.
11498 With argument, move up ARG levels."
11499 (if org-noutline-p
11500 (if (fboundp 'outline-up-heading-all)
11501 (outline-up-heading-all arg) ; emacs 21 version of outline.el
11502 (outline-up-heading arg t)) ; emacs 22 version of outline.el
11503 (org-back-to-heading t)
11504 (looking-at outline-regexp)
11505 (if (<= (- (match-end 0) (match-beginning 0)) arg)
11506 (error "Cannot move up %d levels" arg)
11507 (re-search-backward
11508 (concat "[\n\r]" (regexp-quote
11509 (make-string (- (match-end 0) (match-beginning 0) arg)
11510 ?*))
11511 "[^*]"))
11512 (forward-char 1))))
11513
11514 (defun org-show-hidden-entry ()
11515 "Show an entry where even the heading is hidden."
11516 (save-excursion
11517 (if (not org-noutline-p)
11518 (progn
11519 (org-back-to-heading t)
11520 (org-flag-heading nil)))
11521 (org-show-entry)))
11522
11523 (defun org-check-occur-regexp (regexp)
11524 "If REGEXP starts with \"^\", modify it to check for \\r as well.
11525 Of course, only for the old outline mode."
11526 (if org-noutline-p
11527 regexp
11528 (if (string-match "^\\^" regexp)
11529 (concat "[\n\r]" (substring regexp 1))
11530 regexp)))
11531
11532 (defun org-flag-heading (flag &optional entry)
11533 "Flag the current heading. FLAG non-nil means make invisible.
11534 When ENTRY is non-nil, show the entire entry."
11535 (save-excursion
11536 (org-back-to-heading t)
11537 (if (not org-noutline-p)
11538 ;; Make the current headline visible
11539 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
11540 ;; Check if we should show the entire entry
11541 (if entry
11542 (progn
11543 (org-show-entry)
11544 (save-excursion ;; FIXME: Is this the fix for points in the -|
11545 ;; middle of text? |
11546 (and (outline-next-heading) ;; |
11547 (org-flag-heading nil)))) ; show the next heading _|
11548 (outline-flag-region (max 1 (1- (point)))
11549 (save-excursion (outline-end-of-heading) (point))
11550 (if org-noutline-p
11551 flag
11552 (if flag ?\r ?\n))))))
11553
11554 (defun org-show-subtree ()
11555 "Show everything after this heading at deeper levels."
11556 (outline-flag-region
11557 (point)
11558 (save-excursion
11559 (outline-end-of-subtree) (outline-next-heading) (point))
11560 (if org-noutline-p nil ?\n)))
11561
11562 (defun org-show-entry ()
11563 "Show the body directly following this heading.
11564 Show the heading too, if it is currently invisible."
11565 (interactive)
11566 (save-excursion
11567 (org-back-to-heading t)
11568 (outline-flag-region
11569 (1- (point))
11570 (save-excursion
11571 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
11572 (or (match-beginning 1) (point-max)))
11573 (if org-noutline-p nil ?\n))))
11574
11575
11576 (defun org-make-options-regexp (kwds)
11577 "Make a regular expression for keyword lines."
11578 (concat
11579 (if org-noutline-p "^" "[\n\r]")
11580 "#?[ \t]*\\+\\("
11581 (mapconcat 'regexp-quote kwds "\\|")
11582 "\\):[ \t]*"
11583 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
11584
11585 ;; Make `bookmark-jump' show the jump location if it was hidden.
11586 (eval-after-load "bookmark"
11587 '(if (boundp 'bookmark-after-jump-hook)
11588 ;; We can use the hook
11589 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
11590 ;; Hook not available, use advice
11591 (defadvice bookmark-jump (after org-make-visible activate)
11592 "Make the position visible."
11593 (org-bookmark-jump-unhide))))
11594
11595 (defun org-bookmark-jump-unhide ()
11596 "Unhide the current position, to show the bookmark location."
11597 (and (eq major-mode 'org-mode)
11598 (or (org-invisible-p)
11599 (save-excursion (goto-char (max (point-min) (1- (point))))
11600 (org-invisible-p)))
11601 (org-show-hierarchy-above)))
11602
11603 ;;; Finish up
11604
11605 (provide 'org)
11606
11607 (run-hooks 'org-load-hook)
11608
11609 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
11610 ;;; org.el ends here
11611
11612