]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-export-as-xoxo): Fix call to `indent-region'.
[gnu-emacs] / lisp / textmodes / org.el
1 ;;; org.el --- Outline-based notes management and organize
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 4.26
9 ;;
10 ;; This file is part of GNU Emacs.
11 ;;
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;
28 ;;; Commentary:
29 ;;
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
32 ;;
33 ;; Org-mode develops organizational tasks around a NOTES file that contains
34 ;; information about projects as plain text. Org-mode is implemented on top
35 ;; of outline-mode - ideal to keep the content of large files well structured.
36 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
37 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
38 ;; calendar. Tables are easily created with a built-in table editor. Plain
39 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
40 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
41 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
42 ;; of it) can be exported as a structured ASCII file, or as HTML.
43 ;;
44 ;; Installation
45 ;; ------------
46 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
47 ;; only need to copy the following lines to your .emacs file. The last two
48 ;; lines define *global* keys for the commands `org-store-link' and
49 ;; `org-agenda' - please choose suitable keys yourself.
50 ;;
51 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
52 ;; (define-key global-map "\C-cl" 'org-store-link)
53 ;; (define-key global-map "\C-ca" 'org-agenda)
54 ;;
55 ;; If you have downloaded Org-mode from the Web, you must byte-compile
56 ;; org.el and put it on your load path. In addition to the Emacs Lisp
57 ;; lines above, you also need to add the following lines to .emacs:
58 ;;
59 ;; (autoload 'org-mode "org" "Org mode" t)
60 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
61 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
62 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
63 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
64 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
65 ;;
66 ;; This setup will put all files with extension ".org" into Org-mode. As
67 ;; an alternative, make the first line of a file look like this:
68 ;;
69 ;; MY PROJECTS -*- mode: org; -*-
70 ;;
71 ;; which will select Org-mode for this buffer no matter what the file's
72 ;; name is.
73 ;;
74 ;; Documentation
75 ;; -------------
76 ;; The documentation of Org-mode can be found in the TeXInfo file. The
77 ;; distribution also contains a PDF version of it. At the homepage of
78 ;; Org-mode, you can read the same text online as HTML. There is also an
79 ;; excellent reference card made by Philip Rooke. This card can be found
80 ;; in the etc/ directory of Emacs 22.
81 ;;
82 ;; Changes since version 4.10:
83 ;; ---------------------------
84 ;; Version 4.26
85 ;; - Bug fixes.
86 ;;
87 ;; Version 4.25
88 ;; - Revision of the font-lock faces section, with better tty support.
89 ;; - TODO keywords in Agenda buffer are fontified.
90 ;; - Export converts links between .org files to links between .html files.
91 ;; - Better support for bold/italic/underline emphasis.
92 ;;
93 ;; Version 4.24
94 ;; - Bug fixes.
95 ;;
96 ;; Version 4.23
97 ;; - Bug fixes.
98 ;;
99 ;; Version 4.22
100 ;; - Bug fixes.
101 ;; - In agenda buffer, mouse-1 no longer follows link.
102 ;; See `org-agenda-mouse-1-follows-link' and `org-mouse-1-follows-link'.
103 ;;
104 ;; Version 4.20
105 ;; - Links use now the [[link][description]] format by default.
106 ;; When inserting links, the user is prompted for a description.
107 ;; - If a link has a description, only the description is displayed
108 ;; the link part is hidden. Use C-c C-l to edit the link part.
109 ;; - TAGS are now bold, but in the same color as the headline.
110 ;; - The width of a table column can be limited by using a field "<N>".
111 ;; - New structure for the customization tree.
112 ;; - Bug fixes.
113 ;;
114 ;; Version 4.13
115 ;; - The list of agenda files can be maintainted in an external file.
116 ;; - Bug fixes.
117 ;;
118 ;; Version 4.12
119 ;; - Templates for remember buffer. Note that the remember setup changes.
120 ;; To set up templates, see `org-remember-templates'.
121 ;; - The time in new time stamps can be rounded, see new option
122 ;; `org-time-stamp-rounding-minutes'.
123 ;; - Bug fixes (there are *always* more bugs).
124 ;;
125 ;;; Code:
126
127 (eval-when-compile
128 (require 'cl)
129 (require 'calendar))
130 (require 'outline)
131 (require 'time-date)
132 (require 'easymenu)
133
134 (defvar calc-embedded-close-formula) ; defined by the calc package
135 (defvar calc-embedded-open-formula) ; defined by the calc package
136 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
137
138 ;;; Customization variables
139
140 (defvar org-version "4.26"
141 "The version number of the file org.el.")
142 (defun org-version ()
143 (interactive)
144 (message "Org-mode version %s" org-version))
145
146 ;; The following constant is for compatibility with different versions
147 ;; of outline.el.
148 (defconst org-noutline-p (featurep 'noutline)
149 "Are we using the new outline mode?")
150 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
151 (defconst org-format-transports-properties-p
152 (let ((x "a"))
153 (add-text-properties 0 1 '(test t) x)
154 (get-text-property 0 'test (format "%s" x)))
155 "Does format transport text properties?")
156
157 (defgroup org nil
158 "Outline-based notes management and organizer."
159 :tag "Org"
160 :group 'outlines
161 :group 'hypermedia
162 :group 'calendar)
163
164 (defgroup org-startup nil
165 "Options concerning startup of Org-mode."
166 :tag "Org Startup"
167 :group 'org)
168
169 (defcustom org-startup-folded t
170 "Non-nil means, entering Org-mode will switch to OVERVIEW.
171 This can also be configured on a per-file basis by adding one of
172 the following lines anywhere in the buffer:
173
174 #+STARTUP: fold
175 #+STARTUP: nofold
176 #+STARTUP: content"
177 :group 'org-startup
178 :type '(choice
179 (const :tag "nofold: show all" nil)
180 (const :tag "fold: overview" t)
181 (const :tag "content: all headlines" content)))
182
183 (defcustom org-startup-truncated t
184 "Non-nil means, entering Org-mode will set `truncate-lines'.
185 This is useful since some lines containing links can be very long and
186 uninteresting. Also tables look terrible when wrapped."
187 :group 'org-startup
188 :type 'boolean)
189
190 (defcustom org-startup-align-all-tables nil
191 "Non-nil means, align all tables when visiting a file.
192 This is useful when the column width in tables is forced with <N> cookies
193 in table fields. Such tables will look correct only after the first re-align.
194 This can also be configured on a per-file basis by adding one of
195 the following lines anywhere in the buffer:
196 #+STARTUP: align
197 #+STARTUP: noalign"
198 :group 'org-startup
199 :type 'boolean)
200
201 (defcustom org-startup-with-deadline-check nil
202 "Non-nil means, entering Org-mode will run the deadline check.
203 This means, if you start editing an org file, you will get an
204 immediate reminder of any due deadlines.
205 This can also be configured on a per-file basis by adding one of
206 the following lines anywhere in the buffer:
207 #+STARTUP: dlcheck
208 #+STARTUP: nodlcheck"
209 :group 'org-startup
210 :type 'boolean)
211
212 (defcustom org-insert-mode-line-in-empty-file nil
213 "Non-nil means insert the first line setting Org-mode in empty files.
214 When the function `org-mode' is called interactively in an empty file, this
215 normally means that the file name does not automatically trigger Org-mode.
216 To ensure that the file will always be in Org-mode in the future, a
217 line enforcing Org-mode will be inserted into the buffer, if this option
218 has been set."
219 :group 'org-startup
220 :type 'boolean)
221
222 (defcustom org-CUA-compatible nil
223 "Non-nil means use alternative key bindings for S-<cursor movement>.
224 Org-mode used S-<cursor movement> for changing timestamps and priorities.
225 S-<cursor movement> is also used for example by `CUA-mode' to select text.
226 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
227 alternative bindings. Setting this variable to t will replace the following
228 keys both in Org-mode and in the Org-agenda buffer.
229
230 S-RET -> C-S-RET
231 S-up -> M-p
232 S-down -> M-n
233 S-left -> M--
234 S-right -> M-+
235
236 If you do not like the alternative keys, take a look at the variable
237 `org-disputed-keys'.
238
239 This option is only relevant at load-time of Org-mode. Changing it requires
240 a restart of Emacs to become effective."
241 :group 'org-startup
242 :type 'boolean)
243
244 (defvar org-disputed-keys
245 '((S-up [(shift up)] [(meta ?p)])
246 (S-down [(shift down)] [(meta ?n)])
247 (S-left [(shift left)] [(meta ?-)])
248 (S-right [(shift right)] [(meta ?+)])
249 (S-return [(shift return)] [(control shift return)]))
250 "Keys for which Org-mode and other modes compete.
251 This is an alist, cars are symbols for lookup, 1st element is the default key,
252 second element will be used when `org-CUA-compatible' is t.")
253
254 (defun org-key (key)
255 "Select a key according to `org-CUA-compatible'."
256 (nth (if org-CUA-compatible 2 1)
257 (or (assq key org-disputed-keys)
258 (error "Invalid Key %s in `org-key'" key))))
259
260 (defcustom org-ellipsis nil
261 "The ellipsis to use in the Org-mode outline.
262 When nil, just use the standard three dots. When a string, use that instead,
263 and just in Org-mode (which will then use its own display table).
264 Changing this requires executing `M-x org-mode' in a buffer to become
265 effective."
266 :group 'org-startup
267 :type '(choice (const :tag "Default" nil)
268 (string :tag "String" :value "...#")))
269
270 (defvar org-display-table nil
271 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
272
273 (defgroup org-keywords nil
274 "Keywords in Org-mode."
275 :tag "Org Keywords"
276 :group 'org)
277
278 (defcustom org-deadline-string "DEADLINE:"
279 "String to mark deadline entries.
280 A deadline is this string, followed by a time stamp. Should be a word,
281 terminated by a colon. You can insert a schedule keyword and
282 a timestamp with \\[org-deadline].
283 Changes become only effective after restarting Emacs."
284 :group 'org-keywords
285 :type 'string)
286
287 (defcustom org-scheduled-string "SCHEDULED:"
288 "String to mark scheduled TODO entries.
289 A schedule is this string, followed by a time stamp. Should be a word,
290 terminated by a colon. You can insert a schedule keyword and
291 a timestamp with \\[org-schedule].
292 Changes become only effective after restarting Emacs."
293 :group 'org-keywords
294 :type 'string)
295
296 (defcustom org-closed-string "CLOSED:"
297 "String used as the prefix for timestamps logging closing a TODO entry."
298 :group 'org-keywords
299 :type 'string)
300
301 (defcustom org-comment-string "COMMENT"
302 "Entries starting with this keyword will never be exported.
303 An entry can be toggled between COMMENT and normal with
304 \\[org-toggle-comment].
305 Changes become only effective after restarting Emacs."
306 :group 'org-keywords
307 :type 'string)
308
309 (defcustom org-quote-string "QUOTE"
310 "Entries starting with this keyword will be exported in fixed-width font.
311 Quoting applies only to the text in the entry following the headline, and does
312 not extend beyond the next headline, even if that is lower level.
313 An entry can be toggled between QUOTE and normal with
314 \\[org-toggle-fixed-width-section]."
315 :group 'org-keywords
316 :type 'string)
317
318 (defgroup org-structure nil
319 "Options concerning the general structure of Org-mode files."
320 :tag "Org Structure"
321 :group 'org)
322
323 (defgroup org-cycle nil
324 "Options concerning visibility cycling in Org-mode."
325 :tag "Org Cycle"
326 :group 'org-structure)
327
328 (defcustom org-cycle-emulate-tab t
329 "Where should `org-cycle' emulate TAB.
330 nil Never
331 white Only in completely white lines
332 t Everywhere except in headlines"
333 :group 'org-cycle
334 :type '(choice (const :tag "Never" nil)
335 (const :tag "Only in completely white lines" white)
336 (const :tag "Everywhere except in headlines" t)
337 ))
338
339 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
340 "Hook that is run after `org-cycle' has changed the buffer visibility.
341 The function(s) in this hook must accept a single argument which indicates
342 the new state that was set by the most recent `org-cycle' command. The
343 argument is a symbol. After a global state change, it can have the values
344 `overview', `content', or `all'. After a local state change, it can have
345 the values `folded', `children', or `subtree'."
346 :group 'org-cycle
347 :type 'hook)
348
349 (defgroup org-edit-structure nil
350 "Options concerning structure editing in Org-mode."
351 :tag "Org Edit Structure"
352 :group 'org-structure)
353
354 (defcustom org-odd-levels-only nil
355 "Non-nil means, skip even levels and only use odd levels for the outline.
356 This has the effect that two stars are being added/taken away in
357 promotion/demotion commands. It also influences how levels are
358 handled by the exporters.
359 Changing it requires restart of `font-lock-mode' to become effective
360 for fontification also in regions already fontified.
361 You may also set this on a per-file basis by adding one of the following
362 lines to the buffer:
363
364 #+STARTUP: odd
365 #+STARTUP: oddeven"
366 :group 'org-edit-structure
367 :group 'org-font-lock
368 :type 'boolean)
369
370 (defcustom org-adapt-indentation t
371 "Non-nil means, adapt indentation when promoting and demoting.
372 When this is set and the *entire* text in an entry is indented, the
373 indentation is increased by one space in a demotion command, and
374 decreased by one in a promotion command. If any line in the entry
375 body starts at column 0, indentation is not changed at all."
376 :group 'org-edit-structure
377 :type 'boolean)
378
379 (defcustom org-enable-fixed-width-editor t
380 "Non-nil means, lines starting with \":\" are treated as fixed-width.
381 This currently only means, they are never auto-wrapped.
382 When nil, such lines will be treated like ordinary lines.
383 See also the QUOTE keyword."
384 :group 'org-edit-structure
385 :type 'boolean)
386
387 (defgroup org-sparse-trees nil
388 "Options concerning sparse trees in Org-mode."
389 :tag "Org Sparse Trees"
390 :group 'org-structure)
391
392 (defcustom org-highlight-sparse-tree-matches t
393 "Non-nil means, highlight all matches that define a sparse tree.
394 The highlights will automatically disappear the next time the buffer is
395 changed by an edit command."
396 :group 'org-sparse-trees
397 :type 'boolean)
398
399 (defcustom org-show-hierarchy-above t
400 "Non-nil means, show full hierarchy when showing a spot in the tree.
401 Turning this off makes sparse trees more compact, but also less clear."
402 :group 'org-sparse-trees
403 :type 'boolean)
404
405 (defcustom org-show-following-heading t
406 "Non-nil means, show heading following match in `org-occur'.
407 When doing an `org-occur' it is useful to show the headline which
408 follows the match, even if they do not match the regexp. This makes it
409 easier to edit directly inside the sparse tree. However, if you use
410 `org-occur' mainly as an overview, the following headlines are
411 unnecessary clutter."
412 :group 'org-sparse-trees
413 :type 'boolean)
414
415 (defcustom org-occur-hook '(org-first-headline-recenter)
416 "Hook that is run after `org-occur' has constructed a sparse tree.
417 This can be used to recenter the window to show as much of the structure
418 as possible."
419 :group 'org-sparse-trees
420 :type 'hook)
421
422 (defgroup org-plain-lists nil
423 "Options concerning plain lists in Org-mode."
424 :tag "Org Plain lists"
425 :group 'org-structure)
426
427 (defcustom org-cycle-include-plain-lists nil
428 "Non-nil means, include plain lists into visibility cycling.
429 This means that during cycling, plain list items will *temporarily* be
430 interpreted as outline headlines with a level given by 1000+i where i is the
431 indentation of the bullet. In all other operations, plain list items are
432 not seen as headlines. For example, you cannot assign a TODO keyword to
433 such an item."
434 :group 'org-plain-lists
435 :type 'boolean)
436
437
438 (defcustom org-plain-list-ordered-item-terminator t
439 "The character that makes a line with leading number an ordered list item.
440 Valid values are ?. and ?\). To get both terminators, use t. While
441 ?. may look nicer, it creates the danger that a line with leading
442 number may be incorrectly interpreted as an item. ?\) therefore is
443 the safe choice."
444 :group 'org-plain-lists
445 :type '(choice (const :tag "dot like in \"2.\"" ?.)
446 (const :tag "paren like in \"2)\"" ?\))
447 (const :tab "both" t)))
448
449 (defcustom org-auto-renumber-ordered-lists t
450 "Non-nil means, automatically renumber ordered plain lists.
451 Renumbering happens when the sequence have been changed with
452 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
453 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
454 :group 'org-plain-lists
455 :type 'boolean)
456
457 (defgroup org-archive nil
458 "Options concerning archiving in Org-mode."
459 :tag "Org Archive"
460 :group 'org-structure)
461
462 (defcustom org-archive-location "%s_archive::"
463 "The location where subtrees should be archived.
464 This string consists of two parts, separated by a double-colon.
465
466 The first part is a file name - when omitted, archiving happens in the same
467 file. %s will be replaced by the current file name (without directory part).
468 Archiving to a different file is useful to keep archived entries from
469 contributing to the Org-mode Agenda.
470
471 The part after the double colon is a headline. The archived entries will be
472 filed under that headline. When omitted, the subtrees are simply filed away
473 at the end of the file, as top-level entries.
474
475 Here are a few examples:
476 \"%s_archive::\"
477 If the current file is Projects.org, archive in file
478 Projects.org_archive, as top-level trees. This is the default.
479
480 \"::* Archived Tasks\"
481 Archive in the current file, under the top-level headline
482 \"* Archived Tasks\".
483
484 \"~/org/archive.org::\"
485 Archive in file ~/org/archive.org (absolute path), as top-level trees.
486
487 \"basement::** Finished Tasks\"
488 Archive in file ./basement (relative path), as level 3 trees
489 below the level 2 heading \"** Finished Tasks\".
490
491 You may set this option on a per-file basis by adding to the buffer a
492 line like
493
494 #+ARCHIVE: basement::** Finished Tasks"
495 :group 'org-archive
496 :type 'string)
497
498 (defcustom org-archive-mark-done t
499 "Non-nil means, mark archived entries as DONE."
500 :group 'org-archive
501 :type 'boolean)
502
503 (defcustom org-archive-stamp-time t
504 "Non-nil means, add a time stamp to archived entries.
505 The time stamp will be added directly after the TODO state keyword in the
506 first line, so it is probably best to use this in combinations with
507 `org-archive-mark-done'."
508 :group 'org-archive
509 :type 'boolean)
510
511 (defgroup org-table nil
512 "Options concerning tables in Org-mode."
513 :tag "Org Table"
514 :group 'org)
515
516 (defcustom org-enable-table-editor 'optimized
517 "Non-nil means, lines starting with \"|\" are handled by the table editor.
518 When nil, such lines will be treated like ordinary lines.
519
520 When equal to the symbol `optimized', the table editor will be optimized to
521 do the following:
522 - Use automatic overwrite mode in front of whitespace in table fields.
523 This make the structure of the table stay in tact as long as the edited
524 field does not exceed the column width.
525 - Minimize the number of realigns. Normally, the table is aligned each time
526 TAB or RET are pressed to move to another field. With optimization this
527 happens only if changes to a field might have changed the column width.
528 Optimization requires replacing the functions `self-insert-command',
529 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
530 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
531 very good at guessing when a re-align will be necessary, but you can always
532 force one with \\[org-ctrl-c-ctrl-c].
533
534 If you would like to use the optimized version in Org-mode, but the
535 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
536
537 This variable can be used to turn on and off the table editor during a session,
538 but in order to toggle optimization, a restart is required.
539
540 See also the variable `org-table-auto-blank-field'."
541 :group 'org-table
542 :type '(choice
543 (const :tag "off" nil)
544 (const :tag "on" t)
545 (const :tag "on, optimized" optimized)))
546
547 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
548 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
549 In the optimized version, the table editor takes over all simple keys that
550 normally just insert a character. In tables, the characters are inserted
551 in a way to minimize disturbing the table structure (i.e. in overwrite mode
552 for empty fields). Outside tables, the correct binding of the keys is
553 restored.
554
555 The default for this option is t if the optimized version is also used in
556 Org-mode. See the variable `org-enable-table-editor' for details. Changing
557 this variable requires a restart of Emacs to become effective."
558 :group 'org-table
559 :type 'boolean)
560
561 (defgroup org-table-settings nil
562 "Settings for tables in Org-mode."
563 :tag "Org Table Settings"
564 :group 'org-table)
565
566 (defcustom org-table-default-size "5x2"
567 "The default size for newly created tables, Columns x Rows."
568 :group 'org-table-settings
569 :type 'string)
570
571 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
572 "Regular expression for recognizing numbers in table columns.
573 If a table column contains mostly numbers, it will be aligned to the
574 right. If not, it will be aligned to the left.
575
576 The default value of this option is a regular expression which allows
577 anything which looks remotely like a number as used in scientific
578 context. For example, all of the following will be considered a
579 number:
580 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
581
582 Other options offered by the customize interface are more restrictive."
583 :group 'org-table-settings
584 :type '(choice
585 (const :tag "Positive Integers"
586 "^[0-9]+$")
587 (const :tag "Integers"
588 "^[-+]?[0-9]+$")
589 (const :tag "Floating Point Numbers"
590 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
591 (const :tag "Floating Point Number or Integer"
592 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
593 (const :tag "Exponential, Floating point, Integer"
594 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
595 (const :tag "Very General Number-Like"
596 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
597 (string :tag "Regexp:")))
598
599 (defcustom org-table-number-fraction 0.5
600 "Fraction of numbers in a column required to make the column align right.
601 In a column all non-white fields are considered. If at least this
602 fraction of fields is matched by `org-table-number-fraction',
603 alignment to the right border applies."
604 :group 'org-table-settings
605 :type 'number)
606
607 (defgroup org-table-editing nil
608 "Bahavior of tables during editing in Org-mode."
609 :tag "Org Table Editing"
610 :group 'org-table)
611
612 (defcustom org-table-automatic-realign t
613 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
614 When nil, aligning is only done with \\[org-table-align], or after column
615 removal/insertion."
616 :group 'org-table-editing
617 :type 'boolean)
618
619 (defcustom org-table-limit-column-width t ;kw
620 "Non-nil means, allow to limit the width of table columns with <N> fields."
621 :group 'org-table-editing
622 :type 'boolean)
623
624 (defcustom org-table-auto-blank-field t
625 "Non-nil means, automatically blank table field when starting to type into it.
626 This only happens when typing immediately after a field motion
627 command (TAB, S-TAB or RET).
628 Only relevant when `org-enable-table-editor' is equal to `optimized'."
629 :group 'org-table-editing
630 :type 'boolean)
631
632 (defcustom org-table-tab-jumps-over-hlines t
633 "Non-nil means, tab in the last column of a table with jump over a hline.
634 If a horizontal separator line is following the current line,
635 `org-table-next-field' can either create a new row before that line, or jump
636 over the line. When this option is nil, a new line will be created before
637 this line."
638 :group 'org-table-editing
639 :type 'boolean)
640
641 (defcustom org-table-tab-recognizes-table.el t
642 "Non-nil means, TAB will automatically notice a table.el table.
643 When it sees such a table, it moves point into it and - if necessary -
644 calls `table-recognize-table'."
645 :group 'org-table-editing
646 :type 'boolean)
647
648 (defgroup org-table-calculation nil
649 "Options concerning tables in Org-mode."
650 :tag "Org Table Calculation"
651 :group 'org-table)
652
653 (defcustom org-table-copy-increment t
654 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
655 :group 'org-table-calculation
656 :type 'boolean)
657
658 (defcustom org-calc-default-modes
659 '(calc-internal-prec 12
660 calc-float-format (float 5)
661 calc-angle-mode deg
662 calc-prefer-frac nil
663 calc-symbolic-mode nil
664 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
665 calc-display-working-message t
666 )
667 "List with Calc mode settings for use in calc-eval for table formulas.
668 The list must contain alternating symbols (Calc modes variables and values).
669 Don't remove any of the default settings, just change the values. Org-mode
670 relies on the variables to be present in the list."
671 :group 'org-table-calculation
672 :type 'plist)
673
674 (defcustom org-table-formula-evaluate-inline t
675 "Non-nil means, TAB and RET evaluate a formula in current table field.
676 If the current field starts with an equal sign, it is assumed to be a formula
677 which should be evaluated as described in the manual and in the documentation
678 string of the command `org-table-eval-formula'. This feature requires the
679 Emacs calc package.
680 When this variable is nil, formula calculation is only available through
681 the command \\[org-table-eval-formula]."
682 :group 'org-table-calculation
683 :type 'boolean)
684
685
686 (defcustom org-table-formula-use-constants t
687 "Non-nil means, interpret constants in formulas in tables.
688 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
689 by the value given in `org-table-formula-constants', or by a value obtained
690 from the `constants.el' package."
691 :group 'org-table-calculation
692 :type 'boolean)
693
694 (defcustom org-table-formula-constants nil
695 "Alist with constant names and values, for use in table formulas.
696 The car of each element is a name of a constant, without the `$' before it.
697 The cdr is the value as a string. For example, if you'd like to use the
698 speed of light in a formula, you would configure
699
700 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
701
702 and then use it in an equation like `$1*$c'."
703 :group 'org-table-calculation
704 :type '(repeat
705 (cons (string :tag "name")
706 (string :tag "value"))))
707
708 (defcustom org-table-formula-numbers-only nil
709 "Non-nil means, calculate only with numbers in table formulas.
710 Then all input fields will be converted to a number, and the result
711 must also be a number. When nil, calc's full potential is available
712 in table calculations, including symbolics etc."
713 :group 'org-table-calculation
714 :type 'boolean)
715
716 (defcustom org-table-allow-automatic-line-recalculation t
717 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
718 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
719 :group 'org-table-calculation
720 :type 'boolean)
721
722 (defgroup org-link nil
723 "Options concerning links in Org-mode."
724 :tag "Org Link"
725 :group 'org)
726
727 (defcustom org-descriptive-links t
728 "Non-nil means, hide link part and only show description of bracket links.
729 Bracket links are like [[link][descritpion]]. This variable sets the initial
730 state in new org-mode buffers. The setting can then be toggled on a
731 per-buffer basis from the Org->Hyperlinks menu."
732 :group 'org-link
733 :type 'boolean)
734
735 (defcustom org-link-style 'bracket
736 "The style of links to be inserted with \\[org-insert-link].
737 Possible values are:
738 bracket [[link][description]]. This is recommended
739 plain Description \\n link. The old way, no longer recommended."
740 :group 'org-link
741 :type '(choice
742 (const :tag "Bracket (recommended)" bracket)
743 (const :tag "Plain (no longer recommended)" plain)))
744
745 (defcustom org-link-format "%s"
746 "Default format for external, URL-like linkes in the buffer.
747 This is a format string for printf, %s will be replaced by the link text.
748 The recommended value is just \"%s\", since links will be protected by
749 enclosing them in double brackets. If you prefer plain links (see variable
750 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
751 additional URL: prefix, so the format would be \"<URL:%s>\"."
752 :group 'org-link
753 :type '(choice
754 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
755 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
756 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
757 (string :tag "Other" :value "<%s>")))
758
759 (defcustom org-activate-links '(bracket angle plain radio tag date)
760 "Types of links that should be activated in Org-mode files.
761 This is a list of symbols, each leading to the activation of a certain link
762 type. In principle, it does not hurt to turn on most link types - there may
763 be a small gain when turning off unused link types. The types are:
764
765 bracket The recommended [[link][description]] or [[link]] links with hiding.
766 angular Links in angular brackes that may contain whitespace like
767 <bbdb:Carsten Dominik>.
768 plain Plain links in normal text, no whitespace, like http://google.com.
769 radio Text that is matched by a radio target, see manual for details.
770 tag Tag settings in a headline (link to tag search).
771 date Time stamps (link to calendar).
772 camel CamelCase words defining text searches.
773
774 Changing this variable requires a restart of Emacs to become effective."
775 :group 'org-link
776 :type '(set (const :tag "Double bracket links (new style)" bracket)
777 (const :tag "Angular bracket links (old style)" angular)
778 (const :tag "plain text links" plain)
779 (const :tag "Radio target matches" radio)
780 (const :tag "Tags" tag)
781 (const :tag "Timestamps" date)
782 (const :tag "CamelCase words" camel)))
783
784 (defgroup org-link-store nil
785 "Options concerning storing links in Org-mode"
786 :tag "Org Store Link"
787 :group 'org-link)
788
789 (defcustom org-context-in-file-links t
790 "Non-nil means, file links from `org-store-link' contain context.
791 A search string will be added to the file name with :: as separator and
792 used to find the context when the link is activated by the command
793 `org-open-at-point'.
794 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
795 negates this setting for the duration of the command."
796 :group 'org-link-store
797 :type 'boolean)
798
799 (defcustom org-file-link-context-use-camel-case nil
800 "Non-nil means, use CamelCase to store a search context in a file link.
801 When nil, the search string simply consists of the words of the string.
802 CamelCase is deprecated, and support for it may be dropped in the future."
803 :group 'org-link-store
804 :type 'boolean)
805
806 (defcustom org-keep-stored-link-after-insertion nil
807 "Non-nil means, keep link in list for entire session.
808
809 The command `org-store-link' adds a link pointing to the current
810 location to an internal list. These links accumulate during a session.
811 The command `org-insert-link' can be used to insert links into any
812 Org-mode file (offering completion for all stored links). When this
813 option is nil, every link which has been inserted once using \\[org-insert-link]
814 will be removed from the list, to make completing the unused links
815 more efficient."
816 :group 'org-link-store
817 :type 'boolean)
818
819 (defcustom org-usenet-links-prefer-google nil
820 "Non-nil means, `org-store-link' will create web links to Google groups.
821 When nil, Gnus will be used for such links.
822 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
823 negates this setting for the duration of the command."
824 :group 'org-link-store
825 :type 'boolean)
826
827 (defgroup org-link-follow nil
828 "Options concerning following links in Org-mode"
829 :tag "Org Follow Link"
830 :group 'org-link)
831
832 (defcustom org-tab-follows-link nil
833 "Non-nil means, on links TAB will follow the link.
834 Needs to be set before org.el is loaded."
835 :group 'org-link-follow
836 :type 'boolean)
837
838 (defcustom org-return-follows-link nil
839 "Non-nil means, on links RET will follow the link.
840 Needs to be set before org.el is loaded."
841 :group 'org-link-follow
842 :type 'boolean)
843
844 (defcustom org-mouse-1-follows-link t
845 "Non-nil means, mouse-1 on a link will follow the link.
846 A longer mouse click will still set point. Does not wortk on XEmacs.
847 Needs to be set before org.el is loaded."
848 :group 'org-link-follow
849 :type 'boolean)
850
851 (defcustom org-mark-ring-length 4
852 "Number of different positions to be recorded in the ring
853 Changing this requires a restart of Emacs to work correctly."
854 :group 'org-link-follow
855 :type 'interger)
856
857 (defcustom org-link-frame-setup
858 '((vm . vm-visit-folder-other-frame)
859 (gnus . gnus-other-frame)
860 (file . find-file-other-window))
861 "Setup the frame configuration for following links.
862 When following a link with Emacs, it may often be useful to display
863 this link in another window or frame. This variable can be used to
864 set this up for the different types of links.
865 For VM, use any of
866 `vm-visit-folder'
867 `vm-visit-folder-other-frame'
868 For Gnus, use any of
869 `gnus'
870 `gnus-other-frame'
871 For FILE, use any of
872 `find-file'
873 `find-file-other-window'
874 `find-file-other-frame'
875 For the calendar, use the variable `calendar-setup'.
876 For BBDB, it is currently only possible to display the matches in
877 another window."
878 :group 'org-link-follow
879 :type '(list
880 (cons (const vm)
881 (choice
882 (const vm-visit-folder)
883 (const vm-visit-folder-other-window)
884 (const vm-visit-folder-other-frame)))
885 (cons (const gnus)
886 (choice
887 (const gnus)
888 (const gnus-other-frame)))
889 (cons (const file)
890 (choice
891 (const find-file)
892 (const find-file-other-window)
893 (const find-file-other-frame)))))
894
895 (defcustom org-open-non-existing-files nil
896 "Non-nil means, `org-open-file' will open non-existing file.
897 When nil, an error will be generated."
898 :group 'org-link-follow
899 :type 'boolean)
900
901 (defcustom org-confirm-shell-links 'yes-or-no-p
902 "Non-nil means, ask for confirmation before executing shell links.
903 Shell links can be dangerous, just thing about a link
904
905 [[shell:rm -rf ~/*][Google Search]]
906
907 This link would show up in your Org-mode document as \"Google Search\"
908 but really it would remove your entire home directory. Dangerous indeed.
909 Therefore I *definitely* advise agains setting this varaiable to nil.
910 Just change it to `y-or-n-p' of you want to confirm with a single key press
911 rather than having to type \"yes\"."
912 :group 'org-link-follow
913 :type '(choice
914 (const :tag "with yes-or-no (safer)" yes-or-no-p)
915 (const :tag "with y-or-n (faster)" y-or-n-p)
916 (const :tag "no confirmation (dangerous)" nil)))
917
918 (defconst org-file-apps-defaults-gnu
919 '((t . mailcap))
920 "Default file applications on a UNIX or GNU/Linux system.
921 See `org-file-apps'.")
922
923 (defconst org-file-apps-defaults-macosx
924 '((t . "open %s")
925 ("ps" . "gv %s")
926 ("ps.gz" . "gv %s")
927 ("eps" . "gv %s")
928 ("eps.gz" . "gv %s")
929 ("dvi" . "xdvi %s")
930 ("fig" . "xfig %s"))
931 "Default file applications on a MacOS X system.
932 The system \"open\" is known as a default, but we use X11 applications
933 for some files for which the OS does not have a good default.
934 See `org-file-apps'.")
935
936 (defconst org-file-apps-defaults-windowsnt
937 '((t . (w32-shell-execute "open" file)))
938 "Default file applications on a Windows NT system.
939 The system \"open\" is used for most files.
940 See `org-file-apps'.")
941
942 (defcustom org-file-apps
943 '(
944 ("txt" . emacs)
945 ("tex" . emacs)
946 ("ltx" . emacs)
947 ("org" . emacs)
948 ("el" . emacs)
949 )
950 "External applications for opening `file:path' items in a document.
951 Org-mode uses system defaults for different file types, but
952 you can use this variable to set the application for a given file
953 extension. The entries in this list are cons cells with a file extension
954 and the corresponding command. Possible values for the command are:
955 `emacs' The file will be visited by the current Emacs process.
956 `default' Use the default application for this file type.
957 string A command to be executed by a shell; %s will be replaced
958 by the path to the file.
959 sexp A Lisp form which will be evaluated. The file path will
960 be available in the Lisp variable `file'.
961 For more examples, see the system specific constants
962 `org-file-apps-defaults-macosx'
963 `org-file-apps-defaults-windowsnt'
964 `org-file-apps-defaults-gnu'."
965 :group 'org-link-follow
966 :type '(repeat
967 (cons (choice :value ""
968 (string :tag "Extension")
969 (const :tag "Default for unrecognized files" t)
970 (const :tag "Links to a directory" directory))
971 (choice :value ""
972 (const :tag "Visit with Emacs" emacs)
973 (const :tag "Use system default" default)
974 (string :tag "Command")
975 (sexp :tag "Lisp form")))))
976
977 (defcustom org-mhe-search-all-folders nil
978 "Non-nil means, that the search for the mh-message will be extended to
979 all folders if the message cannot be found in the folder given in the link.
980 Searching all folders is very effective with one of the search engines
981 supported by MH-E, but will be slow with pick."
982 :group 'org-link-follow
983 :type 'boolean)
984
985 (defgroup org-remember nil
986 "Options concerning interaction with remember.el."
987 :tag "Org Remember"
988 :group 'org)
989
990 (defcustom org-directory "~/org"
991 "Directory with org files.
992 This directory will be used as default to prompt for org files.
993 Used by the hooks for remember.el."
994 :group 'org-remember
995 :type 'directory)
996
997 (defcustom org-default-notes-file "~/.notes"
998 "Default target for storing notes.
999 Used by the hooks for remember.el. This can be a string, or nil to mean
1000 the value of `remember-data-file'."
1001 :group 'org-remember
1002 :type '(choice
1003 (const :tag "Default from remember-data-file" nil)
1004 file))
1005
1006 (defcustom org-remember-templates nil
1007 "Templates for the creation of remember buffers.
1008 When nil, just let remember make the buffer.
1009 When not nil, this is a list of 3-element lists. In each entry, the first
1010 element is a character, a unique key to select this template.
1011 The second element is the template. The third element is optional and can
1012 specify a destination file for remember items created with this template.
1013 The default file is given by `org-default-notes-file'.
1014
1015 The template specifies the structure of the remember buffer. It should have
1016 a first line starting with a star, to act as the org-mode headline.
1017 Furthermore, the following %-escapes will be replaced with content:
1018 %t time stamp, date only
1019 %T time stamp with date and time
1020 %u inactive time stamp, date only
1021 %U inactive time stamp with date and time
1022 %n user name
1023 %a annotation, normally the link created with org-store-link
1024 %i initial content, the region when remember is called with C-u.
1025 If %i is indented, the entire inserted text will be indented as well.
1026 %? This will be removed, and the cursor placed at this position."
1027 :group 'org-remember
1028 :type '(repeat :tag "enabled"
1029 (list :value (?a "\n" nil)
1030 (character :tag "Selection Key")
1031 (string :tag "Template")
1032 (file :tag "Destination file (optional)"))))
1033
1034 (defcustom org-reverse-note-order nil
1035 "Non-nil means, store new notes at the beginning of a file or entry.
1036 When nil, new notes will be filed to the end of a file or entry."
1037 :group 'org-remember
1038 :type '(choice
1039 (const :tag "Reverse always" t)
1040 (const :tag "Reverse never" nil)
1041 (repeat :tag "By file name regexp"
1042 (cons regexp boolean))))
1043
1044 (defgroup org-todo nil
1045 "Options concerning TODO items in Org-mode."
1046 :tag "Org TODO"
1047 :group 'org)
1048
1049 (defcustom org-todo-keywords '("TODO" "DONE")
1050 "List of TODO entry keywords.
1051 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1052 considered to mean that the entry is \"done\". All the other mean that
1053 action is required, and will make the entry show up in todo lists, diaries
1054 etc.
1055 The command \\[org-todo] cycles an entry through these states, and an
1056 additional state where no keyword is present. For details about this
1057 cycling, see also the variable `org-todo-interpretation'
1058 Changes become only effective after restarting Emacs."
1059 :group 'org-todo
1060 :group 'org-keywords
1061 :type '(repeat (string :tag "Keyword")))
1062
1063 (defcustom org-todo-interpretation 'sequence
1064 "Controls how TODO keywords are interpreted.
1065 This variable is only relevant if `org-todo-keywords' contains more than two
1066 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1067
1068 When `sequence', \\[org-todo] will always switch to the next state in the
1069 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1070 to state when executed several times in direct succession. Otherwise, it
1071 switches directly to DONE from any state.
1072 See the manual for more information."
1073 :group 'org-todo
1074 :group 'org-keywords
1075 :type '(choice (const sequence)
1076 (const type)))
1077
1078 (defcustom org-after-todo-state-change-hook nil
1079 "Hook which is run after the state of a TODO item was changed.
1080 The new state (a string with a TODO keyword, or nil) is available in the
1081 Lisp variable `state'."
1082 :group 'org-todo
1083 :type 'hook)
1084
1085 (defcustom org-log-done nil
1086 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1087 When the state of an entry is changed from nothing to TODO, remove a previous
1088 closing date."
1089 :group 'org-todo
1090 :type 'boolean)
1091
1092 (defgroup org-priorities nil
1093 "Priorities in Org-mode."
1094 :tag "Org Priorities"
1095 :group 'org-todo)
1096
1097 (defcustom org-default-priority ?B
1098 "The default priority of TODO items.
1099 This is the priority an item get if no explicit priority is given."
1100 :group 'org-priorities
1101 :type 'character)
1102
1103 (defcustom org-lowest-priority ?C
1104 "The lowest priority of TODO items. A character like ?A, ?B etc."
1105 :group 'org-priorities
1106 :type 'character)
1107
1108 (defgroup org-time nil
1109 "Options concerning time stamps and deadlines in Org-mode."
1110 :tag "Org Time"
1111 :group 'org)
1112
1113 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1114 "Formats for `format-time-string' which are used for time stamps.
1115 It is not recommended to change this constant.")
1116
1117 (defcustom org-time-stamp-rounding-minutes 0
1118 "Number of minutes to round time stamps to upon insertion.
1119 When zero, insert the time unmodified. Useful rounding numbers
1120 should be factors of 60, so for example 5, 10, 15.
1121 When this is not zero, you can still force an exact time-stamp by using
1122 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1123 :group 'org-time
1124 :type 'integer)
1125
1126 (defcustom org-deadline-warning-days 30
1127 "No. of days before expiration during which a deadline becomes active.
1128 This variable governs the display in the org file."
1129 :group 'org-time
1130 :type 'number)
1131
1132 (defcustom org-popup-calendar-for-date-prompt t
1133 "Non-nil means, pop up a calendar when prompting for a date.
1134 In the calendar, the date can be selected with mouse-1. However, the
1135 minibuffer will also be active, and you can simply enter the date as well.
1136 When nil, only the minibuffer will be available."
1137 :group 'org-time
1138 :type 'boolean)
1139
1140 (defcustom org-calendar-follow-timestamp-change t
1141 "Non-nil means, make the calendar window follow timestamp changes.
1142 When a timestamp is modified and the calendar window is visible, it will be
1143 moved to the new date."
1144 :group 'org-time
1145 :type 'boolean)
1146
1147 (defgroup org-tags nil
1148 "Options concerning tags in Org-mode."
1149 :tag "Org Tags"
1150 :group 'org)
1151
1152 (defcustom org-tags-column 48
1153 "The column to which tags should be indented in a headline.
1154 If this number is positive, it specifies the column. If it is negative,
1155 it means that the tags should be flushright to that column. For example,
1156 -79 works well for a normal 80 character screen."
1157 :group 'org-tags
1158 :type 'integer)
1159
1160 (defcustom org-auto-align-tags t
1161 "Non-nil means, realign tags after pro/demotion of TODO state change.
1162 These operations change the length of a headline and therefore shift
1163 the tags around. With this options turned on, after each such operation
1164 the tags are again aligned to `org-tags-column'."
1165 :group 'org-tags
1166 :type 'boolean)
1167
1168 (defcustom org-use-tag-inheritance t
1169 "Non-nil means, tags in levels apply also for sublevels.
1170 When nil, only the tags directly given in a specific line apply there.
1171 If you turn off this option, you very likely want to turn on the
1172 companion option `org-tags-match-list-sublevels'."
1173 :group 'org-tags
1174 :type 'boolean)
1175
1176 (defcustom org-tags-match-list-sublevels nil
1177 "Non-nil means list also sublevels of headlines matching tag search.
1178 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1179 the sublevels of a headline matching a tag search often also match
1180 the same search. Listing all of them can create very long lists.
1181 Setting this variable to nil causes subtrees of a match to be skipped.
1182 This option is off by default, because inheritance in on. If you turn
1183 inheritance off, you very likely want to turn this option on.
1184
1185 As a special case, if the tag search is restricted to TODO items, the
1186 value of this variable is ignored and sublevels are always checked, to
1187 make sure all corresponding TODO items find their way into the list."
1188 :group 'org-tags
1189 :type 'boolean)
1190
1191 (defvar org-tags-history nil
1192 "History of minibuffer reads for tags.")
1193 (defvar org-last-tags-completion-table nil
1194 "The last used completion table for tags.")
1195
1196 (defgroup org-agenda nil
1197 "Options concerning agenda display Org-mode."
1198 :tag "Org Agenda"
1199 :group 'org)
1200
1201 (defvar org-category nil
1202 "Variable used by org files to set a category for agenda display.
1203 Such files should use a file variable to set it, for example
1204
1205 -*- mode: org; org-category: \"ELisp\"
1206
1207 or contain a special line
1208
1209 #+CATEGORY: ELisp
1210
1211 If the file does not specify a category, then file's base name
1212 is used instead.")
1213 (make-variable-buffer-local 'org-category)
1214
1215 (defcustom org-agenda-files nil
1216 "The files to be used for agenda display.
1217 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1218 \\[org-remove-file]. You can also use customize to edit the list.
1219
1220 If the value of the variable is not a list but a single file name, then
1221 the list of agenda files is actually stored and maintained in that file, one
1222 agenda file per line."
1223 :group 'org-agenda
1224 :type '(choice
1225 (repeat :tag "List of files" file)
1226 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1227
1228 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1229 "Custom commands for the agenda.
1230 These commands will be offered on the splash screen displayed by the
1231 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1232
1233 key The key (a single char as a string) to be associated with the command.
1234 type The command type, any of the following symbols:
1235 todo Entries with a specific TODO keyword, in all agenda files.
1236 tags Tags match in all agenda files.
1237 todo-tree Sparse tree of specific TODO keyword in *current* file.
1238 tags-tree Sparse tree with all tags matches in *current* file.
1239 occur-tree Occur sparse tree for current file.
1240 match What to search for:
1241 - a single keyword for TODO keyword searches
1242 - a tags match expression for tags searches
1243 - a regular expression for occur searches"
1244 :group 'org-agenda
1245 :type '(repeat
1246 (list (string :tag "Key")
1247 (choice :tag "Type"
1248 (const :tag "Tags search in all agenda files" tags)
1249 (const :tag "TODO keyword search in all agenda files" todo)
1250 (const :tag "Tags sparse tree in current buffer" tags-tree)
1251 (const :tag "TODO keyword tree in current buffer" todo-tree)
1252 (const :tag "Occur tree in current buffer" occur-tree))
1253 (string :tag "Match"))))
1254
1255 (defcustom org-agenda-include-all-todo t
1256 "Non-nil means, the agenda will always contain all TODO entries.
1257 When nil, date-less entries will only be shown if `org-agenda' is called
1258 with a prefix argument.
1259 When non-nil, the TODO entries will be listed at the top of the agenda, before
1260 the entries for specific days."
1261 :group 'org-agenda
1262 :type 'boolean)
1263
1264 (defcustom org-agenda-include-diary nil
1265 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1266 :group 'org-agenda
1267 :type 'boolean)
1268
1269 (defcustom org-calendar-to-agenda-key [?c]
1270 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1271 The command `org-calendar-goto-agenda' will be bound to this key. The
1272 default is the character `c' because then `c' can be used to switch back and
1273 forth between agenda and calendar."
1274 :group 'org-agenda
1275 :type 'sexp)
1276
1277 (defgroup org-agenda-window-setup nil
1278 "Options concerning setting up the Agenda window in Org Mode."
1279 :tag "Org Agenda Window Setup"
1280 :group 'org-agenda)
1281
1282 (defcustom org-agenda-mouse-1-follows-link nil
1283 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1284 A longer mouse click will still set point. Does not wortk on XEmacs.
1285 Needs to be set before org.el is loaded."
1286 :group 'org-agenda-setup
1287 :type 'boolean)
1288
1289 (defcustom org-select-timeline-window t
1290 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1291 When nil, cursor will remain in the current window."
1292 :group 'org-agenda-setup
1293 :type 'boolean)
1294
1295 (defcustom org-select-agenda-window t
1296 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1297 When nil, cursor will remain in the current window."
1298 :group 'org-agenda-setup
1299 :type 'boolean)
1300
1301 (defcustom org-fit-agenda-window t
1302 "Non-nil means, change window size of agenda to fit content."
1303 :group 'org-agenda-setup
1304 :type 'boolean)
1305
1306 (defgroup org-agenda-display nil
1307 "Options concerning what to display initially in Agenda."
1308 :tag "Org Agenda Display"
1309 :group 'org-agenda)
1310
1311 (defcustom org-agenda-show-all-dates t
1312 "Non-nil means, `org-agenda' shows every day in the selected range.
1313 When nil, only the days which actually have entries are shown."
1314 :group 'org-agenda-display
1315 :type 'boolean)
1316
1317 (defcustom org-agenda-start-on-weekday 1
1318 "Non-nil means, start the overview always on the specified weekday.
1319 0 denotes Sunday, 1 denotes Monday etc.
1320 When nil, always start on the current day."
1321 :group 'org-agenda-display
1322 :type '(choice (const :tag "Today" nil)
1323 (number :tag "Weekday No.")))
1324
1325 (defcustom org-agenda-ndays 7
1326 "Number of days to include in overview display.
1327 Should be 1 or 7."
1328 :group 'org-agenda-display
1329 :type 'number)
1330
1331 (defcustom org-agenda-use-time-grid t
1332 "Non-nil means, show a time grid in the agenda schedule.
1333 A time grid is a set of lines for specific times (like every two hours between
1334 8:00 and 20:00). The items scheduled for a day at specific times are
1335 sorted in between these lines.
1336 For details about when the grid will be shown, and what it will look like, see
1337 the variable `org-agenda-time-grid'."
1338 :group 'org-agenda-display
1339 :type 'boolean)
1340
1341 (defcustom org-agenda-time-grid
1342 '((daily today require-timed)
1343 "----------------"
1344 (800 1000 1200 1400 1600 1800 2000))
1345
1346 "The settings for time grid for agenda display.
1347 This is a list of three items. The first item is again a list. It contains
1348 symbols specifying conditions when the grid should be displayed:
1349
1350 daily if the agenda shows a single day
1351 weekly if the agenda shows an entire week
1352 today show grid on current date, independent of daily/weekly display
1353 require-timed show grid only if at least on item has a time specification
1354
1355 The second item is a string which will be places behing the grid time.
1356
1357 The third item is a list of integers, indicating the times that should have
1358 a grid line."
1359 :group 'org-agenda-display
1360 :type
1361 '(list
1362 (set :greedy t :tag "Grid Display Options"
1363 (const :tag "Show grid in single day agenda display" daily)
1364 (const :tag "Show grid in weekly agenda display" weekly)
1365 (const :tag "Always show grid for today" today)
1366 (const :tag "Show grid only if any timed entries are present"
1367 require-timed)
1368 (const :tag "Skip grid times already present in an entry"
1369 remove-match))
1370 (string :tag "Grid String")
1371 (repeat :tag "Grid Times" (integer :tag "Time"))))
1372
1373 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1374 "Sorting structure for the agenda items of a single day.
1375 This is a list of symbols which will be used in sequence to determine
1376 if an entry should be listed before another entry. The following
1377 symbols are recognized:
1378
1379 time-up Put entries with time-of-day indications first, early first
1380 time-down Put entries with time-of-day indications first, late first
1381 category-keep Keep the default order of categories, corresponding to the
1382 sequence in `org-agenda-files'.
1383 category-up Sort alphabetically by category, A-Z.
1384 category-down Sort alphabetically by category, Z-A.
1385 priority-up Sort numerically by priority, high priority last.
1386 priority-down Sort numerically by priority, high priority first.
1387
1388 The different possibilities will be tried in sequence, and testing stops
1389 if one comparison returns a \"not-equal\". For example, the default
1390 '(time-up category-keep priority-down)
1391 means: Pull out all entries having a specified time of day and sort them,
1392 in order to make a time schedule for the current day the first thing in the
1393 agenda listing for the day. Of the entries without a time indication, keep
1394 the grouped in categories, don't sort the categories, but keep them in
1395 the sequence given in `org-agenda-files'. Within each category sort by
1396 priority.
1397
1398 Leaving out `category-keep' would mean that items will be sorted across
1399 categories by priority."
1400 :group 'org-agenda-display
1401 :type '(repeat
1402 (choice
1403 (const time-up)
1404 (const time-down)
1405 (const category-keep)
1406 (const category-up)
1407 (const category-down)
1408 (const priority-up)
1409 (const priority-down))))
1410
1411 (defcustom org-sort-agenda-notime-is-late t
1412 "Non-nil means, items without time are considered late.
1413 This is only relevant for sorting. When t, items which have no explicit
1414 time like 15:30 will be considered as 24:01, i.e. later than any items which
1415 do have a time. When nil, the default time is before 0:00. You can use this
1416 option to decide if the schedule for today should come before or after timeless
1417 agenda entries."
1418 :group 'org-agenda-display
1419 :type 'boolean)
1420
1421
1422 (defgroup org-agenda-prefix nil
1423 "Options concerning the entry prefix in the Org-mode agenda display."
1424 :tag "Org Agenda Prefix"
1425 :group 'org-agenda)
1426
1427 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1428 "Format specification for the prefix of items in the agenda buffer.
1429 This format works similar to a printf format, with the following meaning:
1430
1431 %c the category of the item, \"Diary\" for entries from the diary, or
1432 as given by the CATEGORY keyword or derived from the file name.
1433 %T the first tag of the item.
1434 %t the time-of-day specification if one applies to the entry, in the
1435 format HH:MM
1436 %s Scheduling/Deadline information, a short string
1437
1438 All specifiers work basically like the standard `%s' of printf, but may
1439 contain two additional characters: A question mark just after the `%' and
1440 a whitespace/punctuation character just before the final letter.
1441
1442 If the first character after `%' is a question mark, the entire field
1443 will only be included if the corresponding value applies to the
1444 current entry. This is useful for fields which should have fixed
1445 width when present, but zero width when absent. For example,
1446 \"%?-12t\" will result in a 12 character time field if a time of the
1447 day is specified, but will completely disappear in entries which do
1448 not contain a time.
1449
1450 If there is punctuation or whitespace character just before the final
1451 format letter, this character will be appended to the field value if
1452 the value is not empty. For example, the format \"%-12:c\" leads to
1453 \"Diary: \" if the category is \"Diary\". If the category were be
1454 empty, no additional colon would be interted.
1455
1456 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1457 - Indent the line with two space characters
1458 - Give the category in a 12 chars wide field, padded with whitespace on
1459 the right (because of `-'). Append a colon if there is a category
1460 (because of `:').
1461 - If there is a time-of-day, put it into a 12 chars wide field. If no
1462 time, don't put in an empty field, just skip it (because of '?').
1463 - Finally, put the scheduling information and append a whitespace.
1464
1465 As another example, if you don't want the time-of-day of entries in
1466 the prefix, you could use:
1467
1468 (setq org-agenda-prefix-format \" %-11:c% s\")
1469
1470 See also the variables `org-agenda-remove-times-when-in-prefix' and
1471 `org-agenda-remove-tags-when-in-prefix'."
1472 :type 'string
1473 :group 'org-agenda-prefix)
1474
1475 (defcustom org-timeline-prefix-format " % s"
1476 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1477 :type 'string
1478 :group 'org-agenda-prefix)
1479
1480 (defvar org-prefix-format-compiled nil
1481 "The compiled version of the most recently used prefix format.
1482 Depending on which command was used last, this may be the compiled version
1483 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1484
1485 ;; FIXME: There seem to be situations where this does no work.
1486 (defcustom org-agenda-remove-times-when-in-prefix t
1487 "Non-nil means, remove duplicate time specifications in agenda items.
1488 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1489 time-of-day specification in a headline or diary entry is extracted and
1490 placed into the prefix. If this option is non-nil, the original specification
1491 \(a timestamp or -range, or just a plain time(range) specification like
1492 11:30-4pm) will be removed for agenda display. This makes the agenda less
1493 cluttered.
1494 The option can be t or nil. It may also be the symbol `beg', indicating
1495 that the time should only be removed what it is located at the beginning of
1496 the headline/diary entry."
1497 :group 'org-agenda-prefix
1498 :type '(choice
1499 (const :tag "Always" t)
1500 (const :tag "Never" nil)
1501 (const :tag "When at beginning of entry" beg)))
1502
1503 (defcustom org-agenda-remove-tags-when-in-prefix nil
1504 "Non-nil means, remove the tags from the headline copy in the agenda.
1505 When this is the symbol `prefix', only remove tags when
1506 `org-agenda-prefix-format' contains a `%T' specifier."
1507 :group 'org-agenda-prefix
1508 :type '(choice
1509 (const :tag "Always" t)
1510 (const :tag "Never" nil)
1511 (const :tag "When prefix format contains %T" prefix)))
1512
1513 (defgroup org-export nil
1514 "Options for exporting org-listings."
1515 :tag "Org Export"
1516 :group 'org)
1517
1518 (defgroup org-export-general nil
1519 "General options for exporting Org-mode files."
1520 :tag "Org Export General"
1521 :group 'org-export)
1522
1523 (defcustom org-export-language-setup
1524 '(("en" "Author" "Date" "Table of Contents")
1525 ("da" "Ophavsmand" "Dato" "Indhold")
1526 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1527 ("es" "Autor" "Fecha" "\xccndice")
1528 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1529 ("it" "Autore" "Data" "Indice")
1530 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1531 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1532 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1533 "Terms used in export text, translated to different languages.
1534 Use the variable `org-export-default-language' to set the language,
1535 or use the +OPTION lines for a per-file setting."
1536 :group 'org-export-general
1537 :type '(repeat
1538 (list
1539 (string :tag "HTML language tag")
1540 (string :tag "Author")
1541 (string :tag "Date")
1542 (string :tag "Table of Contents"))))
1543
1544 (defcustom org-export-default-language "en"
1545 "The default language of HTML export, as a string.
1546 This should have an association in `org-export-language-setup'."
1547 :group 'org-export-general
1548 :type 'string)
1549
1550 (defcustom org-export-headline-levels 3
1551 "The last level which is still exported as a headline.
1552 Inferior levels will produce itemize lists when exported.
1553 Note that a numeric prefix argument to an exporter function overrides
1554 this setting.
1555
1556 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1557 :group 'org-export-general
1558 :type 'number)
1559
1560 (defcustom org-export-with-section-numbers t
1561 "Non-nil means, add section numbers to headlines when exporting.
1562
1563 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1564 :group 'org-export-general
1565 :type 'boolean)
1566
1567 (defcustom org-export-with-toc t
1568 "Non-nil means, create a table of contents in exported files.
1569 The TOC contains headlines with levels up to`org-export-headline-levels'.
1570
1571 Headlines which contain any TODO items will be marked with \"(*)\" in
1572 ASCII export, and with red color in HTML output.
1573
1574 In HTML output, the TOC will be clickable.
1575
1576 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1577 :group 'org-export-general
1578 :type 'boolean)
1579
1580 (defcustom org-export-mark-todo-in-toc nil
1581 "Non-nil means, mark TOC lines that contain any open TODO items."
1582 :group 'org-export-general
1583 :type 'boolean)
1584
1585 (defcustom org-export-preserve-breaks nil
1586 "Non-nil means, preserve all line breaks when exporting.
1587 Normally, in HTML output paragraphs will be reformatted. In ASCII
1588 export, line breaks will always be preserved, regardless of this variable.
1589
1590 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1591 :group 'org-export-general
1592 :type 'boolean)
1593
1594 (defgroup org-export-translation nil
1595 "Options for translating special ascii sequences for the export backends."
1596 :tag "Org Export Translation"
1597 :group 'org-export)
1598
1599 (defcustom org-export-with-emphasize t
1600 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1601 If the export target supports emphasizing text, the word will be
1602 typeset in bold, italic, or underlined, respectively. Works only for
1603 single words, but you can say: I *really* *mean* *this*.
1604 Not all export backends support this.
1605
1606 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1607 :group 'org-export-translation
1608 :type 'boolean)
1609
1610 (defcustom org-export-with-sub-superscripts t
1611 "Non-nil means, interpret \"_\" and \"^\" for export.
1612 When this option is turned on, you can use TeX-like syntax for sub- and
1613 superscripts. Several characters after \"_\" or \"^\" will be
1614 considered as a single item - so grouping with {} is normally not
1615 needed. For example, the following things will be parsed as single
1616 sub- or superscripts.
1617
1618 10^24 or 10^tau several digits will be considered 1 item.
1619 10^-12 or 10^-tau a leading sign with digits or a word
1620 x^2-y^3 will be read as x^2 - y^3, because items are
1621 terminated by almost any nonword/nondigit char.
1622 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1623
1624 Still, ambiguity is possible - so when in doubt use {} to enclose the
1625 sub/superscript.
1626 Not all export backends support this, but HTML does.
1627
1628 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1629 :group 'org-export-translation
1630 :type 'boolean)
1631
1632 (defcustom org-export-with-TeX-macros t
1633 "Non-nil means, interpret simple TeX-like macros when exporting.
1634 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1635 No only real TeX macros will work here, but the standard HTML entities
1636 for math can be used as macro names as well. For a list of supported
1637 names in HTML export, see the constant `org-html-entities'.
1638 Not all export backends support this.
1639
1640 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1641 :group 'org-export-translation
1642 :type 'boolean)
1643
1644 (defcustom org-export-with-fixed-width t
1645 "Non-nil means, lines starting with \":\" will be in fixed width font.
1646 This can be used to have pre-formatted text, fragments of code etc. For
1647 example:
1648 : ;; Some Lisp examples
1649 : (while (defc cnt)
1650 : (ding))
1651 will be looking just like this in also HTML. See also the QUOTE keyword.
1652 Not all export backends support this.
1653
1654 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1655 :group 'org-export-translation
1656 :type 'boolean)
1657
1658 (defcustom org-match-sexp-depth 3
1659 "Number of stacked braces for sub/superscript matching.
1660 This has to be set before loading org.el to be effective."
1661 :group 'org-export-translation
1662 :type 'integer)
1663
1664 (defgroup org-export-tables nil
1665 "Options for exporting tables in Org-mode."
1666 :tag "Org Export Tables"
1667 :group 'org-export)
1668
1669 (defcustom org-export-with-tables t
1670 "If non-nil, lines starting with \"|\" define a table.
1671 For example:
1672
1673 | Name | Address | Birthday |
1674 |-------------+----------+-----------|
1675 | Arthur Dent | England | 29.2.2100 |
1676
1677 Not all export backends support this.
1678
1679 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1680 :group 'org-export-tables
1681 :type 'boolean)
1682
1683 (defcustom org-export-highlight-first-table-line t
1684 "Non-nil means, highlight the first table line.
1685 In HTML export, this means use <th> instead of <td>.
1686 In tables created with table.el, this applies to the first table line.
1687 In Org-mode tables, all lines before the first horizontal separator
1688 line will be formatted with <th> tags."
1689 :group 'org-export-tables
1690 :type 'boolean)
1691
1692 (defcustom org-export-table-remove-special-lines t
1693 "Remove special lines and marking characters in calculating tables.
1694 This removes the special marking character column from tables that are set
1695 up for spreadsheet calculations. It also removes the entire lines
1696 marked with `!', `_', or `^'. The lines with `$' are kept, because
1697 the values of constants may be useful to have."
1698 :group 'org-export-tables
1699 :type 'boolean)
1700
1701 (defcustom org-export-prefer-native-exporter-for-tables nil
1702 "Non-nil means, always export tables created with table.el natively.
1703 Natively means, use the HTML code generator in table.el.
1704 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1705 the table does not use row- or column-spanning). This has the
1706 advantage, that the automatic HTML conversions for math symbols and
1707 sub/superscripts can be applied. Org-mode's HTML generator is also
1708 much faster."
1709 :group 'org-export-tables
1710 :type 'boolean)
1711
1712 (defgroup org-export-ascii nil
1713 "Options specific for ASCII export of Org-mode files."
1714 :tag "Org Export ASCII"
1715 :group 'org-export)
1716
1717 (defcustom org-export-ascii-show-new-buffer t
1718 "Non-nil means, popup buffer containing the exported ASCII text.
1719 Otherwise the buffer will just be saved to a file and stay hidden."
1720 :group 'org-export-ascii
1721 :type 'boolean)
1722
1723 (defgroup org-export-xml nil
1724 "Options specific for XML export of Org-mode files."
1725 :tag "Org Export XML"
1726 :group 'org-export)
1727
1728 (defcustom org-export-xml-type 'xoxo ;kw, if we have only one.
1729 "The kind of XML to be produced by the XML exporter.
1730 Allowed values are:
1731 xoxo The XOXO exporter."
1732 :group 'org-export-xml
1733 :type '(choice
1734 (const :tag "XOXO" xoxo)))
1735
1736 (defgroup org-export-html nil
1737 "Options specific for HTML export of Org-mode files."
1738 :tag "Org Export HTML"
1739 :group 'org-export)
1740
1741 (defcustom org-export-html-style
1742 "<style type=\"text/css\">
1743 html {
1744 font-family: Times, serif;
1745 font-size: 12pt;
1746 }
1747 .title { text-align: center; }
1748 .todo, .deadline { color: red; }
1749 .done { color: green; }
1750 .target { background-color: lavender; }
1751 pre {
1752 border: 1pt solid #AEBDCC;
1753 background-color: #F3F5F7;
1754 padding: 5pt;
1755 font-family: courier, monospace;
1756 }
1757 table { border-collapse: collapse; }
1758 td, th {
1759 vertical-align: top;
1760 border: 1pt solid #ADB9CC;
1761 }
1762 </style>"
1763 "The default style specification for exported HTML files.
1764 Since there are different ways of setting style information, this variable
1765 needs to contain the full HTML structure to provide a style, including the
1766 surrounding HTML tags. The style specifications should include definitions
1767 for new classes todo, done, title, and deadline. For example, legal values
1768 would be:
1769
1770 <style type=\"text/css\">
1771 p { font-weight: normal; color: gray; }
1772 h1 { color: black; }
1773 .title { text-align: center; }
1774 .todo, .deadline { color: red; }
1775 .done { color: green; }
1776 </style>
1777
1778 or, if you want to keep the style in a file,
1779
1780 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1781
1782 As the value of this option simply gets inserted into the HTML <head> header,
1783 you can \"misuse\" it to add arbitrary text to the header."
1784 :group 'org-export-html
1785 :type 'string)
1786
1787 (defcustom org-export-html-link-org-files-as-html t
1788 "Non-nil means, make file links to `file.org' point to `file.html'.
1789 When org-mode is exporting an org-mode file to HTML, links to
1790 non-html files are directly put into a href tag in HTML.
1791 However, links to other Org-mode files (recognized by the
1792 extension `.org.) should become links to the corresponding html
1793 file, assuming that the linked org-mode file will also be
1794 converted to HTML.
1795 When nil, the links still point to the plain `.org' file."
1796 :group 'org-export-html
1797 :type 'boolean)
1798
1799 (defcustom org-export-html-inline-images t
1800 "Non-nil means, inline images into exported HTML pages.
1801 The link will still be to the original location of the image file.
1802 So if you are moving the page, lets say to your public HTML site,
1803 you will have to move the image and maybe change the link."
1804 :group 'org-export-html
1805 :type 'boolean)
1806
1807 (defcustom org-export-html-expand t
1808 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1809 When nil, these tags will be exported as plain text and therefore
1810 not be interpreted by a browser.
1811
1812 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1813 :group 'org-export-html
1814 :type 'boolean)
1815
1816 (defcustom org-export-html-table-tag
1817 "<table border=1 cellspacing=0 cellpadding=6>"
1818 "The HTML tag used to start a table.
1819 This must be a <table> tag, but you may change the options like
1820 borders and spacing."
1821 :group 'org-export-html
1822 :type 'string)
1823
1824 (defcustom org-export-html-with-timestamp nil
1825 "If non-nil, write `org-export-html-html-helper-timestamp'
1826 into the exported HTML text. Otherwise, the buffer will just be saved
1827 to a file."
1828 :group 'org-export-html
1829 :type 'boolean)
1830
1831 (defcustom org-export-html-html-helper-timestamp
1832 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1833 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1834 :group 'org-export-html
1835 :type 'string)
1836
1837 (defcustom org-export-html-show-new-buffer nil
1838 "Non-nil means, popup buffer containing the exported html text.
1839 Otherwise, the buffer will just be saved to a file and stay hidden."
1840 :group 'org-export-html
1841 :type 'boolean)
1842
1843 (defgroup org-export-icalendar nil
1844 "Options specific for iCalendar export of Org-mode files."
1845 :tag "Org Export iCalendar"
1846 :group 'org-export)
1847
1848 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1849 "The file name for the iCalendar file covering all agenda files.
1850 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1851 :group 'org-export-icalendar
1852 :type 'file)
1853
1854 (defcustom org-icalendar-include-todo nil
1855 "Non-nil means, export to iCalendar files should also cover TODO items."
1856 :group 'org-export-icalendar
1857 :type 'boolean)
1858
1859 (defcustom org-icalendar-combined-name "OrgMode"
1860 "Calendar name for the combined iCalendar representing all agenda files."
1861 :group 'org-export-icalendar
1862 :type 'string)
1863
1864 (defgroup org-font-lock nil
1865 "Font-lock settings for highlighting in Org-mode."
1866 :tag "Org Font Lock"
1867 :group 'org)
1868
1869 (defcustom org-level-color-stars-only nil
1870 "Non-nil means fontify only the stars in each headline.
1871 When nil, the entire headline is fontified.
1872 Changing it requires restart of `font-lock-mode' to become effective
1873 also in regions already fontified."
1874 :group 'org-font-lock
1875 :type 'boolean)
1876
1877 (defcustom org-hide-leading-stars nil
1878 "Non-nil means, hide the first N-1 stars in a headline.
1879 This works by using the face `org-hide' for these stars. This
1880 face is white for a light background, and black for a dark
1881 background. You may have to customize the face `org-hide' to
1882 make this work.
1883 Changing it requires restart of `font-lock-mode' to become effective
1884 also in regions already fontified.
1885 You may also set this on a per-file basis by adding one of the following
1886 lines to the buffer:
1887
1888 #+STARTUP: hidestars
1889 #+STARTUP: showstars"
1890 :group 'org-font-lock
1891 :type 'boolean)
1892
1893 (defcustom org-fontify-done-headline nil
1894 "Non-nil means, change the face of a headline if it is marked DONE.
1895 Normally, only the TODO/DONE keyword indicates the state of a headline.
1896 When this is non-nil, the headline after the keyword is set to the
1897 `org-headline-done' as an additional indication."
1898 :group 'org-font-lock
1899 :type 'boolean)
1900
1901 (defcustom org-fontify-emphasized-text t
1902 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
1903 Changing this variable requires a restart of Emacs to take effect."
1904 :group 'org-font-lock
1905 :type 'boolean)
1906
1907 (defgroup org-faces nil
1908 "Faces in Org-mode."
1909 :tag "Org Faces"
1910 :group 'org-font-lock)
1911
1912 (defun org-compatible-face (specs)
1913 "Make a compatible face specification.
1914 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
1915 For them we convert a (min-colors 8) entry to a `tty' entry and move it
1916 to the top of the list. The `min-colors' attribute will be removed from
1917 any other entries, and any resulting duplicates will be removed entirely."
1918 (if (or (featurep 'xemacs) (< emacs-major-version 22))
1919 (let (r e a)
1920 (while (setq e (pop specs))
1921 (cond
1922 ((memq (car e) '(t default)) (push e r))
1923 ((setq a (member '(min-colors 8) (car e)))
1924 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
1925 (cdr e)))))
1926 ((setq a (assq 'min-colors (car e)))
1927 (setq e (cons (delq a (car e)) (cdr e)))
1928 (or (assoc (car e) r) (push e r)))
1929 (t (or (assoc (car e) r) (push e r)))))
1930 (nreverse r))
1931 specs))
1932
1933 (defface org-hide
1934 '((((background light)) (:foreground "white"))
1935 (((background dark)) (:foreground "black")))
1936 "Face used to hide leading stars in headlines.
1937 The forground color of this face should be equal to the background
1938 color of the frame."
1939 :group 'org-faces)
1940
1941 (defface org-level-1 ;; font-lock-function-name-face
1942 (org-compatible-face
1943 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
1944 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
1945 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
1946 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
1947 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
1948 (t (:bold t))))
1949 "Face used for level 1 headlines."
1950 :group 'org-faces)
1951
1952 (defface org-level-2 ;; font-lock-variable-name-face
1953 (org-compatible-face
1954 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
1955 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
1956 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
1957 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
1958 (t (:bold t))))
1959 "Face used for level 2 headlines."
1960 :group 'org-faces)
1961
1962 (defface org-level-3 ;; font-lock-keyword-face
1963 (org-compatible-face
1964 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
1965 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
1966 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
1967 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
1968 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
1969 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
1970 (t (:bold t))))
1971 "Face used for level 3 headlines."
1972 :group 'org-faces)
1973
1974 (defface org-level-4 ;; font-lock-comment-face
1975 (org-compatible-face
1976 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
1977 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
1978 (((class color) (min-colors 16) (background light)) (:foreground "red"))
1979 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
1980 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
1981 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
1982 (t (:bold t))))
1983 "Face used for level 4 headlines."
1984 :group 'org-faces)
1985
1986 (defface org-level-5 ;; font-lock-type-face
1987 (org-compatible-face
1988 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
1989 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
1990 (((class color) (min-colors 8)) (:foreground "green"))))
1991 "Face used for level 5 headlines."
1992 :group 'org-faces)
1993
1994 (defface org-level-6 ;; font-lock-constant-face
1995 (org-compatible-face
1996 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
1997 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
1998 (((class color) (min-colors 8)) (:foreground "magenta"))))
1999 "Face used for level 6 headlines."
2000 :group 'org-faces)
2001
2002 (defface org-level-7 ;; font-lock-builtin-face
2003 (org-compatible-face
2004 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2005 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2006 (((class color) (min-colors 8)) (:foreground "blue")))) ;; FIXME: for dark bg?
2007 "Face used for level 7 headlines."
2008 :group 'org-faces)
2009
2010 (defface org-level-8 ;; font-lock-string-face
2011 (org-compatible-face
2012 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2013 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2014 (((class color) (min-colors 8)) (:foreground "green"))))
2015 "Face used for level 8 headlines."
2016 :group 'org-faces)
2017
2018 (defface org-special-keyword ;; font-lock-string-face
2019 (org-compatible-face
2020 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2021 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2022 (t (:italic t))))
2023 "Face used for special keywords."
2024 :group 'org-faces)
2025
2026 (defface org-warning ;; font-lock-warning-face
2027 (org-compatible-face
2028 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2029 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2030 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2031 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2032 (t (:bold t))))
2033 "Face for deadlines and TODO keywords."
2034 :group 'org-faces)
2035
2036 (defface org-headline-done ;; font-lock-string-face
2037 (org-compatible-face
2038 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2039 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2040 (((class color) (min-colors 8) (background light)) (:bold nil))))
2041 "Face used to indicate that a headline is DONE.
2042 This face is only used if `org-fontify-done-headline' is set."
2043 :group 'org-faces)
2044
2045 (defface org-link
2046 '((((class color) (background light)) (:foreground "Purple" :underline t))
2047 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2048 (t (:underline t)))
2049 "Face for links."
2050 :group 'org-faces)
2051
2052 (defface org-date
2053 '((((class color) (background light)) (:foreground "Purple" :underline t))
2054 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2055 (t (:underline t)))
2056 "Face for links."
2057 :group 'org-faces)
2058
2059 (defface org-tag
2060 '((t (:bold t)))
2061 "Face for tags."
2062 :group 'org-faces)
2063
2064 (defface org-todo ;; font-lock-warning-face
2065 (org-compatible-face
2066 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2067 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2068 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2069 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2070 (t (:inverse-video t :bold t))))
2071 "Face for TODO keywords."
2072 :group 'org-faces)
2073
2074 (defface org-done ;; font-lock-type-face
2075 (org-compatible-face
2076 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2077 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2078 (((class color) (min-colors 8)) (:foreground "green"))
2079 (t (:bold t))))
2080 "Face used for DONE."
2081 :group 'org-faces)
2082
2083 (defface org-table ;; font-lock-function-name-face
2084 (org-compatible-face
2085 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2086 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2087 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2088 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2089 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2090 (((class color) (min-colors 8) (background dark)))))
2091 "Face used for tables."
2092 :group 'org-faces)
2093
2094 (defface org-formula
2095 (org-compatible-face
2096 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2097 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2098 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2099 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2100 (t (:bold t :italic t))))
2101 "Face for formulas."
2102 :group 'org-faces)
2103
2104 (defface org-scheduled-today
2105 (org-compatible-face
2106 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2107 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2108 (((class color) (min-colors 8)) (:foreground "green"))
2109 (t (:bold t :italic t))))
2110 "Face for items scheduled for a certain day."
2111 :group 'org-faces)
2112
2113 (defface org-scheduled-previously
2114 (org-compatible-face
2115 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2116 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2117 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2118 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2119 (t (:bold t))))
2120 "Face for items scheduled previously, and not yet done."
2121 :group 'org-faces)
2122
2123 (defface org-time-grid ;; font-lock-variable-name-face
2124 (org-compatible-face
2125 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2126 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2127 (((class color) (min-colors 8)) (:foreground "yellow" :weight light)))) ; FIXME: turn off???
2128 "Face used for time grids."
2129 :group 'org-faces)
2130
2131 (defconst org-level-faces
2132 '(org-level-1 org-level-2 org-level-3 org-level-4
2133 org-level-5 org-level-6 org-level-7 org-level-8
2134 ))
2135 (defconst org-n-levels (length org-level-faces))
2136
2137 (defconst org-bold-re
2138 (if (featurep 'xemacs)
2139 "\\([ ]\\|^\\)\\(\\*\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)"
2140 "\\([ ]\\|^\\)\\(\\*\\(\\w[[:word:] -_]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)")
2141 "Regular expression for bold emphasis.")
2142 (defconst org-italic-re
2143 (if (featurep 'xemacs)
2144 "\\([ ]\\|^\\)\\(/\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)/\\)\\([ ,.]\\|$\\)"
2145 "\\([ ]\\|^\\)\\(/\\(\\w[[:word:] -_]*?\\w\\)/\\)\\([ ,.]\\|$\\)")
2146 "Regular expression for italic emphasis.")
2147 (defconst org-underline-re
2148 (if (featurep 'xemacs)
2149 "\\([ ]\\|^\\)\\(_\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)_\\)\\([ ,.]\\|$\\)"
2150 "\\([ ]\\|^\\)\\(_\\(\\w[[:word:] -_]*?\\w\\)_\\)\\([ ,.]\\|$\\)")
2151 "Regular expression for underline emphasis.")
2152
2153 ;; Variables for pre-computed regular expressions, all buffer local
2154 (defvar org-done-string nil
2155 "The last string in `org-todo-keywords', indicating an item is DONE.")
2156 (make-variable-buffer-local 'org-done-string)
2157 (defvar org-todo-regexp nil
2158 "Matches any of the TODO state keywords.")
2159 (make-variable-buffer-local 'org-todo-regexp)
2160 (defvar org-not-done-regexp nil
2161 "Matches any of the TODO state keywords except the last one.")
2162 (make-variable-buffer-local 'org-not-done-regexp)
2163 (defvar org-todo-line-regexp nil
2164 "Matches a headline and puts TODO state into group 2 if present.")
2165 (make-variable-buffer-local 'org-todo-line-regexp)
2166 (defvar org-nl-done-regexp nil
2167 "Matches newline followed by a headline with the DONE keyword.")
2168 (make-variable-buffer-local 'org-nl-done-regexp)
2169 (defvar org-looking-at-done-regexp nil
2170 "Matches the DONE keyword a point.")
2171 (make-variable-buffer-local 'org-looking-at-done-regexp)
2172 (defvar org-todo-kwd-priority-p nil
2173 "Do TODO items have priorities?")
2174 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2175 (defvar org-todo-kwd-max-priority nil
2176 "Maximum priority of TODO items.")
2177 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2178 (defvar org-ds-keyword-length 12
2179 "Maximum length of the Deadline and SCHEDULED keywords.")
2180 (make-variable-buffer-local 'org-ds-keyword-length)
2181 (defvar org-deadline-regexp nil
2182 "Matches the DEADLINE keyword.")
2183 (make-variable-buffer-local 'org-deadline-regexp)
2184 (defvar org-deadline-time-regexp nil
2185 "Matches the DEADLINE keyword together with a time stamp.")
2186 (make-variable-buffer-local 'org-deadline-time-regexp)
2187 (defvar org-deadline-line-regexp nil
2188 "Matches the DEADLINE keyword and the rest of the line.")
2189 (make-variable-buffer-local 'org-deadline-line-regexp)
2190 (defvar org-scheduled-regexp nil
2191 "Matches the SCHEDULED keyword.")
2192 (make-variable-buffer-local 'org-scheduled-regexp)
2193 (defvar org-scheduled-time-regexp nil
2194 "Matches the SCHEDULED keyword together with a time stamp.")
2195 (make-variable-buffer-local 'org-scheduled-time-regexp)
2196
2197 (defun org-set-regexps-and-options ()
2198 "Precompute regular expressions for current buffer."
2199 (when (eq major-mode 'org-mode)
2200 (let ((re (org-make-options-regexp
2201 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2202 "STARTUP" "ARCHIVE")))
2203 (splitre "[ \t]+")
2204 kwds int key value cat arch)
2205 (save-excursion
2206 (save-restriction
2207 (widen)
2208 (goto-char (point-min))
2209 (while (re-search-forward re nil t)
2210 (setq key (match-string 1) value (match-string 2))
2211 (cond
2212 ((equal key "CATEGORY")
2213 (if (string-match "[ \t]+$" value)
2214 (setq value (replace-match "" t t value)))
2215 (setq cat (intern value)))
2216 ((equal key "SEQ_TODO")
2217 (setq int 'sequence
2218 kwds (append kwds (org-split-string value splitre))))
2219 ((equal key "PRI_TODO")
2220 (setq int 'priority
2221 kwds (append kwds (org-split-string value splitre))))
2222 ((equal key "TYP_TODO")
2223 (setq int 'type
2224 kwds (append kwds (org-split-string value splitre))))
2225 ((equal key "STARTUP")
2226 (let ((opts (org-split-string value splitre))
2227 (set '(("fold" org-startup-folded t)
2228 ("overview" org-startup-folded t)
2229 ("nofold" org-startup-folded nil)
2230 ("showall" org-startup-folded nil)
2231 ("content" org-startup-folded content)
2232 ("hidestars" org-hide-leading-stars t)
2233 ("showstars" org-hide-leading-stars nil)
2234 ("odd" org-odd-levels-only t)
2235 ("oddeven" org-odd-levels-only nil)
2236 ("align" org-startup-align-all-tables t)
2237 ("noalign" org-startup-align-all-tables nil)
2238 ("dlcheck" org-startup-with-deadline-check t)
2239 ("nodlcheck" org-startup-with-deadline-check nil)))
2240 l var val)
2241 (while (setq l (assoc (pop opts) set))
2242 (setq var (nth 1 l) val (nth 2 l))
2243 (set (make-local-variable var) val))))
2244 ((equal key "ARCHIVE")
2245 (string-match " *$" value)
2246 (setq arch (replace-match "" t t value))
2247 (remove-text-properties 0 (length arch)
2248 '(face t fontified t) arch)))
2249 )))
2250 (and cat (set (make-local-variable 'org-category) cat))
2251 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2252 (and arch (set (make-local-variable 'org-archive-location) arch))
2253 (and int (set (make-local-variable 'org-todo-interpretation) int)))
2254 ;; Compute the regular expressions and other local variables
2255 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2256 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2257 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2258 (length org-scheduled-string)))
2259 org-done-string
2260 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2261 org-todo-regexp
2262 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2263 "\\|") "\\)\\>")
2264 org-not-done-regexp
2265 (concat "\\<\\("
2266 (mapconcat 'regexp-quote
2267 (nreverse (cdr (reverse org-todo-keywords)))
2268 "\\|")
2269 "\\)\\>")
2270 org-todo-line-regexp
2271 (concat "^\\(\\*+\\)[ \t]*\\("
2272 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2273 "\\)? *\\(.*\\)")
2274 org-nl-done-regexp
2275 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2276 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2277 org-deadline-regexp (concat "\\<" org-deadline-string)
2278 org-deadline-time-regexp
2279 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2280 org-deadline-line-regexp
2281 (concat "\\<\\(" org-deadline-string "\\).*")
2282 org-scheduled-regexp
2283 (concat "\\<" org-scheduled-string)
2284 org-scheduled-time-regexp
2285 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2286 (org-set-font-lock-defaults)))
2287
2288 ;; Tell the compiler about dynamically scoped variables,
2289 ;; and variables from other packages
2290 (defvar zmacs-regions) ; XEmacs regions
2291 (defvar original-date) ; dynamically scoped in calendar
2292 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2293 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2294 (defvar org-html-entities) ; defined later in this file
2295 (defvar org-goto-start-pos) ; dynamically scoped parameter
2296 (defvar org-time-was-given) ; dynamically scoped parameter
2297 (defvar org-ts-what) ; dynamically scoped parameter
2298 (defvar mark-active) ; Emacs only, not available in XEmacs.
2299 (defvar timecnt) ; dynamically scoped parameter
2300 (defvar levels-open) ; dynamically scoped parameter
2301 (defvar title) ; dynamically scoped parameter
2302 (defvar author) ; dynamically scoped parameter
2303 (defvar email) ; dynamically scoped parameter
2304 (defvar text) ; dynamically scoped parameter
2305 (defvar entry) ; dynamically scoped parameter
2306 (defvar date) ; dynamically scoped parameter
2307 (defvar language) ; dynamically scoped parameter
2308 (defvar options) ; dynamically scoped parameter
2309 (defvar ans1) ; dynamically scoped parameter
2310 (defvar ans2) ; dynamically scoped parameter
2311 (defvar starting-day) ; local variable
2312 (defvar include-all-loc) ; local variable
2313 (defvar vm-message-pointer) ; from vm
2314 (defvar vm-folder-directory) ; from vm
2315 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2316 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2317 (defvar gnus-group-name) ; from gnus
2318 (defvar gnus-article-current) ; from gnus
2319 (defvar w3m-current-url) ; from w3m
2320 (defvar mh-progs) ; from MH-E
2321 (defvar mh-current-folder) ; from MH-E
2322 (defvar mh-show-folder-buffer) ; from MH-E
2323 (defvar mh-index-folder) ; from MH-E
2324 (defvar mh-searcher) ; from MH-E
2325 (defvar org-selected-point) ; dynamically scoped parameter
2326 (defvar calendar-mode-map) ; from calendar.el
2327 (defvar last-arg) ; local variable
2328 (defvar remember-save-after-remembering) ; from remember.el
2329 (defvar remember-data-file) ; from remember.el
2330 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2331 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2332 (defvar orgtbl-mode) ; defined later in this file
2333 ;;; Define the mode
2334
2335 (defvar org-mode-map
2336 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2337 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22.")
2338 (copy-keymap outline-mode-map))
2339 "Keymap for Org-mode.")
2340
2341 (defvar org-struct-menu) ; defined later in this file
2342 (defvar org-org-menu) ; defined later in this file
2343 (defvar org-tbl-menu) ; defined later in this file
2344
2345 ;; We use a before-change function to check if a table might need
2346 ;; an update.
2347 (defvar org-table-may-need-update t
2348 "Indicates that a table might need an update.
2349 This variable is set by `org-before-change-function'.
2350 `org-table-align' sets it back to nil.")
2351 (defvar org-mode-hook nil)
2352 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2353 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2354
2355
2356 ;;;###autoload
2357 (define-derived-mode org-mode outline-mode "Org"
2358 "Outline-based notes management and organizer, alias
2359 \"Carsten's outline-mode for keeping track of everything.\"
2360
2361 Org-mode develops organizational tasks around a NOTES file which
2362 contains information about projects as plain text. Org-mode is
2363 implemented on top of outline-mode, which is ideal to keep the content
2364 of large files well structured. It supports ToDo items, deadlines and
2365 time stamps, which magically appear in the diary listing of the Emacs
2366 calendar. Tables are easily created with a built-in table editor.
2367 Plain text URL-like links connect to websites, emails (VM), Usenet
2368 messages (Gnus), BBDB entries, and any files related to the project.
2369 For printing and sharing of notes, an Org-mode file (or a part of it)
2370 can be exported as a structured ASCII or HTML file.
2371
2372 The following commands are available:
2373
2374 \\{org-mode-map}"
2375 (easy-menu-add org-org-menu)
2376 (easy-menu-add org-tbl-menu)
2377 (org-install-agenda-files-menu)
2378 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2379 (org-add-to-invisibility-spec '(org-cwidth))
2380 (setq outline-regexp "\\*+")
2381 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2382 (setq outline-level 'org-outline-level)
2383 (when (and org-ellipsis (stringp org-ellipsis))
2384 (unless org-display-table
2385 (setq org-display-table (make-display-table)))
2386 (set-display-table-slot org-display-table
2387 4 (string-to-vector org-ellipsis))
2388 (setq buffer-display-table org-display-table))
2389 (org-set-regexps-and-options)
2390 (if org-startup-truncated (setq truncate-lines t))
2391 (set (make-local-variable 'font-lock-unfontify-region-function)
2392 'org-unfontify-region)
2393 ;; Activate before-change-function
2394 (set (make-local-variable 'org-table-may-need-update) t)
2395 (org-add-hook 'before-change-functions 'org-before-change-function nil
2396 'local)
2397 ;; Paragraphs and auto-filling
2398 (org-set-autofill-regexps)
2399 (org-update-radio-target-regexp)
2400 ;; Settings for Calc embedded mode
2401 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2402 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2403 (if (and org-insert-mode-line-in-empty-file
2404 (interactive-p)
2405 (= (point-min) (point-max)))
2406 (insert " -*- mode: org -*-\n\n"))
2407
2408 ;; Get rid of Outline menus, they are not needed
2409 ;; Need to do this here because define-derived-mode sets up
2410 ;; the keymap so late.
2411 (if (featurep 'xemacs)
2412 (progn
2413 (delete-menu-item '("Headings"))
2414 (delete-menu-item '("Show"))
2415 (delete-menu-item '("Hide"))
2416 (set-menubar-dirty-flag))
2417 (define-key org-mode-map [menu-bar headings] 'undefined)
2418 (define-key org-mode-map [menu-bar hide] 'undefined)
2419 (define-key org-mode-map [menu-bar show] 'undefined))
2420
2421 (unless org-inhibit-startup
2422 (if org-startup-align-all-tables
2423 (org-table-map-tables 'org-table-align))
2424 (if org-startup-with-deadline-check
2425 (call-interactively 'org-check-deadlines)
2426 (cond
2427 ((eq org-startup-folded t)
2428 (org-cycle '(4)))
2429 ((eq org-startup-folded 'content)
2430 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2431 (org-cycle '(4)) (org-cycle '(4))))))))
2432
2433 (defsubst org-current-line (&optional pos)
2434 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2435
2436 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2437 mouse-map t)
2438 "Properties to remove when a string without properties is wanted.")
2439
2440 (defsubst org-match-string-no-properties (num &optional string)
2441 (if (featurep 'xemacs)
2442 (let ((s (match-string num string)))
2443 (remove-text-properties 0 (length s) org-rm-props s)
2444 s)
2445 (match-string-no-properties num string)))
2446
2447 (defsubst org-no-properties (s)
2448 (remove-text-properties 0 (length s) org-rm-props s)
2449 s)
2450
2451 (defun org-current-time ()
2452 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2453 (if (> org-time-stamp-rounding-minutes 0)
2454 (let ((r org-time-stamp-rounding-minutes)
2455 (time (decode-time)))
2456 (apply 'encode-time
2457 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2458 (nthcdr 2 time))))
2459 (current-time)))
2460
2461 (defun org-add-props (string plist &rest props)
2462 "Add text properties to entire string, from beginning to end.
2463 PLIST may be a list of properties, PROPS are individual properties and values
2464 that will be added to PLIST. Returns the string that was modified."
2465 (add-text-properties
2466 0 (length string) (if props (append plist props) plist) string)
2467 string)
2468 (put 'org-add-props 'lisp-indent-function 2)
2469
2470
2471 ;;; Font-Lock stuff
2472
2473 (defvar org-mouse-map (make-sparse-keymap))
2474 (define-key org-mouse-map
2475 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2476 (define-key org-mouse-map
2477 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2478 (when org-mouse-1-follows-link
2479 (define-key org-mouse-map [follow-link] 'mouse-face))
2480 (when org-tab-follows-link
2481 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2482 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2483 (when org-return-follows-link
2484 (define-key org-mouse-map [(return)] 'org-open-at-point)
2485 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2486
2487 (require 'font-lock)
2488
2489 (defconst org-non-link-chars "]\t\n\r<>")
2490 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
2491 "wl" "mhe" "rmail" "gnus" "shell"))
2492 (defconst org-link-re-with-space
2493 (concat
2494 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2495 "\\([^" org-non-link-chars " ]"
2496 "[^" org-non-link-chars "]*"
2497 "[^" org-non-link-chars " ]\\)>?")
2498 "Matches a link with spaces, optional angular brackets around it.")
2499
2500 (defconst org-link-re-with-space2
2501 (concat
2502 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2503 "\\([^" org-non-link-chars " ]"
2504 "[^]\t\n\r]*"
2505 "[^" org-non-link-chars " ]\\)>?")
2506 "Matches a link with spaces, optional angular brackets around it.")
2507
2508 (defconst org-angle-link-re
2509 (concat
2510 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2511 "\\([^" org-non-link-chars " ]"
2512 "[^" org-non-link-chars "]*"
2513 "\\)>")
2514 "Matches link with angular brackets, spaces are allowed.")
2515 (defconst org-plain-link-re
2516 (concat
2517 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2518 "\\([^]\t\n\r<>,;() ]+\\)")
2519 "Matches plain link, without spaces.")
2520
2521 (defconst org-bracket-link-regexp
2522 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2523 "Matches a link in double brackets.")
2524
2525 (defconst org-bracket-link-analytic-regexp
2526 (concat
2527 "\\[\\["
2528 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
2529 "\\([^]]+\\)"
2530 "\\]"
2531 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
2532 "\\]"))
2533 ; 1: http:
2534 ; 2: http
2535 ; 3: path
2536 ; 4: [desc]
2537 ; 5: desc
2538
2539
2540 (defconst org-ts-lengths
2541 (cons (length (format-time-string (car org-time-stamp-formats)))
2542 (length (format-time-string (cdr org-time-stamp-formats))))
2543 "This holds the lengths of the two different time formats.")
2544 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2545 "Regular expression for fast time stamp matching.")
2546 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2547 "Regular expression for fast time stamp matching.")
2548 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2549 "Regular expression matching time strings for analysis.")
2550 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2551 "Regular expression matching time stamps, with groups.")
2552 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2553 "Regular expression matching a time stamp range.")
2554 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2555 org-ts-regexp "\\)?")
2556 "Regular expression matching a time stamp or time stamp range.")
2557
2558 (defun org-activate-plain-links (limit)
2559 "Run through the buffer and add overlays to links."
2560 (if (re-search-forward org-plain-link-re limit t)
2561 (progn
2562 (add-text-properties (match-beginning 0) (match-end 0)
2563 (list 'mouse-face 'highlight
2564 'keymap org-mouse-map
2565 ))
2566 t)))
2567
2568 (defun org-activate-angle-links (limit)
2569 "Run through the buffer and add overlays to links."
2570 (if (re-search-forward org-angle-link-re limit t)
2571 (progn
2572 (add-text-properties (match-beginning 0) (match-end 0)
2573 (list 'mouse-face 'highlight
2574 'keymap org-mouse-map
2575 ))
2576 t)))
2577
2578 (defun org-activate-bracket-links (limit)
2579 "Run through the buffer and add overlays to bracketed links."
2580 (if (re-search-forward org-bracket-link-regexp limit t)
2581 (let* ((help (concat "LINK: "
2582 (org-match-string-no-properties 1)))
2583 ;; FIXME: above we should remove the escapes.
2584 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
2585 'keymap org-mouse-map 'mouse-face 'highlight
2586 'help-echo help))
2587 (vp (list 'rear-nonsticky t
2588 'keymap org-mouse-map 'mouse-face 'highlight
2589 'help-echo help)))
2590 ;; We need to remove the invisible property here. Table narrowing
2591 ;; may have made some of this invisible.
2592 (remove-text-properties (match-beginning 0) (match-end 0)
2593 '(invisible nil))
2594 (if (match-end 3)
2595 (progn
2596 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
2597 (add-text-properties (match-beginning 3) (match-end 3) vp)
2598 (add-text-properties (match-end 3) (match-end 0) ip))
2599 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
2600 (add-text-properties (match-beginning 1) (match-end 1) vp)
2601 (add-text-properties (match-end 1) (match-end 0) ip))
2602 t)))
2603
2604 (defun org-activate-dates (limit)
2605 "Run through the buffer and add overlays to dates."
2606 (if (re-search-forward org-tsr-regexp limit t)
2607 (progn
2608 (add-text-properties (match-beginning 0) (match-end 0)
2609 (list 'mouse-face 'highlight
2610 'keymap org-mouse-map))
2611 t)))
2612
2613 (defvar org-target-link-regexp nil
2614 "Regular expression matching radio targets in plain text.")
2615 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2616 "Regular expression matching a link target.")
2617 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2618 "Regular expression matching a link target.")
2619
2620 (defun org-activate-target-links (limit)
2621 "Run through the buffer and add overlays to target matches."
2622 (when org-target-link-regexp
2623 (let ((case-fold-search t))
2624 (if (re-search-forward org-target-link-regexp limit t)
2625 (progn
2626 (add-text-properties (match-beginning 0) (match-end 0)
2627 (list 'mouse-face 'highlight
2628 'keymap org-mouse-map
2629 'help-echo "Radio target link"
2630 'org-linked-text t))
2631 t)))))
2632
2633 (defun org-update-radio-target-regexp ()
2634 "Find all radio targets in this file and update the regular expression."
2635 (interactive)
2636 (when (memq 'radio org-activate-links)
2637 (setq org-target-link-regexp
2638 (org-make-target-link-regexp (org-all-targets 'radio)))
2639 (org-restart-font-lock)))
2640
2641 (defun org-hide-wide-columns (limit)
2642 (let (s e)
2643 (setq s (text-property-any (point) (or limit (point-max))
2644 'org-cwidth t))
2645 (when s
2646 (setq e (next-single-property-change s 'org-cwidth))
2647 (add-text-properties s e '(invisible org-cwidth intangible t))
2648 (goto-char e)
2649 t)))
2650
2651 (defun org-restart-font-lock ()
2652 "Restart font-lock-mode, to force refontification."
2653 (when (and (boundp 'font-lock-mode) font-lock-mode)
2654 (font-lock-mode -1)
2655 (font-lock-mode 1)))
2656
2657 (defun org-all-targets (&optional radio)
2658 "Return a list of all targets in this file.
2659 With optional argument RADIO, only find radio targets."
2660 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2661 rtn)
2662 (save-excursion
2663 (goto-char (point-min))
2664 (while (re-search-forward re nil t)
2665 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
2666 rtn)))
2667
2668 (defun org-make-target-link-regexp (targets)
2669 "Make regular expression matching all strings in TARGETS.
2670 The regular expression finds the targets also if there is a line break
2671 between words."
2672 (and targets
2673 (concat
2674 "\\<\\("
2675 (mapconcat
2676 (lambda (x)
2677 (while (string-match " +" x)
2678 (setq x (replace-match "\\s-+" t t x)))
2679 x)
2680 targets
2681 "\\|")
2682 "\\)\\>")))
2683
2684 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2685 "Matches CamelCase words, possibly with a star before it.")
2686
2687 (defun org-activate-camels (limit)
2688 "Run through the buffer and add overlays to dates."
2689 (if (re-search-forward org-camel-regexp limit t)
2690 (progn
2691 (add-text-properties (match-beginning 0) (match-end 0)
2692 (list 'mouse-face 'highlight
2693 'keymap org-mouse-map))
2694 t)))
2695
2696 (defun org-activate-tags (limit)
2697 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2698 (progn
2699 (add-text-properties (match-beginning 1) (match-end 1)
2700 (list 'mouse-face 'highlight
2701 'keymap org-mouse-map))
2702 t)))
2703
2704 (defun org-font-lock-level ()
2705 (save-excursion
2706 (org-back-to-heading t)
2707 (- (match-end 0) (match-beginning 0))))
2708
2709 (defun org-outline-level ()
2710 (save-excursion
2711 (looking-at outline-regexp)
2712 (if (match-beginning 1)
2713 (+ (org-get-string-indentation (match-string 1)) 1000)
2714 (- (match-end 0) (match-beginning 0)))))
2715
2716 (defvar org-font-lock-keywords nil)
2717
2718 (defun org-set-font-lock-defaults ()
2719 (let* ((em org-fontify-emphasized-text)
2720 (lk org-activate-links)
2721 (org-font-lock-extra-keywords
2722 (list
2723 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2724 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2725 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2726 (1 'org-table))
2727 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
2728 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
2729 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
2730 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
2731 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
2732 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
2733 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
2734 (if org-table-limit-column-width
2735 '(org-hide-wide-columns (0 nil append)))
2736 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2737 '(1 'org-todo t))
2738 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2739 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2740 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2741 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2742 ; (if em '("\\(\\W\\|^\\)\\(\\*\\w+\\*\\)\\(\\W\\|$\\)" 2 'bold prepend))
2743 ; (if em '("\\(\\W\\|^\\)\\(/\\w+/\\)\\(\\W\\|$\\)" 2 'italic prepend))
2744 ; (if em '("\\(\\W\\|^\\)\\(_\\w+_\\)\\(\\W\\|$\\)" 2 'underline prepend))
2745 (if em (list org-bold-re 2 ''bold 'prepend))
2746 (if em (list org-italic-re 2 ''italic 'prepend))
2747 (if em (list org-underline-re 2 ''underline 'prepend))
2748 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2749 "\\|" org-quote-string "\\)\\>")
2750 '(1 'org-special-keyword t))
2751 '("^#.*" (0 'font-lock-comment-face t))
2752 (if org-fontify-done-headline
2753 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2754 '(1 'org-done t) '(2 'org-headline-done t))
2755 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2756 '(1 'org-done t)))
2757 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2758 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2759 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2760 (if org-format-transports-properties-p
2761 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
2762 )))
2763 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
2764 ;; Now set the full font-lock-keywords
2765 (set (make-local-variable 'org-font-lock-keywords)
2766 org-font-lock-extra-keywords)
2767 (set (make-local-variable 'font-lock-defaults)
2768 '(org-font-lock-keywords t nil nil backward-paragraph))
2769 (kill-local-variable 'font-lock-keywords) nil))
2770
2771 (defvar org-m nil)
2772 (defvar org-l nil)
2773 (defvar org-f nil)
2774 (defun org-get-level-face (n)
2775 "Get the right face for match N in font-lock matching of healdines."
2776 (setq org-l (- (match-end 2) (match-beginning 1)))
2777 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2778 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2779 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
2780 (cond
2781 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2782 ((eq n 2) org-f)
2783 (t (if org-level-color-stars-only nil org-f))))
2784
2785 (defun org-unfontify-region (beg end &optional maybe_loudly)
2786 "Remove fontification and activation overlays from links."
2787 (font-lock-default-unfontify-region beg end)
2788 (let* ((buffer-undo-list t)
2789 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2790 (inhibit-modification-hooks t)
2791 deactivate-mark buffer-file-name buffer-file-truename)
2792 (remove-text-properties beg end
2793 '(mouse-face nil keymap nil org-linked-text nil
2794 invisible nil intangible nil))))
2795 ;;; Visibility cycling
2796
2797 (defvar org-cycle-global-status nil)
2798 (defvar org-cycle-subtree-status nil)
2799 (defun org-cycle (&optional arg)
2800 "Visibility cycling for Org-mode.
2801
2802 - When this function is called with a prefix argument, rotate the entire
2803 buffer through 3 states (global cycling)
2804 1. OVERVIEW: Show only top-level headlines.
2805 2. CONTENTS: Show all headlines of all levels, but no body text.
2806 3. SHOW ALL: Show everything.
2807
2808 - When point is at the beginning of a headline, rotate the subtree started
2809 by this line through 3 different states (local cycling)
2810 1. FOLDED: Only the main headline is shown.
2811 2. CHILDREN: The main headline and the direct children are shown.
2812 From this state, you can move to one of the children
2813 and zoom in further.
2814 3. SUBTREE: Show the entire subtree, including body text.
2815
2816 - When there is a numeric prefix, go up to a heading with level ARG, do
2817 a `show-subtree' and return to the previous cursor position. If ARG
2818 is negative, go up that many levels.
2819
2820 - When point is not at the beginning of a headline, execute
2821 `indent-relative', like TAB normally does. See the option
2822 `org-cycle-emulate-tab' for details.
2823
2824 - Special case: if point is the the beginning of the buffer and there is
2825 no headline in line 1, this function will act as if called with prefix arg."
2826 (interactive "P")
2827
2828 (if (or (and (bobp) (not (looking-at outline-regexp)))
2829 (equal arg '(4)))
2830 ;; special case: use global cycling
2831 (setq arg t))
2832
2833 (let ((outline-regexp
2834 (if org-cycle-include-plain-lists
2835 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2836 outline-regexp)))
2837
2838 (cond
2839
2840 ((org-at-table-p 'any)
2841 ;; Enter the table or move to the next field in the table
2842 (or (org-table-recognize-table.el)
2843 (progn
2844 (if arg (org-table-edit-field t)
2845 (org-table-justify-field-maybe)
2846 (org-table-next-field)))))
2847
2848 ((eq arg t) ;; Global cycling
2849
2850 (cond
2851 ((and (eq last-command this-command)
2852 (eq org-cycle-global-status 'overview))
2853 ;; We just created the overview - now do table of contents
2854 ;; This can be slow in very large buffers, so indicate action
2855 (message "CONTENTS...")
2856 (save-excursion
2857 ;; Visit all headings and show their offspring
2858 (goto-char (point-max))
2859 (catch 'exit
2860 (while (and (progn (condition-case nil
2861 (outline-previous-visible-heading 1)
2862 (error (goto-char (point-min))))
2863 t)
2864 (looking-at outline-regexp))
2865 (show-branches)
2866 (if (bobp) (throw 'exit nil))))
2867 (message "CONTENTS...done"))
2868 (setq org-cycle-global-status 'contents)
2869 (run-hook-with-args 'org-cycle-hook 'contents))
2870
2871 ((and (eq last-command this-command)
2872 (eq org-cycle-global-status 'contents))
2873 ;; We just showed the table of contents - now show everything
2874 (show-all)
2875 (message "SHOW ALL")
2876 (setq org-cycle-global-status 'all)
2877 (run-hook-with-args 'org-cycle-hook 'all))
2878
2879 (t
2880 ;; Default action: go to overview
2881 (hide-sublevels 1)
2882 (message "OVERVIEW")
2883 (setq org-cycle-global-status 'overview)
2884 (run-hook-with-args 'org-cycle-hook 'overview))))
2885
2886 ((integerp arg)
2887 ;; Show-subtree, ARG levels up from here.
2888 (save-excursion
2889 (org-back-to-heading)
2890 (outline-up-heading (if (< arg 0) (- arg)
2891 (- (funcall outline-level) arg)))
2892 (org-show-subtree)))
2893
2894 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2895 ;; At a heading: rotate between three different views
2896 (org-back-to-heading)
2897 (let ((goal-column 0) eoh eol eos)
2898 ;; First, some boundaries
2899 (save-excursion
2900 (org-back-to-heading)
2901 (save-excursion
2902 (beginning-of-line 2)
2903 (while (and (not (eobp)) ;; this is like `next-line'
2904 (get-char-property (1- (point)) 'invisible))
2905 (beginning-of-line 2)) (setq eol (point)))
2906 (outline-end-of-heading) (setq eoh (point))
2907 (org-end-of-subtree t) (setq eos (point))
2908 (outline-next-heading))
2909 ;; Find out what to do next and set `this-command'
2910 (cond
2911 ((= eos eoh)
2912 ;; Nothing is hidden behind this heading
2913 (message "EMPTY ENTRY")
2914 (setq org-cycle-subtree-status nil))
2915 ((>= eol eos)
2916 ;; Entire subtree is hidden in one line: open it
2917 (org-show-entry)
2918 (show-children)
2919 (message "CHILDREN")
2920 (setq org-cycle-subtree-status 'children)
2921 (run-hook-with-args 'org-cycle-hook 'children))
2922 ((and (eq last-command this-command)
2923 (eq org-cycle-subtree-status 'children))
2924 ;; We just showed the children, now show everything.
2925 (org-show-subtree)
2926 (message "SUBTREE")
2927 (setq org-cycle-subtree-status 'subtree)
2928 (run-hook-with-args 'org-cycle-hook 'subtree))
2929 (t
2930 ;; Default action: hide the subtree.
2931 (hide-subtree)
2932 (message "FOLDED")
2933 (setq org-cycle-subtree-status 'folded)
2934 (run-hook-with-args 'org-cycle-hook 'folded)))))
2935
2936 ;; TAB emulation
2937 (buffer-read-only (org-back-to-heading))
2938 ((if (and (eq org-cycle-emulate-tab 'white)
2939 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2940 t
2941 (eq org-cycle-emulate-tab t))
2942 (if (and (looking-at "[ \n\r\t]")
2943 (string-match "^[ \t]*$" (buffer-substring
2944 (point-at-bol) (point))))
2945 (progn
2946 (beginning-of-line 1)
2947 (and (looking-at "[ \t]+") (replace-match ""))))
2948 (indent-relative))
2949
2950 (t (save-excursion
2951 (org-back-to-heading)
2952 (org-cycle))))))
2953
2954 (defun org-optimize-window-after-visibility-change (state)
2955 "Adjust the window after a change in outline visibility.
2956 This function is the default value of the hook `org-cycle-hook'."
2957 (when (get-buffer-window (current-buffer))
2958 (cond
2959 ((eq state 'overview) (org-first-headline-recenter 1))
2960 ((eq state 'content) nil)
2961 ((eq state 'all) nil)
2962 ((eq state 'folded) nil)
2963 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2964 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
2965
2966 (defun org-subtree-end-visible-p ()
2967 "Is the end of the current subtree visible?"
2968 (pos-visible-in-window-p
2969 (save-excursion (org-end-of-subtree t) (point))))
2970
2971 (defun org-first-headline-recenter (&optional N)
2972 "Move cursor to the first headline and recenter the headline.
2973 Optional argument N means, put the headline into the Nth line of the window."
2974 (goto-char (point-min))
2975 (when (re-search-forward (concat "^" outline-regexp) nil t)
2976 (beginning-of-line)
2977 (recenter (prefix-numeric-value N))))
2978
2979 (defvar org-goto-window-configuration nil)
2980 (defvar org-goto-marker nil)
2981 (defvar org-goto-map (make-sparse-keymap))
2982 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2983 (while (setq cmd (pop cmds))
2984 (substitute-key-definition cmd cmd org-goto-map global-map)))
2985 (define-key org-goto-map "\C-m" 'org-goto-ret)
2986 (define-key org-goto-map [(left)] 'org-goto-left)
2987 (define-key org-goto-map [(right)] 'org-goto-right)
2988 (define-key org-goto-map [(?q)] 'org-goto-quit)
2989 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2990 (define-key org-goto-map "\C-i" 'org-cycle)
2991 (define-key org-goto-map [(tab)] 'org-cycle)
2992 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2993 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2994 (define-key org-goto-map "n" 'outline-next-visible-heading)
2995 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2996 (define-key org-goto-map "f" 'outline-forward-same-level)
2997 (define-key org-goto-map "b" 'outline-backward-same-level)
2998 (define-key org-goto-map "u" 'outline-up-heading)
2999 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3000 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3001 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3002 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3003 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3004 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3005 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3006
3007 (defconst org-goto-help
3008 "Select a location to jump to, press RET
3009 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3010
3011 (defun org-goto ()
3012 "Go to a different location of the document, keeping current visibility.
3013
3014 When you want to go to a different location in a document, the fastest way
3015 is often to fold the entire buffer and then dive into the tree. This
3016 method has the disadvantage, that the previous location will be folded,
3017 which may not be what you want.
3018
3019 This command works around this by showing a copy of the current buffer in
3020 overview mode. You can dive into the tree in that copy, to find the
3021 location you want to reach. When pressing RET, the command returns to the
3022 original buffer in which the visibility is still unchanged. It then jumps
3023 to the new location, making it and the headline hierarchy above it visible."
3024 (interactive)
3025 (let* ((org-goto-start-pos (point))
3026 (selected-point
3027 (org-get-location (current-buffer) org-goto-help)))
3028 (if selected-point
3029 (progn
3030 (org-mark-ring-push org-goto-start-pos)
3031 (goto-char selected-point)
3032 (if (or (org-invisible-p) (org-invisible-p2))
3033 (org-show-hierarchy-above)))
3034 (error "Quit"))))
3035
3036 (defun org-get-location (buf help)
3037 "Let the user select a location in the Org-mode buffer BUF.
3038 This function uses a recursive edit. It returns the selected position
3039 or nil."
3040 (let (org-selected-point)
3041 (save-excursion
3042 (save-window-excursion
3043 (delete-other-windows)
3044 (switch-to-buffer (get-buffer-create "*org-goto*"))
3045 (with-output-to-temp-buffer "*Help*"
3046 (princ help))
3047 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3048 (setq buffer-read-only nil)
3049 (erase-buffer)
3050 (insert-buffer-substring buf)
3051 (let ((org-startup-truncated t)
3052 (org-startup-folded t)
3053 (org-startup-align-all-tables nil)
3054 (org-startup-with-deadline-check nil))
3055 (org-mode))
3056 (setq buffer-read-only t)
3057 (if (boundp 'org-goto-start-pos)
3058 (goto-char org-goto-start-pos)
3059 (goto-char (point-min)))
3060 (org-beginning-of-line)
3061 (message "Select location and press RET")
3062 ;; now we make sure that during selection, ony very few keys work
3063 ;; and that it is impossible to switch to another window.
3064 (let ((gm (current-global-map))
3065 (overriding-local-map org-goto-map))
3066 (unwind-protect
3067 (progn
3068 (use-global-map org-goto-map)
3069 (recursive-edit))
3070 (use-global-map gm)))))
3071 (kill-buffer "*org-goto*")
3072 org-selected-point))
3073
3074 ;; FIXME: It may not be a good idea to temper with the prefix argument...
3075 (defun org-goto-ret (&optional arg)
3076 "Finish `org-goto' by going to the new location."
3077 (interactive "P")
3078 (setq org-selected-point (point)
3079 current-prefix-arg arg)
3080 (throw 'exit nil))
3081
3082 (defun org-goto-left ()
3083 "Finish `org-goto' by going to the new location."
3084 (interactive)
3085 (if (org-on-heading-p)
3086 (progn
3087 (beginning-of-line 1)
3088 (setq org-selected-point (point)
3089 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3090 (throw 'exit nil))
3091 (error "Not on a heading")))
3092
3093 (defun org-goto-right ()
3094 "Finish `org-goto' by going to the new location."
3095 (interactive)
3096 (if (org-on-heading-p)
3097 (progn
3098 (outline-end-of-subtree)
3099 (or (eobp) (forward-char 1))
3100 (setq org-selected-point (point)
3101 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3102 (throw 'exit nil))
3103 (error "Not on a heading")))
3104
3105 (defun org-goto-quit ()
3106 "Finish `org-goto' without cursor motion."
3107 (interactive)
3108 (setq org-selected-point nil)
3109 (throw 'exit nil))
3110
3111 ;;; Promotion, Demotion, Inserting new headlines
3112
3113 (defvar org-ignore-region nil
3114 "To temporarily disable the active region.")
3115
3116 (defun org-insert-heading (&optional force-heading)
3117 "Insert a new heading or item with same depth at point."
3118 (interactive "P")
3119 (when (or force-heading (not (org-insert-item)))
3120 (let* ((head (save-excursion
3121 (condition-case nil
3122 (org-back-to-heading)
3123 (error (outline-next-heading)))
3124 (prog1 (match-string 0)
3125 (funcall outline-level)))))
3126 (cond
3127 ((and (org-on-heading-p) (bolp)
3128 (save-excursion (backward-char 1) (not (org-invisible-p))))
3129 (open-line 1))
3130 ((bolp) nil)
3131 (t (newline)))
3132 (insert head)
3133 (just-one-space)
3134 (run-hooks 'org-insert-heading-hook))))
3135
3136 (defun org-insert-item ()
3137 "Insert a new item at the current level.
3138 Return t when things worked, nil when we are not in an item."
3139 (when (save-excursion
3140 (condition-case nil
3141 (progn
3142 (org-beginning-of-item)
3143 (org-at-item-p)
3144 t)
3145 (error nil)))
3146 (let* ((bul (match-string 0))
3147 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3148 (match-end 0)))
3149 (eowcol (save-excursion (goto-char eow) (current-column))))
3150 (cond
3151 ((and (org-at-item-p) (<= (point) eow))
3152 ;; before the bullet
3153 (beginning-of-line 1)
3154 (open-line 1))
3155 ((<= (point) eow)
3156 (beginning-of-line 1))
3157 (t (newline)))
3158 (insert bul)
3159 (just-one-space))
3160 (org-maybe-renumber-ordered-list)
3161 t))
3162
3163 (defun org-insert-todo-heading (arg)
3164 "Insert a new heading with the same level and TODO state as current heading.
3165 If the heading has no TODO state, or if the state is DONE, use the first
3166 state (TODO by default). Also with prefix arg, force first state."
3167 (interactive "P")
3168 (org-insert-heading)
3169 (save-excursion
3170 (org-back-to-heading)
3171 (outline-previous-heading)
3172 (looking-at org-todo-line-regexp))
3173 (if (or arg
3174 (not (match-beginning 2))
3175 (equal (match-string 2) org-done-string))
3176 (insert (car org-todo-keywords) " ")
3177 (insert (match-string 2) " ")))
3178
3179 (defun org-promote-subtree ()
3180 "Promote the entire subtree.
3181 See also `org-promote'."
3182 (interactive)
3183 (save-excursion
3184 (org-map-tree 'org-promote)))
3185
3186 (defun org-demote-subtree ()
3187 "Demote the entire subtree. See `org-demote'.
3188 See also `org-promote'."
3189 (interactive)
3190 (save-excursion
3191 (org-map-tree 'org-demote)))
3192
3193 (defun org-do-promote ()
3194 "Promote the current heading higher up the tree.
3195 If the region is active in `transient-mark-mode', promote all headings
3196 in the region."
3197 (interactive)
3198 (save-excursion
3199 (if (org-region-active-p)
3200 (org-map-region 'org-promote (region-beginning) (region-end))
3201 (org-promote)))
3202 (org-fix-position-after-promote))
3203
3204 (defun org-do-demote ()
3205 "Demote the current heading lower down the tree.
3206 If the region is active in `transient-mark-mode', demote all headings
3207 in the region."
3208 (interactive)
3209 (save-excursion
3210 (if (org-region-active-p)
3211 (org-map-region 'org-demote (region-beginning) (region-end))
3212 (org-demote)))
3213 (org-fix-position-after-promote))
3214
3215 (defun org-fix-position-after-promote ()
3216 "Make sure that after pro/demotion cursor position is right."
3217 (and (equal (char-after) ?\ )
3218 (equal (char-before) ?*)
3219 (forward-char 1)))
3220
3221 (defun org-get-legal-level (level change)
3222 "Rectify a level change under the influence of `org-odd-levels-only'
3223 LEVEL is a current level, CHANGE is by how much the level should be
3224 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3225 even level numbers will become the next higher odd number."
3226 (if org-odd-levels-only
3227 (cond ((not change) (1+ (* 2 (/ level 2))))
3228 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3229 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3230 (max 1 (+ level change))))
3231
3232 (defun org-promote ()
3233 "Promote the current heading higher up the tree.
3234 If the region is active in `transient-mark-mode', promote all headings
3235 in the region."
3236 (org-back-to-heading t)
3237 (let* ((level (save-match-data (funcall outline-level)))
3238 (up-head (make-string (org-get-legal-level level -1) ?*))
3239 (diff (abs (- level (length up-head)))))
3240 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3241 (replace-match up-head nil t)
3242 ;; Fixup tag positioning
3243 (and org-auto-align-tags (org-set-tags nil t))
3244 (if org-adapt-indentation
3245 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
3246 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
3247
3248 (defun org-demote ()
3249 "Demote the current heading lower down the tree.
3250 If the region is active in `transient-mark-mode', demote all headings
3251 in the region."
3252 (org-back-to-heading t)
3253 (let* ((level (save-match-data (funcall outline-level)))
3254 (down-head (make-string (org-get-legal-level level 1) ?*))
3255 (diff (abs (- level (length down-head)))))
3256 (replace-match down-head nil t)
3257 ;; Fixup tag positioning
3258 (and org-auto-align-tags (org-set-tags nil t))
3259 (if org-adapt-indentation
3260 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
3261
3262 (defun org-map-tree (fun)
3263 "Call FUN for every heading underneath the current one."
3264 (org-back-to-heading)
3265 (let ((level (funcall outline-level)))
3266 (save-excursion
3267 (funcall fun)
3268 (while (and (progn
3269 (outline-next-heading)
3270 (> (funcall outline-level) level))
3271 (not (eobp)))
3272 (funcall fun)))))
3273
3274 (defun org-map-region (fun beg end)
3275 "Call FUN for every heading between BEG and END."
3276 (let ((org-ignore-region t))
3277 (save-excursion
3278 (setq end (copy-marker end))
3279 (goto-char beg)
3280 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3281 (< (point) end))
3282 (funcall fun))
3283 (while (and (progn
3284 (outline-next-heading)
3285 (< (point) end))
3286 (not (eobp)))
3287 (funcall fun)))))
3288
3289 (defun org-fixup-indentation (from to prohibit)
3290 "Change the indentation in the current entry by re-replacing FROM with TO.
3291 However, if the regexp PROHIBIT matches at all, don't do anything.
3292 This is being used to change indentation along with the length of the
3293 heading marker. But if there are any lines which are not indented, nothing
3294 is changed at all."
3295 (save-excursion
3296 (let ((end (save-excursion (outline-next-heading)
3297 (point-marker))))
3298 (unless (save-excursion (re-search-forward prohibit end t))
3299 (while (re-search-forward from end t)
3300 (replace-match to)
3301 (beginning-of-line 2)))
3302 (move-marker end nil))))
3303
3304 ;;; Vertical tree motion, cutting and pasting of subtrees
3305
3306 (defun org-move-subtree-up (&optional arg)
3307 "Move the current subtree up past ARG headlines of the same level."
3308 (interactive "p")
3309 (org-move-subtree-down (- (prefix-numeric-value arg))))
3310
3311 (defun org-move-subtree-down (&optional arg)
3312 "Move the current subtree down past ARG headlines of the same level."
3313 (interactive "p")
3314 (setq arg (prefix-numeric-value arg))
3315 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3316 'outline-get-last-sibling))
3317 (ins-point (make-marker))
3318 (cnt (abs arg))
3319 beg end txt folded)
3320 ;; Select the tree
3321 (org-back-to-heading)
3322 (setq beg (point))
3323 (save-match-data
3324 (save-excursion (outline-end-of-heading)
3325 (setq folded (org-invisible-p)))
3326 (outline-end-of-subtree))
3327 (outline-next-heading)
3328 (setq end (point))
3329 ;; Find insertion point, with error handling
3330 (goto-char beg)
3331 (while (> cnt 0)
3332 (or (and (funcall movfunc) (looking-at outline-regexp))
3333 (progn (goto-char beg)
3334 (error "Cannot move past superior level or buffer limit")))
3335 (setq cnt (1- cnt)))
3336 (if (> arg 0)
3337 ;; Moving forward - still need to move over subtree
3338 (progn (outline-end-of-subtree)
3339 (outline-next-heading)
3340 (if (not (or (looking-at (concat "^" outline-regexp))
3341 (bolp)))
3342 (newline))))
3343 (move-marker ins-point (point))
3344 (setq txt (buffer-substring beg end))
3345 (delete-region beg end)
3346 (insert txt)
3347 (goto-char ins-point)
3348 (if folded (hide-subtree))
3349 (move-marker ins-point nil)))
3350
3351 (defvar org-subtree-clip ""
3352 "Clipboard for cut and paste of subtrees.
3353 This is actually only a copy of the kill, because we use the normal kill
3354 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3355
3356 (defvar org-subtree-clip-folded nil
3357 "Was the last copied subtree folded?
3358 This is used to fold the tree back after pasting.")
3359
3360 (defun org-cut-subtree ()
3361 "Cut the current subtree into the clipboard.
3362 This is a short-hand for marking the subtree and then cutting it."
3363 (interactive)
3364 (org-copy-subtree 'cut))
3365
3366 (defun org-copy-subtree (&optional cut)
3367 "Cut the current subtree into the clipboard.
3368 This is a short-hand for marking the subtree and then copying it.
3369 If CUT is non nil, actually cut the subtree."
3370 (interactive)
3371 (let (beg end folded)
3372 (org-back-to-heading)
3373 (setq beg (point))
3374 (save-match-data
3375 (save-excursion (outline-end-of-heading)
3376 (setq folded (org-invisible-p)))
3377 (outline-end-of-subtree))
3378 (if (equal (char-after) ?\n) (forward-char 1))
3379 (setq end (point))
3380 (goto-char beg)
3381 (when (> end beg)
3382 (setq org-subtree-clip-folded folded)
3383 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3384 (setq org-subtree-clip (current-kill 0))
3385 (message "%s: Subtree with %d characters"
3386 (if cut "Cut" "Copied")
3387 (length org-subtree-clip)))))
3388
3389 (defun org-paste-subtree (&optional level tree)
3390 "Paste the clipboard as a subtree, with modification of headline level.
3391 The entire subtree is promoted or demoted in order to match a new headline
3392 level. By default, the new level is derived from the visible headings
3393 before and after the insertion point, and taken to be the inferior headline
3394 level of the two. So if the previous visible heading is level 3 and the
3395 next is level 4 (or vice versa), level 4 will be used for insertion.
3396 This makes sure that the subtree remains an independent subtree and does
3397 not swallow low level entries.
3398
3399 You can also force a different level, either by using a numeric prefix
3400 argument, or by inserting the heading marker by hand. For example, if the
3401 cursor is after \"*****\", then the tree will be shifted to level 5.
3402
3403 If you want to insert the tree as is, just use \\[yank].
3404
3405 If optional TREE is given, use this text instead of the kill ring."
3406 (interactive "P")
3407 (unless (org-kill-is-subtree-p tree)
3408 (error
3409 (substitute-command-keys
3410 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3411 (let* ((txt (or tree (current-kill 0)))
3412 (^re (concat "^\\(" outline-regexp "\\)"))
3413 (re (concat "\\(" outline-regexp "\\)"))
3414 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3415
3416 (old-level (if (string-match ^re txt)
3417 (- (match-end 0) (match-beginning 0))
3418 -1))
3419 (force-level (cond (level (prefix-numeric-value level))
3420 ((string-match
3421 ^re_ (buffer-substring (point-at-bol) (point)))
3422 (- (match-end 0) (match-beginning 0)))
3423 (t nil)))
3424 (previous-level (save-excursion
3425 (condition-case nil
3426 (progn
3427 (outline-previous-visible-heading 1)
3428 (if (looking-at re)
3429 (- (match-end 0) (match-beginning 0))
3430 1))
3431 (error 1))))
3432 (next-level (save-excursion
3433 (condition-case nil
3434 (progn
3435 (outline-next-visible-heading 1)
3436 (if (looking-at re)
3437 (- (match-end 0) (match-beginning 0))
3438 1))
3439 (error 1))))
3440 (new-level (or force-level (max previous-level next-level)))
3441 (shift (if (or (= old-level -1)
3442 (= new-level -1)
3443 (= old-level new-level))
3444 0
3445 (- new-level old-level)))
3446 (shift1 shift)
3447 (delta (if (> shift 0) -1 1))
3448 (func (if (> shift 0) 'org-demote 'org-promote))
3449 (org-odd-levels-only nil)
3450 beg end)
3451 ;; Remove the forces level indicator
3452 (if force-level
3453 (delete-region (point-at-bol) (point)))
3454 ;; Make sure we start at the beginning of an empty line
3455 (if (not (bolp)) (insert "\n"))
3456 (if (not (looking-at "[ \t]*$"))
3457 (progn (insert "\n") (backward-char 1)))
3458 ;; Paste
3459 (setq beg (point))
3460 (insert txt)
3461 (setq end (point))
3462 (goto-char beg)
3463 ;; Shift if necessary
3464 (if (= shift 0)
3465 (message "Pasted at level %d, without shift" new-level)
3466 (save-restriction
3467 (narrow-to-region beg end)
3468 (while (not (= shift 0))
3469 (org-map-region func (point-min) (point-max))
3470 (setq shift (+ delta shift)))
3471 (goto-char (point-min))
3472 (message "Pasted at level %d, with shift by %d levels"
3473 new-level shift1)))
3474 (if (and (eq org-subtree-clip (current-kill 0))
3475 org-subtree-clip-folded)
3476 ;; The tree was folded before it was killed/copied
3477 (hide-subtree))))
3478
3479 (defun org-kill-is-subtree-p (&optional txt)
3480 "Check if the current kill is an outline subtree, or a set of trees.
3481 Returns nil if kill does not start with a headline, or if the first
3482 headline level is not the largest headline level in the tree.
3483 So this will actually accept several entries of equal levels as well,
3484 which is OK for `org-paste-subtree'.
3485 If optional TXT is given, check this string instead of the current kill."
3486 (let* ((kill (or txt (current-kill 0) ""))
3487 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3488 (- (match-end 0) (match-beginning 0))))
3489 (re (concat "^" outline-regexp))
3490 (start 1))
3491 (if (not start-level)
3492 nil ;; does not even start with a heading
3493 (catch 'exit
3494 (while (setq start (string-match re kill (1+ start)))
3495 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3496 (throw 'exit nil)))
3497 t))))
3498
3499 ;;; Plain list items
3500
3501 (defun org-at-item-p ()
3502 "Is point in a line starting a hand-formatted item?"
3503 (let ((llt org-plain-list-ordered-item-terminator))
3504 (save-excursion
3505 (goto-char (point-at-bol))
3506 (looking-at
3507 (cond
3508 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3509 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3510 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3511 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3512
3513 (defun org-get-indentation ()
3514 "Get the indentation of the current line, interpreting tabs."
3515 (save-excursion
3516 (beginning-of-line 1)
3517 (skip-chars-forward " \t")
3518 (current-column)))
3519
3520 (defun org-beginning-of-item ()
3521 "Go to the beginning of the current hand-formatted item.
3522 If the cursor is not in an item, throw an error."
3523 (let ((pos (point))
3524 (limit (save-excursion (org-back-to-heading)
3525 (beginning-of-line 2) (point)))
3526 ind ind1)
3527 (if (org-at-item-p)
3528 (beginning-of-line 1)
3529 (beginning-of-line 1)
3530 (skip-chars-forward " \t")
3531 (setq ind (current-column))
3532 (if (catch 'exit
3533 (while t
3534 (beginning-of-line 0)
3535 (if (< (point) limit) (throw 'exit nil))
3536 (unless (looking-at " \t]*$")
3537 (skip-chars-forward " \t")
3538 (setq ind1 (current-column))
3539 (if (< ind1 ind)
3540 (throw 'exit (org-at-item-p))))))
3541 nil
3542 (goto-char pos)
3543 (error "Not in an item")))))
3544
3545 (defun org-end-of-item ()
3546 "Go to the end of the current hand-formatted item.
3547 If the cursor is not in an item, throw an error."
3548 (let ((pos (point))
3549 (limit (save-excursion (outline-next-heading) (point)))
3550 (ind (save-excursion
3551 (org-beginning-of-item)
3552 (skip-chars-forward " \t")
3553 (current-column)))
3554 ind1)
3555 (if (catch 'exit
3556 (while t
3557 (beginning-of-line 2)
3558 (if (>= (point) limit) (throw 'exit t))
3559 (unless (looking-at "[ \t]*$")
3560 (skip-chars-forward " \t")
3561 (setq ind1 (current-column))
3562 (if (<= ind1 ind) (throw 'exit t)))))
3563 (beginning-of-line 1)
3564 (goto-char pos)
3565 (error "Not in an item"))))
3566
3567 (defun org-move-item-down (arg)
3568 "Move the plain list item at point down, i.e. swap with following item.
3569 Subitems (items with larger indentation) are considered part of the item,
3570 so this really moves item trees."
3571 (interactive "p")
3572 (let (beg end ind ind1 (pos (point)) txt)
3573 (org-beginning-of-item)
3574 (setq beg (point))
3575 (setq ind (org-get-indentation))
3576 (org-end-of-item)
3577 (setq end (point))
3578 (setq ind1 (org-get-indentation))
3579 (if (and (org-at-item-p) (= ind ind1))
3580 (progn
3581 (org-end-of-item)
3582 (setq txt (buffer-substring beg end))
3583 (save-excursion
3584 (delete-region beg end))
3585 (setq pos (point))
3586 (insert txt)
3587 (goto-char pos)
3588 (org-maybe-renumber-ordered-list))
3589 (goto-char pos)
3590 (error "Cannot move this item further down"))))
3591
3592 (defun org-move-item-up (arg)
3593 "Move the plain list item at point up, i.e. swap with previous item.
3594 Subitems (items with larger indentation) are considered part of the item,
3595 so this really moves item trees."
3596 (interactive "p")
3597 (let (beg end ind ind1 (pos (point)) txt)
3598 (org-beginning-of-item)
3599 (setq beg (point))
3600 (setq ind (org-get-indentation))
3601 (org-end-of-item)
3602 (setq end (point))
3603 (goto-char beg)
3604 (catch 'exit
3605 (while t
3606 (beginning-of-line 0)
3607 (if (looking-at "[ \t]*$")
3608 nil
3609 (if (<= (setq ind1 (org-get-indentation)) ind)
3610 (throw 'exit t)))))
3611 (condition-case nil
3612 (org-beginning-of-item)
3613 (error (goto-char beg)
3614 (error "Cannot move this item further up")))
3615 (setq ind1 (org-get-indentation))
3616 (if (and (org-at-item-p) (= ind ind1))
3617 (progn
3618 (setq txt (buffer-substring beg end))
3619 (save-excursion
3620 (delete-region beg end))
3621 (setq pos (point))
3622 (insert txt)
3623 (goto-char pos)
3624 (org-maybe-renumber-ordered-list))
3625 (goto-char pos)
3626 (error "Cannot move this item further up"))))
3627
3628 (defun org-maybe-renumber-ordered-list ()
3629 "Renumber the ordered list at point if setup allows it.
3630 This tests the user option `org-auto-renumber-ordered-lists' before
3631 doing the renumbering."
3632 (and org-auto-renumber-ordered-lists
3633 (org-at-item-p)
3634 (match-beginning 3)
3635 (org-renumber-ordered-list 1)))
3636
3637 (defun org-get-string-indentation (s)
3638 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3639 (let ((n -1) (i 0) (w tab-width) c)
3640 (catch 'exit
3641 (while (< (setq n (1+ n)) (length s))
3642 (setq c (aref s n))
3643 (cond ((= c ?\ ) (setq i (1+ i)))
3644 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3645 (t (throw 'exit t)))))
3646 i))
3647
3648 (defun org-renumber-ordered-list (arg)
3649 "Renumber an ordered plain list.
3650 Cursor next to be in the first line of an item, the line that starts
3651 with something like \"1.\" or \"2)\"."
3652 (interactive "p")
3653 (unless (and (org-at-item-p)
3654 (match-beginning 3))
3655 (error "This is not an ordered list"))
3656 (let ((line (org-current-line))
3657 (col (current-column))
3658 (ind (org-get-string-indentation
3659 (buffer-substring (point-at-bol) (match-beginning 3))))
3660 ;; (term (substring (match-string 3) -1))
3661 ind1 (n (1- arg)))
3662 ;; find where this list begins
3663 (catch 'exit
3664 (while t
3665 (catch 'next
3666 (beginning-of-line 0)
3667 (if (looking-at "[ \t]*$") (throw 'next t))
3668 (skip-chars-forward " \t") (setq ind1 (current-column))
3669 (if (or (< ind1 ind)
3670 (and (= ind1 ind)
3671 (not (org-at-item-p))))
3672 (throw 'exit t)))))
3673 ;; Walk forward and replace these numbers
3674 (catch 'exit
3675 (while t
3676 (catch 'next
3677 (beginning-of-line 2)
3678 (if (eobp) (throw 'exit nil))
3679 (if (looking-at "[ \t]*$") (throw 'next nil))
3680 (skip-chars-forward " \t") (setq ind1 (current-column))
3681 (if (> ind1 ind) (throw 'next t))
3682 (if (< ind1 ind) (throw 'exit t))
3683 (if (not (org-at-item-p)) (throw 'exit nil))
3684 (if (not (match-beginning 3))
3685 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3686 (delete-region (match-beginning 3) (1- (match-end 3)))
3687 (goto-char (match-beginning 3))
3688 (insert (format "%d" (setq n (1+ n)))))))
3689 (goto-line line)
3690 (move-to-column col)))
3691
3692 (defvar org-last-indent-begin-marker (make-marker))
3693 (defvar org-last-indent-end-marker (make-marker))
3694
3695 (defun org-outdent-item (arg)
3696 "Outdent a local list item."
3697 (interactive "p")
3698 (org-indent-item (- arg)))
3699
3700 (defun org-indent-item (arg)
3701 "Indent a local list item."
3702 (interactive "p")
3703 (unless (org-at-item-p)
3704 (error "Not on an item"))
3705 (let (beg end ind ind1)
3706 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3707 (setq beg org-last-indent-begin-marker
3708 end org-last-indent-end-marker)
3709 (org-beginning-of-item)
3710 (setq beg (move-marker org-last-indent-begin-marker (point)))
3711 (org-end-of-item)
3712 (setq end (move-marker org-last-indent-end-marker (point))))
3713 (goto-char beg)
3714 (skip-chars-forward " \t") (setq ind (current-column))
3715 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3716 (while (< (point) end)
3717 (beginning-of-line 1)
3718 (skip-chars-forward " \t") (setq ind1 (current-column))
3719 (delete-region (point-at-bol) (point))
3720 (indent-to-column (+ ind1 arg))
3721 (beginning-of-line 2))
3722 (goto-char beg)))
3723
3724 ;;; Archiving
3725
3726 (defun org-archive-subtree ()
3727 "Move the current subtree to the archive.
3728 The archive can be a certain top-level heading in the current file, or in
3729 a different file. The tree will be moved to that location, the subtree
3730 heading be marked DONE, and the current time will be added."
3731 (interactive)
3732 ;; Save all relevant TODO keyword-relatex variables
3733 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3734 (tr-org-todo-keywords org-todo-keywords)
3735 (tr-org-todo-interpretation org-todo-interpretation)
3736 (tr-org-done-string org-done-string)
3737 (tr-org-todo-regexp org-todo-regexp)
3738 (tr-org-todo-line-regexp org-todo-line-regexp)
3739 (this-buffer (current-buffer))
3740 file heading buffer level newfile-p)
3741 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3742 (progn
3743 (setq file (format (match-string 1 org-archive-location)
3744 (file-name-nondirectory buffer-file-name))
3745 heading (match-string 2 org-archive-location)))
3746 (error "Invalid `org-archive-location'"))
3747 (if (> (length file) 0)
3748 (setq newfile-p (not (file-exists-p file))
3749 buffer (find-file-noselect file))
3750 (setq buffer (current-buffer)))
3751 (unless buffer
3752 (error "Cannot access file \"%s\"" file))
3753 (if (and (> (length heading) 0)
3754 (string-match "^\\*+" heading))
3755 (setq level (match-end 0))
3756 (setq heading nil level 0))
3757 (save-excursion
3758 ;; We first only copy, in case something goes wrong
3759 ;; we need to protect this-command, to avoid kill-region sets it,
3760 ;; which would lead to duplication of subtrees
3761 (let (this-command) (org-copy-subtree))
3762 (set-buffer buffer)
3763 ;; Enforce org-mode for the archive buffer
3764 (if (not (eq major-mode 'org-mode))
3765 ;; Force the mode for future visits.
3766 (let ((org-insert-mode-line-in-empty-file t))
3767 (call-interactively 'org-mode)))
3768 (when newfile-p
3769 (goto-char (point-max))
3770 (insert (format "\nArchived entries from file %s\n\n"
3771 (buffer-file-name this-buffer))))
3772 ;; Force the TODO keywords of the original buffer
3773 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3774 (org-todo-keywords tr-org-todo-keywords)
3775 (org-todo-interpretation tr-org-todo-interpretation)
3776 (org-done-string tr-org-done-string)
3777 (org-todo-regexp tr-org-todo-regexp)
3778 (org-todo-line-regexp tr-org-todo-line-regexp))
3779 (goto-char (point-min))
3780 (if heading
3781 (progn
3782 (if (re-search-forward
3783 (concat "\\(^\\|\r\\)"
3784 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3785 nil t)
3786 (goto-char (match-end 0))
3787 ;; Heading not found, just insert it at the end
3788 (goto-char (point-max))
3789 (or (bolp) (insert "\n"))
3790 (insert "\n" heading "\n")
3791 (end-of-line 0))
3792 ;; Make the heading visible, and the following as well
3793 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3794 (if (re-search-forward
3795 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3796 nil t)
3797 (progn (goto-char (match-beginning 0)) (insert "\n")
3798 (beginning-of-line 0))
3799 (goto-char (point-max)) (insert "\n")))
3800 (goto-char (point-max)) (insert "\n"))
3801 ;; Paste
3802 (org-paste-subtree (1+ level))
3803 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3804 (if org-archive-mark-done
3805 (org-todo (length org-todo-keywords)))
3806 ;; Move cursor to right after the TODO keyword
3807 (when org-archive-stamp-time
3808 (beginning-of-line 1)
3809 (looking-at org-todo-line-regexp)
3810 (goto-char (or (match-end 2) (match-beginning 3)))
3811 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3812 (org-current-time))
3813 ")"))
3814 ;; Save the buffer, if it is not the same buffer.
3815 (if (not (eq this-buffer buffer)) (save-buffer))))
3816 ;; Here we are back in the original buffer. Everything seems to have
3817 ;; worked. So now cut the tree and finish up.
3818 (let (this-command) (org-cut-subtree))
3819 (if (looking-at "[ \t]*$") (kill-line))
3820 (message "Subtree archived %s"
3821 (if (eq this-buffer buffer)
3822 (concat "under heading: " heading)
3823 (concat "in file: " (abbreviate-file-name file))))))
3824
3825 ;;; Completion
3826
3827 (defun org-complete (&optional arg)
3828 "Perform completion on word at point.
3829 At the beginning of a headline, this completes TODO keywords as given in
3830 `org-todo-keywords'.
3831 If the current word is preceded by a backslash, completes the TeX symbols
3832 that are supported for HTML support.
3833 If the current word is preceded by \"#+\", completes special words for
3834 setting file options.
3835 At all other locations, this simply calls `ispell-complete-word'."
3836 (interactive "P")
3837 (catch 'exit
3838 (let* ((end (point))
3839 (beg1 (save-excursion
3840 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3841 (skip-chars-backward "a-zA-Z_@0-9")
3842 (point)))
3843 (beg (save-excursion
3844 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3845 (skip-chars-backward "a-zA-Z0-9_:$")
3846 (point)))
3847 (camel (equal (char-before beg) ?*))
3848 (tag (equal (char-before beg1) ?:))
3849 (texp (equal (char-before beg) ?\\))
3850 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3851 beg)
3852 "#+"))
3853 (completion-ignore-case opt)
3854 (type nil)
3855 (tbl nil)
3856 (table (cond
3857 (opt
3858 (setq type :opt)
3859 (mapcar (lambda (x)
3860 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3861 (cons (match-string 2 x) (match-string 1 x)))
3862 (org-split-string (org-get-current-options) "\n")))
3863 (texp
3864 (setq type :tex)
3865 org-html-entities)
3866 ((string-match "\\`\\*+[ \t]*\\'"
3867 (buffer-substring (point-at-bol) beg))
3868 (setq type :todo)
3869 (mapcar 'list org-todo-keywords))
3870 (camel
3871 (setq type :camel)
3872 (save-excursion
3873 (goto-char (point-min))
3874 (while (re-search-forward org-todo-line-regexp nil t)
3875 (push (list
3876 (if org-file-link-context-use-camel-case
3877 (org-make-org-heading-camel (match-string 3) t)
3878 (org-make-org-heading-search-string
3879 (match-string 3) t)))
3880 tbl)))
3881 tbl)
3882 (tag (setq type :tag beg beg1)
3883 (org-get-buffer-tags))
3884 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3885 (pattern (buffer-substring-no-properties beg end))
3886 (completion (try-completion pattern table)))
3887 (cond ((eq completion t)
3888 (if (equal type :opt)
3889 (insert (substring (cdr (assoc (upcase pattern) table))
3890 (length pattern)))))
3891 ((null completion)
3892 (message "Can't find completion for \"%s\"" pattern)
3893 (ding))
3894 ((not (string= pattern completion))
3895 (delete-region beg end)
3896 (if (string-match " +$" completion)
3897 (setq completion (replace-match "" t t completion)))
3898 (insert completion)
3899 (if (get-buffer-window "*Completions*")
3900 (delete-window (get-buffer-window "*Completions*")))
3901 (if (assoc completion table)
3902 (if (eq type :todo) (insert " ")
3903 (if (eq type :tag) (insert ":"))))
3904 (if (and (equal type :opt) (assoc completion table))
3905 (message "%s" (substitute-command-keys
3906 "Press \\[org-complete] again to insert example settings"))))
3907 (t
3908 (message "Making completion list...")
3909 (let ((list (sort (all-completions pattern table) 'string<)))
3910 (with-output-to-temp-buffer "*Completions*"
3911 (condition-case nil
3912 ;; Protection needed for XEmacs and emacs 21
3913 (display-completion-list list pattern)
3914 (error (display-completion-list list)))))
3915 (message "Making completion list...%s" "done"))))))
3916
3917 ;;; Comments, TODO and DEADLINE
3918
3919 (defun org-toggle-comment ()
3920 "Change the COMMENT state of an entry."
3921 (interactive)
3922 (save-excursion
3923 (org-back-to-heading)
3924 (if (looking-at (concat outline-regexp
3925 "\\( +\\<" org-comment-string "\\>\\)"))
3926 (replace-match "" t t nil 1)
3927 (if (looking-at outline-regexp)
3928 (progn
3929 (goto-char (match-end 0))
3930 (insert " " org-comment-string))))))
3931
3932 (defvar org-last-todo-state-is-todo nil
3933 "This is non-nil when the last TODO state change led to a TODO state.
3934 If the last change removed the TODO tag or switched to DONE, then
3935 this is nil.")
3936
3937 (defun org-todo (&optional arg)
3938 "Change the TODO state of an item.
3939 The state of an item is given by a keyword at the start of the heading,
3940 like
3941 *** TODO Write paper
3942 *** DONE Call mom
3943
3944 The different keywords are specified in the variable `org-todo-keywords'.
3945 By default the available states are \"TODO\" and \"DONE\".
3946 So for this example: when the item starts with TODO, it is changed to DONE.
3947 When it starts with DONE, the DONE is removed. And when neither TODO nor
3948 DONE are present, add TODO at the beginning of the heading.
3949
3950 With prefix arg, use completion to determine the new state. With numeric
3951 prefix arg, switch to that state."
3952 (interactive "P")
3953 (save-excursion
3954 (org-back-to-heading)
3955 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3956 (or (looking-at (concat " +" org-todo-regexp " *"))
3957 (looking-at " *"))
3958 (let* ((this (match-string 1))
3959 (completion-ignore-case t)
3960 (member (member this org-todo-keywords))
3961 (tail (cdr member))
3962 (state (cond
3963 ((equal arg '(4))
3964 ;; Read a state with completion
3965 (completing-read "State: " (mapcar (lambda(x) (list x))
3966 org-todo-keywords)
3967 nil t))
3968 ((eq arg 'right)
3969 (if this
3970 (if tail (car tail) nil)
3971 (car org-todo-keywords)))
3972 ((eq arg 'left)
3973 (if (equal member org-todo-keywords)
3974 nil
3975 (if this
3976 (nth (- (length org-todo-keywords) (length tail) 2)
3977 org-todo-keywords)
3978 org-done-string)))
3979 (arg
3980 ;; user requests a specific state
3981 (nth (1- (prefix-numeric-value arg))
3982 org-todo-keywords))
3983 ((null member) (car org-todo-keywords))
3984 ((null tail) nil) ;; -> first entry
3985 ((eq org-todo-interpretation 'sequence)
3986 (car tail))
3987 ((memq org-todo-interpretation '(type priority))
3988 (if (eq this-command last-command)
3989 (car tail)
3990 (if (> (length tail) 0) org-done-string nil)))
3991 (t nil)))
3992 (next (if state (concat " " state " ") " ")))
3993 (replace-match next t t)
3994 (setq org-last-todo-state-is-todo
3995 (not (equal state org-done-string)))
3996 (when org-log-done
3997 (if (equal state org-done-string)
3998 (org-log-done)
3999 (if (not this)
4000 (org-log-done t))))
4001 ;; Fixup tag positioning
4002 (and org-auto-align-tags (org-set-tags nil t))
4003 (run-hooks 'org-after-todo-state-change-hook)))
4004 ;; Fixup cursor location if close to the keyword
4005 (if (and (outline-on-heading-p)
4006 (not (bolp))
4007 (save-excursion (beginning-of-line 1)
4008 (looking-at org-todo-line-regexp))
4009 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
4010 (progn
4011 (goto-char (or (match-end 2) (match-end 1)))
4012 (just-one-space))))
4013
4014 (defun org-log-done (&optional undone)
4015 "Add a time stamp logging that a TODO entry has been closed.
4016 When UNDONE is non-nil, remove such a time stamp again."
4017 (interactive)
4018 (let (beg end col)
4019 (save-excursion
4020 (org-back-to-heading t)
4021 (setq beg (point))
4022 (looking-at (concat outline-regexp " *"))
4023 (goto-char (match-end 0))
4024 (setq col (current-column))
4025 (outline-next-heading)
4026 (setq end (point))
4027 (goto-char beg)
4028 (when (re-search-forward (concat
4029 "[\r\n]\\([ \t]*"
4030 (regexp-quote org-closed-string)
4031 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
4032 (delete-region (match-beginning 1) (match-end 1)))
4033 (unless undone
4034 (org-back-to-heading t)
4035 (skip-chars-forward "^\n\r")
4036 (goto-char (min (1+ (point)) (point-max)))
4037 (when (not (member (char-before) '(?\r ?\n)))
4038 (insert "\n"))
4039 (indent-to col)
4040 (insert org-closed-string " "
4041 (format-time-string
4042 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4043 (org-current-time))
4044 "\n")))))
4045
4046 (defun org-show-todo-tree (arg)
4047 "Make a compact tree which shows all headlines marked with TODO.
4048 The tree will show the lines where the regexp matches, and all higher
4049 headlines above the match.
4050 With \\[universal-argument] prefix, also show the DONE entries.
4051 With a numeric prefix N, construct a sparse tree for the Nth element
4052 of `org-todo-keywords'."
4053 (interactive "P")
4054 (let ((case-fold-search nil)
4055 (kwd-re
4056 (cond ((null arg) org-not-done-regexp)
4057 ((equal arg '(4)) org-todo-regexp)
4058 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
4059 (regexp-quote (nth (1- (prefix-numeric-value arg))
4060 org-todo-keywords)))
4061 (t (error "Invalid prefix argument: %s" arg)))))
4062 (message "%d TODO entries found"
4063 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
4064
4065 (defun org-deadline ()
4066 "Insert the DEADLINE: string to make a deadline.
4067 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4068 to modify it to the correct date."
4069 (interactive)
4070 (insert
4071 org-deadline-string " "
4072 (format-time-string (car org-time-stamp-formats)
4073 (org-read-date nil 'to-time)))
4074 (message "%s" (substitute-command-keys
4075 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
4076
4077 (defun org-schedule ()
4078 "Insert the SCHEDULED: string to schedule a TODO item.
4079 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4080 to modify it to the correct date."
4081 (interactive)
4082 (insert
4083 org-scheduled-string " "
4084 (format-time-string (car org-time-stamp-formats)
4085 (org-read-date nil 'to-time)))
4086 (message "%s" (substitute-command-keys
4087 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
4088
4089
4090 (defun org-occur (regexp &optional callback)
4091 "Make a compact tree which shows all matches of REGEXP.
4092 The tree will show the lines where the regexp matches, and all higher
4093 headlines above the match. It will also show the heading after the match,
4094 to make sure editing the matching entry is easy.
4095 If CALLBACK is non-nil, it is a function which is called to confirm
4096 that the match should indeed be shown."
4097 (interactive "sRegexp: ")
4098 (org-remove-occur-highlights nil nil t)
4099 (setq regexp (org-check-occur-regexp regexp))
4100 (let ((cnt 0))
4101 (save-excursion
4102 (goto-char (point-min))
4103 (hide-sublevels 1)
4104 (while (re-search-forward regexp nil t)
4105 (when (or (not callback)
4106 (save-match-data (funcall callback)))
4107 (setq cnt (1+ cnt))
4108 (org-highlight-new-match (match-beginning 0) (match-end 0))
4109 (org-show-hierarchy-above))))
4110 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
4111 nil 'local)
4112 (run-hooks 'org-occur-hook)
4113 (if (interactive-p)
4114 (message "%d match(es) for regexp %s" cnt regexp))
4115 cnt))
4116
4117 (defun org-show-hierarchy-above ()
4118 "Make sure point and the headings hierarchy above is visible."
4119 (catch 'exit
4120 (if (org-on-heading-p t)
4121 (org-flag-heading nil) ; only show the heading
4122 (and (or (org-invisible-p) (org-invisible-p2))
4123 (org-show-hidden-entry))) ; show entire entry
4124 (save-excursion
4125 (and org-show-following-heading
4126 (outline-next-heading)
4127 (org-flag-heading nil))) ; show the next heading
4128 (when org-show-hierarchy-above
4129 (save-excursion ; show all higher headings
4130 (while (and (condition-case nil
4131 (progn (org-up-heading-all 1) t)
4132 (error nil))
4133 (not (bobp)))
4134 (org-flag-heading nil))))))
4135
4136 ;; Overlay compatibility functions
4137 (defun org-make-overlay (beg end &optional buffer)
4138 (if (featurep 'xemacs)
4139 (make-extent beg end buffer)
4140 (make-overlay beg end buffer)))
4141 (defun org-delete-overlay (ovl)
4142 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4143 (defun org-detatch-overlay (ovl)
4144 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4145 (defun org-move-overlay (ovl beg end &optional buffer)
4146 (if (featurep 'xemacs)
4147 (set-extent-endpoints ovl beg end buffer)
4148 (move-overlay ovl beg end buffer)))
4149 (defun org-overlay-put (ovl prop value)
4150 (if (featurep 'xemacs)
4151 (set-extent-property ovl prop value)
4152 (overlay-put ovl prop value)))
4153
4154 (defvar org-occur-highlights nil)
4155 (defun org-highlight-new-match (beg end)
4156 "Highlight from BEG to END and mark the highlight is an occur headline."
4157 (let ((ov (org-make-overlay beg end)))
4158 (org-overlay-put ov 'face 'secondary-selection)
4159 (push ov org-occur-highlights)))
4160
4161 (defun org-remove-occur-highlights (&optional beg end noremove)
4162 "Remove the occur highlights from the buffer.
4163 BEG and END are ignored. If NOREMOVE is nil, remove this function
4164 from the `before-change-functions' in the current buffer."
4165 (interactive)
4166 (mapc 'org-delete-overlay org-occur-highlights)
4167 (setq org-occur-highlights nil)
4168 (unless noremove
4169 (remove-hook 'before-change-functions
4170 'org-remove-occur-highlights 'local)))
4171
4172 ;;; Priorities
4173
4174 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
4175 "Regular expression matching the priority indicator.")
4176
4177 (defvar org-remove-priority-next-time nil)
4178
4179 (defun org-priority-up ()
4180 "Increase the priority of the current item."
4181 (interactive)
4182 (org-priority 'up))
4183
4184 (defun org-priority-down ()
4185 "Decrease the priority of the current item."
4186 (interactive)
4187 (org-priority 'down))
4188
4189 (defun org-priority (&optional action)
4190 "Change the priority of an item by ARG.
4191 ACTION can be set, up, or down."
4192 (interactive)
4193 (setq action (or action 'set))
4194 (let (current new news have remove)
4195 (save-excursion
4196 (org-back-to-heading)
4197 (if (looking-at org-priority-regexp)
4198 (setq current (string-to-char (match-string 2))
4199 have t)
4200 (setq current org-default-priority))
4201 (cond
4202 ((eq action 'set)
4203 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
4204 (setq new (read-char-exclusive))
4205 (cond ((equal new ?\ ) (setq remove t))
4206 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
4207 (error "Priority must be between `%c' and `%c'"
4208 ?A org-lowest-priority))))
4209 ((eq action 'up)
4210 (setq new (1- current)))
4211 ((eq action 'down)
4212 (setq new (1+ current)))
4213 (t (error "Invalid action")))
4214 (setq new (min (max ?A (upcase new)) org-lowest-priority))
4215 (setq news (format "%c" new))
4216 (if have
4217 (if remove
4218 (replace-match "" t t nil 1)
4219 (replace-match news t t nil 2))
4220 (if remove
4221 (error "No priority cookie found in line")
4222 (looking-at org-todo-line-regexp)
4223 (if (match-end 2)
4224 (progn
4225 (goto-char (match-end 2))
4226 (insert " [#" news "]"))
4227 (goto-char (match-beginning 3))
4228 (insert "[#" news "] ")))))
4229 (if remove
4230 (message "Priority removed")
4231 (message "Priority of current item set to %s" news))))
4232
4233
4234 (defun org-get-priority (s)
4235 "Find priority cookie and return priority."
4236 (save-match-data
4237 (if (not (string-match org-priority-regexp s))
4238 (* 1000 (- org-lowest-priority org-default-priority))
4239 (* 1000 (- org-lowest-priority
4240 (string-to-char (match-string 2 s)))))))
4241
4242 ;;; Timestamps
4243
4244 (defvar org-last-changed-timestamp nil)
4245
4246 (defun org-time-stamp (arg)
4247 "Prompt for a date/time and insert a time stamp.
4248 If the user specifies a time like HH:MM, or if this command is called
4249 with a prefix argument, the time stamp will contain date and time.
4250 Otherwise, only the date will be included. All parts of a date not
4251 specified by the user will be filled in from the current date/time.
4252 So if you press just return without typing anything, the time stamp
4253 will represent the current date/time. If there is already a timestamp
4254 at the cursor, it will be modified."
4255 (interactive "P")
4256 (let ((fmt (if arg (cdr org-time-stamp-formats)
4257 (car org-time-stamp-formats)))
4258 (org-time-was-given nil)
4259 time)
4260 (cond
4261 ((and (org-at-timestamp-p)
4262 (eq last-command 'org-time-stamp)
4263 (eq this-command 'org-time-stamp))
4264 (insert "--")
4265 (setq time (let ((this-command this-command))
4266 (org-read-date arg 'totime)))
4267 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4268 (insert (format-time-string fmt time)))
4269 ((org-at-timestamp-p)
4270 (setq time (let ((this-command this-command))
4271 (org-read-date arg 'totime)))
4272 (and (org-at-timestamp-p) (replace-match
4273 (setq org-last-changed-timestamp
4274 (format-time-string fmt time))
4275 t t))
4276 (message "Timestamp updated"))
4277 (t
4278 (setq time (let ((this-command this-command))
4279 (org-read-date arg 'totime)))
4280 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4281 (insert (format-time-string fmt time))))))
4282
4283 (defun org-time-stamp-inactive (&optional arg)
4284 "Insert an inactive time stamp.
4285 An inactive time stamp is enclosed in square brackets instead of angle
4286 brackets. It is inactive in the sense that it does not trigger agenda entries,
4287 does not link to the calendar and cannot be changed with the S-cursor keys.
4288 So these are more for recording a certain time/date."
4289 (interactive "P")
4290 (let ((fmt (if arg (cdr org-time-stamp-formats)
4291 (car org-time-stamp-formats)))
4292 (org-time-was-given nil)
4293 time)
4294 (setq time (org-read-date arg 'totime))
4295 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4296 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
4297 (insert (format-time-string fmt time))))
4298
4299 (defvar org-date-ovl (org-make-overlay 1 1))
4300 (org-overlay-put org-date-ovl 'face 'org-warning)
4301 (org-detatch-overlay org-date-ovl)
4302
4303 (defun org-read-date (&optional with-time to-time)
4304 "Read a date and make things smooth for the user.
4305 The prompt will suggest to enter an ISO date, but you can also enter anything
4306 which will at least partially be understood by `parse-time-string'.
4307 Unrecognized parts of the date will default to the current day, month, year,
4308 hour and minute. For example,
4309 3-2-5 --> 2003-02-05
4310 feb 15 --> currentyear-02-15
4311 sep 12 9 --> 2009-09-12
4312 12:45 --> today 12:45
4313 22 sept 0:34 --> currentyear-09-22 0:34
4314 12 --> currentyear-currentmonth-12
4315 Fri --> nearest Friday (today or later)
4316 etc.
4317 The function understands only English month and weekday abbreviations,
4318 but this can be configured with the variables `parse-time-months' and
4319 `parse-time-weekdays'.
4320
4321 While prompting, a calendar is popped up - you can also select the
4322 date with the mouse (button 1). The calendar shows a period of three
4323 months. To scroll it to other months, use the keys `>' and `<'.
4324 If you don't like the calendar, turn it off with
4325 \(setq org-popup-calendar-for-date-prompt nil)
4326
4327 With optional argument TO-TIME, the date will immediately be converted
4328 to an internal time.
4329 With an optional argument WITH-TIME, the prompt will suggest to also
4330 insert a time. Note that when WITH-TIME is not set, you can still
4331 enter a time, and this function will inform the calling routine about
4332 this change. The calling routine may then choose to change the format
4333 used to insert the time stamp into the buffer to include the time."
4334 (require 'parse-time)
4335 (let* ((org-time-stamp-rounding-minutes
4336 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
4337 (ct (org-current-time))
4338 (default-time
4339 ;; Default time is either today, or, when entering a range,
4340 ;; the range start.
4341 (if (save-excursion
4342 (re-search-backward
4343 (concat org-ts-regexp "--\\=") ; FIXME: exactly two minuses?
4344 (- (point) 20) t))
4345 (apply
4346 'encode-time
4347 (mapcar (lambda(x) (or x 0))
4348 (parse-time-string (match-string 1))))
4349 ct))
4350 (calendar-move-hook nil)
4351 (view-diary-entries-initially nil)
4352 (timestr (format-time-string
4353 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
4354 (prompt (format "YYYY-MM-DD [%s]: " timestr))
4355 ans ans1 ans2
4356 second minute hour day month year tl wday wday1)
4357
4358 (if org-popup-calendar-for-date-prompt
4359 (save-excursion
4360 (save-window-excursion
4361 (calendar)
4362 (calendar-forward-day (- (time-to-days default-time)
4363 (calendar-absolute-from-gregorian
4364 (calendar-current-date))))
4365 (org-eval-in-calendar nil)
4366 (let* ((old-map (current-local-map))
4367 (map (copy-keymap calendar-mode-map))
4368 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4369 (define-key map (kbd "RET") 'org-calendar-select)
4370 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
4371 'org-calendar-select-mouse)
4372 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
4373 'org-calendar-select-mouse)
4374 (define-key minibuffer-local-map [(meta shift left)]
4375 (lambda () (interactive)
4376 (org-eval-in-calendar '(calendar-backward-month 1))))
4377 (define-key minibuffer-local-map [(meta shift right)]
4378 (lambda () (interactive)
4379 (org-eval-in-calendar '(calendar-forward-month 1))))
4380 (define-key minibuffer-local-map [(shift up)]
4381 (lambda () (interactive)
4382 (org-eval-in-calendar '(calendar-backward-week 1))))
4383 (define-key minibuffer-local-map [(shift down)]
4384 (lambda () (interactive)
4385 (org-eval-in-calendar '(calendar-forward-week 1))))
4386 (define-key minibuffer-local-map [(shift left)]
4387 (lambda () (interactive)
4388 (org-eval-in-calendar '(calendar-backward-day 1))))
4389 (define-key minibuffer-local-map [(shift right)]
4390 (lambda () (interactive)
4391 (org-eval-in-calendar '(calendar-forward-day 1))))
4392 (define-key minibuffer-local-map ">"
4393 (lambda () (interactive)
4394 (org-eval-in-calendar '(scroll-calendar-left 1))))
4395 (define-key minibuffer-local-map "<"
4396 (lambda () (interactive)
4397 (org-eval-in-calendar '(scroll-calendar-right 1))))
4398 (unwind-protect
4399 (progn
4400 (use-local-map map)
4401 (setq ans (read-string prompt "" nil nil))
4402 (if (not (string-match "\\S-" ans)) (setq ans nil))
4403 (setq ans (or ans1 ans ans2)))
4404 (use-local-map old-map)))))
4405 ;; Naked prompt only
4406 (setq ans (read-string prompt "" nil timestr)))
4407 (org-detatch-overlay org-date-ovl)
4408
4409 (if (string-match
4410 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4411 (progn
4412 (setq year (if (match-end 2)
4413 (string-to-number (match-string 2 ans))
4414 (string-to-number (format-time-string "%Y")))
4415 month (string-to-number (match-string 3 ans))
4416 day (string-to-number (match-string 4 ans)))
4417 (if (< year 100) (setq year (+ 2000 year)))
4418 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4419 t nil ans))))
4420 (setq tl (parse-time-string ans)
4421 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
4422 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
4423 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
4424 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
4425 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
4426 second (or (nth 0 tl) 0)
4427 wday (nth 6 tl))
4428 (when (and wday (not (nth 3 tl)))
4429 ;; Weekday was given, but no day, so pick that day in the week
4430 ;; on or after the derived date.
4431 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
4432 (unless (equal wday wday1)
4433 (setq day (+ day (% (- wday wday1 -7) 7)))))
4434 (if (and (boundp 'org-time-was-given)
4435 (nth 2 tl))
4436 (setq org-time-was-given t))
4437 (if (< year 100) (setq year (+ 2000 year)))
4438 (if to-time
4439 (encode-time second minute hour day month year)
4440 (if (or (nth 1 tl) (nth 2 tl))
4441 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4442 (format "%04d-%02d-%02d" year month day)))))
4443
4444 (defun org-eval-in-calendar (form)
4445 "Eval FORM in the calendar window and return to current window.
4446 Also, store the cursor date in variable ans2."
4447 (let ((sw (selected-window)))
4448 (select-window (get-buffer-window "*Calendar*"))
4449 (eval form)
4450 (when (calendar-cursor-to-date)
4451 (let* ((date (calendar-cursor-to-date))
4452 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4453 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4454 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4455 (select-window sw)))
4456
4457 (defun org-calendar-select ()
4458 "Return to `org-read-date' with the date currently selected.
4459 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4460 (interactive)
4461 (when (calendar-cursor-to-date)
4462 (let* ((date (calendar-cursor-to-date))
4463 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4464 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4465 (if (active-minibuffer-window) (exit-minibuffer))))
4466
4467 (defun org-calendar-select-mouse (ev)
4468 "Return to `org-read-date' with the date currently selected.
4469 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4470 (interactive "e")
4471 (mouse-set-point ev)
4472 (when (calendar-cursor-to-date)
4473 (let* ((date (calendar-cursor-to-date))
4474 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4475 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4476 (if (active-minibuffer-window) (exit-minibuffer))))
4477
4478 (defun org-check-deadlines (ndays)
4479 "Check if there are any deadlines due or past due.
4480 A deadline is considered due if it happens within `org-deadline-warning-days'
4481 days from today's date. If the deadline appears in an entry marked DONE,
4482 it is not shown. The prefix arg NDAYS can be used to test that many
4483 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4484 (interactive "P")
4485 (let* ((org-warn-days
4486 (cond
4487 ((equal ndays '(4)) 100000)
4488 (ndays (prefix-numeric-value ndays))
4489 (t org-deadline-warning-days)))
4490 (case-fold-search nil)
4491 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4492 (callback
4493 (lambda ()
4494 (and (let ((d1 (time-to-days (current-time)))
4495 (d2 (time-to-days
4496 (org-time-string-to-time (match-string 1)))))
4497 (< (- d2 d1) org-warn-days))
4498 (not (org-entry-is-done-p))))))
4499 (message "%d deadlines past-due or due within %d days"
4500 (org-occur regexp callback)
4501 org-warn-days)))
4502
4503 (defun org-evaluate-time-range (&optional to-buffer)
4504 "Evaluate a time range by computing the difference between start and end.
4505 Normally the result is just printed in the echo area, but with prefix arg
4506 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4507 If the time range is actually in a table, the result is inserted into the
4508 next column.
4509 For time difference computation, a year is assumed to be exactly 365
4510 days in order to avoid rounding problems."
4511 (interactive "P")
4512 (save-excursion
4513 (unless (org-at-date-range-p)
4514 (goto-char (point-at-bol))
4515 (re-search-forward org-tr-regexp (point-at-eol) t))
4516 (if (not (org-at-date-range-p))
4517 (error "Not at a time-stamp range, and none found in current line")))
4518 (let* ((ts1 (match-string 1))
4519 (ts2 (match-string 2))
4520 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4521 (match-end (match-end 0))
4522 (time1 (org-time-string-to-time ts1))
4523 (time2 (org-time-string-to-time ts2))
4524 (t1 (time-to-seconds time1))
4525 (t2 (time-to-seconds time2))
4526 (diff (abs (- t2 t1)))
4527 (negative (< (- t2 t1) 0))
4528 ;; (ys (floor (* 365 24 60 60)))
4529 (ds (* 24 60 60))
4530 (hs (* 60 60))
4531 (fy "%dy %dd %02d:%02d")
4532 (fy1 "%dy %dd")
4533 (fd "%dd %02d:%02d")
4534 (fd1 "%dd")
4535 (fh "%02d:%02d")
4536 y d h m align)
4537 (if havetime
4538 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4539 y 0
4540 d (floor (/ diff ds)) diff (mod diff ds)
4541 h (floor (/ diff hs)) diff (mod diff hs)
4542 m (floor (/ diff 60)))
4543 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4544 y 0
4545 d (floor (+ (/ diff ds) 0.5))
4546 h 0 m 0))
4547 (if (not to-buffer)
4548 (message (org-make-tdiff-string y d h m))
4549 (when (org-at-table-p)
4550 (goto-char match-end)
4551 (setq align t)
4552 (and (looking-at " *|") (goto-char (match-end 0))))
4553 (if (looking-at
4554 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4555 (replace-match ""))
4556 (if negative (insert " -"))
4557 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4558 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4559 (insert " " (format fh h m))))
4560 (if align (org-table-align))
4561 (message "Time difference inserted"))))
4562
4563 (defun org-make-tdiff-string (y d h m)
4564 (let ((fmt "")
4565 (l nil))
4566 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4567 l (push y l)))
4568 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4569 l (push d l)))
4570 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4571 l (push h l)))
4572 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4573 l (push m l)))
4574 (apply 'format fmt (nreverse l))))
4575
4576 (defun org-time-string-to-time (s)
4577 (apply 'encode-time (org-parse-time-string s)))
4578
4579 (defun org-parse-time-string (s &optional nodefault)
4580 "Parse the standard Org-mode time string.
4581 This should be a lot faster than the normal `parse-time-string'.
4582 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4583 hour and minute fields will be nil if not given."
4584 (if (string-match org-ts-regexp1 s)
4585 (list 0
4586 (if (or (match-beginning 8) (not nodefault))
4587 (string-to-number (or (match-string 8 s) "0")))
4588 (if (or (match-beginning 7) (not nodefault))
4589 (string-to-number (or (match-string 7 s) "0")))
4590 (string-to-number (match-string 4 s))
4591 (string-to-number (match-string 3 s))
4592 (string-to-number (match-string 2 s))
4593 nil nil nil)
4594 (make-list 9 0)))
4595
4596 (defun org-timestamp-up (&optional arg)
4597 "Increase the date item at the cursor by one.
4598 If the cursor is on the year, change the year. If it is on the month or
4599 the day, change that.
4600 With prefix ARG, change by that many units."
4601 (interactive "p")
4602 (org-timestamp-change (prefix-numeric-value arg)))
4603
4604 (defun org-timestamp-down (&optional arg)
4605 "Decrease the date item at the cursor by one.
4606 If the cursor is on the year, change the year. If it is on the month or
4607 the day, change that.
4608 With prefix ARG, change by that many units."
4609 (interactive "p")
4610 (org-timestamp-change (- (prefix-numeric-value arg))))
4611
4612 (defun org-timestamp-up-day (&optional arg)
4613 "Increase the date in the time stamp by one day.
4614 With prefix ARG, change that many days."
4615 (interactive "p")
4616 (if (and (not (org-at-timestamp-p))
4617 (org-on-heading-p))
4618 (org-todo 'up)
4619 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4620
4621 (defun org-timestamp-down-day (&optional arg)
4622 "Decrease the date in the time stamp by one day.
4623 With prefix ARG, change that many days."
4624 (interactive "p")
4625 (if (and (not (org-at-timestamp-p))
4626 (org-on-heading-p))
4627 (org-todo 'down)
4628 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4629
4630 (defsubst org-pos-in-match-range (pos n)
4631 (and (match-beginning n)
4632 (<= (match-beginning n) pos)
4633 (>= (match-end n) pos)))
4634
4635 (defun org-at-timestamp-p ()
4636 "Determine if the cursor is in or at a timestamp."
4637 (interactive)
4638 (let* ((tsr org-ts-regexp2)
4639 (pos (point))
4640 (ans (or (looking-at tsr)
4641 (save-excursion
4642 (skip-chars-backward "^<\n\r\t")
4643 (if (> (point) 1) (backward-char 1))
4644 (and (looking-at tsr)
4645 (> (- (match-end 0) pos) -1))))))
4646 (and (boundp 'org-ts-what)
4647 (setq org-ts-what
4648 (cond
4649 ((org-pos-in-match-range pos 2) 'year)
4650 ((org-pos-in-match-range pos 3) 'month)
4651 ((org-pos-in-match-range pos 7) 'hour)
4652 ((org-pos-in-match-range pos 8) 'minute)
4653 ((or (org-pos-in-match-range pos 4)
4654 (org-pos-in-match-range pos 5)) 'day)
4655 (t 'day))))
4656 ans))
4657
4658 (defun org-timestamp-change (n &optional what)
4659 "Change the date in the time stamp at point.
4660 The date will be changed by N times WHAT. WHAT can be `day', `month',
4661 `year', `minute', `second'. If WHAT is not given, the cursor position
4662 in the timestamp determines what will be changed."
4663 (let ((fmt (car org-time-stamp-formats))
4664 org-ts-what
4665 (pos (point))
4666 ts time time0)
4667 (if (not (org-at-timestamp-p))
4668 (error "Not at a timestamp"))
4669 (setq org-ts-what (or what org-ts-what))
4670 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4671 (- (match-end 0) (match-beginning 0))))
4672 1)
4673 (cdr org-time-stamp-formats)
4674 (car org-time-stamp-formats)))
4675 (setq ts (match-string 0))
4676 (replace-match "")
4677 (setq time0 (org-parse-time-string ts))
4678 (setq time
4679 (apply 'encode-time
4680 (append
4681 (list (or (car time0) 0))
4682 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4683 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4684 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4685 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4686 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4687 (nthcdr 6 time0))))
4688 (if (eq what 'calendar)
4689 (let ((cal-date
4690 (save-excursion
4691 (save-match-data
4692 (set-buffer "*Calendar*")
4693 (calendar-cursor-to-date)))))
4694 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4695 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4696 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4697 (setcar time0 (or (car time0) 0))
4698 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4699 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4700 (setq time (apply 'encode-time time0))))
4701 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4702 (goto-char pos)
4703 ;; Try to recenter the calendar window, if any
4704 (if (and org-calendar-follow-timestamp-change
4705 (get-buffer-window "*Calendar*" t)
4706 (memq org-ts-what '(day month year)))
4707 (org-recenter-calendar (time-to-days time)))))
4708
4709 (defun org-recenter-calendar (date)
4710 "If the calendar is visible, recenter it to DATE."
4711 (let* ((win (selected-window))
4712 (cwin (get-buffer-window "*Calendar*" t))
4713 (calendar-move-hook nil))
4714 (when cwin
4715 (select-window cwin)
4716 (calendar-goto-date (if (listp date) date
4717 (calendar-gregorian-from-absolute date)))
4718 (select-window win))))
4719
4720 (defun org-goto-calendar (&optional arg)
4721 "Go to the Emacs calendar at the current date.
4722 If there is a time stamp in the current line, go to that date.
4723 A prefix ARG can be used to force the current date."
4724 (interactive "P")
4725 (let ((tsr org-ts-regexp) diff
4726 (calendar-move-hook nil)
4727 (view-diary-entries-initially nil))
4728 (if (or (org-at-timestamp-p)
4729 (save-excursion
4730 (beginning-of-line 1)
4731 (looking-at (concat ".*" tsr))))
4732 (let ((d1 (time-to-days (current-time)))
4733 (d2 (time-to-days
4734 (org-time-string-to-time (match-string 1)))))
4735 (setq diff (- d2 d1))))
4736 (calendar)
4737 (calendar-goto-today)
4738 (if (and diff (not arg)) (calendar-forward-day diff))))
4739
4740 (defun org-date-from-calendar ()
4741 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4742 If there is already a time stamp at the cursor position, update it."
4743 (interactive)
4744 (org-timestamp-change 0 'calendar))
4745
4746 ;;; Agenda, and Diary Integration
4747
4748 ;;; Define the mode
4749
4750 (defvar org-agenda-mode-map (make-sparse-keymap)
4751 "Keymap for `org-agenda-mode'.")
4752
4753 (defvar org-agenda-menu) ; defined later in this file.
4754 (defvar org-agenda-follow-mode nil)
4755 (defvar org-agenda-show-log nil)
4756 (defvar org-agenda-buffer-name "*Org Agenda*")
4757 (defvar org-agenda-redo-command nil)
4758 (defvar org-agenda-mode-hook nil)
4759 (defvar org-agenda-type nil)
4760 (defvar org-agenda-force-single-file nil)
4761
4762 ;;;###autoload
4763 (defun org-agenda-mode ()
4764 "Mode for time-sorted view on action items in Org-mode files.
4765
4766 The following commands are available:
4767
4768 \\{org-agenda-mode-map}"
4769 (interactive)
4770 (kill-all-local-variables)
4771 (setq major-mode 'org-agenda-mode)
4772 (setq mode-name "Org-Agenda")
4773 (use-local-map org-agenda-mode-map)
4774 (easy-menu-add org-agenda-menu)
4775 (if org-startup-truncated (setq truncate-lines t))
4776 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4777 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4778 (unless org-agenda-keep-modes
4779 (setq org-agenda-follow-mode nil
4780 org-agenda-show-log nil))
4781 (easy-menu-change
4782 '("Agenda") "Agenda Files"
4783 (append
4784 (list
4785 (vector
4786 (if (get 'org-agenda-files 'org-restrict)
4787 "Restricted to single file"
4788 "Edit File List")
4789 '(org-edit-agenda-file-list)
4790 (not (get 'org-agenda-files 'org-restrict)))
4791 "--")
4792 (mapcar 'org-file-menu-entry (org-agenda-files))))
4793 (org-agenda-set-mode-name)
4794 (apply
4795 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4796 (list 'org-agenda-mode-hook)))
4797
4798 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4799 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
4800 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4801 (define-key org-agenda-mode-map " " 'org-agenda-show)
4802 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4803 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4804 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4805 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4806 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4807 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4808 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4809 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4810 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4811 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4812 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4813 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4814
4815 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4816 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4817 (while l (define-key org-agenda-mode-map
4818 (int-to-string (pop l)) 'digit-argument)))
4819
4820 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4821 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4822 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4823 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4824 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4825 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4826 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4827 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4828 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4829 (define-key org-agenda-mode-map "n" 'next-line)
4830 (define-key org-agenda-mode-map "p" 'previous-line)
4831 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4832 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4833 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4834 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4835 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4836 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4837 (eval-after-load "calendar"
4838 '(define-key calendar-mode-map org-calendar-to-agenda-key
4839 'org-calendar-goto-agenda))
4840 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4841 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4842 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4843 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4844 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4845 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4846 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4847 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4848 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4849 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4850 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4851 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4852 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4853 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4854 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4855 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4856 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4857 "Local keymap for agenda entries from Org-mode.")
4858
4859 (define-key org-agenda-keymap
4860 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4861 (define-key org-agenda-keymap
4862 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4863 (when org-agenda-mouse-1-follows-link
4864 (define-key org-agenda-keymap [follow-link] 'mouse-face))
4865 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4866 '("Agenda"
4867 ("Agenda Files")
4868 "--"
4869 ["Show" org-agenda-show t]
4870 ["Go To (other window)" org-agenda-goto t]
4871 ["Go To (one window)" org-agenda-switch-to t]
4872 ["Follow Mode" org-agenda-follow-mode
4873 :style toggle :selected org-agenda-follow-mode :active t]
4874 "--"
4875 ["Cycle TODO" org-agenda-todo t]
4876 ("Tags"
4877 ["Show all Tags" org-agenda-show-tags t]
4878 ["Set Tags" org-agenda-set-tags t])
4879 ("Reschedule"
4880 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4881 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4882 "--"
4883 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4884 ("Priority"
4885 ["Set Priority" org-agenda-priority t]
4886 ["Increase Priority" org-agenda-priority-up t]
4887 ["Decrease Priority" org-agenda-priority-down t]
4888 ["Show Priority" org-agenda-show-priority t])
4889 "--"
4890 ;; ["New agenda command" org-agenda t]
4891 ["Rebuild buffer" org-agenda-redo t]
4892 "--"
4893 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4894 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4895 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4896 "--"
4897 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4898 :style radio :selected (equal org-agenda-ndays 1)]
4899 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4900 :style radio :selected (equal org-agenda-ndays 7)]
4901 "--"
4902 ["Show Logbook entries" org-agenda-log-mode
4903 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4904 ["Include Diary" org-agenda-toggle-diary
4905 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4906 ["Use Time Grid" org-agenda-toggle-time-grid
4907 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4908 "--"
4909 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4910 ("Calendar Commands"
4911 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4912 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4913 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4914 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4915 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4916 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4917 "--"
4918 ["Quit" org-agenda-quit t]
4919 ["Exit and Release Buffers" org-agenda-exit t]
4920 ))
4921
4922 ;;;###autoload
4923 (defun org-agenda (arg)
4924 "Dispatch agenda commands to collect entries to the agenda buffer.
4925 Prompts for a character to select a command. Any prefix arg will be passed
4926 on to the selected command. The default selections are:
4927
4928 a Call `org-agenda' to display the agenda for the current day or week.
4929 t Call `org-todo-list' to display the global todo list.
4930 T Call `org-todo-list' to display the global todo list, select only
4931 entries with a specific TODO keyword (the user gets a prompt).
4932 m Call `org-tags-view' to display headlines with tags matching
4933 a condition (the user is prompted for the condition).
4934 M Like `m', but select only TODO entries, no ordinary headlines.
4935
4936 More commands can be added by configuring the variable
4937 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4938 searches can be pre-defined in this way.
4939
4940 If the current buffer is in Org-mode and visiting a file, you can also
4941 first press `1' to indicate that the agenda should be temporarily (until the
4942 next use of \\[org-agenda]) restricted to the current file."
4943 (interactive "P")
4944 (catch 'exit
4945 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4946 (custom org-agenda-custom-commands)
4947 c entry key type string)
4948 (put 'org-agenda-files 'org-restrict nil)
4949 (save-window-excursion
4950 (delete-other-windows)
4951 (switch-to-buffer-other-window " *Agenda Commands*")
4952 (erase-buffer)
4953 (insert
4954 "Press key for an agenda command:
4955 --------------------------------
4956 a Agenda for current week or day
4957 t List of all TODO entries T Entries with special TODO kwd
4958 m Match a TAGS query M Like m, but only TODO entries
4959 C Configure your own agenda commands")
4960 (while (setq entry (pop custom))
4961 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4962 (insert (format "\n%-4s%-14s: %s"
4963 key
4964 (cond
4965 ((eq type 'tags) "Tags query")
4966 ((eq type 'todo) "TODO keyword")
4967 ((eq type 'tags-tree) "Tags tree")
4968 ((eq type 'todo-tree) "TODO kwd tree")
4969 ((eq type 'occur-tree) "Occur tree")
4970 (t "???"))
4971 (org-add-props string nil 'face 'org-warning))))
4972 (goto-char (point-min))
4973 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4974 (message "Press key for agenda command%s"
4975 (if restrict-ok ", or [1] to restrict to current file" ""))
4976 (setq c (read-char-exclusive))
4977 (message "")
4978 (when (equal c ?1)
4979 (if restrict-ok
4980 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
4981 (error "Cannot restrict agenda to current buffer"))
4982 (message "Press key for agenda command%s"
4983 (if restrict-ok " (restricted to current file)" ""))
4984 (setq c (read-char-exclusive))
4985 (message "")))
4986 (require 'calendar) ; FIXME: can we avoid this for some commands?
4987 ;; For example the todo list should not need it (but does...)
4988 (cond
4989 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4990 ((equal c ?a) (call-interactively 'org-agenda-list))
4991 ((equal c ?t) (call-interactively 'org-todo-list))
4992 ((equal c ?T)
4993 (setq current-prefix-arg (or arg '(4)))
4994 (call-interactively 'org-todo-list))
4995 ((equal c ?m) (call-interactively 'org-tags-view))
4996 ((equal c ?M)
4997 (setq current-prefix-arg (or arg '(4)))
4998 (call-interactively 'org-tags-view))
4999 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
5000 (setq type (nth 1 entry) string (nth 2 entry))
5001 (cond
5002 ((eq type 'tags)
5003 (org-tags-view current-prefix-arg string))
5004 ((eq type 'todo)
5005 (org-todo-list string))
5006 ((eq type 'tags-tree)
5007 (org-check-for-org-mode)
5008 (org-tags-sparse-tree current-prefix-arg string))
5009 ((eq type 'todo-tree)
5010 (org-check-for-org-mode)
5011 (org-occur (concat "^" outline-regexp "[ \t]*"
5012 (regexp-quote string) "\\>")))
5013 ((eq type 'occur-tree)
5014 (org-check-for-org-mode)
5015 (org-occur string))
5016 (t (error "Invalid custom agenda command type %s" type))))
5017 (t (error "Invalid key"))))))
5018
5019 (defun org-check-for-org-mode ()
5020 "Make sure current buffer is in org-mode. Error if not."
5021 (or (eq major-mode 'org-mode)
5022 (error "Cannot execute org-mode agenda command on buffer in %s."
5023 major-mode)))
5024
5025 (defun org-fit-agenda-window ()
5026 "Fit the window to the buffer size."
5027 (and org-fit-agenda-window
5028 (fboundp 'fit-window-to-buffer)
5029 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
5030 (/ (frame-height) 2))))
5031
5032 (defun org-agenda-files (&optional unrestricted)
5033 "Get the list of agenda files.
5034 Optional UNRESTRICTED means return the full list even if a restriction
5035 is currently in place."
5036 (cond
5037 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
5038 ((stringp org-agenda-files) (org-read-agenda-file-list))
5039 ((listp org-agenda-files) org-agenda-files)
5040 (t (error "Invalid value of `org-agenda-files'"))))
5041
5042 (defvar org-window-configuration)
5043
5044 (defun org-edit-agenda-file-list ()
5045 "Edit the list of agenda files.
5046 Depending on setup, this either uses customize to edit the variable
5047 `org-agenda-files', or it visits the file that is holding the list. In the
5048 latter case, the buffer is set up in a way that saving it automatically kills
5049 the buffer and restores the previous window configuration."
5050 (interactive)
5051 (if (stringp org-agenda-files)
5052 (let ((cw (current-window-configuration)))
5053 (find-file org-agenda-files)
5054 (set (make-local-variable 'org-window-configuration) cw)
5055 (org-add-hook 'after-save-hook
5056 (lambda ()
5057 (set-window-configuration
5058 (prog1 org-window-configuration
5059 (kill-buffer (current-buffer))))
5060 (org-install-agenda-files-menu)
5061 (message "New agenda file list installed"))
5062 nil 'local)
5063 (message (substitute-command-keys
5064 "Edit list and finish with \\[save-buffer]")))
5065 (customize-variable 'org-agenda-files)))
5066
5067 (defun org-store-new-agenda-file-list (list)
5068 "Set new value for the agenda file list and save it correcly."
5069 (if (stringp org-agenda-files)
5070 (let ((f org-agenda-files) b)
5071 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
5072 (with-temp-file f
5073 (insert (mapconcat 'identity list "\n") "\n")))
5074 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5075 (setq org-agenda-files list)
5076 (customize-save-variable 'org-agenda-files org-agenda-files))))
5077
5078 (defun org-read-agenda-file-list ()
5079 "Read the list of agenda files from a file."
5080 (when (stringp org-agenda-files)
5081 (with-temp-buffer
5082 (insert-file-contents org-agenda-files)
5083 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
5084
5085 (defvar org-agenda-markers nil
5086 "List of all currently active markers created by `org-agenda'.")
5087 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
5088 "Creation time of the last agenda marker.")
5089
5090 (defun org-agenda-new-marker (&optional pos)
5091 "Return a new agenda marker.
5092 Org-mode keeps a list of these markers and resets them when they are
5093 no longer in use."
5094 (let ((m (copy-marker (or pos (point)))))
5095 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
5096 (push m org-agenda-markers)
5097 m))
5098
5099 (defun org-agenda-maybe-reset-markers (&optional force)
5100 "Reset markers created by `org-agenda'. But only if they are old enough."
5101 (if (or force
5102 (> (- (time-to-seconds (current-time))
5103 org-agenda-last-marker-time)
5104 5))
5105 (while org-agenda-markers
5106 (move-marker (pop org-agenda-markers) nil))))
5107
5108 (defvar org-agenda-new-buffers nil
5109 "Buffers created to visit agenda files.")
5110
5111 (defun org-get-agenda-file-buffer (file)
5112 "Get a buffer visiting FILE. If the buffer needs to be created, add
5113 it to the list of buffers which might be released later."
5114 (let ((buf (find-buffer-visiting file)))
5115 (if buf
5116 buf ; just return it
5117 ;; Make a new buffer and remember it
5118 (setq buf (find-file-noselect file))
5119 (if buf (push buf org-agenda-new-buffers))
5120 buf)))
5121
5122 (defun org-release-buffers (blist)
5123 "Release all buffers in list, asking the user for confirmation when needed.
5124 When a buffer is unmodified, it is just killed. When modified, it is saved
5125 \(if the user agrees) and then killed."
5126 (let (buf file)
5127 (while (setq buf (pop blist))
5128 (setq file (buffer-file-name buf))
5129 (when (and (buffer-modified-p buf)
5130 file
5131 (y-or-n-p (format "Save file %s? " file)))
5132 (with-current-buffer buf (save-buffer)))
5133 (kill-buffer buf))))
5134
5135 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
5136
5137 (defun org-timeline (&optional include-all keep-modes)
5138 "Show a time-sorted view of the entries in the current org file.
5139 Only entries with a time stamp of today or later will be listed. With
5140 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
5141 under the current date.
5142 If the buffer contains an active region, only check the region for
5143 dates."
5144 (interactive "P")
5145 (require 'calendar)
5146 (org-agenda-maybe-reset-markers 'force)
5147 (org-compile-prefix-format org-timeline-prefix-format)
5148 (let* ((dopast t)
5149 (dotodo include-all)
5150 (doclosed org-agenda-show-log)
5151 (org-agenda-keep-modes keep-modes)
5152 (entry buffer-file-name)
5153 (org-agenda-files (list buffer-file-name))
5154 (date (calendar-current-date))
5155 (win (selected-window))
5156 (pos1 (point))
5157 (beg (if (org-region-active-p) (region-beginning) (point-min)))
5158 (end (if (org-region-active-p) (region-end) (point-max)))
5159 (day-numbers (org-get-all-dates beg end 'no-ranges
5160 t doclosed)) ; always include today
5161 (today (time-to-days (current-time)))
5162 (org-respect-restriction t)
5163 (past t)
5164 args
5165 s e rtn d)
5166 (setq org-agenda-redo-command
5167 (list 'progn
5168 (list 'switch-to-buffer-other-window (current-buffer))
5169 (list 'org-timeline (list 'quote include-all) t)))
5170 (if (not dopast)
5171 ;; Remove past dates from the list of dates.
5172 (setq day-numbers (delq nil (mapcar (lambda(x)
5173 (if (>= x today) x nil))
5174 day-numbers))))
5175 (switch-to-buffer-other-window
5176 (get-buffer-create org-agenda-buffer-name))
5177 (setq buffer-read-only nil)
5178 (erase-buffer)
5179 (org-agenda-mode) (setq buffer-read-only nil)
5180 (set (make-local-variable 'org-agenda-type) 'timeline)
5181 (if doclosed (push :closed args))
5182 (push :timestamp args)
5183 (if dotodo (push :todo args))
5184 (while (setq d (pop day-numbers))
5185 (if (and (>= d today)
5186 dopast
5187 past)
5188 (progn
5189 (setq past nil)
5190 (insert (make-string 79 ?-) "\n")))
5191 (setq date (calendar-gregorian-from-absolute d))
5192 (setq s (point))
5193 (setq rtn (apply 'org-agenda-get-day-entries
5194 entry date args))
5195 (if (or rtn (equal d today))
5196 (progn
5197 (insert (calendar-day-name date) " "
5198 (number-to-string (extract-calendar-day date)) " "
5199 (calendar-month-name (extract-calendar-month date)) " "
5200 (number-to-string (extract-calendar-year date)) "\n")
5201 (put-text-property s (1- (point)) 'face
5202 'org-level-3)
5203 (if (equal d today)
5204 (put-text-property s (1- (point)) 'org-today t))
5205 (insert (org-finalize-agenda-entries rtn) "\n")
5206 (put-text-property s (1- (point)) 'day d))))
5207 (goto-char (point-min))
5208 (setq buffer-read-only t)
5209 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5210 (point-min)))
5211 (when (not org-select-timeline-window)
5212 (select-window win)
5213 (goto-char pos1))))
5214
5215 ;;;###autoload
5216 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
5217 "Produce a weekly view from all files in variable `org-agenda-files'.
5218 The view will be for the current week, but from the overview buffer you
5219 will be able to go to other weeks.
5220 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
5221 also be shown, under the current date.
5222 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
5223 on the days are also shown. See the variable `org-log-done' for how
5224 to turn on logging.
5225 START-DAY defaults to TODAY, or to the most recent match for the weekday
5226 given in `org-agenda-start-on-weekday'.
5227 NDAYS defaults to `org-agenda-ndays'."
5228 (interactive "P")
5229 (org-agenda-maybe-reset-markers 'force)
5230 (org-compile-prefix-format org-agenda-prefix-format)
5231 (require 'calendar)
5232 (let* ((org-agenda-start-on-weekday
5233 (if (or (equal ndays 1)
5234 (and (null ndays) (equal 1 org-agenda-ndays)))
5235 nil org-agenda-start-on-weekday))
5236 (org-agenda-keep-modes keep-modes)
5237 (thefiles (org-agenda-files))
5238 (files thefiles)
5239 (win (selected-window))
5240 (today (time-to-days (current-time)))
5241 (sd (or start-day today))
5242 (start (if (or (null org-agenda-start-on-weekday)
5243 (< org-agenda-ndays 7))
5244 sd
5245 (let* ((nt (calendar-day-of-week
5246 (calendar-gregorian-from-absolute sd)))
5247 (n1 org-agenda-start-on-weekday)
5248 (d (- nt n1)))
5249 (- sd (+ (if (< d 0) 7 0) d)))))
5250 (day-numbers (list start))
5251 (inhibit-redisplay t)
5252 s e rtn rtnall file date d start-pos end-pos todayp nd)
5253 (setq org-agenda-redo-command
5254 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
5255 ;; Make the list of days
5256 (setq ndays (or ndays org-agenda-ndays)
5257 nd ndays)
5258 (while (> ndays 1)
5259 (push (1+ (car day-numbers)) day-numbers)
5260 (setq ndays (1- ndays)))
5261 (setq day-numbers (nreverse day-numbers))
5262 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5263 (progn
5264 (delete-other-windows)
5265 (switch-to-buffer-other-window
5266 (get-buffer-create org-agenda-buffer-name))))
5267 (setq buffer-read-only nil)
5268 (erase-buffer)
5269 (org-agenda-mode) (setq buffer-read-only nil)
5270 (set (make-local-variable 'org-agenda-type) 'agenda)
5271 (set (make-local-variable 'starting-day) (car day-numbers))
5272 (set (make-local-variable 'include-all-loc) include-all)
5273 (when (and (or include-all org-agenda-include-all-todo)
5274 (member today day-numbers))
5275 (setq files thefiles
5276 rtnall nil)
5277 (while (setq file (pop files))
5278 (catch 'nextfile
5279 (org-check-agenda-file file)
5280 (setq date (calendar-gregorian-from-absolute today)
5281 rtn (org-agenda-get-day-entries
5282 file date :todo))
5283 (setq rtnall (append rtnall rtn))))
5284 (when rtnall
5285 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
5286 (add-text-properties (point-min) (1- (point))
5287 (list 'face 'org-level-3))
5288 (insert (org-finalize-agenda-entries rtnall) "\n")))
5289 (while (setq d (pop day-numbers))
5290 (setq date (calendar-gregorian-from-absolute d)
5291 s (point))
5292 (if (or (setq todayp (= d today))
5293 (and (not start-pos) (= d sd)))
5294 (setq start-pos (point))
5295 (if (and start-pos (not end-pos))
5296 (setq end-pos (point))))
5297 (setq files thefiles
5298 rtnall nil)
5299 (while (setq file (pop files))
5300 (catch 'nextfile
5301 (org-check-agenda-file file)
5302 (if org-agenda-show-log
5303 (setq rtn (org-agenda-get-day-entries
5304 file date
5305 :deadline :scheduled :timestamp :closed))
5306 (setq rtn (org-agenda-get-day-entries
5307 file date
5308 :deadline :scheduled :timestamp)))
5309 (setq rtnall (append rtnall rtn))))
5310 (if org-agenda-include-diary
5311 (progn
5312 (require 'diary-lib)
5313 (setq rtn (org-get-entries-from-diary date))
5314 (setq rtnall (append rtnall rtn))))
5315 (if (or rtnall org-agenda-show-all-dates)
5316 (progn
5317 (insert (format "%-9s %2d %s %4d\n"
5318 (calendar-day-name date)
5319 (extract-calendar-day date)
5320 (calendar-month-name (extract-calendar-month date))
5321 (extract-calendar-year date)))
5322 (put-text-property s (1- (point)) 'face
5323 'org-level-3)
5324 (if rtnall (insert
5325 (org-finalize-agenda-entries
5326 (org-agenda-add-time-grid-maybe
5327 rtnall nd todayp))
5328 "\n"))
5329 (put-text-property s (1- (point)) 'day d))))
5330 (goto-char (point-min))
5331 (setq buffer-read-only t)
5332 (org-fit-agenda-window)
5333 (unless (and (pos-visible-in-window-p (point-min))
5334 (pos-visible-in-window-p (point-max)))
5335 (goto-char (1- (point-max)))
5336 (recenter -1)
5337 (if (not (pos-visible-in-window-p (or start-pos 1)))
5338 (progn
5339 (goto-char (or start-pos 1))
5340 (recenter 1))))
5341 (goto-char (or start-pos 1))
5342 (if (not org-select-agenda-window) (select-window win))
5343 (message "")))
5344
5345 (defvar org-select-this-todo-keyword nil)
5346
5347 ;;;###autoload
5348 (defun org-todo-list (arg &optional keep-modes)
5349 "Show all TODO entries from all agenda file in a single list.
5350 The prefix arg can be used to select a specific TODO keyword and limit
5351 the list to these. When using \\[universal-argument], you will be prompted
5352 for a keyword. A numeric prefix directly selects the Nth keyword in
5353 `org-todo-keywords'."
5354 (interactive "P")
5355 (org-agenda-maybe-reset-markers 'force)
5356 (org-compile-prefix-format org-agenda-prefix-format)
5357 (let* ((org-agenda-keep-modes keep-modes)
5358 (today (time-to-days (current-time)))
5359 (date (calendar-gregorian-from-absolute today))
5360 (win (selected-window))
5361 (kwds org-todo-keywords)
5362 (completion-ignore-case t)
5363 (org-select-this-todo-keyword
5364 (if (stringp arg) arg
5365 (and arg (integerp arg) (> arg 0)
5366 (nth (1- arg) org-todo-keywords))))
5367 rtn rtnall files file pos)
5368 (when (equal arg '(4))
5369 (setq org-select-this-todo-keyword
5370 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
5371 nil t)))
5372 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
5373 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5374 (progn
5375 (delete-other-windows)
5376 (switch-to-buffer-other-window
5377 (get-buffer-create org-agenda-buffer-name))))
5378 (setq buffer-read-only nil)
5379 (erase-buffer)
5380 (org-agenda-mode) (setq buffer-read-only nil)
5381 (set (make-local-variable 'org-agenda-type) 'todo)
5382 (set (make-local-variable 'last-arg) arg)
5383 (set (make-local-variable 'org-todo-keywords) kwds)
5384 (set (make-local-variable 'org-agenda-redo-command)
5385 '(org-todo-list (or current-prefix-arg last-arg) t))
5386 (setq files (org-agenda-files)
5387 rtnall nil)
5388 (while (setq file (pop files))
5389 (catch 'nextfile
5390 (org-check-agenda-file file)
5391 (setq rtn (org-agenda-get-day-entries file date :todo))
5392 (setq rtnall (append rtnall rtn))))
5393 (insert "Global list of TODO items of type: ")
5394 (add-text-properties (point-min) (1- (point))
5395 (list 'face 'org-level-3))
5396 (setq pos (point))
5397 (insert (or org-select-this-todo-keyword "ALL") "\n")
5398 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
5399 (setq pos (point))
5400 (insert
5401 "Available with `N r': (0)ALL "
5402 (let ((n 0))
5403 (mapconcat (lambda (x)
5404 (format "(%d)%s" (setq n (1+ n)) x))
5405 org-todo-keywords " "))
5406 "\n")
5407 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
5408 (when rtnall
5409 (insert (org-finalize-agenda-entries rtnall) "\n"))
5410 (goto-char (point-min))
5411 (setq buffer-read-only t)
5412 (org-fit-agenda-window)
5413 (if (not org-select-agenda-window) (select-window win))))
5414
5415 (defun org-check-agenda-file (file)
5416 "Make sure FILE exists. If not, ask user what to do."
5417 (when (not (file-exists-p file))
5418 (message "non-existent file %s. [R]emove from list or [A]bort?"
5419 (abbreviate-file-name file))
5420 (let ((r (downcase (read-char-exclusive))))
5421 (cond
5422 ((equal r ?r)
5423 (org-remove-file file)
5424 (throw 'nextfile t))
5425 (t (error "Abort"))))))
5426
5427 (defun org-agenda-check-type (error &rest types)
5428 "Check if agenda buffer is of allowed type.
5429 If ERROR is non-nil, throw an error, otherwise just return nil."
5430 (if (memq org-agenda-type types)
5431 t
5432 (if error
5433 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
5434 nil)))
5435
5436 (defun org-agenda-quit ()
5437 "Exit agenda by removing the window or the buffer."
5438 (interactive)
5439 (let ((buf (current-buffer)))
5440 (if (not (one-window-p)) (delete-window))
5441 (kill-buffer buf)
5442 (org-agenda-maybe-reset-markers 'force)))
5443
5444 (defun org-agenda-exit ()
5445 "Exit agenda by removing the window or the buffer.
5446 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
5447 Org-mode buffers visited directly by the user will not be touched."
5448 (interactive)
5449 (org-release-buffers org-agenda-new-buffers)
5450 (setq org-agenda-new-buffers nil)
5451 (org-agenda-quit))
5452
5453 (defun org-agenda-redo ()
5454 "Rebuild Agenda.
5455 When this is the global TODO list, a prefix argument will be interpreted."
5456 (interactive)
5457 (message "Rebuilding agenda buffer...")
5458 (eval org-agenda-redo-command)
5459 (message "Rebuilding agenda buffer...done"))
5460
5461 (defun org-agenda-goto-today ()
5462 "Go to today."
5463 (interactive)
5464 (org-agenda-check-type t 'timeline 'agenda)
5465 (if (boundp 'starting-day)
5466 (let ((cmd (car org-agenda-redo-command))
5467 (iall (nth 1 org-agenda-redo-command))
5468 (nday (nth 3 org-agenda-redo-command))
5469 (keep (nth 4 org-agenda-redo-command)))
5470 (eval (list cmd iall nil nday keep)))
5471 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5472 (point-min)))))
5473
5474 (defun org-agenda-later (arg)
5475 "Go forward in time by `org-agenda-ndays' days.
5476 With prefix ARG, go forward that many times `org-agenda-ndays'."
5477 (interactive "p")
5478 (org-agenda-check-type t 'agenda)
5479 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5480 (+ starting-day (* arg org-agenda-ndays)) nil t))
5481
5482 (defun org-agenda-earlier (arg)
5483 "Go back in time by `org-agenda-ndays' days.
5484 With prefix ARG, go back that many times `org-agenda-ndays'."
5485 (interactive "p")
5486 (org-agenda-check-type t 'agenda)
5487 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5488 (- starting-day (* arg org-agenda-ndays)) nil t))
5489
5490 (defun org-agenda-week-view ()
5491 "Switch to weekly view for agenda."
5492 (interactive)
5493 (org-agenda-check-type t 'agenda)
5494 (setq org-agenda-ndays 7)
5495 (org-agenda-list include-all-loc
5496 (or (get-text-property (point) 'day)
5497 starting-day)
5498 nil t)
5499 (org-agenda-set-mode-name)
5500 (message "Switched to week view"))
5501
5502 (defun org-agenda-day-view ()
5503 "Switch to daily view for agenda."
5504 (interactive)
5505 (org-agenda-check-type t 'agenda)
5506 (setq org-agenda-ndays 1)
5507 (org-agenda-list include-all-loc
5508 (or (get-text-property (point) 'day)
5509 starting-day)
5510 nil t)
5511 (org-agenda-set-mode-name)
5512 (message "Switched to day view"))
5513
5514 (defun org-agenda-next-date-line (&optional arg)
5515 "Jump to the next line indicating a date in agenda buffer."
5516 (interactive "p")
5517 (org-agenda-check-type t 'agenda 'timeline)
5518 (beginning-of-line 1)
5519 (if (looking-at "^\\S-") (forward-char 1))
5520 (if (not (re-search-forward "^\\S-" nil t arg))
5521 (progn
5522 (backward-char 1)
5523 (error "No next date after this line in this buffer")))
5524 (goto-char (match-beginning 0)))
5525
5526 (defun org-agenda-previous-date-line (&optional arg)
5527 "Jump to the previous line indicating a date in agenda buffer."
5528 (interactive "p")
5529 (org-agenda-check-type t 'agenda 'timeline)
5530 (beginning-of-line 1)
5531 (if (not (re-search-backward "^\\S-" nil t arg))
5532 (error "No previous date before this line in this buffer")))
5533
5534 ;; Initialize the highlight
5535 (defvar org-hl (org-make-overlay 1 1))
5536 (org-overlay-put org-hl 'face 'highlight)
5537
5538 (defun org-highlight (begin end &optional buffer)
5539 "Highlight a region with overlay."
5540 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
5541 org-hl begin end (or buffer (current-buffer))))
5542
5543 (defun org-unhighlight ()
5544 "Detach overlay INDEX."
5545 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
5546
5547
5548 (defun org-agenda-follow-mode ()
5549 "Toggle follow mode in an agenda buffer."
5550 (interactive)
5551 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5552 (org-agenda-set-mode-name)
5553 (message "Follow mode is %s"
5554 (if org-agenda-follow-mode "on" "off")))
5555
5556 (defun org-agenda-log-mode ()
5557 "Toggle log mode in an agenda buffer."
5558 (interactive)
5559 (org-agenda-check-type t 'agenda 'timeline)
5560 (setq org-agenda-show-log (not org-agenda-show-log))
5561 (org-agenda-set-mode-name)
5562 (org-agenda-redo)
5563 (message "Log mode is %s"
5564 (if org-agenda-show-log "on" "off")))
5565
5566 (defun org-agenda-toggle-diary ()
5567 "Toggle diary inclusion in an agenda buffer."
5568 (interactive)
5569 (org-agenda-check-type t 'agenda)
5570 (setq org-agenda-include-diary (not org-agenda-include-diary))
5571 (org-agenda-redo)
5572 (org-agenda-set-mode-name)
5573 (message "Diary inclusion turned %s"
5574 (if org-agenda-include-diary "on" "off")))
5575
5576 (defun org-agenda-toggle-time-grid ()
5577 "Toggle time grid in an agenda buffer."
5578 (interactive)
5579 (org-agenda-check-type t 'agenda)
5580 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5581 (org-agenda-redo)
5582 (org-agenda-set-mode-name)
5583 (message "Time-grid turned %s"
5584 (if org-agenda-use-time-grid "on" "off")))
5585
5586 (defun org-agenda-set-mode-name ()
5587 "Set the mode name to indicate all the small mode settings."
5588 (setq mode-name
5589 (concat "Org-Agenda"
5590 (if (equal org-agenda-ndays 1) " Day" "")
5591 (if (equal org-agenda-ndays 7) " Week" "")
5592 (if org-agenda-follow-mode " Follow" "")
5593 (if org-agenda-include-diary " Diary" "")
5594 (if org-agenda-use-time-grid " Grid" "")
5595 (if org-agenda-show-log " Log" "")))
5596 (force-mode-line-update))
5597
5598 (defun org-agenda-post-command-hook ()
5599 (and (eolp) (not (bolp)) (backward-char 1))
5600 (if (and org-agenda-follow-mode
5601 (get-text-property (point) 'org-marker))
5602 (org-agenda-show)))
5603
5604 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5605
5606 (defun org-get-entries-from-diary (date)
5607 "Get the (Emacs Calendar) diary entries for DATE."
5608 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5609 (diary-display-hook '(fancy-diary-display))
5610 (list-diary-entries-hook
5611 (cons 'org-diary-default-entry list-diary-entries-hook))
5612 (diary-file-name-prefix-function nil) ; turn this feature off
5613 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5614 entries
5615 (org-disable-agenda-to-diary t))
5616 (save-excursion
5617 (save-window-excursion
5618 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
5619 (if (not (get-buffer fancy-diary-buffer))
5620 (setq entries nil)
5621 (with-current-buffer fancy-diary-buffer
5622 (setq buffer-read-only nil)
5623 (if (= (point-max) 1)
5624 ;; No entries
5625 (setq entries nil)
5626 ;; Omit the date and other unnecessary stuff
5627 (org-agenda-cleanup-fancy-diary)
5628 ;; Add prefix to each line and extend the text properties
5629 (if (= (point-max) 1)
5630 (setq entries nil)
5631 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5632 (set-buffer-modified-p nil)
5633 (kill-buffer fancy-diary-buffer)))
5634 (when entries
5635 (setq entries (org-split-string entries "\n"))
5636 (setq entries
5637 (mapcar
5638 (lambda (x)
5639 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5640 ;; Extend the text properties to the beginning of the line
5641 (org-add-props x (text-properties-at (1- (length x)) x)))
5642 entries)))))
5643
5644 (defun org-agenda-cleanup-fancy-diary ()
5645 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5646 This gets rid of the date, the underline under the date, and
5647 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5648 date. It also removes lines that contain only whitespace."
5649 (goto-char (point-min))
5650 (if (looking-at ".*?:[ \t]*")
5651 (progn
5652 (replace-match "")
5653 (re-search-forward "\n=+$" nil t)
5654 (replace-match "")
5655 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5656 (re-search-forward "\n=+$" nil t)
5657 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5658 (goto-char (point-min))
5659 (while (re-search-forward "^ +\n" nil t)
5660 (replace-match ""))
5661 (goto-char (point-min))
5662 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5663 (replace-match "")))
5664
5665 ;; Make sure entries from the diary have the right text properties.
5666 (eval-after-load "diary-lib"
5667 '(if (boundp 'diary-modify-entry-list-string-function)
5668 ;; We can rely on the hook, nothing to do
5669 nil
5670 ;; Hook not avaiable, must use advice to make this work
5671 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5672 "Make the position visible."
5673 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5674 (stringp string)
5675 buffer-file-name)
5676 (setq string (org-modify-diary-entry-string string))))))
5677
5678 (defun org-modify-diary-entry-string (string)
5679 "Add text properties to string, allowing org-mode to act on it."
5680 (org-add-props string nil
5681 'mouse-face 'highlight
5682 'keymap org-agenda-keymap
5683 'help-echo (format "mouse-2 or RET jump to diary file %s"
5684 (abbreviate-file-name buffer-file-name))
5685 'org-agenda-diary-link t
5686 'org-marker (org-agenda-new-marker (point-at-bol))))
5687
5688 (defun org-diary-default-entry ()
5689 "Add a dummy entry to the diary.
5690 Needed to avoid empty dates which mess up holiday display."
5691 ;; Catch the error if dealing with the new add-to-diary-alist
5692 (when org-disable-agenda-to-diary
5693 (condition-case nil
5694 (add-to-diary-list original-date "Org-mode dummy" "")
5695 (error
5696 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5697
5698 (defun org-cycle-agenda-files ()
5699 "Cycle through the files in `org-agenda-files'.
5700 If the current buffer visits an agenda file, find the next one in the list.
5701 If the current buffer does not, find the first agenda file."
5702 (interactive)
5703 (let* ((fs (org-agenda-files t))
5704 (files (append fs (list (car fs))))
5705 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5706 file)
5707 (unless files (error "No agenda files"))
5708 (catch 'exit
5709 (while (setq file (pop files))
5710 (if (equal (file-truename file) tcf)
5711 (when (car files)
5712 (find-file (car files))
5713 (throw 'exit t))))
5714 (find-file (car fs)))))
5715
5716 (defun org-agenda-file-to-end ()
5717 "Move/add the current file to the end of the agenda file list.
5718 If the file is not present in the list, it is appended to the list. If it is
5719 present, it is moved there."
5720 (interactive)
5721 (org-agenda-file-to-front 'to-end))
5722
5723 (defun org-agenda-file-to-front (&optional to-end)
5724 "Move/add the current file to the top of the agenda file list.
5725 If the file is not present in the list, it is added to the front. If it is
5726 present, it is moved there. With optional argument TO-END, add/move to the
5727 end of the list."
5728 (interactive "P")
5729 (let ((file-alist (mapcar (lambda (x)
5730 (cons (file-truename x) x))
5731 (org-agenda-files t)))
5732 (ctf (file-truename buffer-file-name))
5733 x had)
5734 (setq x (assoc ctf file-alist) had x)
5735
5736 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5737 (if to-end
5738 (setq file-alist (append (delq x file-alist) (list x)))
5739 (setq file-alist (cons x (delq x file-alist))))
5740 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
5741 (org-install-agenda-files-menu)
5742 (message "File %s to %s of agenda file list"
5743 (if had "moved" "added") (if to-end "end" "front"))))
5744
5745 (defun org-remove-file (&optional file)
5746 "Remove current file from the list of files in variable `org-agenda-files'.
5747 These are the files which are being checked for agenda entries.
5748 Optional argument FILE means, use this file instead of the current."
5749 (interactive)
5750 (let* ((file (or file buffer-file-name))
5751 (true-file (file-truename file))
5752 (afile (abbreviate-file-name file))
5753 (files (delq nil (mapcar
5754 (lambda (x)
5755 (if (equal true-file
5756 (file-truename x))
5757 nil x))
5758 (org-agenda-files t)))))
5759 (if (not (= (length files) (length (org-agenda-files t))))
5760 (progn
5761 (org-store-new-agenda-file-list files)
5762 (org-install-agenda-files-menu)
5763 (message "Removed file: %s" afile))
5764 (message "File was not in list: %s" afile))))
5765
5766 (defun org-file-menu-entry (file)
5767 (vector file (list 'find-file file) t))
5768
5769 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5770 "Return a list of all relevant day numbers from BEG to END buffer positions.
5771 If NO-RANGES is non-nil, include only the start and end dates of a range,
5772 not every single day in the range. If FORCE-TODAY is non-nil, make
5773 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5774 inactive time stamps (those in square brackets) are included."
5775 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5776 dates date day day1 day2 ts1 ts2)
5777 (if force-today
5778 (setq dates (list (time-to-days (current-time)))))
5779 (save-excursion
5780 (goto-char beg)
5781 (while (re-search-forward re end t)
5782 (setq day (time-to-days (org-time-string-to-time
5783 (substring (match-string 1) 0 10))))
5784 (or (memq day dates) (push day dates)))
5785 (unless no-ranges
5786 (goto-char beg)
5787 (while (re-search-forward org-tr-regexp end t)
5788 (setq ts1 (substring (match-string 1) 0 10)
5789 ts2 (substring (match-string 2) 0 10)
5790 day1 (time-to-days (org-time-string-to-time ts1))
5791 day2 (time-to-days (org-time-string-to-time ts2)))
5792 (while (< (setq day1 (1+ day1)) day2)
5793 (or (memq day1 dates) (push day1 dates)))))
5794 (sort dates '<))))
5795
5796 ;;;###autoload
5797 (defun org-diary (&rest args)
5798 "Return diary information from org-files.
5799 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5800 It accesses org files and extracts information from those files to be
5801 listed in the diary. The function accepts arguments specifying what
5802 items should be listed. The following arguments are allowed:
5803
5804 :timestamp List the headlines of items containing a date stamp or
5805 date range matching the selected date. Deadlines will
5806 also be listed, on the expiration day.
5807
5808 :deadline List any deadlines past due, or due within
5809 `org-deadline-warning-days'. The listing occurs only
5810 in the diary for *today*, not at any other date. If
5811 an entry is marked DONE, it is no longer listed.
5812
5813 :scheduled List all items which are scheduled for the given date.
5814 The diary for *today* also contains items which were
5815 scheduled earlier and are not yet marked DONE.
5816
5817 :todo List all TODO items from the org-file. This may be a
5818 long list - so this is not turned on by default.
5819 Like deadlines, these entries only show up in the
5820 diary for *today*, not at any other date.
5821
5822 The call in the diary file should look like this:
5823
5824 &%%(org-diary) ~/path/to/some/orgfile.org
5825
5826 Use a separate line for each org file to check. Or, if you omit the file name,
5827 all files listed in `org-agenda-files' will be checked automatically:
5828
5829 &%%(org-diary)
5830
5831 If you don't give any arguments (as in the example above), the default
5832 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5833 also be written as
5834
5835 &%%(org-diary :deadline :timestamp :scheduled)
5836
5837 The function expects the lisp variables `entry' and `date' to be provided
5838 by the caller, because this is how the calendar works. Don't use this
5839 function from a program - use `org-agenda-get-day-entries' instead."
5840 (org-agenda-maybe-reset-markers)
5841 (org-compile-prefix-format org-agenda-prefix-format)
5842 (setq args (or args '(:deadline :scheduled :timestamp)))
5843 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5844 (list entry)
5845 (org-agenda-files t)))
5846 file rtn results)
5847 ;; If this is called during org-agenda, don't return any entries to
5848 ;; the calendar. Org Agenda will list these entries itself.
5849 (if org-disable-agenda-to-diary (setq files nil))
5850 (while (setq file (pop files))
5851 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5852 (setq results (append results rtn)))
5853 (if results
5854 (concat (org-finalize-agenda-entries results) "\n"))))
5855 (defvar org-category-table nil)
5856 (defun org-get-category-table ()
5857 "Get the table of categories and positions in current buffer."
5858 (let (tbl)
5859 (save-excursion
5860 (goto-char (point-min))
5861 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5862 (push (cons (point) (org-trim (match-string 2))) tbl)))
5863 tbl))
5864 (defun org-get-category (&optional pos)
5865 "Get the category applying to position POS."
5866 (if (not org-category-table)
5867 (cond
5868 ((null org-category)
5869 (setq org-category
5870 (if buffer-file-name
5871 (file-name-sans-extension
5872 (file-name-nondirectory buffer-file-name))
5873 "???")))
5874 ((symbolp org-category) (symbol-name org-category))
5875 (t org-category))
5876 (let ((tbl org-category-table)
5877 (pos (or pos (point))))
5878 (while (and tbl (> (caar tbl) pos))
5879 (pop tbl))
5880 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5881 org-category-table))))))
5882
5883 (defun org-agenda-get-day-entries (file date &rest args)
5884 "Does the work for `org-diary' and `org-agenda'.
5885 FILE is the path to a file to be checked for entries. DATE is date like
5886 the one returned by `calendar-current-date'. ARGS are symbols indicating
5887 which kind of entries should be extracted. For details about these, see
5888 the documentation of `org-diary'."
5889 (setq args (or args '(:deadline :scheduled :timestamp)))
5890 (let* ((org-startup-with-deadline-check nil)
5891 (org-startup-folded nil)
5892 (org-startup-align-all-tables nil)
5893 (buffer (if (file-exists-p file)
5894 (org-get-agenda-file-buffer file)
5895 (error "No such file %s" file)))
5896 arg results rtn)
5897 (if (not buffer)
5898 ;; If file does not exist, make sure an error message ends up in diary
5899 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5900 (with-current-buffer buffer
5901 (unless (eq major-mode 'org-mode)
5902 (error "Agenda file %s is not in `org-mode'" file))
5903 (setq org-category-table (org-get-category-table))
5904 (let ((case-fold-search nil))
5905 (save-excursion
5906 (save-restriction
5907 (if org-respect-restriction
5908 (if (org-region-active-p)
5909 ;; Respect a region to restrict search
5910 (narrow-to-region (region-beginning) (region-end)))
5911 ;; If we work for the calendar or many files,
5912 ;; get rid of any restriction
5913 (widen))
5914 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5915 (while (setq arg (pop args))
5916 (cond
5917 ((and (eq arg :todo)
5918 (equal date (calendar-current-date)))
5919 (setq rtn (org-agenda-get-todos))
5920 (setq results (append results rtn)))
5921 ((eq arg :timestamp)
5922 (setq rtn (org-agenda-get-blocks))
5923 (setq results (append results rtn))
5924 (setq rtn (org-agenda-get-timestamps))
5925 (setq results (append results rtn)))
5926 ((eq arg :scheduled)
5927 (setq rtn (org-agenda-get-scheduled))
5928 (setq results (append results rtn)))
5929 ((eq arg :closed)
5930 (setq rtn (org-agenda-get-closed))
5931 (setq results (append results rtn)))
5932 ((and (eq arg :deadline)
5933 (equal date (calendar-current-date)))
5934 (setq rtn (org-agenda-get-deadlines))
5935 (setq results (append results rtn))))))))
5936 results))))
5937
5938 (defun org-entry-is-done-p ()
5939 "Is the current entry marked DONE?"
5940 (save-excursion
5941 (and (re-search-backward "[\r\n]\\*" nil t)
5942 (looking-at org-nl-done-regexp))))
5943
5944 (defun org-at-date-range-p ()
5945 "Is the cursor inside a date range?"
5946 (interactive)
5947 (save-excursion
5948 (catch 'exit
5949 (let ((pos (point)))
5950 (skip-chars-backward "^<\r\n")
5951 (skip-chars-backward "<")
5952 (and (looking-at org-tr-regexp)
5953 (>= (match-end 0) pos)
5954 (throw 'exit t))
5955 (skip-chars-backward "^<\r\n")
5956 (skip-chars-backward "<")
5957 (and (looking-at org-tr-regexp)
5958 (>= (match-end 0) pos)
5959 (throw 'exit t)))
5960 nil)))
5961
5962 (defun org-agenda-get-todos ()
5963 "Return the TODO information for agenda display."
5964 (let* ((props (list 'face nil
5965 'done-face 'org-done
5966 'org-not-done-regexp org-not-done-regexp
5967 'mouse-face 'highlight
5968 'keymap org-agenda-keymap
5969 'help-echo
5970 (format "mouse-2 or RET jump to org file %s"
5971 (abbreviate-file-name buffer-file-name))))
5972 (regexp (concat "[\n\r]\\*+ *\\("
5973 (if org-select-this-todo-keyword
5974 (concat "\\<\\(" org-select-this-todo-keyword
5975 "\\)\\>")
5976 org-not-done-regexp)
5977 "[^\n\r]*\\)"))
5978 marker priority category tags
5979 ee txt)
5980 (goto-char (point-min))
5981 (while (re-search-forward regexp nil t)
5982 (goto-char (match-beginning 1))
5983 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5984 category (org-get-category)
5985 tags (org-get-tags-at (point))
5986 txt (org-format-agenda-item "" (match-string 1) category tags)
5987 priority
5988 (+ (org-get-priority txt)
5989 (if org-todo-kwd-priority-p
5990 (- org-todo-kwd-max-priority -2
5991 (length
5992 (member (match-string 2) org-todo-keywords)))
5993 1)))
5994 (org-add-props txt props
5995 'org-marker marker 'org-hd-marker marker
5996 'priority priority 'category category)
5997 (push txt ee)
5998 (goto-char (match-end 1)))
5999 (nreverse ee)))
6000
6001 (defconst org-agenda-no-heading-message
6002 "No heading for this item in buffer or region.")
6003
6004 (defun org-agenda-get-timestamps ()
6005 "Return the date stamp information for agenda display."
6006 (let* ((props (list 'face nil
6007 'org-not-done-regexp org-not-done-regexp
6008 'mouse-face 'highlight
6009 'keymap org-agenda-keymap
6010 'help-echo
6011 (format "mouse-2 or RET jump to org file %s"
6012 (abbreviate-file-name buffer-file-name))))
6013 (regexp (regexp-quote
6014 (substring
6015 (format-time-string
6016 (car org-time-stamp-formats)
6017 (apply 'encode-time ; DATE bound by calendar
6018 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6019 0 11)))
6020 marker hdmarker deadlinep scheduledp donep tmp priority category
6021 ee txt timestr tags)
6022 (goto-char (point-min))
6023 (while (re-search-forward regexp nil t)
6024 (if (not (save-match-data (org-at-date-range-p)))
6025 (progn
6026 (setq marker (org-agenda-new-marker (match-beginning 0))
6027 category (org-get-category (match-beginning 0))
6028 tmp (buffer-substring (max (point-min)
6029 (- (match-beginning 0)
6030 org-ds-keyword-length))
6031 (match-beginning 0))
6032 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6033 deadlinep (string-match org-deadline-regexp tmp)
6034 scheduledp (string-match org-scheduled-regexp tmp)
6035 donep (org-entry-is-done-p))
6036 (if (string-match ">" timestr)
6037 ;; substring should only run to end of time stamp
6038 (setq timestr (substring timestr 0 (match-end 0))))
6039 (save-excursion
6040 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6041 (progn
6042 (goto-char (match-end 1))
6043 (setq hdmarker (org-agenda-new-marker)
6044 tags (org-get-tags-at))
6045 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6046 (setq txt (org-format-agenda-item
6047 (format "%s%s"
6048 (if deadlinep "Deadline: " "")
6049 (if scheduledp "Scheduled: " ""))
6050 (match-string 1) category tags timestr)))
6051 (setq txt org-agenda-no-heading-message))
6052 (setq priority (org-get-priority txt))
6053 (org-add-props txt props
6054 'org-marker marker 'org-hd-marker hdmarker)
6055 (if deadlinep
6056 (org-add-props txt nil
6057 'face (if donep 'org-done 'org-warning)
6058 'undone-face 'org-warning 'done-face 'org-done
6059 'category category 'priority (+ 100 priority))
6060 (if scheduledp
6061 (org-add-props txt nil
6062 'face 'org-scheduled-today
6063 'undone-face 'org-scheduled-today 'done-face 'org-done
6064 'category category 'priority (+ 99 priority))
6065 (org-add-props txt nil 'priority priority 'category category)))
6066 (push txt ee))
6067 (outline-next-heading))))
6068 (nreverse ee)))
6069
6070 (defun org-agenda-get-closed ()
6071 "Return the logged TODO entries for agenda display."
6072 (let* ((props (list 'mouse-face 'highlight
6073 'org-not-done-regexp org-not-done-regexp
6074 'keymap org-agenda-keymap
6075 'help-echo
6076 (format "mouse-2 or RET jump to org file %s"
6077 (abbreviate-file-name buffer-file-name))))
6078 (regexp (concat
6079 "\\<" org-closed-string " *\\["
6080 (regexp-quote
6081 (substring
6082 (format-time-string
6083 (car org-time-stamp-formats)
6084 (apply 'encode-time ; DATE bound by calendar
6085 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6086 1 11))))
6087 marker hdmarker priority category tags
6088 ee txt timestr)
6089 (goto-char (point-min))
6090 (while (re-search-forward regexp nil t)
6091 (if (not (save-match-data (org-at-date-range-p)))
6092 (progn
6093 (setq marker (org-agenda-new-marker (match-beginning 0))
6094 category (org-get-category (match-beginning 0))
6095 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6096 ;; donep (org-entry-is-done-p)
6097 )
6098 (if (string-match "\\]" timestr)
6099 ;; substring should only run to end of time stamp
6100 (setq timestr (substring timestr 0 (match-end 0))))
6101 (save-excursion
6102 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6103 (progn
6104 (goto-char (match-end 1))
6105 (setq hdmarker (org-agenda-new-marker)
6106 tags (org-get-tags-at))
6107 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6108 (setq txt (org-format-agenda-item
6109 "Closed: "
6110 (match-string 1) category tags timestr)))
6111 (setq txt org-agenda-no-heading-message))
6112 (setq priority 100000)
6113 (org-add-props txt props
6114 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
6115 'priority priority 'category category
6116 'undone-face 'org-warning 'done-face 'org-done)
6117 (push txt ee))
6118 (outline-next-heading))))
6119 (nreverse ee)))
6120
6121 (defun org-agenda-get-deadlines ()
6122 "Return the deadline information for agenda display."
6123 (let* ((wdays org-deadline-warning-days)
6124 (props (list 'mouse-face 'highlight
6125 'org-not-done-regexp org-not-done-regexp
6126 'keymap org-agenda-keymap
6127 'help-echo
6128 (format "mouse-2 or RET jump to org file %s"
6129 (abbreviate-file-name buffer-file-name))))
6130 (regexp org-deadline-time-regexp)
6131 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6132 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6133 d2 diff pos pos1 category tags
6134 ee txt head)
6135 (goto-char (point-min))
6136 (while (re-search-forward regexp nil t)
6137 (setq pos (1- (match-beginning 1))
6138 d2 (time-to-days
6139 (org-time-string-to-time (match-string 1)))
6140 diff (- d2 d1))
6141 ;; When to show a deadline in the calendar:
6142 ;; If the expiration is within wdays warning time.
6143 ;; Past-due deadlines are only shown on the current date
6144 (if (and (< diff wdays) todayp (not (= diff 0)))
6145 (save-excursion
6146 (setq category (org-get-category))
6147 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6148 (progn
6149 (goto-char (match-end 0))
6150 (setq pos1 (match-end 1))
6151 (setq tags (org-get-tags-at pos1))
6152 (setq head (buffer-substring-no-properties
6153 (point)
6154 (progn (skip-chars-forward "^\r\n")
6155 (point))))
6156 (if (string-match org-looking-at-done-regexp head)
6157 (setq txt nil)
6158 (setq txt (org-format-agenda-item
6159 (format "In %3d d.: " diff) head category tags))))
6160 (setq txt org-agenda-no-heading-message))
6161 (when txt
6162 (org-add-props txt props
6163 'org-marker (org-agenda-new-marker pos)
6164 'org-hd-marker (org-agenda-new-marker pos1)
6165 'priority (+ (- 10 diff) (org-get-priority txt))
6166 'category category
6167 'face (cond ((<= diff 0) 'org-warning)
6168 ((<= diff 5) 'org-scheduled-previously)
6169 (t nil))
6170 'undone-face (cond
6171 ((<= diff 0) 'org-warning)
6172 ((<= diff 5) 'org-scheduled-previously)
6173 (t nil))
6174 'done-face 'org-done)
6175 (push txt ee)))))
6176 ee))
6177
6178 (defun org-agenda-get-scheduled ()
6179 "Return the scheduled information for agenda display."
6180 (let* ((props (list 'face 'org-scheduled-previously
6181 'org-not-done-regexp org-not-done-regexp
6182 'undone-face 'org-scheduled-previously
6183 'done-face 'org-done
6184 'mouse-face 'highlight
6185 'keymap org-agenda-keymap
6186 'help-echo
6187 (format "mouse-2 or RET jump to org file %s"
6188 (abbreviate-file-name buffer-file-name))))
6189 (regexp org-scheduled-time-regexp)
6190 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6191 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6192 d2 diff pos pos1 category tags
6193 ee txt head)
6194 (goto-char (point-min))
6195 (while (re-search-forward regexp nil t)
6196 (setq pos (1- (match-beginning 1))
6197 d2 (time-to-days
6198 (org-time-string-to-time (match-string 1)))
6199 diff (- d2 d1))
6200 ;; When to show a scheduled item in the calendar:
6201 ;; If it is on or past the date.
6202 (if (and (< diff 0) todayp)
6203 (save-excursion
6204 (setq category (org-get-category))
6205 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6206 (progn
6207 (goto-char (match-end 0))
6208 (setq pos1 (match-end 1))
6209 (setq tags (org-get-tags-at))
6210 (setq head (buffer-substring-no-properties
6211 (point)
6212 (progn (skip-chars-forward "^\r\n") (point))))
6213 (if (string-match org-looking-at-done-regexp head)
6214 (setq txt nil)
6215 (setq txt (org-format-agenda-item
6216 (format "Sched.%2dx: " (- 1 diff)) head
6217 category tags))))
6218 (setq txt org-agenda-no-heading-message))
6219 (when txt
6220 (org-add-props txt props
6221 'org-marker (org-agenda-new-marker pos)
6222 'org-hd-marker (org-agenda-new-marker pos1)
6223 'priority (+ (- 5 diff) (org-get-priority txt))
6224 'category category)
6225 (push txt ee)))))
6226 ee))
6227
6228 (defun org-agenda-get-blocks ()
6229 "Return the date-range information for agenda display."
6230 (let* ((props (list 'face nil
6231 'org-not-done-regexp org-not-done-regexp
6232 'mouse-face 'highlight
6233 'keymap org-agenda-keymap
6234 'help-echo
6235 (format "mouse-2 or RET jump to org file %s"
6236 (abbreviate-file-name buffer-file-name))))
6237 (regexp org-tr-regexp)
6238 (d0 (calendar-absolute-from-gregorian date))
6239 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
6240 (goto-char (point-min))
6241 (while (re-search-forward regexp nil t)
6242 (setq timestr (match-string 0)
6243 s1 (match-string 1)
6244 s2 (match-string 2)
6245 d1 (time-to-days (org-time-string-to-time s1))
6246 d2 (time-to-days (org-time-string-to-time s2)))
6247 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
6248 ;; Only allow days between the limits, because the normal
6249 ;; date stamps will catch the limits.
6250 (save-excursion
6251 (setq marker (org-agenda-new-marker (point)))
6252 (setq category (org-get-category))
6253 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6254 (progn
6255 (setq hdmarker (org-agenda-new-marker (match-end 1)))
6256 (goto-char (match-end 1))
6257 (setq tags (org-get-tags-at))
6258 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6259 (setq txt (org-format-agenda-item
6260 (format (if (= d1 d2) "" "(%d/%d): ")
6261 (1+ (- d0 d1)) (1+ (- d2 d1)))
6262 (match-string 1) category tags
6263 (if (= d0 d1) timestr))))
6264 (setq txt org-agenda-no-heading-message))
6265 (org-add-props txt props
6266 'org-marker marker 'org-hd-marker hdmarker
6267 'priority (org-get-priority txt) 'category category)
6268 (push txt ee)))
6269 (outline-next-heading))
6270 ;; Sort the entries by expiration date.
6271 (nreverse ee)))
6272
6273 (defconst org-plain-time-of-day-regexp
6274 (concat
6275 "\\(\\<[012]?[0-9]"
6276 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6277 "\\(--?"
6278 "\\(\\<[012]?[0-9]"
6279 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6280 "\\)?")
6281 "Regular expression to match a plain time or time range.
6282 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
6283 groups carry important information:
6284 0 the full match
6285 1 the first time, range or not
6286 8 the second time, if it is a range.")
6287
6288 (defconst org-stamp-time-of-day-regexp
6289 (concat
6290 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
6291 "\\([012][0-9]:[0-5][0-9]\\)>"
6292 "\\(--?"
6293 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
6294 "Regular expression to match a timestamp time or time range.
6295 After a match, the following groups carry important information:
6296 0 the full match
6297 1 date plus weekday, for backreferencing to make sure both times on same day
6298 2 the first time, range or not
6299 4 the second time, if it is a range.")
6300
6301 (defvar org-prefix-has-time nil
6302 "A flag, set by `org-compile-prefix-format'.
6303 The flag is set if the currently compiled format contains a `%t'.")
6304 (defvar org-prefix-has-tag nil
6305 "A flag, set by `org-compile-prefix-format'.
6306 The flag is set if the currently compiled format contains a `%T'.")
6307
6308 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
6309 "Format TXT to be inserted into the agenda buffer.
6310 In particular, it adds the prefix and corresponding text properties. EXTRA
6311 must be a string and replaces the `%s' specifier in the prefix format.
6312 CATEGORY (string, symbol or nil) may be used to overrule the default
6313 category taken from local variable or file name. It will replace the `%c'
6314 specifier in the format. DOTIME, when non-nil, indicates that a
6315 time-of-day should be extracted from TXT for sorting of this entry, and for
6316 the `%t' specifier in the format. When DOTIME is a string, this string is
6317 searched for a time before TXT is. NOPREFIX is a flag and indicates that
6318 only the correctly processes TXT should be returned - this is used by
6319 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
6320 (save-match-data
6321 ;; Diary entries sometimes have extra whitespace at the beginning
6322 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
6323 (let* ((category (or category
6324 org-category
6325 (if buffer-file-name
6326 (file-name-sans-extension
6327 (file-name-nondirectory buffer-file-name))
6328 "")))
6329 (tag (if tags (nth (1- (length tags)) tags) ""))
6330 time ;; needed for the eval of the prefix format
6331 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
6332 (time-of-day (and dotime (org-get-time-of-day ts)))
6333 stamp plain s0 s1 s2 rtn)
6334 (when (and dotime time-of-day org-prefix-has-time)
6335 ;; Extract starting and ending time and move them to prefix
6336 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
6337 (setq plain (string-match org-plain-time-of-day-regexp ts)))
6338 (setq s0 (match-string 0 ts)
6339 s1 (match-string (if plain 1 2) ts)
6340 s2 (match-string (if plain 8 4) ts))
6341
6342 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
6343 ;; them, we might want to remove them there to avoid duplication.
6344 ;; The user can turn this off with a variable.
6345 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
6346 (string-match (concat (regexp-quote s0) " *") txt)
6347 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
6348 (= (match-beginning 0) 0)
6349 t))
6350 (setq txt (replace-match "" nil nil txt))))
6351 ;; Normalize the time(s) to 24 hour
6352 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
6353 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
6354
6355 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
6356 (and org-agenda-remove-tags-when-in-prefix
6357 org-prefix-has-tag))
6358 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
6359 (setq txt (replace-match "" t t txt)))
6360
6361 ;; Create the final string
6362 (if noprefix
6363 (setq rtn txt)
6364 ;; Prepare the variables needed in the eval of the compiled format
6365 (setq time (cond (s2 (concat s1 "-" s2))
6366 (s1 (concat s1 "......"))
6367 (t ""))
6368 extra (or extra "")
6369 category (if (symbolp category) (symbol-name category) category))
6370 ;; Evaluate the compiled format
6371 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
6372
6373 ;; And finally add the text properties
6374 (org-add-props rtn nil
6375 'category (downcase category) 'tags tags
6376 'prefix-length (- (length rtn) (length txt))
6377 'time-of-day time-of-day
6378 'dotime dotime))))
6379
6380 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
6381 (catch 'exit
6382 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
6383 ((and todayp (member 'today (car org-agenda-time-grid))))
6384 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
6385 ((member 'weekly (car org-agenda-time-grid)))
6386 (t (throw 'exit list)))
6387 (let* ((have (delq nil (mapcar
6388 (lambda (x) (get-text-property 1 'time-of-day x))
6389 list)))
6390 (string (nth 1 org-agenda-time-grid))
6391 (gridtimes (nth 2 org-agenda-time-grid))
6392 (req (car org-agenda-time-grid))
6393 (remove (member 'remove-match req))
6394 new time)
6395 (if (and (member 'require-timed req) (not have))
6396 ;; don't show empty grid
6397 (throw 'exit list))
6398 (while (setq time (pop gridtimes))
6399 (unless (and remove (member time have))
6400 (setq time (int-to-string time))
6401 (push (org-format-agenda-item
6402 nil string "" nil
6403 (concat (substring time 0 -2) ":" (substring time -2)))
6404 new)
6405 (put-text-property
6406 1 (length (car new)) 'face 'org-time-grid (car new))))
6407 (if (member 'time-up org-agenda-sorting-strategy)
6408 (append new list)
6409 (append list new)))))
6410
6411 (defun org-compile-prefix-format (format)
6412 "Compile the prefix format into a Lisp form that can be evaluated.
6413 The resulting form is returned and stored in the variable
6414 `org-prefix-format-compiled'."
6415 (setq org-prefix-has-time nil org-prefix-has-tag nil)
6416 (let ((start 0) varform vars var (s format)e c f opt)
6417 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
6418 s start)
6419 (setq var (cdr (assoc (match-string 4 s)
6420 '(("c" . category) ("t" . time) ("s" . extra)
6421 ("T" . tag))))
6422 c (or (match-string 3 s) "")
6423 opt (match-beginning 1)
6424 start (1+ (match-beginning 0)))
6425 (if (equal var 'time) (setq org-prefix-has-time t))
6426 (if (equal var 'tag) (setq org-prefix-has-tag t))
6427 (setq f (concat "%" (match-string 2 s) "s"))
6428 (if opt
6429 (setq varform
6430 `(if (equal "" ,var)
6431 ""
6432 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6433 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6434 (setq s (replace-match "%s" t nil s))
6435 (push varform vars))
6436 (setq vars (nreverse vars))
6437 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6438
6439 (defun org-get-time-of-day (s &optional string)
6440 "Check string S for a time of day.
6441 If found, return it as a military time number between 0 and 2400.
6442 If not found, return nil.
6443 The optional STRING argument forces conversion into a 5 character wide string
6444 HH:MM."
6445 (save-match-data
6446 (when
6447 (or
6448 (string-match
6449 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6450 (string-match
6451 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6452 (let* ((t0 (+ (* 100
6453 (+ (string-to-number (match-string 1 s))
6454 (if (and (match-beginning 4)
6455 (equal (downcase (match-string 4 s)) "pm"))
6456 12 0)))
6457 (if (match-beginning 3)
6458 (string-to-number (match-string 3 s))
6459 0)))
6460 (t1 (concat " "
6461 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6462 (int-to-string t0))))
6463 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6464
6465 (defun org-finalize-agenda-entries (list)
6466 "Sort and concatenate the agenda items."
6467 (setq list (mapcar 'org-agenda-highlight-todo list))
6468 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6469
6470 (defun org-agenda-highlight-todo (x)
6471 (let (re)
6472 (if (eq x 'line)
6473 (save-excursion
6474 (beginning-of-line 1)
6475 (setq re (get-text-property (point) 'org-not-done-regexp))
6476 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
6477 (and (looking-at (concat "[ \t]*" re))
6478 (add-text-properties (match-beginning 0) (match-end 0)
6479 '(face org-todo))))
6480 (setq re (get-text-property 0 'org-not-done-regexp x))
6481 (and re (string-match re x)
6482 (add-text-properties (match-beginning 0) (match-end 0)
6483 '(face org-todo) x))
6484 x)))
6485
6486 (defsubst org-cmp-priority (a b)
6487 "Compare the priorities of string A and B."
6488 (let ((pa (or (get-text-property 1 'priority a) 0))
6489 (pb (or (get-text-property 1 'priority b) 0)))
6490 (cond ((> pa pb) +1)
6491 ((< pa pb) -1)
6492 (t nil))))
6493
6494 (defsubst org-cmp-category (a b)
6495 "Compare the string values of categories of strings A and B."
6496 (let ((ca (or (get-text-property 1 'category a) ""))
6497 (cb (or (get-text-property 1 'category b) "")))
6498 (cond ((string-lessp ca cb) -1)
6499 ((string-lessp cb ca) +1)
6500 (t nil))))
6501
6502 (defsubst org-cmp-time (a b)
6503 "Compare the time-of-day values of strings A and B."
6504 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6505 (ta (or (get-text-property 1 'time-of-day a) def))
6506 (tb (or (get-text-property 1 'time-of-day b) def)))
6507 (cond ((< ta tb) -1)
6508 ((< tb ta) +1)
6509 (t nil))))
6510
6511 (defun org-entries-lessp (a b)
6512 "Predicate for sorting agenda entries."
6513 ;; The following variables will be used when the form is evaluated.
6514 (let* ((time-up (org-cmp-time a b))
6515 (time-down (if time-up (- time-up) nil))
6516 (priority-up (org-cmp-priority a b))
6517 (priority-down (if priority-up (- priority-up) nil))
6518 (category-up (org-cmp-category a b))
6519 (category-down (if category-up (- category-up) nil))
6520 (category-keep (if category-up +1 nil)))
6521 (cdr (assoc
6522 (eval (cons 'or org-agenda-sorting-strategy))
6523 '((-1 . t) (1 . nil) (nil . nil))))))
6524
6525 (defun org-agenda-show-priority ()
6526 "Show the priority of the current item.
6527 This priority is composed of the main priority given with the [#A] cookies,
6528 and by additional input from the age of a schedules or deadline entry."
6529 (interactive)
6530 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6531 (message "Priority is %d" (if pri pri -1000))))
6532
6533 (defun org-agenda-show-tags ()
6534 "Show the tags applicable to the current item."
6535 (interactive)
6536 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6537 (if tags
6538 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6539 (message "No tags associated with this line"))))
6540
6541 (defun org-agenda-goto (&optional highlight)
6542 "Go to the Org-mode file which contains the item at point."
6543 (interactive)
6544 (let* ((marker (or (get-text-property (point) 'org-marker)
6545 (org-agenda-error)))
6546 (buffer (marker-buffer marker))
6547 (pos (marker-position marker)))
6548 (switch-to-buffer-other-window buffer)
6549 (widen)
6550 (goto-char pos)
6551 (when (eq major-mode 'org-mode)
6552 (org-show-hidden-entry)
6553 (save-excursion
6554 (and (outline-next-heading)
6555 (org-flag-heading nil)))) ; show the next heading
6556 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6557
6558 (defun org-agenda-switch-to ()
6559 "Go to the Org-mode file which contains the item at point."
6560 (interactive)
6561 (let* ((marker (or (get-text-property (point) 'org-marker)
6562 (org-agenda-error)))
6563 (buffer (marker-buffer marker))
6564 (pos (marker-position marker)))
6565 (switch-to-buffer buffer)
6566 (delete-other-windows)
6567 (widen)
6568 (goto-char pos)
6569 (when (eq major-mode 'org-mode)
6570 (org-show-hidden-entry)
6571 (save-excursion
6572 (and (outline-next-heading)
6573 (org-flag-heading nil)))))) ; show the next heading
6574
6575 (defun org-agenda-goto-mouse (ev)
6576 "Go to the Org-mode file which contains the item at the mouse click."
6577 (interactive "e")
6578 (mouse-set-point ev)
6579 (org-agenda-goto))
6580
6581 (defun org-agenda-show ()
6582 "Display the Org-mode file which contains the item at point."
6583 (interactive)
6584 (let ((win (selected-window)))
6585 (org-agenda-goto t)
6586 (select-window win)))
6587
6588 (defun org-agenda-recenter (arg)
6589 "Display the Org-mode file which contains the item at point and recenter."
6590 (interactive "P")
6591 (let ((win (selected-window)))
6592 (org-agenda-goto t)
6593 (recenter arg)
6594 (select-window win)))
6595
6596 (defun org-agenda-show-mouse (ev)
6597 "Display the Org-mode file which contains the item at the mouse click."
6598 (interactive "e")
6599 (mouse-set-point ev)
6600 (org-agenda-show))
6601
6602 (defun org-agenda-check-no-diary ()
6603 "Check if the entry is a diary link and abort if yes."
6604 (if (get-text-property (point) 'org-agenda-diary-link)
6605 (org-agenda-error)))
6606
6607 (defun org-agenda-error ()
6608 (error "Command not allowed in this line"))
6609
6610 (defvar org-last-heading-marker (make-marker)
6611 "Marker pointing to the headline that last changed its TODO state
6612 by a remote command from the agenda.")
6613
6614 (defun org-agenda-todo (&optional arg)
6615 "Cycle TODO state of line at point, also in Org-mode file.
6616 This changes the line at point, all other lines in the agenda referring to
6617 the same tree node, and the headline of the tree node in the Org-mode file."
6618 (interactive "P")
6619 (org-agenda-check-no-diary)
6620 (let* ((col (current-column))
6621 (marker (or (get-text-property (point) 'org-marker)
6622 (org-agenda-error)))
6623 (buffer (marker-buffer marker))
6624 (pos (marker-position marker))
6625 (hdmarker (get-text-property (point) 'org-hd-marker))
6626 (buffer-read-only nil)
6627 newhead)
6628 (with-current-buffer buffer
6629 (widen)
6630 (goto-char pos)
6631 (org-show-hidden-entry)
6632 (save-excursion
6633 (and (outline-next-heading)
6634 (org-flag-heading nil))) ; show the next heading
6635 (org-todo arg)
6636 (and (bolp) (forward-char 1))
6637 (setq newhead (org-get-heading))
6638 (save-excursion
6639 (org-back-to-heading)
6640 (move-marker org-last-heading-marker (point))))
6641 (beginning-of-line 1)
6642 (save-excursion
6643 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6644 (move-to-column col)))
6645
6646 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6647 "Change all lines in the agenda buffer which match HDMARKER.
6648 The new content of the line will be NEWHEAD (as modified by
6649 `org-format-agenda-item'). HDMARKER is checked with
6650 `equal' against all `org-hd-marker' text properties in the file.
6651 If FIXFACE is non-nil, the face of each item is modified acording to
6652 the new TODO state."
6653 (let* (props m pl undone-face done-face finish new dotime cat tags)
6654 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6655 (save-excursion
6656 (goto-char (point-max))
6657 (beginning-of-line 1)
6658 (while (not finish)
6659 (setq finish (bobp))
6660 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6661 (equal m hdmarker))
6662 (setq props (text-properties-at (point))
6663 dotime (get-text-property (point) 'dotime)
6664 cat (get-text-property (point) 'category)
6665 tags (get-text-property (point) 'tags)
6666 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6667 pl (get-text-property (point) 'prefix-length)
6668 undone-face (get-text-property (point) 'undone-face)
6669 done-face (get-text-property (point) 'done-face))
6670 (move-to-column pl)
6671 (if (looking-at ".*")
6672 (progn
6673 (replace-match new t t)
6674 (beginning-of-line 1)
6675 (add-text-properties (point-at-bol) (point-at-eol) props)
6676 (when fixface
6677 (add-text-properties
6678 (point-at-bol) (point-at-eol)
6679 (list 'face
6680 (if org-last-todo-state-is-todo
6681 undone-face done-face)))
6682 (org-agenda-highlight-todo 'line))
6683 (beginning-of-line 1))
6684 (error "Line update did not work")))
6685 (beginning-of-line 0)))))
6686
6687 (defun org-agenda-priority-up ()
6688 "Increase the priority of line at point, also in Org-mode file."
6689 (interactive)
6690 (org-agenda-priority 'up))
6691
6692 (defun org-agenda-priority-down ()
6693 "Decrease the priority of line at point, also in Org-mode file."
6694 (interactive)
6695 (org-agenda-priority 'down))
6696
6697 (defun org-agenda-priority (&optional force-direction)
6698 "Set the priority of line at point, also in Org-mode file.
6699 This changes the line at point, all other lines in the agenda referring to
6700 the same tree node, and the headline of the tree node in the Org-mode file."
6701 (interactive)
6702 (org-agenda-check-no-diary)
6703 (let* ((marker (or (get-text-property (point) 'org-marker)
6704 (org-agenda-error)))
6705 (buffer (marker-buffer marker))
6706 (pos (marker-position marker))
6707 (hdmarker (get-text-property (point) 'org-hd-marker))
6708 (buffer-read-only nil)
6709 newhead)
6710 (with-current-buffer buffer
6711 (widen)
6712 (goto-char pos)
6713 (org-show-hidden-entry)
6714 (save-excursion
6715 (and (outline-next-heading)
6716 (org-flag-heading nil))) ; show the next heading
6717 (funcall 'org-priority force-direction)
6718 (end-of-line 1)
6719 (setq newhead (org-get-heading)))
6720 (org-agenda-change-all-lines newhead hdmarker)
6721 (beginning-of-line 1)))
6722
6723 (defun org-get-tags-at (&optional pos)
6724 "Get a list of all headline targs applicable at POS.
6725 POS defaults to point. If tags are inherited, the list contains
6726 the targets in the same sequence as the headlines appear, i.e.
6727 the tags of the current headline come last."
6728 (interactive)
6729 (let (tags)
6730 (save-excursion
6731 (goto-char (or pos (point)))
6732 (save-match-data
6733 (org-back-to-heading t)
6734 (condition-case nil
6735 (while t
6736 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6737 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6738 (or org-use-tag-inheritance (error ""))
6739 (org-up-heading-all 1))
6740 (error nil))))
6741 (message "%s" tags)
6742 tags))
6743
6744 (defun org-agenda-set-tags ()
6745 "Set tags for the current headline."
6746 (interactive)
6747 (org-agenda-check-no-diary)
6748 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6749 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6750 (org-agenda-error)))
6751 (buffer (marker-buffer hdmarker))
6752 (pos (marker-position hdmarker))
6753 (buffer-read-only nil)
6754 newhead)
6755 (with-current-buffer buffer
6756 (widen)
6757 (goto-char pos)
6758 (org-show-hidden-entry)
6759 (save-excursion
6760 (and (outline-next-heading)
6761 (org-flag-heading nil))) ; show the next heading
6762 (call-interactively 'org-set-tags)
6763 (end-of-line 1)
6764 (setq newhead (org-get-heading)))
6765 (org-agenda-change-all-lines newhead hdmarker)
6766 (beginning-of-line 1)))
6767
6768 (defun org-agenda-date-later (arg &optional what)
6769 "Change the date of this item to one day later."
6770 (interactive "p")
6771 (org-agenda-check-type t 'agenda 'timeline)
6772 (org-agenda-check-no-diary)
6773 (let* ((marker (or (get-text-property (point) 'org-marker)
6774 (org-agenda-error)))
6775 (buffer (marker-buffer marker))
6776 (pos (marker-position marker)))
6777 (with-current-buffer buffer
6778 (widen)
6779 (goto-char pos)
6780 (if (not (org-at-timestamp-p))
6781 (error "Cannot find time stamp"))
6782 (org-timestamp-change arg (or what 'day))
6783 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6784
6785 (defun org-agenda-date-earlier (arg &optional what)
6786 "Change the date of this item to one day earlier."
6787 (interactive "p")
6788 (org-agenda-date-later (- arg) what))
6789
6790 (defun org-agenda-date-prompt (arg)
6791 "Change the date of this item. Date is prompted for, with default today.
6792 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6793 be used to request time specification in the time stamp."
6794 (interactive "P")
6795 (org-agenda-check-type t 'agenda 'timeline)
6796 (org-agenda-check-no-diary)
6797 (let* ((marker (or (get-text-property (point) 'org-marker)
6798 (org-agenda-error)))
6799 (buffer (marker-buffer marker))
6800 (pos (marker-position marker)))
6801 (with-current-buffer buffer
6802 (widen)
6803 (goto-char pos)
6804 (if (not (org-at-timestamp-p))
6805 (error "Cannot find time stamp"))
6806 (org-time-stamp arg)
6807 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6808
6809 (defun org-get-heading ()
6810 "Return the heading of the current entry, without the stars."
6811 (save-excursion
6812 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6813 (if (and (re-search-backward "[\r\n]\\*" nil t)
6814 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6815 (match-string 1)
6816 "")))
6817
6818 (defun org-agenda-diary-entry ()
6819 "Make a diary entry, like the `i' command from the calendar.
6820 All the standard commands work: block, weekly etc."
6821 (interactive)
6822 (org-agenda-check-type t 'agenda 'timeline)
6823 (require 'diary-lib)
6824 (let* ((char (progn
6825 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6826 (read-char-exclusive)))
6827 (cmd (cdr (assoc char
6828 '((?d . insert-diary-entry)
6829 (?w . insert-weekly-diary-entry)
6830 (?m . insert-monthly-diary-entry)
6831 (?y . insert-yearly-diary-entry)
6832 (?a . insert-anniversary-diary-entry)
6833 (?b . insert-block-diary-entry)
6834 (?c . insert-cyclic-diary-entry)))))
6835 (oldf (symbol-function 'calendar-cursor-to-date))
6836 (point (point))
6837 (mark (or (mark t) (point))))
6838 (unless cmd
6839 (error "No command associated with <%c>" char))
6840 (unless (and (get-text-property point 'day)
6841 (or (not (equal ?b char))
6842 (get-text-property mark 'day)))
6843 (error "Don't know which date to use for diary entry"))
6844 ;; We implement this by hacking the `calendar-cursor-to-date' function
6845 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6846 (let ((calendar-mark-ring
6847 (list (calendar-gregorian-from-absolute
6848 (or (get-text-property mark 'day)
6849 (get-text-property point 'day))))))
6850 (unwind-protect
6851 (progn
6852 (fset 'calendar-cursor-to-date
6853 (lambda (&optional error)
6854 (calendar-gregorian-from-absolute
6855 (get-text-property point 'day))))
6856 (call-interactively cmd))
6857 (fset 'calendar-cursor-to-date oldf)))))
6858
6859
6860 (defun org-agenda-execute-calendar-command (cmd)
6861 "Execute a calendar command from the agenda, with the date associated to
6862 the cursor position."
6863 (org-agenda-check-type t 'agenda 'timeline)
6864 (require 'diary-lib)
6865 (unless (get-text-property (point) 'day)
6866 (error "Don't know which date to use for calendar command"))
6867 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6868 (point (point))
6869 (date (calendar-gregorian-from-absolute
6870 (get-text-property point 'day)))
6871 (displayed-day (extract-calendar-day date))
6872 (displayed-month (extract-calendar-month date))
6873 (displayed-year (extract-calendar-year date)))
6874 (unwind-protect
6875 (progn
6876 (fset 'calendar-cursor-to-date
6877 (lambda (&optional error)
6878 (calendar-gregorian-from-absolute
6879 (get-text-property point 'day))))
6880 (call-interactively cmd))
6881 (fset 'calendar-cursor-to-date oldf))))
6882
6883 (defun org-agenda-phases-of-moon ()
6884 "Display the phases of the moon for the 3 months around the cursor date."
6885 (interactive)
6886 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6887
6888 (defun org-agenda-holidays ()
6889 "Display the holidays for the 3 months around the cursor date."
6890 (interactive)
6891 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6892
6893 (defun org-agenda-sunrise-sunset (arg)
6894 "Display sunrise and sunset for the cursor date.
6895 Latitude and longitude can be specified with the variables
6896 `calendar-latitude' and `calendar-longitude'. When called with prefix
6897 argument, latitude and longitude will be prompted for."
6898 (interactive "P")
6899 (let ((calendar-longitude (if arg nil calendar-longitude))
6900 (calendar-latitude (if arg nil calendar-latitude))
6901 (calendar-location-name
6902 (if arg "the given coordinates" calendar-location-name)))
6903 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6904
6905 (defun org-agenda-goto-calendar ()
6906 "Open the Emacs calendar with the date at the cursor."
6907 (interactive)
6908 (org-agenda-check-type t 'agenda 'timeline)
6909 (let* ((day (or (get-text-property (point) 'day)
6910 (error "Don't know which date to open in calendar")))
6911 (date (calendar-gregorian-from-absolute day))
6912 (calendar-move-hook nil)
6913 (view-diary-entries-initially nil))
6914 (calendar)
6915 (calendar-goto-date date)))
6916
6917 (defun org-calendar-goto-agenda ()
6918 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6919 This is a command that has to be installed in `calendar-mode-map'."
6920 (interactive)
6921 (org-agenda-list nil (calendar-absolute-from-gregorian
6922 (calendar-cursor-to-date))
6923 nil t))
6924
6925 (defun org-agenda-convert-date ()
6926 (interactive)
6927 (org-agenda-check-type t 'agenda 'timeline)
6928 (let ((day (get-text-property (point) 'day))
6929 date s)
6930 (unless day
6931 (error "Don't know which date to convert"))
6932 (setq date (calendar-gregorian-from-absolute day))
6933 (setq s (concat
6934 "Gregorian: " (calendar-date-string date) "\n"
6935 "ISO: " (calendar-iso-date-string date) "\n"
6936 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6937 "Julian: " (calendar-julian-date-string date) "\n"
6938 "Astron. JD: " (calendar-astro-date-string date)
6939 " (Julian date number at noon UTC)\n"
6940 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6941 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6942 "French: " (calendar-french-date-string date) "\n"
6943 "Mayan: " (calendar-mayan-date-string date) "\n"
6944 "Coptic: " (calendar-coptic-date-string date) "\n"
6945 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6946 "Persian: " (calendar-persian-date-string date) "\n"
6947 "Chinese: " (calendar-chinese-date-string date) "\n"))
6948 (with-output-to-temp-buffer "*Dates*"
6949 (princ s))
6950 (if (fboundp 'fit-window-to-buffer)
6951 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6952
6953 ;;; Tags
6954
6955 (defun org-scan-tags (action matcher &optional todo-only)
6956 "Scan headline tags with inheritance and produce output ACTION.
6957 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6958 evaluated, testing if a given set of tags qualifies a headline for
6959 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6960 are included in the output."
6961 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6962 (mapconcat 'regexp-quote
6963 (nreverse (cdr (reverse org-todo-keywords)))
6964 "\\|")
6965 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6966 (props (list 'face nil
6967 'done-face 'org-done
6968 'undone-face nil
6969 'mouse-face 'highlight
6970 'keymap org-agenda-keymap
6971 'help-echo
6972 (format "mouse-2 or RET jump to org file %s"
6973 (abbreviate-file-name buffer-file-name))))
6974 lspos
6975 tags tags-list tags-alist (llast 0) rtn level category i txt
6976 todo marker)
6977
6978 (save-excursion
6979 (goto-char (point-min))
6980 (when (eq action 'sparse-tree) (hide-sublevels 1))
6981 (while (re-search-forward re nil t)
6982 (setq todo (if (match-end 1) (match-string 2))
6983 tags (if (match-end 4) (match-string 4)))
6984 (goto-char (setq lspos (1+ (match-beginning 0))))
6985 (setq level (funcall outline-level)
6986 category (org-get-category))
6987 (setq i llast llast level)
6988 ;; remove tag lists from same and sublevels
6989 (while (>= i level)
6990 (when (setq entry (assoc i tags-alist))
6991 (setq tags-alist (delete entry tags-alist)))
6992 (setq i (1- i)))
6993 ;; add the nex tags
6994 (when tags
6995 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6996 tags-alist
6997 (cons (cons level tags) tags-alist)))
6998 ;; compile tags for current headline
6999 (setq tags-list
7000 (if org-use-tag-inheritance
7001 (apply 'append (mapcar 'cdr tags-alist))
7002 tags))
7003 (when (and (or (not todo-only) todo)
7004 (eval matcher))
7005 ;; list this headline
7006 (if (eq action 'sparse-tree)
7007 (progn
7008 (org-show-hierarchy-above))
7009 (setq txt (org-format-agenda-item
7010 ""
7011 (concat
7012 (if org-tags-match-list-sublevels
7013 (make-string (1- level) ?.) "")
7014 (org-get-heading))
7015 category tags-list))
7016 (goto-char lspos)
7017 (setq marker (org-agenda-new-marker))
7018 (org-add-props txt props
7019 'org-marker marker 'org-hd-marker marker 'category category)
7020 (push txt rtn))
7021 ;; if we are to skip sublevels, jump to end of subtree
7022 (point)
7023 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
7024 (nreverse rtn)))
7025
7026 (defun org-tags-sparse-tree (&optional arg match)
7027 "Create a sparse tree according to tags search string MATCH.
7028 MATCH can contain positive and negative selection of tags, like
7029 \"+WORK+URGENT-WITHBOSS\"."
7030 (interactive "P")
7031 (let ((org-show-following-heading nil)
7032 (org-show-hierarchy-above nil))
7033 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
7034
7035 (defun org-make-tags-matcher (match)
7036 "Create the TAGS matcher form for the tags-selecting string MATCH."
7037 (unless match
7038 ;; Get a new match request, with completion
7039 (setq org-last-tags-completion-table
7040 (or (org-get-buffer-tags)
7041 org-last-tags-completion-table))
7042 (setq match (completing-read
7043 "Tags: " 'org-tags-completion-function nil nil nil
7044 'org-tags-history)))
7045 ;; parse the string and create a lisp form
7046 (let ((match0 match) minus tag mm matcher orterms term orlist)
7047 (setq orterms (org-split-string match "|"))
7048 (while (setq term (pop orterms))
7049 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
7050 (setq minus (and (match-end 1)
7051 (equal (match-string 1 term) "-"))
7052 tag (match-string 2 term)
7053 term (substring term (match-end 0))
7054 mm (list 'member (downcase tag) 'tags-list)
7055 mm (if minus (list 'not mm) mm))
7056 (push mm matcher))
7057 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
7058 orlist)
7059 (setq matcher nil))
7060 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
7061 ;; Return the string and lisp forms of the matcher
7062 (cons match0 matcher)))
7063
7064 ;;;###autoload
7065 (defun org-tags-view (&optional todo-only match keep-modes)
7066 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
7067 The prefix arg TODO-ONLY limits the search to TODO entries."
7068 (interactive "P")
7069 (org-agenda-maybe-reset-markers 'force)
7070 (org-compile-prefix-format org-agenda-prefix-format)
7071 (let* ((org-agenda-keep-modes keep-modes)
7072 (org-tags-match-list-sublevels
7073 (if todo-only t org-tags-match-list-sublevels))
7074 (win (selected-window))
7075 (completion-ignore-case t)
7076 rtn rtnall files file pos matcher
7077 buffer)
7078 (setq matcher (org-make-tags-matcher match)
7079 match (car matcher) matcher (cdr matcher))
7080 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
7081 (progn
7082 (delete-other-windows)
7083 (switch-to-buffer-other-window
7084 (get-buffer-create org-agenda-buffer-name))))
7085 (setq buffer-read-only nil)
7086 (erase-buffer)
7087 (org-agenda-mode) (setq buffer-read-only nil)
7088 (set (make-local-variable 'org-agenda-type) 'tags)
7089 (set (make-local-variable 'org-agenda-redo-command)
7090 (list 'org-tags-view (list 'quote todo-only)
7091 (list 'if 'current-prefix-arg nil match) t))
7092 (setq files (org-agenda-files)
7093 rtnall nil)
7094 (while (setq file (pop files))
7095 (catch 'nextfile
7096 (org-check-agenda-file file)
7097 (setq buffer (if (file-exists-p file)
7098 (org-get-agenda-file-buffer file)
7099 (error "No such file %s" file)))
7100 (if (not buffer)
7101 ;; If file does not exist, merror message to agenda
7102 (setq rtn (list
7103 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7104 rtnall (append rtnall rtn))
7105 (with-current-buffer buffer
7106 (unless (eq major-mode 'org-mode)
7107 (error "Agenda file %s is not in `org-mode'" file))
7108 (save-excursion
7109 (save-restriction
7110 (if org-respect-restriction
7111 (if (org-region-active-p)
7112 ;; Respect a region to restrict search
7113 (narrow-to-region (region-beginning) (region-end)))
7114 ;; If we work for the calendar or many files,
7115 ;; get rid of any restriction
7116 (widen))
7117 (setq rtn (org-scan-tags 'agenda matcher todo-only))
7118 (setq rtnall (append rtnall rtn))))))))
7119 (insert "Headlines with TAGS match: ")
7120 (add-text-properties (point-min) (1- (point))
7121 (list 'face 'org-level-3))
7122 (setq pos (point))
7123 (insert match "\n")
7124 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7125 (setq pos (point))
7126 (insert "Press `C-u r' to search again with new search string\n")
7127 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7128 (when rtnall
7129 (insert (mapconcat 'identity rtnall "\n")))
7130 (goto-char (point-min))
7131 (setq buffer-read-only t)
7132 (org-fit-agenda-window)
7133 (if (not org-select-agenda-window) (select-window win))))
7134
7135 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
7136 (defun org-set-tags (&optional arg just-align)
7137 "Set the tags for the current headline.
7138 With prefix ARG, realign all tags in headings in the current buffer."
7139 (interactive)
7140 (let* (;(inherit (org-get-inherited-tags))
7141 (re (concat "^" outline-regexp))
7142 (col (current-column))
7143 (current (org-get-tags))
7144 tags hd empty invis)
7145 (if arg
7146 (save-excursion
7147 (goto-char (point-min))
7148 (while (re-search-forward re nil t)
7149 (org-set-tags nil t))
7150 (message "All tags realigned to column %d" org-tags-column))
7151 (if just-align
7152 (setq tags current)
7153 (setq org-last-tags-completion-table
7154 (or (org-get-buffer-tags)
7155 org-last-tags-completion-table))
7156 (setq tags
7157 (let ((org-add-colon-after-tag-completion t))
7158 (completing-read "Tags: " 'org-tags-completion-function
7159 nil nil current 'org-tags-history)))
7160 (while (string-match "[-+&]+" tags)
7161 (setq tags (replace-match ":" t t tags))))
7162 ;; FIXME: still optimize this by not checking when JUST-ALIGN?
7163 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
7164 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
7165 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
7166 (if (equal current "")
7167 (progn
7168 (end-of-line 1)
7169 (or empty (insert-before-markers " ")))
7170 (beginning-of-line 1)
7171 (setq invis (org-invisible-p))
7172 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
7173 (setq hd (match-string 1))
7174 (delete-region (match-beginning 0) (match-end 0))
7175 (insert-before-markers (org-trim hd) (if empty "" " ")))
7176 (unless (equal tags "")
7177 (move-to-column (max (current-column)
7178 (if (> org-tags-column 0)
7179 org-tags-column
7180 (- (- org-tags-column) (length tags))))
7181 t)
7182 (insert-before-markers tags)
7183 (if (and (not invis) (org-invisible-p))
7184 (outline-flag-region (point-at-bol) (point) nil)))
7185 (move-to-column col))))
7186
7187 (defun org-tags-completion-function (string predicate &optional flag)
7188 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
7189 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
7190 (setq s1 (match-string 1 string)
7191 s2 (match-string 2 string))
7192 (setq s1 "" s2 string))
7193 (cond
7194 ((eq flag nil)
7195 ;; try completion
7196 (setq rtn (try-completion s2 ctable))
7197 (if (stringp rtn)
7198 (concat s1 s2 (substring rtn (length s2))
7199 (if (and org-add-colon-after-tag-completion
7200 (assoc rtn ctable))
7201 ":" "")))
7202 )
7203 ((eq flag t)
7204 ;; all-completions
7205 (all-completions s2 ctable)
7206 )
7207 ((eq flag 'lambda)
7208 ;; exact match?
7209 (assoc s2 ctable)))
7210 ))
7211
7212 (defun org-get-tags ()
7213 "Get the TAGS string in the current headline."
7214 (unless (org-on-heading-p)
7215 (error "Not on a heading"))
7216 (save-excursion
7217 (beginning-of-line 1)
7218 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
7219 (org-match-string-no-properties 1)
7220 "")))
7221
7222 (defun org-get-buffer-tags ()
7223 "Get a table of all tags used in the buffer, for completion."
7224 (let (tags)
7225 (save-excursion
7226 (goto-char (point-min))
7227 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
7228 (mapc (lambda (x) (add-to-list 'tags x))
7229 (org-split-string (org-match-string-no-properties 1) ":"))))
7230 (mapcar 'list tags)))
7231
7232 ;;; Link Stuff
7233
7234 (defun org-find-file-at-mouse (ev)
7235 "Open file link or URL at mouse."
7236 (interactive "e")
7237 (mouse-set-point ev)
7238 (org-open-at-point 'in-emacs))
7239
7240 (defun org-open-at-mouse (ev)
7241 "Open file link or URL at mouse."
7242 (interactive "e")
7243 (mouse-set-point ev)
7244 (org-open-at-point))
7245
7246 (defun org-open-at-point (&optional in-emacs)
7247 "Open link at or after point.
7248 If there is no link at point, this function will search forward up to
7249 the end of the current subtree.
7250 Normally, files will be opened by an appropriate application. If the
7251 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7252 (interactive "P")
7253 (org-remove-occur-highlights nil nil t)
7254 (if (org-at-timestamp-p)
7255 (org-agenda-list nil (time-to-days (org-time-string-to-time
7256 (substring (match-string 1) 0 10)))
7257 1)
7258 (let (type path link line search (pos (point)))
7259 (catch 'match
7260 (save-excursion
7261 (skip-chars-forward "^]\n\r")
7262 (when (and (re-search-backward "\\[\\[" nil t)
7263 (looking-at org-bracket-link-regexp)
7264 (<= (match-beginning 0) pos)
7265 (>= (match-end 0) pos))
7266 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7267 (while (string-match " *\n *" link)
7268 (setq link (replace-match " " t t link)))
7269 (if (string-match org-link-re-with-space2 link)
7270 (setq type (match-string 1 link)
7271 path (match-string 2 link))
7272 (setq type "thisfile"
7273 path link))
7274 (throw 'match t)))
7275
7276 (when (get-text-property (point) 'org-linked-text)
7277 (setq type "thisfile"
7278 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7279 (1+ (point)) (point))
7280 path (buffer-substring
7281 (previous-single-property-change pos 'org-linked-text)
7282 (next-single-property-change pos 'org-linked-text)))
7283 (throw 'match t))
7284
7285 (save-excursion
7286 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
7287 (if (equal (char-before) ?<) (backward-char 1))
7288 (when (or (looking-at org-angle-link-re)
7289 (looking-at org-plain-link-re)
7290 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
7291 (re-search-forward org-plain-link-re (point-at-eol) t))
7292 (<= (match-beginning 0) pos)
7293 (>= (match-end 0) pos)))
7294 (setq type (match-string 1)
7295 path (match-string 2))
7296 (throw 'match t)))
7297 (save-excursion
7298 (skip-chars-backward "^ \t\n\r")
7299 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
7300 (setq type "tags"
7301 path (match-string 1))
7302 (while (string-match ":" path)
7303 (setq path (replace-match "+" t t path)))
7304 (throw 'match t)))
7305 (save-excursion
7306 (skip-chars-backward "a-zA-Z_")
7307 (when (and (memq 'camel org-activate-links)
7308 (looking-at org-camel-regexp))
7309 (setq type "camel" path (match-string 0))
7310 (if (equal (char-before) ?*)
7311 (setq path (concat "*" path))))
7312 (throw 'match t)))
7313 (unless path
7314 (error "No link found"))
7315 ;; Remove any trailing spaces in path
7316 (if (string-match " +\\'" path)
7317 (setq path (replace-match "" t t path)))
7318
7319 (cond
7320
7321 ((member type '("http" "https" "ftp" "mailto" "news"))
7322 (browse-url (concat type ":" path)))
7323
7324 ((string= type "tags")
7325 (org-tags-view in-emacs path))
7326 ((or (string= type "camel")
7327 (string= type "thisfile"))
7328 (org-mark-ring-push)
7329 (org-link-search
7330 path
7331 (cond ((equal in-emacs '(4)) 'occur)
7332 ((equal in-emacs '(16)) 'org-occur)
7333 (t nil))))
7334
7335 ((string= type "file")
7336 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
7337 (setq line (string-to-number (match-string 1 path))
7338 path (substring path 0 (match-beginning 0)))
7339 (if (string-match "::\\(.+\\)\\'" path)
7340 (setq search (match-string 1 path)
7341 path (substring path 0 (match-beginning 0)))))
7342 (org-open-file path in-emacs line search))
7343
7344 ((string= type "news")
7345 (org-follow-gnus-link path))
7346
7347 ((string= type "bbdb")
7348 (org-follow-bbdb-link path))
7349
7350 ((string= type "gnus")
7351 (let (group article)
7352 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7353 (error "Error in Gnus link"))
7354 (setq group (match-string 1 path)
7355 article (match-string 3 path))
7356 (org-follow-gnus-link group article)))
7357
7358 ((string= type "vm")
7359 (let (folder article)
7360 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7361 (error "Error in VM link"))
7362 (setq folder (match-string 1 path)
7363 article (match-string 3 path))
7364 ;; in-emacs is the prefix arg, will be interpreted as read-only
7365 (org-follow-vm-link folder article in-emacs)))
7366
7367 ((string= type "wl")
7368 (let (folder article)
7369 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7370 (error "Error in Wanderlust link"))
7371 (setq folder (match-string 1 path)
7372 article (match-string 3 path))
7373 (org-follow-wl-link folder article)))
7374
7375 ((string= type "mhe")
7376 (let (folder article)
7377 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7378 (error "Error in MHE link"))
7379 (setq folder (match-string 1 path)
7380 article (match-string 3 path))
7381 (org-follow-mhe-link folder article)))
7382
7383 ((string= type "rmail")
7384 (let (folder article)
7385 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7386 (error "Error in RMAIL link"))
7387 (setq folder (match-string 1 path)
7388 article (match-string 3 path))
7389 (org-follow-rmail-link folder article)))
7390
7391 ((string= type "shell")
7392 (let ((cmd path))
7393 (while (string-match "@{" cmd)
7394 (setq cmd (replace-match "<" t t cmd)))
7395 (while (string-match "@}" cmd)
7396 (setq cmd (replace-match ">" t t cmd)))
7397 (if (or (not org-confirm-shell-links)
7398 (funcall org-confirm-shell-links
7399 (format "Execute \"%s\" in shell? "
7400 (org-add-props cmd nil
7401 'face 'org-warning))))
7402 (progn
7403 (message "Executing %s" cmd)
7404 (shell-command cmd))
7405 (error "Abort"))))
7406
7407 (t
7408 (browse-url-at-point))))))
7409
7410 (defun org-link-search (s &optional type)
7411 "Search for a link search option.
7412 When S is a CamelCaseWord, search for a target, or for a sentence containing
7413 the words. If S is surrounded by forward slashes, it is interpreted as a
7414 regular expression. In org-mode files, this will create an `org-occur'
7415 sparse tree. In ordinary files, `occur' will be used to list matches.
7416 If the current buffer is in `dired-mode', grep will be used to search
7417 in all files."
7418 (let ((case-fold-search t)
7419 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7420 (pos (point))
7421 (pre "") (post "")
7422 words re0 re1 re2 re3 re4 re5 re2a reall camel)
7423 (cond ((save-excursion
7424 (goto-char (point-min))
7425 (and
7426 (re-search-forward
7427 (concat "<<" (regexp-quote s0) ">>") nil t)
7428 (setq pos (match-beginning 0))))
7429 ;; There is an exact target for this
7430 (goto-char pos))
7431 ((string-match "^/\\(.*\\)/$" s)
7432 ;; A regular expression
7433 (cond
7434 ((eq major-mode 'org-mode)
7435 (org-occur (match-string 1 s)))
7436 ;;((eq major-mode 'dired-mode)
7437 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7438 (t (org-do-occur (match-string 1 s)))))
7439 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
7440 t)
7441 ;; A camel or a normal search string
7442 (when (equal (string-to-char s) ?*)
7443 ;; Anchor on headlines, post may include tags.
7444 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
7445 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
7446 s (substring s 1)))
7447 (remove-text-properties
7448 0 (length s)
7449 '(face nil mouse-face nil keymap nil fontified nil) s)
7450 ;; Make a series of regular expressions to find a match
7451 (setq words
7452 (if camel
7453 (org-camel-to-words s)
7454 (org-split-string s "[ \n\r\t]+"))
7455 re0 (concat "<<" (regexp-quote s0) ">>")
7456 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
7457 re2a (concat "\\<" (mapconcat 'downcase words "[ \t\r\n]+") "\\>")
7458 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
7459 re1 (concat pre re2 post)
7460 re3 (concat pre re4 post)
7461 re5 (concat pre ".*" re4)
7462 re2 (concat pre re2)
7463 re2a (concat pre re2a)
7464 re4 (concat pre re4)
7465 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7466 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7467 re5 "\\)"
7468 ))
7469 (cond
7470 ((eq type 'org-occur) (org-occur reall))
7471 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7472 (t (goto-char (point-min))
7473 (if (or (org-search-not-link re0 nil t)
7474 (org-search-not-link re1 nil t)
7475 (org-search-not-link re2 nil t)
7476 (org-search-not-link re2a nil t)
7477 (org-search-not-link re3 nil t)
7478 (org-search-not-link re4 nil t)
7479 (org-search-not-link re5 nil t)
7480 )
7481 (goto-char (match-beginning 0))
7482 (goto-char pos)
7483 (error "No match")))))
7484 (t
7485 ;; Normal string-search
7486 (goto-char (point-min))
7487 (if (search-forward s nil t)
7488 (goto-char (match-beginning 0))
7489 (error "No match"))))
7490 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7491
7492 (defun org-search-not-link (&rest args)
7493 "Execute `re-search-forward', but only accept matches that are not a link."
7494 (catch 'exit
7495 (let ((pos (point)) p1)
7496 (while (apply 're-search-forward args)
7497 (setq p1 (point))
7498 (if (not (save-match-data
7499 (and (re-search-backward "\\[\\[" nil t)
7500 (looking-at org-bracket-link-regexp)
7501 (<= (match-beginning 0) p1)
7502 (>= (match-end 0) p1))))
7503 (progn (goto-char (match-end 0))
7504 (throw 'exit (point)))
7505 (goto-char (match-end 0)))))))
7506
7507 (defun org-do-occur (regexp &optional cleanup)
7508 "Call the Emacs command `occur'.
7509 If CLEANUP is non-nil, remove the printout of the regular expression
7510 in the *Occur* buffer. This is useful if the regex is long and not useful
7511 to read."
7512 (occur regexp)
7513 (when cleanup
7514 (let ((cwin (selected-window)) win beg end)
7515 (when (setq win (get-buffer-window "*Occur*"))
7516 (select-window win))
7517 (goto-char (point-min))
7518 (when (re-search-forward "match[a-z]+" nil t)
7519 (setq beg (match-end 0))
7520 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7521 (setq end (1- (match-beginning 0)))))
7522 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7523 (goto-char (point-min))
7524 (select-window cwin))))
7525
7526 (defvar org-mark-ring nil
7527 "Mark ring for positions before jumps in Org-mode.")
7528 (defvar org-mark-ring-last-goto nil
7529 "Last position in the mark ring used to go back.")
7530 ;; Fill and close the ring
7531 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7532 (loop for i from 1 to org-mark-ring-length do
7533 (push (make-marker) org-mark-ring))
7534 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7535 org-mark-ring)
7536
7537 (defun org-mark-ring-push (&optional pos buffer)
7538 "Put the current position or POS into the mark ring and rotate it."
7539 (interactive)
7540 (setq pos (or pos (point)))
7541 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7542 (move-marker (car org-mark-ring)
7543 (or pos (point))
7544 (or buffer (current-buffer)))
7545 (message
7546 (substitute-command-keys
7547 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7548
7549 (defun org-mark-ring-goto (&optional n)
7550 "Jump to the previous position in the mark ring.
7551 With prefix arg N, jump back that many stored positions. When
7552 called several times in succession, walk through the entire ring.
7553 Org-mode commands jumping to a different position in the current file,
7554 or to another Org-mode file, automatically push the old position
7555 onto the ring."
7556 (interactive "p")
7557 (let (p m)
7558 (if (eq last-command this-command)
7559 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7560 (setq p org-mark-ring))
7561 (setq org-mark-ring-last-goto p)
7562 (setq m (car p))
7563 (switch-to-buffer (marker-buffer m))
7564 (goto-char m)
7565 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7566
7567 (defun org-camel-to-words (s)
7568 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7569 (let ((case-fold-search nil)
7570 words)
7571 (while (string-match "[a-z][A-Z]" s)
7572 (push (substring s 0 (1+ (match-beginning 0))) words)
7573 (setq s (substring s (1+ (match-beginning 0)))))
7574 (nreverse (cons s words))))
7575
7576 (defun org-remove-angle-brackets (s)
7577 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7578 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7579 s)
7580 (defun org-add-angle-brackets (s)
7581 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7582 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7583 s)
7584
7585 (defun org-follow-bbdb-link (name)
7586 "Follow a BBDB link to NAME."
7587 (require 'bbdb)
7588 (let ((inhibit-redisplay t)
7589 (bbdb-electric-p nil))
7590 (catch 'exit
7591 ;; Exact match on name
7592 (bbdb-name (concat "\\`" name "\\'") nil)
7593 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7594 ;; Exact match on name
7595 (bbdb-company (concat "\\`" name "\\'") nil)
7596 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7597 ;; Partial match on name
7598 (bbdb-name name nil)
7599 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7600 ;; Partial match on company
7601 (bbdb-company name nil)
7602 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7603 ;; General match including network address and notes
7604 (bbdb name nil)
7605 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7606 (delete-window (get-buffer-window "*BBDB*"))
7607 (error "No matching BBDB record")))))
7608
7609 (defun org-follow-gnus-link (&optional group article)
7610 "Follow a Gnus link to GROUP and ARTICLE."
7611 (require 'gnus)
7612 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7613 (if group (gnus-fetch-group group))
7614 (if article
7615 (or (gnus-summary-goto-article article nil 'force)
7616 (if (fboundp 'gnus-summary-insert-cached-articles)
7617 (progn
7618 (gnus-summary-insert-cached-articles)
7619 (gnus-summary-goto-article article nil 'force))
7620 (message "Message could not be found.")))))
7621
7622 (defun org-follow-vm-link (&optional folder article readonly)
7623 "Follow a VM link to FOLDER and ARTICLE."
7624 (require 'vm)
7625 (setq article (org-add-angle-brackets article))
7626 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7627 ;; ange-ftp or efs or tramp access
7628 (let ((user (or (match-string 1 folder) (user-login-name)))
7629 (host (match-string 2 folder))
7630 (file (match-string 3 folder)))
7631 (cond
7632 ((featurep 'tramp)
7633 ;; use tramp to access the file
7634 (if (featurep 'xemacs)
7635 (setq folder (format "[%s@%s]%s" user host file))
7636 (setq folder (format "/%s@%s:%s" user host file))))
7637 (t
7638 ;; use ange-ftp or efs
7639 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
7640 (setq folder (format "/%s@%s:%s" user host file))))))
7641 (when folder
7642 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7643 (sit-for 0.1)
7644 (when article
7645 (vm-select-folder-buffer)
7646 (widen)
7647 (let ((case-fold-search t))
7648 (goto-char (point-min))
7649 (if (not (re-search-forward
7650 (concat "^" "message-id: *" (regexp-quote article))))
7651 (error "Could not find the specified message in this folder"))
7652 (vm-isearch-update)
7653 (vm-isearch-narrow)
7654 (vm-beginning-of-message)
7655 (vm-summarize)))))
7656
7657 (defun org-follow-wl-link (folder article)
7658 "Follow a Wanderlust link to FOLDER and ARTICLE."
7659 (setq article (org-add-angle-brackets article))
7660 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7661 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7662 (wl-summary-redisplay))
7663
7664 (defun org-follow-rmail-link (folder article)
7665 "Follow an RMAIL link to FOLDER and ARTICLE."
7666 (setq article (org-add-angle-brackets article))
7667 (let (message-number)
7668 (save-excursion
7669 (save-window-excursion
7670 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7671 (setq message-number
7672 (save-restriction
7673 (widen)
7674 (goto-char (point-max))
7675 (if (re-search-backward
7676 (concat "^Message-ID:\\s-+" (regexp-quote
7677 (or article "")))
7678 nil t)
7679 (rmail-what-message))))))
7680 (if message-number
7681 (progn
7682 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7683 (rmail-show-message message-number)
7684 message-number)
7685 (error "Message not found"))))
7686
7687 ;; mh-e integration based on planner-mode
7688 (defun org-mhe-get-message-real-folder ()
7689 "Return the name of the current message real folder, so if you use
7690 sequences, it will now work."
7691 (save-excursion
7692 (let* ((folder
7693 (if (equal major-mode 'mh-folder-mode)
7694 mh-current-folder
7695 ;; Refer to the show buffer
7696 mh-show-folder-buffer))
7697 (end-index
7698 (if (boundp 'mh-index-folder)
7699 (min (length mh-index-folder) (length folder))))
7700 )
7701 ;; a simple test on mh-index-data does not work, because
7702 ;; mh-index-data is always nil in a show buffer.
7703 (if (and (boundp 'mh-index-folder)
7704 (string= mh-index-folder (substring folder 0 end-index)))
7705 (if (equal major-mode 'mh-show-mode)
7706 (save-window-excursion
7707 (when (buffer-live-p (get-buffer folder))
7708 (progn
7709 (pop-to-buffer folder)
7710 (org-mhe-get-message-folder-from-index)
7711 )
7712 ))
7713 (org-mhe-get-message-folder-from-index)
7714 )
7715 folder
7716 )
7717 )))
7718
7719 (defun org-mhe-get-message-folder-from-index ()
7720 "Returns the name of the message folder in a index folder buffer."
7721 (save-excursion
7722 (mh-index-previous-folder)
7723 (re-search-forward "^\\(+.*\\)$" nil t)
7724 (message (match-string 1))))
7725
7726 (defun org-mhe-get-message-folder ()
7727 "Return the name of the current message folder. Be careful if you
7728 use sequences."
7729 (save-excursion
7730 (if (equal major-mode 'mh-folder-mode)
7731 mh-current-folder
7732 ;; Refer to the show buffer
7733 mh-show-folder-buffer)))
7734
7735 (defun org-mhe-get-message-num ()
7736 "Return the number of the current message. Be careful if you
7737 use sequences."
7738 (save-excursion
7739 (if (equal major-mode 'mh-folder-mode)
7740 (mh-get-msg-num nil)
7741 ;; Refer to the show buffer
7742 (mh-show-buffer-message-number))))
7743
7744 (defun org-mhe-get-header (header)
7745 "Return a header of the message in folder mode. This will create a
7746 show buffer for the corresponding message. If you have a more clever
7747 idea..."
7748 (let* ((folder (org-mhe-get-message-folder))
7749 (num (org-mhe-get-message-num))
7750 (buffer (get-buffer-create (concat "show-" folder)))
7751 (header-field))
7752 (with-current-buffer buffer
7753 (mh-display-msg num folder)
7754 (if (equal major-mode 'mh-folder-mode)
7755 (mh-header-display)
7756 (mh-show-header-display))
7757 (set-buffer buffer)
7758 (setq header-field (mh-get-header-field header))
7759 (if (equal major-mode 'mh-folder-mode)
7760 (mh-show)
7761 (mh-show-show))
7762 header-field)))
7763
7764 (defun org-follow-mhe-link (folder article)
7765 "Follow an MHE link to FOLDER and ARTICLE.
7766 If ARTICLE is nil FOLDER is shown. If the configuration variable
7767 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
7768 ARTICLE is searched in all folders. Indexed searches (swish++,
7769 namazu, and others supported by MH-E) will always search in all
7770 folders."
7771 (require 'mh-e)
7772 (require 'mh-search)
7773 (require 'mh-utils)
7774 (mh-find-path)
7775 (if (not article)
7776 (mh-visit-folder (mh-normalize-folder-name folder))
7777 (setq article (org-add-angle-brackets article))
7778 (mh-search-choose)
7779 (if (equal mh-searcher 'pick)
7780 (progn
7781 (mh-search folder (list "--message-id" article))
7782 (when (and org-mhe-search-all-folders
7783 (not (org-mhe-get-message-real-folder)))
7784 (kill-this-buffer)
7785 (mh-search "+" (list "--message-id" article))))
7786 (mh-search "+" article))
7787 (if (org-mhe-get-message-real-folder)
7788 (mh-show-msg 1)
7789 (kill-this-buffer)
7790 (error "Message not found"))))
7791
7792 (defun org-upgrade-old-links (&optional query-description)
7793 "Transfer old <...> style links to new [[...]] style links.
7794 With arg query-description, ask at each match for a description text to use
7795 for this link."
7796 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
7797 (save-excursion
7798 (goto-char (point-min))
7799 (let ((re (concat "\\([^[]\\)<\\("
7800 "\\(" (mapconcat 'identity org-link-types "\\|")
7801 "\\):"
7802 "[^" org-non-link-chars "]+\\)>"))
7803 l1 l2 (cnt 0))
7804 (while (re-search-forward re nil t)
7805 (setq cnt (1+ cnt)
7806 l1 (org-match-string-no-properties 2)
7807 l2 (save-match-data (org-link-escape l1)))
7808 (when query-description (setq l1 (read-string "Desc: " l1)))
7809 (if (equal l1 l2)
7810 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
7811 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
7812 (message "%d matches have beed treated" cnt))))
7813
7814 (defun org-open-file (path &optional in-emacs line search)
7815 "Open the file at PATH.
7816 First, this expands any special file name abbreviations. Then the
7817 configuration variable `org-file-apps' is checked if it contains an
7818 entry for this file type, and if yes, the corresponding command is launched.
7819 If no application is found, Emacs simply visits the file.
7820 With optional argument IN-EMACS, Emacs will visit the file.
7821 Optional LINE specifies a line to go to, optional SEARCH a string to
7822 search for. If LINE or SEARCH is given, the file will always be
7823 opened in Emacs.
7824 If the file does not exist, an error is thrown."
7825 (setq in-emacs (or in-emacs line search))
7826 (let* ((file (if (equal path "")
7827 buffer-file-name
7828 (convert-standard-filename (org-expand-file-name path))))
7829 (dirp (file-directory-p file))
7830 (dfile (downcase file))
7831 (old-buffer (current-buffer))
7832 (old-pos (point))
7833 (old-mode major-mode)
7834 ext cmd apps)
7835 (if (and (not (file-exists-p file))
7836 (not org-open-non-existing-files))
7837 (error "No such file: %s" file))
7838 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7839 (setq ext (match-string 1 dfile))
7840 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7841 (setq ext (match-string 1 dfile))))
7842 (setq apps (append org-file-apps (org-default-apps)))
7843 (if in-emacs
7844 (setq cmd 'emacs)
7845 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7846 (cdr (assoc ext apps))
7847 (cdr (assoc t apps)))))
7848 (when (eq cmd 'mailcap)
7849 (require 'mailcap)
7850 (mailcap-parse-mailcaps)
7851 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7852 (command (mailcap-mime-info mime-type)))
7853 (if (stringp command)
7854 (setq cmd command)
7855 (setq cmd 'emacs))))
7856 (cond
7857 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7858 ;; Normalize use of quote, this can vary.
7859 (if (string-match "['\"]%s['\"]" cmd)
7860 (setq cmd (replace-match "'%s'" t t cmd)))
7861 (setq cmd (format cmd file))
7862 (save-window-excursion
7863 (shell-command (concat cmd " &"))))
7864 ((or (stringp cmd)
7865 (eq cmd 'emacs))
7866 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
7867 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7868 (if line (goto-line line)
7869 (if search (org-link-search search))))
7870 ((consp cmd)
7871 (eval cmd))
7872 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7873 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7874 (or (not (equal old-buffer (current-buffer)))
7875 (not (equal old-pos (point))))
7876 (org-mark-ring-push old-pos old-buffer))))
7877
7878 (defun org-default-apps ()
7879 "Return the default applications for this operating system."
7880 (cond
7881 ((eq system-type 'darwin)
7882 org-file-apps-defaults-macosx)
7883 ((eq system-type 'windows-nt)
7884 org-file-apps-defaults-windowsnt)
7885 (t org-file-apps-defaults-gnu)))
7886
7887 (defun org-expand-file-name (path)
7888 "Replace special path abbreviations and expand the file name."
7889 (expand-file-name path))
7890
7891
7892 (defvar org-insert-link-history nil
7893 "Minibuffer history for links inserted with `org-insert-link'.")
7894
7895 (defvar org-stored-links nil
7896 "Contains the links stored with `org-store-link'.")
7897
7898 ;;;###autoload
7899 (defun org-store-link (arg)
7900 "\\<org-mode-map>Store an org-link to the current location.
7901 This link can later be inserted into an org-buffer with
7902 \\[org-insert-link].
7903 For some link types, a prefix arg is interpreted:
7904 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7905 For file links, arg negates `org-context-in-file-links'."
7906 (interactive "P")
7907 (let (link cpltxt desc txt (pos (point)))
7908 (cond
7909
7910 ((eq major-mode 'bbdb-mode)
7911 (setq cpltxt (concat
7912 "bbdb:"
7913 (or (bbdb-record-name (bbdb-current-record))
7914 (bbdb-record-company (bbdb-current-record))))
7915 link (org-make-link cpltxt)))
7916
7917 ((eq major-mode 'calendar-mode)
7918 (let ((cd (calendar-cursor-to-date)))
7919 (setq link
7920 (format-time-string
7921 (car org-time-stamp-formats)
7922 (apply 'encode-time
7923 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7924 nil nil nil))))))
7925
7926 ((or (eq major-mode 'vm-summary-mode)
7927 (eq major-mode 'vm-presentation-mode))
7928 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7929 (vm-follow-summary-cursor)
7930 (save-excursion
7931 (vm-select-folder-buffer)
7932 (let* ((message (car vm-message-pointer))
7933 (folder buffer-file-name)
7934 (subject (vm-su-subject message))
7935 (author (vm-su-full-name message))
7936 (message-id (vm-su-message-id message)))
7937 (setq message-id (org-remove-angle-brackets message-id))
7938 (setq folder (abbreviate-file-name folder))
7939 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7940 folder)
7941 (setq folder (replace-match "" t t folder)))
7942 (setq cpltxt (concat author " on: " subject))
7943 (setq link (org-make-link "vm:" folder "#" message-id)))))
7944
7945 ((eq major-mode 'wl-summary-mode)
7946 (let* ((msgnum (wl-summary-message-number))
7947 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7948 msgnum 'message-id))
7949 (wl-message-entity (elmo-msgdb-overview-get-entity
7950 msgnum (wl-summary-buffer-msgdb)))
7951 (author (wl-summary-line-from)) ; FIXME: correct?
7952 (subject "???")) ; FIXME:
7953 (setq message-id (org-remove-angle-brackets message-id))
7954 (setq cpltxt (concat author " on: " subject))
7955 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
7956 "#" message-id))))
7957
7958 ((or (equal major-mode 'mh-folder-mode)
7959 (equal major-mode 'mh-show-mode))
7960 (let ((from-header (org-mhe-get-header "From:"))
7961 (to-header (org-mhe-get-header "To:"))
7962 (subject (org-mhe-get-header "Subject:")))
7963 (setq cpltxt (concat from-header " on: " subject))
7964 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
7965 (org-remove-angle-brackets
7966 (org-mhe-get-header "Message-Id:"))))))
7967
7968 ((eq major-mode 'rmail-mode)
7969 (save-excursion
7970 (save-restriction
7971 (rmail-narrow-to-non-pruned-header)
7972 (let ((folder buffer-file-name)
7973 (message-id (mail-fetch-field "message-id"))
7974 (author (mail-fetch-field "from"))
7975 (subject (mail-fetch-field "subject")))
7976 (setq message-id (org-remove-angle-brackets message-id))
7977 (setq cpltxt (concat author " on: " subject))
7978 (setq link (org-make-link "rmail:" folder "#" message-id))))))
7979
7980 ((eq major-mode 'gnus-group-mode)
7981 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7982 (gnus-group-group-name)) ; version
7983 ((fboundp 'gnus-group-name)
7984 (gnus-group-name))
7985 (t "???"))))
7986 (setq cpltxt (concat
7987 (if (org-xor arg org-usenet-links-prefer-google)
7988 "http://groups.google.com/groups?group="
7989 "gnus:")
7990 group)
7991 link (org-make-link cpltxt))))
7992
7993 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7994 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7995 (gnus-summary-beginning-of-article)
7996 (let* ((group (car gnus-article-current))
7997 (article (cdr gnus-article-current))
7998 (header (gnus-summary-article-header article))
7999 (author (mail-header-from header))
8000 (message-id (mail-header-id header))
8001 (date (mail-header-date header))
8002 (subject (gnus-summary-subject-string)))
8003 (setq cpltxt (concat author " on: " subject))
8004 (if (org-xor arg org-usenet-links-prefer-google)
8005 (setq link
8006 (concat
8007 cpltxt "\n "
8008 (format "http://groups.google.com/groups?as_umsgid=%s"
8009 (org-fixup-message-id-for-http message-id))))
8010 (setq link (org-make-link "gnus:" group
8011 "#" (number-to-string article))))))
8012
8013 ((eq major-mode 'w3-mode)
8014 (setq cpltxt (url-view-url t)
8015 link (org-make-link cpltxt)))
8016 ((eq major-mode 'w3m-mode)
8017 (setq cpltxt w3m-current-url
8018 link (org-make-link cpltxt)))
8019
8020 ((eq major-mode 'org-mode)
8021 ;; Just link to current headline
8022 (setq cpltxt (concat "file:"
8023 (abbreviate-file-name buffer-file-name)))
8024 ;; Add a context search string
8025 (when (org-xor org-context-in-file-links arg)
8026 ;; Check if we are on a target
8027 (if (save-excursion
8028 (skip-chars-forward "^>\n\r")
8029 (and (re-search-backward "<<" nil t)
8030 (looking-at "<<\\(.*?\\)>>")
8031 (<= (match-beginning 0) pos)
8032 (>= (match-end 0) pos)))
8033 (setq cpltxt (concat cpltxt "::" (match-string 1)))
8034 (setq txt (cond
8035 ((org-on-heading-p) nil)
8036 ((org-region-active-p)
8037 (buffer-substring (region-beginning) (region-end)))
8038 (t (buffer-substring (point-at-bol) (point-at-eol)))))
8039 (setq cpltxt
8040 (concat cpltxt "::"
8041 (if org-file-link-context-use-camel-case
8042 (org-make-org-heading-camel txt)
8043 (org-make-org-heading-search-string txt)))
8044 desc "NONE")))
8045 (if (string-match "::\\'" cpltxt)
8046 (setq cpltxt (substring cpltxt 0 -2)))
8047 (setq link (org-make-link cpltxt)))
8048
8049 (buffer-file-name
8050 ;; Just link to this file here.
8051 (setq cpltxt (concat "file:"
8052 (abbreviate-file-name buffer-file-name)))
8053 ;; Add a context string
8054 (when (org-xor org-context-in-file-links arg)
8055 (setq txt (if (org-region-active-p)
8056 (buffer-substring (region-beginning) (region-end))
8057 (buffer-substring (point-at-bol) (point-at-eol))))
8058 (setq cpltxt
8059 (concat cpltxt "::"
8060 (if org-file-link-context-use-camel-case
8061 (org-make-org-heading-camel txt)
8062 (org-make-org-heading-search-string txt)))
8063 desc "NONE"))
8064 (setq link (org-make-link cpltxt)))
8065
8066 ((interactive-p)
8067 (error "Cannot link to a buffer which is not visiting a file"))
8068
8069 (t (setq link nil)))
8070
8071 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8072 (setq link (or link cpltxt)
8073 desc (or desc cpltxt))
8074 (if (equal desc "NONE") (setq desc nil))
8075
8076 (if (and (interactive-p) link)
8077 (progn
8078 (setq org-stored-links
8079 (cons (list cpltxt link desc) org-stored-links))
8080 (message "Stored: %s" (or cpltxt link)))
8081 (org-make-link-string link desc))))
8082
8083 (defun org-make-org-heading-search-string (&optional string heading)
8084 "Make search string for STRING or current headline."
8085 (interactive)
8086 (let ((s (or string (org-get-heading))))
8087 (unless (and string (not heading))
8088 ;; We are using a headline, clean up garbage in there.
8089 (if (string-match org-todo-regexp s)
8090 (setq s (replace-match "" t t s)))
8091 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8092 (setq s (replace-match "" t t s)))
8093 (setq s (org-trim s))
8094 (if (string-match (concat "^\\(" org-quote-string "\\|"
8095 org-comment-string "\\)") s)
8096 (setq s (replace-match "" t t s)))
8097 (while (string-match org-ts-regexp s)
8098 (setq s (replace-match "" t t s))))
8099 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8100 (setq s (replace-match " " t t s)))
8101 (or string (setq s (concat "*" s))) ; Add * for headlines
8102 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8103
8104 (defun org-make-org-heading-camel (&optional string heading)
8105 "Make a CamelCase string for STRING or the current headline."
8106 (interactive)
8107 (let ((s (or string (org-get-heading))))
8108 (unless (and string (not heading))
8109 ;; We are using a headline, clean up garbage in there.
8110 (if (string-match org-todo-regexp s)
8111 (setq s (replace-match "" t t s)))
8112 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8113 (setq s (replace-match "" t t s)))
8114 (setq s (org-trim s))
8115 (if (string-match (concat "^\\(" org-quote-string "\\|"
8116 org-comment-string "\\)") s)
8117 (setq s (replace-match "" t t s)))
8118 (while (string-match org-ts-regexp s)
8119 (setq s (replace-match "" t t s))))
8120 (while (string-match "[^a-zA-Z_ \t]+" s)
8121 (setq s (replace-match " " t t s)))
8122 (or string (setq s (concat "*" s))) ; Add * for headlines
8123 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
8124
8125 (defun org-make-link (&rest strings)
8126 "Concatenate STRINGS, format resulting string with `org-link-format'."
8127 (format org-link-format (apply 'concat strings)))
8128
8129 (defun org-make-link-string (link &optional description)
8130 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8131 (if (eq org-link-style 'plain)
8132 (if (equal description link)
8133 link
8134 (concat description "\n" link))
8135 (when (stringp description)
8136 ;; Remove brackets from the description, they are fatal.
8137 (while (string-match "\\[\\|\\]" description)
8138 (setq description (replace-match "" t t description))))
8139 (when (equal (org-link-escape link) description)
8140 ;; No description needed, it is identical
8141 (setq description nil))
8142 (when (and (not description)
8143 (not (equal link (org-link-escape link))))
8144 (setq description link))
8145 (concat "[[" (org-link-escape link) "]"
8146 (if description (concat "[" description "]") "")
8147 "]")))
8148
8149 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
8150 "Association list of escapes for some characters problematic in links.")
8151
8152 (defun org-link-escape (text)
8153 "Escape charaters in TEXT that are problematic for links."
8154 (when text
8155 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
8156 org-link-escape-chars "\\|")))
8157 (while (string-match re text)
8158 (setq text
8159 (replace-match
8160 (cdr (assoc (match-string 0 text) org-link-escape-chars))
8161 t t text)))
8162 text)))
8163
8164 (defun org-link-unescape (text)
8165 "Reverse the action of `org-link-escape'."
8166 (when text
8167 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
8168 org-link-escape-chars "\\|")))
8169 (while (string-match re text)
8170 (setq text
8171 (replace-match
8172 (car (rassoc (match-string 0 text) org-link-escape-chars))
8173 t t text)))
8174 text)))
8175
8176 (defun org-xor (a b)
8177 "Exclusive or."
8178 (if a (not b) b))
8179
8180 (defun org-get-header (header)
8181 "Find a header field in the current buffer."
8182 (save-excursion
8183 (goto-char (point-min))
8184 (let ((case-fold-search t) s)
8185 (cond
8186 ((eq header 'from)
8187 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
8188 (setq s (match-string 1)))
8189 (while (string-match "\"" s)
8190 (setq s (replace-match "" t t s)))
8191 (if (string-match "[<(].*" s)
8192 (setq s (replace-match "" t t s))))
8193 ((eq header 'message-id)
8194 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
8195 (setq s (match-string 1))))
8196 ((eq header 'subject)
8197 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
8198 (setq s (match-string 1)))))
8199 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
8200 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
8201 s)))
8202
8203
8204 (defun org-fixup-message-id-for-http (s)
8205 "Replace special characters in a message id, so it can be used in an http query."
8206 (while (string-match "<" s)
8207 (setq s (replace-match "%3C" t t s)))
8208 (while (string-match ">" s)
8209 (setq s (replace-match "%3E" t t s)))
8210 (while (string-match "@" s)
8211 (setq s (replace-match "%40" t t s)))
8212 s)
8213
8214 (defun org-insert-link (&optional complete-file)
8215 "Insert a link. At the prompt, enter the link.
8216
8217 Completion can be used to select a link previously stored with
8218 `org-store-link'. When the empty string is entered (i.e. if you just
8219 press RET at the prompt), the link defaults to the most recently
8220 stored link. As SPC triggers completion in the minibuffer, you need to
8221 use M-SPC or C-q SPC to force the insertion of a space character.
8222
8223 You will also be prompted for a description, and if one is given, it will
8224 be displayed in the buffer instead of the link.
8225
8226 If there is already a link at point, this command will allow you to edit link
8227 and description parts.
8228
8229 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
8230 selected using completion. The path to the file will be relative to
8231 the current directory if the file is in the current directory or a
8232 subdirectory. Otherwise, the link will be the absolute path as
8233 completed in the minibuffer (i.e. normally ~/path/to/file).
8234
8235 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
8236 is in the current directory or below."
8237 (interactive "P")
8238 (let (link desc entry remove file (pos (point)))
8239 (cond
8240 ((save-excursion
8241 (skip-chars-forward "^]\n\r")
8242 (and (re-search-backward "\\[\\[" nil t)
8243 (looking-at org-bracket-link-regexp)
8244 (<= (match-beginning 0) pos)
8245 (>= (match-end 0) pos)))
8246 ;; We do have a link at point, and we are going to edit it.
8247 (setq remove (list (match-beginning 0) (match-end 0)))
8248 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8249 (setq link (read-string "Link: "
8250 (org-link-unescape
8251 (org-match-string-no-properties 1)))))
8252 (complete-file
8253 ;; Completing read for file names.
8254 (setq file (read-file-name "File: "))
8255 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8256 (pwd1 (file-name-as-directory (abbreviate-file-name
8257 (expand-file-name ".")))))
8258 (cond
8259 ((equal complete-file '(16))
8260 (setq link (org-make-link
8261 "file:"
8262 (abbreviate-file-name (expand-file-name file)))))
8263 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8264 (setq link (org-make-link "file:" (match-string 1 file))))
8265 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8266 (expand-file-name file))
8267 (setq link (org-make-link
8268 "file:" (match-string 1 (expand-file-name file)))))
8269 (t (setq link (org-make-link "file:" file))))))
8270 (t
8271 ;; Read link, with completion for stored links.
8272 (setq link (org-completing-read
8273 "Link: " org-stored-links nil nil nil
8274 org-insert-link-history
8275 (or (car (car org-stored-links)))))
8276 (setq entry (assoc link org-stored-links))
8277 (if (not org-keep-stored-link-after-insertion)
8278 (setq org-stored-links (delq (assoc link org-stored-links)
8279 org-stored-links)))
8280 (setq link (if entry (nth 1 entry) link)
8281 desc (or desc (nth 2 entry)))))
8282
8283 (if (string-match org-plain-link-re link)
8284 ;; URL-like link, normalize the use of angular brackets.
8285 (setq link (org-make-link (org-remove-angle-brackets link))))
8286
8287 ;; Check if we are linking to the current file. If yes, simplify the link.
8288 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
8289 (let* ((path (match-string 1 link))
8290 (case-fold-search nil)
8291 (search (match-string 2 link)))
8292 (when (save-match-data
8293 (equal (file-truename buffer-file-name)
8294 (file-truename path)))
8295 ;; We are linking to this same file, with a search option
8296 (setq link search))))
8297 (setq desc (read-string "Description: " desc))
8298 (unless (string-match "\\S-" desc) (setq desc nil))
8299 (if remove (apply 'delete-region remove))
8300 (insert (org-make-link-string link desc))))
8301
8302 (defun org-completing-read (&rest args)
8303 (let ((minibuffer-local-completion-map
8304 (copy-keymap minibuffer-local-completion-map)))
8305 (define-key minibuffer-local-completion-map " " 'self-insert-command)
8306 (apply 'completing-read args)))
8307
8308 ;;; Hooks for remember.el
8309
8310 (defvar org-finish-function nil)
8311
8312 ;;;###autoload
8313 (defun org-remember-annotation ()
8314 "Return a link to the current location as an annotation for remember.el.
8315 If you are using Org-mode files as target for data storage with
8316 remember.el, then the annotations should include a link compatible with the
8317 conventions in Org-mode. This function returns such a link."
8318 (org-store-link nil))
8319
8320 (defconst org-remember-help
8321 "Select a destination location for the note.
8322 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
8323 RET at beg-of-buf -> Append to file as level 2 headline
8324 RET on headline -> Store as sublevel entry to current headline
8325 <left>/<right> -> before/after current headline, same headings level")
8326
8327 ;;;###autoload
8328 (defun org-remember-apply-template ()
8329 "Initialize *remember* buffer with template, invode `org-mode'.
8330 This function should be placed into `remember-mode-hook' and in fact requires
8331 to be run from that hook to fucntion properly."
8332 (when org-remember-templates
8333 (let* ((entry (if (= (length org-remember-templates) 1)
8334 (cdar org-remember-templates)
8335 (message "Select template: %s"
8336 (mapconcat
8337 (lambda (x) (char-to-string (car x)))
8338 org-remember-templates " "))
8339 (cdr (assoc (read-char-exclusive) org-remember-templates))))
8340 (tpl (if (consp (cdr entry)) (cadr entry) (cdr entry)))
8341 (file (if (consp (cdr entry)) (nth 2 entry)))
8342 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
8343 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
8344 (v-u (concat "[" (substring v-t 1 -1) "]"))
8345 (v-U (concat "[" (substring v-T 1 -1) "]"))
8346 (v-a annotation) ; defined in `remember-mode'
8347 (v-i initial) ; defined in `remember-mode'
8348 (v-n user-full-name)
8349 )
8350 (unless tpl (setq tpl "") (message "No template") (ding))
8351 (insert tpl) (goto-char (point-min))
8352 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
8353 (when (and initial (equal (match-string 0) "%i"))
8354 (save-match-data
8355 (let* ((lead (buffer-substring
8356 (point-at-bol) (match-beginning 0))))
8357 (setq v-i (mapconcat 'identity
8358 (org-split-string initial "\n")
8359 (concat "\n" lead))))))
8360 (replace-match
8361 (or (eval (intern (concat "v-" (match-string 1)))) "")
8362 t t))
8363 (let ((org-startup-folded nil)
8364 (org-startup-with-deadline-check nil))
8365 (org-mode))
8366 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
8367 (set (make-local-variable 'org-default-notes-file) file))
8368 (goto-char (point-min))
8369 (if (re-search-forward "%\\?" nil t) (replace-match ""))
8370 (set (make-local-variable 'org-finish-function) 'remember-buffer))))
8371
8372 ;;;###autoload
8373 (defun org-remember-handler ()
8374 "Store stuff from remember.el into an org file.
8375 First prompts for an org file. If the user just presses return, the value
8376 of `org-default-notes-file' is used.
8377 Then the command offers the headings tree of the selected file in order to
8378 file the text at a specific location.
8379 You can either immediately press RET to get the note appended to the
8380 file, or you can use vertical cursor motion and visibility cycling (TAB) to
8381 find a better place. Then press RET or <left> or <right> in insert the note.
8382
8383 Key Cursor position Note gets inserted
8384 -----------------------------------------------------------------------------
8385 RET buffer-start as level 2 heading at end of file
8386 RET on headline as sublevel of the heading at cursor
8387 RET no heading at cursor position, level taken from context.
8388 Or use prefix arg to specify level manually.
8389 <left> on headline as same level, before current heading
8390 <right> on headline as same level, after current heading
8391
8392 So the fastest way to store the note is to press RET RET to append it to
8393 the default file. This way your current train of thought is not
8394 interrupted, in accordance with the principles of remember.el. But with
8395 little extra effort, you can push it directly to the correct location.
8396
8397 Before being stored away, the function ensures that the text has a
8398 headline, i.e. a first line that starts with a \"*\". If not, a headline
8399 is constructed from the current date and some additional data.
8400
8401 If the variable `org-adapt-indentation' is non-nil, the entire text is
8402 also indented so that it starts in the same column as the headline
8403 \(i.e. after the stars).
8404
8405 See also the variable `org-reverse-note-order'."
8406 (catch 'quit
8407 (let* ((txt (buffer-substring (point-min) (point-max)))
8408 (fastp current-prefix-arg)
8409 (file (if fastp org-default-notes-file (org-get-org-file)))
8410 (visiting (find-buffer-visiting file))
8411 (org-startup-with-deadline-check nil)
8412 (org-startup-folded nil)
8413 (org-startup-align-all-tables nil)
8414 spos level indent reversed)
8415 ;; Modify text so that it becomes a nice subtree which can be inserted
8416 ;; into an org tree.
8417 (let* ((lines (split-string txt "\n"))
8418 first)
8419 ;; remove empty lines at the beginning
8420 (while (and lines (string-match "^[ \t]*\n" (car lines)))
8421 (setq lines (cdr lines)))
8422 (setq first (car lines) lines (cdr lines))
8423 (if (string-match "^\\*+" first)
8424 ;; Is already a headline
8425 (setq indent nil)
8426 ;; We need to add a headline: Use time and first buffer line
8427 (setq lines (cons first lines)
8428 first (concat "* " (current-time-string)
8429 " (" (remember-buffer-desc) ")")
8430 indent " "))
8431 (if (and org-adapt-indentation indent)
8432 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
8433 (setq txt (concat first "\n"
8434 (mapconcat 'identity lines "\n"))))
8435 ;; Find the file
8436 (if (not visiting)
8437 (find-file-noselect file))
8438 (with-current-buffer (get-file-buffer file)
8439 (setq reversed (org-notes-order-reversed-p))
8440 (save-excursion
8441 (save-restriction
8442 (widen)
8443 ;; Ask the User for a location
8444 (setq spos (if fastp 1 (org-get-location
8445 (current-buffer)
8446 org-remember-help)))
8447 (if (not spos) (throw 'quit nil)) ; return nil to show we did
8448 ; not handle this note
8449 (goto-char spos)
8450 (cond ((bobp)
8451 ;; Put it at the start or end, as level 2
8452 (save-restriction
8453 (widen)
8454 (goto-char (if reversed (point-min) (point-max)))
8455 (if (not (bolp)) (newline))
8456 (org-paste-subtree 2 txt)))
8457 ((and (org-on-heading-p nil) (not current-prefix-arg))
8458 ;; Put it below this entry, at the beg/end of the subtree
8459 (org-back-to-heading)
8460 (setq level (funcall outline-level))
8461 (if reversed
8462 (outline-end-of-heading)
8463 (outline-end-of-subtree))
8464 (if (not (bolp)) (newline))
8465 (beginning-of-line 1)
8466 (org-paste-subtree (1+ level) txt))
8467 (t
8468 ;; Put it right there, with automatic level determined by
8469 ;; org-paste-subtree or from prefix arg
8470 (org-paste-subtree current-prefix-arg txt)))
8471 (when remember-save-after-remembering
8472 (save-buffer)
8473 (if (not visiting) (kill-buffer (current-buffer)))))))))
8474 t) ;; return t to indicate that we took care of this note.
8475
8476 (defun org-get-org-file ()
8477 "Read a filename, with default directory `org-directory'."
8478 (let ((default (or org-default-notes-file remember-data-file)))
8479 (read-file-name (format "File name [%s]: " default)
8480 (file-name-as-directory org-directory)
8481 default)))
8482
8483 (defun org-notes-order-reversed-p ()
8484 "Check if the current file should receive notes in reversed order."
8485 (cond
8486 ((not org-reverse-note-order) nil)
8487 ((eq t org-reverse-note-order) t)
8488 ((not (listp org-reverse-note-order)) nil)
8489 (t (catch 'exit
8490 (let ((all org-reverse-note-order)
8491 entry)
8492 (while (setq entry (pop all))
8493 (if (string-match (car entry) buffer-file-name)
8494 (throw 'exit (cdr entry))))
8495 nil)))))
8496
8497 ;;; Tables
8498
8499 ;; Watch out: Here we are talking about two different kind of tables.
8500 ;; Most of the code is for the tables created with the Org-mode table editor.
8501 ;; Sometimes, we talk about tables created and edited with the table.el
8502 ;; Emacs package. We call the former org-type tables, and the latter
8503 ;; table.el-type tables.
8504
8505
8506 (defun org-before-change-function (beg end)
8507 "Every change indicates that a table might need an update."
8508 (setq org-table-may-need-update t))
8509
8510 (defconst org-table-line-regexp "^[ \t]*|"
8511 "Detects an org-type table line.")
8512 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8513 "Detects an org-type table line.")
8514 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8515 "Detects a table line marked for automatic recalculation.")
8516 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8517 "Detects a table line marked for automatic recalculation.")
8518 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8519 "Detects a table line marked for automatic recalculation.")
8520 (defconst org-table-hline-regexp "^[ \t]*|-"
8521 "Detects an org-type table hline.")
8522 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8523 "Detects a table-type table hline.")
8524 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8525 "Detects an org-type or table-type table.")
8526 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8527 "Searching from within a table (any type) this finds the first line
8528 outside the table.")
8529 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8530 "Searching from within a table (any type) this finds the first line
8531 outside the table.")
8532
8533 (defun org-table-create-with-table.el ()
8534 "Use the table.el package to insert a new table.
8535 If there is already a table at point, convert between Org-mode tables
8536 and table.el tables."
8537 (interactive)
8538 (require 'table)
8539 (cond
8540 ((org-at-table.el-p)
8541 (if (y-or-n-p "Convert table to Org-mode table? ")
8542 (org-table-convert)))
8543 ((org-at-table-p)
8544 (if (y-or-n-p "Convert table to table.el table? ")
8545 (org-table-convert)))
8546 (t (call-interactively 'table-insert))))
8547
8548 (defun org-table-create-or-convert-from-region (arg)
8549 "Convert region to table, or create an empty table.
8550 If there is an active region, convert it to a table. If there is no such
8551 region, create an empty table."
8552 (interactive "P")
8553 (if (org-region-active-p)
8554 (org-table-convert-region (region-beginning) (region-end) arg)
8555 (org-table-create arg)))
8556
8557 (defun org-table-create (&optional size)
8558 "Query for a size and insert a table skeleton.
8559 SIZE is a string Columns x Rows like for example \"3x2\"."
8560 (interactive "P")
8561 (unless size
8562 (setq size (read-string
8563 (concat "Table size Columns x Rows [e.g. "
8564 org-table-default-size "]: ")
8565 "" nil org-table-default-size)))
8566
8567 (let* ((pos (point))
8568 (indent (make-string (current-column) ?\ ))
8569 (split (org-split-string size " *x *"))
8570 (rows (string-to-number (nth 1 split)))
8571 (columns (string-to-number (car split)))
8572 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8573 "\n")))
8574 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8575 (point-at-bol) (point)))
8576 (beginning-of-line 1)
8577 (newline))
8578 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8579 (dotimes (i rows) (insert line))
8580 (goto-char pos)
8581 (if (> rows 1)
8582 ;; Insert a hline after the first row.
8583 (progn
8584 (end-of-line 1)
8585 (insert "\n|-")
8586 (goto-char pos)))
8587 (org-table-align)))
8588
8589 (defun org-table-convert-region (beg0 end0 &optional nspace)
8590 "Convert region to a table.
8591 The region goes from BEG0 to END0, but these borders will be moved
8592 slightly, to make sure a beginning of line in the first line is included.
8593 When NSPACE is non-nil, it indicates the minimum number of spaces that
8594 separate columns (default: just one space)."
8595 (interactive "rP")
8596 (let* ((beg (min beg0 end0))
8597 (end (max beg0 end0))
8598 (tabsep t)
8599 re)
8600 (goto-char beg)
8601 (beginning-of-line 1)
8602 (setq beg (move-marker (make-marker) (point)))
8603 (goto-char end)
8604 (if (bolp) (backward-char 1) (end-of-line 1))
8605 (setq end (move-marker (make-marker) (point)))
8606 ;; Lets see if this is tab-separated material. If every nonempty line
8607 ;; contains a tab, we will assume that it is tab-separated material
8608 (if nspace
8609 (setq tabsep nil)
8610 (goto-char beg)
8611 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
8612 (if nspace (setq tabsep nil))
8613 (if tabsep
8614 (setq re "^\\|\t")
8615 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
8616 (max 1 (prefix-numeric-value nspace)))))
8617 (goto-char beg)
8618 (while (re-search-forward re end t)
8619 (replace-match "|" t t))
8620 (goto-char beg)
8621 (insert " ")
8622 (org-table-align)))
8623
8624 (defun org-table-import (file arg)
8625 "Import FILE as a table.
8626 The file is assumed to be tab-separated. Such files can be produced by most
8627 spreadsheet and database applications. If no tabs (at least one per line)
8628 are found, lines will be split on whitespace into fields."
8629 (interactive "f\nP")
8630 (or (bolp) (newline))
8631 (let ((beg (point))
8632 (pm (point-max)))
8633 (insert-file-contents file)
8634 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8635
8636 (defun org-table-export ()
8637 "Export table as a tab-separated file.
8638 Such a file can be imported into a spreadsheet program like Excel."
8639 (interactive)
8640 (let* ((beg (org-table-begin))
8641 (end (org-table-end))
8642 (table (buffer-substring beg end))
8643 (file (read-file-name "Export table to: "))
8644 buf)
8645 (unless (or (not (file-exists-p file))
8646 (y-or-n-p (format "Overwrite file %s? " file)))
8647 (error "Abort"))
8648 (with-current-buffer (find-file-noselect file)
8649 (setq buf (current-buffer))
8650 (erase-buffer)
8651 (fundamental-mode)
8652 (insert table)
8653 (goto-char (point-min))
8654 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8655 (replace-match "" t t)
8656 (end-of-line 1))
8657 (goto-char (point-min))
8658 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8659 (replace-match "" t t)
8660 (goto-char (min (1+ (point)) (point-max))))
8661 (goto-char (point-min))
8662 (while (re-search-forward "^-[-+]*$" nil t)
8663 (replace-match "")
8664 (if (looking-at "\n")
8665 (delete-char 1)))
8666 (goto-char (point-min))
8667 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8668 (replace-match "\t" t t))
8669 (save-buffer))
8670 (kill-buffer buf)))
8671
8672 (defvar org-table-aligned-begin-marker (make-marker)
8673 "Marker at the beginning of the table last aligned.
8674 Used to check if cursor still is in that table, to minimize realignment.")
8675 (defvar org-table-aligned-end-marker (make-marker)
8676 "Marker at the end of the table last aligned.
8677 Used to check if cursor still is in that table, to minimize realignment.")
8678 (defvar org-table-last-alignment nil
8679 "List of flags for flushright alignment, from the last re-alignment.
8680 This is being used to correctly align a single field after TAB or RET.")
8681 (defvar org-table-last-column-widths nil
8682 "List of max width of fields in each column.
8683 This is being used to correctly align a single field after TAB or RET.")
8684
8685 (defvar org-last-recalc-line nil)
8686 (defconst org-narrow-column-arrow "=>"
8687 "Used as display property in narrowed table columns.")
8688
8689 (defun org-table-align ()
8690 "Align the table at point by aligning all vertical bars."
8691 (interactive)
8692 (let* (
8693 ;; Limits of table
8694 (beg (org-table-begin))
8695 (end (org-table-end))
8696 ;; Current cursor position
8697 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8698 (colpos (org-table-current-column))
8699 (winstart (window-start))
8700 text lines (new "") lengths l typenums ty fields maxfields i
8701 column
8702 (indent "") cnt frac
8703 rfmt hfmt
8704 (spaces '(1 . 1))
8705 (sp1 (car spaces))
8706 (sp2 (cdr spaces))
8707 (rfmt1 (concat
8708 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8709 (hfmt1 (concat
8710 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8711 emptystrings xx links narrow fmax fmin f1 len c e)
8712 (untabify beg end)
8713 (remove-text-properties beg end '(org-cwidth t display t))
8714 ;; Check if we have links
8715 (goto-char beg)
8716 (setq links (re-search-forward org-bracket-link-regexp end t))
8717 ;; Make sure the link properties are right FIXME: Can this be optimized????
8718 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8719 ;; Check if we are narrowing any columns
8720 (goto-char beg)
8721 (setq narrow (and org-format-transports-properties-p
8722 (re-search-forward "<[0-9]+>" end t)))
8723 ;; Get the rows
8724 (setq lines (org-split-string
8725 (buffer-substring beg end) "\n"))
8726 ;; Store the indentation of the first line
8727 (if (string-match "^ *" (car lines))
8728 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8729 ;; Mark the hlines by setting the corresponding element to nil
8730 ;; At the same time, we remove trailing space.
8731 (setq lines (mapcar (lambda (l)
8732 (if (string-match "^ *|-" l)
8733 nil
8734 (if (string-match "[ \t]+$" l)
8735 (substring l 0 (match-beginning 0))
8736 l)))
8737 lines))
8738 ;; Get the data fields by splitting the lines.
8739 (setq fields (mapcar
8740 (lambda (l)
8741 (org-split-string l " *| *"))
8742 (delq nil (copy-sequence lines))))
8743 ;; How many fields in the longest line?
8744 (condition-case nil
8745 (setq maxfields (apply 'max (mapcar 'length fields)))
8746 (error
8747 (kill-region beg end)
8748 (org-table-create org-table-default-size)
8749 (error "Empty table - created default table")))
8750 ;; A list of empty string to fill any short rows on output
8751 (setq emptystrings (make-list maxfields ""))
8752 ;; Check for special formatting.
8753 (setq i -1)
8754 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8755 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8756 ;; Check if there is an explicit width specified
8757 (when (and org-table-limit-column-width narrow)
8758 (setq c column fmax nil)
8759 (while c
8760 (setq e (pop c))
8761 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8762 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8763 ;; Find fields that are wider than fmax, and shorten them
8764 (when fmax
8765 (loop for xx in column do
8766 (when (and (stringp xx)
8767 (> (org-string-width xx) fmax))
8768 (org-add-props xx nil
8769 'help-echo
8770 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8771 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8772 (unless (> f1 1)
8773 (error "Cannot narrow field starting with wide link \"%s\""
8774 (match-string 0 xx)))
8775 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8776 (add-text-properties (- f1 2) f1
8777 (list 'display org-narrow-column-arrow)
8778 xx)))))
8779 ;; Get the maximum width for each column
8780 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8781 ;; Get the fraction of numbers, to decide about alignment of the column
8782 (setq cnt 0 frac 0.0)
8783 (loop for x in column do
8784 (if (equal x "")
8785 nil
8786 (setq frac ( / (+ (* frac cnt)
8787 (if (string-match org-table-number-regexp x) 1 0))
8788 (setq cnt (1+ cnt))))))
8789 (push (>= frac org-table-number-fraction) typenums))
8790 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8791
8792 ;; Store the alignment of this table, for later editing of single fields
8793 (setq org-table-last-alignment typenums
8794 org-table-last-column-widths lengths)
8795
8796 ;; With invisible characters, `format' does not get the field width right
8797 ;; So we need to make these fields wide by hand.
8798 (when links
8799 (loop for i from 0 upto (1- maxfields) do
8800 (setq len (nth i lengths))
8801 (loop for j from 0 upto (1- (length fields)) do
8802 (setq c (nthcdr i (car (nthcdr j fields))))
8803 (if (and (stringp (car c))
8804 (string-match org-bracket-link-regexp (car c))
8805 (< (org-string-width (car c)) len))
8806 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8807
8808 ;; Compute the formats needed for output of the table
8809 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8810 (while (setq l (pop lengths))
8811 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8812 (setq rfmt (concat rfmt (format rfmt1 ty l))
8813 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8814 (setq rfmt (concat rfmt "\n")
8815 hfmt (concat (substring hfmt 0 -1) "|\n"))
8816
8817 (setq new (mapconcat
8818 (lambda (l)
8819 (if l (apply 'format rfmt
8820 (append (pop fields) emptystrings))
8821 hfmt))
8822 lines ""))
8823 ;; Replace the old one
8824 (delete-region beg end)
8825 (move-marker end nil)
8826 (move-marker org-table-aligned-begin-marker (point))
8827 (insert new)
8828 (move-marker org-table-aligned-end-marker (point))
8829 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
8830 (goto-char org-table-aligned-begin-marker)
8831 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8832 ;; Try to move to the old location (approximately)
8833 (goto-line linepos)
8834 (set-window-start (selected-window) winstart 'noforce)
8835 (org-table-goto-column colpos)
8836 (setq org-table-may-need-update nil)
8837 ))
8838
8839 (defun org-string-width (s)
8840 "Compute width of string, ignoring invisible characters.
8841 This ignores character with invisibility property `org-link', and also
8842 characters with property `org-cwidth', because these will become invisible
8843 upon the next fontification round."
8844 (let (b)
8845 (when (or (eq t buffer-invisibility-spec)
8846 (assq 'org-link buffer-invisibility-spec))
8847 (while (setq b (text-property-any 0 (length s)
8848 'invisible 'org-link s))
8849 (setq s (concat (substring s 0 b)
8850 (substring s (or (next-single-property-change
8851 b 'invisible s) (length s)))))))
8852 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8853 (setq s (concat (substring s 0 b)
8854 (substring s (or (next-single-property-change
8855 b 'org-cwidth s) (length s))))))
8856 (string-width s)))
8857
8858 (defun org-table-begin (&optional table-type)
8859 "Find the beginning of the table and return its position.
8860 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8861 (save-excursion
8862 (if (not (re-search-backward
8863 (if table-type org-table-any-border-regexp
8864 org-table-border-regexp)
8865 nil t))
8866 (error "Can't find beginning of table")
8867 (goto-char (match-beginning 0))
8868 (beginning-of-line 2)
8869 (point))))
8870
8871 (defun org-table-end (&optional table-type)
8872 "Find the end of the table and return its position.
8873 With argument TABLE-TYPE, go to the end of a table.el-type table."
8874 (save-excursion
8875 (if (not (re-search-forward
8876 (if table-type org-table-any-border-regexp
8877 org-table-border-regexp)
8878 nil t))
8879 (goto-char (point-max))
8880 (goto-char (match-beginning 0)))
8881 (point-marker)))
8882
8883 (defun org-table-justify-field-maybe (&optional new)
8884 "Justify the current field, text to left, number to right.
8885 Optional argument NEW may specify text to replace the current field content."
8886 (cond
8887 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8888 ((org-at-table-hline-p))
8889 ((and (not new)
8890 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8891 (current-buffer)))
8892 (< (point) org-table-aligned-begin-marker)
8893 (>= (point) org-table-aligned-end-marker)))
8894 ;; This is not the same table, force a full re-align
8895 (setq org-table-may-need-update t))
8896 (t ;; realign the current field, based on previous full realign
8897 (let* ((pos (point)) s
8898 (col (org-table-current-column))
8899 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8900 l f n o e)
8901 (when (> col 0)
8902 (skip-chars-backward "^|\n")
8903 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8904 (progn
8905 (setq s (match-string 1)
8906 o (match-string 0)
8907 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8908 e (not (= (match-beginning 2) (match-end 2))))
8909 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8910 l (if e "|" (setq org-table-may-need-update t) ""))
8911 n (format f s))
8912 (if new
8913 (if (<= (length new) l) ;; FIXME: length -> str-width?
8914 (setq n (format f new t t)) ;; FIXME: t t?
8915 (setq n (concat new "|") org-table-may-need-update t)))
8916 (or (equal n o)
8917 (let (org-table-may-need-update)
8918 (replace-match n))))
8919 (setq org-table-may-need-update t))
8920 (goto-char pos))))))
8921
8922 (defun org-table-next-field ()
8923 "Go to the next field in the current table, creating new lines as needed.
8924 Before doing so, re-align the table if necessary."
8925 (interactive)
8926 (org-table-maybe-eval-formula)
8927 (org-table-maybe-recalculate-line)
8928 (if (and org-table-automatic-realign
8929 org-table-may-need-update)
8930 (org-table-align))
8931 (let ((end (org-table-end)))
8932 (if (org-at-table-hline-p)
8933 (end-of-line 1))
8934 (condition-case nil
8935 (progn
8936 (re-search-forward "|" end)
8937 (if (looking-at "[ \t]*$")
8938 (re-search-forward "|" end))
8939 (if (and (looking-at "-")
8940 org-table-tab-jumps-over-hlines
8941 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8942 (goto-char (match-beginning 1)))
8943 (if (looking-at "-")
8944 (progn
8945 (beginning-of-line 0)
8946 (org-table-insert-row 'below))
8947 (if (looking-at " ") (forward-char 1))))
8948 (error
8949 (org-table-insert-row 'below)))))
8950
8951 (defun org-table-previous-field ()
8952 "Go to the previous field in the table.
8953 Before doing so, re-align the table if necessary."
8954 (interactive)
8955 (org-table-justify-field-maybe)
8956 (org-table-maybe-recalculate-line)
8957 (if (and org-table-automatic-realign
8958 org-table-may-need-update)
8959 (org-table-align))
8960 (if (org-at-table-hline-p)
8961 (end-of-line 1))
8962 (re-search-backward "|" (org-table-begin))
8963 (re-search-backward "|" (org-table-begin))
8964 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8965 (re-search-backward "|" (org-table-begin)))
8966 (if (looking-at "| ?")
8967 (goto-char (match-end 0))))
8968
8969 (defun org-table-next-row ()
8970 "Go to the next row (same column) in the current table.
8971 Before doing so, re-align the table if necessary."
8972 (interactive)
8973 (org-table-maybe-eval-formula)
8974 (org-table-maybe-recalculate-line)
8975 (if (or (looking-at "[ \t]*$")
8976 (save-excursion (skip-chars-backward " \t") (bolp)))
8977 (newline)
8978 (if (and org-table-automatic-realign
8979 org-table-may-need-update)
8980 (org-table-align))
8981 (let ((col (org-table-current-column)))
8982 (beginning-of-line 2)
8983 (if (or (not (org-at-table-p))
8984 (org-at-table-hline-p))
8985 (progn
8986 (beginning-of-line 0)
8987 (org-table-insert-row 'below)))
8988 (org-table-goto-column col)
8989 (skip-chars-backward "^|\n\r")
8990 (if (looking-at " ") (forward-char 1)))))
8991
8992 (defun org-table-copy-down (n)
8993 "Copy a field down in the current column.
8994 If the field at the cursor is empty, copy into it the content of the nearest
8995 non-empty field above. With argument N, use the Nth non-empty field.
8996 If the current field is not empty, it is copied down to the next row, and
8997 the cursor is moved with it. Therefore, repeating this command causes the
8998 column to be filled row-by-row.
8999 If the variable `org-table-copy-increment' is non-nil and the field is an
9000 integer, it will be incremented while copying."
9001 (interactive "p")
9002 (let* ((colpos (org-table-current-column))
9003 (field (org-table-get-field))
9004 (non-empty (string-match "[^ \t]" field))
9005 (beg (org-table-begin))
9006 txt)
9007 (org-table-check-inside-data-field)
9008 (if non-empty
9009 (progn
9010 (setq txt (org-trim field))
9011 (org-table-next-row)
9012 (org-table-blank-field))
9013 (save-excursion
9014 (setq txt
9015 (catch 'exit
9016 (while (progn (beginning-of-line 1)
9017 (re-search-backward org-table-dataline-regexp
9018 beg t))
9019 (org-table-goto-column colpos t)
9020 (if (and (looking-at
9021 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9022 (= (setq n (1- n)) 0))
9023 (throw 'exit (match-string 1))))))))
9024 (if txt
9025 (progn
9026 (if (and org-table-copy-increment
9027 (string-match "^[0-9]+$" txt))
9028 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9029 (insert txt)
9030 (org-table-maybe-recalculate-line)
9031 (org-table-align))
9032 (error "No non-empty field found"))))
9033
9034 (defun org-table-check-inside-data-field ()
9035 "Is point inside a table data field?
9036 I.e. not on a hline or before the first or after the last column?
9037 This actually throws an error, so it aborts the current command."
9038 (if (or (not (org-at-table-p))
9039 (= (org-table-current-column) 0)
9040 (org-at-table-hline-p)
9041 (looking-at "[ \t]*$"))
9042 (error "Not in table data field")))
9043
9044 (defvar org-table-clip nil
9045 "Clipboard for table regions.")
9046
9047 (defun org-table-blank-field ()
9048 "Blank the current table field or active region."
9049 (interactive)
9050 (org-table-check-inside-data-field)
9051 (if (and (interactive-p) (org-region-active-p))
9052 (let (org-table-clip)
9053 (org-table-cut-region (region-beginning) (region-end)))
9054 (skip-chars-backward "^|")
9055 (backward-char 1)
9056 (if (looking-at "|[^|\n]+")
9057 (let* ((pos (match-beginning 0))
9058 (match (match-string 0))
9059 (len (org-string-width match)))
9060 (replace-match (concat "|" (make-string (1- len) ?\ )))
9061 (goto-char (+ 2 pos))
9062 (substring match 1)))))
9063
9064 (defun org-table-get-field (&optional n replace)
9065 "Return the value of the field in column N of current row.
9066 N defaults to current field.
9067 If REPLACE is a string, replace field with this value. The return value
9068 is always the old value."
9069 (and n (org-table-goto-column n))
9070 (skip-chars-backward "^|\n")
9071 (backward-char 1)
9072 (if (looking-at "|[^|\r\n]*")
9073 (let* ((pos (match-beginning 0))
9074 (val (buffer-substring (1+ pos) (match-end 0))))
9075 (if replace
9076 (replace-match (concat "|" replace)))
9077 (goto-char (min (point-at-eol) (+ 2 pos)))
9078 val)
9079 (forward-char 1) ""))
9080
9081 (defun org-table-current-column ()
9082 "Find out which column we are in.
9083 When called interactively, column is also displayed in echo area."
9084 (interactive)
9085 (if (interactive-p) (org-table-check-inside-data-field))
9086 (save-excursion
9087 (let ((cnt 0) (pos (point)))
9088 (beginning-of-line 1)
9089 (while (search-forward "|" pos t)
9090 (setq cnt (1+ cnt)))
9091 (if (interactive-p) (message "This is table column %d" cnt))
9092 cnt)))
9093
9094 (defun org-table-goto-column (n &optional on-delim force)
9095 "Move the cursor to the Nth column in the current table line.
9096 With optional argument ON-DELIM, stop with point before the left delimiter
9097 of the field.
9098 If there are less than N fields, just go to after the last delimiter.
9099 However, when FORCE is non-nil, create new columns if necessary."
9100 (interactive "p")
9101 (let ((pos (point-at-eol)))
9102 (beginning-of-line 1)
9103 (when (> n 0)
9104 (while (and (> (setq n (1- n)) -1)
9105 (or (search-forward "|" pos t)
9106 (and force
9107 (progn (end-of-line 1)
9108 (skip-chars-backward "^|")
9109 (insert " | "))))))
9110 ; (backward-char 2) t)))))
9111 (when (and force (not (looking-at ".*|")))
9112 (save-excursion (end-of-line 1) (insert " | ")))
9113 (if on-delim
9114 (backward-char 1)
9115 (if (looking-at " ") (forward-char 1))))))
9116
9117 (defun org-at-table-p (&optional table-type)
9118 "Return t if the cursor is inside an org-type table.
9119 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9120 (if org-enable-table-editor
9121 (save-excursion
9122 (beginning-of-line 1)
9123 (looking-at (if table-type org-table-any-line-regexp
9124 org-table-line-regexp)))
9125 nil))
9126
9127 (defun org-at-table.el-p ()
9128 "Return t if and only if we are at a table.el table."
9129 (and (org-at-table-p 'any)
9130 (save-excursion
9131 (goto-char (org-table-begin 'any))
9132 (looking-at org-table1-hline-regexp))))
9133
9134 (defun org-table-recognize-table.el ()
9135 "If there is a table.el table nearby, recognize it and move into it."
9136 (if org-table-tab-recognizes-table.el
9137 (if (org-at-table.el-p)
9138 (progn
9139 (beginning-of-line 1)
9140 (if (looking-at org-table-dataline-regexp)
9141 nil
9142 (if (looking-at org-table1-hline-regexp)
9143 (progn
9144 (beginning-of-line 2)
9145 (if (looking-at org-table-any-border-regexp)
9146 (beginning-of-line -1)))))
9147 (if (re-search-forward "|" (org-table-end t) t)
9148 (progn
9149 (require 'table)
9150 (if (table--at-cell-p (point))
9151 t
9152 (message "recognizing table.el table...")
9153 (table-recognize-table)
9154 (message "recognizing table.el table...done")))
9155 (error "This should not happen..."))
9156 t)
9157 nil)
9158 nil))
9159
9160 (defun org-at-table-hline-p ()
9161 "Return t if the cursor is inside a hline in a table."
9162 (if org-enable-table-editor
9163 (save-excursion
9164 (beginning-of-line 1)
9165 (looking-at org-table-hline-regexp))
9166 nil))
9167
9168 (defun org-table-insert-column ()
9169 "Insert a new column into the table."
9170 (interactive)
9171 (if (not (org-at-table-p))
9172 (error "Not at a table"))
9173 (org-table-find-dataline)
9174 (let* ((col (max 1 (org-table-current-column)))
9175 (beg (org-table-begin))
9176 (end (org-table-end))
9177 ;; Current cursor position
9178 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9179 (colpos col))
9180 (goto-char beg)
9181 (while (< (point) end)
9182 (if (org-at-table-hline-p)
9183 nil
9184 (org-table-goto-column col t)
9185 (insert "| "))
9186 (beginning-of-line 2))
9187 (move-marker end nil)
9188 (goto-line linepos)
9189 (org-table-goto-column colpos)
9190 (org-table-align)
9191 (org-table-modify-formulas 'insert col)))
9192
9193 (defun org-table-find-dataline ()
9194 "Find a dataline in the current table, which is needed for column commands."
9195 (if (and (org-at-table-p)
9196 (not (org-at-table-hline-p)))
9197 t
9198 (let ((col (current-column))
9199 (end (org-table-end)))
9200 (move-to-column col)
9201 (while (and (< (point) end)
9202 (or (not (= (current-column) col))
9203 (org-at-table-hline-p)))
9204 (beginning-of-line 2)
9205 (move-to-column col))
9206 (if (and (org-at-table-p)
9207 (not (org-at-table-hline-p)))
9208 t
9209 (error
9210 "Please position cursor in a data line for column operations")))))
9211
9212 (defun org-table-delete-column ()
9213 "Delete a column into the table."
9214 (interactive)
9215 (if (not (org-at-table-p))
9216 (error "Not at a table"))
9217 (org-table-find-dataline)
9218 (org-table-check-inside-data-field)
9219 (let* ((col (org-table-current-column))
9220 (beg (org-table-begin))
9221 (end (org-table-end))
9222 ;; Current cursor position
9223 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9224 (colpos col))
9225 (goto-char beg)
9226 (while (< (point) end)
9227 (if (org-at-table-hline-p)
9228 nil
9229 (org-table-goto-column col t)
9230 (and (looking-at "|[^|\n]+|")
9231 (replace-match "|")))
9232 (beginning-of-line 2))
9233 (move-marker end nil)
9234 (goto-line linepos)
9235 (org-table-goto-column colpos)
9236 (org-table-align)
9237 (org-table-modify-formulas 'remove col)))
9238
9239 (defun org-table-move-column-right ()
9240 "Move column to the right."
9241 (interactive)
9242 (org-table-move-column nil))
9243 (defun org-table-move-column-left ()
9244 "Move column to the left."
9245 (interactive)
9246 (org-table-move-column 'left))
9247
9248 (defun org-table-move-column (&optional left)
9249 "Move the current column to the right. With arg LEFT, move to the left."
9250 (interactive "P")
9251 (if (not (org-at-table-p))
9252 (error "Not at a table"))
9253 (org-table-find-dataline)
9254 (org-table-check-inside-data-field)
9255 (let* ((col (org-table-current-column))
9256 (col1 (if left (1- col) col))
9257 (beg (org-table-begin))
9258 (end (org-table-end))
9259 ;; Current cursor position
9260 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9261 (colpos (if left (1- col) (1+ col))))
9262 (if (and left (= col 1))
9263 (error "Cannot move column further left"))
9264 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9265 (error "Cannot move column further right"))
9266 (goto-char beg)
9267 (while (< (point) end)
9268 (if (org-at-table-hline-p)
9269 nil
9270 (org-table-goto-column col1 t)
9271 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9272 (replace-match "|\\2|\\1|")))
9273 (beginning-of-line 2))
9274 (move-marker end nil)
9275 (goto-line linepos)
9276 (org-table-goto-column colpos)
9277 (org-table-align)
9278 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
9279
9280 (defun org-table-move-row-down ()
9281 "Move table row down."
9282 (interactive)
9283 (org-table-move-row nil))
9284 (defun org-table-move-row-up ()
9285 "Move table row up."
9286 (interactive)
9287 (org-table-move-row 'up))
9288
9289 (defun org-table-move-row (&optional up)
9290 "Move the current table line down. With arg UP, move it up."
9291 (interactive "P")
9292 (let ((col (current-column))
9293 (pos (point))
9294 (tonew (if up 0 2))
9295 txt)
9296 (beginning-of-line tonew)
9297 (if (not (org-at-table-p))
9298 (progn
9299 (goto-char pos)
9300 (error "Cannot move row further")))
9301 (goto-char pos)
9302 (beginning-of-line 1)
9303 (setq pos (point))
9304 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9305 (delete-region (point) (1+ (point-at-eol)))
9306 (beginning-of-line tonew)
9307 (insert txt)
9308 (beginning-of-line 0)
9309 (move-to-column col)))
9310
9311 (defun org-table-insert-row (&optional arg)
9312 "Insert a new row above the current line into the table.
9313 With prefix ARG, insert below the current line."
9314 (interactive "P")
9315 (if (not (org-at-table-p))
9316 (error "Not at a table"))
9317 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9318 (new (org-table-clean-line line)))
9319 ;; Fix the first field if necessary
9320 (if (string-match "^[ \t]*| *[#$] *|" line)
9321 (setq new (replace-match (match-string 0 line) t t new)))
9322 (beginning-of-line (if arg 2 1))
9323 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9324 (beginning-of-line 0)
9325 (re-search-forward "| ?" (point-at-eol) t)
9326 (and org-table-may-need-update (org-table-align))))
9327
9328 (defun org-table-insert-hline (&optional arg)
9329 "Insert a horizontal-line below the current line into the table.
9330 With prefix ARG, insert above the current line."
9331 (interactive "P")
9332 (if (not (org-at-table-p))
9333 (error "Not at a table"))
9334 (let ((line (org-table-clean-line
9335 (buffer-substring (point-at-bol) (point-at-eol))))
9336 (col (current-column)))
9337 (while (string-match "|\\( +\\)|" line)
9338 (setq line (replace-match
9339 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9340 ?-) "|") t t line)))
9341 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9342 (beginning-of-line (if arg 1 2))
9343 (insert line "\n")
9344 (beginning-of-line (if arg 1 -1))
9345 (move-to-column col)))
9346
9347 (defun org-table-clean-line (s)
9348 "Convert a table line S into a string with only \"|\" and space.
9349 In particular, this does handle wide and invisible characters."
9350 (if (string-match "^[ \t]*|-" s)
9351 ;; It's a hline, just map the characters
9352 (setq s (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) s))
9353 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9354 (setq s (replace-match
9355 (concat "|" (make-string (org-string-width (match-string 1 s))
9356 ?\ ) "|")
9357 t t s)))
9358 s))
9359
9360 (defun org-table-kill-row ()
9361 "Delete the current row or horizontal line from the table."
9362 (interactive)
9363 (if (not (org-at-table-p))
9364 (error "Not at a table"))
9365 (let ((col (current-column)))
9366 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9367 (if (not (org-at-table-p)) (beginning-of-line 0))
9368 (move-to-column col)))
9369
9370 (defun org-table-sort-lines (beg end numericp)
9371 "Sort table lines in region.
9372 Point and mark define the first and last line to include. Both point and
9373 mark should be in the column that is used for sorting. For example, to
9374 sort according to column 3, put the mark in the first line to sort, in
9375 table column 3. Put point into the last line to be included in the sorting,
9376 also in table column 3. The command will prompt for the sorting method
9377 \(n for numerical, a for alphanumeric)."
9378 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
9379 (setq numericp (string-match "[nN]" numericp))
9380 (org-table-align) ;; Just to be safe
9381 (let* (bcol ecol cmp column lns)
9382 (goto-char beg)
9383 (org-table-check-inside-data-field)
9384 (setq column (org-table-current-column)
9385 beg (move-marker (make-marker) (point-at-bol)))
9386 (goto-char end)
9387 (org-table-check-inside-data-field)
9388 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
9389 (untabify beg end)
9390 (goto-char beg)
9391 (org-table-goto-column column)
9392 (skip-chars-backward "^|")
9393 (setq bcol (current-column))
9394 (org-table-goto-column (1+ column))
9395 (skip-chars-backward "^|")
9396 (setq ecol (1- (current-column)))
9397 (setq cmp (if numericp
9398 (lambda (a b) (< (car a) (car b)))
9399 (lambda (a b) (string< (car a) (car b)))))
9400 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
9401 (split-string (buffer-substring beg end) "\n")))
9402 (if numericp
9403 (setq lns (mapcar (lambda(x)
9404 (cons (string-to-number (car x)) (cdr x)))
9405 lns)))
9406 (delete-region beg end)
9407 (move-marker beg nil)
9408 (move-marker end nil)
9409 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
9410 (message "%d lines sorted %s based on column %d"
9411 (length lns)
9412 (if numericp "numerically" "alphabetically") column)))
9413
9414 (defun org-table-cut-region (beg end)
9415 "Copy region in table to the clipboard and blank all relevant fields."
9416 (interactive "r")
9417 (org-table-copy-region beg end 'cut))
9418
9419 (defun org-table-copy-region (beg end &optional cut)
9420 "Copy rectangular region in table to clipboard.
9421 A special clipboard is used which can only be accessed
9422 with `org-table-paste-rectangle'."
9423 (interactive "rP")
9424 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9425 region cols
9426 (rpl (if cut " " nil)))
9427 (goto-char beg)
9428 (org-table-check-inside-data-field)
9429 (setq l01 (count-lines (point-min) (point))
9430 c01 (org-table-current-column))
9431 (goto-char end)
9432 (org-table-check-inside-data-field)
9433 (setq l02 (count-lines (point-min) (point))
9434 c02 (org-table-current-column))
9435 (setq l1 (min l01 l02) l2 (max l01 l02)
9436 c1 (min c01 c02) c2 (max c01 c02))
9437 (catch 'exit
9438 (while t
9439 (catch 'nextline
9440 (if (> l1 l2) (throw 'exit t))
9441 (goto-line l1)
9442 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9443 (setq cols nil ic1 c1 ic2 c2)
9444 (while (< ic1 (1+ ic2))
9445 (push (org-table-get-field ic1 rpl) cols)
9446 (setq ic1 (1+ ic1)))
9447 (push (nreverse cols) region)
9448 (setq l1 (1+ l1)))))
9449 (setq org-table-clip (nreverse region))
9450 (if cut (org-table-align))
9451 org-table-clip))
9452
9453 (defun org-table-paste-rectangle ()
9454 "Paste a rectangular region into a table.
9455 The upper right corner ends up in the current field. All involved fields
9456 will be overwritten. If the rectangle does not fit into the present table,
9457 the table is enlarged as needed. The process ignores horizontal separator
9458 lines."
9459 (interactive)
9460 (unless (and org-table-clip (listp org-table-clip))
9461 (error "First cut/copy a region to paste!"))
9462 (org-table-check-inside-data-field)
9463 (let* ((clip org-table-clip)
9464 (line (count-lines (point-min) (point)))
9465 (col (org-table-current-column))
9466 (org-enable-table-editor t)
9467 (org-table-automatic-realign nil)
9468 c cols field)
9469 (while (setq cols (pop clip))
9470 (while (org-at-table-hline-p) (beginning-of-line 2))
9471 (if (not (org-at-table-p))
9472 (progn (end-of-line 0) (org-table-next-field)))
9473 (setq c col)
9474 (while (setq field (pop cols))
9475 (org-table-goto-column c nil 'force)
9476 (org-table-get-field nil field)
9477 (setq c (1+ c)))
9478 (beginning-of-line 2))
9479 (goto-line line)
9480 (org-table-goto-column col)
9481 (org-table-align)))
9482
9483 (defun org-table-convert ()
9484 "Convert from `org-mode' table to table.el and back.
9485 Obviously, this only works within limits. When an Org-mode table is
9486 converted to table.el, all horizontal separator lines get lost, because
9487 table.el uses these as cell boundaries and has no notion of horizontal lines.
9488 A table.el table can be converted to an Org-mode table only if it does not
9489 do row or column spanning. Multiline cells will become multiple cells.
9490 Beware, Org-mode does not test if the table can be successfully converted - it
9491 blindly applies a recipe that works for simple tables."
9492 (interactive)
9493 (require 'table)
9494 (if (org-at-table.el-p)
9495 ;; convert to Org-mode table
9496 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9497 (end (move-marker (make-marker) (org-table-end t))))
9498 (table-unrecognize-region beg end)
9499 (goto-char beg)
9500 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9501 (replace-match ""))
9502 (goto-char beg))
9503 (if (org-at-table-p)
9504 ;; convert to table.el table
9505 (let ((beg (move-marker (make-marker) (org-table-begin)))
9506 (end (move-marker (make-marker) (org-table-end))))
9507 ;; first, get rid of all horizontal lines
9508 (goto-char beg)
9509 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9510 (replace-match ""))
9511 ;; insert a hline before first
9512 (goto-char beg)
9513 (org-table-insert-hline 'above)
9514 (beginning-of-line -1)
9515 ;; insert a hline after each line
9516 (while (progn (beginning-of-line 3) (< (point) end))
9517 (org-table-insert-hline))
9518 (goto-char beg)
9519 (setq end (move-marker end (org-table-end)))
9520 ;; replace "+" at beginning and ending of hlines
9521 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9522 (replace-match "\\1+-"))
9523 (goto-char beg)
9524 (while (re-search-forward "-|[ \t]*$" end t)
9525 (replace-match "-+"))
9526 (goto-char beg)))))
9527
9528 (defun org-table-wrap-region (arg)
9529 "Wrap several fields in a column like a paragraph.
9530 This is useful if you'd like to spread the contents of a field over several
9531 lines, in order to keep the table compact.
9532
9533 If there is an active region, and both point and mark are in the same column,
9534 the text in the column is wrapped to minimum width for the given number of
9535 lines. Generally, this makes the table more compact. A prefix ARG may be
9536 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9537 formats the selected text to two lines. If the region was longer than two
9538 lines, the remaining lines remain empty. A negative prefix argument reduces
9539 the current number of lines by that amount. The wrapped text is pasted back
9540 into the table. If you formatted it to more lines than it was before, fields
9541 further down in the table get overwritten - so you might need to make space in
9542 the table first.
9543
9544 If there is no region, the current field is split at the cursor position and
9545 the text fragment to the right of the cursor is prepended to the field one
9546 line down.
9547
9548 If there is no region, but you specify a prefix ARG, the current field gets
9549 blank, and the content is appended to the field above."
9550 (interactive "P")
9551 (org-table-check-inside-data-field)
9552 (if (org-region-active-p)
9553 ;; There is a region: fill as a paragraph
9554 (let ((beg (region-beginning))
9555 nlines)
9556 (org-table-cut-region (region-beginning) (region-end))
9557 (if (> (length (car org-table-clip)) 1)
9558 (error "Region must be limited to single column"))
9559 (setq nlines (if arg
9560 (if (< arg 1)
9561 (+ (length org-table-clip) arg)
9562 arg)
9563 (length org-table-clip)))
9564 (setq org-table-clip
9565 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9566 nil nlines)))
9567 (goto-char beg)
9568 (org-table-paste-rectangle))
9569 ;; No region, split the current field at point
9570 (if arg
9571 ;; combine with field above
9572 (let ((s (org-table-blank-field))
9573 (col (org-table-current-column)))
9574 (beginning-of-line 0)
9575 (while (org-at-table-hline-p) (beginning-of-line 0))
9576 (org-table-goto-column col)
9577 (skip-chars-forward "^|")
9578 (skip-chars-backward " ")
9579 (insert " " (org-trim s))
9580 (org-table-align))
9581 ;; split field
9582 (when (looking-at "\\([^|]+\\)+|")
9583 (let ((s (match-string 1)))
9584 (replace-match " |")
9585 (goto-char (match-beginning 0))
9586 (org-table-next-row)
9587 (insert (org-trim s) " ")
9588 (org-table-align))))))
9589
9590 (defvar org-field-marker nil)
9591
9592 (defun org-table-edit-field (arg)
9593 "Edit table field in a different window.
9594 This is mainly useful for fields that contain hidden parts.
9595 When called with a \\[universal-argument] prefix, just make the full field visible so that
9596 it can be edited in place."
9597 (interactive "P")
9598 (if arg
9599 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9600 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9601 (remove-text-properties b e '(org-cwidth t invisible t
9602 display t intangible t))
9603 (if (and (boundp 'font-lock-mode) font-lock-mode)
9604 (font-lock-fontify-block)))
9605 (let ((pos (move-marker (make-marker) (point)))
9606 (field (org-table-get-field))
9607 (cw (current-window-configuration))
9608 p)
9609 (switch-to-buffer-other-window "*Org tmp*")
9610 (erase-buffer)
9611 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9612 (org-mode)
9613 (goto-char (setq p (point-max)))
9614 (insert (org-trim field))
9615 (remove-text-properties p (point-max)
9616 '(invisible t org-cwidth t display t
9617 intangible t))
9618 (goto-char p)
9619 (set (make-local-variable 'org-finish-function)
9620 'org-table-finish-edit-field)
9621 (set (make-local-variable 'org-window-configuration) cw)
9622 (set (make-local-variable 'org-field-marker) pos)
9623 (message "Edit and finish with C-c C-c"))))
9624
9625 (defun org-table-finish-edit-field ()
9626 "Finish editing a table data field.
9627 Remove all newline characters, insert the result into the table, realign
9628 the table and kill the editing buffer."
9629 (let ((pos org-field-marker)
9630 (cw org-window-configuration)
9631 (cb (current-buffer))
9632 text)
9633 (goto-char (point-min))
9634 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9635 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9636 (replace-match " "))
9637 (setq text (org-trim (buffer-string)))
9638 (set-window-configuration cw)
9639 (kill-buffer cb)
9640 (select-window (get-buffer-window (marker-buffer pos)))
9641 (goto-char pos)
9642 (move-marker pos nil)
9643 (org-table-check-inside-data-field)
9644 (org-table-get-field nil text)
9645 (org-table-align)
9646 (message "New field value inserted")))
9647
9648 (defun org-trim (s)
9649 "Remove whitespace at beginning and end of string."
9650 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
9651 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
9652 s)
9653
9654 (defun org-wrap (string &optional width lines)
9655 "Wrap string to either a number of lines, or a width in characters.
9656 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9657 that costs. If there is a word longer than WIDTH, the text is actually
9658 wrapped to the length of that word.
9659 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9660 many lines, whatever width that takes.
9661 The return value is a list of lines, without newlines at the end."
9662 (let* ((words (org-split-string string "[ \t\n]+"))
9663 (maxword (apply 'max (mapcar 'org-string-width words)))
9664 w ll)
9665 (cond (width
9666 (org-do-wrap words (max maxword width)))
9667 (lines
9668 (setq w maxword)
9669 (setq ll (org-do-wrap words maxword))
9670 (if (<= (length ll) lines)
9671 ll
9672 (setq ll words)
9673 (while (> (length ll) lines)
9674 (setq w (1+ w))
9675 (setq ll (org-do-wrap words w)))
9676 ll))
9677 (t (error "Cannot wrap this")))))
9678
9679
9680 (defun org-do-wrap (words width)
9681 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9682 (let (lines line)
9683 (while words
9684 (setq line (pop words))
9685 (while (and words (< (+ (length line) (length (car words))) width))
9686 (setq line (concat line " " (pop words))))
9687 (setq lines (push line lines)))
9688 (nreverse lines)))
9689
9690 (defun org-split-string (string &optional separators)
9691 "Splits STRING into substrings at SEPARATORS.
9692 No empty strings are returned if there are matches at the beginning
9693 and end of string."
9694 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9695 (start 0)
9696 notfirst
9697 (list nil))
9698 (while (and (string-match rexp string
9699 (if (and notfirst
9700 (= start (match-beginning 0))
9701 (< start (length string)))
9702 (1+ start) start))
9703 (< (match-beginning 0) (length string)))
9704 (setq notfirst t)
9705 (or (eq (match-beginning 0) 0)
9706 (and (eq (match-beginning 0) (match-end 0))
9707 (eq (match-beginning 0) start))
9708 (setq list
9709 (cons (substring string start (match-beginning 0))
9710 list)))
9711 (setq start (match-end 0)))
9712 (or (eq start (length string))
9713 (setq list
9714 (cons (substring string start)
9715 list)))
9716 (nreverse list)))
9717
9718 (defun org-table-map-tables (function)
9719 "Apply FUNCTION to the start of all tables in the buffer."
9720 (save-excursion
9721 (save-restriction
9722 (widen)
9723 (goto-char (point-min))
9724 (while (re-search-forward org-table-any-line-regexp nil t)
9725 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9726 (beginning-of-line 1)
9727 (if (looking-at org-table-line-regexp)
9728 (save-excursion (funcall function)))
9729 (re-search-forward org-table-any-border-regexp nil 1))))
9730 (message "Mapping tables: done"))
9731
9732 (defun org-table-sum (&optional beg end nlast)
9733 "Sum numbers in region of current table column.
9734 The result will be displayed in the echo area, and will be available
9735 as kill to be inserted with \\[yank].
9736
9737 If there is an active region, it is interpreted as a rectangle and all
9738 numbers in that rectangle will be summed. If there is no active
9739 region and point is located in a table column, sum all numbers in that
9740 column.
9741
9742 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9743 numbers are assumed to be times as well (in decimal hours) and the
9744 numbers are added as such.
9745
9746 If NLAST is a number, only the NLAST fields will actually be summed."
9747 (interactive)
9748 (save-excursion
9749 (let (col (timecnt 0) diff h m s org-table-clip)
9750 (cond
9751 ((and beg end)) ; beg and end given explicitly
9752 ((org-region-active-p)
9753 (setq beg (region-beginning) end (region-end)))
9754 (t
9755 (setq col (org-table-current-column))
9756 (goto-char (org-table-begin))
9757 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9758 (error "No table data"))
9759 (org-table-goto-column col)
9760 ;not needed? (skip-chars-backward "^|")
9761 (setq beg (point))
9762 (goto-char (org-table-end))
9763 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9764 (error "No table data"))
9765 (org-table-goto-column col)
9766 ;not needed? (skip-chars-forward "^|")
9767 (setq end (point))))
9768 (let* ((items (apply 'append (org-table-copy-region beg end)))
9769 (items1 (cond ((not nlast) items)
9770 ((>= nlast (length items)) items)
9771 (t (setq items (reverse items))
9772 (setcdr (nthcdr (1- nlast) items) nil)
9773 (nreverse items))))
9774 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9775 items1)))
9776 (res (apply '+ numbers))
9777 (sres (if (= timecnt 0)
9778 (format "%g" res)
9779 (setq diff (* 3600 res)
9780 h (floor (/ diff 3600)) diff (mod diff 3600)
9781 m (floor (/ diff 60)) diff (mod diff 60)
9782 s diff)
9783 (format "%d:%02d:%02d" h m s))))
9784 (kill-new sres)
9785 (if (interactive-p)
9786 (message "%s"
9787 (substitute-command-keys
9788 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9789 (length numbers) sres))))
9790 sres))))
9791
9792 (defun org-table-get-number-for-summing (s)
9793 (let (n)
9794 (if (string-match "^ *|? *" s)
9795 (setq s (replace-match "" nil nil s)))
9796 (if (string-match " *|? *$" s)
9797 (setq s (replace-match "" nil nil s)))
9798 (setq n (string-to-number s))
9799 (cond
9800 ((and (string-match "0" s)
9801 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9802 ((string-match "\\`[ \t]+\\'" s) nil)
9803 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9804 (let ((h (string-to-number (or (match-string 1 s) "0")))
9805 (m (string-to-number (or (match-string 2 s) "0")))
9806 (s (string-to-number (or (match-string 4 s) "0"))))
9807 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9808 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9809 ((equal n 0) nil)
9810 (t n))))
9811
9812 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9813 "Get a calc vector from a column, accorting to descriptor DESC.
9814 Optional arguments TBEG and COL can give the beginning of the table and
9815 the current column, to avoid unnecessary parsing."
9816 (save-excursion
9817 (or tbeg (setq tbeg (org-table-begin)))
9818 (or col (setq col (org-table-current-column)))
9819 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9820 (cond
9821 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9822 (setq n1 (- (match-end 1) (match-beginning 1)))
9823 (if (match-beginning 3)
9824 (setq n2 (- (match-end 2) (match-beginning 3))))
9825 (setq n (if n2 (max n1 n2) n1))
9826 (setq n1 (if n2 (min n1 n2)))
9827 (setq nn n)
9828 (while (and (> nn 0)
9829 (re-search-backward org-table-hline-regexp tbeg t))
9830 (push (org-current-line) hline-list)
9831 (setq nn (1- nn)))
9832 (setq hline-list (nreverse hline-list))
9833 (goto-line (nth (1- n) hline-list))
9834 (when (re-search-forward org-table-dataline-regexp)
9835 (org-table-goto-column col)
9836 (setq beg (point)))
9837 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9838 (when (re-search-backward org-table-dataline-regexp)
9839 (org-table-goto-column col)
9840 (setq end (point)))
9841 (setq l (apply 'append (org-table-copy-region beg end)))
9842 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9843 (if (equal x "") "0" x))
9844 l ",") "]"))
9845 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9846 (setq n1 (string-to-number (match-string 1 desc))
9847 n2 (string-to-number (match-string 2 desc)))
9848 (beginning-of-line 1)
9849 (save-excursion
9850 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9851 (org-table-goto-column col)
9852 (setq beg (point))))
9853 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9854 (org-table-goto-column col)
9855 (setq end (point)))
9856 (setq l (apply 'append (org-table-copy-region beg end)))
9857 (concat "[" (mapconcat
9858 (lambda (x) (setq x (org-trim x))
9859 (if (equal x "") "0" x))
9860 l ",") "]"))
9861 ((string-match "\\([0-9]+\\)" desc)
9862 (beginning-of-line 1)
9863 (when (re-search-backward org-table-dataline-regexp tbeg t
9864 (string-to-number (match-string 0 desc)))
9865 (org-table-goto-column col)
9866 (org-trim (org-table-get-field))))))))
9867
9868 (defvar org-table-formula-history nil)
9869
9870 (defvar org-table-column-names nil
9871 "Alist with column names, derived from the `!' line.")
9872 (defvar org-table-column-name-regexp nil
9873 "Regular expression matching the current column names.")
9874 (defvar org-table-local-parameters nil
9875 "Alist with parameter names, derived from the `$' line.")
9876 (defvar org-table-named-field-locations nil
9877 "Alist with locations of named fields.")
9878
9879 (defun org-table-get-formula (&optional equation named)
9880 "Read a formula from the minibuffer, offer stored formula as default."
9881 (let* ((name (car (rassoc (list (org-current-line)
9882 (org-table-current-column))
9883 org-table-named-field-locations)))
9884 (scol (if named
9885 (if name name
9886 (error "Not in a named field"))
9887 (int-to-string (org-table-current-column))))
9888 (dummy (and name (not named)
9889 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9890 (error "Abort")))
9891 (org-table-may-need-update nil)
9892 (stored-list (org-table-get-stored-formulas))
9893 (stored (cdr (assoc scol stored-list)))
9894 (eq (cond
9895 ((and stored equation (string-match "^ *=? *$" equation))
9896 stored)
9897 ((stringp equation)
9898 equation)
9899 (t (read-string
9900 (format "%s formula $%s=" (if named "Field" "Column") scol)
9901 (or stored "") 'org-table-formula-history
9902 ;stored
9903 ))))
9904 mustsave)
9905 (when (not (string-match "\\S-" eq))
9906 ;; remove formula
9907 (setq stored-list (delq (assoc scol stored-list) stored-list))
9908 (org-table-store-formulas stored-list)
9909 (error "Formula removed"))
9910 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9911 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9912 (if (and name (not named))
9913 ;; We set the column equation, delete the named one.
9914 (setq stored-list (delq (assoc name stored-list) stored-list)
9915 mustsave t))
9916 (if stored
9917 (setcdr (assoc scol stored-list) eq)
9918 (setq stored-list (cons (cons scol eq) stored-list)))
9919 (if (or mustsave (not (equal stored eq)))
9920 (org-table-store-formulas stored-list))
9921 eq))
9922
9923 (defun org-table-store-formulas (alist)
9924 "Store the list of formulas below the current table."
9925 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9926 (save-excursion
9927 (goto-char (org-table-end))
9928 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9929 (delete-region (point) (match-end 0)))
9930 (insert "#+TBLFM: "
9931 (mapconcat (lambda (x)
9932 (concat "$" (car x) "=" (cdr x)))
9933 alist "::")
9934 "\n")))
9935
9936 (defun org-table-get-stored-formulas ()
9937 "Return an alist with the t=stored formulas directly after current table."
9938 (interactive)
9939 (let (scol eq eq-alist strings string seen)
9940 (save-excursion
9941 (goto-char (org-table-end))
9942 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9943 (setq strings (org-split-string (match-string 2) " *:: *"))
9944 (while (setq string (pop strings))
9945 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9946 (setq scol (match-string 1 string)
9947 eq (match-string 2 string)
9948 eq-alist (cons (cons scol eq) eq-alist))
9949 (if (member scol seen)
9950 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9951 (push scol seen))))))
9952 (nreverse eq-alist)))
9953
9954 (defun org-table-modify-formulas (action &rest columns)
9955 "Modify the formulas stored below the current table.
9956 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9957 expected, for the other actions only a single column number is needed."
9958 (let ((list (org-table-get-stored-formulas))
9959 (nmax (length (org-split-string
9960 (buffer-substring (point-at-bol) (point-at-eol))
9961 "|")))
9962 col col1 col2 scol si sc1 sc2)
9963 (cond
9964 ((null list)) ; No action needed if there are no stored formulas
9965 ((eq action 'remove)
9966 (setq col (car columns)
9967 scol (int-to-string col))
9968 (org-table-replace-in-formulas list scol "INVALID")
9969 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9970 (loop for i from (1+ col) upto nmax by 1 do
9971 (setq si (int-to-string i))
9972 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9973 (if (assoc si list) (setcar (assoc si list)
9974 (int-to-string (1- i))))))
9975 ((eq action 'insert)
9976 (setq col (car columns))
9977 (loop for i from nmax downto col by 1 do
9978 (setq si (int-to-string i))
9979 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9980 (if (assoc si list) (setcar (assoc si list)
9981 (int-to-string (1+ i))))))
9982 ((eq action 'swap)
9983 (setq col1 (car columns) col2 (nth 1 columns)
9984 sc1 (int-to-string col1) sc2 (int-to-string col2))
9985 ;; Hopefully, ZqZtZ will never be a name in a table
9986 (org-table-replace-in-formulas list sc1 "ZqZtZ")
9987 (org-table-replace-in-formulas list sc2 sc1)
9988 (org-table-replace-in-formulas list "ZqZtZ" sc2)
9989 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
9990 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9991 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
9992 (t (error "Invalid action in `org-table-modify-formulas'")))
9993 (if list (org-table-store-formulas list))))
9994
9995 (defun org-table-replace-in-formulas (list s1 s2)
9996 (let (elt re s)
9997 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9998 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
9999 re (concat (regexp-quote s1) "\\>"))
10000 (while (setq elt (pop list))
10001 (setq s (cdr elt))
10002 (while (string-match re s)
10003 (setq s (replace-match s2 t t s)))
10004 (setcdr elt s))))
10005
10006 (defun org-table-get-specials ()
10007 "Get the column names and local parameters for this table."
10008 (save-excursion
10009 (let ((beg (org-table-begin)) (end (org-table-end))
10010 names name fields fields1 field cnt c v line col)
10011 (setq org-table-column-names nil
10012 org-table-local-parameters nil
10013 org-table-named-field-locations nil)
10014 (goto-char beg)
10015 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10016 (setq names (org-split-string (match-string 1) " *| *")
10017 cnt 1)
10018 (while (setq name (pop names))
10019 (setq cnt (1+ cnt))
10020 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10021 (push (cons name (int-to-string cnt)) org-table-column-names))))
10022 (setq org-table-column-names (nreverse org-table-column-names))
10023 (setq org-table-column-name-regexp
10024 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10025 (goto-char beg)
10026 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10027 (setq fields (org-split-string (match-string 1) " *| *"))
10028 (while (setq field (pop fields))
10029 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10030 (push (cons (match-string 1 field) (match-string 2 field))
10031 org-table-local-parameters))))
10032 (goto-char beg)
10033 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10034 (setq c (match-string 1)
10035 fields (org-split-string (match-string 2) " *| *"))
10036 (save-excursion
10037 (beginning-of-line (if (equal c "_") 2 0))
10038 (setq line (org-current-line) col 1)
10039 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10040 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10041 (while (and fields1 (setq field (pop fields)))
10042 (setq v (pop fields1) col (1+ col))
10043 (when (and (stringp field) (stringp v)
10044 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10045 (push (cons field v) org-table-local-parameters)
10046 (push (list field line col) org-table-named-field-locations)))))))
10047
10048 (defun org-this-word ()
10049 ;; Get the current word
10050 (save-excursion
10051 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
10052 (end (progn (skip-chars-forward "^ \t\n") (point))))
10053 (buffer-substring-no-properties beg end))))
10054
10055 (defun org-table-maybe-eval-formula ()
10056 "Check if the current field starts with \"=\" or \":=\".
10057 If yes, store the formula and apply it."
10058 ;; We already know we are in a table. Get field will only return a formula
10059 ;; when appropriate. It might return a separator line, but no problem.
10060 (when org-table-formula-evaluate-inline
10061 (let* ((field (org-trim (or (org-table-get-field) "")))
10062 named eq)
10063 (when (string-match "^:?=\\(.*\\)" field)
10064 (setq named (equal (string-to-char field) ?:)
10065 eq (match-string 1 field))
10066 (if (fboundp 'calc-eval)
10067 (org-table-eval-formula (if named '(4) nil) eq))))))
10068
10069 (defvar org-recalc-commands nil
10070 "List of commands triggering the recalculation of a line.
10071 Will be filled automatically during use.")
10072
10073 (defvar org-recalc-marks
10074 '((" " . "Unmarked: no special line, no automatic recalculation")
10075 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10076 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10077 ("!" . "Column name definition line. Reference in formula as $name.")
10078 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10079 ("_" . "Names for values in row below this one.")
10080 ("^" . "Names for values in row above this one.")))
10081
10082 (defun org-table-rotate-recalc-marks (&optional newchar)
10083 "Rotate the recalculation mark in the first column.
10084 If in any row, the first field is not consistent with a mark,
10085 insert a new column for the markers.
10086 When there is an active region, change all the lines in the region,
10087 after prompting for the marking character.
10088 After each change, a message will be displayed indicating the meaning
10089 of the new mark."
10090 (interactive)
10091 (unless (org-at-table-p) (error "Not at a table"))
10092 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10093 (beg (org-table-begin))
10094 (end (org-table-end))
10095 (l (org-current-line))
10096 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10097 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10098 (have-col
10099 (save-excursion
10100 (goto-char beg)
10101 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10102 (col (org-table-current-column))
10103 (forcenew (car (assoc newchar org-recalc-marks)))
10104 epos new)
10105 (when l1
10106 (message "Change region to what mark? Type # * ! $ or SPC: ")
10107 (setq newchar (char-to-string (read-char-exclusive))
10108 forcenew (car (assoc newchar org-recalc-marks))))
10109 (if (and newchar (not forcenew))
10110 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10111 newchar))
10112 (if l1 (goto-line l1))
10113 (save-excursion
10114 (beginning-of-line 1)
10115 (unless (looking-at org-table-dataline-regexp)
10116 (error "Not at a table data line")))
10117 (unless have-col
10118 (org-table-goto-column 1)
10119 (org-table-insert-column)
10120 (org-table-goto-column (1+ col)))
10121 (setq epos (point-at-eol))
10122 (save-excursion
10123 (beginning-of-line 1)
10124 (org-table-get-field
10125 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10126 (concat " "
10127 (setq new (or forcenew
10128 (cadr (member (match-string 1) marks))))
10129 " ")
10130 " # ")))
10131 (if (and l1 l2)
10132 (progn
10133 (goto-line l1)
10134 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10135 (and (looking-at org-table-dataline-regexp)
10136 (org-table-get-field 1 (concat " " new " "))))
10137 (goto-line l1)))
10138 (if (not (= epos (point-at-eol))) (org-table-align))
10139 (goto-line l)
10140 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
10141
10142 (defun org-table-maybe-recalculate-line ()
10143 "Recompute the current line if marked for it, and if we haven't just done it."
10144 (interactive)
10145 (and org-table-allow-automatic-line-recalculation
10146 (not (and (memq last-command org-recalc-commands)
10147 (equal org-last-recalc-line (org-current-line))))
10148 (save-excursion (beginning-of-line 1)
10149 (looking-at org-table-auto-recalculate-regexp))
10150 (fboundp 'calc-eval)
10151 (org-table-recalculate) t))
10152
10153 (defvar org-table-formula-debug nil
10154 "Non-nil means, debug table formulas.
10155 When nil, simply write \"#ERROR\" in corrupted fields.")
10156
10157 (defvar modes)
10158 (defsubst org-set-calc-mode (var &optional value)
10159 (if (stringp var)
10160 (setq var (assoc var '(("D" calc-angle-mode deg)
10161 ("R" calc-angle-mode rad)
10162 ("F" calc-prefer-frac t)
10163 ("S" calc-symbolic-mode t)))
10164 value (nth 2 var) var (nth 1 var)))
10165 (if (memq var modes)
10166 (setcar (cdr (memq var modes)) value)
10167 (cons var (cons value modes)))
10168 modes)
10169
10170 (defun org-table-eval-formula (&optional arg equation
10171 suppress-align suppress-const
10172 suppress-store)
10173 "Replace the table field value at the cursor by the result of a calculation.
10174
10175 This function makes use of Dave Gillespie's Calc package, in my view the
10176 most exciting program ever written for GNU Emacs. So you need to have Calc
10177 installed in order to use this function.
10178
10179 In a table, this command replaces the value in the current field with the
10180 result of a formula. It also installs the formula as the \"current\" column
10181 formula, by storing it in a special line below the table. When called
10182 with a `C-u' prefix, the current field must ba a named field, and the
10183 formula is installed as valid in only this specific field.
10184
10185 When called, the command first prompts for a formula, which is read in
10186 the minibuffer. Previously entered formulas are available through the
10187 history list, and the last used formula is offered as a default.
10188 These stored formulas are adapted correctly when moving, inserting, or
10189 deleting columns with the corresponding commands.
10190
10191 The formula can be any algebraic expression understood by the Calc package.
10192 For details, see the Org-mode manual.
10193
10194 This function can also be called from Lisp programs and offers
10195 additional arguments: EQUATION can be the formula to apply. If this
10196 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10197 used to speed-up recursive calls by by-passing unnecessary aligns.
10198 SUPPRESS-CONST suppresses the interpretation of constants in the
10199 formula, assuming that this has been done already outside the function.
10200 SUPPRESS-STORE means the formula should not be stored, either because
10201 it is already stored, or because it is a modified equation that should
10202 not overwrite the stored one."
10203 (interactive "P")
10204 (require 'calc)
10205 (org-table-check-inside-data-field)
10206 (org-table-get-specials)
10207 (let* (fields
10208 (ndown (if (integerp arg) arg 1))
10209 (org-table-automatic-realign nil)
10210 (case-fold-search nil)
10211 (down (> ndown 1))
10212 (formula (if (and equation suppress-store)
10213 equation
10214 (org-table-get-formula equation (equal arg '(4)))))
10215 (n0 (org-table-current-column))
10216 (modes (copy-sequence org-calc-default-modes))
10217 n form fmt x ev orig c)
10218 ;; Parse the format string. Since we have a lot of modes, this is
10219 ;; a lot of work. However, I think calc still uses most of the time.
10220 (if (string-match ";" formula)
10221 (let ((tmp (org-split-string formula ";")))
10222 (setq formula (car tmp)
10223 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10224 (nth 1 tmp)))
10225 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
10226 (setq c (string-to-char (match-string 1 fmt))
10227 n (string-to-number (or (match-string 1 fmt) "")))
10228 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
10229 (setq modes (org-set-calc-mode
10230 'calc-float-format
10231 (list (cdr (assoc c '((?n . float) (?f . fix)
10232 (?s . sci) (?e . eng))))
10233 n))))
10234 (setq fmt (replace-match "" t t fmt)))
10235 (while (string-match "[DRFS]" fmt)
10236 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10237 (setq fmt (replace-match "" t t fmt)))
10238 (unless (string-match "\\S-" fmt)
10239 (setq fmt nil))))
10240 (if (and (not suppress-const) org-table-formula-use-constants)
10241 (setq formula (org-table-formula-substitute-names formula)))
10242 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10243 (while (> ndown 0)
10244 (setq fields (org-split-string
10245 (buffer-substring
10246 (point-at-bol) (point-at-eol)) " *| *"))
10247 (if org-table-formula-numbers-only
10248 (setq fields (mapcar
10249 (lambda (x) (number-to-string (string-to-number x)))
10250 fields)))
10251 (setq ndown (1- ndown))
10252 (setq form (copy-sequence formula))
10253 ;; Insert the references to fields in same row
10254 (while (string-match "\\$\\([0-9]+\\)?" form)
10255 (setq n (if (match-beginning 1)
10256 (string-to-number (match-string 1 form))
10257 n0)
10258 x (nth (1- n) fields))
10259 (unless x (error "Invalid field specifier \"%s\""
10260 (match-string 0 form)))
10261 (if (equal x "") (setq x "0"))
10262 (setq form (replace-match (concat "(" x ")") t t form)))
10263 ;; Insert ranges in current column
10264 (while (string-match "\\&[-I0-9]+" form)
10265 (setq form (replace-match
10266 (save-match-data
10267 (org-table-get-vertical-vector (match-string 0 form)
10268 nil n0))
10269 t t form)))
10270 (setq ev (calc-eval (cons form modes)
10271 (if org-table-formula-numbers-only 'num)))
10272
10273 (when org-table-formula-debug
10274 (with-output-to-temp-buffer "*Help*"
10275 (princ (format "Substitution history of formula
10276 Orig: %s
10277 $xyz-> %s
10278 $1-> %s\n" orig formula form))
10279 (if (listp ev)
10280 (princ (format " %s^\nError: %s"
10281 (make-string (car ev) ?\-) (nth 1 ev)))
10282 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10283 ev (or fmt "NONE")
10284 (if fmt (format fmt (string-to-number ev)) ev)))))
10285 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
10286 (unless (and (interactive-p) (not ndown))
10287 (unless (let (inhibit-redisplay)
10288 (y-or-n-p "Debugging Formula. Continue to next? "))
10289 (org-table-align)
10290 (error "Abort"))
10291 (delete-window (get-buffer-window "*Help*"))
10292 (message "")))
10293 (if (listp ev) (setq fmt nil ev "#ERROR"))
10294 (org-table-justify-field-maybe
10295 (if fmt (format fmt (string-to-number ev)) ev))
10296 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10297 (call-interactively 'org-return)
10298 (setq ndown 0)))
10299 (and down (org-table-maybe-recalculate-line))
10300 (or suppress-align (and org-table-may-need-update
10301 (org-table-align)))))
10302
10303 (defun org-table-recalculate (&optional all noalign)
10304 "Recalculate the current table line by applying all stored formulas.
10305 With prefix arg ALL, do this for all lines in the table."
10306 (interactive "P")
10307 (or (memq this-command org-recalc-commands)
10308 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10309 (unless (org-at-table-p) (error "Not at a table"))
10310 (org-table-get-specials)
10311 (let* ((eqlist (sort (org-table-get-stored-formulas)
10312 (lambda (a b) (string< (car a) (car b)))))
10313 (inhibit-redisplay t)
10314 (line-re org-table-dataline-regexp)
10315 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10316 (thiscol (org-table-current-column))
10317 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
10318 ;; Insert constants in all formulas
10319 (setq eqlist
10320 (mapcar (lambda (x)
10321 (setcdr x (org-table-formula-substitute-names (cdr x)))
10322 x)
10323 eqlist))
10324 ;; Split the equation list
10325 (while (setq eq (pop eqlist))
10326 (if (<= (string-to-char (car eq)) ?9)
10327 (push eq eqlnum)
10328 (push eq eqlname)))
10329 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10330 (if all
10331 (progn
10332 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10333 (goto-char (setq beg (org-table-begin)))
10334 (if (re-search-forward org-table-calculate-mark-regexp end t)
10335 ;; This is a table with marked lines, only compute selected lines
10336 (setq line-re org-table-recalculate-regexp)
10337 ;; Move forward to the first non-header line
10338 (if (and (re-search-forward org-table-dataline-regexp end t)
10339 (re-search-forward org-table-hline-regexp end t)
10340 (re-search-forward org-table-dataline-regexp end t))
10341 (setq beg (match-beginning 0))
10342 nil))) ;; just leave beg where it is
10343 (setq beg (point-at-bol)
10344 end (move-marker (make-marker) (1+ (point-at-eol)))))
10345 (goto-char beg)
10346 (and all (message "Re-applying formulas to full table..."))
10347 (while (re-search-forward line-re end t)
10348 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
10349 ;; Unprotected line, recalculate
10350 (and all (message "Re-applying formulas to full table...(line %d)"
10351 (setq cnt (1+ cnt))))
10352 (setq org-last-recalc-line (org-current-line))
10353 (setq eql eqlnum)
10354 (while (setq entry (pop eql))
10355 (goto-line org-last-recalc-line)
10356 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10357 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
10358 (goto-line thisline)
10359 (org-table-goto-column thiscol)
10360 (or noalign (and org-table-may-need-update (org-table-align))
10361 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10362 ;; Now do the names fields
10363 (while (setq eq (pop eqlname))
10364 (setq name (car eq)
10365 a (assoc name org-table-named-field-locations))
10366 (when a
10367 (message "Re-applying formula to named field: %s" name)
10368 (goto-line (nth 1 a))
10369 (org-table-goto-column (nth 2 a))
10370 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
10371 ;; back to initial position
10372 (goto-line thisline)
10373 (org-table-goto-column thiscol)
10374 (or noalign (and org-table-may-need-update (org-table-align))
10375 (and all (message "Re-applying formulas...done")))))
10376
10377 (defun org-table-formula-substitute-names (f)
10378 "Replace $const with values in string F."
10379 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
10380 ;; First, check for column names
10381 (while (setq start (string-match org-table-column-name-regexp f start))
10382 (setq start (1+ start))
10383 (setq a (assoc (match-string 1 f) org-table-column-names))
10384 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10385 ;; Expand ranges to vectors
10386 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
10387 (setq n1 (string-to-number (match-string 1 f))
10388 n2 (string-to-number (match-string 2 f))
10389 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
10390 s (concat "[($" (number-to-string (1- nn1)) ")"))
10391 (loop for i from nn1 upto nn2 do
10392 (setq s (concat s ",($" (int-to-string i) ")")))
10393 (setq s (concat s "]"))
10394 (if (< n2 n1) (setq s (concat "rev(" s ")")))
10395 (setq f (replace-match s t t f)))
10396 ;; Parameters and constants
10397 (setq start 0)
10398 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
10399 (setq start (1+ start))
10400 (if (setq a (save-match-data
10401 (org-table-get-constant (match-string 1 f))))
10402 (setq f (replace-match (concat "(" a ")") t t f))))
10403 (if org-table-formula-debug
10404 (put-text-property 0 (length f) :orig-formula f1 f))
10405 f))
10406
10407 (defun org-table-get-constant (const)
10408 "Find the value for a parameter or constant in a formula.
10409 Parameters get priority."
10410 (or (cdr (assoc const org-table-local-parameters))
10411 (cdr (assoc const org-table-formula-constants))
10412 (and (fboundp 'constants-get) (constants-get const))
10413 "#UNDEFINED_NAME"))
10414
10415 (defvar org-edit-formulas-map (make-sparse-keymap))
10416 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
10417 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
10418 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
10419
10420 (defvar org-pos)
10421
10422 (defun org-table-edit-formulas ()
10423 "Edit the formulas of the current table in a separate buffer."
10424 (interactive)
10425 (unless (org-at-table-p)
10426 (error "Not at a table"))
10427 (org-table-get-specials)
10428 (let ((eql (org-table-get-stored-formulas))
10429 (pos (move-marker (make-marker) (point)))
10430 (wc (current-window-configuration))
10431 entry loc s)
10432 (switch-to-buffer-other-window "*Edit Formulas*")
10433 (erase-buffer)
10434 (fundamental-mode)
10435 (set (make-local-variable 'org-pos) pos)
10436 (set (make-local-variable 'org-window-configuration) wc)
10437 (use-local-map org-edit-formulas-map)
10438 (setq s "# Edit formulas and finish with `C-c C-c'.
10439 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
10440 # Use `C-c ?' to get information about $name at point.
10441 # To cancel editing, press `C-c C-q'.\n")
10442 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10443 (insert s)
10444 (while (setq entry (pop eql))
10445 (when (setq loc (assoc (car entry) org-table-named-field-locations))
10446 (setq s (format "# Named formula, referring to column %d in line %d\n"
10447 (nth 2 loc) (nth 1 loc)))
10448 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10449 (insert s))
10450 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
10451 (remove-text-properties 0 (length s) '(face nil) s)
10452 (insert s))
10453 (goto-char (point-min))
10454 (message "Edit formulas and finish with `C-c C-c'.")))
10455
10456 (defun org-show-variable ()
10457 "Show the location/value of the $ expression at point."
10458 (interactive)
10459 (let (var (pos org-pos) (win (selected-window)) e)
10460 (save-excursion
10461 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
10462 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
10463 (setq var (match-string 1))
10464 (error "No variable at point")))
10465 (cond
10466 ((setq e (assoc var org-table-named-field-locations))
10467 (switch-to-buffer-other-window (marker-buffer pos))
10468 (goto-line (nth 1 e))
10469 (org-table-goto-column (nth 2 e))
10470 (select-window win)
10471 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10472 ((setq e (assoc var org-table-column-names))
10473 (switch-to-buffer-other-window (marker-buffer pos))
10474 (goto-char pos)
10475 (goto-char (org-table-begin))
10476 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10477 (org-table-end) t)
10478 (progn
10479 (goto-char (match-beginning 1))
10480 (message "Named column (column %s)" (cdr e)))
10481 (error "Column name not found"))
10482 (select-window win))
10483 ((string-match "^[0-9]$" var)
10484 ;; column number
10485 (switch-to-buffer-other-window (marker-buffer pos))
10486 (goto-char pos)
10487 (goto-char (org-table-begin))
10488 (recenter 1)
10489 (if (re-search-forward org-table-dataline-regexp
10490 (org-table-end) t)
10491 (progn
10492 (goto-char (match-beginning 0))
10493 (org-table-goto-column (string-to-number var))
10494 (message "Column %s" var))
10495 (error "Column name not found"))
10496 (select-window win))
10497 ((setq e (assoc var org-table-local-parameters))
10498 (switch-to-buffer-other-window (marker-buffer pos))
10499 (goto-char pos)
10500 (goto-char (org-table-begin))
10501 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10502 (progn
10503 (goto-char (match-beginning 1))
10504 (message "Local parameter."))
10505 (error "Parameter not found"))
10506 (select-window win))
10507 (t
10508 (cond
10509 ((setq e (assoc var org-table-formula-constants))
10510 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
10511 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10512 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
10513 (t (error "Undefined name $%s" var)))))))
10514
10515 (defun org-finish-edit-formulas (&optional arg)
10516 "Parse the buffer for formula definitions and install them.
10517 With prefix ARG, apply the new formulas to the table."
10518 (interactive "P")
10519 (let ((pos org-pos) eql)
10520 (goto-char (point-min))
10521 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
10522 (push (cons (match-string 1) (match-string 2)) eql))
10523 (set-window-configuration org-window-configuration)
10524 (select-window (get-buffer-window (marker-buffer pos)))
10525 (goto-char pos)
10526 (unless (org-at-table-p)
10527 (error "Lost table position - cannot install formulae"))
10528 (org-table-store-formulas eql)
10529 (move-marker pos nil)
10530 (kill-buffer "*Edit Formulas*")
10531 (if arg
10532 (org-table-recalculate 'all)
10533 (message "New formulas installed - press C-u C-c C-c to apply."))))
10534
10535 (defun org-abort-edit-formulas ()
10536 "Abort editing formulas, without installing the changes."
10537 (interactive)
10538 (let ((pos org-pos))
10539 (set-window-configuration org-window-configuration)
10540 (select-window (get-buffer-window (marker-buffer pos)))
10541 (goto-char pos)
10542 (message "Formula editing aborted without installing changes")))
10543
10544 ;;; The orgtbl minor mode
10545
10546 ;; Define a minor mode which can be used in other modes in order to
10547 ;; integrate the org-mode table editor.
10548
10549 ;; This is really a hack, because the org-mode table editor uses several
10550 ;; keys which normally belong to the major mode, for example the TAB and
10551 ;; RET keys. Here is how it works: The minor mode defines all the keys
10552 ;; necessary to operate the table editor, but wraps the commands into a
10553 ;; function which tests if the cursor is currently inside a table. If that
10554 ;; is the case, the table editor command is executed. However, when any of
10555 ;; those keys is used outside a table, the function uses `key-binding' to
10556 ;; look up if the key has an associated command in another currently active
10557 ;; keymap (minor modes, major mode, global), and executes that command.
10558 ;; There might be problems if any of the keys used by the table editor is
10559 ;; otherwise used as a prefix key.
10560
10561 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10562 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10563 ;; addresses this by checking explicitly for both bindings.
10564
10565 ;; The optimized version (see variable `orgtbl-optimized') takes over
10566 ;; all keys which are bound to `self-insert-command' in the *global map*.
10567 ;; Some modes bind other commands to simple characters, for example
10568 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10569 ;; active, this binding is ignored inside tables and replaced with a
10570 ;; modified self-insert.
10571
10572 (defvar orgtbl-mode nil
10573 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10574 table editor in arbitrary modes.")
10575 (make-variable-buffer-local 'orgtbl-mode)
10576
10577 (defvar orgtbl-mode-map (make-keymap)
10578 "Keymap for `orgtbl-mode'.")
10579
10580 ;;;###autoload
10581 (defun turn-on-orgtbl ()
10582 "Unconditionally turn on `orgtbl-mode'."
10583 (orgtbl-mode 1))
10584
10585 ;;;###autoload
10586 (defun orgtbl-mode (&optional arg)
10587 "The `org-mode' table editor as a minor mode for use in other modes."
10588 (interactive)
10589 (if (eq major-mode 'org-mode)
10590 ;; Exit without error, in case some hook functions calls this
10591 ;; by accident in org-mode.
10592 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10593 (setq orgtbl-mode
10594 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10595 (if orgtbl-mode
10596 (progn
10597 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10598 ;; Make sure we are first in minor-mode-map-alist
10599 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10600 (and c (setq minor-mode-map-alist
10601 (cons c (delq c minor-mode-map-alist)))))
10602 (set (make-local-variable (quote org-table-may-need-update)) t)
10603 (org-add-hook 'before-change-functions 'org-before-change-function
10604 nil 'local)
10605 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
10606 auto-fill-inhibit-regexp)
10607 (set (make-local-variable 'auto-fill-inhibit-regexp)
10608 (if auto-fill-inhibit-regexp
10609 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
10610 "[ \t]*|"))
10611 (org-add-to-invisibility-spec '(org-cwidth))
10612 (easy-menu-add orgtbl-mode-menu)
10613 (run-hooks 'orgtbl-mode-hook))
10614 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10615 (org-cleanup-narrow-column-properties)
10616 (org-remove-from-invisibility-spec '(org-cwidth))
10617 (remove-hook 'before-change-functions 'org-before-change-function t)
10618 (easy-menu-remove orgtbl-mode-menu)
10619 (force-mode-line-update 'all))))
10620
10621 (defun org-cleanup-narrow-column-properties ()
10622 "Remove all properties related to narrow-column invisibility."
10623 (let ((s 1))
10624 (while (setq s (text-property-any s (point-max)
10625 'display org-narrow-column-arrow))
10626 (remove-text-properties s (1+ s) '(display t)))
10627 (setq s 1)
10628 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10629 (remove-text-properties s (1+ s) '(org-cwidth t)))
10630 (setq s 1)
10631 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10632 (remove-text-properties s (1+ s) '(invisible t)))))
10633
10634 ;; Install it as a minor mode.
10635 (put 'orgtbl-mode :included t)
10636 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10637 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10638
10639 (defun orgtbl-make-binding (fun n &rest keys)
10640 "Create a function for binding in the table minor mode.
10641 FUN is the command to call inside a table. N is used to create a unique
10642 command name. KEYS are keys that should be checked in for a command
10643 to execute outside of tables."
10644 (eval
10645 (list 'defun
10646 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10647 '(arg)
10648 (concat "In tables, run `" (symbol-name fun) "'.\n"
10649 "Outside of tables, run the binding of `"
10650 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10651 "'.")
10652 '(interactive "p")
10653 (list 'if
10654 '(org-at-table-p)
10655 (list 'call-interactively (list 'quote fun))
10656 (list 'let '(orgtbl-mode)
10657 (list 'call-interactively
10658 (append '(or)
10659 (mapcar (lambda (k)
10660 (list 'key-binding k))
10661 keys)
10662 '('orgtbl-error))))))))
10663
10664 (defun orgtbl-error ()
10665 "Error when there is no default binding for a table key."
10666 (interactive)
10667 (error "This key is has no function outside tables"))
10668
10669 (defun orgtbl-setup ()
10670 "Setup orgtbl keymaps."
10671 (let ((nfunc 0)
10672 (bindings
10673 (list
10674 '([(meta shift left)] org-table-delete-column)
10675 '([(meta left)] org-table-move-column-left)
10676 '([(meta right)] org-table-move-column-right)
10677 '([(meta shift right)] org-table-insert-column)
10678 '([(meta shift up)] org-table-kill-row)
10679 '([(meta shift down)] org-table-insert-row)
10680 '([(meta up)] org-table-move-row-up)
10681 '([(meta down)] org-table-move-row-down)
10682 '("\C-c\C-w" org-table-cut-region)
10683 '("\C-c\M-w" org-table-copy-region)
10684 '("\C-c\C-y" org-table-paste-rectangle)
10685 '("\C-c-" org-table-insert-hline)
10686 ; '([(shift tab)] org-table-previous-field)
10687 '("\C-m" org-table-next-row)
10688 (list (org-key 'S-return) 'org-table-copy-down)
10689 '([(meta return)] org-table-wrap-region)
10690 '("\C-c\C-q" org-table-wrap-region)
10691 '("\C-c?" org-table-current-column)
10692 '("\C-c " org-table-blank-field)
10693 '("\C-c+" org-table-sum)
10694 '("\C-c=" org-table-eval-formula)
10695 '("\C-c'" org-table-edit-formulas)
10696 '("\C-c`" org-table-edit-field)
10697 '("\C-c*" org-table-recalculate)
10698 '("\C-c|" org-table-create-or-convert-from-region)
10699 '("\C-c^" org-table-sort-lines)
10700 '([(control ?#)] org-table-rotate-recalc-marks)))
10701 elt key fun cmd)
10702 (while (setq elt (pop bindings))
10703 (setq nfunc (1+ nfunc))
10704 (setq key (car elt)
10705 fun (nth 1 elt)
10706 cmd (orgtbl-make-binding fun nfunc key))
10707 (define-key orgtbl-mode-map key cmd))
10708 ;; Special treatment needed for TAB and RET
10709 (define-key orgtbl-mode-map [(return)]
10710 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10711 (define-key orgtbl-mode-map "\C-m"
10712 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10713 (define-key orgtbl-mode-map [(tab)]
10714 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10715 (define-key orgtbl-mode-map "\C-i"
10716 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10717 (define-key orgtbl-mode-map "\C-i"
10718 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10719 (define-key orgtbl-mode-map "\C-c\C-c"
10720 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10721 (when orgtbl-optimized
10722 ;; If the user wants maximum table support, we need to hijack
10723 ;; some standard editing functions
10724 (org-remap orgtbl-mode-map
10725 'self-insert-command 'orgtbl-self-insert-command
10726 'delete-char 'org-delete-char
10727 'delete-backward-char 'org-delete-backward-char)
10728 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10729 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10730 '("OrgTbl"
10731 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10732 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10733 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10734 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10735 "--"
10736 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10737 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10738 ["Copy Field from Above"
10739 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10740 "--"
10741 ("Column"
10742 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10743 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10744 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10745 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
10746 "--"
10747 ["Enable Narrowing" (setq org-table-limit-column-width (not org-table-limit-column-width)) :active (org-at-table-p) :selected org-table-limit-column-width :style toggle])
10748 ("Row"
10749 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10750 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10751 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10752 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10753 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10754 "--"
10755 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10756 ("Rectangle"
10757 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10758 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10759 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10760 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10761 "--"
10762 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10763 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10764 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10765 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10766 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10767 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10768 ["Sum Column/Rectangle" org-table-sum
10769 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10770 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10771 ["Debug Formulas"
10772 (setq org-table-formula-debug (not org-table-formula-debug))
10773 :style toggle :selected org-table-formula-debug]
10774 ))
10775 t)
10776
10777 (defun orgtbl-tab (arg)
10778 "Justification and field motion for `orgtbl-mode'."
10779 (interactive "P")
10780 (if arg (org-table-edit-field t)
10781 (org-table-justify-field-maybe)
10782 (org-table-next-field)))
10783
10784 (defun orgtbl-ret ()
10785 "Justification and field motion for `orgtbl-mode'."
10786 (interactive)
10787 (org-table-justify-field-maybe)
10788 (org-table-next-row))
10789
10790 (defun orgtbl-self-insert-command (N)
10791 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10792 If the cursor is in a table looking at whitespace, the whitespace is
10793 overwritten, and the table is not marked as requiring realignment."
10794 (interactive "p")
10795 (if (and (org-at-table-p)
10796 (or
10797 (and org-table-auto-blank-field
10798 (member last-command
10799 '(orgtbl-hijacker-command-100
10800 orgtbl-hijacker-command-101
10801 orgtbl-hijacker-command-102
10802 orgtbl-hijacker-command-103
10803 orgtbl-hijacker-command-104
10804 orgtbl-hijacker-command-105))
10805 (org-table-blank-field))
10806 t)
10807 (eq N 1)
10808 (looking-at "[^|\n]* +|"))
10809 (let (org-table-may-need-update)
10810 (goto-char (1- (match-end 0)))
10811 (delete-backward-char 1)
10812 (goto-char (match-beginning 0))
10813 (self-insert-command N))
10814 (setq org-table-may-need-update t)
10815 (let (orgtbl-mode)
10816 (call-interactively (key-binding (vector last-input-event))))))
10817
10818 (defun org-force-self-insert (N)
10819 "Needed to enforce self-insert under remapping."
10820 (interactive "p")
10821 (self-insert-command N))
10822
10823 ;;; Exporting
10824
10825 (defconst org-level-max 20)
10826
10827 (defun org-export-find-first-heading-line (list)
10828 "Remove all lines from LIST which are before the first headline."
10829 (let ((orig-list list)
10830 (re (concat "^" outline-regexp)))
10831 (while (and list
10832 (not (string-match re (car list))))
10833 (pop list))
10834 (or list orig-list)))
10835
10836 (defun org-skip-comments (lines)
10837 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10838 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10839 (re2 "^\\(\\*+\\)[ \t\n\r]")
10840 rtn line level)
10841 (while (setq line (pop lines))
10842 (cond
10843 ((and (string-match re1 line)
10844 (setq level (- (match-end 1) (match-beginning 1))))
10845 ;; Beginning of a COMMENT subtree. Skip it.
10846 (while (and (setq line (pop lines))
10847 (or (not (string-match re2 line))
10848 (> (- (match-end 1) (match-beginning 1)) level))))
10849 (setq lines (cons line lines)))
10850 ((string-match "^#" line)
10851 ;; an ordinary comment line
10852 )
10853 ((and org-export-table-remove-special-lines
10854 (string-match "^[ \t]*| *[!_^] *|" line))
10855 ;; a special table line that should be removed
10856 )
10857 (t (setq rtn (cons line rtn)))))
10858 (nreverse rtn)))
10859
10860 ;; ASCII
10861
10862 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10863 "Characters for underlining headings in ASCII export.")
10864
10865 (defconst org-html-entities
10866 '(("nbsp")
10867 ("iexcl")
10868 ("cent")
10869 ("pound")
10870 ("curren")
10871 ("yen")
10872 ("brvbar")
10873 ("sect")
10874 ("uml")
10875 ("copy")
10876 ("ordf")
10877 ("laquo")
10878 ("not")
10879 ("shy")
10880 ("reg")
10881 ("macr")
10882 ("deg")
10883 ("plusmn")
10884 ("sup2")
10885 ("sup3")
10886 ("acute")
10887 ("micro")
10888 ("para")
10889 ("middot")
10890 ("odot"."o")
10891 ("star"."*")
10892 ("cedil")
10893 ("sup1")
10894 ("ordm")
10895 ("raquo")
10896 ("frac14")
10897 ("frac12")
10898 ("frac34")
10899 ("iquest")
10900 ("Agrave")
10901 ("Aacute")
10902 ("Acirc")
10903 ("Atilde")
10904 ("Auml")
10905 ("Aring") ("AA"."&Aring;")
10906 ("AElig")
10907 ("Ccedil")
10908 ("Egrave")
10909 ("Eacute")
10910 ("Ecirc")
10911 ("Euml")
10912 ("Igrave")
10913 ("Iacute")
10914 ("Icirc")
10915 ("Iuml")
10916 ("ETH")
10917 ("Ntilde")
10918 ("Ograve")
10919 ("Oacute")
10920 ("Ocirc")
10921 ("Otilde")
10922 ("Ouml")
10923 ("times")
10924 ("Oslash")
10925 ("Ugrave")
10926 ("Uacute")
10927 ("Ucirc")
10928 ("Uuml")
10929 ("Yacute")
10930 ("THORN")
10931 ("szlig")
10932 ("agrave")
10933 ("aacute")
10934 ("acirc")
10935 ("atilde")
10936 ("auml")
10937 ("aring")
10938 ("aelig")
10939 ("ccedil")
10940 ("egrave")
10941 ("eacute")
10942 ("ecirc")
10943 ("euml")
10944 ("igrave")
10945 ("iacute")
10946 ("icirc")
10947 ("iuml")
10948 ("eth")
10949 ("ntilde")
10950 ("ograve")
10951 ("oacute")
10952 ("ocirc")
10953 ("otilde")
10954 ("ouml")
10955 ("divide")
10956 ("oslash")
10957 ("ugrave")
10958 ("uacute")
10959 ("ucirc")
10960 ("uuml")
10961 ("yacute")
10962 ("thorn")
10963 ("yuml")
10964 ("fnof")
10965 ("Alpha")
10966 ("Beta")
10967 ("Gamma")
10968 ("Delta")
10969 ("Epsilon")
10970 ("Zeta")
10971 ("Eta")
10972 ("Theta")
10973 ("Iota")
10974 ("Kappa")
10975 ("Lambda")
10976 ("Mu")
10977 ("Nu")
10978 ("Xi")
10979 ("Omicron")
10980 ("Pi")
10981 ("Rho")
10982 ("Sigma")
10983 ("Tau")
10984 ("Upsilon")
10985 ("Phi")
10986 ("Chi")
10987 ("Psi")
10988 ("Omega")
10989 ("alpha")
10990 ("beta")
10991 ("gamma")
10992 ("delta")
10993 ("epsilon")
10994 ("varepsilon"."&epsilon;")
10995 ("zeta")
10996 ("eta")
10997 ("theta")
10998 ("iota")
10999 ("kappa")
11000 ("lambda")
11001 ("mu")
11002 ("nu")
11003 ("xi")
11004 ("omicron")
11005 ("pi")
11006 ("rho")
11007 ("sigmaf") ("varsigma"."&sigmaf;")
11008 ("sigma")
11009 ("tau")
11010 ("upsilon")
11011 ("phi")
11012 ("chi")
11013 ("psi")
11014 ("omega")
11015 ("thetasym") ("vartheta"."&thetasym;")
11016 ("upsih")
11017 ("piv")
11018 ("bull") ("bullet"."&bull;")
11019 ("hellip") ("dots"."&hellip;")
11020 ("prime")
11021 ("Prime")
11022 ("oline")
11023 ("frasl")
11024 ("weierp")
11025 ("image")
11026 ("real")
11027 ("trade")
11028 ("alefsym")
11029 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
11030 ("uarr") ("uparrow"."&uarr;")
11031 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
11032 ("darr")("downarrow"."&darr;")
11033 ("harr") ("leftrightarrow"."&harr;")
11034 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
11035 ("lArr") ("Leftarrow"."&lArr;")
11036 ("uArr") ("Uparrow"."&uArr;")
11037 ("rArr") ("Rightarrow"."&rArr;")
11038 ("dArr") ("Downarrow"."&dArr;")
11039 ("hArr") ("Leftrightarrow"."&hArr;")
11040 ("forall")
11041 ("part") ("partial"."&part;")
11042 ("exist") ("exists"."&exist;")
11043 ("empty") ("emptyset"."&empty;")
11044 ("nabla")
11045 ("isin") ("in"."&isin;")
11046 ("notin")
11047 ("ni")
11048 ("prod")
11049 ("sum")
11050 ("minus")
11051 ("lowast") ("ast"."&lowast;")
11052 ("radic")
11053 ("prop") ("proptp"."&prop;")
11054 ("infin") ("infty"."&infin;")
11055 ("ang") ("angle"."&ang;")
11056 ("and") ("vee"."&and;")
11057 ("or") ("wedge"."&or;")
11058 ("cap")
11059 ("cup")
11060 ("int")
11061 ("there4")
11062 ("sim")
11063 ("cong") ("simeq"."&cong;")
11064 ("asymp")("approx"."&asymp;")
11065 ("ne") ("neq"."&ne;")
11066 ("equiv")
11067 ("le")
11068 ("ge")
11069 ("sub") ("subset"."&sub;")
11070 ("sup") ("supset"."&sup;")
11071 ("nsub")
11072 ("sube")
11073 ("supe")
11074 ("oplus")
11075 ("otimes")
11076 ("perp")
11077 ("sdot") ("cdot"."&sdot;")
11078 ("lceil")
11079 ("rceil")
11080 ("lfloor")
11081 ("rfloor")
11082 ("lang")
11083 ("rang")
11084 ("loz") ("Diamond"."&loz;")
11085 ("spades") ("spadesuit"."&spades;")
11086 ("clubs") ("clubsuit"."&clubs;")
11087 ("hearts") ("diamondsuit"."&hearts;")
11088 ("diams") ("diamondsuit"."&diams;")
11089 ("quot")
11090 ("amp")
11091 ("lt")
11092 ("gt")
11093 ("OElig")
11094 ("oelig")
11095 ("Scaron")
11096 ("scaron")
11097 ("Yuml")
11098 ("circ")
11099 ("tilde")
11100 ("ensp")
11101 ("emsp")
11102 ("thinsp")
11103 ("zwnj")
11104 ("zwj")
11105 ("lrm")
11106 ("rlm")
11107 ("ndash")
11108 ("mdash")
11109 ("lsquo")
11110 ("rsquo")
11111 ("sbquo")
11112 ("ldquo")
11113 ("rdquo")
11114 ("bdquo")
11115 ("dagger")
11116 ("Dagger")
11117 ("permil")
11118 ("lsaquo")
11119 ("rsaquo")
11120 ("euro")
11121
11122 ("arccos"."arccos")
11123 ("arcsin"."arcsin")
11124 ("arctan"."arctan")
11125 ("arg"."arg")
11126 ("cos"."cos")
11127 ("cosh"."cosh")
11128 ("cot"."cot")
11129 ("coth"."coth")
11130 ("csc"."csc")
11131 ("deg"."deg")
11132 ("det"."det")
11133 ("dim"."dim")
11134 ("exp"."exp")
11135 ("gcd"."gcd")
11136 ("hom"."hom")
11137 ("inf"."inf")
11138 ("ker"."ker")
11139 ("lg"."lg")
11140 ("lim"."lim")
11141 ("liminf"."liminf")
11142 ("limsup"."limsup")
11143 ("ln"."ln")
11144 ("log"."log")
11145 ("max"."max")
11146 ("min"."min")
11147 ("Pr"."Pr")
11148 ("sec"."sec")
11149 ("sin"."sin")
11150 ("sinh"."sinh")
11151 ("sup"."sup")
11152 ("tan"."tan")
11153 ("tanh"."tanh")
11154 )
11155 "Entities for TeX->HTML translation.
11156 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
11157 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
11158 In that case, \"\\ent\" will be translated to \"&other;\".
11159 The list contains HTML entities for Latin-1, Greek and other symbols.
11160 It is supplemented by a number of commonly used TeX macros with appropriate
11161 translations. There is currently no way for users to extend this.")
11162
11163 (defun org-cleaned-string-for-export (string)
11164 "Cleanup a buffer substring so that links can be created safely."
11165 (interactive)
11166 (let* ((cb (current-buffer))
11167 (re-radio (and org-target-link-regexp
11168 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
11169 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
11170 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
11171 rtn)
11172 (save-excursion
11173 (set-buffer (get-buffer-create " org-mode-tmp"))
11174 (erase-buffer)
11175 (insert string)
11176 (org-mode)
11177 ;; Find targets in comments and move them out of comments,
11178 ;; but mark them as targets that should be invisible
11179 (goto-char (point-min))
11180 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
11181 (replace-match "\\1(INVISIBLE)"))
11182 ;; Find matches for radio targets and turn them into internal links
11183 (goto-char (point-min))
11184 (when re-radio
11185 (while (re-search-forward re-radio nil t)
11186 (replace-match "\\1[[\\2]]")))
11187 ;; Find all links that contain a newline and put them into a single line
11188 (goto-char (point-min))
11189 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
11190 (replace-match "\\1 \\3")
11191 (goto-char (match-beginning 0)))
11192 ;; Normalize links: Convert angle and plain links into bracket links
11193 (goto-char (point-min))
11194 (while (re-search-forward re-plain-link nil t)
11195 (replace-match
11196 (concat
11197 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11198 t t))
11199 (goto-char (point-min))
11200 (while (re-search-forward re-angle-link nil t)
11201 (replace-match
11202 (concat
11203 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11204 t t))
11205
11206 ;; Remove comments
11207 (goto-char (point-min))
11208 (while (re-search-forward "^#.*\n?" nil t)
11209 (replace-match ""))
11210 (setq rtn (buffer-string)))
11211 (kill-buffer " org-mode-tmp")
11212 rtn))
11213
11214 (defun org-solidify-link-text (s &optional alist)
11215 "Take link text and make a safe target out of it."
11216 (save-match-data
11217 (let* ((rtn
11218 (mapconcat
11219 'identity
11220 (org-split-string s "[ \t\r\n]+") "--"))
11221 (a (assoc rtn alist)))
11222 (or (cdr a) rtn))))
11223
11224 (defun org-convert-to-odd-levels ()
11225 "Convert an org-mode file with all levels allowed to one with odd levels.
11226 This will leave level 1 alone, convert level 2 to level 3, level 3 to
11227 level 5 etc."
11228 (interactive)
11229 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
11230 (let ((org-odd-levels-only nil) n)
11231 (save-excursion
11232 (goto-char (point-min))
11233 (while (re-search-forward "^\\*\\*+" nil t)
11234 (setq n (1- (length (match-string 0))))
11235 (while (>= (setq n (1- n)) 0)
11236 (org-demote))
11237 (end-of-line 1))))))
11238
11239
11240 (defun org-convert-to-oddeven-levels ()
11241 "Convert an org-mode file with only odd levels to one with odd and even levels.
11242 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
11243 section with an even level, conversion would destroy the structure of the file. An error
11244 is signaled in this case."
11245 (interactive)
11246 (goto-char (point-min))
11247 ;; First check if there are no even levels
11248 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
11249 (org-show-hierarchy-above)
11250 (error "Not all levels are odd in this file. Conversion not possible."))
11251 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
11252 (let ((org-odd-levels-only nil) n)
11253 (save-excursion
11254 (goto-char (point-min))
11255 (while (re-search-forward "^\\*\\*+" nil t)
11256 (setq n (/ (length (match-string 0)) 2))
11257 (while (>= (setq n (1- n)) 0)
11258 (org-promote))
11259 (end-of-line 1))))))
11260
11261 (defun org-tr-level (n)
11262 "Make N odd if required."
11263 (if org-odd-levels-only (1+ (/ n 2)) n))
11264
11265 (defvar org-last-level nil) ; dynamically scoped variable
11266
11267 (defun org-export-as-ascii (arg)
11268 "Export the outline as a pretty ASCII file.
11269 If there is an active region, export only the region.
11270 The prefix ARG specifies how many levels of the outline should become
11271 underlined headlines. The default is 3."
11272 (interactive "P")
11273 (setq-default org-todo-line-regexp org-todo-line-regexp)
11274 (let* ((region
11275 (buffer-substring
11276 (if (org-region-active-p) (region-beginning) (point-min))
11277 (if (org-region-active-p) (region-end) (point-max))))
11278 (lines (org-export-find-first-heading-line
11279 (org-skip-comments
11280 (org-split-string
11281 (org-cleaned-string-for-export region)
11282 "[\r\n]"))))
11283 (org-startup-with-deadline-check nil)
11284 (level 0) line txt
11285 (umax nil)
11286 (case-fold-search nil)
11287 (filename (concat (file-name-sans-extension buffer-file-name)
11288 ".txt"))
11289 (buffer (find-file-noselect filename))
11290 (levels-open (make-vector org-level-max nil))
11291 (date (format-time-string "%Y/%m/%d" (current-time)))
11292 (time (format-time-string "%X" (org-current-time)))
11293 (author user-full-name)
11294 (title (buffer-name))
11295 (options nil)
11296 (email user-mail-address)
11297 (language org-export-default-language)
11298 (text nil)
11299 (todo nil)
11300 (lang-words nil))
11301
11302 (setq org-last-level 1)
11303 (org-init-section-numbers)
11304
11305 (find-file-noselect filename)
11306
11307 ;; Search for the export key lines
11308 (org-parse-key-lines)
11309
11310 (setq lang-words (or (assoc language org-export-language-setup)
11311 (assoc "en" org-export-language-setup)))
11312 (if org-export-ascii-show-new-buffer
11313 (switch-to-buffer-other-window buffer)
11314 (set-buffer buffer))
11315 (erase-buffer)
11316 (fundamental-mode)
11317 (if options (org-parse-export-options options))
11318 (setq umax (if arg (prefix-numeric-value arg)
11319 org-export-headline-levels))
11320
11321 ;; File header
11322 (if title (org-insert-centered title ?=))
11323 (insert "\n")
11324 (if (or author email)
11325 (insert (concat (nth 1 lang-words) ": " (or author "")
11326 (if email (concat " <" email ">") "")
11327 "\n")))
11328 (if (and date time)
11329 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
11330 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
11331
11332 (insert "\n\n")
11333
11334 (if org-export-with-toc
11335 (progn
11336 (insert (nth 3 lang-words) "\n"
11337 (make-string (length (nth 3 lang-words)) ?=) "\n")
11338 (mapcar '(lambda (line)
11339 (if (string-match org-todo-line-regexp
11340 line)
11341 ;; This is a headline
11342 (progn
11343 (setq level (- (match-end 1) (match-beginning 1))
11344 level (org-tr-level level)
11345 txt (match-string 3 line)
11346 todo
11347 (or (and (match-beginning 2)
11348 (not (equal (match-string 2 line)
11349 org-done-string)))
11350 ; TODO, not DONE
11351 (and org-export-mark-todo-in-toc
11352 (= level umax)
11353 (org-search-todo-below
11354 line lines level))))
11355 (setq txt (org-html-expand-for-ascii txt))
11356
11357 (if org-export-with-section-numbers
11358 (setq txt (concat (org-section-number level)
11359 " " txt)))
11360 (if (<= level umax)
11361 (progn
11362 (insert
11363 (make-string (* (1- level) 4) ?\ )
11364 (format (if todo "%s (*)\n" "%s\n") txt))
11365 (setq org-last-level level))
11366 ))))
11367 lines)))
11368
11369 (org-init-section-numbers)
11370 (while (setq line (pop lines))
11371 ;; Remove the quoted HTML tags.
11372 (setq line (org-html-expand-for-ascii line))
11373 ;; Remove targets
11374 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
11375 (setq line (replace-match "" t t line)))
11376 ;; Replace internal links
11377 (while (string-match org-bracket-link-regexp line)
11378 (setq line (replace-match
11379 (if (match-end 3) "[\\3]" "[\\1]")
11380 t nil line)))
11381 (cond
11382 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11383 ;; a Headline
11384 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11385 txt (match-string 2 line))
11386 (org-ascii-level-start level txt umax))
11387 (t (insert line "\n"))))
11388 (normal-mode)
11389 (save-buffer)
11390 (goto-char (point-min))))
11391
11392 (defun org-search-todo-below (line lines level)
11393 "Search the subtree below LINE for any TODO entries."
11394 (let ((rest (cdr (memq line lines)))
11395 (re org-todo-line-regexp)
11396 line lv todo)
11397 (catch 'exit
11398 (while (setq line (pop rest))
11399 (if (string-match re line)
11400 (progn
11401 (setq lv (- (match-end 1) (match-beginning 1))
11402 todo (and (match-beginning 2)
11403 (not (equal (match-string 2 line)
11404 org-done-string))))
11405 ; TODO, not DONE
11406 (if (<= lv level) (throw 'exit nil))
11407 (if todo (throw 'exit t))))))))
11408
11409 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
11410 ;; We could also implement *bold*,/italic/ and _underline_ for ASCII export
11411 (defun org-html-expand-for-ascii (line)
11412 "Handle quoted HTML for ASCII export."
11413 (if org-export-html-expand
11414 (while (string-match "@<[^<>\n]*>" line)
11415 ;; We just remove the tags for now.
11416 (setq line (replace-match "" nil nil line))))
11417 line)
11418
11419 (defun org-insert-centered (s &optional underline)
11420 "Insert the string S centered and underline it with character UNDERLINE."
11421 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
11422 (insert (make-string ind ?\ ) s "\n")
11423 (if underline
11424 (insert (make-string ind ?\ )
11425 (make-string (string-width s) underline)
11426 "\n"))))
11427
11428 (defun org-ascii-level-start (level title umax)
11429 "Insert a new level in ASCII export."
11430 (let (char)
11431 (if (> level umax)
11432 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
11433 (if (or (not (equal (char-before) ?\n))
11434 (not (equal (char-before (1- (point))) ?\n)))
11435 (insert "\n"))
11436 (setq char (nth (- umax level) (reverse org-ascii-underline)))
11437 (if org-export-with-section-numbers
11438 (setq title (concat (org-section-number level) " " title)))
11439 (insert title "\n" (make-string (string-width title) char) "\n"))))
11440
11441 (defun org-export-copy-visible ()
11442 "Copy the visible part of the buffer to another buffer, for printing.
11443 Also removes the first line of the buffer if it specifies a mode,
11444 and all options lines."
11445 (interactive)
11446 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
11447 ".txt"))
11448 (buffer (find-file-noselect filename))
11449 (ore (concat
11450 (org-make-options-regexp
11451 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
11452 "STARTUP" "ARCHIVE"
11453 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
11454 (if org-noutline-p "\\(\n\\|$\\)" "")))
11455 s e)
11456 (with-current-buffer buffer
11457 (erase-buffer)
11458 (text-mode))
11459 (save-excursion
11460 (setq s (goto-char (point-min)))
11461 (while (not (= (point) (point-max)))
11462 (goto-char (org-find-invisible))
11463 (append-to-buffer buffer s (point))
11464 (setq s (goto-char (org-find-visible)))))
11465 (switch-to-buffer-other-window buffer)
11466 (newline)
11467 (goto-char (point-min))
11468 (if (looking-at ".*-\\*- mode:.*\n")
11469 (replace-match ""))
11470 (while (re-search-forward ore nil t)
11471 (replace-match ""))
11472 (goto-char (point-min))))
11473
11474 (defun org-find-visible ()
11475 (if (featurep 'noutline)
11476 (let ((s (point)))
11477 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11478 (get-char-property s 'invisible)))
11479 s)
11480 (skip-chars-forward "^\n")
11481 (point)))
11482 (defun org-find-invisible ()
11483 (if (featurep 'noutline)
11484 (let ((s (point)))
11485 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11486 (not (get-char-property s 'invisible))))
11487 s)
11488 (skip-chars-forward "^\r")
11489 (point)))
11490
11491 ;; HTML
11492
11493 (defun org-get-current-options ()
11494 "Return a string with current options as keyword options.
11495 Does include HTML export options as well as TODO and CATEGORY stuff."
11496 (format
11497 "#+TITLE: %s
11498 #+AUTHOR: %s
11499 #+EMAIL: %s
11500 #+LANGUAGE: %s
11501 #+TEXT: Some descriptive text to be emitted. Several lines OK.
11502 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
11503 #+CATEGORY: %s
11504 #+SEQ_TODO: %s
11505 #+TYP_TODO: %s
11506 #+STARTUP: %s %s %s %s %s
11507 #+ARCHIVE: %s
11508 "
11509 (buffer-name) (user-full-name) user-mail-address org-export-default-language
11510 org-export-headline-levels
11511 org-export-with-section-numbers
11512 org-export-with-toc
11513 org-export-preserve-breaks
11514 org-export-html-expand
11515 org-export-with-fixed-width
11516 org-export-with-tables
11517 org-export-with-sub-superscripts
11518 org-export-with-emphasize
11519 org-export-with-TeX-macros
11520 (file-name-nondirectory buffer-file-name)
11521 (if (equal org-todo-interpretation 'sequence)
11522 (mapconcat 'identity org-todo-keywords " ")
11523 "TODO FEEDBACK VERIFY DONE")
11524 (if (equal org-todo-interpretation 'type)
11525 (mapconcat 'identity org-todo-keywords " ")
11526 "Me Jason Marie DONE")
11527 (cdr (assoc org-startup-folded
11528 '((nil . "showall") (t . "overview") (content . "content"))))
11529 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
11530 (if org-odd-levels-only "odd" "oddeven")
11531 (if org-hide-leading-stars "hidestars" "showstars")
11532 (if org-startup-align-all-tables "align" "noalign")
11533 org-archive-location
11534 ))
11535
11536 (defun org-insert-export-options-template ()
11537 "Insert into the buffer a template with information for exporting."
11538 (interactive)
11539 (if (not (bolp)) (newline))
11540 (let ((s (org-get-current-options)))
11541 (and (string-match "#\\+CATEGORY" s)
11542 (setq s (substring s 0 (match-beginning 0))))
11543 (insert s)))
11544
11545 (defun org-toggle-fixed-width-section (arg)
11546 "Toggle the fixed-width export.
11547 If there is no active region, the QUOTE keyword at the current headline is
11548 inserted or removed. When present, it causes the text between this headline
11549 and the next to be exported as fixed-width text, and unmodified.
11550 If there is an active region, this command adds or removes a colon as the
11551 first character of this line. If the first character of a line is a colon,
11552 this line is also exported in fixed-width font."
11553 (interactive "P")
11554 (let* ((cc 0)
11555 (regionp (org-region-active-p))
11556 (beg (if regionp (region-beginning) (point)))
11557 (end (if regionp (region-end)))
11558 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
11559 (re "[ \t]*\\(:\\)")
11560 off)
11561 (if regionp
11562 (save-excursion
11563 (goto-char beg)
11564 (setq cc (current-column))
11565 (beginning-of-line 1)
11566 (setq off (looking-at re))
11567 (while (> nlines 0)
11568 (setq nlines (1- nlines))
11569 (beginning-of-line 1)
11570 (cond
11571 (arg
11572 (move-to-column cc t)
11573 (insert ":\n")
11574 (forward-line -1))
11575 ((and off (looking-at re))
11576 (replace-match "" t t nil 1))
11577 ((not off) (move-to-column cc t) (insert ":")))
11578 (forward-line 1)))
11579 (save-excursion
11580 (org-back-to-heading)
11581 (if (looking-at (concat outline-regexp
11582 "\\( +\\<" org-quote-string "\\>\\)"))
11583 (replace-match "" t t nil 1)
11584 (if (looking-at outline-regexp)
11585 (progn
11586 (goto-char (match-end 0))
11587 (insert " " org-quote-string))))))))
11588
11589 (defun org-export-as-html-and-open (arg)
11590 "Export the outline as HTML and immediately open it with a browser.
11591 If there is an active region, export only the region.
11592 The prefix ARG specifies how many levels of the outline should become
11593 headlines. The default is 3. Lower levels will become bulleted lists."
11594 (interactive "P")
11595 (org-export-as-html arg 'hidden)
11596 (org-open-file buffer-file-name))
11597
11598 (defun org-export-as-html-batch ()
11599 "Call `org-export-as-html', may be used in batch processing as
11600 emacs --batch
11601 --load=$HOME/lib/emacs/org.el
11602 --eval \"(setq org-export-headline-levels 2)\"
11603 --visit=MyFile --funcall org-export-as-html-batch"
11604 (org-export-as-html org-export-headline-levels 'hidden))
11605
11606 (defun org-export-as-html (arg &optional hidden)
11607 "Export the outline as a pretty HTML file.
11608 If there is an active region, export only the region.
11609 The prefix ARG specifies how many levels of the outline should become
11610 headlines. The default is 3. Lower levels will become bulleted lists."
11611 (interactive "P")
11612 (setq-default org-todo-line-regexp org-todo-line-regexp)
11613 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
11614 (setq-default org-done-string org-done-string)
11615 (let* ((style org-export-html-style)
11616 (odd org-odd-levels-only)
11617 (region-p (org-region-active-p))
11618 (region
11619 (buffer-substring
11620 (if region-p (region-beginning) (point-min))
11621 (if region-p (region-end) (point-max))))
11622 (all_lines
11623 (org-skip-comments (org-split-string
11624 (org-cleaned-string-for-export region)
11625 "[\r\n]")))
11626 (lines (org-export-find-first-heading-line all_lines))
11627 (level 0) (line "") (origline "") txt todo
11628 (umax nil)
11629 (filename (concat (file-name-sans-extension buffer-file-name)
11630 ".html"))
11631 (buffer (find-file-noselect filename))
11632 (levels-open (make-vector org-level-max nil))
11633 (date (format-time-string "%Y/%m/%d" (current-time)))
11634 (time (format-time-string "%X" (org-current-time)))
11635 (author user-full-name)
11636 (title (buffer-name))
11637 (options nil)
11638 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
11639 (inquote nil)
11640 (infixed nil)
11641 (in-local-list nil)
11642 (local-list-num nil)
11643 (local-list-indent nil)
11644 (llt org-plain-list-ordered-item-terminator)
11645 (email user-mail-address)
11646 (language org-export-default-language)
11647 (text nil)
11648 (lang-words nil)
11649 (target-alist nil) tg
11650 (head-count 0) cnt
11651 (start 0)
11652 ;; FIXME: The following returns always nil under XEmacs
11653 (coding-system (and (fboundp 'coding-system-get)
11654 (boundp 'buffer-file-coding-system)
11655 buffer-file-coding-system))
11656 (coding-system-for-write (or coding-system coding-system-for-write))
11657 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
11658 (charset (and coding-system
11659 (coding-system-get coding-system 'mime-charset)))
11660 table-open type
11661 table-buffer table-orig-buffer
11662 ind start-is-num starter
11663 rpl path desc desc1 desc2 link
11664 )
11665 (message "Exporting...")
11666
11667 (setq org-last-level 1)
11668 (org-init-section-numbers)
11669
11670 ;; Search for the export key lines
11671 (org-parse-key-lines)
11672 (setq lang-words (or (assoc language org-export-language-setup)
11673 (assoc "en" org-export-language-setup)))
11674
11675 ;; Switch to the output buffer
11676 (if (or hidden (not org-export-html-show-new-buffer))
11677 (set-buffer buffer)
11678 (switch-to-buffer-other-window buffer))
11679 (erase-buffer)
11680 (fundamental-mode)
11681 (let ((case-fold-search nil)
11682 (org-odd-levels-only odd))
11683 (if options (org-parse-export-options options))
11684 (setq umax (if arg (prefix-numeric-value arg)
11685 org-export-headline-levels))
11686
11687 ;; File header
11688 (insert (format
11689 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
11690 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
11691 <html lang=\"%s\"><head>
11692 <title>%s</title>
11693 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
11694 <meta name=generator content=\"Org-mode\">
11695 <meta name=generated content=\"%s %s\">
11696 <meta name=author content=\"%s\">
11697 %s
11698 </head><body>
11699 "
11700 language (org-html-expand title) (or charset "iso-8859-1")
11701 date time author style))
11702 (if title (insert (concat "<H1 class=\"title\">"
11703 (org-html-expand title) "</H1>\n")))
11704 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11705 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11706 email "&gt;</a>\n")))
11707 (if (or author email) (insert "<br>\n"))
11708 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11709 date " " time "<br>\n")))
11710 (if text (insert (concat "<p>\n" (org-html-expand text))))
11711 (if org-export-with-toc
11712 (progn
11713 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11714 (insert "<ul>\n")
11715 (setq lines
11716 (mapcar '(lambda (line)
11717 (if (string-match org-todo-line-regexp line)
11718 ;; This is a headline
11719 (progn
11720 (setq level (- (match-end 1) (match-beginning 1))
11721 level (org-tr-level level)
11722 txt (save-match-data
11723 (org-html-expand
11724 (match-string 3 line)))
11725 todo
11726 (or (and (match-beginning 2)
11727 (not (equal (match-string 2 line)
11728 org-done-string)))
11729 ; TODO, not DONE
11730 (and org-export-mark-todo-in-toc
11731 (= level umax)
11732 (org-search-todo-below
11733 line lines level))))
11734 (if org-export-with-section-numbers
11735 (setq txt (concat (org-section-number level)
11736 " " txt)))
11737 (if (<= level umax)
11738 (progn
11739 (setq head-count (+ head-count 1))
11740 (if (> level org-last-level)
11741 (progn
11742 (setq cnt (- level org-last-level))
11743 (while (>= (setq cnt (1- cnt)) 0)
11744 (insert "<ul>"))
11745 (insert "\n")))
11746 (if (< level org-last-level)
11747 (progn
11748 (setq cnt (- org-last-level level))
11749 (while (>= (setq cnt (1- cnt)) 0)
11750 (insert "</ul>"))
11751 (insert "\n")))
11752 ;; Check for targets
11753 (while (string-match org-target-regexp line)
11754 (setq tg (match-string 1 line)
11755 line (replace-match
11756 (concat "@<span class=\"target\">" tg "@</span> ")
11757 t t line))
11758 (push (cons (org-solidify-link-text tg)
11759 (format "sec-%d" head-count))
11760 target-alist))
11761 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11762 (setq txt (replace-match "" t t txt)))
11763 (insert
11764 (format
11765 (if todo
11766 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11767 "<li><a href=\"#sec-%d\">%s</a>\n")
11768 head-count txt))
11769
11770 (setq org-last-level level))
11771 )))
11772 line)
11773 lines))
11774 (while (> org-last-level 0)
11775 (setq org-last-level (1- org-last-level))
11776 (insert "</ul>\n"))
11777 ))
11778 (setq head-count 0)
11779 (org-init-section-numbers)
11780
11781 (while (setq line (pop lines) origline line)
11782 (catch 'nextline
11783
11784 ;; end of quote section?
11785 (when (and inquote (string-match "^\\*+" line))
11786 (insert "</pre>\n")
11787 (setq inquote nil))
11788 ;; inside a quote section?
11789 (when inquote
11790 (insert (org-html-protect line) "\n")
11791 (throw 'nextline nil))
11792
11793 ;; verbatim lines
11794 (when (and org-export-with-fixed-width
11795 (string-match "^[ \t]*:\\(.*\\)" line))
11796 (when (not infixed)
11797 (setq infixed t)
11798 (insert "<pre>\n"))
11799 (insert (org-html-protect (match-string 1 line)) "\n")
11800 (when (and lines
11801 (not (string-match "^[ \t]*\\(:.*\\)"
11802 (car lines))))
11803 (setq infixed nil)
11804 (insert "</pre>\n"))
11805 (throw 'nextline nil))
11806
11807
11808 ;; make targets to anchors
11809 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11810 (cond
11811 ((match-end 2)
11812 (setq line (replace-match
11813 (concat "@<a name=\""
11814 (org-solidify-link-text (match-string 1 line))
11815 "\">\\nbsp@</a>")
11816 t t line)))
11817 ((and org-export-with-toc (equal (string-to-char line) ?*))
11818 (setq line (replace-match
11819 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11820 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11821 t t line)))
11822 (t
11823 (setq line (replace-match
11824 (concat "@<a name=\""
11825 (org-solidify-link-text (match-string 1 line))
11826 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11827 t t line)))))
11828
11829 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11830 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11831 (setq line (org-html-expand line))
11832
11833 ;; Format the links
11834 (setq start 0)
11835 (while (string-match org-bracket-link-analytic-regexp line start)
11836 (setq start (match-beginning 0))
11837 (setq type (if (match-end 2) (match-string 2 line) "internal"))
11838 (setq path (match-string 3 line))
11839 (setq desc1 (if (match-end 5) (match-string 5 line))
11840 desc2 (if (match-end 2) (concat type ":" path) path)
11841 desc (or desc1 desc2))
11842 (cond
11843 ((equal type "internal")
11844 (setq rpl
11845 (concat
11846 "<a href=\"#"
11847 (org-solidify-link-text path target-alist)
11848 "\">" desc "</a>")))
11849 ((member type '("http" "https" "ftp" "mailto" "news"))
11850 ;; standard URL
11851 (setq link (concat type ":" path))
11852 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
11853 ((string= type "file")
11854 ;; FILE link
11855 (let* ((filename path)
11856 (abs-p (file-name-absolute-p filename))
11857 thefile file-is-image-p search)
11858 (save-match-data
11859 (if (string-match "::\\(.*\\)" filename)
11860 (setq search (match-string 1 filename)
11861 filename (replace-match "" nil nil filename)))
11862 (setq file-is-image-p
11863 (string-match (org-image-file-name-regexp) filename))
11864 (setq thefile (if abs-p (expand-file-name filename) filename))
11865 (when (and org-export-html-link-org-files-as-html
11866 (string-match "\\.org$" thefile))
11867 (setq thefile (concat (substring thefile 0
11868 (match-beginning 0))
11869 ".html"))
11870 (if (and search
11871 ;; make sure this is can be used as target search
11872 (not (string-match "^[0-9]*$" search))
11873 (not (string-match "^\\*" search))
11874 (not (string-match "^/.*/$" search)))
11875 (setq thefile (concat thefile "#"
11876 (org-solidify-link-text
11877 (org-link-unescape search)))))))
11878 (setq rpl (if (and org-export-html-inline-images
11879 file-is-image-p)
11880 (concat "<img src=\"" thefile "\"/>")
11881 (concat "<a href=\"" thefile "\">" desc "</a>")))))
11882 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11883 (setq rpl (concat "<i>&lt;" type ":"
11884 (save-match-data (org-link-unescape path))
11885 "&gt;</i>"))))
11886 (setq line (replace-match rpl t t line)
11887 start (+ start (length rpl))))
11888 ;; TODO items
11889 (if (and (string-match org-todo-line-regexp line)
11890 (match-beginning 2))
11891 (if (equal (match-string 2 line) org-done-string)
11892 (setq line (replace-match
11893 "<span class=\"done\">\\2</span>"
11894 nil nil line 2))
11895 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11896 nil nil line 2))))
11897
11898 ;; DEADLINES
11899 (if (string-match org-deadline-line-regexp line)
11900 (progn
11901 (if (save-match-data
11902 (string-match "<a href"
11903 (substring line 0 (match-beginning 0))))
11904 nil ; Don't do the replacement - it is inside a link
11905 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11906 nil nil line 1)))))
11907 (cond
11908 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11909 ;; This is a headline
11910 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11911 txt (match-string 2 line))
11912 (if (<= level umax) (setq head-count (+ head-count 1)))
11913 (when in-local-list
11914 ;; Close any local lists before inserting a new header line
11915 (while local-list-num
11916 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11917 (pop local-list-num))
11918 (setq local-list-indent nil
11919 in-local-list nil))
11920 (org-html-level-start level txt umax
11921 (and org-export-with-toc (<= level umax))
11922 head-count)
11923 ;; QUOTES
11924 (when (string-match quote-re line)
11925 (insert "<pre>")
11926 (setq inquote t)))
11927
11928 ((and org-export-with-tables
11929 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11930 (if (not table-open)
11931 ;; New table starts
11932 (setq table-open t table-buffer nil table-orig-buffer nil))
11933 ;; Accumulate lines
11934 (setq table-buffer (cons line table-buffer)
11935 table-orig-buffer (cons origline table-orig-buffer))
11936 (when (or (not lines)
11937 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11938 (car lines))))
11939 (setq table-open nil
11940 table-buffer (nreverse table-buffer)
11941 table-orig-buffer (nreverse table-orig-buffer))
11942 (insert (org-format-table-html table-buffer table-orig-buffer))))
11943 (t
11944 ;; Normal lines
11945 (when (and (string-match
11946 (cond
11947 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11948 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11949 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11950 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11951 line))
11952 (setq ind (org-get-string-indentation line)
11953 start-is-num (match-beginning 4)
11954 starter (if (match-beginning 2) (match-string 2 line))
11955 line (substring line (match-beginning 5)))
11956 (unless (string-match "[^ \t]" line)
11957 ;; empty line. Pretend indentation is large.
11958 (setq ind (1+ (or (car local-list-indent) 1))))
11959 (while (and in-local-list
11960 (or (and (= ind (car local-list-indent))
11961 (not starter))
11962 (< ind (car local-list-indent))))
11963 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11964 (pop local-list-num) (pop local-list-indent)
11965 (setq in-local-list local-list-indent))
11966 (cond
11967 ((and starter
11968 (or (not in-local-list)
11969 (> ind (car local-list-indent))))
11970 ;; Start new (level of ) list
11971 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11972 (push start-is-num local-list-num)
11973 (push ind local-list-indent)
11974 (setq in-local-list t))
11975 (starter
11976 ;; continue current list
11977 (insert "<li>\n"))))
11978 ;; Empty lines start a new paragraph. If hand-formatted lists
11979 ;; are not fully interpreted, lines starting with "-", "+", "*"
11980 ;; also start a new paragraph.
11981 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11982 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11983 ))
11984 (if org-export-html-with-timestamp
11985 (insert org-export-html-html-helper-timestamp))
11986 (insert "</body>\n</html>\n")
11987 (normal-mode)
11988 (save-buffer)
11989 (goto-char (point-min)))))
11990
11991 (defun org-format-table-html (lines olines)
11992 "Find out which HTML converter to use and return the HTML code."
11993 (if (string-match "^[ \t]*|" (car lines))
11994 ;; A normal org table
11995 (org-format-org-table-html lines)
11996 ;; Table made by table.el - test for spanning
11997 (let* ((hlines (delq nil (mapcar
11998 (lambda (x)
11999 (if (string-match "^[ \t]*\\+-" x) x
12000 nil))
12001 lines)))
12002 (first (car hlines))
12003 (ll (and (string-match "\\S-+" first)
12004 (match-string 0 first)))
12005 (re (concat "^[ \t]*" (regexp-quote ll)))
12006 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
12007 hlines))))
12008 (if (and (not spanning)
12009 (not org-export-prefer-native-exporter-for-tables))
12010 ;; We can use my own converter with HTML conversions
12011 (org-format-table-table-html lines)
12012 ;; Need to use the code generator in table.el, with the original text.
12013 (org-format-table-table-html-using-table-generate-source olines)))))
12014
12015 (defun org-format-org-table-html (lines)
12016 "Format a table into HTML."
12017 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12018 (setq lines (nreverse lines))
12019 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12020 (setq lines (nreverse lines))
12021 (when org-export-table-remove-special-lines
12022 ;; Check if the table has a marking column. If yes remove the
12023 ;; column and the special lines
12024 (let* ((special
12025 (not
12026 (memq nil
12027 (mapcar
12028 (lambda (x)
12029 (or (string-match "^[ \t]*|-" x)
12030 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
12031 lines)))))
12032 (if special
12033 (setq lines
12034 (delq nil
12035 (mapcar
12036 (lambda (x)
12037 (if (string-match "^[ \t]*| *[!_^] *|" x)
12038 nil ; ignore this line
12039 (and (or (string-match "^[ \t]*|-+\\+" x)
12040 (string-match "^[ \t]*|[^|]*|" x))
12041 (replace-match "|" t t x))))
12042 lines))))))
12043
12044 (let ((head (and org-export-highlight-first-table-line
12045 (delq nil (mapcar
12046 (lambda (x) (string-match "^[ \t]*|-" x))
12047 (cdr lines)))))
12048 line fields html)
12049 (setq html (concat org-export-html-table-tag "\n"))
12050 (while (setq line (pop lines))
12051 (catch 'next-line
12052 (if (string-match "^[ \t]*|-" line)
12053 (progn
12054 (setq head nil) ;; head ends here, first time around
12055 ;; ignore this line
12056 (throw 'next-line t)))
12057 ;; Break the line into fields
12058 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
12059 (setq html (concat
12060 html
12061 "<tr>"
12062 (mapconcat (lambda (x)
12063 (if head
12064 (concat "<th>" x "</th>")
12065 (concat "<td>" x "</td>")))
12066 fields "")
12067 "</tr>\n"))))
12068 (setq html (concat html "</table>\n"))
12069 html))
12070
12071 (defun org-fake-empty-table-line (line)
12072 "Replace everything except \"|\" with spaces."
12073 (let ((i (length line))
12074 (newstr (copy-sequence line)))
12075 (while (> i 0)
12076 (setq i (1- i))
12077 (if (not (eq (aref newstr i) ?|))
12078 (aset newstr i ?\ )))
12079 newstr))
12080
12081 (defun org-format-table-table-html (lines)
12082 "Format a table generated by table.el into HTML.
12083 This conversion does *not* use `table-generate-source' from table.el.
12084 This has the advantage that Org-mode's HTML conversions can be used.
12085 But it has the disadvantage, that no cell- or row-spanning is allowed."
12086 (let (line field-buffer
12087 (head org-export-highlight-first-table-line)
12088 fields html empty)
12089 (setq html (concat org-export-html-table-tag "\n"))
12090 (while (setq line (pop lines))
12091 (setq empty "&nbsp")
12092 (catch 'next-line
12093 (if (string-match "^[ \t]*\\+-" line)
12094 (progn
12095 (if field-buffer
12096 (progn
12097 (setq html (concat
12098 html
12099 "<tr>"
12100 (mapconcat
12101 (lambda (x)
12102 (if (equal x "") (setq x empty))
12103 (if head
12104 (concat "<th>" x "</th>\n")
12105 (concat "<td>" x "</td>\n")))
12106 field-buffer "\n")
12107 "</tr>\n"))
12108 (setq head nil)
12109 (setq field-buffer nil)))
12110 ;; Ignore this line
12111 (throw 'next-line t)))
12112 ;; Break the line into fields and store the fields
12113 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
12114 (if field-buffer
12115 (setq field-buffer (mapcar
12116 (lambda (x)
12117 (concat x "<br>" (pop fields)))
12118 field-buffer))
12119 (setq field-buffer fields))))
12120 (setq html (concat html "</table>\n"))
12121 html))
12122
12123 (defun org-format-table-table-html-using-table-generate-source (lines)
12124 "Format a table into html, using `table-generate-source' from table.el.
12125 This has the advantage that cell- or row-spanning is allowed.
12126 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
12127 (require 'table)
12128 (with-current-buffer (get-buffer-create " org-tmp1 ")
12129 (erase-buffer)
12130 (insert (mapconcat 'identity lines "\n"))
12131 (goto-char (point-min))
12132 (if (not (re-search-forward "|[^+]" nil t))
12133 (error "Error processing table"))
12134 (table-recognize-table)
12135 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
12136 (table-generate-source 'html " org-tmp2 ")
12137 (set-buffer " org-tmp2 ")
12138 (buffer-substring (point-min) (point-max))))
12139
12140 (defun org-html-protect (s)
12141 ;; convert & to &amp;, < to &lt; and > to &gt;
12142 (let ((start 0))
12143 (while (string-match "&" s start)
12144 (setq s (replace-match "&amp;" t t s)
12145 start (1+ (match-beginning 0))))
12146 (while (string-match "<" s)
12147 (setq s (replace-match "&lt;" t t s)))
12148 (while (string-match ">" s)
12149 (setq s (replace-match "&gt;" t t s))))
12150 s)
12151
12152 (defun org-html-expand (string)
12153 "Prepare STRING for HTML export. Applies all active conversions.
12154 If there are links in the string, don't modify these."
12155 (let* (m s l res)
12156 (while (setq m (string-match org-bracket-link-regexp string))
12157 (setq s (substring string 0 m)
12158 l (match-string 0 string)
12159 string (substring string (match-end 0)))
12160 (push (org-html-do-expand s) res)
12161 (push l res))
12162 (push (org-html-do-expand string) res)
12163 (apply 'concat (nreverse res))))
12164
12165 (defun org-html-do-expand (s)
12166 "Apply all active conversions to translate special ASCII to HTML."
12167 (setq s (org-html-protect s))
12168 (if org-export-html-expand
12169 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
12170 (setq s (replace-match "<\\1>" nil nil s))))
12171 (if org-export-with-emphasize
12172 (setq s (org-export-html-convert-emphasize s)))
12173 (if org-export-with-sub-superscripts
12174 (setq s (org-export-html-convert-sub-super s)))
12175 (if org-export-with-TeX-macros
12176 (let ((start 0) wd ass)
12177 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
12178 (setq wd (match-string 1 s))
12179 (if (setq ass (assoc wd org-html-entities))
12180 (setq s (replace-match (or (cdr ass)
12181 (concat "&" (car ass) ";"))
12182 t t s))
12183 (setq start (+ start (length wd)))))))
12184 s)
12185
12186 (defun org-create-multibrace-regexp (left right n)
12187 "Create a regular expression which will match a balanced sexp.
12188 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
12189 as single character strings.
12190 The regexp returned will match the entire expression including the
12191 delimiters. It will also define a single group which contains the
12192 match except for the outermost delimiters. The maximum depth of
12193 stacked delimiters is N. Escaping delimiters is not possible."
12194 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
12195 (or "\\|")
12196 (re nothing)
12197 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
12198 (while (> n 1)
12199 (setq n (1- n)
12200 re (concat re or next)
12201 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
12202 (concat left "\\(" re "\\)" right)))
12203
12204 (defvar org-match-substring-regexp
12205 (concat
12206 "\\([^\\]\\)\\([_^]\\)\\("
12207 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
12208 "\\|"
12209 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
12210 "\\|"
12211 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
12212 "The regular expression matching a sub- or superscript.")
12213
12214 (defun org-export-html-convert-sub-super (string)
12215 "Convert sub- and superscripts in STRING to HTML."
12216 (let (key c)
12217 (while (string-match org-match-substring-regexp string)
12218 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
12219 (setq c (or (match-string 8 string)
12220 (match-string 6 string)
12221 (match-string 5 string)))
12222 (setq string (replace-match
12223 (concat (match-string 1 string)
12224 "<" key ">" c "</" key ">")
12225 t t string)))
12226 (while (string-match "\\\\\\([_^]\\)" string)
12227 (setq string (replace-match (match-string 1 string) t t string))))
12228 string)
12229
12230 (defun org-export-html-convert-emphasize (string)
12231 (while (string-match org-italic-re string)
12232 (setq string (replace-match "\\1<i>\\3</i>\\4" t nil string)))
12233 (while (string-match org-bold-re string)
12234 (setq string (replace-match "\\1<b>\\3</b>\\4" t nil string)))
12235 (while (string-match org-underline-re string)
12236 (setq string (replace-match "\\1<u>\\3</u>\\4" t nil string)))
12237 string)
12238
12239 (defun org-parse-key-lines ()
12240 "Find the special key lines with the information for exporters."
12241 (save-excursion
12242 (goto-char 0)
12243 (let ((re (org-make-options-regexp
12244 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12245 key)
12246 (while (re-search-forward re nil t)
12247 (setq key (match-string 1))
12248 (cond ((string-equal key "TITLE")
12249 (setq title (match-string 2)))
12250 ((string-equal key "AUTHOR")
12251 (setq author (match-string 2)))
12252 ((string-equal key "EMAIL")
12253 (setq email (match-string 2)))
12254 ((string-equal key "LANGUAGE")
12255 (setq language (match-string 2)))
12256 ((string-equal key "TEXT")
12257 (setq text (concat text "\n" (match-string 2))))
12258 ((string-equal key "OPTIONS")
12259 (setq options (match-string 2))))))))
12260
12261 (defun org-parse-export-options (s)
12262 "Parse the export options line."
12263 (let ((op '(("H" . org-export-headline-levels)
12264 ("num" . org-export-with-section-numbers)
12265 ("toc" . org-export-with-toc)
12266 ("\\n" . org-export-preserve-breaks)
12267 ("@" . org-export-html-expand)
12268 (":" . org-export-with-fixed-width)
12269 ("|" . org-export-with-tables)
12270 ("^" . org-export-with-sub-superscripts)
12271 ("*" . org-export-with-emphasize)
12272 ("TeX" . org-export-with-TeX-macros)))
12273 o)
12274 (while (setq o (pop op))
12275 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
12276 s)
12277 (set (make-local-variable (cdr o))
12278 (car (read-from-string (match-string 1 s))))))))
12279
12280 (defun org-html-level-start (level title umax with-toc head-count)
12281 "Insert a new level in HTML export."
12282 (let ((l (1+ (max level umax))))
12283 (while (<= l org-level-max)
12284 (if (aref levels-open (1- l))
12285 (progn
12286 (org-html-level-close l)
12287 (aset levels-open (1- l) nil)))
12288 (setq l (1+ l)))
12289 (if (> level umax)
12290 (progn
12291 (if (aref levels-open (1- level))
12292 (insert "<li>" title "<p>\n")
12293 (aset levels-open (1- level) t)
12294 (insert "<ul><li>" title "<p>\n")))
12295 (if org-export-with-section-numbers
12296 (setq title (concat (org-section-number level) " " title)))
12297 (setq level (+ level 1))
12298 (if with-toc
12299 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
12300 level head-count title level))
12301 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
12302
12303 (defun org-html-level-close (&rest args)
12304 "Terminate one level in HTML export."
12305 (insert "</ul>"))
12306
12307 ;; Variable holding the vector with section numbers
12308 (defvar org-section-numbers (make-vector org-level-max 0))
12309
12310 (defun org-init-section-numbers ()
12311 "Initialize the vector for the section numbers."
12312 (let* ((level -1)
12313 (numbers (nreverse (org-split-string "" "\\.")))
12314 (depth (1- (length org-section-numbers)))
12315 (i depth) number-string)
12316 (while (>= i 0)
12317 (if (> i level)
12318 (aset org-section-numbers i 0)
12319 (setq number-string (or (car numbers) "0"))
12320 (if (string-match "\\`[A-Z]\\'" number-string)
12321 (aset org-section-numbers i
12322 (- (string-to-char number-string) ?A -1))
12323 (aset org-section-numbers i (string-to-number number-string)))
12324 (pop numbers))
12325 (setq i (1- i)))))
12326
12327 (defun org-section-number (&optional level)
12328 "Return a string with the current section number.
12329 When LEVEL is non-nil, increase section numbers on that level."
12330 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
12331 (when level
12332 (when (> level -1)
12333 (aset org-section-numbers
12334 level (1+ (aref org-section-numbers level))))
12335 (setq idx (1+ level))
12336 (while (<= idx depth)
12337 (if (not (= idx 1))
12338 (aset org-section-numbers idx 0))
12339 (setq idx (1+ idx))))
12340 (setq idx 0)
12341 (while (<= idx depth)
12342 (setq n (aref org-section-numbers idx))
12343 (setq string (concat string (if (not (string= string "")) "." "")
12344 (int-to-string n)))
12345 (setq idx (1+ idx)))
12346 (save-match-data
12347 (if (string-match "\\`\\([@0]\\.\\)+" string)
12348 (setq string (replace-match "" nil nil string)))
12349 (if (string-match "\\(\\.0\\)+\\'" string)
12350 (setq string (replace-match "" nil nil string))))
12351 string))
12352
12353
12354 (defun org-export-icalendar-this-file ()
12355 "Export current file as an iCalendar file.
12356 The iCalendar file will be located in the same directory as the Org-mode
12357 file, but with extension `.ics'."
12358 (interactive)
12359 (org-export-icalendar nil buffer-file-name))
12360
12361 (defun org-export-as-xml ()
12362 "Export current buffer as XOXO XML buffer."
12363 (interactive)
12364 (cond ((eq org-export-xml-type 'xoxo)
12365 (org-export-as-xoxo (current-buffer)))))
12366
12367 (defun org-export-as-xoxo-insert-into (buffer &rest output)
12368 (with-current-buffer buffer
12369 (apply 'insert output)))
12370
12371 (defun org-export-as-xoxo (&optional buffer)
12372 "Export the org buffer as XOXO.
12373 The XOXO buffer is named *xoxo-<source buffer name>*"
12374 (interactive (list (current-buffer)))
12375 ;; A quickie abstraction
12376
12377 ;; Output everything as XOXO
12378 (with-current-buffer (get-buffer buffer)
12379 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
12380 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
12381 ".xml"))
12382 (out (find-file-noselect filename))
12383 (last-level 1)
12384 (hanging-li nil))
12385 ;; Check the output buffer is empty.
12386 (with-current-buffer out (erase-buffer))
12387 ;; Kick off the output
12388 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
12389 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
12390 (let* ((hd (match-string-no-properties 1))
12391 (level (length hd))
12392 (text (concat
12393 (match-string-no-properties 2)
12394 (save-excursion
12395 (goto-char (match-end 0))
12396 (let ((str ""))
12397 (catch 'loop
12398 (while 't
12399 (forward-line)
12400 (if (looking-at "^[ \t]\\(.*\\)")
12401 (setq str (concat str (match-string-no-properties 1)))
12402 (throw 'loop str)))))))))
12403
12404 ;; Handle level rendering
12405 (cond
12406 ((> level last-level)
12407 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
12408
12409 ((< level last-level)
12410 (dotimes (- (- last-level level) 1)
12411 (if hanging-li
12412 (org-export-as-xoxo-insert-into out "</li>\n"))
12413 (org-export-as-xoxo-insert-into out "</ol>\n"))
12414 (when hanging-li
12415 (org-export-as-xoxo-insert-into out "</li>\n")
12416 (setq hanging-li nil)))
12417
12418 ((equal level last-level)
12419 (if hanging-li
12420 (org-export-as-xoxo-insert-into out "</li>\n")))
12421 )
12422
12423 (setq last-level level)
12424
12425 ;; And output the new li
12426 (setq hanging-li 't)
12427 (if (equal ?+ (elt text 0))
12428 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
12429 (org-export-as-xoxo-insert-into out "<li>" text))))
12430
12431 ;; Finally finish off the ol
12432 (dotimes (- last-level 1)
12433 (if hanging-li
12434 (org-export-as-xoxo-insert-into out "</li>\n"))
12435 (org-export-as-xoxo-insert-into out "</ol>\n"))
12436
12437 ;; Finish the buffer off and clean it up.
12438 (switch-to-buffer-other-window out)
12439 (indent-region (point-min) (point-max) nil)
12440 (save-buffer)
12441 (goto-char (point-min))
12442 )))
12443
12444 ;;;###autoload
12445 (defun org-export-icalendar-all-agenda-files ()
12446 "Export all files in `org-agenda-files' to iCalendar .ics files.
12447 Each iCalendar file will be located in the same directory as the Org-mode
12448 file, but with extension `.ics'."
12449 (interactive)
12450 (apply 'org-export-icalendar nil (org-agenda-files t)))
12451
12452 ;;;###autoload
12453 (defun org-export-icalendar-combine-agenda-files ()
12454 "Export all files in `org-agenda-files' to a single combined iCalendar file.
12455 The file is stored under the name `org-combined-agenda-icalendar-file'."
12456 (interactive)
12457 (apply 'org-export-icalendar t (org-agenda-files t)))
12458
12459 (defun org-export-icalendar (combine &rest files)
12460 "Create iCalendar files for all elements of FILES.
12461 If COMBINE is non-nil, combine all calendar entries into a single large
12462 file and store it under the name `org-combined-agenda-icalendar-file'."
12463 (save-excursion
12464 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
12465 (when combine
12466 (setq ical-file org-combined-agenda-icalendar-file
12467 ical-buffer (org-get-agenda-file-buffer ical-file))
12468 (set-buffer ical-buffer) (erase-buffer))
12469 (while (setq file (pop files))
12470 (catch 'nextfile
12471 (org-check-agenda-file file)
12472 (unless combine
12473 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
12474 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
12475 (set-buffer ical-buffer) (erase-buffer))
12476 (set-buffer (org-get-agenda-file-buffer file))
12477 (setq category (or org-category
12478 (file-name-sans-extension
12479 (file-name-nondirectory buffer-file-name))))
12480 (if (symbolp category) (setq category (symbol-name category)))
12481 (let ((standard-output ical-buffer))
12482 (if combine
12483 (and (not started) (setq started t)
12484 (org-start-icalendar-file org-icalendar-combined-name))
12485 (org-start-icalendar-file category))
12486 (org-print-icalendar-entries combine category)
12487 (when (or (and combine (not files)) (not combine))
12488 (org-finish-icalendar-file)
12489 (set-buffer ical-buffer)
12490 (save-buffer)
12491 (run-hooks 'org-after-save-iCalendar-file-hook)))))
12492 (org-release-buffers org-agenda-new-buffers))))
12493
12494 (defvar org-after-save-iCalendar-file-hook nil
12495 "Hook run after an iCalendar file has been saved.
12496 The iCalendar buffer is still current when this hook is run.
12497 A good way to use this is to tell a desktop calenndar application to re-read
12498 the iCalendar file.")
12499
12500 (defun org-print-icalendar-entries (&optional combine category)
12501 "Print iCalendar entries for the current Org-mode file to `standard-output'.
12502 When COMBINE is non nil, add the category to each line."
12503 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
12504 (dts (org-ical-ts-to-string
12505 (format-time-string (cdr org-time-stamp-formats) (current-time))
12506 "DTSTART"))
12507 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
12508 (save-excursion
12509 (goto-char (point-min))
12510 (while (re-search-forward org-ts-regexp nil t)
12511 (setq pos (match-beginning 0)
12512 ts (match-string 0)
12513 inc t
12514 hd (org-get-heading))
12515 (if (looking-at re2)
12516 (progn
12517 (goto-char (match-end 0))
12518 (setq ts2 (match-string 1) inc nil))
12519 (setq ts2 ts
12520 tmp (buffer-substring (max (point-min)
12521 (- pos org-ds-keyword-length))
12522 pos)
12523 deadlinep (string-match org-deadline-regexp tmp)
12524 scheduledp (string-match org-scheduled-regexp tmp)
12525 ;; donep (org-entry-is-done-p)
12526 ))
12527 (if (or (string-match org-tr-regexp hd)
12528 (string-match org-ts-regexp hd))
12529 (setq hd (replace-match "" t t hd)))
12530 (if combine
12531 (setq hd (concat hd " (category " category ")")))
12532 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
12533 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
12534 (princ (format "BEGIN:VEVENT
12535 %s
12536 %s
12537 SUMMARY:%s
12538 END:VEVENT\n"
12539 (org-ical-ts-to-string ts "DTSTART")
12540 (org-ical-ts-to-string ts2 "DTEND" inc)
12541 hd)))
12542 (when org-icalendar-include-todo
12543 (goto-char (point-min))
12544 (while (re-search-forward org-todo-line-regexp nil t)
12545 (setq state (match-string 1))
12546 (unless (equal state org-done-string)
12547 (setq hd (match-string 3))
12548 (if (string-match org-priority-regexp hd)
12549 (setq pri (string-to-char (match-string 2 hd))
12550 hd (concat (substring hd 0 (match-beginning 1))
12551 (substring hd (- (match-end 1)))))
12552 (setq pri org-default-priority))
12553 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
12554 (- org-lowest-priority ?A))))))
12555
12556 (princ (format "BEGIN:VTODO
12557 %s
12558 SUMMARY:%s
12559 SEQUENCE:1
12560 PRIORITY:%d
12561 END:VTODO\n"
12562 dts hd pri))))))))
12563
12564 (defun org-start-icalendar-file (name)
12565 "Start an iCalendar file by inserting the header."
12566 (let ((user user-full-name)
12567 (name (or name "unknown"))
12568 (timezone (cadr (current-time-zone))))
12569 (princ
12570 (format "BEGIN:VCALENDAR
12571 VERSION:2.0
12572 X-WR-CALNAME:%s
12573 PRODID:-//%s//Emacs with Org-mode//EN
12574 X-WR-TIMEZONE:%s
12575 CALSCALE:GREGORIAN\n" name user timezone))))
12576
12577 (defun org-finish-icalendar-file ()
12578 "Finish an iCalendar file by inserting the END statement."
12579 (princ "END:VCALENDAR\n"))
12580
12581 (defun org-ical-ts-to-string (s keyword &optional inc)
12582 "Take a time string S and convert it to iCalendar format.
12583 KEYWORD is added in front, to make a complete line like DTSTART....
12584 When INC is non-nil, increase the hour by two (if time string contains
12585 a time), or the day by one (if it does not contain a time)."
12586 (let ((t1 (org-parse-time-string s 'nodefault))
12587 t2 fmt have-time time)
12588 (if (and (car t1) (nth 1 t1) (nth 2 t1))
12589 (setq t2 t1 have-time t)
12590 (setq t2 (org-parse-time-string s)))
12591 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
12592 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
12593 (when inc
12594 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
12595 (setq time (encode-time s mi h d m y)))
12596 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
12597 (concat keyword (format-time-string fmt time))))
12598
12599
12600 ;;; Key bindings
12601
12602 ;; - Bindings in Org-mode map are currently
12603 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
12604 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
12605 ;; e (?) useful from outline-mode
12606 ;; i k @ expendable from outline-mode
12607 ;; 0123456789 % & ()_{} " ` free
12608
12609 ;; Make `C-c C-x' a prefix key
12610 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
12611
12612 ;; TAB key with modifiers
12613 (define-key org-mode-map "\C-i" 'org-cycle)
12614 (define-key org-mode-map [(tab)] 'org-cycle)
12615 (define-key org-mode-map [(meta tab)] 'org-complete)
12616 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
12617 ;; The following line is necessary under Suse GNU/Linux
12618 (unless (featurep 'xemacs)
12619 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
12620 (define-key org-mode-map [(shift tab)] 'org-shifttab)
12621
12622 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
12623 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
12624 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12625 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
12626 (define-key org-mode-map [(meta return)] 'org-meta-return)
12627 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
12628 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
12629
12630 ;; Cursor keys with modifiers
12631 (define-key org-mode-map [(meta left)] 'org-metaleft)
12632 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
12633 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
12634 (define-key org-mode-map [(meta right)] 'org-metaright)
12635 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
12636 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
12637 (define-key org-mode-map [(meta up)] 'org-metaup)
12638 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
12639 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
12640 (define-key org-mode-map [(meta down)] 'org-metadown)
12641 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
12642 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
12643
12644 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12645 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
12646 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
12647 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
12648 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
12649 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
12650 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
12651 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
12652 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
12653 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
12654 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
12655 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
12656 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
12657 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
12658 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
12659 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
12660
12661 ;; All the other keys
12662
12663 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12664 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
12665 (define-key org-mode-map "\C-c\C-j" 'org-goto)
12666 (define-key org-mode-map "\C-c\C-t" 'org-todo)
12667 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
12668 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
12669 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
12670 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12671 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
12672 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
12673 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12674 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
12675 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
12676 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
12677 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
12678 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
12679 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
12680 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
12681 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12682 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12683 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12684 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12685 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
12686 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
12687 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12688 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
12689 (define-key org-mode-map "\C-c]" 'org-remove-file)
12690 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
12691 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
12692 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
12693 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12694 (define-key org-mode-map "\C-m" 'org-return)
12695 (define-key org-mode-map "\C-c?" 'org-table-current-column)
12696 (define-key org-mode-map "\C-c " 'org-table-blank-field)
12697 (define-key org-mode-map "\C-c+" 'org-table-sum)
12698 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
12699 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
12700 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
12701 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12702 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
12703 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12704 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
12705 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12706 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
12707 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
12708 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
12709 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
12710 ;; OPML support is only an option for the future
12711 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
12712 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
12713 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
12714 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
12715 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
12716 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
12717 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
12718 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12719 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
12720 (define-key org-mode-map "\C-c\C-xx" 'org-export-as-xml)
12721 (define-key org-mode-map "\C-c\C-x\C-x" 'org-export-as-xml)
12722 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
12723 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
12724
12725 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12726 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12727 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12728 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12729
12730 (defsubst org-table-p () (org-at-table-p))
12731
12732 (defun org-self-insert-command (N)
12733 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12734 If the cursor is in a table looking at whitespace, the whitespace is
12735 overwritten, and the table is not marked as requiring realignment."
12736 (interactive "p")
12737 (if (and (org-table-p)
12738 (progn
12739 ;; check if we blank the field, and if that triggers align
12740 (and org-table-auto-blank-field
12741 (member last-command
12742 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12743 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12744 ;; got extra space, this field does not determine column width
12745 (let (org-table-may-need-update) (org-table-blank-field))
12746 ;; no extra space, this field may determine column width
12747 (org-table-blank-field)))
12748 t)
12749 (eq N 1)
12750 (looking-at "[^|\n]* |"))
12751 (let (org-table-may-need-update)
12752 (goto-char (1- (match-end 0)))
12753 (delete-backward-char 1)
12754 (goto-char (match-beginning 0))
12755 (self-insert-command N))
12756 (setq org-table-may-need-update t)
12757 (self-insert-command N)))
12758
12759 (defun org-delete-backward-char (N)
12760 "Like `delete-backward-char', insert whitespace at field end in tables.
12761 When deleting backwards, in tables this function will insert whitespace in
12762 front of the next \"|\" separator, to keep the table aligned. The table will
12763 still be marked for re-alignment if the field did fill the entire column,
12764 because, in this case the deletion might narrow the column."
12765 (interactive "p")
12766 (if (and (org-table-p)
12767 (eq N 1)
12768 (string-match "|" (buffer-substring (point-at-bol) (point)))
12769 (looking-at ".*?|"))
12770 (let ((pos (point))
12771 (noalign (looking-at "[^|\n\r]* |"))
12772 (c org-table-may-need-update))
12773 (backward-delete-char N)
12774 (skip-chars-forward "^|")
12775 (insert " ")
12776 (goto-char (1- pos))
12777 ;; noalign: if there were two spaces at the end, this field
12778 ;; does not determine the width of the column.
12779 (if noalign (setq org-table-may-need-update c)))
12780 (backward-delete-char N)))
12781
12782 (defun org-delete-char (N)
12783 "Like `delete-char', but insert whitespace at field end in tables.
12784 When deleting characters, in tables this function will insert whitespace in
12785 front of the next \"|\" separator, to keep the table aligned. The table will
12786 still be marked for re-alignment if the field did fill the entire column,
12787 because, in this case the deletion might narrow the column."
12788 (interactive "p")
12789 (if (and (org-table-p)
12790 (not (bolp))
12791 (not (= (char-after) ?|))
12792 (eq N 1))
12793 (if (looking-at ".*?|")
12794 (let ((pos (point))
12795 (noalign (looking-at "[^|\n\r]* |"))
12796 (c org-table-may-need-update))
12797 (replace-match (concat
12798 (substring (match-string 0) 1 -1)
12799 " |"))
12800 (goto-char pos)
12801 ;; noalign: if there were two spaces at the end, this field
12802 ;; does not determine the width of the column.
12803 (if noalign (setq org-table-may-need-update c))))
12804 (delete-char N)))
12805
12806 ;; How to do this: Measure non-white length of current string
12807 ;; If equal to column width, we should realign.
12808
12809 (defun org-remap (map &rest commands)
12810 "In MAP, remap the functions given in COMMANDS.
12811 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12812 (let (new old)
12813 (while commands
12814 (setq old (pop commands) new (pop commands))
12815 (if (fboundp 'command-remapping)
12816 (define-key map (vector 'remap old) new)
12817 (substitute-key-definition old new map global-map)))))
12818
12819 (when (eq org-enable-table-editor 'optimized)
12820 ;; If the user wants maximum table support, we need to hijack
12821 ;; some standard editing functions
12822 (org-remap org-mode-map
12823 'self-insert-command 'org-self-insert-command
12824 'delete-char 'org-delete-char
12825 'delete-backward-char 'org-delete-backward-char)
12826 (define-key org-mode-map "|" 'org-force-self-insert))
12827
12828 (defun org-shiftcursor-error ()
12829 "Throw an error because Shift-Cursor command was applied in wrong context."
12830 (error "This command is active in special context like tables, headlines or timestamps"))
12831
12832 (defun org-shifttab ()
12833 "Global visibility cycling or move to previous table field.
12834 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12835 See the individual commands for more information."
12836 (interactive)
12837 (cond
12838 ((org-at-table-p) (org-table-previous-field))
12839 (t (org-cycle '(4)))))
12840
12841 (defun org-shiftmetaleft ()
12842 "Promote subtree or delete table column.
12843 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12844 See the individual commands for more information."
12845 (interactive)
12846 (cond
12847 ((org-at-table-p) (org-table-delete-column))
12848 ((org-on-heading-p) (org-promote-subtree))
12849 ((org-at-item-p) (call-interactively 'org-outdent-item))
12850 (t (org-shiftcursor-error))))
12851
12852 (defun org-shiftmetaright ()
12853 "Demote subtree or insert table column.
12854 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12855 See the individual commands for more information."
12856 (interactive)
12857 (cond
12858 ((org-at-table-p) (org-table-insert-column))
12859 ((org-on-heading-p) (org-demote-subtree))
12860 ((org-at-item-p) (call-interactively 'org-indent-item))
12861 (t (org-shiftcursor-error))))
12862
12863 (defun org-shiftmetaup (&optional arg)
12864 "Move subtree up or kill table row.
12865 Calls `org-move-subtree-up' or `org-table-kill-row' or
12866 `org-move-item-up' depending on context. See the individual commands
12867 for more information."
12868 (interactive "P")
12869 (cond
12870 ((org-at-table-p) (org-table-kill-row))
12871 ((org-on-heading-p) (org-move-subtree-up arg))
12872 ((org-at-item-p) (org-move-item-up arg))
12873 (t (org-shiftcursor-error))))
12874 (defun org-shiftmetadown (&optional arg)
12875 "Move subtree down or insert table row.
12876 Calls `org-move-subtree-down' or `org-table-insert-row' or
12877 `org-move-item-down', depending on context. See the individual
12878 commands for more information."
12879 (interactive "P")
12880 (cond
12881 ((org-at-table-p) (org-table-insert-row arg))
12882 ((org-on-heading-p) (org-move-subtree-down arg))
12883 ((org-at-item-p) (org-move-item-down arg))
12884 (t (org-shiftcursor-error))))
12885
12886 (defun org-metaleft (&optional arg)
12887 "Promote heading or move table column to left.
12888 Calls `org-do-promote' or `org-table-move-column', depending on context.
12889 With no specific context, calls the Emacs default `backward-word'.
12890 See the individual commands for more information."
12891 (interactive "P")
12892 (cond
12893 ((org-at-table-p) (org-table-move-column 'left))
12894 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12895 (t (backward-word (prefix-numeric-value arg)))))
12896
12897 (defun org-metaright (&optional arg)
12898 "Demote subtree or move table column to right.
12899 Calls `org-do-demote' or `org-table-move-column', depending on context.
12900 With no specific context, calls the Emacs default `forward-word'.
12901 See the individual commands for more information."
12902 (interactive "P")
12903 (cond
12904 ((org-at-table-p) (org-table-move-column nil))
12905 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12906 (t (forward-word (prefix-numeric-value arg)))))
12907
12908 (defun org-metaup (&optional arg)
12909 "Move subtree up or move table row up.
12910 Calls `org-move-subtree-up' or `org-table-move-row' or
12911 `org-move-item-up', depending on context. See the individual commands
12912 for more information."
12913 (interactive "P")
12914 (cond
12915 ((org-at-table-p) (org-table-move-row 'up))
12916 ((org-on-heading-p) (org-move-subtree-up arg))
12917 ((org-at-item-p) (org-move-item-up arg))
12918 (t (org-shiftcursor-error))))
12919
12920 (defun org-metadown (&optional arg)
12921 "Move subtree down or move table row down.
12922 Calls `org-move-subtree-down' or `org-table-move-row' or
12923 `org-move-item-down', depending on context. See the individual
12924 commands for more information."
12925 (interactive "P")
12926 (cond
12927 ((org-at-table-p) (org-table-move-row nil))
12928 ((org-on-heading-p) (org-move-subtree-down arg))
12929 ((org-at-item-p) (org-move-item-down arg))
12930 (t (org-shiftcursor-error))))
12931
12932 (defun org-shiftup (&optional arg)
12933 "Increase item in timestamp or increase priority of current item.
12934 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12935 See the individual commands for more information."
12936 (interactive "P")
12937 (cond
12938 ((org-at-timestamp-p) (org-timestamp-up arg))
12939 (t (org-priority-up))))
12940
12941 (defun org-shiftdown (&optional arg)
12942 "Decrease item in timestamp or decrease priority of current item.
12943 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12944 See the individual commands for more information."
12945 (interactive "P")
12946 (cond
12947 ((org-at-timestamp-p) (org-timestamp-down arg))
12948 (t (org-priority-down))))
12949
12950 (defun org-shiftright ()
12951 "Next TODO keyword or timestamp one day later, depending on context."
12952 (interactive)
12953 (cond
12954 ((org-at-timestamp-p) (org-timestamp-up-day))
12955 ((org-on-heading-p) (org-todo 'right))
12956 (t (org-shiftcursor-error))))
12957
12958 (defun org-shiftleft ()
12959 "Previous TODO keyword or timestamp one day earlier, depending on context."
12960 (interactive)
12961 (cond
12962 ((org-at-timestamp-p) (org-timestamp-down-day))
12963 ((org-on-heading-p) (org-todo 'left))
12964 (t (org-shiftcursor-error))))
12965
12966 (defun org-copy-special ()
12967 "Copy region in table or copy current subtree.
12968 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12969 See the individual commands for more information."
12970 (interactive)
12971 (call-interactively
12972 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12973
12974 (defun org-cut-special ()
12975 "Cut region in table or cut current subtree.
12976 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12977 See the individual commands for more information."
12978 (interactive)
12979 (call-interactively
12980 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12981
12982 (defun org-paste-special (arg)
12983 "Paste rectangular region into table, or past subtree relative to level.
12984 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12985 See the individual commands for more information."
12986 (interactive "P")
12987 (if (org-at-table-p)
12988 (org-table-paste-rectangle)
12989 (org-paste-subtree arg)))
12990
12991 (defun org-ctrl-c-ctrl-c (&optional arg)
12992 "Set tags in headline, or update according to changed information at point.
12993
12994 This command does many different things, depending on context:
12995
12996 - If the cursor is in a headline, prompt for tags and insert them
12997 into the current line, aligned to `org-tags-column'. When called
12998 with prefix arg, realign all tags in the current buffer.
12999
13000 - If the cursor is in one of the special #+KEYWORD lines, this
13001 triggers scanning the buffer for these lines and updating the
13002 information.
13003
13004 - If the cursor is inside a table, realign the table. This command
13005 works even if the automatic table editor has been turned off.
13006
13007 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13008 the entire table.
13009
13010 - If the cursor is inside a table created by the table.el package,
13011 activate that table.
13012
13013 - If the current buffer is a remember buffer, close note and file it.
13014 with a prefix argument, file it without further interaction to the default
13015 location.
13016
13017 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13018 links in this buffer.
13019
13020 - If the cursor is on a numbered item in a plain list, renumber the
13021 ordered list."
13022 (interactive "P")
13023 (let ((org-enable-table-editor t))
13024 (cond
13025 ((and (local-variable-p 'org-finish-function (current-buffer))
13026 (fboundp org-finish-function))
13027 (funcall org-finish-function))
13028 ((org-on-target-p) (org-update-radio-target-regexp))
13029 ((org-on-heading-p) (org-set-tags arg))
13030 ((org-at-table.el-p)
13031 (require 'table)
13032 (beginning-of-line 1)
13033 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13034 (table-recognize-table))
13035 ((org-at-table-p)
13036 (org-table-maybe-eval-formula)
13037 (if arg
13038 (org-table-recalculate t)
13039 (org-table-maybe-recalculate-line))
13040 (org-table-align))
13041 ((org-at-item-p)
13042 (org-renumber-ordered-list (prefix-numeric-value arg)))
13043 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13044 (cond
13045 ((equal (match-string 1) "TBLFM")
13046 ;; Recalculate the table before this line
13047 (save-excursion
13048 (beginning-of-line 1)
13049 (skip-chars-backward " \r\n\t")
13050 (if (org-at-table-p) (org-table-recalculate t))))
13051 (t
13052 (org-mode-restart))))
13053 (t (error "C-c C-c can do nothing useful at this location.")))))
13054
13055 (defun org-mode-restart ()
13056 "Restart Org-mode, to scan again for special lines.
13057 Also updates the keyword regular expressions."
13058 (interactive)
13059 (let ((org-inhibit-startup t)) (org-mode))
13060 (message "Org-mode restarted to refresh keyword and special line setup"))
13061
13062 (defun org-return ()
13063 "Goto next table row or insert a newline.
13064 Calls `org-table-next-row' or `newline', depending on context.
13065 See the individual commands for more information."
13066 (interactive)
13067 (cond
13068 ((org-at-table-p)
13069 (org-table-justify-field-maybe)
13070 (org-table-next-row))
13071 (t (newline))))
13072
13073 (defun org-meta-return (&optional arg)
13074 "Insert a new heading or wrap a region in a table.
13075 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13076 See the individual commands for more information."
13077 (interactive "P")
13078 (cond
13079 ((org-at-table-p)
13080 (org-table-wrap-region arg))
13081 (t (org-insert-heading arg))))
13082
13083 ;;; Menu entries
13084
13085 ;; Define the Org-mode menus
13086 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13087 '("Tbl"
13088 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
13089 ["Next Field" org-cycle (org-at-table-p)]
13090 ["Previous Field" org-shifttab (org-at-table-p)]
13091 ["Next Row" org-return (org-at-table-p)]
13092 "--"
13093 ["Blank Field" org-table-blank-field (org-at-table-p)]
13094 ["Edit Field" org-table-edit-field (org-at-table-p)]
13095 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13096 "--"
13097 ("Column"
13098 ["Move Column Left" org-metaleft (org-at-table-p)]
13099 ["Move Column Right" org-metaright (org-at-table-p)]
13100 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13101 ["Insert Column" org-shiftmetaright (org-at-table-p)]
13102 "--"
13103 ["Enable Narrowing" (setq org-table-limit-column-width (not org-table-limit-column-width)) :active (org-at-table-p) :selected org-table-limit-column-width :style toggle])
13104 ("Row"
13105 ["Move Row Up" org-metaup (org-at-table-p)]
13106 ["Move Row Down" org-metadown (org-at-table-p)]
13107 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13108 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13109 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13110 "--"
13111 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
13112 ("Rectangle"
13113 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13114 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13115 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13116 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13117 "--"
13118 ("Calculate"
13119 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13120 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13121 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
13122 "--"
13123 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13124 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13125 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13126 "--"
13127 ["Sum Column/Rectangle" org-table-sum
13128 (or (org-at-table-p) (org-region-active-p))]
13129 ["Which Column?" org-table-current-column (org-at-table-p)])
13130 ["Debug Formulas"
13131 (setq org-table-formula-debug (not org-table-formula-debug))
13132 :style toggle :selected org-table-formula-debug]
13133 "--"
13134 ["Create" org-table-create (and (not (org-at-table-p))
13135 org-enable-table-editor)]
13136 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13137 ["Import from File" org-table-import (not (org-at-table-p))]
13138 ["Export to File" org-table-export (org-at-table-p)]
13139 "--"
13140 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13141
13142 (easy-menu-define org-org-menu org-mode-map "Org menu"
13143 '("Org"
13144 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
13145 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
13146 ["Sparse Tree" org-occur t]
13147 ["Show All" show-all t]
13148 "--"
13149 ["New Heading" org-insert-heading t]
13150 ("Navigate Headings"
13151 ["Up" outline-up-heading t]
13152 ["Next" outline-next-visible-heading t]
13153 ["Previous" outline-previous-visible-heading t]
13154 ["Next Same Level" outline-forward-same-level t]
13155 ["Previous Same Level" outline-backward-same-level t]
13156 "--"
13157 ["Jump" org-goto t])
13158 ("Edit Structure"
13159 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13160 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13161 "--"
13162 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13163 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13164 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13165 "--"
13166 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13167 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13168 ["Demote Heading" org-metaright (not (org-at-table-p))]
13169 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13170 "--"
13171 ["Archive Subtree" org-archive-subtree t]
13172 "--"
13173 ["Convert to odd levels" org-convert-to-odd-levels t]
13174 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13175 "--"
13176 ("TODO Lists"
13177 ["TODO/DONE/-" org-todo t]
13178 ["Show TODO Tree" org-show-todo-tree t]
13179 ["Global TODO list" org-todo-list t]
13180 "--"
13181 ["Set Priority" org-priority t]
13182 ["Priority Up" org-shiftup t]
13183 ["Priority Down" org-shiftdown t])
13184 ("Dates and Scheduling"
13185 ["Timestamp" org-time-stamp t]
13186 ["Timestamp (inactive)" org-time-stamp-inactive t]
13187 ("Change Date"
13188 ["1 Day Later" org-timestamp-up-day t]
13189 ["1 Day Earlier" org-timestamp-down-day t]
13190 ["1 ... Later" org-shiftup t]
13191 ["1 ... Earlier" org-shiftdown t])
13192 ["Compute Time Range" org-evaluate-time-range t]
13193 ["Schedule Item" org-schedule t]
13194 ["Deadline" org-deadline t]
13195 "--"
13196 ["Goto Calendar" org-goto-calendar t]
13197 ["Date from Calendar" org-date-from-calendar t])
13198 "--"
13199 ["Agenda Command" org-agenda t]
13200 ("File List for Agenda")
13201 ("Special views current file"
13202 ["TODO Tree" org-show-todo-tree t]
13203 ["Check Deadlines" org-check-deadlines t]
13204 ["Timeline" org-timeline t]
13205 ["Tags Tree" org-tags-sparse-tree t])
13206 "--"
13207 ("Hyperlinks"
13208 ["Store Link (Global)" org-store-link t]
13209 ["Insert Link" org-insert-link t]
13210 ["Follow Link" org-open-at-point t]
13211 "--"
13212 ["Descriptive Links"
13213 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13214 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
13215 ["Literal Links"
13216 (progn
13217 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13218 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
13219 "--"
13220 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
13221 (save-excursion (goto-char (point-min))
13222 (re-search-forward "<[a-z]+:" nil t))])
13223 "--"
13224 ("Export"
13225 ["ASCII" org-export-as-ascii t]
13226 ["Extract Visible Text" org-export-copy-visible t]
13227 ["HTML" org-export-as-html t]
13228 ["HTML and Open" org-export-as-html-and-open t]
13229 ["XML (XOXO)" org-export-as-xml t]
13230 "--"
13231 ["iCalendar this file" org-export-icalendar-this-file t]
13232 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
13233 :active t :keys "C-c C-x C-i"]
13234 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
13235 "--"
13236 ["Option Template" org-insert-export-options-template t]
13237 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
13238 "--"
13239 ("Documentation"
13240 ["Show Version" org-version t]
13241 ["Info Documentation" org-info t])
13242 ("Customize"
13243 ["Browse Org Group" org-customize t]
13244 "--"
13245 ["Expand This Menu" org-create-customize-menu
13246 (fboundp 'customize-menu-create)])
13247 "--"
13248 ["Refresh setup" org-mode-restart t]
13249 ))
13250
13251 (defun org-info (&optional node)
13252 "Read documentation for Org-mode in the info system.
13253 With optional NODE, go directly to that node."
13254 (interactive)
13255 (require 'info)
13256 (Info-goto-node (format "(org)%s" (or node ""))))
13257
13258 (defun org-install-agenda-files-menu ()
13259 (let ((bl (buffer-list)))
13260 (save-excursion
13261 (while bl
13262 (set-buffer (pop bl))
13263 (if (eq major-mode 'org-mode) (setq bl nil)))
13264 (when (eq major-mode 'org-mode)
13265 (easy-menu-change
13266 '("Org") "File List for Agenda"
13267 (append
13268 (list
13269 ["Edit File List" (org-edit-agenda-file-list) t]
13270 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13271 ["Remove Current File from List" org-remove-file t]
13272 ["Cycle through agenda files" org-cycle-agenda-files t]
13273 "--")
13274 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13275
13276 ;;; Documentation
13277
13278 (defun org-customize ()
13279 "Call the customize function with org as argument."
13280 (interactive)
13281 (customize-browse 'org))
13282
13283 (defun org-create-customize-menu ()
13284 "Create a full customization menu for Org-mode, insert it into the menu."
13285 (interactive)
13286 (if (fboundp 'customize-menu-create)
13287 (progn
13288 (easy-menu-change
13289 '("Org") "Customize"
13290 `(["Browse Org group" org-customize t]
13291 "--"
13292 ,(customize-menu-create 'org)
13293 ["Set" Custom-set t]
13294 ["Save" Custom-save t]
13295 ["Reset to Current" Custom-reset-current t]
13296 ["Reset to Saved" Custom-reset-saved t]
13297 ["Reset to Standard Settings" Custom-reset-standard t]))
13298 (message "\"Org\"-menu now contains full customization menu"))
13299 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13300
13301 ;;; Miscellaneous stuff
13302
13303 (defun org-move-line-down (arg)
13304 "Move the current line down. With prefix argument, move it past ARG lines."
13305 (interactive "p")
13306 (let ((col (current-column))
13307 beg end pos)
13308 (beginning-of-line 1) (setq beg (point))
13309 (beginning-of-line 2) (setq end (point))
13310 (beginning-of-line (+ 1 arg))
13311 (setq pos (move-marker (make-marker) (point)))
13312 (insert (delete-and-extract-region beg end))
13313 (goto-char pos)
13314 (move-to-column col)))
13315
13316 (defun org-move-line-up (arg)
13317 "Move the current line up. With prefix argument, move it past ARG lines."
13318 (interactive "p")
13319 (let ((col (current-column))
13320 beg end pos)
13321 (beginning-of-line 1) (setq beg (point))
13322 (beginning-of-line 2) (setq end (point))
13323 (beginning-of-line (- arg))
13324 (setq pos (move-marker (make-marker) (point)))
13325 (insert (delete-and-extract-region beg end))
13326 (goto-char pos)
13327 (move-to-column col)))
13328
13329 ;; Paragraph filling stuff.
13330 ;; We want this to be just right, so use the full arsenal.
13331 ;; FIXME: This very likely does not work correctly for XEmacs, because the
13332 ;; filladapt package works slightly differently.
13333
13334 (defun org-set-autofill-regexps ()
13335 (interactive)
13336 ;; In the paragraph separator we include headlines, because filling
13337 ;; text in a line directly attached to a headline would otherwise
13338 ;; fill the headline as well.
13339 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
13340 ;; The paragraph starter includes hand-formatted lists.
13341 (set (make-local-variable 'paragraph-start)
13342 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13343 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13344 ;; But only if the user has not turned off tables or fixed-width regions
13345 (set (make-local-variable 'auto-fill-inhibit-regexp)
13346 (concat "\\*\\|#"
13347 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13348 (concat
13349 "\\|[ \t]*["
13350 (if org-enable-table-editor "|" "")
13351 (if org-enable-fixed-width-editor ":" "")
13352 "]"))))
13353 ;; We use our own fill-paragraph function, to make sure that tables
13354 ;; and fixed-width regions are not wrapped. That function will pass
13355 ;; through to `fill-paragraph' when appropriate.
13356 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
13357 ;; Adaptive filling: To get full control, first make sure that
13358 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13359 (set (make-local-variable 'adaptive-fill-regexp) "\000")
13360 (set (make-local-variable 'adaptive-fill-function)
13361 'org-adaptive-fill-function))
13362
13363 (defun org-fill-paragraph (&optional justify)
13364 "Re-align a table, pass through to fill-paragraph if no table."
13365 (let ((table-p (org-at-table-p))
13366 (table.el-p (org-at-table.el-p)))
13367 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
13368 (table.el-p t) ; skip table.el tables
13369 (table-p (org-table-align) t) ; align org-mode tables
13370 (t nil)))) ; call paragraph-fill
13371
13372 ;; For reference, this is the default value of adaptive-fill-regexp
13373 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13374
13375 (defun org-adaptive-fill-function ()
13376 "Return a fill prefix for org-mode files.
13377 In particular, this makes sure hanging paragraphs for hand-formatted lists
13378 work correctly."
13379 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
13380 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
13381
13382 ;; Functions needed for Emacs/XEmacs region compatibility
13383
13384 (defun org-add-hook (hook function &optional append local)
13385 "Add-hook, compatible with both Emacsen."
13386 (if (and local (featurep 'xemacs))
13387 (add-local-hook hook function append)
13388 (add-hook hook function append local)))
13389
13390 (defun org-region-active-p ()
13391 "Is `transient-mark-mode' on and the region active?
13392 Works on both Emacs and XEmacs."
13393 (if org-ignore-region
13394 nil
13395 (if (featurep 'xemacs)
13396 (and zmacs-regions (region-active-p))
13397 (and transient-mark-mode mark-active))))
13398
13399 (defun org-add-to-invisibility-spec (arg)
13400 "Add elements to `buffer-invisibility-spec'.
13401 See documentation for `buffer-invisibility-spec' for the kind of elements
13402 that can be added."
13403 (cond
13404 ((fboundp 'add-to-invisibility-spec)
13405 (add-to-invisibility-spec arg))
13406 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
13407 (setq buffer-invisibility-spec (list arg)))
13408 (t
13409 (setq buffer-invisibility-spec
13410 (cons arg buffer-invisibility-spec)))))
13411
13412 (defun org-remove-from-invisibility-spec (arg)
13413 "Remove elements from `buffer-invisibility-spec'."
13414 (if (fboundp 'remove-from-invisibility-spec)
13415 (remove-from-invisibility-spec arg)
13416 (if (consp buffer-invisibility-spec)
13417 (setq buffer-invisibility-spec
13418 (delete arg buffer-invisibility-spec)))))
13419
13420 (defun org-in-invisibility-spec-p (arg)
13421 "Is ARG a member of `buffer-invisibility-spec'?"
13422 (if (consp buffer-invisibility-spec)
13423 (member arg buffer-invisibility-spec)
13424 nil))
13425
13426 (defun org-image-file-name-regexp ()
13427 "Return regexp matching the file names of images."
13428 (if (fboundp 'image-file-name-regexp)
13429 (image-file-name-regexp)
13430 (let ((image-file-name-extensions
13431 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13432 "xbm" "xpm" "pbm" "pgm" "ppm")))
13433 (concat "\\."
13434 (regexp-opt (nconc (mapcar 'upcase
13435 image-file-name-extensions)
13436 image-file-name-extensions)
13437 t)
13438 "\\'"))))
13439
13440 ;; Functions needed for compatibility with old outline.el.
13441
13442 ;; Programming for the old outline.el (that uses selective display
13443 ;; instead of `invisible' text properties) is a nightmare, mostly
13444 ;; because regular expressions can no longer be anchored at
13445 ;; beginning/end of line. Therefore a number of function need special
13446 ;; treatment when the old outline.el is being used.
13447
13448 ;; The following functions capture almost the entire compatibility code
13449 ;; between the different versions of outline-mode. The only other
13450 ;; places where this is important are the font-lock-keywords, and in
13451 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
13452
13453 ;; C-a should go to the beginning of a *visible* line, also in the
13454 ;; new outline.el. I guess this should be patched into Emacs?
13455 (defun org-beginning-of-line ()
13456 "Go to the beginning of the current line. If that is invisible, continue
13457 to a visible line beginning. This makes the function of C-a more intuitive."
13458 (interactive)
13459 (beginning-of-line 1)
13460 (if (bobp)
13461 nil
13462 (backward-char 1)
13463 (if (org-invisible-p)
13464 (while (and (not (bobp)) (org-invisible-p))
13465 (backward-char 1)
13466 (beginning-of-line 1))
13467 (forward-char 1))))
13468
13469 (when org-noutline-p
13470 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
13471 ;; FIXME: should I use substitute-key-definition to reach other bindings
13472 ;; of beginning-of-line?
13473
13474 (defun org-invisible-p ()
13475 "Check if point is at a character currently not visible."
13476 (if org-noutline-p
13477 ;; Early versions of noutline don't have `outline-invisible-p'.
13478 (if (fboundp 'outline-invisible-p)
13479 (outline-invisible-p)
13480 (get-char-property (point) 'invisible))
13481 (save-excursion
13482 (skip-chars-backward "^\r\n")
13483 (equal (char-before) ?\r))))
13484
13485 (defun org-invisible-p2 ()
13486 "Check if point is at a character currently not visible."
13487 (save-excursion
13488 (if org-noutline-p
13489 (progn
13490 (if (and (eolp) (not (bobp))) (backward-char 1))
13491 ;; Early versions of noutline don't have `outline-invisible-p'.
13492 (if (fboundp 'outline-invisible-p)
13493 (outline-invisible-p)
13494 (get-char-property (point) 'invisible)))
13495 (skip-chars-backward "^\r\n")
13496 (equal (char-before) ?\r))))
13497
13498 (defun org-back-to-heading (&optional invisible-ok)
13499 "Move to previous heading line, or beg of this line if it's a heading.
13500 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
13501 (if org-noutline-p
13502 (outline-back-to-heading invisible-ok)
13503 (if (and (memq (char-before) '(?\n ?\r))
13504 (looking-at outline-regexp))
13505 t
13506 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
13507 outline-regexp)
13508 nil t)
13509 (if invisible-ok
13510 (progn (goto-char (match-end 1))
13511 (looking-at outline-regexp)))
13512 (error "Before first heading")))))
13513
13514 (defun org-on-heading-p (&optional invisible-ok)
13515 "Return t if point is on a (visible) heading line.
13516 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
13517 (if org-noutline-p
13518 (outline-on-heading-p 'invisible-ok)
13519 (save-excursion
13520 (skip-chars-backward "^\n\r")
13521 (and (looking-at outline-regexp)
13522 (or invisible-ok
13523 (bobp)
13524 (equal (char-before) ?\n))))))
13525
13526 (defun org-on-target-p ()
13527 (let ((pos (point)))
13528 (save-excursion
13529 (skip-chars-forward "<")
13530 (and (re-search-backward "<<" nil t)
13531 (or (looking-at org-radio-target-regexp)
13532 (looking-at org-target-regexp))
13533 (<= (match-beginning 0) pos)
13534 (>= (1+ (match-end 0)) pos)))))
13535
13536 (defun org-up-heading-all (arg)
13537 "Move to the heading line of which the present line is a subheading.
13538 This function considers both visible and invisible heading lines.
13539 With argument, move up ARG levels."
13540 (if org-noutline-p
13541 (if (fboundp 'outline-up-heading-all)
13542 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13543 (outline-up-heading arg t)) ; emacs 22 version of outline.el
13544 (org-back-to-heading t)
13545 (looking-at outline-regexp)
13546 (if (<= (- (match-end 0) (match-beginning 0)) arg)
13547 (error "Cannot move up %d levels" arg)
13548 (re-search-backward
13549 (concat "[\n\r]" (regexp-quote
13550 (make-string (- (match-end 0) (match-beginning 0) arg)
13551 ?*))
13552 "[^*]"))
13553 (forward-char 1))))
13554
13555 (defun org-show-hidden-entry ()
13556 "Show an entry where even the heading is hidden."
13557 (save-excursion
13558 (if (not org-noutline-p)
13559 (progn
13560 (org-back-to-heading t)
13561 (org-flag-heading nil)))
13562 (org-show-entry)))
13563
13564 (defun org-check-occur-regexp (regexp)
13565 "If REGEXP starts with \"^\", modify it to check for \\r as well.
13566 Of course, only for the old outline mode."
13567 (if org-noutline-p
13568 regexp
13569 (if (string-match "^\\^" regexp)
13570 (concat "[\n\r]" (substring regexp 1))
13571 regexp)))
13572
13573 (defun org-flag-heading (flag &optional entry)
13574 "Flag the current heading. FLAG non-nil means make invisible.
13575 When ENTRY is non-nil, show the entire entry."
13576 (save-excursion
13577 (org-back-to-heading t)
13578 (if (not org-noutline-p)
13579 ;; Make the current headline visible
13580 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
13581 ;; Check if we should show the entire entry
13582 (if entry
13583 (progn
13584 (org-show-entry)
13585 (save-excursion ;; FIXME: Is this the fix for points in the -|
13586 ;; middle of text? |
13587 (and (outline-next-heading) ;; |
13588 (org-flag-heading nil)))) ; show the next heading _|
13589 (outline-flag-region (max 1 (1- (point)))
13590 (save-excursion (outline-end-of-heading) (point))
13591 (if org-noutline-p
13592 flag
13593 (if flag ?\r ?\n))))))
13594
13595 (defun org-end-of-subtree (&optional invisible-OK)
13596 ;; This is an exact copy of the original function, but it uses
13597 ;; `org-back-to-heading', to make it work also in invisible
13598 ;; trees. And is uses an invisible-OK argument.
13599 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13600 (org-back-to-heading invisible-OK)
13601 (let ((first t)
13602 (level (funcall outline-level)))
13603 (while (and (not (eobp))
13604 (or first (> (funcall outline-level) level)))
13605 (setq first nil)
13606 (outline-next-heading))
13607 (if (memq (preceding-char) '(?\n ?\^M))
13608 (progn
13609 ;; Go to end of line before heading
13610 (forward-char -1)
13611 (if (memq (preceding-char) '(?\n ?\^M))
13612 ;; leave blank line before heading
13613 (forward-char -1))))))
13614
13615 (defun org-show-subtree ()
13616 "Show everything after this heading at deeper levels."
13617 (outline-flag-region
13618 (point)
13619 (save-excursion
13620 (outline-end-of-subtree) (outline-next-heading) (point))
13621 (if org-noutline-p nil ?\n)))
13622
13623 (defun org-show-entry ()
13624 "Show the body directly following this heading.
13625 Show the heading too, if it is currently invisible."
13626 (interactive)
13627 (save-excursion
13628 (org-back-to-heading t)
13629 (outline-flag-region
13630 (1- (point))
13631 (save-excursion
13632 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13633 (or (match-beginning 1) (point-max)))
13634 (if org-noutline-p nil ?\n))))
13635
13636 (defun org-make-options-regexp (kwds)
13637 "Make a regular expression for keyword lines."
13638 (concat
13639 (if org-noutline-p "^" "[\n\r]")
13640 "#?[ \t]*\\+\\("
13641 (mapconcat 'regexp-quote kwds "\\|")
13642 "\\):[ \t]*"
13643 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
13644
13645 ;; Make `bookmark-jump' show the jump location if it was hidden.
13646 (eval-after-load "bookmark"
13647 '(if (boundp 'bookmark-after-jump-hook)
13648 ;; We can use the hook
13649 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13650 ;; Hook not available, use advice
13651 (defadvice bookmark-jump (after org-make-visible activate)
13652 "Make the position visible."
13653 (org-bookmark-jump-unhide))))
13654
13655 (defun org-bookmark-jump-unhide ()
13656 "Unhide the current position, to show the bookmark location."
13657 (and (eq major-mode 'org-mode)
13658 (or (org-invisible-p)
13659 (save-excursion (goto-char (max (point-min) (1- (point))))
13660 (org-invisible-p)))
13661 (org-show-hierarchy-above)))
13662
13663 ;;; Finish up
13664
13665 (provide 'org)
13666
13667 (run-hooks 'org-load-hook)
13668
13669 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13670 ;;; org.el ends here
13671