]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-mode): Removed no invalid settings for calc embedded
[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.42
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 NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
47 ;;
48 ;;
49 ;; Installation
50 ;; ------------
51 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
52 ;; only need to copy the following lines to your .emacs file. The last two
53 ;; lines define *global* keys for the commands `org-store-link' and
54 ;; `org-agenda' - please choose suitable keys yourself.
55 ;;
56 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
57 ;; (define-key global-map "\C-cl" 'org-store-link)
58 ;; (define-key global-map "\C-ca" 'org-agenda)
59 ;;
60 ;; Furthermore you need to activate font-lock-mode in org-mode buffers.
61 ;; either of the following two lins will do the trick:
62 ;;
63 ;; (global-font-lock-mode 1) ; for all buffers
64 ;; (add-hook 'org-mode-hook 'turn-on-font-lock) ; org-mode buffers only
65 ;;
66 ;; If you have downloaded Org-mode from the Web, you have to take additional
67 ;; action: Byte-compile org.el and org-publish.el and put them together with
68 ;; org-install.el on your load path. Then also add to your .emacs file:
69 ;;
70 ;; (require 'org-install)
71 ;;
72 ;;
73 ;; Activation
74 ;; ----------
75 ;; The setup above will put all files with extension ".org" into Org-mode.
76 ;; As an alternative, make the first line of a file look like this:
77 ;;
78 ;; MY PROJECTS -*- mode: org; -*-
79 ;;
80 ;; which will select Org-mode for this buffer no matter what the file's
81 ;; name is.
82 ;;
83 ;; Documentation
84 ;; -------------
85 ;; The documentation of Org-mode can be found in the TeXInfo file. The
86 ;; distribution also contains a PDF version of it. At the homepage of
87 ;; Org-mode, you can read the same text online as HTML. There is also an
88 ;; excellent reference card made by Philip Rooke. This card can be found
89 ;; in the etc/ directory of Emacs 22.
90 ;;
91 ;; Recent changes
92 ;; --------------
93 ;; Version 4.42
94 ;; - Bug fixes
95 ;; - `s' key in the agenda saves all org-mode buffers.
96 ;;
97 ;; Version 4.41
98 ;; - Shift-curser keys can modify inactive time stamps (inactive time
99 ;; stamps are the ones in [...] brackets.
100 ;; - Toggle all checkboxes in a region/below a headline.
101 ;; - Bug fixes.
102 ;;
103 ;; Version 4.40
104 ;; - Bug fixes.
105 ;;
106 ;; Version 4.39
107 ;; - Special tag ARCHIVE keeps a subtree closed and away from agenda lists.
108 ;; - LaTeX code in Org-mode files can be converted to images for HTML.
109 ;; - Bug fixes.
110 ;; - CDLaTeX-mode features can be used in Org-mode to help inserting
111 ;; LaTeX environment and math.
112 ;;
113 ;; Version 4.38
114 ;; - noutline.el is now required (important for XEmacs users only).
115 ;; - Dynamic blocks.
116 ;; - Archiving of all level 1 trees without open TODO items.
117 ;; - Clock reports can be inserted into the file in a special section.
118 ;; - FAQ removed from the manual, now only on the web.
119 ;; - Bug fixes.
120 ;;
121 ;; Version 4.37
122 ;; - Clock-feature for measuring time spent on specific items.
123 ;; - Improved emphasizing allows configuration and stacking.
124 ;;
125 ;; Version 4.36
126 ;; - Improved indentation of ASCII export, when headlines become items.
127 ;; - Handling of 12am and 12pm fixed. Times beyond 24:00 can be used
128 ;; and will not lead to conflicts.
129 ;; - Support for mutually exclusive TAGS with the fast tags interface.
130 ;; - Bug fixes.
131 ;;
132 ;; Version 4.35
133 ;; - HTML export is now valid XHTML.
134 ;; - Timeline can also show dates without entries. See new option
135 ;; `org-timeline-show-empty-dates'.
136 ;; - The bullets created by the ASCII exporter can now be configured.
137 ;; See the new option `org-export-ascii-bullets'.
138 ;; - New face `org-upcoming-deadline' (was `org-scheduled-previously').
139 ;; - New function `org-context' to allow testing for local context.
140 ;;
141 ;; Version 4.34
142 ;; - Bug fixes.
143 ;;
144 ;; Version 4.33
145 ;; - New commands to move through plain lists: S-up and S-down.
146 ;; - Bug fixes and documentation update.
147 ;;
148 ;; Version 4.32
149 ;; - Fast (single-key-per-tag) interface for setting TAGS.
150 ;; - The list of legal tags can be configured globally and locally.
151 ;; - Elisp and Info links (thanks to Todd Neal).
152 ;; - `org-export-publishing-directory' can be an alist, with different
153 ;; directories for different export types.
154 ;; - All context-sensitive commands use `call-interactively' to dispatch.
155 ;; - `org-confirm-shell-links' renamed to `org-confirm-shell-link-function'.
156 ;; - Bug fixes.
157 ;;
158 ;; Version 4.31
159 ;; - Bug fixes.
160 ;;
161 ;; Version 4.30
162 ;; - Modified installation: Autoloads have been collected in org-install.el.
163 ;; - Logging (org-log-done) is now a #+STARTUP option.
164 ;; - Checkboxes in plain list items, following up on Frank Ruell's idea.
165 ;; - File links inserted with C-c C-l will use relative paths if the linked
166 ;; file is in the current directory or a subdirectory of it.
167 ;; - New variable `org-link-file-path-type' to specify preference for
168 ;; relative and absolute paths.
169 ;; - New CSS classes for tags, timestamps, timestamp keywords.
170 ;; - Bug and typo fixes.
171 ;;
172 ;; Version 4.29
173 ;; - Inlining images in HTML export now depends on wheather the link
174 ;; contains a description or not.
175 ;; - TODO items can be scheduled from the global TODO list using C-c C-s.
176 ;; - TODO items already scheduled can be made to disappear from the global
177 ;; todo list, see `org-agenda-todo-ignore-scheduled'.
178 ;; - In Tables, formulas may also be Lisp forms.
179 ;; - Exporting the visible part of an outline with `C-c C-x v' works now
180 ;; for all available exporters.
181 ;; - Bug fixes, lots of them :-(
182 ;;
183 ;; Version 4.28
184 ;; - Bug fixes.
185 ;;
186 ;; Version 4.27
187 ;; - HTML exporter generalized to receive external options.
188 ;; As part of the process, author, email and date have been moved to the
189 ;; end of the HTML file.
190 ;; - Support for customizable file search in file links.
191 ;; - BibTeX database links as first application of the above.
192 ;; - New option `org-agenda-todo-list-sublevels' to turn off listing TODO
193 ;; entries that are sublevels of another TODO entry.
194 ;;
195 ;;
196 ;;; Code:
197
198 (eval-when-compile
199 (require 'cl)
200 (require 'calendar))
201 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
202 ;; the file noutline.el being loaded.
203 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
204 ;; We require noutline, which might be provided in outline.el
205 (require 'outline) (require 'noutline)
206 ;; Other stuff we need.
207 (require 'time-date)
208 (require 'easymenu)
209
210 ;;; Customization variables
211
212 (defvar org-version "4.42"
213 "The version number of the file org.el.")
214 (defun org-version ()
215 (interactive)
216 (message "Org-mode version %s" org-version))
217
218 ;; The following constant is for compatibility with different versions
219 ;; of outline.el.
220 (defconst org-noutline-p (featurep 'noutline)
221 "Are we using the new outline mode?")
222 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
223 (defconst org-format-transports-properties-p
224 (let ((x "a"))
225 (add-text-properties 0 1 '(test t) x)
226 (get-text-property 0 'test (format "%s" x)))
227 "Does format transport text properties?")
228
229 (defgroup org nil
230 "Outline-based notes management and organizer."
231 :tag "Org"
232 :group 'outlines
233 :group 'hypermedia
234 :group 'calendar)
235
236 (defgroup org-startup nil
237 "Options concerning startup of Org-mode."
238 :tag "Org Startup"
239 :group 'org)
240
241 (defcustom org-startup-folded t
242 "Non-nil means, entering Org-mode will switch to OVERVIEW.
243 This can also be configured on a per-file basis by adding one of
244 the following lines anywhere in the buffer:
245
246 #+STARTUP: fold
247 #+STARTUP: nofold
248 #+STARTUP: content"
249 :group 'org-startup
250 :type '(choice
251 (const :tag "nofold: show all" nil)
252 (const :tag "fold: overview" t)
253 (const :tag "content: all headlines" content)))
254
255 (defcustom org-startup-truncated t
256 "Non-nil means, entering Org-mode will set `truncate-lines'.
257 This is useful since some lines containing links can be very long and
258 uninteresting. Also tables look terrible when wrapped."
259 :group 'org-startup
260 :type 'boolean)
261
262 (defcustom org-startup-align-all-tables nil
263 "Non-nil means, align all tables when visiting a file.
264 This is useful when the column width in tables is forced with <N> cookies
265 in table fields. Such tables will look correct only after the first re-align.
266 This can also be configured on a per-file basis by adding one of
267 the following lines anywhere in the buffer:
268 #+STARTUP: align
269 #+STARTUP: noalign"
270 :group 'org-startup
271 :type 'boolean)
272
273 (defcustom org-startup-with-deadline-check nil
274 "Non-nil means, entering Org-mode will run the deadline check.
275 This means, if you start editing an org file, you will get an
276 immediate reminder of any due deadlines.
277 This can also be configured on a per-file basis by adding one of
278 the following lines anywhere in the buffer:
279 #+STARTUP: dlcheck
280 #+STARTUP: nodlcheck"
281 :group 'org-startup
282 :type 'boolean)
283
284 (defcustom org-insert-mode-line-in-empty-file nil
285 "Non-nil means insert the first line setting Org-mode in empty files.
286 When the function `org-mode' is called interactively in an empty file, this
287 normally means that the file name does not automatically trigger Org-mode.
288 To ensure that the file will always be in Org-mode in the future, a
289 line enforcing Org-mode will be inserted into the buffer, if this option
290 has been set."
291 :group 'org-startup
292 :type 'boolean)
293
294 (defcustom org-CUA-compatible nil
295 "Non-nil means use alternative key bindings for S-<cursor movement>.
296 Org-mode used S-<cursor movement> for changing timestamps and priorities.
297 S-<cursor movement> is also used for example by `CUA-mode' to select text.
298 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
299 alternative bindings. Setting this variable to t will replace the following
300 keys both in Org-mode and in the Org-agenda buffer.
301
302 S-RET -> C-S-RET
303 S-up -> M-p
304 S-down -> M-n
305 S-left -> M--
306 S-right -> M-+
307
308 If you do not like the alternative keys, take a look at the variable
309 `org-disputed-keys'.
310
311 This option is only relevant at load-time of Org-mode. Changing it requires
312 a restart of Emacs to become effective."
313 :group 'org-startup
314 :type 'boolean)
315
316 (defvar org-disputed-keys
317 '((S-up [(shift up)] [(meta ?p)])
318 (S-down [(shift down)] [(meta ?n)])
319 (S-left [(shift left)] [(meta ?-)])
320 (S-right [(shift right)] [(meta ?+)])
321 (S-return [(shift return)] [(control shift return)]))
322 "Keys for which Org-mode and other modes compete.
323 This is an alist, cars are symbols for lookup, 1st element is the default key,
324 second element will be used when `org-CUA-compatible' is t.")
325
326 (defun org-key (key)
327 "Select a key according to `org-CUA-compatible'."
328 (nth (if org-CUA-compatible 2 1)
329 (or (assq key org-disputed-keys)
330 (error "Invalid Key %s in `org-key'" key))))
331
332 (defcustom org-ellipsis nil
333 "The ellipsis to use in the Org-mode outline.
334 When nil, just use the standard three dots. When a string, use that instead,
335 and just in Org-mode (which will then use its own display table).
336 Changing this requires executing `M-x org-mode' in a buffer to become
337 effective."
338 :group 'org-startup
339 :type '(choice (const :tag "Default" nil)
340 (string :tag "String" :value "...#")))
341
342 (defvar org-display-table nil
343 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
344
345 (defgroup org-keywords nil
346 "Keywords in Org-mode."
347 :tag "Org Keywords"
348 :group 'org)
349
350 (defcustom org-deadline-string "DEADLINE:"
351 "String to mark deadline entries.
352 A deadline is this string, followed by a time stamp. Should be a word,
353 terminated by a colon. You can insert a schedule keyword and
354 a timestamp with \\[org-deadline].
355 Changes become only effective after restarting Emacs."
356 :group 'org-keywords
357 :type 'string)
358
359 (defcustom org-scheduled-string "SCHEDULED:"
360 "String to mark scheduled TODO entries.
361 A schedule is this string, followed by a time stamp. Should be a word,
362 terminated by a colon. You can insert a schedule keyword and
363 a timestamp with \\[org-schedule].
364 Changes become only effective after restarting Emacs."
365 :group 'org-keywords
366 :type 'string)
367
368 (defcustom org-closed-string "CLOSED:"
369 "String used as the prefix for timestamps logging closing a TODO entry."
370 :group 'org-keywords
371 :type 'string)
372
373 (defcustom org-clock-string "CLOCK:"
374 "String used as prefix for timestamps clocking work hours on an item."
375 :group 'org-keywords
376 :type 'string)
377
378 (defcustom org-comment-string "COMMENT"
379 "Entries starting with this keyword will never be exported.
380 An entry can be toggled between COMMENT and normal with
381 \\[org-toggle-comment].
382 Changes become only effective after restarting Emacs."
383 :group 'org-keywords
384 :type 'string)
385
386 (defcustom org-quote-string "QUOTE"
387 "Entries starting with this keyword will be exported in fixed-width font.
388 Quoting applies only to the text in the entry following the headline, and does
389 not extend beyond the next headline, even if that is lower level.
390 An entry can be toggled between QUOTE and normal with
391 \\[org-toggle-fixed-width-section]."
392 :group 'org-keywords
393 :type 'string)
394
395 (defgroup org-structure nil
396 "Options concerning the general structure of Org-mode files."
397 :tag "Org Structure"
398 :group 'org)
399
400 (defgroup org-cycle nil
401 "Options concerning visibility cycling in Org-mode."
402 :tag "Org Cycle"
403 :group 'org-structure)
404
405 (defcustom org-cycle-global-at-bob t
406 "Cycle globally if cursor is at beginning of buffer and not at a headline.
407 This makes it possible to do global cycling without having to use S-TAB or
408 C-u TAB. For this special case to work, the first line of the buffer
409 must not be a headline - it may be empty ot some other text. When used in
410 this way, `org-cycle-hook' is disables temporarily, to make sure the
411 cursor stays at the beginning of the buffer.
412 When this option is nil, don't do anything special at the beginning
413 of the buffer."
414 :group 'org-cycle
415 :type 'boolean)
416
417 (defcustom org-cycle-emulate-tab t
418 "Where should `org-cycle' emulate TAB.
419 nil Never
420 white Only in completely white lines
421 whitestart Only at the beginning of lines, before the first non-white char.
422 t Everywhere except in headlines
423 If TAB is used in a place where it does not emulate TAB, the current subtree
424 visibility is cycled."
425 :group 'org-cycle
426 :type '(choice (const :tag "Never" nil)
427 (const :tag "Only in completely white lines" white)
428 (const :tag "Before first char in a line" whitestart)
429 (const :tag "Everywhere except in headlines" t)
430 ))
431
432 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
433 org-optimize-window-after-visibility-change)
434 "Hook that is run after `org-cycle' has changed the buffer visibility.
435 The function(s) in this hook must accept a single argument which indicates
436 the new state that was set by the most recent `org-cycle' command. The
437 argument is a symbol. After a global state change, it can have the values
438 `overview', `content', or `all'. After a local state change, it can have
439 the values `folded', `children', or `subtree'."
440 :group 'org-cycle
441 :type 'hook)
442
443 (defgroup org-edit-structure nil
444 "Options concerning structure editing in Org-mode."
445 :tag "Org Edit Structure"
446 :group 'org-structure)
447
448 (defcustom org-odd-levels-only nil
449 "Non-nil means, skip even levels and only use odd levels for the outline.
450 This has the effect that two stars are being added/taken away in
451 promotion/demotion commands. It also influences how levels are
452 handled by the exporters.
453 Changing it requires restart of `font-lock-mode' to become effective
454 for fontification also in regions already fontified.
455 You may also set this on a per-file basis by adding one of the following
456 lines to the buffer:
457
458 #+STARTUP: odd
459 #+STARTUP: oddeven"
460 :group 'org-edit-structure
461 :group 'org-font-lock
462 :type 'boolean)
463
464 (defcustom org-adapt-indentation t
465 "Non-nil means, adapt indentation when promoting and demoting.
466 When this is set and the *entire* text in an entry is indented, the
467 indentation is increased by one space in a demotion command, and
468 decreased by one in a promotion command. If any line in the entry
469 body starts at column 0, indentation is not changed at all."
470 :group 'org-edit-structure
471 :type 'boolean)
472
473 (defcustom org-insert-heading-hook nil
474 "Hook being run after inserting a new heading."
475 :group 'org-edit-structure
476 :type 'boolean)
477
478 (defcustom org-enable-fixed-width-editor t
479 "Non-nil means, lines starting with \":\" are treated as fixed-width.
480 This currently only means, they are never auto-wrapped.
481 When nil, such lines will be treated like ordinary lines.
482 See also the QUOTE keyword."
483 :group 'org-edit-structure
484 :type 'boolean)
485
486 (defgroup org-sparse-trees nil
487 "Options concerning sparse trees in Org-mode."
488 :tag "Org Sparse Trees"
489 :group 'org-structure)
490
491 (defcustom org-highlight-sparse-tree-matches t
492 "Non-nil means, highlight all matches that define a sparse tree.
493 The highlights will automatically disappear the next time the buffer is
494 changed by an edit command."
495 :group 'org-sparse-trees
496 :type 'boolean)
497
498 (defcustom org-show-hierarchy-above t
499 "Non-nil means, show full hierarchy when showing a spot in the tree.
500 Turning this off makes sparse trees more compact, but also less clear."
501 :group 'org-sparse-trees
502 :type 'boolean)
503
504 (defcustom org-show-following-heading t
505 "Non-nil means, show heading following match in `org-occur'.
506 When doing an `org-occur' it is useful to show the headline which
507 follows the match, even if they do not match the regexp. This makes it
508 easier to edit directly inside the sparse tree. However, if you use
509 `org-occur' mainly as an overview, the following headlines are
510 unnecessary clutter."
511 :group 'org-sparse-trees
512 :type 'boolean)
513
514 (defcustom org-occur-hook '(org-first-headline-recenter)
515 "Hook that is run after `org-occur' has constructed a sparse tree.
516 This can be used to recenter the window to show as much of the structure
517 as possible."
518 :group 'org-sparse-trees
519 :type 'hook)
520
521 (defgroup org-plain-lists nil
522 "Options concerning plain lists in Org-mode."
523 :tag "Org Plain lists"
524 :group 'org-structure)
525
526 (defcustom org-cycle-include-plain-lists nil
527 "Non-nil means, include plain lists into visibility cycling.
528 This means that during cycling, plain list items will *temporarily* be
529 interpreted as outline headlines with a level given by 1000+i where i is the
530 indentation of the bullet. In all other operations, plain list items are
531 not seen as headlines. For example, you cannot assign a TODO keyword to
532 such an item."
533 :group 'org-plain-lists
534 :type 'boolean)
535
536
537 (defcustom org-plain-list-ordered-item-terminator t
538 "The character that makes a line with leading number an ordered list item.
539 Valid values are ?. and ?\). To get both terminators, use t. While
540 ?. may look nicer, it creates the danger that a line with leading
541 number may be incorrectly interpreted as an item. ?\) therefore is
542 the safe choice."
543 :group 'org-plain-lists
544 :type '(choice (const :tag "dot like in \"2.\"" ?.)
545 (const :tag "paren like in \"2)\"" ?\))
546 (const :tab "both" t)))
547
548 (defcustom org-auto-renumber-ordered-lists t
549 "Non-nil means, automatically renumber ordered plain lists.
550 Renumbering happens when the sequence have been changed with
551 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
552 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
553 :group 'org-plain-lists
554 :type 'boolean)
555
556 (defgroup org-archive nil
557 "Options concerning archiving in Org-mode."
558 :tag "Org Archive"
559 :group 'org-structure)
560
561 (defcustom org-archive-tag "ARCHIVE"
562 "The tag that marks a subtree as archived.
563 An archived subtree does not open during visibility cycling, and does
564 not contribute to the agenda listings."
565 :group 'org-archive
566 :group 'org-keywords
567 :type 'string)
568
569 (defcustom org-agenda-skip-archived-trees t
570 "Non-nil means, the agenda will skip any items located in archived trees.
571 An archived tree is a tree marked with the tag ARCHIVE."
572 :group 'org-archive
573 :group 'org-agenda-display
574 :type 'boolean)
575
576 (defcustom org-cycle-open-archived-trees nil
577 "Non-nil means, `org-cycle' will open archived trees.
578 An archived tree is a tree marked with the tag ARCHIVE.
579 When nil, archived trees will stay folded. You can still open them with
580 normal outline commands like `show-all', but not with the cycling commands."
581 :group 'org-archive
582 :group 'org-cycle
583 :type 'boolean)
584
585 (defcustom org-sparse-tree-open-archived-trees nil
586 "Non-nil means sparse tree construction shows matches in archived trees.
587 When nil, matches in these trees are highlighted, but the trees are kept in
588 collapsed state."
589 :group 'org-archive
590 :group 'org-sparse-trees
591 :type 'boolean)
592
593 (defcustom org-archive-location "%s_archive::"
594 "The location where subtrees should be archived.
595 This string consists of two parts, separated by a double-colon.
596
597 The first part is a file name - when omitted, archiving happens in the same
598 file. %s will be replaced by the current file name (without directory part).
599 Archiving to a different file is useful to keep archived entries from
600 contributing to the Org-mode Agenda.
601
602 The part after the double colon is a headline. The archived entries will be
603 filed under that headline. When omitted, the subtrees are simply filed away
604 at the end of the file, as top-level entries.
605
606 Here are a few examples:
607 \"%s_archive::\"
608 If the current file is Projects.org, archive in file
609 Projects.org_archive, as top-level trees. This is the default.
610
611 \"::* Archived Tasks\"
612 Archive in the current file, under the top-level headline
613 \"* Archived Tasks\".
614
615 \"~/org/archive.org::\"
616 Archive in file ~/org/archive.org (absolute path), as top-level trees.
617
618 \"basement::** Finished Tasks\"
619 Archive in file ./basement (relative path), as level 3 trees
620 below the level 2 heading \"** Finished Tasks\".
621
622 You may set this option on a per-file basis by adding to the buffer a
623 line like
624
625 #+ARCHIVE: basement::** Finished Tasks"
626 :group 'org-archive
627 :type 'string)
628
629 (defcustom org-archive-mark-done t
630 "Non-nil means, mark entries as DONE when they are moved to the archive file."
631 :group 'org-archive
632 :type 'boolean)
633
634 (defcustom org-archive-stamp-time t
635 "Non-nil means, add a time stamp to entries moved to an archive file.
636 The time stamp will be added directly after the TODO state keyword in the
637 first line, so it is probably best to use this in combinations with
638 `org-archive-mark-done'."
639 :group 'org-archive
640 :type 'boolean)
641
642 (defgroup org-table nil
643 "Options concerning tables in Org-mode."
644 :tag "Org Table"
645 :group 'org)
646
647 (defcustom org-enable-table-editor 'optimized
648 "Non-nil means, lines starting with \"|\" are handled by the table editor.
649 When nil, such lines will be treated like ordinary lines.
650
651 When equal to the symbol `optimized', the table editor will be optimized to
652 do the following:
653 - Use automatic overwrite mode in front of whitespace in table fields.
654 This make the structure of the table stay in tact as long as the edited
655 field does not exceed the column width.
656 - Minimize the number of realigns. Normally, the table is aligned each time
657 TAB or RET are pressed to move to another field. With optimization this
658 happens only if changes to a field might have changed the column width.
659 Optimization requires replacing the functions `self-insert-command',
660 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
661 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
662 very good at guessing when a re-align will be necessary, but you can always
663 force one with \\[org-ctrl-c-ctrl-c].
664
665 If you would like to use the optimized version in Org-mode, but the
666 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
667
668 This variable can be used to turn on and off the table editor during a session,
669 but in order to toggle optimization, a restart is required.
670
671 See also the variable `org-table-auto-blank-field'."
672 :group 'org-table
673 :type '(choice
674 (const :tag "off" nil)
675 (const :tag "on" t)
676 (const :tag "on, optimized" optimized)))
677
678 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
679 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
680 In the optimized version, the table editor takes over all simple keys that
681 normally just insert a character. In tables, the characters are inserted
682 in a way to minimize disturbing the table structure (i.e. in overwrite mode
683 for empty fields). Outside tables, the correct binding of the keys is
684 restored.
685
686 The default for this option is t if the optimized version is also used in
687 Org-mode. See the variable `org-enable-table-editor' for details. Changing
688 this variable requires a restart of Emacs to become effective."
689 :group 'org-table
690 :type 'boolean)
691
692 (defgroup org-table-settings nil
693 "Settings for tables in Org-mode."
694 :tag "Org Table Settings"
695 :group 'org-table)
696
697 (defcustom org-table-default-size "5x2"
698 "The default size for newly created tables, Columns x Rows."
699 :group 'org-table-settings
700 :type 'string)
701
702 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
703 "Regular expression for recognizing numbers in table columns.
704 If a table column contains mostly numbers, it will be aligned to the
705 right. If not, it will be aligned to the left.
706
707 The default value of this option is a regular expression which allows
708 anything which looks remotely like a number as used in scientific
709 context. For example, all of the following will be considered a
710 number:
711 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
712
713 Other options offered by the customize interface are more restrictive."
714 :group 'org-table-settings
715 :type '(choice
716 (const :tag "Positive Integers"
717 "^[0-9]+$")
718 (const :tag "Integers"
719 "^[-+]?[0-9]+$")
720 (const :tag "Floating Point Numbers"
721 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
722 (const :tag "Floating Point Number or Integer"
723 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
724 (const :tag "Exponential, Floating point, Integer"
725 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
726 (const :tag "Very General Number-Like"
727 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
728 (string :tag "Regexp:")))
729
730 (defcustom org-table-number-fraction 0.5
731 "Fraction of numbers in a column required to make the column align right.
732 In a column all non-white fields are considered. If at least this
733 fraction of fields is matched by `org-table-number-fraction',
734 alignment to the right border applies."
735 :group 'org-table-settings
736 :type 'number)
737
738 (defgroup org-table-editing nil
739 "Bahavior of tables during editing in Org-mode."
740 :tag "Org Table Editing"
741 :group 'org-table)
742
743 (defcustom org-table-automatic-realign t
744 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
745 When nil, aligning is only done with \\[org-table-align], or after column
746 removal/insertion."
747 :group 'org-table-editing
748 :type 'boolean)
749
750 (defcustom org-table-limit-column-width t ;kw
751 "Non-nil means, allow to limit the width of table columns with <N> fields."
752 :group 'org-table-editing
753 :type 'boolean)
754
755 (defcustom org-table-auto-blank-field t
756 "Non-nil means, automatically blank table field when starting to type into it.
757 This only happens when typing immediately after a field motion
758 command (TAB, S-TAB or RET).
759 Only relevant when `org-enable-table-editor' is equal to `optimized'."
760 :group 'org-table-editing
761 :type 'boolean)
762
763 (defcustom org-table-tab-jumps-over-hlines t
764 "Non-nil means, tab in the last column of a table with jump over a hline.
765 If a horizontal separator line is following the current line,
766 `org-table-next-field' can either create a new row before that line, or jump
767 over the line. When this option is nil, a new line will be created before
768 this line."
769 :group 'org-table-editing
770 :type 'boolean)
771
772 (defcustom org-table-tab-recognizes-table.el t
773 "Non-nil means, TAB will automatically notice a table.el table.
774 When it sees such a table, it moves point into it and - if necessary -
775 calls `table-recognize-table'."
776 :group 'org-table-editing
777 :type 'boolean)
778
779 (defgroup org-table-calculation nil
780 "Options concerning tables in Org-mode."
781 :tag "Org Table Calculation"
782 :group 'org-table)
783
784 (defcustom org-table-copy-increment t
785 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
786 :group 'org-table-calculation
787 :type 'boolean)
788
789 (defcustom org-calc-default-modes
790 '(calc-internal-prec 12
791 calc-float-format (float 5)
792 calc-angle-mode deg
793 calc-prefer-frac nil
794 calc-symbolic-mode nil
795 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
796 calc-display-working-message t
797 )
798 "List with Calc mode settings for use in calc-eval for table formulas.
799 The list must contain alternating symbols (Calc modes variables and values).
800 Don't remove any of the default settings, just change the values. Org-mode
801 relies on the variables to be present in the list."
802 :group 'org-table-calculation
803 :type 'plist)
804
805 (defcustom org-table-formula-evaluate-inline t
806 "Non-nil means, TAB and RET evaluate a formula in current table field.
807 If the current field starts with an equal sign, it is assumed to be a formula
808 which should be evaluated as described in the manual and in the documentation
809 string of the command `org-table-eval-formula'. This feature requires the
810 Emacs calc package.
811 When this variable is nil, formula calculation is only available through
812 the command \\[org-table-eval-formula]."
813 :group 'org-table-calculation
814 :type 'boolean)
815
816
817 (defcustom org-table-formula-use-constants t
818 "Non-nil means, interpret constants in formulas in tables.
819 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
820 by the value given in `org-table-formula-constants', or by a value obtained
821 from the `constants.el' package."
822 :group 'org-table-calculation
823 :type 'boolean)
824
825 (defcustom org-table-formula-constants nil
826 "Alist with constant names and values, for use in table formulas.
827 The car of each element is a name of a constant, without the `$' before it.
828 The cdr is the value as a string. For example, if you'd like to use the
829 speed of light in a formula, you would configure
830
831 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
832
833 and then use it in an equation like `$1*$c'."
834 :group 'org-table-calculation
835 :type '(repeat
836 (cons (string :tag "name")
837 (string :tag "value"))))
838
839 (defcustom org-table-formula-numbers-only nil
840 "Non-nil means, calculate only with numbers in table formulas.
841 Then all input fields will be converted to a number, and the result
842 must also be a number. When nil, calc's full potential is available
843 in table calculations, including symbolics etc."
844 :group 'org-table-calculation
845 :type 'boolean)
846
847 (defcustom org-table-allow-automatic-line-recalculation t
848 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
849 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
850 :group 'org-table-calculation
851 :type 'boolean)
852
853 (defgroup org-link nil
854 "Options concerning links in Org-mode."
855 :tag "Org Link"
856 :group 'org)
857
858 (defcustom org-descriptive-links t
859 "Non-nil means, hide link part and only show description of bracket links.
860 Bracket links are like [[link][descritpion]]. This variable sets the initial
861 state in new org-mode buffers. The setting can then be toggled on a
862 per-buffer basis from the Org->Hyperlinks menu."
863 :group 'org-link
864 :type 'boolean)
865
866 (defcustom org-link-style 'bracket
867 "The style of links to be inserted with \\[org-insert-link].
868 Possible values are:
869 bracket [[link][description]]. This is recommended
870 plain Description \\n link. The old way, no longer recommended."
871 :group 'org-link
872 :type '(choice
873 (const :tag "Bracket (recommended)" bracket)
874 (const :tag "Plain (no longer recommended)" plain)))
875
876 (defcustom org-link-format "%s"
877 "Default format for external, URL-like linkes in the buffer.
878 This is a format string for printf, %s will be replaced by the link text.
879 The recommended value is just \"%s\", since links will be protected by
880 enclosing them in double brackets. If you prefer plain links (see variable
881 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
882 additional URL: prefix, so the format would be \"<URL:%s>\"."
883 :group 'org-link
884 :type '(choice
885 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
886 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
887 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
888 (string :tag "Other" :value "<%s>")))
889
890 (defcustom org-link-file-path-type 'adaptive
891 "How the path name in file links should be stored.
892 Valid values are:
893
894 relative relative to the current directory, i.e. the directory of the file
895 into which the link is being inserted.
896 absolute absolute path, if possible with ~ for home directory.
897 noabbrev absolute path, no abbreviation of home directory.
898 adaptive Use relative path for files in the current directory and sub-
899 directories of it. For other files, use an absolute path."
900 :group 'org-link
901 :type '(choice
902 (const relative)
903 (const absolute)
904 (const noabbrev)
905 (const adaptive)))
906
907 (defcustom org-activate-links '(bracket angle plain radio tag date)
908 "Types of links that should be activated in Org-mode files.
909 This is a list of symbols, each leading to the activation of a certain link
910 type. In principle, it does not hurt to turn on most link types - there may
911 be a small gain when turning off unused link types. The types are:
912
913 bracket The recommended [[link][description]] or [[link]] links with hiding.
914 angular Links in angular brackes that may contain whitespace like
915 <bbdb:Carsten Dominik>.
916 plain Plain links in normal text, no whitespace, like http://google.com.
917 radio Text that is matched by a radio target, see manual for details.
918 tag Tag settings in a headline (link to tag search).
919 date Time stamps (link to calendar).
920 camel CamelCase words defining text searches.
921
922 Changing this variable requires a restart of Emacs to become effective."
923 :group 'org-link
924 :type '(set (const :tag "Double bracket links (new style)" bracket)
925 (const :tag "Angular bracket links (old style)" angular)
926 (const :tag "plain text links" plain)
927 (const :tag "Radio target matches" radio)
928 (const :tag "Tags" tag)
929 (const :tag "Timestamps" date)
930 (const :tag "CamelCase words" camel)))
931
932 (defgroup org-link-store nil
933 "Options concerning storing links in Org-mode"
934 :tag "Org Store Link"
935 :group 'org-link)
936
937 (defcustom org-context-in-file-links t
938 "Non-nil means, file links from `org-store-link' contain context.
939 A search string will be added to the file name with :: as separator and
940 used to find the context when the link is activated by the command
941 `org-open-at-point'.
942 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
943 negates this setting for the duration of the command."
944 :group 'org-link-store
945 :type 'boolean)
946
947 (defcustom org-file-link-context-use-camel-case nil
948 "Non-nil means, use CamelCase to store a search context in a file link.
949 When nil, the search string simply consists of the words of the string.
950 CamelCase is deprecated, and support for it may be dropped in the future."
951 :group 'org-link-store
952 :type 'boolean)
953
954 (defcustom org-keep-stored-link-after-insertion nil
955 "Non-nil means, keep link in list for entire session.
956
957 The command `org-store-link' adds a link pointing to the current
958 location to an internal list. These links accumulate during a session.
959 The command `org-insert-link' can be used to insert links into any
960 Org-mode file (offering completion for all stored links). When this
961 option is nil, every link which has been inserted once using \\[org-insert-link]
962 will be removed from the list, to make completing the unused links
963 more efficient."
964 :group 'org-link-store
965 :type 'boolean)
966
967 (defcustom org-usenet-links-prefer-google nil
968 "Non-nil means, `org-store-link' will create web links to Google groups.
969 When nil, Gnus will be used for such links.
970 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
971 negates this setting for the duration of the command."
972 :group 'org-link-store
973 :type 'boolean)
974
975 (defgroup org-link-follow nil
976 "Options concerning following links in Org-mode"
977 :tag "Org Follow Link"
978 :group 'org-link)
979
980 (defcustom org-tab-follows-link nil
981 "Non-nil means, on links TAB will follow the link.
982 Needs to be set before org.el is loaded."
983 :group 'org-link-follow
984 :type 'boolean)
985
986 (defcustom org-return-follows-link nil
987 "Non-nil means, on links RET will follow the link.
988 Needs to be set before org.el is loaded."
989 :group 'org-link-follow
990 :type 'boolean)
991
992 (defcustom org-mouse-1-follows-link t
993 "Non-nil means, mouse-1 on a link will follow the link.
994 A longer mouse click will still set point. Does not wortk on XEmacs.
995 Needs to be set before org.el is loaded."
996 :group 'org-link-follow
997 :type 'boolean)
998
999 (defcustom org-mark-ring-length 4
1000 "Number of different positions to be recorded in the ring
1001 Changing this requires a restart of Emacs to work correctly."
1002 :group 'org-link-follow
1003 :type 'interger)
1004
1005 (defcustom org-link-frame-setup
1006 '((vm . vm-visit-folder-other-frame)
1007 (gnus . gnus-other-frame)
1008 (file . find-file-other-window))
1009 "Setup the frame configuration for following links.
1010 When following a link with Emacs, it may often be useful to display
1011 this link in another window or frame. This variable can be used to
1012 set this up for the different types of links.
1013 For VM, use any of
1014 `vm-visit-folder'
1015 `vm-visit-folder-other-frame'
1016 For Gnus, use any of
1017 `gnus'
1018 `gnus-other-frame'
1019 For FILE, use any of
1020 `find-file'
1021 `find-file-other-window'
1022 `find-file-other-frame'
1023 For the calendar, use the variable `calendar-setup'.
1024 For BBDB, it is currently only possible to display the matches in
1025 another window."
1026 :group 'org-link-follow
1027 :type '(list
1028 (cons (const vm)
1029 (choice
1030 (const vm-visit-folder)
1031 (const vm-visit-folder-other-window)
1032 (const vm-visit-folder-other-frame)))
1033 (cons (const gnus)
1034 (choice
1035 (const gnus)
1036 (const gnus-other-frame)))
1037 (cons (const file)
1038 (choice
1039 (const find-file)
1040 (const find-file-other-window)
1041 (const find-file-other-frame)))))
1042
1043 (defcustom org-open-non-existing-files nil
1044 "Non-nil means, `org-open-file' will open non-existing file.
1045 When nil, an error will be generated."
1046 :group 'org-link-follow
1047 :type 'boolean)
1048
1049 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1050 "Non-nil means, ask for confirmation before executing shell links.
1051 Shell links can be dangerous, just thing about a link
1052
1053 [[shell:rm -rf ~/*][Google Search]]
1054
1055 This link would show up in your Org-mode document as \"Google Search\"
1056 but really it would remove your entire home directory.
1057 Therefore I *definitely* advise against setting this variable to nil.
1058 Just change it to `y-or-n-p' of you want to confirm with a single key press
1059 rather than having to type \"yes\"."
1060 :group 'org-link-follow
1061 :type '(choice
1062 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1063 (const :tag "with y-or-n (faster)" y-or-n-p)
1064 (const :tag "no confirmation (dangerous)" nil)))
1065
1066 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1067 "Non-nil means, ask for confirmation before executing elisp links.
1068 Elisp links can be dangerous, just thing about a link
1069
1070 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1071
1072 This link would show up in your Org-mode document as \"Google Search\"
1073 but really it would remove your entire home directory.
1074 Therefore I *definitely* advise against setting this variable to nil.
1075 Just change it to `y-or-n-p' of you want to confirm with a single key press
1076 rather than having to type \"yes\"."
1077 :group 'org-link-follow
1078 :type '(choice
1079 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1080 (const :tag "with y-or-n (faster)" y-or-n-p)
1081 (const :tag "no confirmation (dangerous)" nil)))
1082
1083 (defconst org-file-apps-defaults-gnu
1084 '((remote . emacs)
1085 (t . mailcap))
1086 "Default file applications on a UNIX or GNU/Linux system.
1087 See `org-file-apps'.")
1088
1089 (defconst org-file-apps-defaults-macosx
1090 '((remote . emacs)
1091 (t . "open %s")
1092 ("ps" . "gv %s")
1093 ("ps.gz" . "gv %s")
1094 ("eps" . "gv %s")
1095 ("eps.gz" . "gv %s")
1096 ("dvi" . "xdvi %s")
1097 ("fig" . "xfig %s"))
1098 "Default file applications on a MacOS X system.
1099 The system \"open\" is known as a default, but we use X11 applications
1100 for some files for which the OS does not have a good default.
1101 See `org-file-apps'.")
1102
1103 (defconst org-file-apps-defaults-windowsnt
1104 (list
1105 '(remote . emacs)
1106 (cons t
1107 (list (if (featurep 'xemacs)
1108 'mswindows-shell-execute
1109 'w32-shell-execute)
1110 "open" 'file)))
1111 "Default file applications on a Windows NT system.
1112 The system \"open\" is used for most files.
1113 See `org-file-apps'.")
1114
1115 (defcustom org-file-apps
1116 '(
1117 ("txt" . emacs)
1118 ("tex" . emacs)
1119 ("ltx" . emacs)
1120 ("org" . emacs)
1121 ("el" . emacs)
1122 ("bib" . emacs)
1123 )
1124 "External applications for opening `file:path' items in a document.
1125 Org-mode uses system defaults for different file types, but
1126 you can use this variable to set the application for a given file
1127 extension. The entries in this list are cons cells where the car identifies
1128 files and the cdr the corresponding command. Possible values for the
1129 file identifier are
1130 \"ext\" A string identifying an extension
1131 `directory' Matches a directory
1132 `remote' Matches a remove file, accessible through tramp or efs.
1133 Remote files most likely should be visited through emacs
1134 because external applications cannot handle such paths.
1135 t Default for all remaining files
1136
1137 Possible values for the command are:
1138 `emacs' The file will be visited by the current Emacs process.
1139 `default' Use the default application for this file type.
1140 string A command to be executed by a shell; %s will be replaced
1141 by the path to the file.
1142 sexp A Lisp form which will be evaluated. The file path will
1143 be available in the Lisp variable `file'.
1144 For more examples, see the system specific constants
1145 `org-file-apps-defaults-macosx'
1146 `org-file-apps-defaults-windowsnt'
1147 `org-file-apps-defaults-gnu'."
1148 :group 'org-link-follow
1149 :type '(repeat
1150 (cons (choice :value ""
1151 (string :tag "Extension")
1152 (const :tag "Default for unrecognized files" t)
1153 (const :tag "Remote file" remote)
1154 (const :tag "Links to a directory" directory))
1155 (choice :value ""
1156 (const :tag "Visit with Emacs" emacs)
1157 (const :tag "Use system default" default)
1158 (string :tag "Command")
1159 (sexp :tag "Lisp form")))))
1160
1161 (defcustom org-mhe-search-all-folders nil
1162 "Non-nil means, that the search for the mh-message will be extended to
1163 all folders if the message cannot be found in the folder given in the link.
1164 Searching all folders is very effective with one of the search engines
1165 supported by MH-E, but will be slow with pick."
1166 :group 'org-link-follow
1167 :type 'boolean)
1168
1169 (defgroup org-remember nil
1170 "Options concerning interaction with remember.el."
1171 :tag "Org Remember"
1172 :group 'org)
1173
1174 (defcustom org-directory "~/org"
1175 "Directory with org files.
1176 This directory will be used as default to prompt for org files.
1177 Used by the hooks for remember.el."
1178 :group 'org-remember
1179 :type 'directory)
1180
1181 (defcustom org-default-notes-file "~/.notes"
1182 "Default target for storing notes.
1183 Used by the hooks for remember.el. This can be a string, or nil to mean
1184 the value of `remember-data-file'."
1185 :group 'org-remember
1186 :type '(choice
1187 (const :tag "Default from remember-data-file" nil)
1188 file))
1189
1190 (defcustom org-remember-templates nil
1191 "Templates for the creation of remember buffers.
1192 When nil, just let remember make the buffer.
1193 When not nil, this is a list of 3-element lists. In each entry, the first
1194 element is a character, a unique key to select this template.
1195 The second element is the template. The third element is optional and can
1196 specify a destination file for remember items created with this template.
1197 The default file is given by `org-default-notes-file'.
1198
1199 The template specifies the structure of the remember buffer. It should have
1200 a first line starting with a star, to act as the org-mode headline.
1201 Furthermore, the following %-escapes will be replaced with content:
1202 %t time stamp, date only
1203 %T time stamp with date and time
1204 %u inactive time stamp, date only
1205 %U inactive time stamp with date and time
1206 %n user name
1207 %a annotation, normally the link created with org-store-link
1208 %i initial content, the region when remember is called with C-u.
1209 If %i is indented, the entire inserted text will be indented as well.
1210 %? This will be removed, and the cursor placed at this position."
1211 :group 'org-remember
1212 :type '(repeat :tag "enabled"
1213 (list :value (?a "\n" nil)
1214 (character :tag "Selection Key")
1215 (string :tag "Template")
1216 (file :tag "Destination file (optional)"))))
1217
1218 (defcustom org-reverse-note-order nil
1219 "Non-nil means, store new notes at the beginning of a file or entry.
1220 When nil, new notes will be filed to the end of a file or entry."
1221 :group 'org-remember
1222 :type '(choice
1223 (const :tag "Reverse always" t)
1224 (const :tag "Reverse never" nil)
1225 (repeat :tag "By file name regexp"
1226 (cons regexp boolean))))
1227
1228 (defgroup org-todo nil
1229 "Options concerning TODO items in Org-mode."
1230 :tag "Org TODO"
1231 :group 'org)
1232
1233 (defcustom org-todo-keywords '("TODO" "DONE")
1234 "List of TODO entry keywords.
1235 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1236 considered to mean that the entry is \"done\". All the other mean that
1237 action is required, and will make the entry show up in todo lists, diaries
1238 etc.
1239 The command \\[org-todo] cycles an entry through these states, and an
1240 additional state where no keyword is present. For details about this
1241 cycling, see also the variable `org-todo-interpretation'
1242 Changes become only effective after restarting Emacs."
1243 :group 'org-todo
1244 :group 'org-keywords
1245 :type '(repeat (string :tag "Keyword")))
1246
1247 (defcustom org-todo-interpretation 'sequence
1248 "Controls how TODO keywords are interpreted.
1249 This variable is only relevant if `org-todo-keywords' contains more than two
1250 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1251
1252 When `sequence', \\[org-todo] will always switch to the next state in the
1253 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1254 to state when executed several times in direct succession. Otherwise, it
1255 switches directly to DONE from any state.
1256 See the manual for more information."
1257 :group 'org-todo
1258 :group 'org-keywords
1259 :type '(choice (const sequence)
1260 (const type)))
1261
1262 (defcustom org-after-todo-state-change-hook nil
1263 "Hook which is run after the state of a TODO item was changed.
1264 The new state (a string with a TODO keyword, or nil) is available in the
1265 Lisp variable `state'."
1266 :group 'org-todo
1267 :type 'hook)
1268
1269 (defcustom org-log-done nil
1270 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1271 When the state of an entry is changed from nothing to TODO, remove a previous
1272 closing date.
1273 This can also be configured on a per-file basis by adding one of
1274 the following lines anywhere in the buffer:
1275
1276 #+STARTUP: logging
1277 #+STARTUP: nologging"
1278 :group 'org-todo
1279 :type 'boolean)
1280
1281 (defgroup org-priorities nil
1282 "Priorities in Org-mode."
1283 :tag "Org Priorities"
1284 :group 'org-todo)
1285
1286 (defcustom org-default-priority ?B
1287 "The default priority of TODO items.
1288 This is the priority an item get if no explicit priority is given."
1289 :group 'org-priorities
1290 :type 'character)
1291
1292 (defcustom org-lowest-priority ?C
1293 "The lowest priority of TODO items. A character like ?A, ?B etc."
1294 :group 'org-priorities
1295 :type 'character)
1296
1297 (defgroup org-time nil
1298 "Options concerning time stamps and deadlines in Org-mode."
1299 :tag "Org Time"
1300 :group 'org)
1301
1302 (defcustom org-insert-labeled-timestamps-at-point nil
1303 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1304 When nil, these labeled time stamps are forces into the second line of an
1305 entry, just after the headline. When scheduling from the global TODO list,
1306 the time stamp will always be forced into the second line."
1307 :group 'org-time
1308 :type 'boolean)
1309
1310 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1311 "Formats for `format-time-string' which are used for time stamps.
1312 It is not recommended to change this constant.")
1313
1314 (defcustom org-time-stamp-rounding-minutes 0
1315 "Number of minutes to round time stamps to upon insertion.
1316 When zero, insert the time unmodified. Useful rounding numbers
1317 should be factors of 60, so for example 5, 10, 15.
1318 When this is not zero, you can still force an exact time-stamp by using
1319 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1320 :group 'org-time
1321 :type 'integer)
1322
1323 (defcustom org-deadline-warning-days 30
1324 "No. of days before expiration during which a deadline becomes active.
1325 This variable governs the display in the org file."
1326 :group 'org-time
1327 :type 'number)
1328
1329 (defcustom org-popup-calendar-for-date-prompt t
1330 "Non-nil means, pop up a calendar when prompting for a date.
1331 In the calendar, the date can be selected with mouse-1. However, the
1332 minibuffer will also be active, and you can simply enter the date as well.
1333 When nil, only the minibuffer will be available."
1334 :group 'org-time
1335 :type 'boolean)
1336
1337 (defcustom org-calendar-follow-timestamp-change t
1338 "Non-nil means, make the calendar window follow timestamp changes.
1339 When a timestamp is modified and the calendar window is visible, it will be
1340 moved to the new date."
1341 :group 'org-time
1342 :type 'boolean)
1343
1344 (defgroup org-tags nil
1345 "Options concerning tags in Org-mode."
1346 :tag "Org Tags"
1347 :group 'org)
1348
1349 (defcustom org-tag-alist nil
1350 "List of tags allowed in Org-mode files.
1351 When this list is nil, Org-mode will base TAG input on what is already in the
1352 buffer.
1353 The value of this variable is an alist, the car may be (and should) be a
1354 character that is used to select that tag through the fast-tag-selection
1355 interface. See the manual for details."
1356 :group 'org-tags
1357 :type '(repeat
1358 (choice
1359 (cons (string :tag "Tag name")
1360 (character :tag "Access char"))
1361 (const :tag "Start radio group" (:startgroup))
1362 (const :tag "End radio group" (:endgroup)))))
1363
1364 (defcustom org-use-fast-tag-selection 'auto
1365 "Non-nil means, use fast tag selection scheme.
1366 This is a special interface to select and deselect tags with single keys.
1367 When nil, fast selection is never used.
1368 When the symbol `auto', fast selection is used if and only if selection
1369 characters for tags have been configured, either through the variable
1370 `org-tag-alist' or through a #+TAGS line in the buffer.
1371 When t, fast selection is always used and selection keys are assigned
1372 automatically if necessary."
1373 :group 'org-tags
1374 :type '(choice
1375 (const :tag "Always" t)
1376 (const :tag "Never" nil)
1377 (const :tag "When selection characters are configured" 'auto)))
1378
1379 (defcustom org-tags-column 48
1380 "The column to which tags should be indented in a headline.
1381 If this number is positive, it specifies the column. If it is negative,
1382 it means that the tags should be flushright to that column. For example,
1383 -79 works well for a normal 80 character screen."
1384 :group 'org-tags
1385 :type 'integer)
1386
1387 (defcustom org-auto-align-tags t
1388 "Non-nil means, realign tags after pro/demotion of TODO state change.
1389 These operations change the length of a headline and therefore shift
1390 the tags around. With this options turned on, after each such operation
1391 the tags are again aligned to `org-tags-column'."
1392 :group 'org-tags
1393 :type 'boolean)
1394
1395 (defcustom org-use-tag-inheritance t
1396 "Non-nil means, tags in levels apply also for sublevels.
1397 When nil, only the tags directly given in a specific line apply there.
1398 If you turn off this option, you very likely want to turn on the
1399 companion option `org-tags-match-list-sublevels'."
1400 :group 'org-tags
1401 :type 'boolean)
1402
1403 (defcustom org-tags-match-list-sublevels nil
1404 "Non-nil means list also sublevels of headlines matching tag search.
1405 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1406 the sublevels of a headline matching a tag search often also match
1407 the same search. Listing all of them can create very long lists.
1408 Setting this variable to nil causes subtrees of a match to be skipped.
1409 This option is off by default, because inheritance in on. If you turn
1410 inheritance off, you very likely want to turn this option on.
1411
1412 As a special case, if the tag search is restricted to TODO items, the
1413 value of this variable is ignored and sublevels are always checked, to
1414 make sure all corresponding TODO items find their way into the list."
1415 :group 'org-tags
1416 :type 'boolean)
1417
1418 (defvar org-tags-history nil
1419 "History of minibuffer reads for tags.")
1420 (defvar org-last-tags-completion-table nil
1421 "The last used completion table for tags.")
1422
1423 (defgroup org-agenda nil
1424 "Options concerning agenda display Org-mode."
1425 :tag "Org Agenda"
1426 :group 'org)
1427
1428 (defvar org-category nil
1429 "Variable used by org files to set a category for agenda display.
1430 Such files should use a file variable to set it, for example
1431
1432 -*- mode: org; org-category: \"ELisp\"
1433
1434 or contain a special line
1435
1436 #+CATEGORY: ELisp
1437
1438 If the file does not specify a category, then file's base name
1439 is used instead.")
1440 (make-variable-buffer-local 'org-category)
1441
1442 (defcustom org-agenda-files nil
1443 "The files to be used for agenda display.
1444 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1445 \\[org-remove-file]. You can also use customize to edit the list.
1446
1447 If the value of the variable is not a list but a single file name, then
1448 the list of agenda files is actually stored and maintained in that file, one
1449 agenda file per line."
1450 :group 'org-agenda
1451 :type '(choice
1452 (repeat :tag "List of files" file)
1453 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1454
1455 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1456 "Custom commands for the agenda.
1457 These commands will be offered on the splash screen displayed by the
1458 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1459
1460 key The key (a single char as a string) to be associated with the command.
1461 type The command type, any of the following symbols:
1462 todo Entries with a specific TODO keyword, in all agenda files.
1463 tags Tags match in all agenda files.
1464 tags-todo Tags match in all agenda files, TODO entries only.
1465 todo-tree Sparse tree of specific TODO keyword in *current* file.
1466 tags-tree Sparse tree with all tags matches in *current* file.
1467 occur-tree Occur sparse tree for current file.
1468 match What to search for:
1469 - a single keyword for TODO keyword searches
1470 - a tags match expression for tags searches
1471 - a regular expression for occur searches"
1472 :group 'org-agenda
1473 :type '(repeat
1474 (list (string :tag "Key")
1475 (choice :tag "Type"
1476 (const :tag "Tags search in all agenda files" tags)
1477 (const :tag "Tags search of TODO entries, all agenda files" tags-todo)
1478 (const :tag "TODO keyword search in all agenda files" todo)
1479 (const :tag "Tags sparse tree in current buffer" tags-tree)
1480 (const :tag "TODO keyword tree in current buffer" todo-tree)
1481 (const :tag "Occur tree in current buffer" occur-tree))
1482 (string :tag "Match"))))
1483
1484 (defcustom org-agenda-todo-list-sublevels t
1485 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1486 When nil, the sublevels of a TODO entry are not checked, resulting in
1487 potentially much shorter TODO lists."
1488 :group 'org-agenda
1489 :group 'org-todo
1490 :type 'boolean)
1491
1492 (defcustom org-agenda-todo-ignore-scheduled nil
1493 "Non-nil means, don't show scheduled entries in the global todo list.
1494 The idea behind this is that by scheduling it, you have already taken care
1495 of this item."
1496 :group 'org-agenda
1497 :group 'org-todo
1498 :type 'boolean)
1499
1500 (defcustom org-agenda-include-all-todo nil
1501 "Non-nil means, the agenda will always contain all TODO entries.
1502 When nil, date-less entries will only be shown if `org-agenda' is called
1503 with a prefix argument.
1504 When non-nil, the TODO entries will be listed at the top of the agenda, before
1505 the entries for specific days."
1506 :group 'org-agenda
1507 :type 'boolean)
1508
1509 (defcustom org-agenda-include-diary nil
1510 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1511 :group 'org-agenda
1512 :type 'boolean)
1513
1514 (defcustom org-calendar-to-agenda-key [?c]
1515 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1516 The command `org-calendar-goto-agenda' will be bound to this key. The
1517 default is the character `c' because then `c' can be used to switch back and
1518 forth between agenda and calendar."
1519 :group 'org-agenda
1520 :type 'sexp)
1521
1522 (defgroup org-agenda-setup nil
1523 "Options concerning setting up the Agenda window in Org Mode."
1524 :tag "Org Agenda Window Setup"
1525 :group 'org-agenda)
1526
1527 (defcustom org-agenda-mouse-1-follows-link nil
1528 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1529 A longer mouse click will still set point. Does not wortk on XEmacs.
1530 Needs to be set before org.el is loaded."
1531 :group 'org-agenda-setup
1532 :type 'boolean)
1533
1534 (defcustom org-agenda-start-with-follow-mode nil
1535 "The initial value of follwo-mode in a newly created agenda window."
1536 :group 'org-agenda-setup
1537 :type 'boolean)
1538
1539 (defcustom org-select-agenda-window t
1540 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1541 When nil, cursor will remain in the current window."
1542 :group 'org-agenda-setup
1543 :type 'boolean)
1544
1545 (defcustom org-fit-agenda-window t
1546 "Non-nil means, change window size of agenda to fit content."
1547 :group 'org-agenda-setup
1548 :type 'boolean)
1549
1550 (defgroup org-agenda-display nil
1551 "Options concerning what to display initially in Agenda."
1552 :tag "Org Agenda Display"
1553 :group 'org-agenda)
1554
1555 (defcustom org-agenda-show-all-dates t
1556 "Non-nil means, `org-agenda' shows every day in the selected range.
1557 When nil, only the days which actually have entries are shown."
1558 :group 'org-agenda-display
1559 :type 'boolean)
1560
1561 (defcustom org-agenda-start-on-weekday 1
1562 "Non-nil means, start the overview always on the specified weekday.
1563 0 denotes Sunday, 1 denotes Monday etc.
1564 When nil, always start on the current day."
1565 :group 'org-agenda-display
1566 :type '(choice (const :tag "Today" nil)
1567 (number :tag "Weekday No.")))
1568
1569 (defcustom org-agenda-ndays 7
1570 "Number of days to include in overview display.
1571 Should be 1 or 7."
1572 :group 'org-agenda-display
1573 :type 'number)
1574
1575 (defcustom org-agenda-use-time-grid t
1576 "Non-nil means, show a time grid in the agenda schedule.
1577 A time grid is a set of lines for specific times (like every two hours between
1578 8:00 and 20:00). The items scheduled for a day at specific times are
1579 sorted in between these lines.
1580 For details about when the grid will be shown, and what it will look like, see
1581 the variable `org-agenda-time-grid'."
1582 :group 'org-agenda-display
1583 :type 'boolean)
1584
1585 (defcustom org-agenda-time-grid
1586 '((daily today require-timed)
1587 "----------------"
1588 (800 1000 1200 1400 1600 1800 2000))
1589
1590 "The settings for time grid for agenda display.
1591 This is a list of three items. The first item is again a list. It contains
1592 symbols specifying conditions when the grid should be displayed:
1593
1594 daily if the agenda shows a single day
1595 weekly if the agenda shows an entire week
1596 today show grid on current date, independent of daily/weekly display
1597 require-timed show grid only if at least on item has a time specification
1598
1599 The second item is a string which will be places behing the grid time.
1600
1601 The third item is a list of integers, indicating the times that should have
1602 a grid line."
1603 :group 'org-agenda-display
1604 :type
1605 '(list
1606 (set :greedy t :tag "Grid Display Options"
1607 (const :tag "Show grid in single day agenda display" daily)
1608 (const :tag "Show grid in weekly agenda display" weekly)
1609 (const :tag "Always show grid for today" today)
1610 (const :tag "Show grid only if any timed entries are present"
1611 require-timed)
1612 (const :tag "Skip grid times already present in an entry"
1613 remove-match))
1614 (string :tag "Grid String")
1615 (repeat :tag "Grid Times" (integer :tag "Time"))))
1616
1617 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1618 "Sorting structure for the agenda items of a single day.
1619 This is a list of symbols which will be used in sequence to determine
1620 if an entry should be listed before another entry. The following
1621 symbols are recognized:
1622
1623 time-up Put entries with time-of-day indications first, early first
1624 time-down Put entries with time-of-day indications first, late first
1625 category-keep Keep the default order of categories, corresponding to the
1626 sequence in `org-agenda-files'.
1627 category-up Sort alphabetically by category, A-Z.
1628 category-down Sort alphabetically by category, Z-A.
1629 priority-up Sort numerically by priority, high priority last.
1630 priority-down Sort numerically by priority, high priority first.
1631
1632 The different possibilities will be tried in sequence, and testing stops
1633 if one comparison returns a \"not-equal\". For example, the default
1634 '(time-up category-keep priority-down)
1635 means: Pull out all entries having a specified time of day and sort them,
1636 in order to make a time schedule for the current day the first thing in the
1637 agenda listing for the day. Of the entries without a time indication, keep
1638 the grouped in categories, don't sort the categories, but keep them in
1639 the sequence given in `org-agenda-files'. Within each category sort by
1640 priority.
1641
1642 Leaving out `category-keep' would mean that items will be sorted across
1643 categories by priority."
1644 :group 'org-agenda-display
1645 :type '(repeat
1646 (choice
1647 (const time-up)
1648 (const time-down)
1649 (const category-keep)
1650 (const category-up)
1651 (const category-down)
1652 (const priority-up)
1653 (const priority-down))))
1654
1655 (defcustom org-sort-agenda-notime-is-late t
1656 "Non-nil means, items without time are considered late.
1657 This is only relevant for sorting. When t, items which have no explicit
1658 time like 15:30 will be considered as 99:01, i.e. later than any items which
1659 do have a time. When nil, the default time is before 0:00. You can use this
1660 option to decide if the schedule for today should come before or after timeless
1661 agenda entries."
1662 :group 'org-agenda-display
1663 :type 'boolean)
1664
1665
1666 (defgroup org-agenda-prefix nil
1667 "Options concerning the entry prefix in the Org-mode agenda display."
1668 :tag "Org Agenda Prefix"
1669 :group 'org-agenda)
1670
1671 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1672 "Format specification for the prefix of items in the agenda buffer.
1673 This format works similar to a printf format, with the following meaning:
1674
1675 %c the category of the item, \"Diary\" for entries from the diary, or
1676 as given by the CATEGORY keyword or derived from the file name.
1677 %T the first tag of the item.
1678 %t the time-of-day specification if one applies to the entry, in the
1679 format HH:MM
1680 %s Scheduling/Deadline information, a short string
1681
1682 All specifiers work basically like the standard `%s' of printf, but may
1683 contain two additional characters: A question mark just after the `%' and
1684 a whitespace/punctuation character just before the final letter.
1685
1686 If the first character after `%' is a question mark, the entire field
1687 will only be included if the corresponding value applies to the
1688 current entry. This is useful for fields which should have fixed
1689 width when present, but zero width when absent. For example,
1690 \"%?-12t\" will result in a 12 character time field if a time of the
1691 day is specified, but will completely disappear in entries which do
1692 not contain a time.
1693
1694 If there is punctuation or whitespace character just before the final
1695 format letter, this character will be appended to the field value if
1696 the value is not empty. For example, the format \"%-12:c\" leads to
1697 \"Diary: \" if the category is \"Diary\". If the category were be
1698 empty, no additional colon would be interted.
1699
1700 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1701 - Indent the line with two space characters
1702 - Give the category in a 12 chars wide field, padded with whitespace on
1703 the right (because of `-'). Append a colon if there is a category
1704 (because of `:').
1705 - If there is a time-of-day, put it into a 12 chars wide field. If no
1706 time, don't put in an empty field, just skip it (because of '?').
1707 - Finally, put the scheduling information and append a whitespace.
1708
1709 As another example, if you don't want the time-of-day of entries in
1710 the prefix, you could use:
1711
1712 (setq org-agenda-prefix-format \" %-11:c% s\")
1713
1714 See also the variables `org-agenda-remove-times-when-in-prefix' and
1715 `org-agenda-remove-tags-when-in-prefix'."
1716 :type 'string
1717 :group 'org-agenda-prefix)
1718
1719 (defvar org-prefix-format-compiled nil
1720 "The compiled version of the most recently used prefix format.
1721 Depending on which command was used last, this may be the compiled version
1722 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1723
1724 (defcustom org-agenda-remove-times-when-in-prefix t
1725 "Non-nil means, remove duplicate time specifications in agenda items.
1726 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1727 time-of-day specification in a headline or diary entry is extracted and
1728 placed into the prefix. If this option is non-nil, the original specification
1729 \(a timestamp or -range, or just a plain time(range) specification like
1730 11:30-4pm) will be removed for agenda display. This makes the agenda less
1731 cluttered.
1732 The option can be t or nil. It may also be the symbol `beg', indicating
1733 that the time should only be removed what it is located at the beginning of
1734 the headline/diary entry."
1735 :group 'org-agenda-prefix
1736 :type '(choice
1737 (const :tag "Always" t)
1738 (const :tag "Never" nil)
1739 (const :tag "When at beginning of entry" beg)))
1740
1741 (defcustom org-agenda-remove-tags-when-in-prefix nil
1742 "Non-nil means, remove the tags from the headline copy in the agenda.
1743 When this is the symbol `prefix', only remove tags when
1744 `org-agenda-prefix-format' contains a `%T' specifier."
1745 :group 'org-agenda-prefix
1746 :type '(choice
1747 (const :tag "Always" t)
1748 (const :tag "Never" nil)
1749 (const :tag "When prefix format contains %T" prefix)))
1750
1751 (defgroup org-agenda-timeline nil
1752 "Options concerning the timeline buffer in Org Mode."
1753 :tag "Org Agenda Timeline"
1754 :group 'org-agenda)
1755
1756 (defcustom org-timeline-prefix-format " % s"
1757 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1758 :type 'string
1759 :group 'org-agenda-timeline)
1760
1761 (defcustom org-select-timeline-window t
1762 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1763 When nil, cursor will remain in the current window."
1764 :group 'org-agenda-timeline
1765 :type 'boolean)
1766
1767 (defcustom org-timeline-show-empty-dates 3
1768 "Non-nil means, `org-timeline' also shows dates without an entry.
1769 When nil, only the days which actually have entries are shown.
1770 When t, all days between the first and the last date are shown.
1771 When an integer, show also empty dates, but if there is a gap of more than
1772 N days, just insert a special line indicating the size of the gap."
1773 :group 'org-agenda-timeline
1774 :type '(choice
1775 (const :tag "None" nil)
1776 (const :tag "All" t)
1777 (number :tag "at most")))
1778
1779 (defgroup org-latex nil
1780 "Options for embedding LaTeX code into Org-mode"
1781 :tag "Org LaTeX"
1782 :group 'org)
1783
1784 (defcustom org-format-latex-options
1785 '(:foreground "Black" :background "Transparent" :scale 1.0
1786 :matchers ("begin" "$" "$$" "\\(" "\\["))
1787 "Options for creating images from LaTeX fragments.
1788 This is a property list with the following properties:
1789 :foreground the foreground color, for example \"Black\".
1790 :background the background color, or \"Transparent\".
1791 :scale a scaling factor for the size of the images
1792 :matchers a list indicating which matchers should be used to
1793 find LaTeX fragments. Valid members of this list are:
1794 \"begin\" find environments
1795 \"$\" find math expressions surrounded by $...$
1796 \"$$\" find math expressions surrounded by $$....$$
1797 \"\\(\" find math expressions surrounded by \\(...\\)
1798 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1799 :group 'org-latex
1800 :type 'plist)
1801
1802 (defgroup org-export nil
1803 "Options for exporting org-listings."
1804 :tag "Org Export"
1805 :group 'org)
1806
1807 (defgroup org-export-general nil
1808 "General options for exporting Org-mode files."
1809 :tag "Org Export General"
1810 :group 'org-export)
1811
1812 (defcustom org-export-publishing-directory "."
1813 "Path to the location where exported files should be located.
1814 This path may be relative to the directory where the Org-mode file lives.
1815 The default is to put them into the same directory as the Org-mode file.
1816 The variable may also be an alist with export types `:html', `:ascii',
1817 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1818 is relative, it is interpreted relative to the directory where the exported
1819 Org-mode files lives."
1820 :group 'org-export-general
1821 :type '(choice
1822 (directory)
1823 (repeat
1824 (cons
1825 (choice :tag "Type"
1826 (const :html) (const :ascii) (const :ical) (const :xoxo))
1827 (directory)))))
1828
1829 (defcustom org-export-language-setup
1830 '(("en" "Author" "Date" "Table of Contents")
1831 ("da" "Ophavsmand" "Dato" "Indhold")
1832 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1833 ("es" "Autor" "Fecha" "\xccndice")
1834 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1835 ("it" "Autore" "Data" "Indice")
1836 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1837 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1838 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1839 "Terms used in export text, translated to different languages.
1840 Use the variable `org-export-default-language' to set the language,
1841 or use the +OPTION lines for a per-file setting."
1842 :group 'org-export-general
1843 :type '(repeat
1844 (list
1845 (string :tag "HTML language tag")
1846 (string :tag "Author")
1847 (string :tag "Date")
1848 (string :tag "Table of Contents"))))
1849
1850 (defcustom org-export-default-language "en"
1851 "The default language of HTML export, as a string.
1852 This should have an association in `org-export-language-setup'."
1853 :group 'org-export-general
1854 :type 'string)
1855
1856 (defcustom org-export-headline-levels 3
1857 "The last level which is still exported as a headline.
1858 Inferior levels will produce itemize lists when exported.
1859 Note that a numeric prefix argument to an exporter function overrides
1860 this setting.
1861
1862 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1863 :group 'org-export-general
1864 :type 'number)
1865
1866 (defcustom org-export-with-section-numbers t
1867 "Non-nil means, add section numbers to headlines when exporting.
1868
1869 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1870 :group 'org-export-general
1871 :type 'boolean)
1872
1873 (defcustom org-export-with-toc t
1874 "Non-nil means, create a table of contents in exported files.
1875 The TOC contains headlines with levels up to`org-export-headline-levels'.
1876
1877 Headlines which contain any TODO items will be marked with \"(*)\" in
1878 ASCII export, and with red color in HTML output.
1879
1880 In HTML output, the TOC will be clickable.
1881
1882 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1883 :group 'org-export-general
1884 :type 'boolean)
1885
1886 (defcustom org-export-mark-todo-in-toc nil
1887 "Non-nil means, mark TOC lines that contain any open TODO items."
1888 :group 'org-export-general
1889 :type 'boolean)
1890
1891 (defcustom org-export-preserve-breaks nil
1892 "Non-nil means, preserve all line breaks when exporting.
1893 Normally, in HTML output paragraphs will be reformatted. In ASCII
1894 export, line breaks will always be preserved, regardless of this variable.
1895
1896 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1897 :group 'org-export-general
1898 :type 'boolean)
1899
1900 (defcustom org-export-with-archived-trees 'headline
1901 "Whether subtrees with the ARCHIVE tag should be exported.
1902 This can have three different values
1903 nil Do not export, pretend this tree is not present
1904 t Do export the entire tree
1905 headline Only export the headline, but skip the tree below it."
1906 :group 'org-export-general
1907 :group 'org-archive
1908 :type '(choice
1909 (const :tag "not at all" nil)
1910 (const :tag "headline only" 'headline)
1911 (const :tag "entirely" t)))
1912
1913 (defcustom org-export-with-timestamps t
1914 "Nil means, do not export time stamps and associated keywords."
1915 :group 'org-export
1916 :type 'boolean)
1917
1918 (defcustom org-export-remove-timestamps-from-toc t
1919 "Nil means, remove timestamps from the table of contents entries."
1920 :group 'org-export
1921 :type 'boolean)
1922
1923 (defcustom org-export-with-tags t
1924 "Nil means, do not export tags, just remove them from headlines."
1925 :group 'org-export-general
1926 :type 'boolean)
1927
1928 (defcustom org-export-with-timestamps t
1929 "Nil means, do not export timestamps and associated keywords."
1930 :group 'org-export-general
1931 :type 'boolean)
1932
1933 (defgroup org-export-translation nil
1934 "Options for translating special ascii sequences for the export backends."
1935 :tag "Org Export Translation"
1936 :group 'org-export)
1937
1938 (defcustom org-export-with-emphasize t
1939 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1940 If the export target supports emphasizing text, the word will be
1941 typeset in bold, italic, or underlined, respectively. Works only for
1942 single words, but you can say: I *really* *mean* *this*.
1943 Not all export backends support this.
1944
1945 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1946 :group 'org-export-translation
1947 :type 'boolean)
1948
1949 (defcustom org-export-with-sub-superscripts t
1950 "Non-nil means, interpret \"_\" and \"^\" for export.
1951 When this option is turned on, you can use TeX-like syntax for sub- and
1952 superscripts. Several characters after \"_\" or \"^\" will be
1953 considered as a single item - so grouping with {} is normally not
1954 needed. For example, the following things will be parsed as single
1955 sub- or superscripts.
1956
1957 10^24 or 10^tau several digits will be considered 1 item.
1958 10^-12 or 10^-tau a leading sign with digits or a word
1959 x^2-y^3 will be read as x^2 - y^3, because items are
1960 terminated by almost any nonword/nondigit char.
1961 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1962
1963 Still, ambiguity is possible - so when in doubt use {} to enclose the
1964 sub/superscript.
1965 Not all export backends support this, but HTML does.
1966
1967 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1968 :group 'org-export-translation
1969 :type 'boolean)
1970
1971 (defcustom org-export-with-TeX-macros t
1972 "Non-nil means, interpret simple TeX-like macros when exporting.
1973 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1974 No only real TeX macros will work here, but the standard HTML entities
1975 for math can be used as macro names as well. For a list of supported
1976 names in HTML export, see the constant `org-html-entities'.
1977 Not all export backends support this.
1978
1979 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1980 :group 'org-export-translation
1981 :group 'org-latex
1982 :type 'boolean)
1983
1984 (defcustom org-export-with-LaTeX-fragments nil
1985 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
1986 When set, the exporter will find LaTeX environments if the \\begin line is
1987 the first non-white thing on a line. It will also find the math delimiters
1988 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
1989 display math.
1990
1991 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
1992 :group 'org-export-translation
1993 :group 'org-latex
1994 :type 'boolean)
1995
1996 (defcustom org-export-with-fixed-width t
1997 "Non-nil means, lines starting with \":\" will be in fixed width font.
1998 This can be used to have pre-formatted text, fragments of code etc. For
1999 example:
2000 : ;; Some Lisp examples
2001 : (while (defc cnt)
2002 : (ding))
2003 will be looking just like this in also HTML. See also the QUOTE keyword.
2004 Not all export backends support this.
2005
2006 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2007 :group 'org-export-translation
2008 :type 'boolean)
2009
2010 (defcustom org-match-sexp-depth 3
2011 "Number of stacked braces for sub/superscript matching.
2012 This has to be set before loading org.el to be effective."
2013 :group 'org-export-translation
2014 :type 'integer)
2015
2016 (defgroup org-export-tables nil
2017 "Options for exporting tables in Org-mode."
2018 :tag "Org Export Tables"
2019 :group 'org-export)
2020
2021 (defcustom org-export-with-tables t
2022 "If non-nil, lines starting with \"|\" define a table.
2023 For example:
2024
2025 | Name | Address | Birthday |
2026 |-------------+----------+-----------|
2027 | Arthur Dent | England | 29.2.2100 |
2028
2029 Not all export backends support this.
2030
2031 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2032 :group 'org-export-tables
2033 :type 'boolean)
2034
2035 (defcustom org-export-highlight-first-table-line t
2036 "Non-nil means, highlight the first table line.
2037 In HTML export, this means use <th> instead of <td>.
2038 In tables created with table.el, this applies to the first table line.
2039 In Org-mode tables, all lines before the first horizontal separator
2040 line will be formatted with <th> tags."
2041 :group 'org-export-tables
2042 :type 'boolean)
2043
2044 (defcustom org-export-table-remove-special-lines t
2045 "Remove special lines and marking characters in calculating tables.
2046 This removes the special marking character column from tables that are set
2047 up for spreadsheet calculations. It also removes the entire lines
2048 marked with `!', `_', or `^'. The lines with `$' are kept, because
2049 the values of constants may be useful to have."
2050 :group 'org-export-tables
2051 :type 'boolean)
2052
2053 (defcustom org-export-prefer-native-exporter-for-tables nil
2054 "Non-nil means, always export tables created with table.el natively.
2055 Natively means, use the HTML code generator in table.el.
2056 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2057 the table does not use row- or column-spanning). This has the
2058 advantage, that the automatic HTML conversions for math symbols and
2059 sub/superscripts can be applied. Org-mode's HTML generator is also
2060 much faster."
2061 :group 'org-export-tables
2062 :type 'boolean)
2063
2064 (defgroup org-export-ascii nil
2065 "Options specific for ASCII export of Org-mode files."
2066 :tag "Org Export ASCII"
2067 :group 'org-export)
2068
2069 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2070 "Characters for underlining headings in ASCII export.
2071 In the given sequence, these characters will be used for level 1, 2, ..."
2072 :group 'org-export-ascii
2073 :type '(repeat character))
2074
2075 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2076 "Bullet characters for headlines converted to lists in ASCII export.
2077 The first character is is used for the first lest level generated in this
2078 way, and so on. If there are more levels than characters given here,
2079 the list will be repeated.
2080 Note that plain lists will keep the same bullets as the have in the
2081 Org-mode file."
2082 :group 'org-export-ascii
2083 :type '(repeat character))
2084
2085 (defcustom org-export-ascii-show-new-buffer t
2086 "Non-nil means, popup buffer containing the exported ASCII text.
2087 Otherwise the buffer will just be saved to a file and stay hidden."
2088 :group 'org-export-ascii
2089 :type 'boolean)
2090
2091 (defgroup org-export-xml nil
2092 "Options specific for XML export of Org-mode files."
2093 :tag "Org Export XML"
2094 :group 'org-export)
2095
2096 (defgroup org-export-html nil
2097 "Options specific for HTML export of Org-mode files."
2098 :tag "Org Export HTML"
2099 :group 'org-export)
2100
2101 (defcustom org-export-html-style
2102 "<style type=\"text/css\">
2103 html {
2104 font-family: Times, serif;
2105 font-size: 12pt;
2106 }
2107 .title { text-align: center; }
2108 .todo { color: red; }
2109 .done { color: green; }
2110 .timestamp { color: grey }
2111 .timestamp-kwd { color: CadetBlue }
2112 .tag { background-color:lightblue; font-weight:normal }
2113 .target { background-color: lavender; }
2114 pre {
2115 border: 1pt solid #AEBDCC;
2116 background-color: #F3F5F7;
2117 padding: 5pt;
2118 font-family: courier, monospace;
2119 }
2120 table { border-collapse: collapse; }
2121 td, th {
2122 vertical-align: top;
2123 border: 1pt solid #ADB9CC;
2124 }
2125 </style>"
2126 "The default style specification for exported HTML files.
2127 Since there are different ways of setting style information, this variable
2128 needs to contain the full HTML structure to provide a style, including the
2129 surrounding HTML tags. The style specifications should include definitions
2130 for new classes todo, done, title, and deadline. For example, legal values
2131 would be:
2132
2133 <style type=\"text/css\">
2134 p { font-weight: normal; color: gray; }
2135 h1 { color: black; }
2136 .title { text-align: center; }
2137 .todo, .deadline { color: red; }
2138 .done { color: green; }
2139 </style>
2140
2141 or, if you want to keep the style in a file,
2142
2143 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2144
2145 As the value of this option simply gets inserted into the HTML <head> header,
2146 you can \"misuse\" it to add arbitrary text to the header."
2147 :group 'org-export-html
2148 :type 'string)
2149
2150 (defcustom org-export-html-link-org-files-as-html t
2151 "Non-nil means, make file links to `file.org' point to `file.html'.
2152 When org-mode is exporting an org-mode file to HTML, links to
2153 non-html files are directly put into a href tag in HTML.
2154 However, links to other Org-mode files (recognized by the
2155 extension `.org.) should become links to the corresponding html
2156 file, assuming that the linked org-mode file will also be
2157 converted to HTML.
2158 When nil, the links still point to the plain `.org' file."
2159 :group 'org-export-html
2160 :type 'boolean)
2161
2162 (defcustom org-export-html-inline-images 'maybe
2163 "Non-nil means, inline images into exported HTML pages.
2164 This is done using an <img> tag. When nil, an anchor with href is used to
2165 link to the image. If this option is `maybe', then images in links with
2166 an empty description will be inlined, while images with a description will
2167 be linked only."
2168 :group 'org-export-html
2169 :type '(choice (const :tag "Never" nil)
2170 (const :tag "Always" t)
2171 (const :tag "When there is no description" maybe)))
2172
2173 (defcustom org-export-html-expand t
2174 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2175 When nil, these tags will be exported as plain text and therefore
2176 not be interpreted by a browser.
2177
2178 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2179 :group 'org-export-html
2180 :type 'boolean)
2181
2182 (defcustom org-export-html-table-tag
2183 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2184 "The HTML tag used to start a table.
2185 This must be a <table> tag, but you may change the options like
2186 borders and spacing."
2187 :group 'org-export-html
2188 :type 'string)
2189
2190 (defcustom org-export-html-with-timestamp nil
2191 "If non-nil, write `org-export-html-html-helper-timestamp'
2192 into the exported HTML text. Otherwise, the buffer will just be saved
2193 to a file."
2194 :group 'org-export-html
2195 :type 'boolean)
2196
2197 (defcustom org-export-html-html-helper-timestamp
2198 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2199 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2200 :group 'org-export-html
2201 :type 'string)
2202
2203 (defcustom org-export-html-show-new-buffer nil
2204 "Non-nil means, popup buffer containing the exported html text.
2205 Otherwise, the buffer will just be saved to a file and stay hidden."
2206 :group 'org-export-html
2207 :type 'boolean)
2208
2209 (defgroup org-export-icalendar nil
2210 "Options specific for iCalendar export of Org-mode files."
2211 :tag "Org Export iCalendar"
2212 :group 'org-export)
2213
2214 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2215 "The file name for the iCalendar file covering all agenda files.
2216 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2217 The file name should be absolute."
2218 :group 'org-export-icalendar
2219 :type 'file)
2220
2221 (defcustom org-icalendar-include-todo nil
2222 "Non-nil means, export to iCalendar files should also cover TODO items."
2223 :group 'org-export-icalendar
2224 :type 'boolean)
2225
2226 (defcustom org-icalendar-combined-name "OrgMode"
2227 "Calendar name for the combined iCalendar representing all agenda files."
2228 :group 'org-export-icalendar
2229 :type 'string)
2230
2231 (defgroup org-font-lock nil
2232 "Font-lock settings for highlighting in Org-mode."
2233 :tag "Org Font Lock"
2234 :group 'org)
2235
2236 (defcustom org-level-color-stars-only nil
2237 "Non-nil means fontify only the stars in each headline.
2238 When nil, the entire headline is fontified.
2239 Changing it requires restart of `font-lock-mode' to become effective
2240 also in regions already fontified."
2241 :group 'org-font-lock
2242 :type 'boolean)
2243
2244 (defcustom org-hide-leading-stars nil
2245 "Non-nil means, hide the first N-1 stars in a headline.
2246 This works by using the face `org-hide' for these stars. This
2247 face is white for a light background, and black for a dark
2248 background. You may have to customize the face `org-hide' to
2249 make this work.
2250 Changing it requires restart of `font-lock-mode' to become effective
2251 also in regions already fontified.
2252 You may also set this on a per-file basis by adding one of the following
2253 lines to the buffer:
2254
2255 #+STARTUP: hidestars
2256 #+STARTUP: showstars"
2257 :group 'org-font-lock
2258 :type 'boolean)
2259
2260 (defcustom org-fontify-done-headline nil
2261 "Non-nil means, change the face of a headline if it is marked DONE.
2262 Normally, only the TODO/DONE keyword indicates the state of a headline.
2263 When this is non-nil, the headline after the keyword is set to the
2264 `org-headline-done' as an additional indication."
2265 :group 'org-font-lock
2266 :type 'boolean)
2267
2268 (defcustom org-fontify-emphasized-text t
2269 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2270 Changing this variable requires a restart of Emacs to take effect."
2271 :group 'org-font-lock
2272 :type 'boolean)
2273
2274 (defvar org-emph-re nil
2275 "Regular expression for matching emphasis.")
2276 (defvar org-emphasis-regexp-components) ; defined just below
2277 (defvar org-emphasis-alist) ; defined just below
2278 (defun org-set-emph-re (var val)
2279 "Set variable and compute the emphasis regular expression."
2280 (set var val)
2281 (when (and (boundp 'org-emphasis-alist)
2282 (boundp 'org-emphasis-regexp-components)
2283 org-emphasis-alist org-emphasis-regexp-components)
2284 (let* ((e org-emphasis-regexp-components)
2285 (pre (car e))
2286 (post (nth 1 e))
2287 (border (nth 2 e))
2288 (body (nth 3 e))
2289 (nl (nth 4 e))
2290 (stacked (nth 5 e))
2291 (body1 (concat body "*?"))
2292 (markers (mapconcat 'car org-emphasis-alist "")))
2293 ;; make sure special characters appear at the right position in the class
2294 (if (string-match "\\^" markers)
2295 (setq markers (concat (replace-match "" t t markers) "^")))
2296 (if (string-match "-" markers)
2297 (setq markers (concat (replace-match "" t t markers) "-")))
2298 (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2299 ;; Make the regexp
2300 (setq org-emph-re
2301 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2302 "\\("
2303 "\\([" markers "]\\)"
2304 "\\("
2305 "[^" border markers "]"
2306 body1
2307 "[^" border markers "]"
2308 "\\)"
2309 "\\3\\)"
2310 "\\([" post (if stacked markers) "]\\|$\\)")))))
2311
2312 (defcustom org-emphasis-regexp-components
2313 '(" \t(" " \t.,?;:'\")" " \t\r\n,." "." 1 nil)
2314 "Components used to build the reqular expression for emphasis.
2315 This is a list with 6 entries. Terminology: In an emphasis string
2316 like \" *strong word* \", we call the initial space PREMATCH, the final
2317 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2318 and \"trong wor\" is the body. The different components in this variable
2319 specify what is allowed/forbidden in each part:
2320
2321 pre Chars allowed as prematch. Beginning of line will be allowed too.
2322 post Chars allowed as postmatch. End of line will be allowed too.
2323 border The chars *forbidden* as border characters. In addition to the
2324 characters given here, all marker characters are forbidden too.
2325 body-regexp A regexp like \".\" to match a body character. Don't use
2326 non-shy groups here, and don't allow newline here.
2327 newline The maximum number of newlines allowed in an emphasis exp.
2328 stacked Non-nil means, allow stacked styles. This works only in HTML
2329 export. When this is set, all marker characters (as given in
2330 `org-emphasis-alist') will be allowed as pre/post, aiding
2331 inside-out matching.
2332 Use customize to modify this, or restart emacs after changing it."
2333 :group 'org-font-lock
2334 :set 'org-set-emph-re
2335 :type '(list
2336 (sexp :tag "Allowed chars in pre ")
2337 (sexp :tag "Allowed chars in post ")
2338 (sexp :tag "Forbidden chars in border ")
2339 (sexp :tag "Regexp for body ")
2340 (integer :tag "number of newlines allowed")
2341 (boolean :tag "Stacking allowed ")))
2342
2343 (defcustom org-emphasis-alist
2344 '(("*" bold "<b>" "</b>")
2345 ("/" italic "<i>" "</i>")
2346 ("_" underline "<u>" "</u>")
2347 ("=" shadow "<code>" "</code>")
2348 ("+" (:strike-through t) "<del>" "</del>")
2349 )
2350 "Special syntax for emphasised text.
2351 Text starting and ending with a special character will be emphasized, for
2352 example *bold*, _underlined_ and /italic/. This variable sets the marker
2353 characters, the face to bbe used by font-lock for highlighting in Org-mode
2354 emacs buffers, and the HTML tags to be used for this.
2355 Use customize to modify this, or restart emacs after changing it."
2356 :group 'org-font-lock
2357 :set 'org-set-emph-re
2358 :type '(repeat
2359 (list
2360 (string :tag "Marker character")
2361 (choice
2362 (face :tag "Font-lock-face")
2363 (plist :tag "Face property list"))
2364 (string :tag "HTML start tag")
2365 (string :tag "HTML end tag"))))
2366
2367 (defgroup org-faces nil
2368 "Faces in Org-mode."
2369 :tag "Org Faces"
2370 :group 'org-font-lock)
2371
2372 (defun org-compatible-face (specs)
2373 "Make a compatible face specification.
2374 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2375 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2376 to the top of the list. The `min-colors' attribute will be removed from
2377 any other entries, and any resulting duplicates will be removed entirely."
2378 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2379 (let (r e a)
2380 (while (setq e (pop specs))
2381 (cond
2382 ((memq (car e) '(t default)) (push e r))
2383 ((setq a (member '(min-colors 8) (car e)))
2384 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2385 (cdr e)))))
2386 ((setq a (assq 'min-colors (car e)))
2387 (setq e (cons (delq a (car e)) (cdr e)))
2388 (or (assoc (car e) r) (push e r)))
2389 (t (or (assoc (car e) r) (push e r)))))
2390 (nreverse r))
2391 specs))
2392
2393 (defface org-hide
2394 '((((background light)) (:foreground "white"))
2395 (((background dark)) (:foreground "black")))
2396 "Face used to hide leading stars in headlines.
2397 The forground color of this face should be equal to the background
2398 color of the frame."
2399 :group 'org-faces)
2400
2401 (defface org-level-1 ;; font-lock-function-name-face
2402 (org-compatible-face
2403 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2404 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2405 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2406 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2407 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2408 (t (:bold t))))
2409 "Face used for level 1 headlines."
2410 :group 'org-faces)
2411
2412 (defface org-level-2 ;; font-lock-variable-name-face
2413 (org-compatible-face
2414 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2415 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2416 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2417 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2418 (t (:bold t))))
2419 "Face used for level 2 headlines."
2420 :group 'org-faces)
2421
2422 (defface org-level-3 ;; font-lock-keyword-face
2423 (org-compatible-face
2424 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2425 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2426 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2427 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2428 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2429 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2430 (t (:bold t))))
2431 "Face used for level 3 headlines."
2432 :group 'org-faces)
2433
2434 (defface org-level-4 ;; font-lock-comment-face
2435 (org-compatible-face
2436 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2437 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2438 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2439 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2440 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2441 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2442 (t (:bold t))))
2443 "Face used for level 4 headlines."
2444 :group 'org-faces)
2445
2446 (defface org-level-5 ;; font-lock-type-face
2447 (org-compatible-face
2448 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2449 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2450 (((class color) (min-colors 8)) (:foreground "green"))))
2451 "Face used for level 5 headlines."
2452 :group 'org-faces)
2453
2454 (defface org-level-6 ;; font-lock-constant-face
2455 (org-compatible-face
2456 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2457 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2458 (((class color) (min-colors 8)) (:foreground "magenta"))))
2459 "Face used for level 6 headlines."
2460 :group 'org-faces)
2461
2462 (defface org-level-7 ;; font-lock-builtin-face
2463 (org-compatible-face
2464 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2465 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2466 (((class color) (min-colors 8)) (:foreground "blue"))))
2467 "Face used for level 7 headlines."
2468 :group 'org-faces)
2469
2470 (defface org-level-8 ;; font-lock-string-face
2471 (org-compatible-face
2472 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2473 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2474 (((class color) (min-colors 8)) (:foreground "green"))))
2475 "Face used for level 8 headlines."
2476 :group 'org-faces)
2477
2478 (defface org-special-keyword ;; font-lock-string-face
2479 (org-compatible-face
2480 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2481 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2482 (t (:italic t))))
2483 "Face used for special keywords."
2484 :group 'org-faces)
2485
2486 (defface org-warning ;; font-lock-warning-face
2487 (org-compatible-face
2488 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2489 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2490 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2491 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2492 (t (:bold t))))
2493 "Face for deadlines and TODO keywords."
2494 :group 'org-faces)
2495
2496 (defface org-headline-done ;; font-lock-string-face
2497 (org-compatible-face
2498 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2499 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2500 (((class color) (min-colors 8) (background light)) (:bold nil))))
2501 "Face used to indicate that a headline is DONE.
2502 This face is only used if `org-fontify-done-headline' is set."
2503 :group 'org-faces)
2504
2505 (defface org-archived ; similar to shadow
2506 (org-compatible-face
2507 '((((class color grayscale) (min-colors 88) (background light))
2508 (:foreground "grey50"))
2509 (((class color grayscale) (min-colors 88) (background dark))
2510 (:foreground "grey70"))
2511 (((class color) (min-colors 8) (background light))
2512 (:foreground "green"))
2513 (((class color) (min-colors 8) (background dark))
2514 (:foreground "yellow"))))
2515 "Face for headline with the ARCHIVE tag."
2516 :group 'org-faces)
2517
2518 (defface org-link
2519 '((((class color) (background light)) (:foreground "Purple" :underline t))
2520 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2521 (t (:underline t)))
2522 "Face for links."
2523 :group 'org-faces)
2524
2525 (defface org-date
2526 '((((class color) (background light)) (:foreground "Purple" :underline t))
2527 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2528 (t (:underline t)))
2529 "Face for links."
2530 :group 'org-faces)
2531
2532 (defface org-tag
2533 '((t (:bold t)))
2534 "Face for tags."
2535 :group 'org-faces)
2536
2537 (defface org-todo ;; font-lock-warning-face
2538 (org-compatible-face
2539 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2540 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2541 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2542 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2543 (t (:inverse-video t :bold t))))
2544 "Face for TODO keywords."
2545 :group 'org-faces)
2546
2547 (defface org-done ;; font-lock-type-face
2548 (org-compatible-face
2549 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2550 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2551 (((class color) (min-colors 8)) (:foreground "green"))
2552 (t (:bold t))))
2553 "Face used for DONE."
2554 :group 'org-faces)
2555
2556 (defface org-table ;; font-lock-function-name-face
2557 (org-compatible-face
2558 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2559 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2560 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2561 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2562 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2563 (((class color) (min-colors 8) (background dark)))))
2564 "Face used for tables."
2565 :group 'org-faces)
2566
2567 (defface org-formula
2568 (org-compatible-face
2569 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2570 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2571 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2572 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2573 (t (:bold t :italic t))))
2574 "Face for formulas."
2575 :group 'org-faces)
2576
2577 (defface org-scheduled-today
2578 (org-compatible-face
2579 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2580 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2581 (((class color) (min-colors 8)) (:foreground "green"))
2582 (t (:bold t :italic t))))
2583 "Face for items scheduled for a certain day."
2584 :group 'org-faces)
2585
2586 (defface org-scheduled-previously
2587 (org-compatible-face
2588 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2589 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2590 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2591 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2592 (t (:bold t))))
2593 "Face for items scheduled previously, and not yet done."
2594 :group 'org-faces)
2595
2596 (defface org-upcoming-deadline
2597 (org-compatible-face
2598 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2599 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2600 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2601 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2602 (t (:bold t))))
2603 "Face for items scheduled previously, and not yet done."
2604 :group 'org-faces)
2605
2606 (defface org-time-grid ;; font-lock-variable-name-face
2607 (org-compatible-face
2608 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2609 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2610 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2611 "Face used for time grids."
2612 :group 'org-faces)
2613
2614 (defconst org-level-faces
2615 '(org-level-1 org-level-2 org-level-3 org-level-4
2616 org-level-5 org-level-6 org-level-7 org-level-8
2617 ))
2618 (defconst org-n-levels (length org-level-faces))
2619
2620
2621 ;; Variables for pre-computed regular expressions, all buffer local
2622 (defvar org-done-string nil
2623 "The last string in `org-todo-keywords', indicating an item is DONE.")
2624 (make-variable-buffer-local 'org-done-string)
2625 (defvar org-todo-regexp nil
2626 "Matches any of the TODO state keywords.")
2627 (make-variable-buffer-local 'org-todo-regexp)
2628 (defvar org-not-done-regexp nil
2629 "Matches any of the TODO state keywords except the last one.")
2630 (make-variable-buffer-local 'org-not-done-regexp)
2631 (defvar org-todo-line-regexp nil
2632 "Matches a headline and puts TODO state into group 2 if present.")
2633 (make-variable-buffer-local 'org-todo-line-regexp)
2634 (defvar org-todo-line-tags-regexp nil
2635 "Matches a headline and puts TODO state into group 2 if present.
2636 Also put tags into group 4 if tags are present.")
2637 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2638 (defvar org-nl-done-regexp nil
2639 "Matches newline followed by a headline with the DONE keyword.")
2640 (make-variable-buffer-local 'org-nl-done-regexp)
2641 (defvar org-looking-at-done-regexp nil
2642 "Matches the DONE keyword a point.")
2643 (make-variable-buffer-local 'org-looking-at-done-regexp)
2644 (defvar org-todo-kwd-priority-p nil
2645 "Do TODO items have priorities?")
2646 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2647 (defvar org-todo-kwd-max-priority nil
2648 "Maximum priority of TODO items.")
2649 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2650 (defvar org-ds-keyword-length 12
2651 "Maximum length of the Deadline and SCHEDULED keywords.")
2652 (make-variable-buffer-local 'org-ds-keyword-length)
2653 (defvar org-deadline-regexp nil
2654 "Matches the DEADLINE keyword.")
2655 (make-variable-buffer-local 'org-deadline-regexp)
2656 (defvar org-deadline-time-regexp nil
2657 "Matches the DEADLINE keyword together with a time stamp.")
2658 (make-variable-buffer-local 'org-deadline-time-regexp)
2659 (defvar org-deadline-line-regexp nil
2660 "Matches the DEADLINE keyword and the rest of the line.")
2661 (make-variable-buffer-local 'org-deadline-line-regexp)
2662 (defvar org-scheduled-regexp nil
2663 "Matches the SCHEDULED keyword.")
2664 (make-variable-buffer-local 'org-scheduled-regexp)
2665 (defvar org-scheduled-time-regexp nil
2666 "Matches the SCHEDULED keyword together with a time stamp.")
2667 (make-variable-buffer-local 'org-scheduled-time-regexp)
2668 (defvar org-closed-time-regexp nil
2669 "Matches the CLOSED keyword together with a time stamp.")
2670 (make-variable-buffer-local 'org-closed-time-regexp)
2671
2672 (defvar org-keyword-time-regexp nil
2673 "Matches any of the 3 keywords, together with the time stamp.")
2674 (make-variable-buffer-local 'org-keyword-time-regexp)
2675 (defvar org-maybe-keyword-time-regexp nil
2676 "Matches a timestamp, possibly preceeded by a keyword.")
2677 (make-variable-buffer-local 'org-keyword-time-regexp)
2678
2679 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2680 mouse-map t)
2681 "Properties to remove when a string without properties is wanted.")
2682
2683 (defsubst org-match-string-no-properties (num &optional string)
2684 (if (featurep 'xemacs)
2685 (let ((s (match-string num string)))
2686 (remove-text-properties 0 (length s) org-rm-props s)
2687 s)
2688 (match-string-no-properties num string)))
2689
2690 (defsubst org-no-properties (s)
2691 (remove-text-properties 0 (length s) org-rm-props s)
2692 s)
2693
2694 (defsubst org-mode-p ()
2695 "Check if the current buffer is in Org-mode."
2696 (eq major-mode 'org-mode))
2697
2698 (defun org-set-regexps-and-options ()
2699 "Precompute regular expressions for current buffer."
2700 (when (org-mode-p)
2701 (let ((re (org-make-options-regexp
2702 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2703 "STARTUP" "ARCHIVE" "TAGS")))
2704 (splitre "[ \t]+")
2705 kwds int key value cat arch tags)
2706 (save-excursion
2707 (save-restriction
2708 (widen)
2709 (goto-char (point-min))
2710 (while (re-search-forward re nil t)
2711 (setq key (match-string 1) value (org-match-string-no-properties 2))
2712 (cond
2713 ((equal key "CATEGORY")
2714 (if (string-match "[ \t]+$" value)
2715 (setq value (replace-match "" t t value)))
2716 (setq cat (intern value)))
2717 ((equal key "SEQ_TODO")
2718 (setq int 'sequence
2719 kwds (append kwds (org-split-string value splitre))))
2720 ((equal key "PRI_TODO")
2721 (setq int 'priority
2722 kwds (append kwds (org-split-string value splitre))))
2723 ((equal key "TYP_TODO")
2724 (setq int 'type
2725 kwds (append kwds (org-split-string value splitre))))
2726 ((equal key "TAGS")
2727 (setq tags (append tags (org-split-string value splitre))))
2728 ((equal key "STARTUP")
2729 (let ((opts (org-split-string value splitre))
2730 (set '(("fold" org-startup-folded t)
2731 ("overview" org-startup-folded t)
2732 ("nofold" org-startup-folded nil)
2733 ("showall" org-startup-folded nil)
2734 ("content" org-startup-folded content)
2735 ("hidestars" org-hide-leading-stars t)
2736 ("showstars" org-hide-leading-stars nil)
2737 ("odd" org-odd-levels-only t)
2738 ("oddeven" org-odd-levels-only nil)
2739 ("align" org-startup-align-all-tables t)
2740 ("noalign" org-startup-align-all-tables nil)
2741 ("logging" org-log-done t)
2742 ("nologging" org-log-done nil)
2743 ("dlcheck" org-startup-with-deadline-check t)
2744 ("nodlcheck" org-startup-with-deadline-check nil)))
2745 l var val)
2746 (while (setq l (assoc (pop opts) set))
2747 (setq var (nth 1 l) val (nth 2 l))
2748 (set (make-local-variable var) val))))
2749 ((equal key "ARCHIVE")
2750 (string-match " *$" value)
2751 (setq arch (replace-match "" t t value))
2752 (remove-text-properties 0 (length arch)
2753 '(face t fontified t) arch)))
2754 )))
2755 (and cat (set (make-local-variable 'org-category) cat))
2756 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2757 (and arch (set (make-local-variable 'org-archive-location) arch))
2758 (and int (set (make-local-variable 'org-todo-interpretation) int))
2759 (when tags
2760 (let (e tgs)
2761 (while (setq e (pop tags))
2762 (cond
2763 ((equal e "{") (push '(:startgroup) tgs))
2764 ((equal e "}") (push '(:endgroup) tgs))
2765 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2766 (push (cons (match-string 1 e)
2767 (string-to-char (match-string 2 e)))
2768 tgs))
2769 (t (push (list e) tgs))))
2770 (set (make-local-variable 'org-tag-alist) nil)
2771 (while (setq e (pop tgs))
2772 (or (and (stringp (car e))
2773 (assoc (car e) org-tag-alist))
2774 (push e org-tag-alist))))))
2775
2776 ;; Compute the regular expressions and other local variables
2777 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2778 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2779 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2780 (length org-scheduled-string)))
2781 org-done-string
2782 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2783 org-todo-regexp
2784 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2785 "\\|") "\\)\\>")
2786 org-not-done-regexp
2787 (concat "\\<\\("
2788 (mapconcat 'regexp-quote
2789 (nreverse (cdr (reverse org-todo-keywords)))
2790 "\\|")
2791 "\\)\\>")
2792 org-todo-line-regexp
2793 (concat "^\\(\\*+\\)[ \t]*\\("
2794 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2795 "\\)? *\\(.*\\)")
2796 org-nl-done-regexp
2797 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2798 org-todo-line-tags-regexp
2799 (concat "^\\(\\*+\\)[ \t]*\\("
2800 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2801 "\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
2802 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2803 org-deadline-regexp (concat "\\<" org-deadline-string)
2804 org-deadline-time-regexp
2805 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2806 org-deadline-line-regexp
2807 (concat "\\<\\(" org-deadline-string "\\).*")
2808 org-scheduled-regexp
2809 (concat "\\<" org-scheduled-string)
2810 org-scheduled-time-regexp
2811 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2812 org-closed-time-regexp
2813 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2814 org-keyword-time-regexp
2815 (concat "\\<\\(" org-scheduled-string
2816 "\\|" org-deadline-string
2817 "\\|" org-closed-string
2818 "\\|" org-clock-string "\\)"
2819 " *[[<]\\([^]>]+\\)[]>]")
2820 org-maybe-keyword-time-regexp
2821 (concat "\\(\\<\\(" org-scheduled-string
2822 "\\|" org-deadline-string
2823 "\\|" org-closed-string
2824 "\\|" org-clock-string "\\)\\)?"
2825 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
2826
2827 (org-set-font-lock-defaults)))
2828
2829 ;; Tell the compiler about dynamically scoped variables,
2830 ;; and variables from other packages
2831 (defvar calc-embedded-close-formula) ; defined by the calc package
2832 (defvar calc-embedded-open-formula) ; defined by the calc package
2833 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
2834 (defvar zmacs-regions) ; XEmacs regions
2835 (defvar original-date) ; dynamically scoped in calendar
2836 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2837 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2838 (defvar org-html-entities) ; defined later in this file
2839 (defvar org-goto-start-pos) ; dynamically scoped parameter
2840 (defvar org-time-was-given) ; dynamically scoped parameter
2841 (defvar org-ts-what) ; dynamically scoped parameter
2842 (defvar org-current-export-file) ; dynamically scoped parameter
2843 (defvar org-current-export-dir) ; dynamically scoped parameter
2844 (defvar mark-active) ; Emacs only, not available in XEmacs.
2845 (defvar timecnt) ; dynamically scoped parameter
2846 (defvar levels-open) ; dynamically scoped parameter
2847 (defvar entry) ; dynamically scoped parameter
2848 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
2849 (defvar date) ; dynamically scoped parameter
2850 (defvar description) ; dynamically scoped parameter
2851 (defvar ans1) ; dynamically scoped parameter
2852 (defvar ans2) ; dynamically scoped parameter
2853 (defvar starting-day) ; local variable
2854 (defvar include-all-loc) ; local variable
2855 (defvar vm-message-pointer) ; from vm
2856 (defvar vm-folder-directory) ; from vm
2857 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2858 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2859 (defvar gnus-group-name) ; from gnus
2860 (defvar gnus-article-current) ; from gnus
2861 (defvar w3m-current-url) ; from w3m
2862 (defvar w3m-current-title) ; from w3m
2863 (defvar mh-progs) ; from MH-E
2864 (defvar mh-current-folder) ; from MH-E
2865 (defvar mh-show-folder-buffer) ; from MH-E
2866 (defvar mh-index-folder) ; from MH-E
2867 (defvar mh-searcher) ; from MH-E
2868 (defvar org-selected-point) ; dynamically scoped parameter
2869 (defvar calendar-mode-map) ; from calendar.el
2870 (defvar last-arg) ; local variable
2871 (defvar remember-save-after-remembering) ; from remember.el
2872 (defvar remember-data-file) ; from remember.el
2873 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2874 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2875 (defvar orgtbl-mode) ; defined later in this file
2876 (defvar Info-current-file) ; from info.el
2877 (defvar Info-current-node) ; from info.el
2878 (defvar texmathp-why) ; from texmathp.el
2879 (defvar org-latex-regexps)
2880
2881 ;;; Define the mode
2882
2883 (defvar org-mode-map
2884 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2885 (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.")
2886 (copy-keymap outline-mode-map))
2887 "Keymap for Org-mode.")
2888
2889 (defvar org-struct-menu) ; defined later in this file
2890 (defvar org-org-menu) ; defined later in this file
2891 (defvar org-tbl-menu) ; defined later in this file
2892
2893 ;; We use a before-change function to check if a table might need
2894 ;; an update.
2895 (defvar org-table-may-need-update t
2896 "Indicates that a table might need an update.
2897 This variable is set by `org-before-change-function'.
2898 `org-table-align' sets it back to nil.")
2899 (defvar org-mode-hook nil)
2900 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2901 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2902
2903
2904 ;;;###autoload
2905 (define-derived-mode org-mode outline-mode "Org"
2906 "Outline-based notes management and organizer, alias
2907 \"Carsten's outline-mode for keeping track of everything.\"
2908
2909 Org-mode develops organizational tasks around a NOTES file which
2910 contains information about projects as plain text. Org-mode is
2911 implemented on top of outline-mode, which is ideal to keep the content
2912 of large files well structured. It supports ToDo items, deadlines and
2913 time stamps, which magically appear in the diary listing of the Emacs
2914 calendar. Tables are easily created with a built-in table editor.
2915 Plain text URL-like links connect to websites, emails (VM), Usenet
2916 messages (Gnus), BBDB entries, and any files related to the project.
2917 For printing and sharing of notes, an Org-mode file (or a part of it)
2918 can be exported as a structured ASCII or HTML file.
2919
2920 The following commands are available:
2921
2922 \\{org-mode-map}"
2923
2924 ;; Get rid of Outline menus, they are not needed
2925 ;; Need to do this here because define-derived-mode sets up
2926 ;; the keymap so late.
2927 (if (featurep 'xemacs)
2928 (if org-noutline-p
2929 (progn
2930 (easy-menu-remove outline-mode-menu-heading)
2931 (easy-menu-remove outline-mode-menu-show)
2932 (easy-menu-remove outline-mode-menu-hide))
2933 (delete-menu-item '("Headings"))
2934 (delete-menu-item '("Show"))
2935 (delete-menu-item '("Hide"))
2936 (set-menubar-dirty-flag))
2937 (define-key org-mode-map [menu-bar headings] 'undefined)
2938 (define-key org-mode-map [menu-bar hide] 'undefined)
2939 (define-key org-mode-map [menu-bar show] 'undefined))
2940
2941 (easy-menu-add org-org-menu)
2942 (easy-menu-add org-tbl-menu)
2943 (org-install-agenda-files-menu)
2944 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2945 (org-add-to-invisibility-spec '(org-cwidth))
2946 (when (featurep 'xemacs)
2947 (set (make-local-variable 'line-move-ignore-invisible) t))
2948 (setq outline-regexp "\\*+")
2949 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2950 (setq outline-level 'org-outline-level)
2951 (when (and org-ellipsis (stringp org-ellipsis))
2952 (unless org-display-table
2953 (setq org-display-table (make-display-table)))
2954 (set-display-table-slot org-display-table
2955 4 (string-to-vector org-ellipsis))
2956 (setq buffer-display-table org-display-table))
2957 (org-set-regexps-and-options)
2958 (modify-syntax-entry ?# "<")
2959 (if org-startup-truncated (setq truncate-lines t))
2960 (set (make-local-variable 'font-lock-unfontify-region-function)
2961 'org-unfontify-region)
2962 ;; Activate before-change-function
2963 (set (make-local-variable 'org-table-may-need-update) t)
2964 (org-add-hook 'before-change-functions 'org-before-change-function nil
2965 'local)
2966 ;; Check for running clock before killing a buffer
2967 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
2968 ;; Paragraphs and auto-filling
2969 (org-set-autofill-regexps)
2970 (org-update-radio-target-regexp)
2971
2972 (if (and org-insert-mode-line-in-empty-file
2973 (interactive-p)
2974 (= (point-min) (point-max)))
2975 (insert " -*- mode: org -*-\n\n"))
2976
2977 (unless org-inhibit-startup
2978 (when org-startup-align-all-tables
2979 (let ((bmp (buffer-modified-p)))
2980 (org-table-map-tables 'org-table-align)
2981 (set-buffer-modified-p bmp)))
2982 (if org-startup-with-deadline-check
2983 (call-interactively 'org-check-deadlines)
2984 (cond
2985 ((eq org-startup-folded t)
2986 (org-cycle '(4)))
2987 ((eq org-startup-folded 'content)
2988 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2989 (org-cycle '(4)) (org-cycle '(4))))))))
2990
2991 (defsubst org-call-with-arg (command arg)
2992 "Call COMMAND interactively, but pretend prefix are was ARG."
2993 (let ((current-prefix-arg arg)) (call-interactively command)))
2994
2995 (defsubst org-current-line (&optional pos)
2996 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2997
2998 (defun org-current-time ()
2999 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3000 (if (> org-time-stamp-rounding-minutes 0)
3001 (let ((r org-time-stamp-rounding-minutes)
3002 (time (decode-time)))
3003 (apply 'encode-time
3004 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3005 (nthcdr 2 time))))
3006 (current-time)))
3007
3008 (defun org-add-props (string plist &rest props)
3009 "Add text properties to entire string, from beginning to end.
3010 PLIST may be a list of properties, PROPS are individual properties and values
3011 that will be added to PLIST. Returns the string that was modified."
3012 (add-text-properties
3013 0 (length string) (if props (append plist props) plist) string)
3014 string)
3015 (put 'org-add-props 'lisp-indent-function 2)
3016
3017
3018 ;;; Font-Lock stuff
3019
3020 (defvar org-mouse-map (make-sparse-keymap))
3021 (define-key org-mouse-map
3022 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3023 (define-key org-mouse-map
3024 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3025 (when org-mouse-1-follows-link
3026 (define-key org-mouse-map [follow-link] 'mouse-face))
3027 (when org-tab-follows-link
3028 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3029 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3030 (when org-return-follows-link
3031 (define-key org-mouse-map [(return)] 'org-open-at-point)
3032 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3033
3034 (require 'font-lock)
3035
3036 (defconst org-non-link-chars "]\t\n\r<>")
3037 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3038 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3039 (defconst org-link-re-with-space
3040 (concat
3041 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3042 "\\([^" org-non-link-chars " ]"
3043 "[^" org-non-link-chars "]*"
3044 "[^" org-non-link-chars " ]\\)>?")
3045 "Matches a link with spaces, optional angular brackets around it.")
3046
3047 (defconst org-link-re-with-space2
3048 (concat
3049 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3050 "\\([^" org-non-link-chars " ]"
3051 "[^]\t\n\r]*"
3052 "[^" org-non-link-chars " ]\\)>?")
3053 "Matches a link with spaces, optional angular brackets around it.")
3054
3055 (defconst org-angle-link-re
3056 (concat
3057 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3058 "\\([^" org-non-link-chars " ]"
3059 "[^" org-non-link-chars "]*"
3060 "\\)>")
3061 "Matches link with angular brackets, spaces are allowed.")
3062 (defconst org-plain-link-re
3063 (concat
3064 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3065 "\\([^]\t\n\r<>,;() ]+\\)")
3066 "Matches plain link, without spaces.")
3067
3068 (defconst org-bracket-link-regexp
3069 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3070 "Matches a link in double brackets.")
3071
3072 (defconst org-bracket-link-analytic-regexp
3073 (concat
3074 "\\[\\["
3075 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3076 "\\([^]]+\\)"
3077 "\\]"
3078 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3079 "\\]"))
3080 ; 1: http:
3081 ; 2: http
3082 ; 3: path
3083 ; 4: [desc]
3084 ; 5: desc
3085
3086
3087 (defconst org-ts-lengths
3088 (cons (length (format-time-string (car org-time-stamp-formats)))
3089 (length (format-time-string (cdr org-time-stamp-formats))))
3090 "This holds the lengths of the two different time formats.")
3091 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3092 "Regular expression for fast time stamp matching.")
3093 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3094 "Regular expression for fast time stamp matching.")
3095 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3096 "Regular expression matching time strings for analysis.")
3097 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3098 "Regular expression matching time stamps, with groups.")
3099 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3100 "Regular expression matching time stamps (also [..]), with groups.")
3101 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3102 "Regular expression matching a time stamp range.")
3103 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3104 org-ts-regexp "\\)?")
3105 "Regular expression matching a time stamp or time stamp range.")
3106
3107 (defvar org-§emph-face nil)
3108
3109 (defun org-do-emphasis-faces (limit)
3110 "Run through the buffer and add overlays to links."
3111 (if (re-search-forward org-emph-re limit t)
3112 (progn
3113 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3114 'face
3115 (nth 1 (assoc (match-string 3)
3116 org-emphasis-alist)))
3117 (add-text-properties (match-beginning 2) (match-end 2)
3118 '(font-lock-multiline t))
3119 (backward-char 1)
3120 t)))
3121
3122 (defun org-activate-plain-links (limit)
3123 "Run through the buffer and add overlays to links."
3124 (if (re-search-forward org-plain-link-re limit t)
3125 (progn
3126 (add-text-properties (match-beginning 0) (match-end 0)
3127 (list 'mouse-face 'highlight
3128 'keymap org-mouse-map
3129 ))
3130 t)))
3131
3132 (defun org-activate-angle-links (limit)
3133 "Run through the buffer and add overlays to links."
3134 (if (re-search-forward org-angle-link-re limit t)
3135 (progn
3136 (add-text-properties (match-beginning 0) (match-end 0)
3137 (list 'mouse-face 'highlight
3138 'keymap org-mouse-map
3139 ))
3140 t)))
3141
3142 (defun org-activate-bracket-links (limit)
3143 "Run through the buffer and add overlays to bracketed links."
3144 (if (re-search-forward org-bracket-link-regexp limit t)
3145 (let* ((help (concat "LINK: "
3146 (org-match-string-no-properties 1)))
3147 ;; FIXME: above we should remove the escapes.
3148 ;; but that requires another match, protecting match data,
3149 ;; a lot of overhead for font-lock.
3150 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
3151 'keymap org-mouse-map 'mouse-face 'highlight
3152 'help-echo help))
3153 (vp (list 'rear-nonsticky t
3154 'keymap org-mouse-map 'mouse-face 'highlight
3155 'help-echo help)))
3156 ;; We need to remove the invisible property here. Table narrowing
3157 ;; may have made some of this invisible.
3158 (remove-text-properties (match-beginning 0) (match-end 0)
3159 '(invisible nil))
3160 (if (match-end 3)
3161 (progn
3162 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3163 (add-text-properties (match-beginning 3) (match-end 3) vp)
3164 (add-text-properties (match-end 3) (match-end 0) ip))
3165 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3166 (add-text-properties (match-beginning 1) (match-end 1) vp)
3167 (add-text-properties (match-end 1) (match-end 0) ip))
3168 t)))
3169
3170 (defun org-activate-dates (limit)
3171 "Run through the buffer and add overlays to dates."
3172 (if (re-search-forward org-tsr-regexp limit t)
3173 (progn
3174 (add-text-properties (match-beginning 0) (match-end 0)
3175 (list 'mouse-face 'highlight
3176 'keymap org-mouse-map))
3177 t)))
3178
3179 (defvar org-target-link-regexp nil
3180 "Regular expression matching radio targets in plain text.")
3181 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3182 "Regular expression matching a link target.")
3183 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3184 "Regular expression matching a link target.")
3185
3186 (defun org-activate-target-links (limit)
3187 "Run through the buffer and add overlays to target matches."
3188 (when org-target-link-regexp
3189 (let ((case-fold-search t))
3190 (if (re-search-forward org-target-link-regexp limit t)
3191 (progn
3192 (add-text-properties (match-beginning 0) (match-end 0)
3193 (list 'mouse-face 'highlight
3194 'keymap org-mouse-map
3195 'help-echo "Radio target link"
3196 'org-linked-text t))
3197 t)))))
3198
3199 (defun org-update-radio-target-regexp ()
3200 "Find all radio targets in this file and update the regular expression."
3201 (interactive)
3202 (when (memq 'radio org-activate-links)
3203 (setq org-target-link-regexp
3204 (org-make-target-link-regexp (org-all-targets 'radio)))
3205 (org-restart-font-lock)))
3206
3207 (defun org-hide-wide-columns (limit)
3208 (let (s e)
3209 (setq s (text-property-any (point) (or limit (point-max))
3210 'org-cwidth t))
3211 (when s
3212 (setq e (next-single-property-change s 'org-cwidth))
3213 (add-text-properties s e '(invisible org-cwidth intangible t))
3214 (goto-char e)
3215 t)))
3216
3217 (defun org-restart-font-lock ()
3218 "Restart font-lock-mode, to force refontification."
3219 (when (and (boundp 'font-lock-mode) font-lock-mode)
3220 (font-lock-mode -1)
3221 (font-lock-mode 1)))
3222
3223 (defun org-all-targets (&optional radio)
3224 "Return a list of all targets in this file.
3225 With optional argument RADIO, only find radio targets."
3226 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3227 rtn)
3228 (save-excursion
3229 (goto-char (point-min))
3230 (while (re-search-forward re nil t)
3231 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3232 rtn)))
3233
3234 (defun org-make-target-link-regexp (targets)
3235 "Make regular expression matching all strings in TARGETS.
3236 The regular expression finds the targets also if there is a line break
3237 between words."
3238 (and targets
3239 (concat
3240 "\\<\\("
3241 (mapconcat
3242 (lambda (x)
3243 (while (string-match " +" x)
3244 (setq x (replace-match "\\s-+" t t x)))
3245 x)
3246 targets
3247 "\\|")
3248 "\\)\\>")))
3249
3250 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3251 "Matches CamelCase words, possibly with a star before it.")
3252
3253 (defun org-activate-camels (limit)
3254 "Run through the buffer and add overlays to dates."
3255 (if (re-search-forward org-camel-regexp limit t)
3256 (progn
3257 (add-text-properties (match-beginning 0) (match-end 0)
3258 (list 'mouse-face 'highlight
3259 'keymap org-mouse-map))
3260 t)))
3261
3262 (defun org-activate-tags (limit)
3263 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3264 (progn
3265 (add-text-properties (match-beginning 1) (match-end 1)
3266 (list 'mouse-face 'highlight
3267 'keymap org-mouse-map))
3268 t)))
3269
3270 (defun org-font-lock-level ()
3271 (save-excursion
3272 (org-back-to-heading t)
3273 (- (match-end 0) (match-beginning 0))))
3274
3275 (defun org-outline-level ()
3276 (save-excursion
3277 (looking-at outline-regexp)
3278 (if (match-beginning 1)
3279 (+ (org-get-string-indentation (match-string 1)) 1000)
3280 (- (match-end 0) (match-beginning 0)))))
3281
3282 (defvar org-font-lock-keywords nil)
3283
3284 (defun org-set-font-lock-defaults ()
3285 (let* ((em org-fontify-emphasized-text)
3286 (lk org-activate-links)
3287 (org-font-lock-extra-keywords
3288 ;; Headlines
3289 (list
3290 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3291 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3292 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3293 (1 'org-table))
3294 ;; Links
3295 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3296 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3297 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3298 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3299 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3300 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3301 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3302 (if org-table-limit-column-width
3303 '(org-hide-wide-columns (0 nil append)))
3304 ;; TODO lines
3305 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3306 '(1 'org-todo t))
3307 ;; Priorities
3308 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3309 ;; Special keywords
3310 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3311 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3312 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3313 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3314 ;; Emphasis
3315 (if em '(org-do-emphasis-faces))
3316 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3317 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3318 2 'bold prepend)
3319 ;; COMMENT
3320 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3321 "\\|" org-quote-string "\\)\\>")
3322 '(1 'org-special-keyword t))
3323 '("^#.*" (0 'font-lock-comment-face t))
3324 ;; DONE
3325 (if org-fontify-done-headline
3326 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3327 '(1 'org-done t) '(2 'org-headline-done t))
3328 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3329 '(1 'org-done t)))
3330 ;; Table stuff
3331 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3332 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3333 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3334 (if org-format-transports-properties-p
3335 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3336 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3337 )))
3338 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3339 ;; Now set the full font-lock-keywords
3340 (set (make-local-variable 'org-font-lock-keywords)
3341 org-font-lock-extra-keywords)
3342 (set (make-local-variable 'font-lock-defaults)
3343 '(org-font-lock-keywords t nil nil backward-paragraph))
3344 (kill-local-variable 'font-lock-keywords) nil))
3345
3346 (defvar org-m nil)
3347 (defvar org-l nil)
3348 (defvar org-f nil)
3349 (defun org-get-level-face (n)
3350 "Get the right face for match N in font-lock matching of healdines."
3351 (setq org-l (- (match-end 2) (match-beginning 1)))
3352 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3353 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3354 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3355 (cond
3356 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3357 ((eq n 2) org-f)
3358 (t (if org-level-color-stars-only nil org-f))))
3359
3360 (defun org-unfontify-region (beg end &optional maybe_loudly)
3361 "Remove fontification and activation overlays from links."
3362 (font-lock-default-unfontify-region beg end)
3363 (let* ((buffer-undo-list t)
3364 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3365 (inhibit-modification-hooks t)
3366 deactivate-mark buffer-file-name buffer-file-truename)
3367 (remove-text-properties beg end
3368 '(mouse-face nil keymap nil org-linked-text nil
3369 invisible nil intangible nil))))
3370 ;;; Visibility cycling
3371
3372 (defvar org-cycle-global-status nil)
3373 (make-variable-buffer-local 'org-cycle-global-status)
3374 (defvar org-cycle-subtree-status nil)
3375 (make-variable-buffer-local 'org-cycle-subtree-status)
3376
3377 ;;;###autoload
3378 (defun org-cycle (&optional arg)
3379 "Visibility cycling for Org-mode.
3380
3381 - When this function is called with a prefix argument, rotate the entire
3382 buffer through 3 states (global cycling)
3383 1. OVERVIEW: Show only top-level headlines.
3384 2. CONTENTS: Show all headlines of all levels, but no body text.
3385 3. SHOW ALL: Show everything.
3386
3387 - When point is at the beginning of a headline, rotate the subtree started
3388 by this line through 3 different states (local cycling)
3389 1. FOLDED: Only the main headline is shown.
3390 2. CHILDREN: The main headline and the direct children are shown.
3391 From this state, you can move to one of the children
3392 and zoom in further.
3393 3. SUBTREE: Show the entire subtree, including body text.
3394
3395 - When there is a numeric prefix, go up to a heading with level ARG, do
3396 a `show-subtree' and return to the previous cursor position. If ARG
3397 is negative, go up that many levels.
3398
3399 - When point is not at the beginning of a headline, execute
3400 `indent-relative', like TAB normally does. See the option
3401 `org-cycle-emulate-tab' for details.
3402
3403 - Special case: if point is the the beginning of the buffer and there is
3404 no headline in line 1, this function will act as if called with prefix arg."
3405 (interactive "P")
3406
3407 (let* ((outline-regexp
3408 (if org-cycle-include-plain-lists
3409 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
3410 outline-regexp))
3411 (bob-special (and org-cycle-global-at-bob (bobp)
3412 (not (looking-at outline-regexp))))
3413 (org-cycle-hook
3414 (if bob-special
3415 (delq 'org-optimize-window-after-visibility-change
3416 (copy-sequence org-cycle-hook))
3417 org-cycle-hook))
3418 (pos (point)))
3419
3420 (if (or bob-special (equal arg '(4)))
3421 ;; special case: use global cycling
3422 (setq arg t))
3423
3424 (cond
3425
3426 ((org-at-table-p 'any)
3427 ;; Enter the table or move to the next field in the table
3428 (or (org-table-recognize-table.el)
3429 (progn
3430 (if arg (org-table-edit-field t)
3431 (org-table-justify-field-maybe)
3432 (call-interactively 'org-table-next-field)))))
3433
3434 ((eq arg t) ;; Global cycling
3435
3436 (cond
3437 ((and (eq last-command this-command)
3438 (eq org-cycle-global-status 'overview))
3439 ;; We just created the overview - now do table of contents
3440 ;; This can be slow in very large buffers, so indicate action
3441 (message "CONTENTS...")
3442 (org-content)
3443 (message "CONTENTS...done")
3444 (setq org-cycle-global-status 'contents)
3445 (run-hook-with-args 'org-cycle-hook 'contents))
3446
3447 ((and (eq last-command this-command)
3448 (eq org-cycle-global-status 'contents))
3449 ;; We just showed the table of contents - now show everything
3450 (show-all)
3451 (message "SHOW ALL")
3452 (setq org-cycle-global-status 'all)
3453 (run-hook-with-args 'org-cycle-hook 'all))
3454
3455 (t
3456 ;; Default action: go to overview
3457 (org-overview)
3458 (message "OVERVIEW")
3459 (setq org-cycle-global-status 'overview)
3460 (run-hook-with-args 'org-cycle-hook 'overview))))
3461
3462 ((integerp arg)
3463 ;; Show-subtree, ARG levels up from here.
3464 (save-excursion
3465 (org-back-to-heading)
3466 (outline-up-heading (if (< arg 0) (- arg)
3467 (- (funcall outline-level) arg)))
3468 (org-show-subtree)))
3469
3470 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3471 ;; At a heading: rotate between three different views
3472 (org-back-to-heading)
3473 (let ((goal-column 0) eoh eol eos)
3474 ;; First, some boundaries
3475 (save-excursion
3476 (org-back-to-heading)
3477 (save-excursion
3478 (beginning-of-line 2)
3479 (while (and (not (eobp)) ;; this is like `next-line'
3480 (get-char-property (1- (point)) 'invisible))
3481 (beginning-of-line 2)) (setq eol (point)))
3482 (outline-end-of-heading) (setq eoh (point))
3483 (org-end-of-subtree t) (setq eos (point))
3484 (outline-next-heading))
3485 ;; Find out what to do next and set `this-command'
3486 (cond
3487 ((and (= eos eoh)
3488 ;; Nothing is hidden behind this heading
3489 (message "EMPTY ENTRY")
3490 (setq org-cycle-subtree-status nil)))
3491 ((>= eol eos)
3492 ;; Entire subtree is hidden in one line: open it
3493 (org-show-entry)
3494 (show-children)
3495 (message "CHILDREN")
3496 (setq org-cycle-subtree-status 'children)
3497 (run-hook-with-args 'org-cycle-hook 'children))
3498 ((and (eq last-command this-command)
3499 (eq org-cycle-subtree-status 'children))
3500 ;; We just showed the children, now show everything.
3501 (org-show-subtree)
3502 (message "SUBTREE")
3503 (setq org-cycle-subtree-status 'subtree)
3504 (run-hook-with-args 'org-cycle-hook 'subtree))
3505 (t
3506 ;; Default action: hide the subtree.
3507 (hide-subtree)
3508 (message "FOLDED")
3509 (setq org-cycle-subtree-status 'folded)
3510 (run-hook-with-args 'org-cycle-hook 'folded)))))
3511
3512 ;; TAB emulation
3513 (buffer-read-only (org-back-to-heading))
3514
3515 ((org-try-cdlatex-tab))
3516
3517 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3518 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3519 (or (and (eq org-cycle-emulate-tab 'white)
3520 (= (match-end 0) (point-at-eol)))
3521 (and (eq org-cycle-emulate-tab 'whitestart)
3522 (>= (match-end 0) pos))))
3523 t
3524 (eq org-cycle-emulate-tab t))
3525 (if (and (looking-at "[ \n\r\t]")
3526 (string-match "^[ \t]*$" (buffer-substring
3527 (point-at-bol) (point))))
3528 (progn
3529 (beginning-of-line 1)
3530 (and (looking-at "[ \t]+") (replace-match ""))))
3531 (indent-relative))
3532
3533 (t (save-excursion
3534 (org-back-to-heading)
3535 (org-cycle))))))
3536
3537 ;;;###autoload
3538 (defun org-global-cycle (&optional arg)
3539 "Cycle the global visibility. For details see `org-cycle'."
3540 (interactive "P")
3541 (if (integerp arg)
3542 (progn
3543 (show-all)
3544 (hide-sublevels arg)
3545 (setq org-cycle-global-status 'contents))
3546 (org-cycle '(4))))
3547
3548 (defun org-overview ()
3549 "Switch to overview mode, shoing only top-level headlines.
3550 Really, this shows all headlines with level equal or greater than the level
3551 of the first headline in the buffer. This is important, because if the
3552 first headline is not level one, then (hide-sublevels 1) gives confusing
3553 results."
3554 (interactive)
3555 (hide-sublevels (save-excursion
3556 (goto-char (point-min))
3557 (if (re-search-forward (concat "^" outline-regexp) nil t)
3558 (progn
3559 (goto-char (match-beginning 0))
3560 (funcall outline-level))
3561 1))))
3562
3563 ;; FIXME: allow an argument to give a limiting level for this.
3564 (defun org-content ()
3565 "Show all headlines in the buffer, like a table of contents"
3566 (interactive)
3567 (save-excursion
3568 ;; Visit all headings and show their offspring
3569 (goto-char (point-max))
3570 (catch 'exit
3571 (while (and (progn (condition-case nil
3572 (outline-previous-visible-heading 1)
3573 (error (goto-char (point-min))))
3574 t)
3575 (looking-at outline-regexp))
3576 (show-branches)
3577 (if (bobp) (throw 'exit nil))))))
3578
3579
3580 (defun org-optimize-window-after-visibility-change (state)
3581 "Adjust the window after a change in outline visibility.
3582 This function is the default value of the hook `org-cycle-hook'."
3583 (when (get-buffer-window (current-buffer))
3584 (cond
3585 ((eq state 'overview) (org-first-headline-recenter 1))
3586 ((eq state 'content) nil)
3587 ((eq state 'all) nil)
3588 ((eq state 'folded) nil)
3589 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3590 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3591
3592 (defun org-subtree-end-visible-p ()
3593 "Is the end of the current subtree visible?"
3594 (pos-visible-in-window-p
3595 (save-excursion (org-end-of-subtree t) (point))))
3596
3597 (defun org-first-headline-recenter (&optional N)
3598 "Move cursor to the first headline and recenter the headline.
3599 Optional argument N means, put the headline into the Nth line of the window."
3600 (goto-char (point-min))
3601 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3602 (beginning-of-line)
3603 (recenter (prefix-numeric-value N))))
3604
3605 (defvar org-goto-window-configuration nil)
3606 (defvar org-goto-marker nil)
3607 (defvar org-goto-map (make-sparse-keymap))
3608 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3609 (while (setq cmd (pop cmds))
3610 (substitute-key-definition cmd cmd org-goto-map global-map)))
3611 (define-key org-goto-map "\C-m" 'org-goto-ret)
3612 (define-key org-goto-map [(left)] 'org-goto-left)
3613 (define-key org-goto-map [(right)] 'org-goto-right)
3614 (define-key org-goto-map [(?q)] 'org-goto-quit)
3615 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3616 (define-key org-goto-map "\C-i" 'org-cycle)
3617 (define-key org-goto-map [(tab)] 'org-cycle)
3618 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3619 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3620 (define-key org-goto-map "n" 'outline-next-visible-heading)
3621 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3622 (define-key org-goto-map "f" 'outline-forward-same-level)
3623 (define-key org-goto-map "b" 'outline-backward-same-level)
3624 (define-key org-goto-map "u" 'outline-up-heading)
3625 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3626 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3627 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3628 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3629 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3630 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3631 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3632
3633 (defconst org-goto-help
3634 "Select a location to jump to, press RET
3635 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3636
3637 (defun org-goto ()
3638 "Go to a different location of the document, keeping current visibility.
3639
3640 When you want to go to a different location in a document, the fastest way
3641 is often to fold the entire buffer and then dive into the tree. This
3642 method has the disadvantage, that the previous location will be folded,
3643 which may not be what you want.
3644
3645 This command works around this by showing a copy of the current buffer in
3646 overview mode. You can dive into the tree in that copy, to find the
3647 location you want to reach. When pressing RET, the command returns to the
3648 original buffer in which the visibility is still unchanged. It then jumps
3649 to the new location, making it and the headline hierarchy above it visible."
3650 (interactive)
3651 (let* ((org-goto-start-pos (point))
3652 (selected-point
3653 (org-get-location (current-buffer) org-goto-help)))
3654 (if selected-point
3655 (progn
3656 (org-mark-ring-push org-goto-start-pos)
3657 (goto-char selected-point)
3658 (if (or (org-invisible-p) (org-invisible-p2))
3659 (org-show-hierarchy-above)))
3660 (error "Quit"))))
3661
3662 (defun org-get-location (buf help)
3663 "Let the user select a location in the Org-mode buffer BUF.
3664 This function uses a recursive edit. It returns the selected position
3665 or nil."
3666 (let (org-selected-point)
3667 (save-excursion
3668 (save-window-excursion
3669 (delete-other-windows)
3670 (switch-to-buffer (get-buffer-create "*org-goto*"))
3671 (with-output-to-temp-buffer "*Help*"
3672 (princ help))
3673 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3674 (setq buffer-read-only nil)
3675 (erase-buffer)
3676 (insert-buffer-substring buf)
3677 (let ((org-startup-truncated t)
3678 (org-startup-folded t)
3679 (org-startup-align-all-tables nil)
3680 (org-startup-with-deadline-check nil))
3681 (org-mode))
3682 (setq buffer-read-only t)
3683 (if (boundp 'org-goto-start-pos)
3684 (goto-char org-goto-start-pos)
3685 (goto-char (point-min)))
3686 (org-beginning-of-line)
3687 (message "Select location and press RET")
3688 ;; now we make sure that during selection, ony very few keys work
3689 ;; and that it is impossible to switch to another window.
3690 (let ((gm (current-global-map))
3691 (overriding-local-map org-goto-map))
3692 (unwind-protect
3693 (progn
3694 (use-global-map org-goto-map)
3695 (recursive-edit))
3696 (use-global-map gm)))))
3697 (kill-buffer "*org-goto*")
3698 org-selected-point))
3699
3700 (defun org-goto-ret (&optional arg)
3701 "Finish `org-goto' by going to the new location."
3702 (interactive "P")
3703 (setq org-selected-point (point)
3704 current-prefix-arg arg)
3705 (throw 'exit nil))
3706
3707 (defun org-goto-left ()
3708 "Finish `org-goto' by going to the new location."
3709 (interactive)
3710 (if (org-on-heading-p)
3711 (progn
3712 (beginning-of-line 1)
3713 (setq org-selected-point (point)
3714 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3715 (throw 'exit nil))
3716 (error "Not on a heading")))
3717
3718 (defun org-goto-right ()
3719 "Finish `org-goto' by going to the new location."
3720 (interactive)
3721 (if (org-on-heading-p)
3722 (progn
3723 (outline-end-of-subtree)
3724 (or (eobp) (forward-char 1))
3725 (setq org-selected-point (point)
3726 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3727 (throw 'exit nil))
3728 (error "Not on a heading")))
3729
3730 (defun org-goto-quit ()
3731 "Finish `org-goto' without cursor motion."
3732 (interactive)
3733 (setq org-selected-point nil)
3734 (throw 'exit nil))
3735
3736 ;;; Promotion, Demotion, Inserting new headlines
3737
3738 (defvar org-ignore-region nil
3739 "To temporarily disable the active region.")
3740
3741 (defun org-insert-heading (&optional force-heading)
3742 "Insert a new heading or item with same depth at point.
3743 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3744 If point is at the beginning of a headline, insert a sibling before the
3745 current headline. If point is in the middle of a headline, split the headline
3746 at that position and make the rest of the headline part of the sibling below
3747 the current headline."
3748 (interactive "P")
3749 (if (= (buffer-size) 0)
3750 (insert "\n* ")
3751 (when (or force-heading (not (org-insert-item)))
3752 (let* ((head (save-excursion
3753 (condition-case nil
3754 (progn
3755 (org-back-to-heading)
3756 (match-string 0))
3757 (error "*"))))
3758 pos)
3759 (cond
3760 ((and (org-on-heading-p) (bolp)
3761 (save-excursion (backward-char 1) (not (org-invisible-p))))
3762 (open-line 1))
3763 ((and (bolp) (save-excursion
3764 (backward-char 1) (not (org-invisible-p))))
3765 nil)
3766 (t (newline)))
3767 (insert head) (just-one-space)
3768 (setq pos (point))
3769 (end-of-line 1)
3770 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3771 (run-hooks 'org-insert-heading-hook)))))
3772
3773 (defun org-insert-item (&optional checkbox)
3774 "Insert a new item at the current level.
3775 Return t when things worked, nil when we are not in an item."
3776 (when (save-excursion
3777 (condition-case nil
3778 (progn
3779 (org-beginning-of-item)
3780 (org-at-item-p)
3781 t)
3782 (error nil)))
3783 (let* ((bul (match-string 0))
3784 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3785 (match-end 0)))
3786 pos)
3787 (cond
3788 ((and (org-at-item-p) (<= (point) eow))
3789 ;; before the bullet
3790 (beginning-of-line 1)
3791 (open-line 1))
3792 ((<= (point) eow)
3793 (beginning-of-line 1))
3794 (t (newline)))
3795 (insert bul (if checkbox "[ ]" ""))
3796 (just-one-space)
3797 (setq pos (point))
3798 (end-of-line 1)
3799 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3800 (org-maybe-renumber-ordered-list)
3801 t))
3802
3803 (defun org-insert-todo-heading (arg)
3804 "Insert a new heading with the same level and TODO state as current heading.
3805 If the heading has no TODO state, or if the state is DONE, use the first
3806 state (TODO by default). Also with prefix arg, force first state."
3807 (interactive "P")
3808 (when (not (org-insert-item 'checkbox))
3809 (org-insert-heading)
3810 (save-excursion
3811 (org-back-to-heading)
3812 (if org-noutline-p
3813 (outline-previous-heading)
3814 (outline-previous-visible-heading t))
3815 (looking-at org-todo-line-regexp))
3816 (if (or arg
3817 (not (match-beginning 2))
3818 (equal (match-string 2) org-done-string))
3819 (insert (car org-todo-keywords) " ")
3820 (insert (match-string 2) " "))))
3821
3822 (defun org-promote-subtree ()
3823 "Promote the entire subtree.
3824 See also `org-promote'."
3825 (interactive)
3826 (save-excursion
3827 (org-map-tree 'org-promote)))
3828
3829 (defun org-demote-subtree ()
3830 "Demote the entire subtree. See `org-demote'.
3831 See also `org-promote'."
3832 (interactive)
3833 (save-excursion
3834 (org-map-tree 'org-demote)))
3835
3836 (defun org-do-promote ()
3837 "Promote the current heading higher up the tree.
3838 If the region is active in `transient-mark-mode', promote all headings
3839 in the region."
3840 (interactive)
3841 (save-excursion
3842 (if (org-region-active-p)
3843 (org-map-region 'org-promote (region-beginning) (region-end))
3844 (org-promote)))
3845 (org-fix-position-after-promote))
3846
3847 (defun org-do-demote ()
3848 "Demote the current heading lower down the tree.
3849 If the region is active in `transient-mark-mode', demote all headings
3850 in the region."
3851 (interactive)
3852 (save-excursion
3853 (if (org-region-active-p)
3854 (org-map-region 'org-demote (region-beginning) (region-end))
3855 (org-demote)))
3856 (org-fix-position-after-promote))
3857
3858 (defun org-fix-position-after-promote ()
3859 "Make sure that after pro/demotion cursor position is right."
3860 (and (equal (char-after) ?\ )
3861 (equal (char-before) ?*)
3862 (forward-char 1)))
3863
3864 (defun org-get-legal-level (level change)
3865 "Rectify a level change under the influence of `org-odd-levels-only'
3866 LEVEL is a current level, CHANGE is by how much the level should be
3867 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3868 even level numbers will become the next higher odd number."
3869 (if org-odd-levels-only
3870 (cond ((not change) (1+ (* 2 (/ level 2))))
3871 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3872 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3873 (max 1 (+ level change))))
3874
3875 (defun org-promote ()
3876 "Promote the current heading higher up the tree.
3877 If the region is active in `transient-mark-mode', promote all headings
3878 in the region."
3879 (org-back-to-heading t)
3880 (let* ((level (save-match-data (funcall outline-level)))
3881 (up-head (make-string (org-get-legal-level level -1) ?*))
3882 (diff (abs (- level (length up-head)))))
3883 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3884 (replace-match up-head nil t)
3885 ;; Fixup tag positioning
3886 (and org-auto-align-tags (org-set-tags nil t))
3887 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
3888
3889 (defun org-demote ()
3890 "Demote the current heading lower down the tree.
3891 If the region is active in `transient-mark-mode', demote all headings
3892 in the region."
3893 (org-back-to-heading t)
3894 (let* ((level (save-match-data (funcall outline-level)))
3895 (down-head (make-string (org-get-legal-level level 1) ?*))
3896 (diff (abs (- level (length down-head)))))
3897 (replace-match down-head nil t)
3898 ;; Fixup tag positioning
3899 (and org-auto-align-tags (org-set-tags nil t))
3900 (if org-adapt-indentation (org-fixup-indentation diff))))
3901
3902 (defun org-map-tree (fun)
3903 "Call FUN for every heading underneath the current one."
3904 (org-back-to-heading)
3905 (let ((level (funcall outline-level)))
3906 (save-excursion
3907 (funcall fun)
3908 (while (and (progn
3909 (outline-next-heading)
3910 (> (funcall outline-level) level))
3911 (not (eobp)))
3912 (funcall fun)))))
3913
3914 (defun org-map-region (fun beg end)
3915 "Call FUN for every heading between BEG and END."
3916 (let ((org-ignore-region t))
3917 (save-excursion
3918 (setq end (copy-marker end))
3919 (goto-char beg)
3920 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3921 (< (point) end))
3922 (funcall fun))
3923 (while (and (progn
3924 (outline-next-heading)
3925 (< (point) end))
3926 (not (eobp)))
3927 (funcall fun)))))
3928
3929 (defun org-fixup-indentation (diff)
3930 "Change the indentation in the current entry by DIFF
3931 However, if any line in the current entry has no indentation, or if it
3932 would end up with no indentation after the change, nothing at all is done."
3933 (save-excursion
3934 (let ((end (save-excursion (outline-next-heading)
3935 (point-marker)))
3936 (prohibit (if (> diff 0)
3937 "^\\S-"
3938 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
3939 col)
3940 (unless (save-excursion (re-search-forward prohibit end t))
3941 (while (re-search-forward "^[ \t]+" end t)
3942 (goto-char (match-end 0))
3943 (setq col (current-column))
3944 (if (< diff 0) (replace-match ""))
3945 (indent-to (+ diff col))))
3946 (move-marker end nil))))
3947
3948 ;;; Vertical tree motion, cutting and pasting of subtrees
3949
3950 (defun org-move-subtree-up (&optional arg)
3951 "Move the current subtree up past ARG headlines of the same level."
3952 (interactive "p")
3953 (org-move-subtree-down (- (prefix-numeric-value arg))))
3954
3955 (defun org-move-subtree-down (&optional arg)
3956 "Move the current subtree down past ARG headlines of the same level."
3957 (interactive "p")
3958 (setq arg (prefix-numeric-value arg))
3959 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3960 'outline-get-last-sibling))
3961 (ins-point (make-marker))
3962 (cnt (abs arg))
3963 beg end txt folded)
3964 ;; Select the tree
3965 (org-back-to-heading)
3966 (setq beg (point))
3967 (save-match-data
3968 (save-excursion (outline-end-of-heading)
3969 (setq folded (org-invisible-p)))
3970 (outline-end-of-subtree))
3971 (outline-next-heading)
3972 (setq end (point))
3973 ;; Find insertion point, with error handling
3974 (goto-char beg)
3975 (while (> cnt 0)
3976 (or (and (funcall movfunc) (looking-at outline-regexp))
3977 (progn (goto-char beg)
3978 (error "Cannot move past superior level or buffer limit")))
3979 (setq cnt (1- cnt)))
3980 (if (> arg 0)
3981 ;; Moving forward - still need to move over subtree
3982 (progn (outline-end-of-subtree)
3983 (outline-next-heading)
3984 (if (not (or (looking-at (concat "^" outline-regexp))
3985 (bolp)))
3986 (newline))))
3987 (move-marker ins-point (point))
3988 (setq txt (buffer-substring beg end))
3989 (delete-region beg end)
3990 (insert txt)
3991 (goto-char ins-point)
3992 (if folded (hide-subtree))
3993 (move-marker ins-point nil)))
3994
3995 (defvar org-subtree-clip ""
3996 "Clipboard for cut and paste of subtrees.
3997 This is actually only a copy of the kill, because we use the normal kill
3998 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3999
4000 (defvar org-subtree-clip-folded nil
4001 "Was the last copied subtree folded?
4002 This is used to fold the tree back after pasting.")
4003
4004 (defun org-cut-subtree ()
4005 "Cut the current subtree into the clipboard.
4006 This is a short-hand for marking the subtree and then cutting it."
4007 (interactive)
4008 (org-copy-subtree 'cut))
4009
4010 (defun org-copy-subtree (&optional cut)
4011 "Cut the current subtree into the clipboard.
4012 This is a short-hand for marking the subtree and then copying it.
4013 If CUT is non nil, actually cut the subtree."
4014 (interactive)
4015 (let (beg end folded)
4016 (org-back-to-heading)
4017 (setq beg (point))
4018 (save-match-data
4019 (save-excursion (outline-end-of-heading)
4020 (setq folded (org-invisible-p)))
4021 (outline-end-of-subtree))
4022 (if (equal (char-after) ?\n) (forward-char 1))
4023 (setq end (point))
4024 (goto-char beg)
4025 (when (> end beg)
4026 (setq org-subtree-clip-folded folded)
4027 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4028 (setq org-subtree-clip (current-kill 0))
4029 (message "%s: Subtree with %d characters"
4030 (if cut "Cut" "Copied")
4031 (length org-subtree-clip)))))
4032
4033 (defun org-paste-subtree (&optional level tree)
4034 "Paste the clipboard as a subtree, with modification of headline level.
4035 The entire subtree is promoted or demoted in order to match a new headline
4036 level. By default, the new level is derived from the visible headings
4037 before and after the insertion point, and taken to be the inferior headline
4038 level of the two. So if the previous visible heading is level 3 and the
4039 next is level 4 (or vice versa), level 4 will be used for insertion.
4040 This makes sure that the subtree remains an independent subtree and does
4041 not swallow low level entries.
4042
4043 You can also force a different level, either by using a numeric prefix
4044 argument, or by inserting the heading marker by hand. For example, if the
4045 cursor is after \"*****\", then the tree will be shifted to level 5.
4046
4047 If you want to insert the tree as is, just use \\[yank].
4048
4049 If optional TREE is given, use this text instead of the kill ring."
4050 (interactive "P")
4051 (unless (org-kill-is-subtree-p tree)
4052 (error
4053 (substitute-command-keys
4054 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4055 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4056 (^re (concat "^\\(" outline-regexp "\\)"))
4057 (re (concat "\\(" outline-regexp "\\)"))
4058 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4059
4060 (old-level (if (string-match ^re txt)
4061 (- (match-end 0) (match-beginning 0))
4062 -1))
4063 (force-level (cond (level (prefix-numeric-value level))
4064 ((string-match
4065 ^re_ (buffer-substring (point-at-bol) (point)))
4066 (- (match-end 0) (match-beginning 0)))
4067 (t nil)))
4068 (previous-level (save-excursion
4069 (condition-case nil
4070 (progn
4071 (outline-previous-visible-heading 1)
4072 (if (looking-at re)
4073 (- (match-end 0) (match-beginning 0))
4074 1))
4075 (error 1))))
4076 (next-level (save-excursion
4077 (condition-case nil
4078 (progn
4079 (outline-next-visible-heading 1)
4080 (if (looking-at re)
4081 (- (match-end 0) (match-beginning 0))
4082 1))
4083 (error 1))))
4084 (new-level (or force-level (max previous-level next-level)))
4085 (shift (if (or (= old-level -1)
4086 (= new-level -1)
4087 (= old-level new-level))
4088 0
4089 (- new-level old-level)))
4090 (shift1 shift)
4091 (delta (if (> shift 0) -1 1))
4092 (func (if (> shift 0) 'org-demote 'org-promote))
4093 (org-odd-levels-only nil)
4094 beg end)
4095 ;; Remove the forces level indicator
4096 (if force-level
4097 (delete-region (point-at-bol) (point)))
4098 ;; Make sure we start at the beginning of an empty line
4099 (if (not (bolp)) (insert "\n"))
4100 (if (not (looking-at "[ \t]*$"))
4101 (progn (insert "\n") (backward-char 1)))
4102 ;; Paste
4103 (setq beg (point))
4104 (if (string-match "[ \t\r\n]+\\'" txt)
4105 (setq txt (replace-match "\n" t t txt)))
4106 (insert txt)
4107 (setq end (point))
4108 (if (looking-at "[ \t\r\n]+")
4109 (replace-match "\n"))
4110 (goto-char beg)
4111 ;; Shift if necessary
4112 (if (= shift 0)
4113 (message "Pasted at level %d, without shift" new-level)
4114 (save-restriction
4115 (narrow-to-region beg end)
4116 (while (not (= shift 0))
4117 (org-map-region func (point-min) (point-max))
4118 (setq shift (+ delta shift)))
4119 (goto-char (point-min))
4120 (message "Pasted at level %d, with shift by %d levels"
4121 new-level shift1)))
4122 (if (and kill-ring
4123 (eq org-subtree-clip (current-kill 0))
4124 org-subtree-clip-folded)
4125 ;; The tree was folded before it was killed/copied
4126 (hide-subtree))))
4127
4128 (defun org-kill-is-subtree-p (&optional txt)
4129 "Check if the current kill is an outline subtree, or a set of trees.
4130 Returns nil if kill does not start with a headline, or if the first
4131 headline level is not the largest headline level in the tree.
4132 So this will actually accept several entries of equal levels as well,
4133 which is OK for `org-paste-subtree'.
4134 If optional TXT is given, check this string instead of the current kill."
4135 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4136 (start-level (and kill
4137 (string-match (concat "\\`" outline-regexp) kill)
4138 (- (match-end 0) (match-beginning 0))))
4139 (re (concat "^" outline-regexp))
4140 (start 1))
4141 (if (not start-level)
4142 nil ;; does not even start with a heading
4143 (catch 'exit
4144 (while (setq start (string-match re kill (1+ start)))
4145 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4146 (throw 'exit nil)))
4147 t))))
4148
4149 (defun org-narrow-to-subtree ()
4150 "Narrow buffer to the current subtree."
4151 (interactive)
4152 (save-excursion
4153 (narrow-to-region
4154 (progn (org-back-to-heading) (point))
4155 (progn (org-end-of-subtree t) (point)))))
4156
4157 ;;; Plain list items
4158
4159 (defun org-at-item-p ()
4160 "Is point in a line starting a hand-formatted item?"
4161 (let ((llt org-plain-list-ordered-item-terminator))
4162 (save-excursion
4163 (goto-char (point-at-bol))
4164 (looking-at
4165 (cond
4166 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4167 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4168 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4169 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4170
4171 (defun org-at-item-checkbox-p ()
4172 "Is point at a line starting a plain-list item with a checklet?"
4173 (and (org-at-item-p)
4174 (save-excursion
4175 (goto-char (match-end 0))
4176 (skip-chars-forward " \t")
4177 (looking-at "\\[[ X]\\]"))))
4178
4179 (defun org-toggle-checkbox (&optional arg)
4180 "Toggle the checkbox in the current line."
4181 (interactive "P")
4182 (catch 'exit
4183 (let (beg end status (firstnew 'unknown))
4184 (cond
4185 ((org-region-active-p)
4186 (setq beg (region-beginning) end (region-end)))
4187 ((org-on-heading-p)
4188 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4189 ((org-at-item-checkbox-p)
4190 (save-excursion
4191 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4192 (throw 'exit t))
4193 (t (error "Not at a checkbox or heading, and no active region")))
4194 (save-excursion
4195 (goto-char beg)
4196 (while (< (point) end)
4197 (when (org-at-item-checkbox-p)
4198 (setq status (equal (match-string 0) "[X]"))
4199 (when (eq firstnew 'unknown)
4200 (setq firstnew (not status)))
4201 (replace-match
4202 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4203 (beginning-of-line 2))))))
4204
4205 (defun org-get-indentation (&optional line)
4206 "Get the indentation of the current line, interpreting tabs.
4207 When LINE is given, assume it represents a line and compute its indentation."
4208 (if line
4209 (if (string-match "^ *" (org-remove-tabs line))
4210 (match-end 0))
4211 (save-excursion
4212 (beginning-of-line 1)
4213 (skip-chars-forward " \t")
4214 (current-column))))
4215
4216 (defun org-remove-tabs (s &optional width)
4217 "Replace tabulators in S with spaces.
4218 Assumes that s is a single line, starting in column 0."
4219 (setq width (or width tab-width))
4220 (while (string-match "\t" s)
4221 (setq s (replace-match
4222 (make-string
4223 (- (* width (/ (+ (match-beginning 0) width) width))
4224 (match-beginning 0)) ?\ )
4225 t t s)))
4226 s)
4227
4228 ;; FIXME: document properly.
4229 (defun org-fix-indentation (line ind)
4230 "If the current indenation is smaller than ind1, leave it alone.
4231 If it is larger than ind, reduce it by ind."
4232 (let* ((l (org-remove-tabs line))
4233 (i (org-get-indentation l))
4234 (i1 (car ind)) (i2 (cdr ind)))
4235 (if (>= i i2) (setq l (substring line i2)))
4236 (if (> i1 0)
4237 (concat (make-string i1 ?\ ) l)
4238 l)))
4239
4240 (defun org-beginning-of-item ()
4241 "Go to the beginning of the current hand-formatted item.
4242 If the cursor is not in an item, throw an error."
4243 (interactive)
4244 (let ((pos (point))
4245 (limit (save-excursion (org-back-to-heading)
4246 (beginning-of-line 2) (point)))
4247 ind ind1)
4248 (if (org-at-item-p)
4249 (beginning-of-line 1)
4250 (beginning-of-line 1)
4251 (skip-chars-forward " \t")
4252 (setq ind (current-column))
4253 (if (catch 'exit
4254 (while t
4255 (beginning-of-line 0)
4256 (if (< (point) limit) (throw 'exit nil))
4257 (unless (looking-at "[ \t]*$")
4258 (skip-chars-forward " \t")
4259 (setq ind1 (current-column))
4260 (if (< ind1 ind)
4261 (throw 'exit (org-at-item-p))))))
4262 nil
4263 (goto-char pos)
4264 (error "Not in an item")))))
4265
4266 (defun org-end-of-item ()
4267 "Go to the end of the current hand-formatted item.
4268 If the cursor is not in an item, throw an error."
4269 (interactive)
4270 (let ((pos (point))
4271 (limit (save-excursion (outline-next-heading) (point)))
4272 (ind (save-excursion
4273 (org-beginning-of-item)
4274 (skip-chars-forward " \t")
4275 (current-column)))
4276 ind1)
4277 (if (catch 'exit
4278 (while t
4279 (beginning-of-line 2)
4280 (if (>= (point) limit) (throw 'exit t))
4281 (unless (looking-at "[ \t]*$")
4282 (skip-chars-forward " \t")
4283 (setq ind1 (current-column))
4284 (if (<= ind1 ind) (throw 'exit t)))))
4285 (beginning-of-line 1)
4286 (goto-char pos)
4287 (error "Not in an item"))))
4288
4289 (defun org-next-item ()
4290 "Move to the beginning of the next item in the current plain list.
4291 Error if not at a plain list, or if this is the last item in the list."
4292 (interactive)
4293 (let (ind ind1 (pos (point)))
4294 (org-beginning-of-item)
4295 (setq ind (org-get-indentation))
4296 (org-end-of-item)
4297 (setq ind1 (org-get-indentation))
4298 (unless (and (org-at-item-p) (= ind ind1))
4299 (goto-char pos)
4300 (error "On last item"))))
4301
4302 (defun org-previous-item ()
4303 "Move to the beginning of the previous item in the current plain list.
4304 Error if not at a plain list, or if this is the last item in the list."
4305 (interactive)
4306 (let (beg ind (pos (point)))
4307 (org-beginning-of-item)
4308 (setq beg (point))
4309 (setq ind (org-get-indentation))
4310 (goto-char beg)
4311 (catch 'exit
4312 (while t
4313 (beginning-of-line 0)
4314 (if (looking-at "[ \t]*$")
4315 nil
4316 (if (<= (org-get-indentation) ind)
4317 (throw 'exit t)))))
4318 (condition-case nil
4319 (org-beginning-of-item)
4320 (error (goto-char pos)
4321 (error "On first item")))))
4322
4323 (defun org-move-item-down ()
4324 "Move the plain list item at point down, i.e. swap with following item.
4325 Subitems (items with larger indentation) are considered part of the item,
4326 so this really moves item trees."
4327 (interactive)
4328 (let (beg end ind ind1 (pos (point)) txt)
4329 (org-beginning-of-item)
4330 (setq beg (point))
4331 (setq ind (org-get-indentation))
4332 (org-end-of-item)
4333 (setq end (point))
4334 (setq ind1 (org-get-indentation))
4335 (if (and (org-at-item-p) (= ind ind1))
4336 (progn
4337 (org-end-of-item)
4338 (setq txt (buffer-substring beg end))
4339 (save-excursion
4340 (delete-region beg end))
4341 (setq pos (point))
4342 (insert txt)
4343 (goto-char pos)
4344 (org-maybe-renumber-ordered-list))
4345 (goto-char pos)
4346 (error "Cannot move this item further down"))))
4347
4348 (defun org-move-item-up (arg)
4349 "Move the plain list item at point up, i.e. swap with previous item.
4350 Subitems (items with larger indentation) are considered part of the item,
4351 so this really moves item trees."
4352 (interactive "p")
4353 (let (beg end ind ind1 (pos (point)) txt)
4354 (org-beginning-of-item)
4355 (setq beg (point))
4356 (setq ind (org-get-indentation))
4357 (org-end-of-item)
4358 (setq end (point))
4359 (goto-char beg)
4360 (catch 'exit
4361 (while t
4362 (beginning-of-line 0)
4363 (if (looking-at "[ \t]*$")
4364 nil
4365 (if (<= (setq ind1 (org-get-indentation)) ind)
4366 (throw 'exit t)))))
4367 (condition-case nil
4368 (org-beginning-of-item)
4369 (error (goto-char beg)
4370 (error "Cannot move this item further up")))
4371 (setq ind1 (org-get-indentation))
4372 (if (and (org-at-item-p) (= ind ind1))
4373 (progn
4374 (setq txt (buffer-substring beg end))
4375 (save-excursion
4376 (delete-region beg end))
4377 (setq pos (point))
4378 (insert txt)
4379 (goto-char pos)
4380 (org-maybe-renumber-ordered-list))
4381 (goto-char pos)
4382 (error "Cannot move this item further up"))))
4383
4384 (defun org-maybe-renumber-ordered-list ()
4385 "Renumber the ordered list at point if setup allows it.
4386 This tests the user option `org-auto-renumber-ordered-lists' before
4387 doing the renumbering."
4388 (and org-auto-renumber-ordered-lists
4389 (org-at-item-p)
4390 (match-beginning 3)
4391 (org-renumber-ordered-list 1)))
4392
4393 (defun org-get-string-indentation (s)
4394 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4395 (let ((n -1) (i 0) (w tab-width) c)
4396 (catch 'exit
4397 (while (< (setq n (1+ n)) (length s))
4398 (setq c (aref s n))
4399 (cond ((= c ?\ ) (setq i (1+ i)))
4400 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4401 (t (throw 'exit t)))))
4402 i))
4403
4404 (defun org-renumber-ordered-list (arg)
4405 "Renumber an ordered plain list.
4406 Cursor needs to be in the first line of an item, the line that starts
4407 with something like \"1.\" or \"2)\"."
4408 (interactive "p")
4409 (unless (and (org-at-item-p)
4410 (match-beginning 3))
4411 (error "This is not an ordered list"))
4412 (let ((line (org-current-line))
4413 (col (current-column))
4414 (ind (org-get-string-indentation
4415 (buffer-substring (point-at-bol) (match-beginning 3))))
4416 ;; (term (substring (match-string 3) -1))
4417 ind1 (n (1- arg)))
4418 ;; find where this list begins
4419 (catch 'exit
4420 (while t
4421 (catch 'next
4422 (beginning-of-line 0)
4423 (if (looking-at "[ \t]*$") (throw 'next t))
4424 (skip-chars-forward " \t") (setq ind1 (current-column))
4425 (if (or (< ind1 ind)
4426 (and (= ind1 ind)
4427 (not (org-at-item-p))))
4428 (throw 'exit t)))))
4429 ;; Walk forward and replace these numbers
4430 (catch 'exit
4431 (while t
4432 (catch 'next
4433 (beginning-of-line 2)
4434 (if (eobp) (throw 'exit nil))
4435 (if (looking-at "[ \t]*$") (throw 'next nil))
4436 (skip-chars-forward " \t") (setq ind1 (current-column))
4437 (if (> ind1 ind) (throw 'next t))
4438 (if (< ind1 ind) (throw 'exit t))
4439 (if (not (org-at-item-p)) (throw 'exit nil))
4440 (if (not (match-beginning 3))
4441 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4442 (delete-region (match-beginning 3) (1- (match-end 3)))
4443 (goto-char (match-beginning 3))
4444 (insert (format "%d" (setq n (1+ n)))))))
4445 (goto-line line)
4446 (move-to-column col)))
4447
4448 (defvar org-last-indent-begin-marker (make-marker))
4449 (defvar org-last-indent-end-marker (make-marker))
4450
4451 (defun org-outdent-item (arg)
4452 "Outdent a local list item."
4453 (interactive "p")
4454 (org-indent-item (- arg)))
4455
4456 (defun org-indent-item (arg)
4457 "Indent a local list item."
4458 (interactive "p")
4459 (unless (org-at-item-p)
4460 (error "Not on an item"))
4461 (save-excursion
4462 (let (beg end ind ind1)
4463 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4464 (setq beg org-last-indent-begin-marker
4465 end org-last-indent-end-marker)
4466 (org-beginning-of-item)
4467 (setq beg (move-marker org-last-indent-begin-marker (point)))
4468 (org-end-of-item)
4469 (setq end (move-marker org-last-indent-end-marker (point))))
4470 (goto-char beg)
4471 (skip-chars-forward " \t") (setq ind (current-column))
4472 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4473 (while (< (point) end)
4474 (beginning-of-line 1)
4475 (skip-chars-forward " \t") (setq ind1 (current-column))
4476 (delete-region (point-at-bol) (point))
4477 (indent-to-column (+ ind1 arg))
4478 (beginning-of-line 2)))))
4479
4480 ;;; Archiving
4481
4482 (defun org-archive-subtree (&optional find-done)
4483 "Move the current subtree to the archive.
4484 The archive can be a certain top-level heading in the current file, or in
4485 a different file. The tree will be moved to that location, the subtree
4486 heading be marked DONE, and the current time will be added.
4487
4488 When called with prefix argument FIND-DONE, find whole trees without any
4489 open TODO items and archive them (after getting confirmation from the user).
4490 If the cursor is not at a headline when this comand is called, try all level
4491 1 trees. If the cursor is on a headline, only try the direct children of
4492 this heading. "
4493 (interactive "P")
4494 (if find-done
4495 (org-archive-all-done)
4496 ;; Save all relevant TODO keyword-relatex variables
4497
4498 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4499 (tr-org-todo-keywords org-todo-keywords)
4500 (tr-org-todo-interpretation org-todo-interpretation)
4501 (tr-org-done-string org-done-string)
4502 (tr-org-todo-regexp org-todo-regexp)
4503 (tr-org-todo-line-regexp org-todo-line-regexp)
4504 (this-buffer (current-buffer))
4505 file heading buffer level newfile-p)
4506 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4507 (progn
4508 (setq file (format (match-string 1 org-archive-location)
4509 (file-name-nondirectory buffer-file-name))
4510 heading (match-string 2 org-archive-location)))
4511 (error "Invalid `org-archive-location'"))
4512 (if (> (length file) 0)
4513 (setq newfile-p (not (file-exists-p file))
4514 buffer (find-file-noselect file))
4515 (setq buffer (current-buffer)))
4516 (unless buffer
4517 (error "Cannot access file \"%s\"" file))
4518 (if (and (> (length heading) 0)
4519 (string-match "^\\*+" heading))
4520 (setq level (match-end 0))
4521 (setq heading nil level 0))
4522 (save-excursion
4523 ;; We first only copy, in case something goes wrong
4524 ;; we need to protect this-command, to avoid kill-region sets it,
4525 ;; which would lead to duplication of subtrees
4526 (let (this-command) (org-copy-subtree))
4527 (set-buffer buffer)
4528 ;; Enforce org-mode for the archive buffer
4529 (if (not (org-mode-p))
4530 ;; Force the mode for future visits.
4531 (let ((org-insert-mode-line-in-empty-file t))
4532 (call-interactively 'org-mode)))
4533 (when newfile-p
4534 (goto-char (point-max))
4535 (insert (format "\nArchived entries from file %s\n\n"
4536 (buffer-file-name this-buffer))))
4537 ;; Force the TODO keywords of the original buffer
4538 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4539 (org-todo-keywords tr-org-todo-keywords)
4540 (org-todo-interpretation tr-org-todo-interpretation)
4541 (org-done-string tr-org-done-string)
4542 (org-todo-regexp tr-org-todo-regexp)
4543 (org-todo-line-regexp tr-org-todo-line-regexp))
4544 (goto-char (point-min))
4545 (if heading
4546 (progn
4547 (if (re-search-forward
4548 (concat "\\(^\\|\r\\)"
4549 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4550 nil t)
4551 (goto-char (match-end 0))
4552 ;; Heading not found, just insert it at the end
4553 (goto-char (point-max))
4554 (or (bolp) (insert "\n"))
4555 (insert "\n" heading "\n")
4556 (end-of-line 0))
4557 ;; Make the subtree visible
4558 (show-subtree)
4559 (org-end-of-subtree t)
4560 (skip-chars-backward " \t\r\n]")
4561 (and (looking-at "[ \t\r\n]*")
4562 (replace-match "\n\n")))
4563 ;; No specific heading, just go to end of file.
4564 (goto-char (point-max)) (insert "\n"))
4565 ;; Paste
4566 (org-paste-subtree (1+ level))
4567 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4568 (if org-archive-mark-done
4569 (org-todo (length org-todo-keywords)))
4570 ;; Move cursor to right after the TODO keyword
4571 (when org-archive-stamp-time
4572 (beginning-of-line 1)
4573 (looking-at org-todo-line-regexp)
4574 (goto-char (or (match-end 2) (match-beginning 3)))
4575 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4576 (org-current-time))
4577 ")"))
4578 ;; Save the buffer, if it is not the same buffer.
4579 (if (not (eq this-buffer buffer)) (save-buffer))))
4580 ;; Here we are back in the original buffer. Everything seems to have
4581 ;; worked. So now cut the tree and finish up.
4582 (let (this-command) (org-cut-subtree))
4583 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4584 (message "Subtree archived %s"
4585 (if (eq this-buffer buffer)
4586 (concat "under heading: " heading)
4587 (concat "in file: " (abbreviate-file-name file)))))))
4588
4589 (defun org-archive-all-done (&optional tag)
4590 "Archive sublevels of the current tree without open TODO items.
4591 If the cursor is not on a headline, try all level 1 trees. If
4592 it is on a headline, try all direct children.
4593 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
4594 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4595 (rea (concat ".*:" org-archive-tag ":"))
4596 (begm (make-marker))
4597 (endm (make-marker))
4598 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
4599 "Move subtree to archive (no open TODO items)? "))
4600 beg end (cntarch 0))
4601 (if (org-on-heading-p)
4602 (progn
4603 (setq re1 (concat "^" (regexp-quote
4604 (make-string
4605 (1+ (- (match-end 0) (match-beginning 0)))
4606 ?*))
4607 " "))
4608 (move-marker begm (point))
4609 (move-marker endm (org-end-of-subtree)))
4610 (setq re1 "^* ")
4611 (move-marker begm (point-min))
4612 (move-marker endm (point-max)))
4613 (save-excursion
4614 (goto-char begm)
4615 (while (re-search-forward re1 endm t)
4616 (setq beg (match-beginning 0)
4617 end (save-excursion (org-end-of-subtree t) (point)))
4618 (goto-char beg)
4619 (if (re-search-forward re end t)
4620 (goto-char end)
4621 (goto-char beg)
4622 (if (and (or (not tag) (not (looking-at rea)))
4623 (y-or-n-p question))
4624 (progn
4625 (if tag
4626 (org-toggle-tag org-archive-tag 'on)
4627 (org-archive-subtree))
4628 (setq cntarch (1+ cntarch)))
4629 (goto-char end)))))
4630 (message "%d trees archived" cntarch)))
4631
4632 (defun org-cycle-hide-archived-subtrees (state)
4633 "Re-hide all archived subtrees after a visibility state change."
4634 (when (and (not org-cycle-open-archived-trees)
4635 (not (memq state '(overview folded))))
4636 (save-excursion
4637 (let* ((globalp (memq state '(contents all)))
4638 (beg (if globalp (point-min) (point)))
4639 (end (if globalp (point-max) (org-end-of-subtree))))
4640 (org-hide-archived-subtrees beg end)))))
4641
4642 (defun org-hide-archived-subtrees (beg end)
4643 "Re-hide all archived subtrees after a visibility state change."
4644 (save-excursion
4645 (let* ((re (concat ":" org-archive-tag ":")))
4646 (goto-char beg)
4647 (while (re-search-forward re end t)
4648 (and (org-on-heading-p) (hide-subtree))
4649 (org-end-of-subtree)))))
4650
4651 (defun org-toggle-tag (tag &optional onoff)
4652 "Toggle the tag TAG for the current line.
4653 If ONOFF is `on' or `off', don't toggle but set to this state."
4654 (unless (org-on-heading-p) (error "Not on headling"))
4655 (let (res current)
4656 (save-excursion
4657 (beginning-of-line)
4658 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
4659 (point-at-eol) t)
4660 (progn
4661 (setq current (match-string 1))
4662 (replace-match ""))
4663 (setq current ""))
4664 (setq current (nreverse (org-split-string current ":")))
4665 (cond
4666 ((eq onoff 'on)
4667 (setq res t)
4668 (or (member tag current) (push tag current)))
4669 ((eq onoff 'off)
4670 (or (not (member tag current)) (setq current (delete tag current))))
4671 (t (if (member tag current)
4672 (setq current (delete tag current))
4673 (setq res t)
4674 (push tag current))))
4675 (end-of-line 1)
4676 (when current
4677 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
4678 (org-set-tags nil t))
4679 res))
4680
4681 (defun org-toggle-archive-tag (&optional arg)
4682 "Toggle the archive tag for the current headline.
4683 With prefix ARG, check all children of current headline and offer tagging
4684 the children that do not contain any open TODO items."
4685 (interactive "P")
4686 (if arg
4687 (org-archive-all-done 'tag)
4688 (let (set)
4689 (save-excursion
4690 (org-back-to-heading t)
4691 (setq set (org-toggle-tag org-archive-tag))
4692 (when set (hide-subtree)))
4693 (and set (beginning-of-line 1))
4694 (message "Subtree %s" (if set "archived" "unarchived")))))
4695
4696 (defun org-prepare-agenda-buffers (files)
4697 "Create buffers for all agenda files, protect archived trees and comments."
4698 (interactive)
4699 (let ((pa '(:org-archived t))
4700 (pc '(:org-comment t))
4701 (pall '(:org-archived t :org-comment t))
4702 (rea (concat ":" org-archive-tag ":"))
4703 file re)
4704 (save-excursion
4705 (while (setq file (pop files))
4706 (org-check-agenda-file file)
4707 (set-buffer (org-get-agenda-file-buffer file))
4708 (widen)
4709 (save-excursion
4710 (remove-text-properties (point-min) (point-max) pall)
4711 (when org-agenda-skip-archived-trees
4712 (goto-char (point-min))
4713 (while (re-search-forward rea nil t)
4714 (if (org-on-heading-p)
4715 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
4716 (goto-char (point-min))
4717 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
4718 (while (re-search-forward re nil t)
4719 (add-text-properties
4720 (match-beginning 0) (org-end-of-subtree t) pc)))))))
4721
4722 (defun org-agenda-skip ()
4723 "Throw to `:skip' in places that should be skipped."
4724 (let ((p (point-at-bol)))
4725 (and org-agenda-skip-archived-trees
4726 (get-text-property p :org-archived)
4727 (org-end-of-subtree)
4728 (throw :skip t))
4729 (and (get-text-property p :org-comment)
4730 (org-end-of-subtree)
4731 (throw :skip t))
4732 (if (equal (char-after p) ?#) (throw :skip t))))
4733
4734 (defun org-agenda-toggle-archive-tag ()
4735 "Toggle the archive tag for the current entry."
4736 (interactive)
4737 (org-agenda-check-no-diary)
4738 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
4739 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
4740 (org-agenda-error)))
4741 (buffer (marker-buffer hdmarker))
4742 (pos (marker-position hdmarker))
4743 (buffer-read-only nil)
4744 newhead)
4745 (with-current-buffer buffer
4746 (widen)
4747 (goto-char pos)
4748 (org-show-hidden-entry)
4749 (save-excursion
4750 (and (outline-next-heading)
4751 (org-flag-heading nil))) ; show the next heading
4752 (call-interactively 'org-toggle-archive-tag)
4753 (end-of-line 1)
4754 (setq newhead (org-get-heading)))
4755 (org-agenda-change-all-lines newhead hdmarker)
4756 (beginning-of-line 1)))
4757
4758 ;;; Dynamic blocks
4759
4760 (defun org-find-dblock (name)
4761 "Find the first dynamic block with name NAME in the buffer.
4762 If not found, stay at current position and return nil."
4763 (let (pos)
4764 (save-excursion
4765 (goto-char (point-min))
4766 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
4767 nil t)
4768 (match-beginning 0))))
4769 (if pos (goto-char pos))
4770 pos))
4771
4772 (defconst org-dblock-start-re
4773 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)[ \t]+\\(.*\\)"
4774 "Matches the startline of a dynamic block, with parameters.")
4775
4776 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
4777 "Matches the end of a dyhamic block.")
4778
4779 (defun org-create-dblock (plist)
4780 "Create a dynamic block section, with parameters taken from PLIST.
4781 PLIST must containe a :name entry which is used as name of the block."
4782 (unless (bolp) (newline))
4783 (let ((name (plist-get plist :name)))
4784 (insert "#+BEGIN: " name)
4785 (while plist
4786 (if (eq (car plist) :name)
4787 (setq plist (cddr plist))
4788 (insert " " (prin1-to-string (pop plist)))))
4789 (insert "\n\n#+END:\n")
4790 (beginning-of-line -2)))
4791
4792 (defun org-prepare-dblock ()
4793 "Prepare dynamic block for refresh.
4794 This empties the block, puts the cursor at the insert position and returns
4795 the property list including an extra property :name with the block name."
4796 (unless (looking-at org-dblock-start-re)
4797 (error "Not at a dynamic block"))
4798 (let* ((begdel (1+ (match-end 0)))
4799 (name (match-string 1))
4800 (params (append (list :name name)
4801 (read (concat "(" (match-string 2) ")")))))
4802 (unless (re-search-forward org-dblock-end-re nil t)
4803 (error "Dynamic block not terminated"))
4804 (delete-region begdel (match-beginning 0))
4805 (goto-char begdel)
4806 (open-line 1)
4807 params))
4808
4809 (defun org-map-dblocks (&optional command)
4810 "Apply COMMAND to all dynamic blocks in the current buffer.
4811 If COMMAND is not given, use `org-update-dblock'."
4812 (let ((cmd (or command 'org-update-dblock))
4813 pos)
4814 (save-excursion
4815 (goto-char (point-min))
4816 (while (re-search-forward org-dblock-start-re nil t)
4817 (goto-char (setq pos (match-beginning 0)))
4818 (condition-case nil
4819 (funcall cmd)
4820 (error (message "Error during update of dynamic block")))
4821 (goto-char pos)
4822 (unless (re-search-forward org-dblock-end-re nil t)
4823 (error "Dynamic block not terminated"))))))
4824
4825 (defun org-dblock-update (&optional arg)
4826 "User command for updating dynamic blocks.
4827 Update the dynamic block at point. With prefix ARG, update all dynamic
4828 blocks in the buffer."
4829 (interactive "P")
4830 (if arg
4831 (org-update-all-dblocks)
4832 (or (looking-at org-dblock-start-re)
4833 (org-beginning-of-dblock))
4834 (org-update-dblock)))
4835
4836 (defun org-update-dblock ()
4837 "Update the dynamic block at point
4838 This means to empty the block, parse for parameters and then call
4839 the correct writing function."
4840 (let* ((pos (point))
4841 (params (org-prepare-dblock))
4842 (name (plist-get params :name))
4843 (cmd (intern (concat "org-dblock-write:" name))))
4844 (funcall cmd params)
4845 (goto-char pos)))
4846
4847 (defun org-beginning-of-dblock ()
4848 "Find the beginning of the dynamic block at point.
4849 Error if there is no scuh block at point."
4850 (let ((pos (point))
4851 beg)
4852 (end-of-line 1)
4853 (if (and (re-search-backward org-dblock-start-re nil t)
4854 (setq beg (match-beginning 0))
4855 (re-search-forward org-dblock-end-re nil t)
4856 (> (match-end 0) pos))
4857 (goto-char beg)
4858 (goto-char pos)
4859 (error "Not in a dynamic block"))))
4860
4861 (defun org-update-all-dblocks ()
4862 "Update all dynamic blocks in the buffer.
4863 This function can be used in a hook."
4864 (when (org-mode-p)
4865 (org-map-dblocks 'org-update-dblock)))
4866
4867
4868 ;;; Completion
4869
4870 (defun org-complete (&optional arg)
4871 "Perform completion on word at point.
4872 At the beginning of a headline, this completes TODO keywords as given in
4873 `org-todo-keywords'.
4874 If the current word is preceded by a backslash, completes the TeX symbols
4875 that are supported for HTML support.
4876 If the current word is preceded by \"#+\", completes special words for
4877 setting file options.
4878 At all other locations, this simply calls `ispell-complete-word'."
4879 (interactive "P")
4880 (catch 'exit
4881 (let* ((end (point))
4882 (beg1 (save-excursion
4883 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4884 (skip-chars-backward "a-zA-Z_@0-9")
4885 (point)))
4886 (beg (save-excursion
4887 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4888 (skip-chars-backward "a-zA-Z0-9_:$")
4889 (point)))
4890 (confirm (lambda (x) (stringp (car x))))
4891 (camel (equal (char-before beg) ?*))
4892 (tag (equal (char-before beg1) ?:))
4893 (texp (equal (char-before beg) ?\\))
4894 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
4895 beg)
4896 "#+"))
4897 (completion-ignore-case opt)
4898 (type nil)
4899 (tbl nil)
4900 (table (cond
4901 (opt
4902 (setq type :opt)
4903 (mapcar (lambda (x)
4904 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
4905 (cons (match-string 2 x) (match-string 1 x)))
4906 (org-split-string (org-get-current-options) "\n")))
4907 (texp
4908 (setq type :tex)
4909 org-html-entities)
4910 ((string-match "\\`\\*+[ \t]*\\'"
4911 (buffer-substring (point-at-bol) beg))
4912 (setq type :todo)
4913 (mapcar 'list org-todo-keywords))
4914 (camel
4915 (setq type :camel)
4916 (save-excursion
4917 (goto-char (point-min))
4918 (while (re-search-forward org-todo-line-regexp nil t)
4919 (push (list
4920 (if org-file-link-context-use-camel-case
4921 (org-make-org-heading-camel (match-string 3) t)
4922 (org-make-org-heading-search-string
4923 (match-string 3) t)))
4924 tbl)))
4925 tbl)
4926 (tag (setq type :tag beg beg1)
4927 (or org-tag-alist (org-get-buffer-tags)))
4928 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
4929 (pattern (buffer-substring-no-properties beg end))
4930 (completion (try-completion pattern table confirm)))
4931 (cond ((eq completion t)
4932 (if (equal type :opt)
4933 (insert (substring (cdr (assoc (upcase pattern) table))
4934 (length pattern)))))
4935 ((null completion)
4936 (message "Can't find completion for \"%s\"" pattern)
4937 (ding))
4938 ((not (string= pattern completion))
4939 (delete-region beg end)
4940 (if (string-match " +$" completion)
4941 (setq completion (replace-match "" t t completion)))
4942 (insert completion)
4943 (if (get-buffer-window "*Completions*")
4944 (delete-window (get-buffer-window "*Completions*")))
4945 (if (assoc completion table)
4946 (if (eq type :todo) (insert " ")
4947 (if (eq type :tag) (insert ":"))))
4948 (if (and (equal type :opt) (assoc completion table))
4949 (message "%s" (substitute-command-keys
4950 "Press \\[org-complete] again to insert example settings"))))
4951 (t
4952 (message "Making completion list...")
4953 (let ((list (sort (all-completions pattern table confirm)
4954 'string<)))
4955 (with-output-to-temp-buffer "*Completions*"
4956 (condition-case nil
4957 ;; Protection needed for XEmacs and emacs 21
4958 (display-completion-list list pattern)
4959 (error (display-completion-list list)))))
4960 (message "Making completion list...%s" "done"))))))
4961
4962 ;;; Comments, TODO and DEADLINE
4963
4964 (defun org-toggle-comment ()
4965 "Change the COMMENT state of an entry."
4966 (interactive)
4967 (save-excursion
4968 (org-back-to-heading)
4969 (if (looking-at (concat outline-regexp
4970 "\\( +\\<" org-comment-string "\\>\\)"))
4971 (replace-match "" t t nil 1)
4972 (if (looking-at outline-regexp)
4973 (progn
4974 (goto-char (match-end 0))
4975 (insert " " org-comment-string))))))
4976
4977 (defvar org-last-todo-state-is-todo nil
4978 "This is non-nil when the last TODO state change led to a TODO state.
4979 If the last change removed the TODO tag or switched to DONE, then
4980 this is nil.")
4981
4982 (defun org-todo (&optional arg)
4983 "Change the TODO state of an item.
4984 The state of an item is given by a keyword at the start of the heading,
4985 like
4986 *** TODO Write paper
4987 *** DONE Call mom
4988
4989 The different keywords are specified in the variable `org-todo-keywords'.
4990 By default the available states are \"TODO\" and \"DONE\".
4991 So for this example: when the item starts with TODO, it is changed to DONE.
4992 When it starts with DONE, the DONE is removed. And when neither TODO nor
4993 DONE are present, add TODO at the beginning of the heading.
4994
4995 With prefix arg, use completion to determine the new state. With numeric
4996 prefix arg, switch to that state."
4997 (interactive "P")
4998 (save-excursion
4999 (org-back-to-heading)
5000 (if (looking-at outline-regexp) (goto-char (match-end 0)))
5001 (or (looking-at (concat " +" org-todo-regexp " *"))
5002 (looking-at " *"))
5003 (let* ((this (match-string 1))
5004 (completion-ignore-case t)
5005 (member (member this org-todo-keywords))
5006 (tail (cdr member))
5007 (state (cond
5008 ((equal arg '(4))
5009 ;; Read a state with completion
5010 (completing-read "State: " (mapcar (lambda(x) (list x))
5011 org-todo-keywords)
5012 nil t))
5013 ((eq arg 'right)
5014 (if this
5015 (if tail (car tail) nil)
5016 (car org-todo-keywords)))
5017 ((eq arg 'left)
5018 (if (equal member org-todo-keywords)
5019 nil
5020 (if this
5021 (nth (- (length org-todo-keywords) (length tail) 2)
5022 org-todo-keywords)
5023 org-done-string)))
5024 (arg
5025 ;; user requests a specific state
5026 (nth (1- (prefix-numeric-value arg))
5027 org-todo-keywords))
5028 ((null member) (car org-todo-keywords))
5029 ((null tail) nil) ;; -> first entry
5030 ((eq org-todo-interpretation 'sequence)
5031 (car tail))
5032 ((memq org-todo-interpretation '(type priority))
5033 (if (eq this-command last-command)
5034 (car tail)
5035 (if (> (length tail) 0) org-done-string nil)))
5036 (t nil)))
5037 (next (if state (concat " " state " ") " ")))
5038 (replace-match next t t)
5039 (setq org-last-todo-state-is-todo
5040 (not (equal state org-done-string)))
5041 (when org-log-done
5042 (if (equal state org-done-string)
5043 (org-add-planning-info 'closed (current-time) 'scheduled)
5044 (if (not this)
5045 (org-add-planning-info nil nil 'closed))))
5046 ;; Fixup tag positioning
5047 (and org-auto-align-tags (org-set-tags nil t))
5048 (run-hooks 'org-after-todo-state-change-hook)))
5049 ;; Fixup cursor location if close to the keyword
5050 (if (and (outline-on-heading-p)
5051 (not (bolp))
5052 (save-excursion (beginning-of-line 1)
5053 (looking-at org-todo-line-regexp))
5054 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5055 (progn
5056 (goto-char (or (match-end 2) (match-end 1)))
5057 (just-one-space))))
5058
5059 (defun org-log-done (&optional undone)
5060 "Add a time stamp logging that a TODO entry has been closed.
5061 When UNDONE is non-nil, remove such a time stamp again."
5062 (interactive)
5063 (let (beg end col)
5064 (save-excursion
5065 (org-back-to-heading t)
5066 (setq beg (point))
5067 (looking-at (concat outline-regexp " *"))
5068 (goto-char (match-end 0))
5069 (setq col (current-column))
5070 (outline-next-heading)
5071 (setq end (point))
5072 (goto-char beg)
5073 (when (re-search-forward (concat
5074 "[\r\n]\\([ \t]*"
5075 (regexp-quote org-closed-string)
5076 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
5077 (delete-region (match-beginning 1) (match-end 1)))
5078 (unless undone
5079 (org-back-to-heading t)
5080 (skip-chars-forward "^\n\r")
5081 (goto-char (min (1+ (point)) (point-max)))
5082 (when (not (member (char-before) '(?\r ?\n)))
5083 (insert "\n"))
5084 (indent-to col)
5085 (insert org-closed-string " "
5086 (format-time-string
5087 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5088 (org-current-time))
5089 "\n")))))
5090
5091 (defun org-show-todo-tree (arg)
5092 "Make a compact tree which shows all headlines marked with TODO.
5093 The tree will show the lines where the regexp matches, and all higher
5094 headlines above the match.
5095 With \\[universal-argument] prefix, also show the DONE entries.
5096 With a numeric prefix N, construct a sparse tree for the Nth element
5097 of `org-todo-keywords'."
5098 (interactive "P")
5099 (let ((case-fold-search nil)
5100 (kwd-re
5101 (cond ((null arg) org-not-done-regexp)
5102 ((equal arg '(4)) org-todo-regexp)
5103 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5104 (regexp-quote (nth (1- (prefix-numeric-value arg))
5105 org-todo-keywords)))
5106 (t (error "Invalid prefix argument: %s" arg)))))
5107 (message "%d TODO entries found"
5108 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5109
5110 (defun org-deadline ()
5111 "Insert the DEADLINE: string to make a deadline.
5112 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5113 to modify it to the correct date."
5114 (interactive)
5115 (org-add-planning-info 'deadline nil 'closed))
5116
5117 (defun org-schedule ()
5118 "Insert the SCHEDULED: string to schedule a TODO item.
5119 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5120 to modify it to the correct date."
5121 (interactive)
5122 (org-add-planning-info 'scheduled nil 'closed))
5123
5124 (defun org-add-planning-info (what &optional time &rest remove)
5125 "Insert new timestamp with keyword in the line directly after the headline.
5126 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5127 If non is given, the user is prompted for a date.
5128 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5129 be removed."
5130 (interactive)
5131 (when what (setq time (or time (org-read-date nil 'to-time))))
5132 (when (and org-insert-labeled-timestamps-at-point
5133 (member what '(scheduled deadline)))
5134 (insert
5135 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
5136 " "
5137 (format-time-string (car org-time-stamp-formats) time))
5138 (setq what nil))
5139 (save-excursion
5140 (let (col list elt (buffer-invisibility-spec nil) ts)
5141 (org-back-to-heading t)
5142 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5143 (goto-char (match-end 1))
5144 (setq col (current-column))
5145 (goto-char (1+ (match-end 0)))
5146 (if (and (not (looking-at outline-regexp))
5147 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5148 "[^\r\n]*"))
5149 (not (equal (match-string 1) org-clock-string)))
5150 (narrow-to-region (match-beginning 0) (match-end 0))
5151 (insert "\n")
5152 (backward-char 1)
5153 (narrow-to-region (point) (point))
5154 (indent-to-column col))
5155 ;; Check if we have to remove something.
5156 (setq list (cons what remove))
5157 (while list
5158 (setq elt (pop list))
5159 (goto-char (point-min))
5160 (when (or (and (eq elt 'scheduled)
5161 (re-search-forward org-scheduled-time-regexp nil t))
5162 (and (eq elt 'deadline)
5163 (re-search-forward org-deadline-time-regexp nil t))
5164 (and (eq elt 'closed)
5165 (re-search-forward org-closed-time-regexp nil t)))
5166 (replace-match "")
5167 (if (looking-at " +") (replace-match ""))))
5168 (goto-char (point-max))
5169 (when what
5170 (insert
5171 (if (not (equal (char-before) ?\ )) " " "")
5172 (cond ((eq what 'scheduled) org-scheduled-string)
5173 ((eq what 'deadline) org-deadline-string)
5174 ((eq what 'closed) org-closed-string))
5175 " ")
5176 (insert
5177 (setq ts
5178 (format-time-string
5179 (if (eq what 'closed)
5180 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5181 (car org-time-stamp-formats))
5182 time))))
5183 (goto-char (point-min))
5184 (widen)
5185 (if (looking-at "[ \t]+\r?\n")
5186 (replace-match ""))
5187 ts)))
5188
5189 (defun org-occur (regexp &optional callback)
5190 "Make a compact tree which shows all matches of REGEXP.
5191 The tree will show the lines where the regexp matches, and all higher
5192 headlines above the match. It will also show the heading after the match,
5193 to make sure editing the matching entry is easy.
5194 If CALLBACK is non-nil, it is a function which is called to confirm
5195 that the match should indeed be shown."
5196 (interactive "sRegexp: ")
5197 (org-remove-occur-highlights nil nil t)
5198 (setq regexp (org-check-occur-regexp regexp))
5199 (let ((cnt 0))
5200 (save-excursion
5201 (goto-char (point-min))
5202 (org-overview)
5203 (while (re-search-forward regexp nil t)
5204 (when (or (not callback)
5205 (save-match-data (funcall callback)))
5206 (setq cnt (1+ cnt))
5207 (org-highlight-new-match (match-beginning 0) (match-end 0))
5208 (org-show-hierarchy-above))))
5209 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5210 nil 'local)
5211 (unless org-sparse-tree-open-archived-trees
5212 (org-hide-archived-subtrees (point-min) (point-max)))
5213 (run-hooks 'org-occur-hook)
5214 (if (interactive-p)
5215 (message "%d match(es) for regexp %s" cnt regexp))
5216 cnt))
5217
5218 (defun org-show-hierarchy-above ()
5219 "Make sure point and the headings hierarchy above is visible."
5220 (catch 'exit
5221 (if (org-on-heading-p t)
5222 (org-flag-heading nil) ; only show the heading
5223 (and (or (org-invisible-p) (org-invisible-p2))
5224 (org-show-hidden-entry))) ; show entire entry
5225 (save-excursion
5226 (and org-show-following-heading
5227 (outline-next-heading)
5228 (org-flag-heading nil))) ; show the next heading
5229 (when org-show-hierarchy-above
5230 (save-excursion ; show all higher headings
5231 (while (and (condition-case nil
5232 (progn (org-up-heading-all 1) t)
5233 (error nil))
5234 (not (bobp)))
5235 (org-flag-heading nil))))))
5236
5237 ;; Overlay compatibility functions
5238 (defun org-make-overlay (beg end &optional buffer)
5239 (if (featurep 'xemacs)
5240 (make-extent beg end buffer)
5241 (make-overlay beg end buffer)))
5242 (defun org-delete-overlay (ovl)
5243 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5244 (defun org-detatch-overlay (ovl)
5245 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5246 (defun org-move-overlay (ovl beg end &optional buffer)
5247 (if (featurep 'xemacs)
5248 (set-extent-endpoints ovl beg end buffer)
5249 (move-overlay ovl beg end buffer)))
5250 (defun org-overlay-put (ovl prop value)
5251 (if (featurep 'xemacs)
5252 (set-extent-property ovl prop value)
5253 (overlay-put ovl prop value)))
5254 (defun org-overlays-at (pos)
5255 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5256 (defun org-overlay-start (o)
5257 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5258 (defun org-overlay-end (o)
5259 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5260
5261 (defvar org-occur-highlights nil)
5262 (make-variable-buffer-local 'org-occur-highlights)
5263 (defun org-highlight-new-match (beg end)
5264 "Highlight from BEG to END and mark the highlight is an occur headline."
5265 (let ((ov (org-make-overlay beg end)))
5266 (org-overlay-put ov 'face 'secondary-selection)
5267 (push ov org-occur-highlights)))
5268
5269 (defvar org-inhibit-highlight-removal nil)
5270 (defun org-remove-occur-highlights (&optional beg end noremove)
5271 "Remove the occur highlights from the buffer.
5272 BEG and END are ignored. If NOREMOVE is nil, remove this function
5273 from the `before-change-functions' in the current buffer."
5274 (interactive)
5275 (unless org-inhibit-highlight-removal
5276 (mapc 'org-delete-overlay org-occur-highlights)
5277 (setq org-occur-highlights nil)
5278 (unless noremove
5279 (remove-hook 'before-change-functions
5280 'org-remove-occur-highlights 'local))))
5281
5282 ;;; Priorities
5283
5284 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5285 "Regular expression matching the priority indicator.")
5286
5287 (defvar org-remove-priority-next-time nil)
5288
5289 (defun org-priority-up ()
5290 "Increase the priority of the current item."
5291 (interactive)
5292 (org-priority 'up))
5293
5294 (defun org-priority-down ()
5295 "Decrease the priority of the current item."
5296 (interactive)
5297 (org-priority 'down))
5298
5299 (defun org-priority (&optional action)
5300 "Change the priority of an item by ARG.
5301 ACTION can be set, up, or down."
5302 (interactive)
5303 (setq action (or action 'set))
5304 (let (current new news have remove)
5305 (save-excursion
5306 (org-back-to-heading)
5307 (if (looking-at org-priority-regexp)
5308 (setq current (string-to-char (match-string 2))
5309 have t)
5310 (setq current org-default-priority))
5311 (cond
5312 ((eq action 'set)
5313 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5314 (setq new (read-char-exclusive))
5315 (cond ((equal new ?\ ) (setq remove t))
5316 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5317 (error "Priority must be between `%c' and `%c'"
5318 ?A org-lowest-priority))))
5319 ((eq action 'up)
5320 (setq new (1- current)))
5321 ((eq action 'down)
5322 (setq new (1+ current)))
5323 (t (error "Invalid action")))
5324 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5325 (setq news (format "%c" new))
5326 (if have
5327 (if remove
5328 (replace-match "" t t nil 1)
5329 (replace-match news t t nil 2))
5330 (if remove
5331 (error "No priority cookie found in line")
5332 (looking-at org-todo-line-regexp)
5333 (if (match-end 2)
5334 (progn
5335 (goto-char (match-end 2))
5336 (insert " [#" news "]"))
5337 (goto-char (match-beginning 3))
5338 (insert "[#" news "] ")))))
5339 (if remove
5340 (message "Priority removed")
5341 (message "Priority of current item set to %s" news))))
5342
5343
5344 (defun org-get-priority (s)
5345 "Find priority cookie and return priority."
5346 (save-match-data
5347 (if (not (string-match org-priority-regexp s))
5348 (* 1000 (- org-lowest-priority org-default-priority))
5349 (* 1000 (- org-lowest-priority
5350 (string-to-char (match-string 2 s)))))))
5351
5352 ;;; Timestamps
5353
5354 (defvar org-last-changed-timestamp nil)
5355
5356 (defun org-time-stamp (arg)
5357 "Prompt for a date/time and insert a time stamp.
5358 If the user specifies a time like HH:MM, or if this command is called
5359 with a prefix argument, the time stamp will contain date and time.
5360 Otherwise, only the date will be included. All parts of a date not
5361 specified by the user will be filled in from the current date/time.
5362 So if you press just return without typing anything, the time stamp
5363 will represent the current date/time. If there is already a timestamp
5364 at the cursor, it will be modified."
5365 (interactive "P")
5366 (let ((fmt (if arg (cdr org-time-stamp-formats)
5367 (car org-time-stamp-formats)))
5368 (org-time-was-given nil)
5369 time)
5370 (cond
5371 ((and (org-at-timestamp-p)
5372 (eq last-command 'org-time-stamp)
5373 (eq this-command 'org-time-stamp))
5374 (insert "--")
5375 (setq time (let ((this-command this-command))
5376 (org-read-date arg 'totime)))
5377 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5378 (insert (format-time-string fmt time)))
5379 ((org-at-timestamp-p)
5380 (setq time (let ((this-command this-command))
5381 (org-read-date arg 'totime)))
5382 (and (org-at-timestamp-p) (replace-match
5383 (setq org-last-changed-timestamp
5384 (format-time-string fmt time))
5385 t t))
5386 (message "Timestamp updated"))
5387 (t
5388 (setq time (let ((this-command this-command))
5389 (org-read-date arg 'totime)))
5390 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5391 (insert (format-time-string fmt time))))))
5392
5393 (defun org-time-stamp-inactive (&optional arg)
5394 "Insert an inactive time stamp.
5395 An inactive time stamp is enclosed in square brackets instead of angle
5396 brackets. It is inactive in the sense that it does not trigger agenda entries,
5397 does not link to the calendar and cannot be changed with the S-cursor keys.
5398 So these are more for recording a certain time/date."
5399 (interactive "P")
5400 (let ((fmt (if arg (cdr org-time-stamp-formats)
5401 (car org-time-stamp-formats)))
5402 (org-time-was-given nil)
5403 time)
5404 (setq time (org-read-date arg 'totime))
5405 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5406 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
5407 (insert (format-time-string fmt time))))
5408
5409 (defvar org-date-ovl (org-make-overlay 1 1))
5410 (org-overlay-put org-date-ovl 'face 'org-warning)
5411 (org-detatch-overlay org-date-ovl)
5412
5413 (defun org-read-date (&optional with-time to-time)
5414 "Read a date and make things smooth for the user.
5415 The prompt will suggest to enter an ISO date, but you can also enter anything
5416 which will at least partially be understood by `parse-time-string'.
5417 Unrecognized parts of the date will default to the current day, month, year,
5418 hour and minute. For example,
5419 3-2-5 --> 2003-02-05
5420 feb 15 --> currentyear-02-15
5421 sep 12 9 --> 2009-09-12
5422 12:45 --> today 12:45
5423 22 sept 0:34 --> currentyear-09-22 0:34
5424 12 --> currentyear-currentmonth-12
5425 Fri --> nearest Friday (today or later)
5426 etc.
5427 The function understands only English month and weekday abbreviations,
5428 but this can be configured with the variables `parse-time-months' and
5429 `parse-time-weekdays'.
5430
5431 While prompting, a calendar is popped up - you can also select the
5432 date with the mouse (button 1). The calendar shows a period of three
5433 months. To scroll it to other months, use the keys `>' and `<'.
5434 If you don't like the calendar, turn it off with
5435 \(setq org-popup-calendar-for-date-prompt nil)
5436
5437 With optional argument TO-TIME, the date will immediately be converted
5438 to an internal time.
5439 With an optional argument WITH-TIME, the prompt will suggest to also
5440 insert a time. Note that when WITH-TIME is not set, you can still
5441 enter a time, and this function will inform the calling routine about
5442 this change. The calling routine may then choose to change the format
5443 used to insert the time stamp into the buffer to include the time."
5444 (require 'parse-time)
5445 (let* ((org-time-stamp-rounding-minutes
5446 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5447 (ct (org-current-time))
5448 (default-time
5449 ;; Default time is either today, or, when entering a range,
5450 ;; the range start.
5451 (if (save-excursion
5452 (re-search-backward
5453 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5454 (- (point) 20) t))
5455 (apply
5456 'encode-time
5457 (mapcar (lambda(x) (or x 0))
5458 (parse-time-string (match-string 1))))
5459 ct))
5460 (calendar-move-hook nil)
5461 (view-diary-entries-initially nil)
5462 (view-calendar-holidays-initially nil)
5463 (timestr (format-time-string
5464 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5465 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5466 ans ans1 ans2
5467 second minute hour day month year tl wday wday1)
5468
5469 (if org-popup-calendar-for-date-prompt
5470 (save-excursion
5471 (save-window-excursion
5472 (calendar)
5473 (calendar-forward-day (- (time-to-days default-time)
5474 (calendar-absolute-from-gregorian
5475 (calendar-current-date))))
5476 (org-eval-in-calendar nil)
5477 (let* ((old-map (current-local-map))
5478 (map (copy-keymap calendar-mode-map))
5479 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5480 (define-key map (kbd "RET") 'org-calendar-select)
5481 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5482 'org-calendar-select-mouse)
5483 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5484 'org-calendar-select-mouse)
5485 (define-key minibuffer-local-map [(meta shift left)]
5486 (lambda () (interactive)
5487 (org-eval-in-calendar '(calendar-backward-month 1))))
5488 (define-key minibuffer-local-map [(meta shift right)]
5489 (lambda () (interactive)
5490 (org-eval-in-calendar '(calendar-forward-month 1))))
5491 (define-key minibuffer-local-map [(shift up)]
5492 (lambda () (interactive)
5493 (org-eval-in-calendar '(calendar-backward-week 1))))
5494 (define-key minibuffer-local-map [(shift down)]
5495 (lambda () (interactive)
5496 (org-eval-in-calendar '(calendar-forward-week 1))))
5497 (define-key minibuffer-local-map [(shift left)]
5498 (lambda () (interactive)
5499 (org-eval-in-calendar '(calendar-backward-day 1))))
5500 (define-key minibuffer-local-map [(shift right)]
5501 (lambda () (interactive)
5502 (org-eval-in-calendar '(calendar-forward-day 1))))
5503 (define-key minibuffer-local-map ">"
5504 (lambda () (interactive)
5505 (org-eval-in-calendar '(scroll-calendar-left 1))))
5506 (define-key minibuffer-local-map "<"
5507 (lambda () (interactive)
5508 (org-eval-in-calendar '(scroll-calendar-right 1))))
5509 (unwind-protect
5510 (progn
5511 (use-local-map map)
5512 (setq ans (read-string prompt "" nil nil))
5513 (if (not (string-match "\\S-" ans)) (setq ans nil))
5514 (setq ans (or ans1 ans ans2)))
5515 (use-local-map old-map)))))
5516 ;; Naked prompt only
5517 (setq ans (read-string prompt "" nil timestr)))
5518 (org-detatch-overlay org-date-ovl)
5519
5520 (if (string-match
5521 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5522 (progn
5523 (setq year (if (match-end 2)
5524 (string-to-number (match-string 2 ans))
5525 (string-to-number (format-time-string "%Y")))
5526 month (string-to-number (match-string 3 ans))
5527 day (string-to-number (match-string 4 ans)))
5528 (if (< year 100) (setq year (+ 2000 year)))
5529 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
5530 t nil ans))))
5531 (setq tl (parse-time-string ans)
5532 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
5533 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
5534 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
5535 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
5536 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
5537 second (or (nth 0 tl) 0)
5538 wday (nth 6 tl))
5539 (when (and wday (not (nth 3 tl)))
5540 ;; Weekday was given, but no day, so pick that day in the week
5541 ;; on or after the derived date.
5542 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
5543 (unless (equal wday wday1)
5544 (setq day (+ day (% (- wday wday1 -7) 7)))))
5545 (if (and (boundp 'org-time-was-given)
5546 (nth 2 tl))
5547 (setq org-time-was-given t))
5548 (if (< year 100) (setq year (+ 2000 year)))
5549 (if to-time
5550 (encode-time second minute hour day month year)
5551 (if (or (nth 1 tl) (nth 2 tl))
5552 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
5553 (format "%04d-%02d-%02d" year month day)))))
5554
5555 (defun org-eval-in-calendar (form)
5556 "Eval FORM in the calendar window and return to current window.
5557 Also, store the cursor date in variable ans2."
5558 (let ((sw (selected-window)))
5559 (select-window (get-buffer-window "*Calendar*"))
5560 (eval form)
5561 (when (calendar-cursor-to-date)
5562 (let* ((date (calendar-cursor-to-date))
5563 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5564 (setq ans2 (format-time-string "%Y-%m-%d" time))))
5565 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
5566 (select-window sw)))
5567
5568 (defun org-calendar-select ()
5569 "Return to `org-read-date' with the date currently selected.
5570 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5571 (interactive)
5572 (when (calendar-cursor-to-date)
5573 (let* ((date (calendar-cursor-to-date))
5574 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5575 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5576 (if (active-minibuffer-window) (exit-minibuffer))))
5577
5578 (defun org-calendar-select-mouse (ev)
5579 "Return to `org-read-date' with the date currently selected.
5580 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5581 (interactive "e")
5582 (mouse-set-point ev)
5583 (when (calendar-cursor-to-date)
5584 (let* ((date (calendar-cursor-to-date))
5585 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5586 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5587 (if (active-minibuffer-window) (exit-minibuffer))))
5588
5589 (defun org-check-deadlines (ndays)
5590 "Check if there are any deadlines due or past due.
5591 A deadline is considered due if it happens within `org-deadline-warning-days'
5592 days from today's date. If the deadline appears in an entry marked DONE,
5593 it is not shown. The prefix arg NDAYS can be used to test that many
5594 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
5595 (interactive "P")
5596 (let* ((org-warn-days
5597 (cond
5598 ((equal ndays '(4)) 100000)
5599 (ndays (prefix-numeric-value ndays))
5600 (t org-deadline-warning-days)))
5601 (case-fold-search nil)
5602 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
5603 (callback
5604 (lambda ()
5605 (and (let ((d1 (time-to-days (current-time)))
5606 (d2 (time-to-days
5607 (org-time-string-to-time (match-string 1)))))
5608 (< (- d2 d1) org-warn-days))
5609 (not (org-entry-is-done-p))))))
5610 (message "%d deadlines past-due or due within %d days"
5611 (org-occur regexp callback)
5612 org-warn-days)))
5613
5614 (defun org-evaluate-time-range (&optional to-buffer)
5615 "Evaluate a time range by computing the difference between start and end.
5616 Normally the result is just printed in the echo area, but with prefix arg
5617 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
5618 If the time range is actually in a table, the result is inserted into the
5619 next column.
5620 For time difference computation, a year is assumed to be exactly 365
5621 days in order to avoid rounding problems."
5622 (interactive "P")
5623 (save-excursion
5624 (unless (org-at-date-range-p)
5625 (goto-char (point-at-bol))
5626 (re-search-forward org-tr-regexp (point-at-eol) t))
5627 (if (not (org-at-date-range-p))
5628 (error "Not at a time-stamp range, and none found in current line")))
5629 (let* ((ts1 (match-string 1))
5630 (ts2 (match-string 2))
5631 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
5632 (match-end (match-end 0))
5633 (time1 (org-time-string-to-time ts1))
5634 (time2 (org-time-string-to-time ts2))
5635 (t1 (time-to-seconds time1))
5636 (t2 (time-to-seconds time2))
5637 (diff (abs (- t2 t1)))
5638 (negative (< (- t2 t1) 0))
5639 ;; (ys (floor (* 365 24 60 60)))
5640 (ds (* 24 60 60))
5641 (hs (* 60 60))
5642 (fy "%dy %dd %02d:%02d")
5643 (fy1 "%dy %dd")
5644 (fd "%dd %02d:%02d")
5645 (fd1 "%dd")
5646 (fh "%02d:%02d")
5647 y d h m align)
5648 (if havetime
5649 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5650 y 0
5651 d (floor (/ diff ds)) diff (mod diff ds)
5652 h (floor (/ diff hs)) diff (mod diff hs)
5653 m (floor (/ diff 60)))
5654 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5655 y 0
5656 d (floor (+ (/ diff ds) 0.5))
5657 h 0 m 0))
5658 (if (not to-buffer)
5659 (message (org-make-tdiff-string y d h m))
5660 (when (org-at-table-p)
5661 (goto-char match-end)
5662 (setq align t)
5663 (and (looking-at " *|") (goto-char (match-end 0))))
5664 (if (looking-at
5665 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
5666 (replace-match ""))
5667 (if negative (insert " -"))
5668 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
5669 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
5670 (insert " " (format fh h m))))
5671 (if align (org-table-align))
5672 (message "Time difference inserted"))))
5673
5674 (defun org-make-tdiff-string (y d h m)
5675 (let ((fmt "")
5676 (l nil))
5677 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5678 l (push y l)))
5679 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5680 l (push d l)))
5681 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5682 l (push h l)))
5683 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5684 l (push m l)))
5685 (apply 'format fmt (nreverse l))))
5686
5687 (defun org-time-string-to-time (s)
5688 (apply 'encode-time (org-parse-time-string s)))
5689
5690 (defun org-parse-time-string (s &optional nodefault)
5691 "Parse the standard Org-mode time string.
5692 This should be a lot faster than the normal `parse-time-string'.
5693 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5694 hour and minute fields will be nil if not given."
5695 (if (string-match org-ts-regexp1 s)
5696 (list 0
5697 (if (or (match-beginning 8) (not nodefault))
5698 (string-to-number (or (match-string 8 s) "0")))
5699 (if (or (match-beginning 7) (not nodefault))
5700 (string-to-number (or (match-string 7 s) "0")))
5701 (string-to-number (match-string 4 s))
5702 (string-to-number (match-string 3 s))
5703 (string-to-number (match-string 2 s))
5704 nil nil nil)
5705 (make-list 9 0)))
5706
5707 (defun org-timestamp-up (&optional arg)
5708 "Increase the date item at the cursor by one.
5709 If the cursor is on the year, change the year. If it is on the month or
5710 the day, change that.
5711 With prefix ARG, change by that many units."
5712 (interactive "p")
5713 (org-timestamp-change (prefix-numeric-value arg)))
5714
5715 (defun org-timestamp-down (&optional arg)
5716 "Decrease the date item at the cursor by one.
5717 If the cursor is on the year, change the year. If it is on the month or
5718 the day, change that.
5719 With prefix ARG, change by that many units."
5720 (interactive "p")
5721 (org-timestamp-change (- (prefix-numeric-value arg))))
5722
5723 (defun org-timestamp-up-day (&optional arg)
5724 "Increase the date in the time stamp by one day.
5725 With prefix ARG, change that many days."
5726 (interactive "p")
5727 (if (and (not (org-at-timestamp-p t))
5728 (org-on-heading-p))
5729 (org-todo 'up)
5730 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5731
5732 (defun org-timestamp-down-day (&optional arg)
5733 "Decrease the date in the time stamp by one day.
5734 With prefix ARG, change that many days."
5735 (interactive "p")
5736 (if (and (not (org-at-timestamp-p t))
5737 (org-on-heading-p))
5738 (org-todo 'down)
5739 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5740
5741 (defsubst org-pos-in-match-range (pos n)
5742 (and (match-beginning n)
5743 (<= (match-beginning n) pos)
5744 (>= (match-end n) pos)))
5745
5746 (defun org-at-timestamp-p (&optional also-inactive)
5747 "Determine if the cursor is in or at a timestamp."
5748 (interactive)
5749 (let* ((tsr (if also-inactive org-ts-regexp3 org-ts-regexp2))
5750 (pos (point))
5751 (ans (or (looking-at tsr)
5752 (save-excursion
5753 (skip-chars-backward "^[<\n\r\t")
5754 (if (> (point) 1) (backward-char 1))
5755 (and (looking-at tsr)
5756 (> (- (match-end 0) pos) -1))))))
5757 (and (boundp 'org-ts-what)
5758 (setq org-ts-what
5759 (cond
5760 ((org-pos-in-match-range pos 2) 'year)
5761 ((org-pos-in-match-range pos 3) 'month)
5762 ((org-pos-in-match-range pos 7) 'hour)
5763 ((org-pos-in-match-range pos 8) 'minute)
5764 ((or (org-pos-in-match-range pos 4)
5765 (org-pos-in-match-range pos 5)) 'day)
5766 (t 'day))))
5767 ans))
5768
5769 (defun org-timestamp-change (n &optional what)
5770 "Change the date in the time stamp at point.
5771 The date will be changed by N times WHAT. WHAT can be `day', `month',
5772 `year', `minute', `second'. If WHAT is not given, the cursor position
5773 in the timestamp determines what will be changed."
5774 (let ((fmt (car org-time-stamp-formats))
5775 org-ts-what
5776 (pos (point))
5777 ts time time0)
5778 (if (not (org-at-timestamp-p t))
5779 (error "Not at a timestamp"))
5780 (setq org-ts-what (or what org-ts-what))
5781 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5782 (- (match-end 0) (match-beginning 0))))
5783 1)
5784 (cdr org-time-stamp-formats)
5785 (car org-time-stamp-formats)))
5786 (if (= (char-after (match-beginning 0)) ?\[)
5787 (setq fmt (concat "[" (substring fmt 1 -1) "]")))
5788 (setq ts (match-string 0))
5789 (replace-match "")
5790 (setq time0 (org-parse-time-string ts))
5791 (setq time
5792 (apply 'encode-time
5793 (append
5794 (list (or (car time0) 0))
5795 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5796 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5797 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5798 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5799 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5800 (nthcdr 6 time0))))
5801 (if (eq what 'calendar)
5802 (let ((cal-date
5803 (save-excursion
5804 (save-match-data
5805 (set-buffer "*Calendar*")
5806 (calendar-cursor-to-date)))))
5807 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5808 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5809 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5810 (setcar time0 (or (car time0) 0))
5811 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5812 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5813 (setq time (apply 'encode-time time0))))
5814 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5815 (goto-char pos)
5816 ;; Try to recenter the calendar window, if any
5817 (if (and org-calendar-follow-timestamp-change
5818 (get-buffer-window "*Calendar*" t)
5819 (memq org-ts-what '(day month year)))
5820 (org-recenter-calendar (time-to-days time)))))
5821
5822 (defun org-recenter-calendar (date)
5823 "If the calendar is visible, recenter it to DATE."
5824 (let* ((win (selected-window))
5825 (cwin (get-buffer-window "*Calendar*" t))
5826 (calendar-move-hook nil))
5827 (when cwin
5828 (select-window cwin)
5829 (calendar-goto-date (if (listp date) date
5830 (calendar-gregorian-from-absolute date)))
5831 (select-window win))))
5832
5833 (defun org-goto-calendar (&optional arg)
5834 "Go to the Emacs calendar at the current date.
5835 If there is a time stamp in the current line, go to that date.
5836 A prefix ARG can be used to force the current date."
5837 (interactive "P")
5838 (let ((tsr org-ts-regexp) diff
5839 (calendar-move-hook nil)
5840 (view-calendar-holidays-initially nil)
5841 (view-diary-entries-initially nil))
5842 (if (or (org-at-timestamp-p)
5843 (save-excursion
5844 (beginning-of-line 1)
5845 (looking-at (concat ".*" tsr))))
5846 (let ((d1 (time-to-days (current-time)))
5847 (d2 (time-to-days
5848 (org-time-string-to-time (match-string 1)))))
5849 (setq diff (- d2 d1))))
5850 (calendar)
5851 (calendar-goto-today)
5852 (if (and diff (not arg)) (calendar-forward-day diff))))
5853
5854 (defun org-date-from-calendar ()
5855 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
5856 If there is already a time stamp at the cursor position, update it."
5857 (interactive)
5858 (org-timestamp-change 0 'calendar))
5859
5860 ;;; The clock for measuring work time.
5861
5862 (defvar org-clock-marker (make-marker)
5863 "Marker recording the last clock-in.")
5864
5865 (defun org-clock-in ()
5866 "Start the clock on the current item.
5867 If necessary, clock-out of the currently active clock."
5868 (interactive)
5869 (org-clock-out t)
5870 (let (ts)
5871 (save-excursion
5872 (org-back-to-heading t)
5873 (beginning-of-line 2)
5874 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5875 (not (equal (match-string 1) org-clock-string)))
5876 (beginning-of-line 1))
5877 (insert "\n") (backward-char 1)
5878 (indent-relative)
5879 (insert org-clock-string " "
5880 (setq ts (concat "[" (format-time-string
5881 (substring
5882 (cdr org-time-stamp-formats) 1 -1)
5883 (current-time))
5884 "]")))
5885 (move-marker org-clock-marker (point))
5886 (message "Clock started at %s" ts))))
5887
5888 (defun org-clock-out (&optional fail-quietly)
5889 "Stop the currently running clock.
5890 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
5891 (interactive)
5892 (catch 'exit
5893 (if (not (marker-buffer org-clock-marker))
5894 (if fail-quietly (throw 'exit t) (error "No active clock")))
5895 (let (ts te s h m)
5896 (save-excursion
5897 (set-buffer (marker-buffer org-clock-marker))
5898 (goto-char org-clock-marker)
5899 (beginning-of-line 1)
5900 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5901 (equal (match-string 1) org-clock-string))
5902 (setq ts (match-string 2))
5903 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
5904 (goto-char org-clock-marker)
5905 (setq te (concat "[" (format-time-string
5906 (substring
5907 (cdr org-time-stamp-formats) 1 -1)
5908 (current-time))
5909 "]"))
5910 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
5911 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
5912 h (floor (/ s 3600))
5913 s (- s (* 3600 h))
5914 m (floor (/ s 60))
5915 s (- s (* 60 s)))
5916 (insert "--" te " => " (format "%2d:%02d" h m))
5917 (move-marker org-clock-marker nil)
5918 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
5919
5920 (defun org-clock-cancel ()
5921 "Cancel the running clock be removing the start timestamp."
5922 (interactive)
5923 (if (not (marker-buffer org-clock-marker))
5924 (error "No active clock"))
5925 (save-excursion
5926 (set-buffer (marker-buffer org-clock-marker))
5927 (goto-char org-clock-marker)
5928 (delete-region (1- (point-at-bol)) (point-at-eol)))
5929 (message "Clock canceled"))
5930
5931 (defvar org-clock-file-total-minutes nil
5932 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
5933 (make-variable-buffer-local 'org-clock-file-total-minutes)
5934
5935 (defun org-clock-sum ()
5936 "Sum the times for each subtree.
5937 Puts the resulting times in minutes as a text property on each headline."
5938 (interactive)
5939 (let* ((bmp (buffer-modified-p))
5940 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
5941 org-clock-string
5942 ".*=>[ \t]*\\([0-9]+\\):\\([0-9]+\\)[ \t]*$"))
5943 (lmax 30)
5944 (ltimes (make-vector lmax 0))
5945 (t1 0)
5946 (level 0)
5947 time)
5948 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
5949 (save-excursion
5950 (goto-char (point-max))
5951 (while (re-search-backward re nil t)
5952 (if (match-end 2)
5953 ;; A time
5954 (setq t1 (+ t1 (* 60 (string-to-number (match-string 2)))
5955 (string-to-number (match-string 3))))
5956 ;; A headline
5957 (setq level (- (match-end 1) (match-beginning 1)))
5958 (when (or (> t1 0) (> (aref ltimes level) 0))
5959 (loop for l from 0 to level do
5960 (aset ltimes l (+ (aref ltimes l) t1)))
5961 (setq t1 0 time (aref ltimes level))
5962 (loop for l from level to (1- lmax) do
5963 (aset ltimes l 0))
5964 (goto-char (match-beginning 0))
5965 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
5966 (setq org-clock-file-total-minutes (aref ltimes 0)))
5967 (set-buffer-modified-p bmp)))
5968
5969 (defun org-clock-display (&optional total-only)
5970 "Show subtree times in the entire buffer.
5971 If TOTAL-ONLY is non-nil, only show the total time for the entire file
5972 in the echo area."
5973 (interactive)
5974 (org-remove-clock-overlays)
5975 (let (time h m p)
5976 (org-clock-sum)
5977 (unless total-only
5978 (save-excursion
5979 (goto-char (point-min))
5980 (while (setq p (next-single-property-change (point) :org-clock-minutes))
5981 (goto-char p)
5982 (when (setq time (get-text-property p :org-clock-minutes))
5983 (org-put-clock-overlay time (funcall outline-level))))
5984 (setq h (/ org-clock-file-total-minutes 60)
5985 m (- org-clock-file-total-minutes (* 60 h)))
5986 ;; Arrange to remove the overlays upon next change.
5987 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
5988 nil 'local)))
5989 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
5990
5991 (defvar org-clock-overlays nil)
5992 (make-variable-buffer-local 'org-clock-overlays)
5993
5994 (defun org-put-clock-overlay (time &optional level)
5995 "Put an overlays on the current line, displaying TIME.
5996 If LEVEL is given, prefix time with a corresponding number of stars.
5997 This creates a new overlay and stores it in `org-clock-overlays', so that it
5998 will be easy to remove."
5999 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
6000 (l (if level (org-get-legal-level level 0) 0))
6001 (off 0)
6002 ov tx)
6003 (move-to-column c)
6004 (unless (eolp) (skip-chars-backward "^ \t"))
6005 (skip-chars-backward " \t")
6006 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6007 tx (concat (buffer-substring (1- (point)) (point))
6008 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6009 (org-add-props (format "%s %2d:%02d%s"
6010 (make-string l ?*) h m
6011 (make-string (- 10 l) ?\ ))
6012 '(face secondary-selection))
6013 ""))
6014 (org-overlay-put ov 'display tx)
6015 (push ov org-clock-overlays)))
6016
6017 (defun org-remove-clock-overlays (&optional beg end noremove)
6018 "Remove the occur highlights from the buffer.
6019 BEG and END are ignored. If NOREMOVE is nil, remove this function
6020 from the `before-change-functions' in the current buffer."
6021 (interactive)
6022 (unless org-inhibit-highlight-removal
6023 (mapc 'org-delete-overlay org-clock-overlays)
6024 (setq org-clock-overlays nil)
6025 (unless noremove
6026 (remove-hook 'before-change-functions
6027 'org-remove-clock-overlays 'local))))
6028
6029 (defun org-clock-out-if-current ()
6030 "Clock out if the current entry contains the running clock.
6031 This is used to stop the clock after a TODO entry is marked DONE."
6032 (when (and (equal state org-done-string)
6033 (equal (marker-buffer org-clock-marker) (current-buffer))
6034 (< (point) org-clock-marker)
6035 (> (save-excursion (outline-next-heading) (point))
6036 org-clock-marker))
6037 (org-clock-out)))
6038
6039 (add-hook 'org-after-todo-state-change-hook
6040 'org-clock-out-if-current)
6041
6042 (defun org-check-running-clock ()
6043 "Check if the current buffer contains the running clock.
6044 If yes, offer to stop it and to save the buffer with the changes."
6045 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6046 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6047 (buffer-name))))
6048 (org-clock-out)
6049 (when (y-or-n-p "Save changed buffer?")
6050 (save-buffer))))
6051
6052 (defun org-clock-report ()
6053 "Create a table containing a report about clocked time.
6054 If the buffer contains lines
6055 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6056
6057 #+END: clocktable
6058 then the table will be inserted between these lines, replacing whatever
6059 is was there before. If these lines are not in the buffer, the table
6060 is inserted at point, surrounded by the special lines.
6061 The BEGIN line can contain parameters. Allowed are:
6062 :maxlevel The maximum level to be included in the table. Default is 3.
6063 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6064 (interactive)
6065 (org-remove-clock-overlays)
6066 (unless (org-find-dblock "clocktable")
6067 (org-create-dblock (list :name "clocktable"
6068 :maxlevel 2 :emphasize nil)))
6069 (org-update-dblock))
6070
6071 (defun org-dblock-write:clocktable (params)
6072 "Write the standard clocktable."
6073 (let ((hlchars '((1 . "*") (2 . ?/)))
6074 (emph nil)
6075 (ins (make-marker))
6076 ipos time h m p level hlc hdl maxlevel)
6077 (setq maxlevel (or (plist-get params :maxlevel) 3)
6078 emph (plist-get params :emphasize))
6079 (move-marker ins (point))
6080 (setq ipos (point))
6081 (insert-before-markers "Clock summary at ["
6082 (substring
6083 (format-time-string (cdr org-time-stamp-formats))
6084 1 -1)
6085 "]\n|L|Headline|Time|\n")
6086 (org-clock-sum)
6087 (setq h (/ org-clock-file-total-minutes 60)
6088 m (- org-clock-file-total-minutes (* 60 h)))
6089 (insert-before-markers "|-\n|0|" "*Total file time*| "
6090 (format "*%d:%02d*" h m)
6091 "|\n")
6092 (goto-char (point-min))
6093 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6094 (goto-char p)
6095 (when (setq time (get-text-property p :org-clock-minutes))
6096 (beginning-of-line 1)
6097 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6098 (setq level (- (match-end 1) (match-beginning 1)))
6099 (<= level maxlevel))
6100 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6101 hdl (match-string 2)
6102 h (/ time 60)
6103 m (- time (* 60 h)))
6104 (save-excursion
6105 (goto-char ins)
6106 (if (= level 1) (insert-before-markers "|-\n"))
6107 (insert-before-markers
6108 "| " (int-to-string level) "|" hlc hdl hlc " |"
6109 (make-string (1- level) ?|)
6110 hlc
6111 (format "%d:%02d" h m)
6112 hlc
6113 " |\n")))))
6114 (goto-char ins)
6115 (backward-delete-char 1)
6116 (goto-char ipos)
6117 (skip-chars-forward "^|")
6118 (org-table-align)))
6119
6120 (defun org-collect-clock-time-entries ()
6121 "Return an internal list with clocking information.
6122 This list has one entry for each CLOCK interval.
6123 FIXME: describe the elements."
6124 (interactive)
6125 (let ((re (concat "^[ \t]*" org-clock-string
6126 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
6127 rtn beg end next cont level title total closedp leafp
6128 clockpos titlepos h m donep)
6129 (save-excursion
6130 (org-clock-sum)
6131 (goto-char (point-min))
6132 (while (re-search-forward re nil t)
6133 (setq clockpos (match-beginning 0)
6134 beg (match-string 1) end (match-string 2)
6135 cont (match-end 0))
6136 (setq beg (apply 'encode-time (org-parse-time-string beg))
6137 end (apply 'encode-time (org-parse-time-string end)))
6138 (org-back-to-heading t)
6139 (setq donep (org-entry-is-done-p))
6140 (setq titlepos (point)
6141 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
6142 h (/ total 60) m (- total (* 60 h))
6143 total (cons h m))
6144 (looking-at "\\(\\*+\\) +\\(.*\\)")
6145 (setq level (- (match-end 1) (match-beginning 1))
6146 title (org-match-string-no-properties 2))
6147 (save-excursion (outline-next-heading) (setq next (point)))
6148 (setq closedp (re-search-forward org-closed-time-regexp next t))
6149 (goto-char next)
6150 (setq leafp (and (looking-at "^\\*+ ")
6151 (<= (- (match-end 0) (point)) level)))
6152 (push (list beg end clockpos closedp donep
6153 total title titlepos level leafp)
6154 rtn)
6155 (goto-char cont)))
6156 (nreverse rtn)))
6157
6158 ;;; Agenda, and Diary Integration
6159
6160 ;;; Define the mode
6161
6162 (defvar org-agenda-mode-map (make-sparse-keymap)
6163 "Keymap for `org-agenda-mode'.")
6164
6165 (defvar org-agenda-menu) ; defined later in this file.
6166 (defvar org-agenda-follow-mode nil)
6167 (defvar org-agenda-show-log nil)
6168 (defvar org-agenda-buffer-name "*Org Agenda*")
6169 (defvar org-agenda-redo-command nil)
6170 (defvar org-agenda-mode-hook nil)
6171 (defvar org-agenda-type nil)
6172 (defvar org-agenda-force-single-file nil)
6173
6174 (defun org-agenda-mode ()
6175 "Mode for time-sorted view on action items in Org-mode files.
6176
6177 The following commands are available:
6178
6179 \\{org-agenda-mode-map}"
6180 (interactive)
6181 (kill-all-local-variables)
6182 (setq major-mode 'org-agenda-mode)
6183 (setq mode-name "Org-Agenda")
6184 (use-local-map org-agenda-mode-map)
6185 (easy-menu-add org-agenda-menu)
6186 (if org-startup-truncated (setq truncate-lines t))
6187 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
6188 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
6189 (unless org-agenda-keep-modes
6190 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
6191 org-agenda-show-log nil))
6192 (easy-menu-change
6193 '("Agenda") "Agenda Files"
6194 (append
6195 (list
6196 (vector
6197 (if (get 'org-agenda-files 'org-restrict)
6198 "Restricted to single file"
6199 "Edit File List")
6200 '(org-edit-agenda-file-list)
6201 (not (get 'org-agenda-files 'org-restrict)))
6202 "--")
6203 (mapcar 'org-file-menu-entry (org-agenda-files))))
6204 (org-agenda-set-mode-name)
6205 (apply
6206 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
6207 (list 'org-agenda-mode-hook)))
6208
6209 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
6210 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
6211 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
6212 (define-key org-agenda-mode-map " " 'org-agenda-show)
6213 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
6214 (define-key org-agenda-mode-map "o" 'delete-other-windows)
6215 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
6216 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
6217 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
6218 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
6219 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
6220 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
6221 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
6222 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
6223 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
6224 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
6225 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
6226
6227 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
6228 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
6229 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
6230 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
6231 (while l (define-key org-agenda-mode-map
6232 (int-to-string (pop l)) 'digit-argument)))
6233
6234 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
6235 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
6236 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
6237 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
6238 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
6239 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
6240 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
6241 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
6242 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
6243 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
6244 (define-key org-agenda-mode-map "n" 'next-line)
6245 (define-key org-agenda-mode-map "p" 'previous-line)
6246 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
6247 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
6248 (define-key org-agenda-mode-map "," 'org-agenda-priority)
6249 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
6250 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
6251 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
6252 (eval-after-load "calendar"
6253 '(define-key calendar-mode-map org-calendar-to-agenda-key
6254 'org-calendar-goto-agenda))
6255 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
6256 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
6257 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
6258 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
6259 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
6260 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
6261 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
6262 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
6263 (define-key org-agenda-mode-map "O" 'org-clock-out)
6264 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
6265 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
6266 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
6267 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
6268 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
6269 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
6270 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
6271 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
6272 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
6273 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
6274 "Local keymap for agenda entries from Org-mode.")
6275
6276 (define-key org-agenda-keymap
6277 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
6278 (define-key org-agenda-keymap
6279 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
6280 (when org-agenda-mouse-1-follows-link
6281 (define-key org-agenda-keymap [follow-link] 'mouse-face))
6282 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
6283 '("Agenda"
6284 ("Agenda Files")
6285 "--"
6286 ["Show" org-agenda-show t]
6287 ["Go To (other window)" org-agenda-goto t]
6288 ["Go To (one window)" org-agenda-switch-to t]
6289 ["Follow Mode" org-agenda-follow-mode
6290 :style toggle :selected org-agenda-follow-mode :active t]
6291 "--"
6292 ["Cycle TODO" org-agenda-todo t]
6293 ("Tags"
6294 ["Show all Tags" org-agenda-show-tags t]
6295 ["Set Tags" org-agenda-set-tags t])
6296 ("Schedule"
6297 ["Schedule" org-agenda-schedule t]
6298 ["Set Deadline" org-agenda-deadline t]
6299 "--"
6300 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
6301 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
6302 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6303 ("Priority"
6304 ["Set Priority" org-agenda-priority t]
6305 ["Increase Priority" org-agenda-priority-up t]
6306 ["Decrease Priority" org-agenda-priority-down t]
6307 ["Show Priority" org-agenda-show-priority t])
6308 "--"
6309 ;; ["New agenda command" org-agenda t]
6310 ["Rebuild buffer" org-agenda-redo t]
6311 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
6312 "--"
6313 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6314 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6315 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6316 "--"
6317 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6318 :style radio :selected (equal org-agenda-ndays 1)]
6319 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6320 :style radio :selected (equal org-agenda-ndays 7)]
6321 "--"
6322 ["Show Logbook entries" org-agenda-log-mode
6323 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6324 ["Include Diary" org-agenda-toggle-diary
6325 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6326 ["Use Time Grid" org-agenda-toggle-time-grid
6327 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6328 "--"
6329 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6330 ("Calendar Commands"
6331 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6332 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6333 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6334 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6335 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
6336 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
6337 "--"
6338 ["Quit" org-agenda-quit t]
6339 ["Exit and Release Buffers" org-agenda-exit t]
6340 ))
6341
6342 ;;;###autoload
6343 (defun org-agenda (arg)
6344 "Dispatch agenda commands to collect entries to the agenda buffer.
6345 Prompts for a character to select a command. Any prefix arg will be passed
6346 on to the selected command. The default selections are:
6347
6348 a Call `org-agenda' to display the agenda for the current day or week.
6349 t Call `org-todo-list' to display the global todo list.
6350 T Call `org-todo-list' to display the global todo list, select only
6351 entries with a specific TODO keyword (the user gets a prompt).
6352 m Call `org-tags-view' to display headlines with tags matching
6353 a condition (the user is prompted for the condition).
6354 M Like `m', but select only TODO entries, no ordinary headlines.
6355
6356 More commands can be added by configuring the variable
6357 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
6358 searches can be pre-defined in this way.
6359
6360 If the current buffer is in Org-mode and visiting a file, you can also
6361 first press `1' to indicate that the agenda should be temporarily (until the
6362 next use of \\[org-agenda]) restricted to the current file."
6363 (interactive "P")
6364 (catch 'exit
6365 (let ((restrict-ok (and buffer-file-name (org-mode-p)))
6366 (bfn buffer-file-name)
6367 (custom org-agenda-custom-commands)
6368 c entry key type string)
6369 (put 'org-agenda-files 'org-restrict nil)
6370 (save-window-excursion
6371 (delete-other-windows)
6372 (switch-to-buffer-other-window " *Agenda Commands*")
6373 (erase-buffer)
6374 (insert
6375 "Press key for an agenda command:
6376 --------------------------------
6377 a Agenda for current week or day
6378 t List of all TODO entries T Entries with special TODO kwd
6379 m Match a TAGS query M Like m, but only TODO entries
6380 C Configure your own agenda commands")
6381 (while (setq entry (pop custom))
6382 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
6383 (insert (format "\n%-4s%-14s: %s"
6384 key
6385 (cond
6386 ((eq type 'tags) "Tags query")
6387 ((eq type 'todo) "TODO keyword")
6388 ((eq type 'tags-tree) "Tags tree")
6389 ((eq type 'todo-tree) "TODO kwd tree")
6390 ((eq type 'occur-tree) "Occur tree")
6391 (t "???"))
6392 (org-add-props string nil 'face 'org-warning))))
6393 (goto-char (point-min))
6394 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
6395 (message "Press key for agenda command%s"
6396 (if restrict-ok ", or [1] to restrict to current file" ""))
6397 (setq c (read-char-exclusive))
6398 (message "")
6399 (when (equal c ?1)
6400 (if restrict-ok
6401 (put 'org-agenda-files 'org-restrict (list bfn))
6402 (error "Cannot restrict agenda to current buffer"))
6403 (message "Press key for agenda command%s"
6404 (if restrict-ok " (restricted to current file)" ""))
6405 (setq c (read-char-exclusive))
6406 (message "")))
6407 (require 'calendar) ; FIXME: can we avoid this for some commands?
6408 ;; For example the todo list should not need it (but does...)
6409 (cond
6410 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
6411 ((equal c ?a) (call-interactively 'org-agenda-list))
6412 ((equal c ?t) (call-interactively 'org-todo-list))
6413 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
6414 ((equal c ?m) (call-interactively 'org-tags-view))
6415 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
6416 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
6417 (setq type (nth 1 entry) string (nth 2 entry))
6418 (cond
6419 ((eq type 'tags)
6420 (org-tags-view current-prefix-arg string))
6421 ((eq type 'tags-todo)
6422 (org-tags-view '(4) string))
6423 ((eq type 'todo)
6424 (org-todo-list string))
6425 ((eq type 'tags-tree)
6426 (org-check-for-org-mode)
6427 (org-tags-sparse-tree current-prefix-arg string))
6428 ((eq type 'todo-tree)
6429 (org-check-for-org-mode)
6430 (org-occur (concat "^" outline-regexp "[ \t]*"
6431 (regexp-quote string) "\\>")))
6432 ((eq type 'occur-tree)
6433 (org-check-for-org-mode)
6434 (org-occur string))
6435 (t (error "Invalid custom agenda command type %s" type))))
6436 (t (error "Invalid key"))))))
6437
6438 (defun org-check-for-org-mode ()
6439 "Make sure current buffer is in org-mode. Error if not."
6440 (or (org-mode-p)
6441 (error "Cannot execute org-mode agenda command on buffer in %s."
6442 major-mode)))
6443
6444 (defun org-fit-agenda-window ()
6445 "Fit the window to the buffer size."
6446 (and org-fit-agenda-window
6447 (fboundp 'fit-window-to-buffer)
6448 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
6449 (/ (frame-height) 2))))
6450
6451 (defun org-agenda-files (&optional unrestricted)
6452 "Get the list of agenda files.
6453 Optional UNRESTRICTED means return the full list even if a restriction
6454 is currently in place."
6455 (cond
6456 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
6457 ((stringp org-agenda-files) (org-read-agenda-file-list))
6458 ((listp org-agenda-files) org-agenda-files)
6459 (t (error "Invalid value of `org-agenda-files'"))))
6460
6461 (defvar org-window-configuration)
6462
6463 (defun org-edit-agenda-file-list ()
6464 "Edit the list of agenda files.
6465 Depending on setup, this either uses customize to edit the variable
6466 `org-agenda-files', or it visits the file that is holding the list. In the
6467 latter case, the buffer is set up in a way that saving it automatically kills
6468 the buffer and restores the previous window configuration."
6469 (interactive)
6470 (if (stringp org-agenda-files)
6471 (let ((cw (current-window-configuration)))
6472 (find-file org-agenda-files)
6473 (set (make-local-variable 'org-window-configuration) cw)
6474 (org-add-hook 'after-save-hook
6475 (lambda ()
6476 (set-window-configuration
6477 (prog1 org-window-configuration
6478 (kill-buffer (current-buffer))))
6479 (org-install-agenda-files-menu)
6480 (message "New agenda file list installed"))
6481 nil 'local)
6482 (message (substitute-command-keys
6483 "Edit list and finish with \\[save-buffer]")))
6484 (customize-variable 'org-agenda-files)))
6485
6486 (defun org-store-new-agenda-file-list (list)
6487 "Set new value for the agenda file list and save it correcly."
6488 (if (stringp org-agenda-files)
6489 (let ((f org-agenda-files) b)
6490 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
6491 (with-temp-file f
6492 (insert (mapconcat 'identity list "\n") "\n")))
6493 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
6494 (setq org-agenda-files list)
6495 (customize-save-variable 'org-agenda-files org-agenda-files))))
6496
6497 (defun org-read-agenda-file-list ()
6498 "Read the list of agenda files from a file."
6499 (when (stringp org-agenda-files)
6500 (with-temp-buffer
6501 (insert-file-contents org-agenda-files)
6502 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
6503
6504 (defvar org-agenda-markers nil
6505 "List of all currently active markers created by `org-agenda'.")
6506 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
6507 "Creation time of the last agenda marker.")
6508
6509 (defun org-agenda-new-marker (&optional pos)
6510 "Return a new agenda marker.
6511 Org-mode keeps a list of these markers and resets them when they are
6512 no longer in use."
6513 (let ((m (copy-marker (or pos (point)))))
6514 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
6515 (push m org-agenda-markers)
6516 m))
6517
6518 (defun org-agenda-maybe-reset-markers (&optional force)
6519 "Reset markers created by `org-agenda'. But only if they are old enough."
6520 (if (or force
6521 (> (- (time-to-seconds (current-time))
6522 org-agenda-last-marker-time)
6523 5))
6524 (while org-agenda-markers
6525 (move-marker (pop org-agenda-markers) nil))))
6526
6527 (defvar org-agenda-new-buffers nil
6528 "Buffers created to visit agenda files.")
6529
6530 (defun org-get-agenda-file-buffer (file)
6531 "Get a buffer visiting FILE. If the buffer needs to be created, add
6532 it to the list of buffers which might be released later."
6533 (let ((buf (find-buffer-visiting file)))
6534 (if buf
6535 buf ; just return it
6536 ;; Make a new buffer and remember it
6537 (setq buf (find-file-noselect file))
6538 (if buf (push buf org-agenda-new-buffers))
6539 buf)))
6540
6541 (defun org-release-buffers (blist)
6542 "Release all buffers in list, asking the user for confirmation when needed.
6543 When a buffer is unmodified, it is just killed. When modified, it is saved
6544 \(if the user agrees) and then killed."
6545 (let (buf file)
6546 (while (setq buf (pop blist))
6547 (setq file (buffer-file-name buf))
6548 (when (and (buffer-modified-p buf)
6549 file
6550 (y-or-n-p (format "Save file %s? " file)))
6551 (with-current-buffer buf (save-buffer)))
6552 (kill-buffer buf))))
6553
6554 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
6555
6556 (defun org-timeline (&optional include-all keep-modes)
6557 "Show a time-sorted view of the entries in the current org file.
6558 Only entries with a time stamp of today or later will be listed. With
6559 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
6560 under the current date.
6561 If the buffer contains an active region, only check the region for
6562 dates."
6563 (interactive "P")
6564 (require 'calendar)
6565 (org-agenda-maybe-reset-markers 'force)
6566 (org-compile-prefix-format org-timeline-prefix-format)
6567 (let* ((dopast t)
6568 (dotodo include-all)
6569 (doclosed org-agenda-show-log)
6570 (org-agenda-keep-modes keep-modes)
6571 (entry buffer-file-name)
6572 (org-agenda-files (list buffer-file-name))
6573 (date (calendar-current-date))
6574 (win (selected-window))
6575 (pos1 (point))
6576 (beg (if (org-region-active-p) (region-beginning) (point-min)))
6577 (end (if (org-region-active-p) (region-end) (point-max)))
6578 (day-numbers (org-get-all-dates beg end 'no-ranges
6579 t doclosed ; always include today
6580 org-timeline-show-empty-dates))
6581 (today (time-to-days (current-time)))
6582 (org-respect-restriction t)
6583 (past t)
6584 args
6585 s e rtn d emptyp)
6586 (org-prepare-agenda-buffers org-agenda-files)
6587 (setq org-agenda-redo-command
6588 (list 'progn
6589 (list 'switch-to-buffer-other-window (current-buffer))
6590 (list 'org-timeline (list 'quote include-all) t)))
6591 (if (not dopast)
6592 ;; Remove past dates from the list of dates.
6593 (setq day-numbers (delq nil (mapcar (lambda(x)
6594 (if (>= x today) x nil))
6595 day-numbers))))
6596 (switch-to-buffer-other-window
6597 (get-buffer-create org-agenda-buffer-name))
6598 (setq buffer-read-only nil)
6599 (erase-buffer)
6600 (org-agenda-mode) (setq buffer-read-only nil)
6601 (set (make-local-variable 'org-agenda-type) 'timeline)
6602 (if doclosed (push :closed args))
6603 (push :timestamp args)
6604 (if dotodo (push :todo args))
6605 (while (setq d (pop day-numbers))
6606 (if (and (listp d) (eq (car d) :omitted))
6607 (progn
6608 (setq s (point))
6609 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
6610 (put-text-property s (1- (point)) 'face 'org-level-3))
6611 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
6612 (if (and (>= d today)
6613 dopast
6614 past)
6615 (progn
6616 (setq past nil)
6617 (insert (make-string 79 ?-) "\n")))
6618 (setq date (calendar-gregorian-from-absolute d))
6619 (setq s (point))
6620 (setq rtn (and (not emptyp)
6621 (apply 'org-agenda-get-day-entries
6622 entry date args)))
6623 (if (or rtn (equal d today) org-timeline-show-empty-dates)
6624 (progn
6625 (insert (calendar-day-name date) " "
6626 (number-to-string (extract-calendar-day date)) " "
6627 (calendar-month-name (extract-calendar-month date)) " "
6628 (number-to-string (extract-calendar-year date)) "\n")
6629 (put-text-property s (1- (point)) 'face
6630 'org-level-3)
6631 (if (equal d today)
6632 (put-text-property s (1- (point)) 'org-today t))
6633 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
6634 (put-text-property s (1- (point)) 'day d)))))
6635 (goto-char (point-min))
6636 (setq buffer-read-only t)
6637 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6638 (point-min)))
6639 (when (not org-select-timeline-window)
6640 (select-window win)
6641 (goto-char pos1))))
6642
6643 ;;;###autoload
6644 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
6645 "Produce a weekly view from all files in variable `org-agenda-files'.
6646 The view will be for the current week, but from the overview buffer you
6647 will be able to go to other weeks.
6648 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
6649 also be shown, under the current date.
6650 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
6651 on the days are also shown. See the variable `org-log-done' for how
6652 to turn on logging.
6653 START-DAY defaults to TODAY, or to the most recent match for the weekday
6654 given in `org-agenda-start-on-weekday'.
6655 NDAYS defaults to `org-agenda-ndays'."
6656 (interactive "P")
6657 (org-agenda-maybe-reset-markers 'force)
6658 (org-compile-prefix-format org-agenda-prefix-format)
6659 (require 'calendar)
6660 (let* ((org-agenda-start-on-weekday
6661 (if (or (equal ndays 1)
6662 (and (null ndays) (equal 1 org-agenda-ndays)))
6663 nil org-agenda-start-on-weekday))
6664 (org-agenda-keep-modes keep-modes)
6665 (thefiles (org-agenda-files))
6666 (files thefiles)
6667 (win (selected-window))
6668 (today (time-to-days (current-time)))
6669 (sd (or start-day today))
6670 (start (if (or (null org-agenda-start-on-weekday)
6671 (< org-agenda-ndays 7))
6672 sd
6673 (let* ((nt (calendar-day-of-week
6674 (calendar-gregorian-from-absolute sd)))
6675 (n1 org-agenda-start-on-weekday)
6676 (d (- nt n1)))
6677 (- sd (+ (if (< d 0) 7 0) d)))))
6678 (day-numbers (list start))
6679 (inhibit-redisplay t)
6680 s e rtn rtnall file date d start-pos end-pos todayp nd)
6681 (org-prepare-agenda-buffers files)
6682 (setq org-agenda-redo-command
6683 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
6684 ;; Make the list of days
6685 (setq ndays (or ndays org-agenda-ndays)
6686 nd ndays)
6687 (while (> ndays 1)
6688 (push (1+ (car day-numbers)) day-numbers)
6689 (setq ndays (1- ndays)))
6690 (setq day-numbers (nreverse day-numbers))
6691 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6692 (progn
6693 (delete-other-windows)
6694 (switch-to-buffer-other-window
6695 (get-buffer-create org-agenda-buffer-name))))
6696 (setq buffer-read-only nil)
6697 (erase-buffer)
6698 (org-agenda-mode) (setq buffer-read-only nil)
6699 (set (make-local-variable 'org-agenda-type) 'agenda)
6700 (set (make-local-variable 'starting-day) (car day-numbers))
6701 (set (make-local-variable 'include-all-loc) include-all)
6702 (when (and (or include-all org-agenda-include-all-todo)
6703 (member today day-numbers))
6704 (setq files thefiles
6705 rtnall nil)
6706 (while (setq file (pop files))
6707 (catch 'nextfile
6708 (org-check-agenda-file file)
6709 (setq date (calendar-gregorian-from-absolute today)
6710 rtn (org-agenda-get-day-entries
6711 file date :todo))
6712 (setq rtnall (append rtnall rtn))))
6713 (when rtnall
6714 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
6715 (add-text-properties (point-min) (1- (point))
6716 (list 'face 'org-level-3))
6717 (insert (org-finalize-agenda-entries rtnall) "\n")))
6718 (while (setq d (pop day-numbers))
6719 (setq date (calendar-gregorian-from-absolute d)
6720 s (point))
6721 (if (or (setq todayp (= d today))
6722 (and (not start-pos) (= d sd)))
6723 (setq start-pos (point))
6724 (if (and start-pos (not end-pos))
6725 (setq end-pos (point))))
6726 (setq files thefiles
6727 rtnall nil)
6728 (while (setq file (pop files))
6729 (catch 'nextfile
6730 (org-check-agenda-file file)
6731 (if org-agenda-show-log
6732 (setq rtn (org-agenda-get-day-entries
6733 file date
6734 :deadline :scheduled :timestamp :closed))
6735 (setq rtn (org-agenda-get-day-entries
6736 file date
6737 :deadline :scheduled :timestamp)))
6738 (setq rtnall (append rtnall rtn))))
6739 (if org-agenda-include-diary
6740 (progn
6741 (require 'diary-lib)
6742 (setq rtn (org-get-entries-from-diary date))
6743 (setq rtnall (append rtnall rtn))))
6744 (if (or rtnall org-agenda-show-all-dates)
6745 (progn
6746 (insert (format "%-9s %2d %s %4d\n"
6747 (calendar-day-name date)
6748 (extract-calendar-day date)
6749 (calendar-month-name (extract-calendar-month date))
6750 (extract-calendar-year date)))
6751 (put-text-property s (1- (point)) 'face
6752 'org-level-3)
6753 (if rtnall (insert
6754 (org-finalize-agenda-entries
6755 (org-agenda-add-time-grid-maybe
6756 rtnall nd todayp))
6757 "\n"))
6758 (put-text-property s (1- (point)) 'day d))))
6759 (goto-char (point-min))
6760 (setq buffer-read-only t)
6761 (org-fit-agenda-window)
6762 (unless (and (pos-visible-in-window-p (point-min))
6763 (pos-visible-in-window-p (point-max)))
6764 (goto-char (1- (point-max)))
6765 (recenter -1)
6766 (if (not (pos-visible-in-window-p (or start-pos 1)))
6767 (progn
6768 (goto-char (or start-pos 1))
6769 (recenter 1))))
6770 (goto-char (or start-pos 1))
6771 (if (not org-select-agenda-window) (select-window win))
6772 (message "")))
6773
6774 (defvar org-select-this-todo-keyword nil)
6775
6776 ;;;###autoload
6777 (defun org-todo-list (arg &optional keep-modes)
6778 "Show all TODO entries from all agenda file in a single list.
6779 The prefix arg can be used to select a specific TODO keyword and limit
6780 the list to these. When using \\[universal-argument], you will be prompted
6781 for a keyword. A numeric prefix directly selects the Nth keyword in
6782 `org-todo-keywords'."
6783 (interactive "P")
6784 (org-agenda-maybe-reset-markers 'force)
6785 (org-compile-prefix-format org-agenda-prefix-format)
6786 (let* ((org-agenda-keep-modes keep-modes)
6787 (today (time-to-days (current-time)))
6788 (date (calendar-gregorian-from-absolute today))
6789 (win (selected-window))
6790 (kwds org-todo-keywords)
6791 (completion-ignore-case t)
6792 (org-select-this-todo-keyword
6793 (if (stringp arg) arg
6794 (and arg (integerp arg) (> arg 0)
6795 (nth (1- arg) org-todo-keywords))))
6796 rtn rtnall files file pos)
6797 (when (equal arg '(4))
6798 (setq org-select-this-todo-keyword
6799 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
6800 nil t)))
6801 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
6802 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6803 (progn
6804 (delete-other-windows)
6805 (switch-to-buffer-other-window
6806 (get-buffer-create org-agenda-buffer-name))))
6807 (setq buffer-read-only nil)
6808 (erase-buffer)
6809 (org-agenda-mode) (setq buffer-read-only nil)
6810 (set (make-local-variable 'org-agenda-type) 'todo)
6811 (set (make-local-variable 'last-arg) arg)
6812 (set (make-local-variable 'org-todo-keywords) kwds)
6813 (set (make-local-variable 'org-agenda-redo-command)
6814 '(org-todo-list (or current-prefix-arg last-arg) t))
6815 (setq files (org-agenda-files)
6816 rtnall nil)
6817 (org-prepare-agenda-buffers files)
6818 (while (setq file (pop files))
6819 (catch 'nextfile
6820 (org-check-agenda-file file)
6821 (setq rtn (org-agenda-get-day-entries file date :todo))
6822 (setq rtnall (append rtnall rtn))))
6823 (insert "Global list of TODO items of type: ")
6824 (add-text-properties (point-min) (1- (point))
6825 (list 'face 'org-level-3))
6826 (setq pos (point))
6827 (insert (or org-select-this-todo-keyword "ALL") "\n")
6828 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6829 (setq pos (point))
6830 (insert
6831 "Available with `N r': (0)ALL "
6832 (let ((n 0))
6833 (mapconcat (lambda (x)
6834 (format "(%d)%s" (setq n (1+ n)) x))
6835 org-todo-keywords " "))
6836 "\n")
6837 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
6838 (when rtnall
6839 (insert (org-finalize-agenda-entries rtnall) "\n"))
6840 (goto-char (point-min))
6841 (setq buffer-read-only t)
6842 (org-fit-agenda-window)
6843 (if (not org-select-agenda-window) (select-window win))))
6844
6845 (defun org-check-agenda-file (file)
6846 "Make sure FILE exists. If not, ask user what to do."
6847 (when (not (file-exists-p file))
6848 (message "non-existent file %s. [R]emove from list or [A]bort?"
6849 (abbreviate-file-name file))
6850 (let ((r (downcase (read-char-exclusive))))
6851 (cond
6852 ((equal r ?r)
6853 (org-remove-file file)
6854 (throw 'nextfile t))
6855 (t (error "Abort"))))))
6856
6857 (defun org-agenda-check-type (error &rest types)
6858 "Check if agenda buffer is of allowed type.
6859 If ERROR is non-nil, throw an error, otherwise just return nil."
6860 (if (memq org-agenda-type types)
6861 t
6862 (if error
6863 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
6864 nil)))
6865
6866 (defun org-agenda-quit ()
6867 "Exit agenda by removing the window or the buffer."
6868 (interactive)
6869 (let ((buf (current-buffer)))
6870 (if (not (one-window-p)) (delete-window))
6871 (kill-buffer buf)
6872 (org-agenda-maybe-reset-markers 'force)))
6873
6874 (defun org-agenda-exit ()
6875 "Exit agenda by removing the window or the buffer.
6876 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
6877 Org-mode buffers visited directly by the user will not be touched."
6878 (interactive)
6879 (org-release-buffers org-agenda-new-buffers)
6880 (setq org-agenda-new-buffers nil)
6881 (org-agenda-quit))
6882
6883 ;; FIXME: move this function.
6884 (defun org-save-all-org-buffers ()
6885 "Save all Org-mode buffers without user confirmation."
6886 (interactive)
6887 (message "Saving all Org-mode buffers...")
6888 (save-some-buffers t 'org-mode-p)
6889 (message "Saving all Org-mode buffers... done"))
6890
6891 (defun org-agenda-redo ()
6892 "Rebuild Agenda.
6893 When this is the global TODO list, a prefix argument will be interpreted."
6894 (interactive)
6895 (message "Rebuilding agenda buffer...")
6896 (eval org-agenda-redo-command)
6897 (message "Rebuilding agenda buffer...done"))
6898
6899 (defun org-agenda-goto-today ()
6900 "Go to today."
6901 (interactive)
6902 (org-agenda-check-type t 'timeline 'agenda)
6903 (if (boundp 'starting-day)
6904 (let ((cmd (car org-agenda-redo-command))
6905 (iall (nth 1 org-agenda-redo-command))
6906 (nday (nth 3 org-agenda-redo-command))
6907 (keep (nth 4 org-agenda-redo-command)))
6908 (eval (list cmd iall nil nday keep)))
6909 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6910 (point-min)))))
6911
6912 (defun org-agenda-later (arg)
6913 "Go forward in time by `org-agenda-ndays' days.
6914 With prefix ARG, go forward that many times `org-agenda-ndays'."
6915 (interactive "p")
6916 (org-agenda-check-type t 'agenda)
6917 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6918 (+ starting-day (* arg org-agenda-ndays)) nil t))
6919
6920 (defun org-agenda-earlier (arg)
6921 "Go back in time by `org-agenda-ndays' days.
6922 With prefix ARG, go back that many times `org-agenda-ndays'."
6923 (interactive "p")
6924 (org-agenda-check-type t 'agenda)
6925 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6926 (- starting-day (* arg org-agenda-ndays)) nil t))
6927
6928 (defun org-agenda-week-view ()
6929 "Switch to weekly view for agenda."
6930 (interactive)
6931 (org-agenda-check-type t 'agenda)
6932 (setq org-agenda-ndays 7)
6933 (org-agenda-list include-all-loc
6934 (or (get-text-property (point) 'day)
6935 starting-day)
6936 nil t)
6937 (org-agenda-set-mode-name)
6938 (message "Switched to week view"))
6939
6940 (defun org-agenda-day-view ()
6941 "Switch to daily view for agenda."
6942 (interactive)
6943 (org-agenda-check-type t 'agenda)
6944 (setq org-agenda-ndays 1)
6945 (org-agenda-list include-all-loc
6946 (or (get-text-property (point) 'day)
6947 starting-day)
6948 nil t)
6949 (org-agenda-set-mode-name)
6950 (message "Switched to day view"))
6951
6952 (defun org-agenda-next-date-line (&optional arg)
6953 "Jump to the next line indicating a date in agenda buffer."
6954 (interactive "p")
6955 (org-agenda-check-type t 'agenda 'timeline)
6956 (beginning-of-line 1)
6957 (if (looking-at "^\\S-") (forward-char 1))
6958 (if (not (re-search-forward "^\\S-" nil t arg))
6959 (progn
6960 (backward-char 1)
6961 (error "No next date after this line in this buffer")))
6962 (goto-char (match-beginning 0)))
6963
6964 (defun org-agenda-previous-date-line (&optional arg)
6965 "Jump to the previous line indicating a date in agenda buffer."
6966 (interactive "p")
6967 (org-agenda-check-type t 'agenda 'timeline)
6968 (beginning-of-line 1)
6969 (if (not (re-search-backward "^\\S-" nil t arg))
6970 (error "No previous date before this line in this buffer")))
6971
6972 ;; Initialize the highlight
6973 (defvar org-hl (org-make-overlay 1 1))
6974 (org-overlay-put org-hl 'face 'highlight)
6975
6976 (defun org-highlight (begin end &optional buffer)
6977 "Highlight a region with overlay."
6978 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
6979 org-hl begin end (or buffer (current-buffer))))
6980
6981 (defun org-unhighlight ()
6982 "Detach overlay INDEX."
6983 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
6984
6985
6986 (defun org-agenda-follow-mode ()
6987 "Toggle follow mode in an agenda buffer."
6988 (interactive)
6989 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
6990 (org-agenda-set-mode-name)
6991 (message "Follow mode is %s"
6992 (if org-agenda-follow-mode "on" "off")))
6993
6994 (defun org-agenda-log-mode ()
6995 "Toggle log mode in an agenda buffer."
6996 (interactive)
6997 (org-agenda-check-type t 'agenda 'timeline)
6998 (setq org-agenda-show-log (not org-agenda-show-log))
6999 (org-agenda-set-mode-name)
7000 (org-agenda-redo)
7001 (message "Log mode is %s"
7002 (if org-agenda-show-log "on" "off")))
7003
7004 (defun org-agenda-toggle-diary ()
7005 "Toggle diary inclusion in an agenda buffer."
7006 (interactive)
7007 (org-agenda-check-type t 'agenda)
7008 (setq org-agenda-include-diary (not org-agenda-include-diary))
7009 (org-agenda-redo)
7010 (org-agenda-set-mode-name)
7011 (message "Diary inclusion turned %s"
7012 (if org-agenda-include-diary "on" "off")))
7013
7014 (defun org-agenda-toggle-time-grid ()
7015 "Toggle time grid in an agenda buffer."
7016 (interactive)
7017 (org-agenda-check-type t 'agenda)
7018 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
7019 (org-agenda-redo)
7020 (org-agenda-set-mode-name)
7021 (message "Time-grid turned %s"
7022 (if org-agenda-use-time-grid "on" "off")))
7023
7024 (defun org-agenda-set-mode-name ()
7025 "Set the mode name to indicate all the small mode settings."
7026 (setq mode-name
7027 (concat "Org-Agenda"
7028 (if (equal org-agenda-ndays 1) " Day" "")
7029 (if (equal org-agenda-ndays 7) " Week" "")
7030 (if org-agenda-follow-mode " Follow" "")
7031 (if org-agenda-include-diary " Diary" "")
7032 (if org-agenda-use-time-grid " Grid" "")
7033 (if org-agenda-show-log " Log" "")))
7034 (force-mode-line-update))
7035
7036 (defun org-agenda-post-command-hook ()
7037 (and (eolp) (not (bolp)) (backward-char 1))
7038 (if (and org-agenda-follow-mode
7039 (get-text-property (point) 'org-marker))
7040 (org-agenda-show)))
7041
7042 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
7043
7044 (defun org-get-entries-from-diary (date)
7045 "Get the (Emacs Calendar) diary entries for DATE."
7046 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
7047 (diary-display-hook '(fancy-diary-display))
7048 (list-diary-entries-hook
7049 (cons 'org-diary-default-entry list-diary-entries-hook))
7050 (diary-file-name-prefix-function nil) ; turn this feature off
7051 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
7052 entries
7053 (org-disable-agenda-to-diary t))
7054 (save-excursion
7055 (save-window-excursion
7056 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
7057 (if (not (get-buffer fancy-diary-buffer))
7058 (setq entries nil)
7059 (with-current-buffer fancy-diary-buffer
7060 (setq buffer-read-only nil)
7061 (if (= (point-max) 1)
7062 ;; No entries
7063 (setq entries nil)
7064 ;; Omit the date and other unnecessary stuff
7065 (org-agenda-cleanup-fancy-diary)
7066 ;; Add prefix to each line and extend the text properties
7067 (if (= (point-max) 1)
7068 (setq entries nil)
7069 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
7070 (set-buffer-modified-p nil)
7071 (kill-buffer fancy-diary-buffer)))
7072 (when entries
7073 (setq entries (org-split-string entries "\n"))
7074 (setq entries
7075 (mapcar
7076 (lambda (x)
7077 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
7078 ;; Extend the text properties to the beginning of the line
7079 (org-add-props x (text-properties-at (1- (length x)) x)))
7080 entries)))))
7081
7082 (defun org-agenda-cleanup-fancy-diary ()
7083 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
7084 This gets rid of the date, the underline under the date, and
7085 the dummy entry installed by `org-mode' to ensure non-empty diary for each
7086 date. It also removes lines that contain only whitespace."
7087 (goto-char (point-min))
7088 (if (looking-at ".*?:[ \t]*")
7089 (progn
7090 (replace-match "")
7091 (re-search-forward "\n=+$" nil t)
7092 (replace-match "")
7093 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
7094 (re-search-forward "\n=+$" nil t)
7095 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
7096 (goto-char (point-min))
7097 (while (re-search-forward "^ +\n" nil t)
7098 (replace-match ""))
7099 (goto-char (point-min))
7100 (if (re-search-forward "^Org-mode dummy\n?" nil t)
7101 (replace-match "")))
7102
7103 ;; Make sure entries from the diary have the right text properties.
7104 (eval-after-load "diary-lib"
7105 '(if (boundp 'diary-modify-entry-list-string-function)
7106 ;; We can rely on the hook, nothing to do
7107 nil
7108 ;; Hook not avaiable, must use advice to make this work
7109 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
7110 "Make the position visible."
7111 (if (and org-disable-agenda-to-diary ;; called from org-agenda
7112 (stringp string)
7113 buffer-file-name)
7114 (setq string (org-modify-diary-entry-string string))))))
7115
7116 (defun org-modify-diary-entry-string (string)
7117 "Add text properties to string, allowing org-mode to act on it."
7118 (org-add-props string nil
7119 'mouse-face 'highlight
7120 'keymap org-agenda-keymap
7121 'help-echo (format "mouse-2 or RET jump to diary file %s"
7122 (abbreviate-file-name buffer-file-name))
7123 'org-agenda-diary-link t
7124 'org-marker (org-agenda-new-marker (point-at-bol))))
7125
7126 (defun org-diary-default-entry ()
7127 "Add a dummy entry to the diary.
7128 Needed to avoid empty dates which mess up holiday display."
7129 ;; Catch the error if dealing with the new add-to-diary-alist
7130 (when org-disable-agenda-to-diary
7131 (condition-case nil
7132 (add-to-diary-list original-date "Org-mode dummy" "")
7133 (error
7134 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
7135
7136 (defun org-cycle-agenda-files ()
7137 "Cycle through the files in `org-agenda-files'.
7138 If the current buffer visits an agenda file, find the next one in the list.
7139 If the current buffer does not, find the first agenda file."
7140 (interactive)
7141 (let* ((fs (org-agenda-files t))
7142 (files (append fs (list (car fs))))
7143 (tcf (if buffer-file-name (file-truename buffer-file-name)))
7144 file)
7145 (unless files (error "No agenda files"))
7146 (catch 'exit
7147 (while (setq file (pop files))
7148 (if (equal (file-truename file) tcf)
7149 (when (car files)
7150 (find-file (car files))
7151 (throw 'exit t))))
7152 (find-file (car fs)))))
7153
7154 (defun org-agenda-file-to-end ()
7155 "Move/add the current file to the end of the agenda file list.
7156 If the file is not present in the list, it is appended to the list. If it is
7157 present, it is moved there."
7158 (interactive)
7159 (org-agenda-file-to-front 'to-end))
7160
7161 (defun org-agenda-file-to-front (&optional to-end)
7162 "Move/add the current file to the top of the agenda file list.
7163 If the file is not present in the list, it is added to the front. If it is
7164 present, it is moved there. With optional argument TO-END, add/move to the
7165 end of the list."
7166 (interactive "P")
7167 (let ((file-alist (mapcar (lambda (x)
7168 (cons (file-truename x) x))
7169 (org-agenda-files t)))
7170 (ctf (file-truename buffer-file-name))
7171 x had)
7172 (setq x (assoc ctf file-alist) had x)
7173
7174 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
7175 (if to-end
7176 (setq file-alist (append (delq x file-alist) (list x)))
7177 (setq file-alist (cons x (delq x file-alist))))
7178 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
7179 (org-install-agenda-files-menu)
7180 (message "File %s to %s of agenda file list"
7181 (if had "moved" "added") (if to-end "end" "front"))))
7182
7183 (defun org-remove-file (&optional file)
7184 "Remove current file from the list of files in variable `org-agenda-files'.
7185 These are the files which are being checked for agenda entries.
7186 Optional argument FILE means, use this file instead of the current."
7187 (interactive)
7188 (let* ((file (or file buffer-file-name))
7189 (true-file (file-truename file))
7190 (afile (abbreviate-file-name file))
7191 (files (delq nil (mapcar
7192 (lambda (x)
7193 (if (equal true-file
7194 (file-truename x))
7195 nil x))
7196 (org-agenda-files t)))))
7197 (if (not (= (length files) (length (org-agenda-files t))))
7198 (progn
7199 (org-store-new-agenda-file-list files)
7200 (org-install-agenda-files-menu)
7201 (message "Removed file: %s" afile))
7202 (message "File was not in list: %s" afile))))
7203
7204 (defun org-file-menu-entry (file)
7205 (vector file (list 'find-file file) t))
7206
7207 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
7208 "Return a list of all relevant day numbers from BEG to END buffer positions.
7209 If NO-RANGES is non-nil, include only the start and end dates of a range,
7210 not every single day in the range. If FORCE-TODAY is non-nil, make
7211 sure that TODAY is included in the list. If INACTIVE is non-nil, also
7212 inactive time stamps (those in square brackets) are included.
7213 When EMPTY is non-nil, also include days without any entries."
7214 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
7215 dates dates1 date day day1 day2 ts1 ts2)
7216 (if force-today
7217 (setq dates (list (time-to-days (current-time)))))
7218 (save-excursion
7219 (goto-char beg)
7220 (while (re-search-forward re end t)
7221 (setq day (time-to-days (org-time-string-to-time
7222 (substring (match-string 1) 0 10))))
7223 (or (memq day dates) (push day dates)))
7224 (unless no-ranges
7225 (goto-char beg)
7226 (while (re-search-forward org-tr-regexp end t)
7227 (setq ts1 (substring (match-string 1) 0 10)
7228 ts2 (substring (match-string 2) 0 10)
7229 day1 (time-to-days (org-time-string-to-time ts1))
7230 day2 (time-to-days (org-time-string-to-time ts2)))
7231 (while (< (setq day1 (1+ day1)) day2)
7232 (or (memq day1 dates) (push day1 dates)))))
7233 (setq dates (sort dates '<))
7234 (when empty
7235 (while (setq day (pop dates))
7236 (setq day2 (car dates))
7237 (push day dates1)
7238 (when (and day2 empty)
7239 (if (or (eq empty t)
7240 (and (numberp empty) (<= (- day2 day) empty)))
7241 (while (< (setq day (1+ day)) day2)
7242 (push (list day) dates1))
7243 (push (cons :omitted (- day2 day)) dates1))))
7244 (setq dates (nreverse dates1)))
7245 dates)))
7246
7247 ;;;###autoload
7248 (defun org-diary (&rest args)
7249 "Return diary information from org-files.
7250 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
7251 It accesses org files and extracts information from those files to be
7252 listed in the diary. The function accepts arguments specifying what
7253 items should be listed. The following arguments are allowed:
7254
7255 :timestamp List the headlines of items containing a date stamp or
7256 date range matching the selected date. Deadlines will
7257 also be listed, on the expiration day.
7258
7259 :deadline List any deadlines past due, or due within
7260 `org-deadline-warning-days'. The listing occurs only
7261 in the diary for *today*, not at any other date. If
7262 an entry is marked DONE, it is no longer listed.
7263
7264 :scheduled List all items which are scheduled for the given date.
7265 The diary for *today* also contains items which were
7266 scheduled earlier and are not yet marked DONE.
7267
7268 :todo List all TODO items from the org-file. This may be a
7269 long list - so this is not turned on by default.
7270 Like deadlines, these entries only show up in the
7271 diary for *today*, not at any other date.
7272
7273 The call in the diary file should look like this:
7274
7275 &%%(org-diary) ~/path/to/some/orgfile.org
7276
7277 Use a separate line for each org file to check. Or, if you omit the file name,
7278 all files listed in `org-agenda-files' will be checked automatically:
7279
7280 &%%(org-diary)
7281
7282 If you don't give any arguments (as in the example above), the default
7283 arguments (:deadline :scheduled :timestamp) are used. So the example above may
7284 also be written as
7285
7286 &%%(org-diary :deadline :timestamp :scheduled)
7287
7288 The function expects the lisp variables `entry' and `date' to be provided
7289 by the caller, because this is how the calendar works. Don't use this
7290 function from a program - use `org-agenda-get-day-entries' instead."
7291 (org-agenda-maybe-reset-markers)
7292 (org-compile-prefix-format org-agenda-prefix-format)
7293 (setq args (or args '(:deadline :scheduled :timestamp)))
7294 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
7295 (list entry)
7296 (org-agenda-files t)))
7297 file rtn results)
7298 ;; If this is called during org-agenda, don't return any entries to
7299 ;; the calendar. Org Agenda will list these entries itself.
7300 (if org-disable-agenda-to-diary (setq files nil))
7301 (while (setq file (pop files))
7302 (setq rtn (apply 'org-agenda-get-day-entries file date args))
7303 (setq results (append results rtn)))
7304 (if results
7305 (concat (org-finalize-agenda-entries results) "\n"))))
7306 (defvar org-category-table nil)
7307 (defun org-get-category-table ()
7308 "Get the table of categories and positions in current buffer."
7309 (let (tbl)
7310 (save-excursion
7311 (goto-char (point-min))
7312 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
7313 (push (cons (point) (org-trim (match-string 2))) tbl)))
7314 tbl))
7315 (defun org-get-category (&optional pos)
7316 "Get the category applying to position POS."
7317 (if (not org-category-table)
7318 (cond
7319 ((null org-category)
7320 (setq org-category
7321 (if buffer-file-name
7322 (file-name-sans-extension
7323 (file-name-nondirectory buffer-file-name))
7324 "???")))
7325 ((symbolp org-category) (symbol-name org-category))
7326 (t org-category))
7327 (let ((tbl org-category-table)
7328 (pos (or pos (point))))
7329 (while (and tbl (> (caar tbl) pos))
7330 (pop tbl))
7331 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
7332 org-category-table))))))
7333
7334 (defun org-agenda-get-day-entries (file date &rest args)
7335 "Does the work for `org-diary' and `org-agenda'.
7336 FILE is the path to a file to be checked for entries. DATE is date like
7337 the one returned by `calendar-current-date'. ARGS are symbols indicating
7338 which kind of entries should be extracted. For details about these, see
7339 the documentation of `org-diary'."
7340 (setq args (or args '(:deadline :scheduled :timestamp)))
7341 (let* ((org-startup-with-deadline-check nil)
7342 (org-startup-folded nil)
7343 (org-startup-align-all-tables nil)
7344 (buffer (if (file-exists-p file)
7345 (org-get-agenda-file-buffer file)
7346 (error "No such file %s" file)))
7347 arg results rtn)
7348 (if (not buffer)
7349 ;; If file does not exist, make sure an error message ends up in diary
7350 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7351 (with-current-buffer buffer
7352 (unless (org-mode-p)
7353 (error "Agenda file %s is not in `org-mode'" file))
7354 (setq org-category-table (org-get-category-table))
7355 (let ((case-fold-search nil))
7356 (save-excursion
7357 (save-restriction
7358 (if org-respect-restriction
7359 (if (org-region-active-p)
7360 ;; Respect a region to restrict search
7361 (narrow-to-region (region-beginning) (region-end)))
7362 ;; If we work for the calendar or many files,
7363 ;; get rid of any restriction
7364 (widen))
7365 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
7366 (while (setq arg (pop args))
7367 (cond
7368 ((and (eq arg :todo)
7369 (equal date (calendar-current-date)))
7370 (setq rtn (org-agenda-get-todos))
7371 (setq results (append results rtn)))
7372 ((eq arg :timestamp)
7373 (setq rtn (org-agenda-get-blocks))
7374 (setq results (append results rtn))
7375 (setq rtn (org-agenda-get-timestamps))
7376 (setq results (append results rtn)))
7377 ((eq arg :scheduled)
7378 (setq rtn (org-agenda-get-scheduled))
7379 (setq results (append results rtn)))
7380 ((eq arg :closed)
7381 (setq rtn (org-agenda-get-closed))
7382 (setq results (append results rtn)))
7383 ((and (eq arg :deadline)
7384 (equal date (calendar-current-date)))
7385 (setq rtn (org-agenda-get-deadlines))
7386 (setq results (append results rtn))))))))
7387 results))))
7388
7389 (defun org-entry-is-done-p ()
7390 "Is the current entry marked DONE?"
7391 (save-excursion
7392 (and (re-search-backward "[\r\n]\\*" nil t)
7393 (looking-at org-nl-done-regexp))))
7394
7395 (defun org-at-date-range-p ()
7396 "Is the cursor inside a date range?"
7397 (interactive)
7398 (save-excursion
7399 (catch 'exit
7400 (let ((pos (point)))
7401 (skip-chars-backward "^<\r\n")
7402 (skip-chars-backward "<")
7403 (and (looking-at org-tr-regexp)
7404 (>= (match-end 0) pos)
7405 (throw 'exit t))
7406 (skip-chars-backward "^<\r\n")
7407 (skip-chars-backward "<")
7408 (and (looking-at org-tr-regexp)
7409 (>= (match-end 0) pos)
7410 (throw 'exit t)))
7411 nil)))
7412
7413 (defun org-agenda-get-todos ()
7414 "Return the TODO information for agenda display."
7415 (let* ((props (list 'face nil
7416 'done-face 'org-done
7417 'org-not-done-regexp org-not-done-regexp
7418 'mouse-face 'highlight
7419 'keymap org-agenda-keymap
7420 'help-echo
7421 (format "mouse-2 or RET jump to org file %s"
7422 (abbreviate-file-name buffer-file-name))))
7423 (regexp (concat "[\n\r]\\*+ *\\("
7424 (if org-select-this-todo-keyword
7425 (concat "\\<\\(" org-select-this-todo-keyword
7426 "\\)\\>")
7427 org-not-done-regexp)
7428 "[^\n\r]*\\)"))
7429 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
7430 marker priority category tags
7431 ee txt)
7432 (goto-char (point-min))
7433 (while (re-search-forward regexp nil t)
7434 (catch :skip
7435 (and org-agenda-todo-ignore-scheduled
7436 (looking-at sched-re)
7437 (throw :skip nil))
7438 (org-agenda-skip)
7439 (goto-char (match-beginning 1))
7440 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
7441 category (org-get-category)
7442 tags (org-get-tags-at (point))
7443 txt (org-format-agenda-item "" (match-string 1) category tags)
7444 priority
7445 (+ (org-get-priority txt)
7446 (if org-todo-kwd-priority-p
7447 (- org-todo-kwd-max-priority -2
7448 (length
7449 (member (match-string 2) org-todo-keywords)))
7450 1)))
7451 (org-add-props txt props
7452 'org-marker marker 'org-hd-marker marker
7453 'priority priority 'category category)
7454 (push txt ee)
7455 (if org-agenda-todo-list-sublevels
7456 (goto-char (match-end 1))
7457 (org-end-of-subtree 'invisible))))
7458 (nreverse ee)))
7459
7460 (defconst org-agenda-no-heading-message
7461 "No heading for this item in buffer or region.")
7462
7463 (defun org-agenda-get-timestamps ()
7464 "Return the date stamp information for agenda display."
7465 (let* ((props (list 'face nil
7466 'org-not-done-regexp org-not-done-regexp
7467 'mouse-face 'highlight
7468 'keymap org-agenda-keymap
7469 'help-echo
7470 (format "mouse-2 or RET jump to org file %s"
7471 (abbreviate-file-name buffer-file-name))))
7472 (regexp (regexp-quote
7473 (substring
7474 (format-time-string
7475 (car org-time-stamp-formats)
7476 (apply 'encode-time ; DATE bound by calendar
7477 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7478 0 11)))
7479 marker hdmarker deadlinep scheduledp donep tmp priority category
7480 ee txt timestr tags)
7481 (goto-char (point-min))
7482 (while (re-search-forward regexp nil t)
7483 (catch :skip
7484 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
7485 (org-agenda-skip)
7486 (setq marker (org-agenda-new-marker (match-beginning 0))
7487 category (org-get-category (match-beginning 0))
7488 tmp (buffer-substring (max (point-min)
7489 (- (match-beginning 0)
7490 org-ds-keyword-length))
7491 (match-beginning 0))
7492 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7493 deadlinep (string-match org-deadline-regexp tmp)
7494 scheduledp (string-match org-scheduled-regexp tmp)
7495 donep (org-entry-is-done-p))
7496 (if (string-match ">" timestr)
7497 ;; substring should only run to end of time stamp
7498 (setq timestr (substring timestr 0 (match-end 0))))
7499 (save-excursion
7500 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7501 (progn
7502 (goto-char (match-end 1))
7503 (setq hdmarker (org-agenda-new-marker)
7504 tags (org-get-tags-at))
7505 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7506 (setq txt (org-format-agenda-item
7507 (format "%s%s"
7508 (if deadlinep "Deadline: " "")
7509 (if scheduledp "Scheduled: " ""))
7510 (match-string 1) category tags timestr)))
7511 (setq txt org-agenda-no-heading-message))
7512 (setq priority (org-get-priority txt))
7513 (org-add-props txt props
7514 'org-marker marker 'org-hd-marker hdmarker)
7515 (if deadlinep
7516 (org-add-props txt nil
7517 'face (if donep 'org-done 'org-warning)
7518 'undone-face 'org-warning 'done-face 'org-done
7519 'category category 'priority (+ 100 priority))
7520 (if scheduledp
7521 (org-add-props txt nil
7522 'face 'org-scheduled-today
7523 'undone-face 'org-scheduled-today 'done-face 'org-done
7524 'category category 'priority (+ 99 priority))
7525 (org-add-props txt nil 'priority priority 'category category)))
7526 (push txt ee))
7527 (outline-next-heading)))
7528 (nreverse ee)))
7529
7530 (defun org-agenda-get-closed ()
7531 "Return the logged TODO entries for agenda display."
7532 (let* ((props (list 'mouse-face 'highlight
7533 'org-not-done-regexp org-not-done-regexp
7534 'keymap org-agenda-keymap
7535 'help-echo
7536 (format "mouse-2 or RET jump to org file %s"
7537 (abbreviate-file-name buffer-file-name))))
7538 (regexp (concat
7539 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
7540 (regexp-quote
7541 (substring
7542 (format-time-string
7543 (car org-time-stamp-formats)
7544 (apply 'encode-time ; DATE bound by calendar
7545 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7546 1 11))))
7547 marker hdmarker priority category tags closedp
7548 ee txt timestr)
7549 (goto-char (point-min))
7550 (while (re-search-forward regexp nil t)
7551 (catch :skip
7552 (org-agenda-skip)
7553 (setq marker (org-agenda-new-marker (match-beginning 0))
7554 closedp (equal (match-string 1) org-closed-string)
7555 category (org-get-category (match-beginning 0))
7556 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7557 ;; donep (org-entry-is-done-p)
7558 )
7559 (if (string-match "\\]" timestr)
7560 ;; substring should only run to end of time stamp
7561 (setq timestr (substring timestr 0 (match-end 0))))
7562 (save-excursion
7563 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7564 (progn
7565 (goto-char (match-end 1))
7566 (setq hdmarker (org-agenda-new-marker)
7567 tags (org-get-tags-at))
7568 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7569 (setq txt (org-format-agenda-item
7570 (if closedp "Closed: " "Clocked: ")
7571 (match-string 1) category tags timestr)))
7572 (setq txt org-agenda-no-heading-message))
7573 (setq priority 100000)
7574 (org-add-props txt props
7575 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
7576 'priority priority 'category category
7577 'undone-face 'org-warning 'done-face 'org-done)
7578 (push txt ee))
7579 (outline-next-heading)))
7580 (nreverse ee)))
7581
7582 (defun org-agenda-get-deadlines ()
7583 "Return the deadline information for agenda display."
7584 (let* ((wdays org-deadline-warning-days)
7585 (props (list 'mouse-face 'highlight
7586 'org-not-done-regexp org-not-done-regexp
7587 'keymap org-agenda-keymap
7588 'help-echo
7589 (format "mouse-2 or RET jump to org file %s"
7590 (abbreviate-file-name buffer-file-name))))
7591 (regexp org-deadline-time-regexp)
7592 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7593 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7594 d2 diff pos pos1 category tags
7595 ee txt head face)
7596 (goto-char (point-min))
7597 (while (re-search-forward regexp nil t)
7598 (catch :skip
7599 (org-agenda-skip)
7600 (setq pos (1- (match-beginning 1))
7601 d2 (time-to-days
7602 (org-time-string-to-time (match-string 1)))
7603 diff (- d2 d1))
7604 ;; When to show a deadline in the calendar:
7605 ;; If the expiration is within wdays warning time.
7606 ;; Past-due deadlines are only shown on the current date
7607 (if (and (< diff wdays) todayp (not (= diff 0)))
7608 (save-excursion
7609 (setq category (org-get-category))
7610 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7611 (progn
7612 (goto-char (match-end 0))
7613 (setq pos1 (match-end 1))
7614 (setq tags (org-get-tags-at pos1))
7615 (setq head (buffer-substring-no-properties
7616 (point)
7617 (progn (skip-chars-forward "^\r\n")
7618 (point))))
7619 (if (string-match org-looking-at-done-regexp head)
7620 (setq txt nil)
7621 (setq txt (org-format-agenda-item
7622 (format "In %3d d.: " diff) head category tags))))
7623 (setq txt org-agenda-no-heading-message))
7624 (when txt
7625 (setq face (cond ((<= diff 0) 'org-warning)
7626 ((<= diff 5) 'org-upcoming-deadline)
7627 (t nil)))
7628 (org-add-props txt props
7629 'org-marker (org-agenda-new-marker pos)
7630 'org-hd-marker (org-agenda-new-marker pos1)
7631 'priority (+ (- 10 diff) (org-get-priority txt))
7632 'category category
7633 'face face 'undone-face face 'done-face 'org-done)
7634 (push txt ee))))))
7635 ee))
7636
7637 (defun org-agenda-get-scheduled ()
7638 "Return the scheduled information for agenda display."
7639 (let* ((props (list 'face 'org-scheduled-previously
7640 'org-not-done-regexp org-not-done-regexp
7641 'undone-face 'org-scheduled-previously
7642 'done-face 'org-done
7643 'mouse-face 'highlight
7644 'keymap org-agenda-keymap
7645 'help-echo
7646 (format "mouse-2 or RET jump to org file %s"
7647 (abbreviate-file-name buffer-file-name))))
7648 (regexp org-scheduled-time-regexp)
7649 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7650 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7651 d2 diff pos pos1 category tags
7652 ee txt head)
7653 (goto-char (point-min))
7654 (while (re-search-forward regexp nil t)
7655 (catch :skip
7656 (org-agenda-skip)
7657 (setq pos (1- (match-beginning 1))
7658 d2 (time-to-days
7659 (org-time-string-to-time (match-string 1)))
7660 diff (- d2 d1))
7661 ;; When to show a scheduled item in the calendar:
7662 ;; If it is on or past the date.
7663 (if (and (< diff 0) todayp)
7664 (save-excursion
7665 (setq category (org-get-category))
7666 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7667 (progn
7668 (goto-char (match-end 0))
7669 (setq pos1 (match-end 1))
7670 (setq tags (org-get-tags-at))
7671 (setq head (buffer-substring-no-properties
7672 (point)
7673 (progn (skip-chars-forward "^\r\n") (point))))
7674 (if (string-match org-looking-at-done-regexp head)
7675 (setq txt nil)
7676 (setq txt (org-format-agenda-item
7677 (format "Sched.%2dx: " (- 1 diff)) head
7678 category tags))))
7679 (setq txt org-agenda-no-heading-message))
7680 (when txt
7681 (org-add-props txt props
7682 'org-marker (org-agenda-new-marker pos)
7683 'org-hd-marker (org-agenda-new-marker pos1)
7684 'priority (+ (- 5 diff) (org-get-priority txt))
7685 'category category)
7686 (push txt ee))))))
7687 ee))
7688
7689 (defun org-agenda-get-blocks ()
7690 "Return the date-range information for agenda display."
7691 (let* ((props (list 'face nil
7692 'org-not-done-regexp org-not-done-regexp
7693 'mouse-face 'highlight
7694 'keymap org-agenda-keymap
7695 'help-echo
7696 (format "mouse-2 or RET jump to org file %s"
7697 (abbreviate-file-name buffer-file-name))))
7698 (regexp org-tr-regexp)
7699 (d0 (calendar-absolute-from-gregorian date))
7700 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
7701 (goto-char (point-min))
7702 (while (re-search-forward regexp nil t)
7703 (catch :skip
7704 (org-agenda-skip)
7705 (setq timestr (match-string 0)
7706 s1 (match-string 1)
7707 s2 (match-string 2)
7708 d1 (time-to-days (org-time-string-to-time s1))
7709 d2 (time-to-days (org-time-string-to-time s2)))
7710 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
7711 ;; Only allow days between the limits, because the normal
7712 ;; date stamps will catch the limits.
7713 (save-excursion
7714 (setq marker (org-agenda-new-marker (point)))
7715 (setq category (org-get-category))
7716 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7717 (progn
7718 (setq hdmarker (org-agenda-new-marker (match-end 1)))
7719 (goto-char (match-end 1))
7720 (setq tags (org-get-tags-at))
7721 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7722 (setq txt (org-format-agenda-item
7723 (format (if (= d1 d2) "" "(%d/%d): ")
7724 (1+ (- d0 d1)) (1+ (- d2 d1)))
7725 (match-string 1) category tags
7726 (if (= d0 d1) timestr))))
7727 (setq txt org-agenda-no-heading-message))
7728 (org-add-props txt props
7729 'org-marker marker 'org-hd-marker hdmarker
7730 'priority (org-get-priority txt) 'category category)
7731 (push txt ee)))
7732 (outline-next-heading)))
7733 ;; Sort the entries by expiration date.
7734 (nreverse ee)))
7735
7736 (defconst org-plain-time-of-day-regexp
7737 (concat
7738 "\\(\\<[012]?[0-9]"
7739 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7740 "\\(--?"
7741 "\\(\\<[012]?[0-9]"
7742 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7743 "\\)?")
7744 "Regular expression to match a plain time or time range.
7745 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
7746 groups carry important information:
7747 0 the full match
7748 1 the first time, range or not
7749 8 the second time, if it is a range.")
7750
7751 (defconst org-stamp-time-of-day-regexp
7752 (concat
7753 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
7754 "\\([012][0-9]:[0-5][0-9]\\)>"
7755 "\\(--?"
7756 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
7757 "Regular expression to match a timestamp time or time range.
7758 After a match, the following groups carry important information:
7759 0 the full match
7760 1 date plus weekday, for backreferencing to make sure both times on same day
7761 2 the first time, range or not
7762 4 the second time, if it is a range.")
7763
7764 (defvar org-prefix-has-time nil
7765 "A flag, set by `org-compile-prefix-format'.
7766 The flag is set if the currently compiled format contains a `%t'.")
7767 (defvar org-prefix-has-tag nil
7768 "A flag, set by `org-compile-prefix-format'.
7769 The flag is set if the currently compiled format contains a `%T'.")
7770
7771 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
7772 "Format TXT to be inserted into the agenda buffer.
7773 In particular, it adds the prefix and corresponding text properties. EXTRA
7774 must be a string and replaces the `%s' specifier in the prefix format.
7775 CATEGORY (string, symbol or nil) may be used to overrule the default
7776 category taken from local variable or file name. It will replace the `%c'
7777 specifier in the format. DOTIME, when non-nil, indicates that a
7778 time-of-day should be extracted from TXT for sorting of this entry, and for
7779 the `%t' specifier in the format. When DOTIME is a string, this string is
7780 searched for a time before TXT is. NOPREFIX is a flag and indicates that
7781 only the correctly processes TXT should be returned - this is used by
7782 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
7783 (save-match-data
7784 ;; Diary entries sometimes have extra whitespace at the beginning
7785 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
7786 (let* ((category (or category
7787 org-category
7788 (if buffer-file-name
7789 (file-name-sans-extension
7790 (file-name-nondirectory buffer-file-name))
7791 "")))
7792 (tag (if tags (nth (1- (length tags)) tags) ""))
7793 time ;; needed for the eval of the prefix format
7794 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
7795 (time-of-day (and dotime (org-get-time-of-day ts)))
7796 stamp plain s0 s1 s2 rtn)
7797 (when (and dotime time-of-day org-prefix-has-time)
7798 ;; Extract starting and ending time and move them to prefix
7799 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
7800 (setq plain (string-match org-plain-time-of-day-regexp ts)))
7801 (setq s0 (match-string 0 ts)
7802 s1 (match-string (if plain 1 2) ts)
7803 s2 (match-string (if plain 8 4) ts))
7804
7805 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
7806 ;; them, we might want to remove them there to avoid duplication.
7807 ;; The user can turn this off with a variable.
7808 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
7809 (string-match (concat (regexp-quote s0) " *") txt)
7810 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
7811 (= (match-beginning 0) 0)
7812 t))
7813 (setq txt (replace-match "" nil nil txt))))
7814 ;; Normalize the time(s) to 24 hour
7815 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
7816 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
7817
7818 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
7819 ;; Tags are in the string
7820 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
7821 (and org-agenda-remove-tags-when-in-prefix
7822 org-prefix-has-tag))
7823 (setq txt (replace-match "" t t txt))
7824 (setq txt (replace-match
7825 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
7826 (match-string 2 txt))
7827 t t txt))))
7828
7829 ;; Create the final string
7830 (if noprefix
7831 (setq rtn txt)
7832 ;; Prepare the variables needed in the eval of the compiled format
7833 (setq time (cond (s2 (concat s1 "-" s2))
7834 (s1 (concat s1 "......"))
7835 (t ""))
7836 extra (or extra "")
7837 category (if (symbolp category) (symbol-name category) category))
7838 ;; Evaluate the compiled format
7839 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
7840
7841 ;; And finally add the text properties
7842 (org-add-props rtn nil
7843 'category (downcase category) 'tags tags
7844 'prefix-length (- (length rtn) (length txt))
7845 'time-of-day time-of-day
7846 'dotime dotime))))
7847
7848 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
7849 (catch 'exit
7850 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
7851 ((and todayp (member 'today (car org-agenda-time-grid))))
7852 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
7853 ((member 'weekly (car org-agenda-time-grid)))
7854 (t (throw 'exit list)))
7855 (let* ((have (delq nil (mapcar
7856 (lambda (x) (get-text-property 1 'time-of-day x))
7857 list)))
7858 (string (nth 1 org-agenda-time-grid))
7859 (gridtimes (nth 2 org-agenda-time-grid))
7860 (req (car org-agenda-time-grid))
7861 (remove (member 'remove-match req))
7862 new time)
7863 (if (and (member 'require-timed req) (not have))
7864 ;; don't show empty grid
7865 (throw 'exit list))
7866 (while (setq time (pop gridtimes))
7867 (unless (and remove (member time have))
7868 (setq time (int-to-string time))
7869 (push (org-format-agenda-item
7870 nil string "" nil
7871 (concat (substring time 0 -2) ":" (substring time -2)))
7872 new)
7873 (put-text-property
7874 1 (length (car new)) 'face 'org-time-grid (car new))))
7875 (if (member 'time-up org-agenda-sorting-strategy)
7876 (append new list)
7877 (append list new)))))
7878
7879 (defun org-compile-prefix-format (format)
7880 "Compile the prefix format into a Lisp form that can be evaluated.
7881 The resulting form is returned and stored in the variable
7882 `org-prefix-format-compiled'."
7883 (setq org-prefix-has-time nil org-prefix-has-tag nil)
7884 (let ((start 0) varform vars var (s format)e c f opt)
7885 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
7886 s start)
7887 (setq var (cdr (assoc (match-string 4 s)
7888 '(("c" . category) ("t" . time) ("s" . extra)
7889 ("T" . tag))))
7890 c (or (match-string 3 s) "")
7891 opt (match-beginning 1)
7892 start (1+ (match-beginning 0)))
7893 (if (equal var 'time) (setq org-prefix-has-time t))
7894 (if (equal var 'tag) (setq org-prefix-has-tag t))
7895 (setq f (concat "%" (match-string 2 s) "s"))
7896 (if opt
7897 (setq varform
7898 `(if (equal "" ,var)
7899 ""
7900 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
7901 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
7902 (setq s (replace-match "%s" t nil s))
7903 (push varform vars))
7904 (setq vars (nreverse vars))
7905 (setq org-prefix-format-compiled `(format ,s ,@vars))))
7906
7907 (defun org-get-time-of-day (s &optional string mod24)
7908 "Check string S for a time of day.
7909 If found, return it as a military time number between 0 and 2400.
7910 If not found, return nil.
7911 The optional STRING argument forces conversion into a 5 character wide string
7912 HH:MM."
7913 (save-match-data
7914 (when
7915 (or
7916 (string-match
7917 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
7918 (string-match
7919 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
7920 (let* ((h (string-to-number (match-string 1 s)))
7921 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
7922 (ampm (if (match-end 4) (downcase (match-string 4 s))))
7923 (am-p (equal ampm "am"))
7924 (h1 (cond ((not ampm) h)
7925 ((= h 12) (if am-p 0 12))
7926 (t (+ h (if am-p 0 12)))))
7927 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
7928 (mod h1 24) h1))
7929 (t0 (+ (* 100 h2) m))
7930 (t1 (concat (if (>= h1 24) "+" " ")
7931 (if (< t0 100) "0" "")
7932 (if (< t0 10) "0" "")
7933 (int-to-string t0))))
7934 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
7935
7936 (defun org-finalize-agenda-entries (list)
7937 "Sort and concatenate the agenda items."
7938 (setq list (mapcar 'org-agenda-highlight-todo list))
7939 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
7940
7941 (defun org-agenda-highlight-todo (x)
7942 (let (re pl)
7943 (if (eq x 'line)
7944 (save-excursion
7945 (beginning-of-line 1)
7946 (setq re (get-text-property (point) 'org-not-done-regexp))
7947 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
7948 (and (looking-at (concat "[ \t]*" re))
7949 (add-text-properties (match-beginning 0) (match-end 0)
7950 '(face org-todo))))
7951 (setq re (get-text-property 0 'org-not-done-regexp x)
7952 pl (get-text-property 0 'prefix-length x))
7953 (and re (equal (string-match re x pl) pl)
7954 (add-text-properties (match-beginning 0) (match-end 0)
7955 '(face org-todo) x))
7956 x)))
7957
7958 (defsubst org-cmp-priority (a b)
7959 "Compare the priorities of string A and B."
7960 (let ((pa (or (get-text-property 1 'priority a) 0))
7961 (pb (or (get-text-property 1 'priority b) 0)))
7962 (cond ((> pa pb) +1)
7963 ((< pa pb) -1)
7964 (t nil))))
7965
7966 (defsubst org-cmp-category (a b)
7967 "Compare the string values of categories of strings A and B."
7968 (let ((ca (or (get-text-property 1 'category a) ""))
7969 (cb (or (get-text-property 1 'category b) "")))
7970 (cond ((string-lessp ca cb) -1)
7971 ((string-lessp cb ca) +1)
7972 (t nil))))
7973
7974 (defsubst org-cmp-time (a b)
7975 "Compare the time-of-day values of strings A and B."
7976 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
7977 (ta (or (get-text-property 1 'time-of-day a) def))
7978 (tb (or (get-text-property 1 'time-of-day b) def)))
7979 (cond ((< ta tb) -1)
7980 ((< tb ta) +1)
7981 (t nil))))
7982
7983 (defun org-entries-lessp (a b)
7984 "Predicate for sorting agenda entries."
7985 ;; The following variables will be used when the form is evaluated.
7986 (let* ((time-up (org-cmp-time a b))
7987 (time-down (if time-up (- time-up) nil))
7988 (priority-up (org-cmp-priority a b))
7989 (priority-down (if priority-up (- priority-up) nil))
7990 (category-up (org-cmp-category a b))
7991 (category-down (if category-up (- category-up) nil))
7992 (category-keep (if category-up +1 nil)))
7993 (cdr (assoc
7994 (eval (cons 'or org-agenda-sorting-strategy))
7995 '((-1 . t) (1 . nil) (nil . nil))))))
7996
7997 (defun org-agenda-show-priority ()
7998 "Show the priority of the current item.
7999 This priority is composed of the main priority given with the [#A] cookies,
8000 and by additional input from the age of a schedules or deadline entry."
8001 (interactive)
8002 (let* ((pri (get-text-property (point-at-bol) 'priority)))
8003 (message "Priority is %d" (if pri pri -1000))))
8004
8005 (defun org-agenda-show-tags ()
8006 "Show the tags applicable to the current item."
8007 (interactive)
8008 (let* ((tags (get-text-property (point-at-bol) 'tags)))
8009 (if tags
8010 (message "Tags are :%s:"
8011 (org-no-properties (mapconcat 'identity tags ":")))
8012 (message "No tags associated with this line"))))
8013
8014 (defun org-agenda-goto (&optional highlight)
8015 "Go to the Org-mode file which contains the item at point."
8016 (interactive)
8017 (let* ((marker (or (get-text-property (point) 'org-marker)
8018 (org-agenda-error)))
8019 (buffer (marker-buffer marker))
8020 (pos (marker-position marker)))
8021 (switch-to-buffer-other-window buffer)
8022 (widen)
8023 (goto-char pos)
8024 (when (org-mode-p)
8025 (org-show-hidden-entry)
8026 (save-excursion
8027 (and (outline-next-heading)
8028 (org-flag-heading nil)))) ; show the next heading
8029 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
8030
8031 (defun org-agenda-switch-to ()
8032 "Go to the Org-mode file which contains the item at point."
8033 (interactive)
8034 (let* ((marker (or (get-text-property (point) 'org-marker)
8035 (org-agenda-error)))
8036 (buffer (marker-buffer marker))
8037 (pos (marker-position marker)))
8038 (switch-to-buffer buffer)
8039 (delete-other-windows)
8040 (widen)
8041 (goto-char pos)
8042 (when (org-mode-p)
8043 (org-show-hidden-entry)
8044 (save-excursion
8045 (and (outline-next-heading)
8046 (org-flag-heading nil)))))) ; show the next heading
8047
8048 (defun org-agenda-goto-mouse (ev)
8049 "Go to the Org-mode file which contains the item at the mouse click."
8050 (interactive "e")
8051 (mouse-set-point ev)
8052 (org-agenda-goto))
8053
8054 (defun org-agenda-show ()
8055 "Display the Org-mode file which contains the item at point."
8056 (interactive)
8057 (let ((win (selected-window)))
8058 (org-agenda-goto t)
8059 (select-window win)))
8060
8061 (defun org-agenda-recenter (arg)
8062 "Display the Org-mode file which contains the item at point and recenter."
8063 (interactive "P")
8064 (let ((win (selected-window)))
8065 (org-agenda-goto t)
8066 (recenter arg)
8067 (select-window win)))
8068
8069 (defun org-agenda-show-mouse (ev)
8070 "Display the Org-mode file which contains the item at the mouse click."
8071 (interactive "e")
8072 (mouse-set-point ev)
8073 (org-agenda-show))
8074
8075 (defun org-agenda-check-no-diary ()
8076 "Check if the entry is a diary link and abort if yes."
8077 (if (get-text-property (point) 'org-agenda-diary-link)
8078 (org-agenda-error)))
8079
8080 (defun org-agenda-error ()
8081 (error "Command not allowed in this line"))
8082
8083 (defvar org-last-heading-marker (make-marker)
8084 "Marker pointing to the headline that last changed its TODO state
8085 by a remote command from the agenda.")
8086
8087 (defun org-agenda-todo (&optional arg)
8088 "Cycle TODO state of line at point, also in Org-mode file.
8089 This changes the line at point, all other lines in the agenda referring to
8090 the same tree node, and the headline of the tree node in the Org-mode file."
8091 (interactive "P")
8092 (org-agenda-check-no-diary)
8093 (let* ((col (current-column))
8094 (marker (or (get-text-property (point) 'org-marker)
8095 (org-agenda-error)))
8096 (buffer (marker-buffer marker))
8097 (pos (marker-position marker))
8098 (hdmarker (get-text-property (point) 'org-hd-marker))
8099 (buffer-read-only nil)
8100 newhead)
8101 (with-current-buffer buffer
8102 (widen)
8103 (goto-char pos)
8104 (org-show-hidden-entry)
8105 (save-excursion
8106 (and (outline-next-heading)
8107 (org-flag-heading nil))) ; show the next heading
8108 (org-todo arg)
8109 (and (bolp) (forward-char 1))
8110 (setq newhead (org-get-heading))
8111 (save-excursion
8112 (org-back-to-heading)
8113 (move-marker org-last-heading-marker (point))))
8114 (beginning-of-line 1)
8115 (save-excursion
8116 (org-agenda-change-all-lines newhead hdmarker 'fixface))
8117 (move-to-column col)))
8118
8119 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
8120 "Change all lines in the agenda buffer which match HDMARKER.
8121 The new content of the line will be NEWHEAD (as modified by
8122 `org-format-agenda-item'). HDMARKER is checked with
8123 `equal' against all `org-hd-marker' text properties in the file.
8124 If FIXFACE is non-nil, the face of each item is modified acording to
8125 the new TODO state."
8126 (let* (props m pl undone-face done-face finish new dotime cat tags)
8127 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
8128 (save-excursion
8129 (goto-char (point-max))
8130 (beginning-of-line 1)
8131 (while (not finish)
8132 (setq finish (bobp))
8133 (when (and (setq m (get-text-property (point) 'org-hd-marker))
8134 (equal m hdmarker))
8135 (setq props (text-properties-at (point))
8136 dotime (get-text-property (point) 'dotime)
8137 cat (get-text-property (point) 'category)
8138 tags (get-text-property (point) 'tags)
8139 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
8140 pl (get-text-property (point) 'prefix-length)
8141 undone-face (get-text-property (point) 'undone-face)
8142 done-face (get-text-property (point) 'done-face))
8143 (move-to-column pl)
8144 (if (looking-at ".*")
8145 (progn
8146 (replace-match new t t)
8147 (beginning-of-line 1)
8148 (add-text-properties (point-at-bol) (point-at-eol) props)
8149 (when fixface
8150 (add-text-properties
8151 (point-at-bol) (point-at-eol)
8152 (list 'face
8153 (if org-last-todo-state-is-todo
8154 undone-face done-face)))
8155 (org-agenda-highlight-todo 'line))
8156 (beginning-of-line 1))
8157 (error "Line update did not work")))
8158 (beginning-of-line 0)))))
8159
8160 (defun org-agenda-priority-up ()
8161 "Increase the priority of line at point, also in Org-mode file."
8162 (interactive)
8163 (org-agenda-priority 'up))
8164
8165 (defun org-agenda-priority-down ()
8166 "Decrease the priority of line at point, also in Org-mode file."
8167 (interactive)
8168 (org-agenda-priority 'down))
8169
8170 (defun org-agenda-priority (&optional force-direction)
8171 "Set the priority of line at point, also in Org-mode file.
8172 This changes the line at point, all other lines in the agenda referring to
8173 the same tree node, and the headline of the tree node in the Org-mode file."
8174 (interactive)
8175 (org-agenda-check-no-diary)
8176 (let* ((marker (or (get-text-property (point) 'org-marker)
8177 (org-agenda-error)))
8178 (buffer (marker-buffer marker))
8179 (pos (marker-position marker))
8180 (hdmarker (get-text-property (point) 'org-hd-marker))
8181 (buffer-read-only nil)
8182 newhead)
8183 (with-current-buffer buffer
8184 (widen)
8185 (goto-char pos)
8186 (org-show-hidden-entry)
8187 (save-excursion
8188 (and (outline-next-heading)
8189 (org-flag-heading nil))) ; show the next heading
8190 (funcall 'org-priority force-direction)
8191 (end-of-line 1)
8192 (setq newhead (org-get-heading)))
8193 (org-agenda-change-all-lines newhead hdmarker)
8194 (beginning-of-line 1)))
8195
8196 (defun org-get-tags-at (&optional pos)
8197 "Get a list of all headline tags applicable at POS.
8198 POS defaults to point. If tags are inherited, the list contains
8199 the targets in the same sequence as the headlines appear, i.e.
8200 the tags of the current headline come last."
8201 (interactive)
8202 (let (tags)
8203 (save-excursion
8204 (goto-char (or pos (point)))
8205 (save-match-data
8206 (org-back-to-heading t)
8207 (condition-case nil
8208 (while t
8209 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
8210 (setq tags (append (org-split-string
8211 (org-match-string-no-properties 1) ":")
8212 tags)))
8213 (or org-use-tag-inheritance (error ""))
8214 (org-up-heading-all 1))
8215 (error nil))))
8216 (message "%s" tags)
8217 tags))
8218
8219 (defun org-agenda-set-tags ()
8220 "Set tags for the current headline."
8221 (interactive)
8222 (org-agenda-check-no-diary)
8223 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
8224 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
8225 (org-agenda-error)))
8226 (buffer (marker-buffer hdmarker))
8227 (pos (marker-position hdmarker))
8228 (buffer-read-only nil)
8229 newhead)
8230 (with-current-buffer buffer
8231 (widen)
8232 (goto-char pos)
8233 (org-show-hidden-entry)
8234 (save-excursion
8235 (and (outline-next-heading)
8236 (org-flag-heading nil))) ; show the next heading
8237 (call-interactively 'org-set-tags)
8238 (end-of-line 1)
8239 (setq newhead (org-get-heading)))
8240 (org-agenda-change-all-lines newhead hdmarker)
8241 (beginning-of-line 1)))
8242
8243 (defun org-agenda-date-later (arg &optional what)
8244 "Change the date of this item to one day later."
8245 (interactive "p")
8246 (org-agenda-check-type t 'agenda 'timeline)
8247 (org-agenda-check-no-diary)
8248 (let* ((marker (or (get-text-property (point) 'org-marker)
8249 (org-agenda-error)))
8250 (buffer (marker-buffer marker))
8251 (pos (marker-position marker)))
8252 (with-current-buffer buffer
8253 (widen)
8254 (goto-char pos)
8255 (if (not (org-at-timestamp-p))
8256 (error "Cannot find time stamp"))
8257 (org-timestamp-change arg (or what 'day))
8258 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8259
8260 (defun org-agenda-date-earlier (arg &optional what)
8261 "Change the date of this item to one day earlier."
8262 (interactive "p")
8263 (org-agenda-date-later (- arg) what))
8264
8265 (defun org-agenda-date-prompt (arg)
8266 "Change the date of this item. Date is prompted for, with default today.
8267 The prefix ARG is passed to the `org-time-stamp' command and can therefore
8268 be used to request time specification in the time stamp."
8269 (interactive "P")
8270 (org-agenda-check-type t 'agenda 'timeline)
8271 (org-agenda-check-no-diary)
8272 (let* ((marker (or (get-text-property (point) 'org-marker)
8273 (org-agenda-error)))
8274 (buffer (marker-buffer marker))
8275 (pos (marker-position marker)))
8276 (with-current-buffer buffer
8277 (widen)
8278 (goto-char pos)
8279 (if (not (org-at-timestamp-p))
8280 (error "Cannot find time stamp"))
8281 (org-time-stamp arg)
8282 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8283
8284 (defun org-agenda-schedule (arg)
8285 "Schedule the item at point."
8286 (interactive "P")
8287 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8288 (org-agenda-check-no-diary)
8289 (let* ((marker (or (get-text-property (point) 'org-marker)
8290 (org-agenda-error)))
8291 (buffer (marker-buffer marker))
8292 (pos (marker-position marker))
8293 (org-insert-labeled-timestamps-at-point nil)
8294 ts)
8295 (with-current-buffer buffer
8296 (widen)
8297 (goto-char pos)
8298 (setq ts (org-schedule))
8299 (message "Item scheduled for %s" ts))))
8300
8301 (defun org-agenda-deadline (arg)
8302 "Schedule the item at point."
8303 (interactive "P")
8304 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8305 (org-agenda-check-no-diary)
8306 (let* ((marker (or (get-text-property (point) 'org-marker)
8307 (org-agenda-error)))
8308 (buffer (marker-buffer marker))
8309 (pos (marker-position marker))
8310 (org-insert-labeled-timestamps-at-point nil)
8311 ts)
8312 (with-current-buffer buffer
8313 (widen)
8314 (goto-char pos)
8315 (setq ts (org-deadline))
8316 (message "Deadline for this item set to %s" ts))))
8317
8318 (defun org-get-heading ()
8319 "Return the heading of the current entry, without the stars."
8320 (save-excursion
8321 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
8322 (if (and (re-search-backward "[\r\n]\\*" nil t)
8323 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
8324 (match-string 1)
8325 "")))
8326
8327 (defun org-agenda-clock-in (&optional arg)
8328 "Start the clock on the currently selected item."
8329 (interactive "P")
8330 (org-agenda-check-no-diary)
8331 (let* ((marker (or (get-text-property (point) 'org-marker)
8332 (org-agenda-error)))
8333 (pos (marker-position marker)))
8334 (with-current-buffer (marker-buffer marker)
8335 (widen)
8336 (goto-char pos)
8337 (org-clock-in))))
8338
8339 (defun org-agenda-diary-entry ()
8340 "Make a diary entry, like the `i' command from the calendar.
8341 All the standard commands work: block, weekly etc."
8342 (interactive)
8343 (org-agenda-check-type t 'agenda 'timeline)
8344 (require 'diary-lib)
8345 (let* ((char (progn
8346 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
8347 (read-char-exclusive)))
8348 (cmd (cdr (assoc char
8349 '((?d . insert-diary-entry)
8350 (?w . insert-weekly-diary-entry)
8351 (?m . insert-monthly-diary-entry)
8352 (?y . insert-yearly-diary-entry)
8353 (?a . insert-anniversary-diary-entry)
8354 (?b . insert-block-diary-entry)
8355 (?c . insert-cyclic-diary-entry)))))
8356 (oldf (symbol-function 'calendar-cursor-to-date))
8357 (point (point))
8358 (mark (or (mark t) (point))))
8359 (unless cmd
8360 (error "No command associated with <%c>" char))
8361 (unless (and (get-text-property point 'day)
8362 (or (not (equal ?b char))
8363 (get-text-property mark 'day)))
8364 (error "Don't know which date to use for diary entry"))
8365 ;; We implement this by hacking the `calendar-cursor-to-date' function
8366 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
8367 (let ((calendar-mark-ring
8368 (list (calendar-gregorian-from-absolute
8369 (or (get-text-property mark 'day)
8370 (get-text-property point 'day))))))
8371 (unwind-protect
8372 (progn
8373 (fset 'calendar-cursor-to-date
8374 (lambda (&optional error)
8375 (calendar-gregorian-from-absolute
8376 (get-text-property point 'day))))
8377 (call-interactively cmd))
8378 (fset 'calendar-cursor-to-date oldf)))))
8379
8380
8381 (defun org-agenda-execute-calendar-command (cmd)
8382 "Execute a calendar command from the agenda, with the date associated to
8383 the cursor position."
8384 (org-agenda-check-type t 'agenda 'timeline)
8385 (require 'diary-lib)
8386 (unless (get-text-property (point) 'day)
8387 (error "Don't know which date to use for calendar command"))
8388 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
8389 (point (point))
8390 (date (calendar-gregorian-from-absolute
8391 (get-text-property point 'day)))
8392 (displayed-day (extract-calendar-day date))
8393 (displayed-month (extract-calendar-month date))
8394 (displayed-year (extract-calendar-year date)))
8395 (unwind-protect
8396 (progn
8397 (fset 'calendar-cursor-to-date
8398 (lambda (&optional error)
8399 (calendar-gregorian-from-absolute
8400 (get-text-property point 'day))))
8401 (call-interactively cmd))
8402 (fset 'calendar-cursor-to-date oldf))))
8403
8404 (defun org-agenda-phases-of-moon ()
8405 "Display the phases of the moon for the 3 months around the cursor date."
8406 (interactive)
8407 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
8408
8409 (defun org-agenda-holidays ()
8410 "Display the holidays for the 3 months around the cursor date."
8411 (interactive)
8412 (org-agenda-execute-calendar-command 'list-calendar-holidays))
8413
8414 (defun org-agenda-sunrise-sunset (arg)
8415 "Display sunrise and sunset for the cursor date.
8416 Latitude and longitude can be specified with the variables
8417 `calendar-latitude' and `calendar-longitude'. When called with prefix
8418 argument, latitude and longitude will be prompted for."
8419 (interactive "P")
8420 (let ((calendar-longitude (if arg nil calendar-longitude))
8421 (calendar-latitude (if arg nil calendar-latitude))
8422 (calendar-location-name
8423 (if arg "the given coordinates" calendar-location-name)))
8424 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
8425
8426 (defun org-agenda-goto-calendar ()
8427 "Open the Emacs calendar with the date at the cursor."
8428 (interactive)
8429 (org-agenda-check-type t 'agenda 'timeline)
8430 (let* ((day (or (get-text-property (point) 'day)
8431 (error "Don't know which date to open in calendar")))
8432 (date (calendar-gregorian-from-absolute day))
8433 (calendar-move-hook nil)
8434 (view-calendar-holidays-initially nil)
8435 (view-diary-entries-initially nil))
8436 (calendar)
8437 (calendar-goto-date date)))
8438
8439 (defun org-calendar-goto-agenda ()
8440 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
8441 This is a command that has to be installed in `calendar-mode-map'."
8442 (interactive)
8443 (org-agenda-list nil (calendar-absolute-from-gregorian
8444 (calendar-cursor-to-date))
8445 nil t))
8446
8447 (defun org-agenda-convert-date ()
8448 (interactive)
8449 (org-agenda-check-type t 'agenda 'timeline)
8450 (let ((day (get-text-property (point) 'day))
8451 date s)
8452 (unless day
8453 (error "Don't know which date to convert"))
8454 (setq date (calendar-gregorian-from-absolute day))
8455 (setq s (concat
8456 "Gregorian: " (calendar-date-string date) "\n"
8457 "ISO: " (calendar-iso-date-string date) "\n"
8458 "Day of Yr: " (calendar-day-of-year-string date) "\n"
8459 "Julian: " (calendar-julian-date-string date) "\n"
8460 "Astron. JD: " (calendar-astro-date-string date)
8461 " (Julian date number at noon UTC)\n"
8462 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
8463 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
8464 "French: " (calendar-french-date-string date) "\n"
8465 "Mayan: " (calendar-mayan-date-string date) "\n"
8466 "Coptic: " (calendar-coptic-date-string date) "\n"
8467 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
8468 "Persian: " (calendar-persian-date-string date) "\n"
8469 "Chinese: " (calendar-chinese-date-string date) "\n"))
8470 (with-output-to-temp-buffer "*Dates*"
8471 (princ s))
8472 (if (fboundp 'fit-window-to-buffer)
8473 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
8474
8475 ;;; Tags
8476
8477 (defun org-scan-tags (action matcher &optional todo-only)
8478 "Scan headline tags with inheritance and produce output ACTION.
8479 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8480 evaluated, testing if a given set of tags qualifies a headline for
8481 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8482 are included in the output."
8483 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8484 (mapconcat 'regexp-quote
8485 (nreverse (cdr (reverse org-todo-keywords)))
8486 "\\|")
8487 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
8488 (props (list 'face nil
8489 'done-face 'org-done
8490 'undone-face nil
8491 'mouse-face 'highlight
8492 'keymap org-agenda-keymap
8493 'help-echo
8494 (format "mouse-2 or RET jump to org file %s"
8495 (abbreviate-file-name buffer-file-name))))
8496 lspos
8497 tags tags-list tags-alist (llast 0) rtn level category i txt
8498 todo marker)
8499 (save-excursion
8500 (goto-char (point-min))
8501 (when (eq action 'sparse-tree) (org-overview))
8502 (while (re-search-forward re nil t)
8503 (catch :skip
8504 (and (eq action 'agenda) (org-agenda-skip))
8505 (setq todo (if (match-end 1) (match-string 2))
8506 tags (if (match-end 4) (match-string 4)))
8507 (goto-char (setq lspos (1+ (match-beginning 0))))
8508 (setq level (funcall outline-level)
8509 category (org-get-category))
8510 (setq i llast llast level)
8511 ;; remove tag lists from same and sublevels
8512 (while (>= i level)
8513 (when (setq entry (assoc i tags-alist))
8514 (setq tags-alist (delete entry tags-alist)))
8515 (setq i (1- i)))
8516 ;; add the nex tags
8517 (when tags
8518 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8519 tags-alist
8520 (cons (cons level tags) tags-alist)))
8521 ;; compile tags for current headline
8522 (setq tags-list
8523 (if org-use-tag-inheritance
8524 (apply 'append (mapcar 'cdr tags-alist))
8525 tags))
8526 (when (and (or (not todo-only) todo)
8527 (eval matcher)
8528 (or (not org-agenda-skip-archived-trees)
8529 (not (member org-archive-tag tags-list))))
8530 ;; list this headline
8531 (if (eq action 'sparse-tree)
8532 (progn
8533 (org-show-hierarchy-above))
8534 (setq txt (org-format-agenda-item
8535 ""
8536 (concat
8537 (if org-tags-match-list-sublevels
8538 (make-string (1- level) ?.) "")
8539 (org-get-heading))
8540 category tags-list))
8541 (goto-char lspos)
8542 (setq marker (org-agenda-new-marker))
8543 (org-add-props txt props
8544 'org-marker marker 'org-hd-marker marker 'category category)
8545 (push txt rtn))
8546 ;; if we are to skip sublevels, jump to end of subtree
8547 (point)
8548 (or org-tags-match-list-sublevels (org-end-of-subtree))))))
8549 (when (and (eq action 'sparse-tree)
8550 (not org-sparse-tree-open-archived-trees))
8551 (org-hide-archived-subtrees (point-min) (point-max)))
8552 (nreverse rtn)))
8553
8554 (defun org-tags-sparse-tree (&optional arg match)
8555 "Create a sparse tree according to tags search string MATCH.
8556 MATCH can contain positive and negative selection of tags, like
8557 \"+WORK+URGENT-WITHBOSS\"."
8558 (interactive "P")
8559 (let ((org-show-following-heading nil)
8560 (org-show-hierarchy-above nil))
8561 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
8562
8563 (defun org-make-tags-matcher (match)
8564 "Create the TAGS matcher form for the tags-selecting string MATCH."
8565 (unless match
8566 ;; Get a new match request, with completion
8567 (setq org-last-tags-completion-table
8568 (or (org-get-buffer-tags)
8569 org-last-tags-completion-table))
8570 (setq match (completing-read
8571 "Tags: " 'org-tags-completion-function nil nil nil
8572 'org-tags-history)))
8573 ;; parse the string and create a lisp form
8574 (let ((match0 match) minus tag mm matcher orterms term orlist)
8575 (setq orterms (org-split-string match "|"))
8576 (while (setq term (pop orterms))
8577 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
8578 (setq minus (and (match-end 1)
8579 (equal (match-string 1 term) "-"))
8580 tag (match-string 2 term)
8581 term (substring term (match-end 0))
8582 mm (list 'member (downcase tag) 'tags-list)
8583 mm (if minus (list 'not mm) mm))
8584 (push mm matcher))
8585 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
8586 orlist)
8587 (setq matcher nil))
8588 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8589 ;; Return the string and lisp forms of the matcher
8590 (cons match0 matcher)))
8591
8592 ;;;###autoload
8593 (defun org-tags-view (&optional todo-only match keep-modes)
8594 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
8595 The prefix arg TODO-ONLY limits the search to TODO entries."
8596 (interactive "P")
8597 (org-agenda-maybe-reset-markers 'force)
8598 (org-compile-prefix-format org-agenda-prefix-format)
8599 (let* ((org-agenda-keep-modes keep-modes)
8600 (org-tags-match-list-sublevels
8601 (if todo-only t org-tags-match-list-sublevels))
8602 (win (selected-window))
8603 (completion-ignore-case t)
8604 rtn rtnall files file pos matcher
8605 buffer)
8606 (setq matcher (org-make-tags-matcher match)
8607 match (car matcher) matcher (cdr matcher))
8608 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
8609 (progn
8610 (delete-other-windows)
8611 (switch-to-buffer-other-window
8612 (get-buffer-create org-agenda-buffer-name))))
8613 (setq buffer-read-only nil)
8614 (erase-buffer)
8615 (org-agenda-mode) (setq buffer-read-only nil)
8616 (set (make-local-variable 'org-agenda-type) 'tags)
8617 (set (make-local-variable 'org-agenda-redo-command)
8618 (list 'org-tags-view (list 'quote todo-only)
8619 (list 'if 'current-prefix-arg nil match) t))
8620 (setq files (org-agenda-files)
8621 rtnall nil)
8622 (org-prepare-agenda-buffers files)
8623 (while (setq file (pop files))
8624 (catch 'nextfile
8625 (org-check-agenda-file file)
8626 (setq buffer (if (file-exists-p file)
8627 (org-get-agenda-file-buffer file)
8628 (error "No such file %s" file)))
8629 (if (not buffer)
8630 ;; If file does not exist, merror message to agenda
8631 (setq rtn (list
8632 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8633 rtnall (append rtnall rtn))
8634 (with-current-buffer buffer
8635 (unless (org-mode-p)
8636 (error "Agenda file %s is not in `org-mode'" file))
8637 (setq org-category-table (org-get-category-table))
8638 (save-excursion
8639 (save-restriction
8640 (if org-respect-restriction
8641 (if (org-region-active-p)
8642 ;; Respect a region to restrict search
8643 (narrow-to-region (region-beginning) (region-end)))
8644 ;; If we work for the calendar or many files,
8645 ;; get rid of any restriction
8646 (widen))
8647 (setq rtn (org-scan-tags 'agenda matcher todo-only))
8648 (setq rtnall (append rtnall rtn))))))))
8649 (insert "Headlines with TAGS match: ")
8650 (add-text-properties (point-min) (1- (point))
8651 (list 'face 'org-level-3))
8652 (setq pos (point))
8653 (insert match "\n")
8654 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
8655 (setq pos (point))
8656 (insert "Press `C-u r' to search again with new search string\n")
8657 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
8658 (when rtnall
8659 (insert (mapconcat 'identity rtnall "\n")))
8660 (goto-char (point-min))
8661 (setq buffer-read-only t)
8662 (org-fit-agenda-window)
8663 (if (not org-select-agenda-window) (select-window win))))
8664
8665 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8666 (defun org-set-tags (&optional arg just-align)
8667 "Set the tags for the current headline.
8668 With prefix ARG, realign all tags in headings in the current buffer."
8669 (interactive "P")
8670 (let* ((re (concat "^" outline-regexp))
8671 (col (current-column))
8672 (current (org-get-tags))
8673 table current-tags inherited-tags ; computed below when needed
8674 tags hd empty invis)
8675 (if arg
8676 (save-excursion
8677 (goto-char (point-min))
8678 (while (re-search-forward re nil t)
8679 (org-set-tags nil t))
8680 (message "All tags realigned to column %d" org-tags-column))
8681 (if just-align
8682 (setq tags current)
8683 (setq table (or org-tag-alist (org-get-buffer-tags))
8684 org-last-tags-completion-table table
8685 current-tags (org-split-string current ":")
8686 inherited-tags (nreverse
8687 (nthcdr (length current-tags)
8688 (nreverse (org-get-tags-at))))
8689 tags
8690 (if (or (eq t org-use-fast-tag-selection)
8691 (and org-use-fast-tag-selection
8692 (delq nil (mapcar 'cdr table))))
8693 (org-fast-tag-selection current-tags inherited-tags table)
8694 (let ((org-add-colon-after-tag-completion t))
8695 (completing-read "Tags: " 'org-tags-completion-function
8696 nil nil current 'org-tags-history))))
8697 (while (string-match "[-+&]+" tags)
8698 (setq tags (replace-match ":" t t tags))))
8699
8700 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
8701 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8702 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8703 (if (equal current "")
8704 (progn
8705 (end-of-line 1)
8706 (or empty (insert-before-markers " ")))
8707 (beginning-of-line 1)
8708 (setq invis (org-invisible-p))
8709 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
8710 (setq hd (match-string 1))
8711 (delete-region (match-beginning 0) (match-end 0))
8712 (insert-before-markers (org-trim hd) (if empty "" " ")))
8713 (if (equal tags "")
8714 (save-excursion
8715 (beginning-of-line 1)
8716 (and (re-search-forward "[ \t]+$" (point-at-eol) t)
8717 (replace-match "")))
8718 (move-to-column (max (current-column)
8719 (if (> org-tags-column 0)
8720 org-tags-column
8721 (- (- org-tags-column) (length tags))))
8722 t)
8723 (insert-before-markers tags)
8724 (if (and (not invis) (org-invisible-p))
8725 (outline-flag-region (point-at-bol) (point) nil)))
8726 (move-to-column col))))
8727
8728 (defun org-tags-completion-function (string predicate &optional flag)
8729 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8730 (confirm (lambda (x) (stringp (car x)))))
8731 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8732 (setq s1 (match-string 1 string)
8733 s2 (match-string 2 string))
8734 (setq s1 "" s2 string))
8735 (cond
8736 ((eq flag nil)
8737 ;; try completion
8738 (setq rtn (try-completion s2 ctable confirm))
8739 (if (stringp rtn)
8740 (concat s1 s2 (substring rtn (length s2))
8741 (if (and org-add-colon-after-tag-completion
8742 (assoc rtn ctable))
8743 ":" "")))
8744 )
8745 ((eq flag t)
8746 ;; all-completions
8747 (all-completions s2 ctable confirm)
8748 )
8749 ((eq flag 'lambda)
8750 ;; exact match?
8751 (assoc s2 ctable)))
8752 ))
8753
8754 (defun org-fast-tag-insert (kwd tags face &optional end)
8755 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
8756 (insert (format "%-12s" (concat kwd ":"))
8757 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
8758 (or end "")))
8759
8760 (defun org-fast-tag-selection (current inherited table)
8761 "Fast tag selection with single keys.
8762 CURRENT is the current list of tags in the headline, INHERITED is the
8763 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
8764 possibly with grouping information.
8765 If the keys are nil, a-z are automatically assigned.
8766 Returns the new tags string, or nil to not change the current settings."
8767 (let* ((maxlen (apply 'max (mapcar
8768 (lambda (x)
8769 (if (stringp (car x)) (string-width (car x)) 0))
8770 table)))
8771 (fwidth (+ maxlen 3 1 3))
8772 (ncol (/ (- (window-width) 4) fwidth))
8773 (i-face 'org-done)
8774 (c-face 'org-tag)
8775 tg cnt e c char c1 c2 ntable tbl rtn
8776 groups ingroup)
8777 (save-window-excursion
8778 (delete-other-windows)
8779 (split-window-vertically)
8780 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
8781 (erase-buffer)
8782 (org-fast-tag-insert "Inherited" inherited i-face "\n")
8783 (org-fast-tag-insert "Current" current c-face "\n\n")
8784 (setq tbl table char ?a cnt 0)
8785 (while (setq e (pop tbl))
8786 (cond
8787 ((equal e '(:startgroup))
8788 (push '() groups) (setq ingroup t)
8789 (when (not (= cnt 0))
8790 (setq cnt 0)
8791 (insert "\n"))
8792 (insert "{ "))
8793 ((equal e '(:endgroup))
8794 (setq ingroup nil cnt 0)
8795 (insert "}\n"))
8796 (t
8797 (setq tg (car e) c2 nil)
8798 (if (cdr e)
8799 (setq c (cdr e))
8800 ;; automatically assign a character.
8801 (setq c1 (string-to-char
8802 (downcase (substring
8803 tg (if (= (string-to-char tg) ?@) 1 0)))))
8804 (if (or (rassoc c1 ntable) (rassoc c1 table))
8805 (while (or (rassoc char ntable) (rassoc char table))
8806 (setq char (1+ char)))
8807 (setq c2 c1))
8808 (setq c (or c2 char)))
8809 (if ingroup (push tg (car groups)))
8810 (setq tg (org-add-props tg nil 'face
8811 (cond
8812 ((member tg current) c-face)
8813 ((member tg inherited) i-face)
8814 (t nil))))
8815 (if (and (= cnt 0) (not ingroup)) (insert " "))
8816 (insert "[" c "] " tg (make-string
8817 (- fwidth 4 (length tg)) ?\ ))
8818 (push (cons tg c) ntable)
8819 (when (= (setq cnt (1+ cnt)) ncol)
8820 (insert "\n")
8821 (if ingroup (insert " "))
8822 (setq cnt 0)))))
8823 (setq ntable (nreverse ntable))
8824 (insert "\n")
8825 (goto-char (point-min))
8826 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
8827 (setq rtn
8828 (catch 'exit
8829 (while t
8830 (message "[key]:Toggle SPC: clear current RET accept%s"
8831 (if groups " [!] ignore goups" ""))
8832 (setq c (read-char-exclusive))
8833 (cond
8834 ((= c ?\r) (throw 'exit t))
8835 ((= c ?!)
8836 (setq groups nil)
8837 (goto-char (point-min))
8838 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
8839 ((or (= c ?\C-g)
8840 (and (= c ?q) (not (rassoc c ntable))))
8841 (setq quit-flag t))
8842 ((= c ?\ ) (setq current nil))
8843 ((setq e (rassoc c ntable) tg (car e))
8844 (if (member tg current)
8845 (setq current (delete tg current))
8846 (loop for g in groups do
8847 (if (member tg g)
8848 (mapcar (lambda (x)
8849 (setq current (delete x current)))
8850 g)))
8851 (setq current (cons tg current)))))
8852 ;; Create a sorted list
8853 (setq current
8854 (sort current
8855 (lambda (a b)
8856 (assoc b (cdr (memq (assoc a ntable) ntable))))))
8857 (goto-char (point-min))
8858 (beginning-of-line 2)
8859 (delete-region (point) (point-at-eol))
8860 (org-fast-tag-insert "Current" current c-face)
8861 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
8862 (setq tg (match-string 1))
8863 (add-text-properties (match-beginning 1) (match-end 1)
8864 (list 'face
8865 (cond
8866 ((member tg current) c-face)
8867 ((member tg inherited) i-face)
8868 (t nil)))))
8869 (goto-char (point-min)))))
8870 (if rtn
8871 (mapconcat 'identity current ":")
8872 nil))))
8873
8874 (defun org-get-tags ()
8875 "Get the TAGS string in the current headline."
8876 (unless (org-on-heading-p)
8877 (error "Not on a heading"))
8878 (save-excursion
8879 (beginning-of-line 1)
8880 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
8881 (org-match-string-no-properties 1)
8882 "")))
8883
8884 (defun org-get-buffer-tags ()
8885 "Get a table of all tags used in the buffer, for completion."
8886 (let (tags)
8887 (save-excursion
8888 (goto-char (point-min))
8889 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
8890 (mapc (lambda (x) (add-to-list 'tags x))
8891 (org-split-string (org-match-string-no-properties 1) ":"))))
8892 (mapcar 'list tags)))
8893
8894 ;;; Link Stuff
8895
8896 (defvar org-create-file-search-functions nil
8897 "List of functions to construct the right search string for a file link.
8898 These functions are called in turn with point at the location to
8899 which the link should point.
8900
8901 A function in the hook should first test if it would like to
8902 handle this file type, for example by checking the major-mode or
8903 the file extension. If it decides not to handle this file, it
8904 should just return nil to give other functions a chance. If it
8905 does handle the file, it must return the search string to be used
8906 when following the link. The search string will be part of the
8907 file link, given after a double colon, and `org-open-at-point'
8908 will automatically search for it. If special measures must be
8909 taken to make the search successful, another function should be
8910 added to the companion hook `org-execute-file-search-functions',
8911 which see.
8912
8913 A function in this hook may also use `setq' to set the variable
8914 `description' to provide a suggestion for the descriptive text to
8915 be used for this link when it gets inserted into an Org-mode
8916 buffer with \\[org-insert-link].")
8917
8918 (defvar org-execute-file-search-functions nil
8919 "List of functions to execute a file search triggered by a link.
8920
8921 Functions added to this hook must accept a single argument, the
8922 search string that was part of the file link, the part after the
8923 double colon. The function must first check if it would like to
8924 handle this search, for example by checking the major-mode or the
8925 file extension. If it decides not to handle this search, it
8926 should just return nil to give other functions a chance. If it
8927 does handle the search, it must return a non-nil value to keep
8928 other functions from trying.
8929
8930 Each function can access the current prefix argument through the
8931 variable `current-prefix-argument'. Note that a single prefix is
8932 used to force opening a link in Emacs, so it may be good to only
8933 use a numeric or double prefix to guide the search function.
8934
8935 In case this is needed, a function in this hook can also restore
8936 the window configuration before `org-open-at-point' was called using:
8937
8938 (set-window-configuration org-window-config-before-follow-link)")
8939
8940 (defun org-find-file-at-mouse (ev)
8941 "Open file link or URL at mouse."
8942 (interactive "e")
8943 (mouse-set-point ev)
8944 (org-open-at-point 'in-emacs))
8945
8946 (defun org-open-at-mouse (ev)
8947 "Open file link or URL at mouse."
8948 (interactive "e")
8949 (mouse-set-point ev)
8950 (org-open-at-point))
8951
8952 (defvar org-window-config-before-follow-link nil
8953 "The window configuration before following a link.
8954 This is saved in case the need arises to restore it.")
8955
8956 (defun org-open-at-point (&optional in-emacs)
8957 "Open link at or after point.
8958 If there is no link at point, this function will search forward up to
8959 the end of the current subtree.
8960 Normally, files will be opened by an appropriate application. If the
8961 optional argument IN-EMACS is non-nil, Emacs will visit the file."
8962 (interactive "P")
8963 (setq org-window-config-before-follow-link (current-window-configuration))
8964 (org-remove-occur-highlights nil nil t)
8965 (if (org-at-timestamp-p)
8966 (org-agenda-list nil (time-to-days (org-time-string-to-time
8967 (substring (match-string 1) 0 10)))
8968 1)
8969 (let (type path link line search (pos (point)))
8970 (catch 'match
8971 (save-excursion
8972 (skip-chars-forward "^]\n\r")
8973 (when (and (re-search-backward "\\[\\[" nil t)
8974 (looking-at org-bracket-link-regexp)
8975 (<= (match-beginning 0) pos)
8976 (>= (match-end 0) pos))
8977 (setq link (org-link-unescape (org-match-string-no-properties 1)))
8978 (while (string-match " *\n *" link)
8979 (setq link (replace-match " " t t link)))
8980 (if (string-match org-link-re-with-space2 link)
8981 (setq type (match-string 1 link)
8982 path (match-string 2 link))
8983 (setq type "thisfile"
8984 path link))
8985 (throw 'match t)))
8986
8987 (when (get-text-property (point) 'org-linked-text)
8988 (setq type "thisfile"
8989 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8990 (1+ (point)) (point))
8991 path (buffer-substring
8992 (previous-single-property-change pos 'org-linked-text)
8993 (next-single-property-change pos 'org-linked-text)))
8994 (throw 'match t))
8995
8996 (save-excursion
8997 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
8998 (if (equal (char-before) ?<) (backward-char 1))
8999 (when (or (looking-at org-angle-link-re)
9000 (looking-at org-plain-link-re)
9001 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
9002 (re-search-forward org-plain-link-re (point-at-eol) t))
9003 (<= (match-beginning 0) pos)
9004 (>= (match-end 0) pos)))
9005 (setq type (match-string 1)
9006 path (match-string 2))
9007 (throw 'match t)))
9008 (save-excursion
9009 (skip-chars-backward "^ \t\n\r")
9010 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
9011 (setq type "tags"
9012 path (match-string 1))
9013 (while (string-match ":" path)
9014 (setq path (replace-match "+" t t path)))
9015 (throw 'match t)))
9016 (save-excursion
9017 (skip-chars-backward "a-zA-Z_")
9018 (when (and (memq 'camel org-activate-links)
9019 (looking-at org-camel-regexp))
9020 (setq type "camel" path (match-string 0))
9021 (if (equal (char-before) ?*)
9022 (setq path (concat "*" path))))
9023 (throw 'match t)))
9024 (unless path
9025 (error "No link found"))
9026 ;; Remove any trailing spaces in path
9027 (if (string-match " +\\'" path)
9028 (setq path (replace-match "" t t path)))
9029
9030 (cond
9031
9032 ((member type '("http" "https" "ftp" "mailto" "news"))
9033 (browse-url (concat type ":" path)))
9034
9035 ((string= type "tags")
9036 (org-tags-view in-emacs path))
9037 ((or (string= type "camel")
9038 (string= type "thisfile"))
9039 (org-mark-ring-push)
9040 (org-link-search
9041 path
9042 (cond ((equal in-emacs '(4)) 'occur)
9043 ((equal in-emacs '(16)) 'org-occur)
9044 (t nil))))
9045
9046 ((string= type "file")
9047 (if (string-match "::\\([0-9]+\\)\\'" path)
9048 (setq line (string-to-number (match-string 1 path))
9049 path (substring path 0 (match-beginning 0)))
9050 (if (string-match "::\\(.+\\)\\'" path)
9051 (setq search (match-string 1 path)
9052 path (substring path 0 (match-beginning 0)))))
9053 (org-open-file path in-emacs line search))
9054
9055 ((string= type "news")
9056 (org-follow-gnus-link path))
9057
9058 ((string= type "bbdb")
9059 (org-follow-bbdb-link path))
9060
9061 ((string= type "info")
9062 (org-follow-info-link path))
9063
9064 ((string= type "gnus")
9065 (let (group article)
9066 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9067 (error "Error in Gnus link"))
9068 (setq group (match-string 1 path)
9069 article (match-string 3 path))
9070 (org-follow-gnus-link group article)))
9071
9072 ((string= type "vm")
9073 (let (folder article)
9074 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9075 (error "Error in VM link"))
9076 (setq folder (match-string 1 path)
9077 article (match-string 3 path))
9078 ;; in-emacs is the prefix arg, will be interpreted as read-only
9079 (org-follow-vm-link folder article in-emacs)))
9080
9081 ((string= type "wl")
9082 (let (folder article)
9083 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9084 (error "Error in Wanderlust link"))
9085 (setq folder (match-string 1 path)
9086 article (match-string 3 path))
9087 (org-follow-wl-link folder article)))
9088
9089 ((string= type "mhe")
9090 (let (folder article)
9091 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9092 (error "Error in MHE link"))
9093 (setq folder (match-string 1 path)
9094 article (match-string 3 path))
9095 (org-follow-mhe-link folder article)))
9096
9097 ((string= type "rmail")
9098 (let (folder article)
9099 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9100 (error "Error in RMAIL link"))
9101 (setq folder (match-string 1 path)
9102 article (match-string 3 path))
9103 (org-follow-rmail-link folder article)))
9104
9105 ((string= type "shell")
9106 (let ((cmd path))
9107 (while (string-match "@{" cmd)
9108 (setq cmd (replace-match "<" t t cmd)))
9109 (while (string-match "@}" cmd)
9110 (setq cmd (replace-match ">" t t cmd)))
9111 (if (or (not org-confirm-shell-link-function)
9112 (funcall org-confirm-shell-link-function
9113 (format "Execute \"%s\" in shell? "
9114 (org-add-props cmd nil
9115 'face 'org-warning))))
9116 (progn
9117 (message "Executing %s" cmd)
9118 (shell-command cmd))
9119 (error "Abort"))))
9120
9121 ((string= type "elisp")
9122 (let ((cmd path))
9123 (if (or (not org-confirm-elisp-link-function)
9124 (funcall org-confirm-elisp-link-function
9125 (format "Execute \"%s\" as elisp? "
9126 (org-add-props cmd nil
9127 'face 'org-warning))))
9128 (message "%s => %s" cmd (eval (read cmd)))
9129 (error "Abort"))))
9130
9131 (t
9132 (browse-url-at-point))))))
9133
9134 (defun org-link-search (s &optional type)
9135 "Search for a link search option.
9136 When S is a CamelCaseWord, search for a target, or for a sentence containing
9137 the words. If S is surrounded by forward slashes, it is interpreted as a
9138 regular expression. In org-mode files, this will create an `org-occur'
9139 sparse tree. In ordinary files, `occur' will be used to list matches.
9140 If the current buffer is in `dired-mode', grep will be used to search
9141 in all files."
9142 (let ((case-fold-search t)
9143 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9144 (pos (point))
9145 (pre "") (post "")
9146 words re0 re1 re2 re3 re4 re5 re2a reall camel)
9147 (cond
9148 ;; First check if there are any special
9149 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9150 ;; Now try the builtin stuff
9151 ((save-excursion
9152 (goto-char (point-min))
9153 (and
9154 (re-search-forward
9155 (concat "<<" (regexp-quote s0) ">>") nil t)
9156 (setq pos (match-beginning 0))))
9157 ;; There is an exact target for this
9158 (goto-char pos))
9159 ((string-match "^/\\(.*\\)/$" s)
9160 ;; A regular expression
9161 (cond
9162 ((org-mode-p)
9163 (org-occur (match-string 1 s)))
9164 ;;((eq major-mode 'dired-mode)
9165 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9166 (t (org-do-occur (match-string 1 s)))))
9167 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
9168 t)
9169 ;; A camel or a normal search string
9170 (when (equal (string-to-char s) ?*)
9171 ;; Anchor on headlines, post may include tags.
9172 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9173 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9174 s (substring s 1)))
9175 (remove-text-properties
9176 0 (length s)
9177 '(face nil mouse-face nil keymap nil fontified nil) s)
9178 ;; Make a series of regular expressions to find a match
9179 (setq words
9180 (if camel
9181 (org-camel-to-words s)
9182 (org-split-string s "[ \n\r\t]+"))
9183 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9184 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9185 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9186 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9187 re1 (concat pre re2 post)
9188 re3 (concat pre re4 post)
9189 re5 (concat pre ".*" re4)
9190 re2 (concat pre re2)
9191 re2a (concat pre re2a)
9192 re4 (concat pre re4)
9193 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9194 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9195 re5 "\\)"
9196 ))
9197 (cond
9198 ((eq type 'org-occur) (org-occur reall))
9199 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9200 (t (goto-char (point-min))
9201 (if (or (org-search-not-link re0 nil t)
9202 (org-search-not-link re1 nil t)
9203 (org-search-not-link re2 nil t)
9204 (org-search-not-link re2a nil t)
9205 (org-search-not-link re3 nil t)
9206 (org-search-not-link re4 nil t)
9207 (org-search-not-link re5 nil t)
9208 )
9209 (goto-char (match-beginning 1))
9210 (goto-char pos)
9211 (error "No match")))))
9212 (t
9213 ;; Normal string-search
9214 (goto-char (point-min))
9215 (if (search-forward s nil t)
9216 (goto-char (match-beginning 0))
9217 (error "No match"))))
9218 (and (org-mode-p) (org-show-hierarchy-above))))
9219
9220 (defun org-search-not-link (&rest args)
9221 "Execute `re-search-forward', but only accept matches that are not a link."
9222 (catch 'exit
9223 (let (p1)
9224 (while (apply 're-search-forward args)
9225 (setq p1 (point))
9226 (if (not (save-match-data
9227 (and (re-search-backward "\\[\\[" nil t)
9228 (looking-at org-bracket-link-regexp)
9229 (<= (match-beginning 0) p1)
9230 (>= (match-end 0) p1))))
9231 (progn (goto-char (match-end 0))
9232 (throw 'exit (point)))
9233 (goto-char (match-end 0)))))))
9234
9235 (defun org-do-occur (regexp &optional cleanup)
9236 "Call the Emacs command `occur'.
9237 If CLEANUP is non-nil, remove the printout of the regular expression
9238 in the *Occur* buffer. This is useful if the regex is long and not useful
9239 to read."
9240 (occur regexp)
9241 (when cleanup
9242 (let ((cwin (selected-window)) win beg end)
9243 (when (setq win (get-buffer-window "*Occur*"))
9244 (select-window win))
9245 (goto-char (point-min))
9246 (when (re-search-forward "match[a-z]+" nil t)
9247 (setq beg (match-end 0))
9248 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9249 (setq end (1- (match-beginning 0)))))
9250 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9251 (goto-char (point-min))
9252 (select-window cwin))))
9253
9254 (defvar org-mark-ring nil
9255 "Mark ring for positions before jumps in Org-mode.")
9256 (defvar org-mark-ring-last-goto nil
9257 "Last position in the mark ring used to go back.")
9258 ;; Fill and close the ring
9259 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9260 (loop for i from 1 to org-mark-ring-length do
9261 (push (make-marker) org-mark-ring))
9262 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9263 org-mark-ring)
9264
9265 (defun org-mark-ring-push (&optional pos buffer)
9266 "Put the current position or POS into the mark ring and rotate it."
9267 (interactive)
9268 (setq pos (or pos (point)))
9269 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9270 (move-marker (car org-mark-ring)
9271 (or pos (point))
9272 (or buffer (current-buffer)))
9273 (message
9274 (substitute-command-keys
9275 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9276
9277 (defun org-mark-ring-goto (&optional n)
9278 "Jump to the previous position in the mark ring.
9279 With prefix arg N, jump back that many stored positions. When
9280 called several times in succession, walk through the entire ring.
9281 Org-mode commands jumping to a different position in the current file,
9282 or to another Org-mode file, automatically push the old position
9283 onto the ring."
9284 (interactive "p")
9285 (let (p m)
9286 (if (eq last-command this-command)
9287 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9288 (setq p org-mark-ring))
9289 (setq org-mark-ring-last-goto p)
9290 (setq m (car p))
9291 (switch-to-buffer (marker-buffer m))
9292 (goto-char m)
9293 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
9294
9295 (defun org-camel-to-words (s)
9296 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
9297 (let ((case-fold-search nil)
9298 words)
9299 (while (string-match "[a-z][A-Z]" s)
9300 (push (substring s 0 (1+ (match-beginning 0))) words)
9301 (setq s (substring s (1+ (match-beginning 0)))))
9302 (nreverse (cons s words))))
9303
9304 (defun org-remove-angle-brackets (s)
9305 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9306 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9307 s)
9308 (defun org-add-angle-brackets (s)
9309 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9310 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9311 s)
9312
9313 (defun org-follow-bbdb-link (name)
9314 "Follow a BBDB link to NAME."
9315 (require 'bbdb)
9316 (let ((inhibit-redisplay t)
9317 (bbdb-electric-p nil))
9318 (catch 'exit
9319 ;; Exact match on name
9320 (bbdb-name (concat "\\`" name "\\'") nil)
9321 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9322 ;; Exact match on name
9323 (bbdb-company (concat "\\`" name "\\'") nil)
9324 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9325 ;; Partial match on name
9326 (bbdb-name name nil)
9327 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9328 ;; Partial match on company
9329 (bbdb-company name nil)
9330 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9331 ;; General match including network address and notes
9332 (bbdb name nil)
9333 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
9334 (delete-window (get-buffer-window "*BBDB*"))
9335 (error "No matching BBDB record")))))
9336
9337
9338 (defun org-follow-info-link (name)
9339 "Follow an info file & node link to NAME."
9340 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
9341 (string-match "\\(.*\\)" name))
9342 (progn
9343 (require 'info)
9344 (if (match-string 2 name) ; If there isn't a node, choose "Top"
9345 (Info-find-node (match-string 1 name) (match-string 2 name))
9346 (Info-find-node (match-string 1 name) "Top")))
9347 (message (concat "Could not open: " name))))
9348
9349 (defun org-follow-gnus-link (&optional group article)
9350 "Follow a Gnus link to GROUP and ARTICLE."
9351 (require 'gnus)
9352 (funcall (cdr (assq 'gnus org-link-frame-setup)))
9353 (if group (gnus-fetch-group group))
9354 (if article
9355 (or (gnus-summary-goto-article article nil 'force)
9356 (if (fboundp 'gnus-summary-insert-cached-articles)
9357 (progn
9358 (gnus-summary-insert-cached-articles)
9359 (gnus-summary-goto-article article nil 'force))
9360 (message "Message could not be found.")))))
9361
9362 (defun org-follow-vm-link (&optional folder article readonly)
9363 "Follow a VM link to FOLDER and ARTICLE."
9364 (require 'vm)
9365 (setq article (org-add-angle-brackets article))
9366 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
9367 ;; ange-ftp or efs or tramp access
9368 (let ((user (or (match-string 1 folder) (user-login-name)))
9369 (host (match-string 2 folder))
9370 (file (match-string 3 folder)))
9371 (cond
9372 ((featurep 'tramp)
9373 ;; use tramp to access the file
9374 (if (featurep 'xemacs)
9375 (setq folder (format "[%s@%s]%s" user host file))
9376 (setq folder (format "/%s@%s:%s" user host file))))
9377 (t
9378 ;; use ange-ftp or efs
9379 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
9380 (setq folder (format "/%s@%s:%s" user host file))))))
9381 (when folder
9382 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
9383 (sit-for 0.1)
9384 (when article
9385 (vm-select-folder-buffer)
9386 (widen)
9387 (let ((case-fold-search t))
9388 (goto-char (point-min))
9389 (if (not (re-search-forward
9390 (concat "^" "message-id: *" (regexp-quote article))))
9391 (error "Could not find the specified message in this folder"))
9392 (vm-isearch-update)
9393 (vm-isearch-narrow)
9394 (vm-beginning-of-message)
9395 (vm-summarize)))))
9396
9397 (defun org-follow-wl-link (folder article)
9398 "Follow a Wanderlust link to FOLDER and ARTICLE."
9399 (setq article (org-add-angle-brackets article))
9400 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
9401 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
9402 (wl-summary-redisplay))
9403
9404 (defun org-follow-rmail-link (folder article)
9405 "Follow an RMAIL link to FOLDER and ARTICLE."
9406 (setq article (org-add-angle-brackets article))
9407 (let (message-number)
9408 (save-excursion
9409 (save-window-excursion
9410 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9411 (setq message-number
9412 (save-restriction
9413 (widen)
9414 (goto-char (point-max))
9415 (if (re-search-backward
9416 (concat "^Message-ID:\\s-+" (regexp-quote
9417 (or article "")))
9418 nil t)
9419 (rmail-what-message))))))
9420 (if message-number
9421 (progn
9422 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9423 (rmail-show-message message-number)
9424 message-number)
9425 (error "Message not found"))))
9426
9427 ;; mh-e integration based on planner-mode
9428 (defun org-mhe-get-message-real-folder ()
9429 "Return the name of the current message real folder, so if you use
9430 sequences, it will now work."
9431 (save-excursion
9432 (let* ((folder
9433 (if (equal major-mode 'mh-folder-mode)
9434 mh-current-folder
9435 ;; Refer to the show buffer
9436 mh-show-folder-buffer))
9437 (end-index
9438 (if (boundp 'mh-index-folder)
9439 (min (length mh-index-folder) (length folder))))
9440 )
9441 ;; a simple test on mh-index-data does not work, because
9442 ;; mh-index-data is always nil in a show buffer.
9443 (if (and (boundp 'mh-index-folder)
9444 (string= mh-index-folder (substring folder 0 end-index)))
9445 (if (equal major-mode 'mh-show-mode)
9446 (save-window-excursion
9447 (when (buffer-live-p (get-buffer folder))
9448 (progn
9449 (pop-to-buffer folder)
9450 (org-mhe-get-message-folder-from-index)
9451 )
9452 ))
9453 (org-mhe-get-message-folder-from-index)
9454 )
9455 folder
9456 )
9457 )))
9458
9459 (defun org-mhe-get-message-folder-from-index ()
9460 "Returns the name of the message folder in a index folder buffer."
9461 (save-excursion
9462 (mh-index-previous-folder)
9463 (re-search-forward "^\\(+.*\\)$" nil t)
9464 (message (match-string 1))))
9465
9466 (defun org-mhe-get-message-folder ()
9467 "Return the name of the current message folder. Be careful if you
9468 use sequences."
9469 (save-excursion
9470 (if (equal major-mode 'mh-folder-mode)
9471 mh-current-folder
9472 ;; Refer to the show buffer
9473 mh-show-folder-buffer)))
9474
9475 (defun org-mhe-get-message-num ()
9476 "Return the number of the current message. Be careful if you
9477 use sequences."
9478 (save-excursion
9479 (if (equal major-mode 'mh-folder-mode)
9480 (mh-get-msg-num nil)
9481 ;; Refer to the show buffer
9482 (mh-show-buffer-message-number))))
9483
9484 (defun org-mhe-get-header (header)
9485 "Return a header of the message in folder mode. This will create a
9486 show buffer for the corresponding message. If you have a more clever
9487 idea..."
9488 (let* ((folder (org-mhe-get-message-folder))
9489 (num (org-mhe-get-message-num))
9490 (buffer (get-buffer-create (concat "show-" folder)))
9491 (header-field))
9492 (with-current-buffer buffer
9493 (mh-display-msg num folder)
9494 (if (equal major-mode 'mh-folder-mode)
9495 (mh-header-display)
9496 (mh-show-header-display))
9497 (set-buffer buffer)
9498 (setq header-field (mh-get-header-field header))
9499 (if (equal major-mode 'mh-folder-mode)
9500 (mh-show)
9501 (mh-show-show))
9502 header-field)))
9503
9504 (defun org-follow-mhe-link (folder article)
9505 "Follow an MHE link to FOLDER and ARTICLE.
9506 If ARTICLE is nil FOLDER is shown. If the configuration variable
9507 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9508 ARTICLE is searched in all folders. Indexed searches (swish++,
9509 namazu, and others supported by MH-E) will always search in all
9510 folders."
9511 (require 'mh-e)
9512 (require 'mh-search)
9513 (require 'mh-utils)
9514 (mh-find-path)
9515 (if (not article)
9516 (mh-visit-folder (mh-normalize-folder-name folder))
9517 (setq article (org-add-angle-brackets article))
9518 (mh-search-choose)
9519 (if (equal mh-searcher 'pick)
9520 (progn
9521 (mh-search folder (list "--message-id" article))
9522 (when (and org-mhe-search-all-folders
9523 (not (org-mhe-get-message-real-folder)))
9524 (kill-this-buffer)
9525 (mh-search "+" (list "--message-id" article))))
9526 (mh-search "+" article))
9527 (if (org-mhe-get-message-real-folder)
9528 (mh-show-msg 1)
9529 (kill-this-buffer)
9530 (error "Message not found"))))
9531
9532 ;; BibTeX links
9533
9534 ;; Use the custom search meachnism to construct and use search strings for
9535 ;; file links to BibTeX database entries.
9536
9537 (defun org-create-file-search-in-bibtex ()
9538 "Create the search string and description for a BibTeX database entry."
9539 (when (eq major-mode 'bibtex-mode)
9540 ;; yes, we want to construct this search string.
9541 ;; Make a good description for this entry, using names, year and the title
9542 ;; Put it into the `description' variable which is dynamically scoped.
9543 (let ((bibtex-autokey-names 1)
9544 (bibtex-autokey-names-stretch 1)
9545 (bibtex-autokey-name-case-convert-function 'identity)
9546 (bibtex-autokey-name-separator " & ")
9547 (bibtex-autokey-additional-names " et al.")
9548 (bibtex-autokey-year-length 4)
9549 (bibtex-autokey-name-year-separator " ")
9550 (bibtex-autokey-titlewords 3)
9551 (bibtex-autokey-titleword-separator " ")
9552 (bibtex-autokey-titleword-case-convert-function 'identity)
9553 (bibtex-autokey-titleword-length 'infty)
9554 (bibtex-autokey-year-title-separator ": "))
9555 (setq description (bibtex-generate-autokey)))
9556 ;; Now parse the entry, get the key and return it.
9557 (save-excursion
9558 (bibtex-beginning-of-entry)
9559 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9560
9561 (defun org-execute-file-search-in-bibtex (s)
9562 "Find the link search string S as a key for a database entry."
9563 (when (eq major-mode 'bibtex-mode)
9564 ;; Yes, we want to do the search in this file.
9565 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9566 (goto-char (point-min))
9567 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9568 (regexp-quote s) "[ \t\n]*,") nil t)
9569 (goto-char (match-beginning 0)))
9570 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9571 ;; Use double prefix to indicate that any web link should be browsed
9572 (let ((b (current-buffer)) (p (point)))
9573 ;; Restore the window configuration because we just use the web link
9574 (set-window-configuration org-window-config-before-follow-link)
9575 (save-excursion (set-buffer b) (goto-char p)
9576 (bibtex-url)))
9577 (recenter 0)) ; Move entry start to beginning of window
9578 ;; return t to indicate that the search is done.
9579 t))
9580
9581 ;; Finally add the functions to the right hooks.
9582 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
9583 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
9584
9585 ;; end of Bibtex link setup
9586
9587 (defun org-upgrade-old-links (&optional query-description)
9588 "Transfer old <...> style links to new [[...]] style links.
9589 With arg query-description, ask at each match for a description text to use
9590 for this link."
9591 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
9592 (save-excursion
9593 (goto-char (point-min))
9594 (let ((re (concat "\\([^[]\\)<\\("
9595 "\\(" (mapconcat 'identity org-link-types "\\|")
9596 "\\):"
9597 "[^" org-non-link-chars "]+\\)>"))
9598 l1 l2 (cnt 0))
9599 (while (re-search-forward re nil t)
9600 (setq cnt (1+ cnt)
9601 l1 (org-match-string-no-properties 2)
9602 l2 (save-match-data (org-link-escape l1)))
9603 (when query-description (setq l1 (read-string "Desc: " l1)))
9604 (if (equal l1 l2)
9605 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
9606 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
9607 (message "%d matches have beed treated" cnt))))
9608
9609 (defun org-open-file (path &optional in-emacs line search)
9610 "Open the file at PATH.
9611 First, this expands any special file name abbreviations. Then the
9612 configuration variable `org-file-apps' is checked if it contains an
9613 entry for this file type, and if yes, the corresponding command is launched.
9614 If no application is found, Emacs simply visits the file.
9615 With optional argument IN-EMACS, Emacs will visit the file.
9616 Optional LINE specifies a line to go to, optional SEARCH a string to
9617 search for. If LINE or SEARCH is given, the file will always be
9618 opened in Emacs.
9619 If the file does not exist, an error is thrown."
9620 (setq in-emacs (or in-emacs line search))
9621 (let* ((file (if (equal path "")
9622 buffer-file-name
9623 path))
9624 (apps (append org-file-apps (org-default-apps)))
9625 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9626 (dirp (if remp nil (file-directory-p file)))
9627 (dfile (downcase file))
9628 (old-buffer (current-buffer))
9629 (old-pos (point))
9630 (old-mode major-mode)
9631 ext cmd)
9632 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9633 (setq ext (match-string 1 dfile))
9634 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9635 (setq ext (match-string 1 dfile))))
9636 (if in-emacs
9637 (setq cmd 'emacs)
9638 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9639 (and dirp (cdr (assoc 'directory apps)))
9640 (cdr (assoc ext apps))
9641 (cdr (assoc t apps)))))
9642 (when (eq cmd 'mailcap)
9643 (require 'mailcap)
9644 (mailcap-parse-mailcaps)
9645 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9646 (command (mailcap-mime-info mime-type)))
9647 (if (stringp command)
9648 (setq cmd command)
9649 (setq cmd 'emacs))))
9650 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
9651 (not (file-exists-p file))
9652 (not org-open-non-existing-files))
9653 (error "No such file: %s" file))
9654 (cond
9655 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9656 ;; Normalize use of quote, this can vary.
9657 (if (string-match "['\"]%s['\"]" cmd)
9658 (setq cmd (replace-match "'%s'" t t cmd)))
9659 (setq cmd (format cmd file))
9660 (save-window-excursion
9661 (shell-command (concat cmd " &"))))
9662 ((or (stringp cmd)
9663 (eq cmd 'emacs))
9664 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
9665 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
9666 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9667 (if line (goto-line line)
9668 (if search (org-link-search search))))
9669 ((consp cmd)
9670 (eval cmd))
9671 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9672 (and (org-mode-p) (eq old-mode 'org-mode)
9673 (or (not (equal old-buffer (current-buffer)))
9674 (not (equal old-pos (point))))
9675 (org-mark-ring-push old-pos old-buffer))))
9676
9677 (defun org-default-apps ()
9678 "Return the default applications for this operating system."
9679 (cond
9680 ((eq system-type 'darwin)
9681 org-file-apps-defaults-macosx)
9682 ((eq system-type 'windows-nt)
9683 org-file-apps-defaults-windowsnt)
9684 (t org-file-apps-defaults-gnu)))
9685
9686 (defun org-expand-file-name (path)
9687 "Replace special path abbreviations and expand the file name."
9688 (expand-file-name path))
9689
9690 (defun org-file-remote-p (file)
9691 "Test whether FILE specifies a location on a remote system.
9692 Return non-nil if the location is indeed remote.
9693
9694 For example, the filename \"/user@host:/foo\" specifies a location
9695 on the system \"/user@host:\"."
9696 (cond ((fboundp 'file-remote-p)
9697 (file-remote-p file))
9698 ((fboundp 'tramp-handle-file-remote-p)
9699 (tramp-handle-file-remote-p file))
9700 ((and (boundp 'ange-ftp-name-format)
9701 (string-match ange-ftp-name-format file))
9702 t)
9703 (t nil)))
9704
9705 (defvar org-insert-link-history nil
9706 "Minibuffer history for links inserted with `org-insert-link'.")
9707
9708 (defvar org-stored-links nil
9709 "Contains the links stored with `org-store-link'.")
9710
9711 ;;;###autoload
9712 (defun org-store-link (arg)
9713 "\\<org-mode-map>Store an org-link to the current location.
9714 This link can later be inserted into an org-buffer with
9715 \\[org-insert-link].
9716 For some link types, a prefix arg is interpreted:
9717 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9718 For file links, arg negates `org-context-in-file-links'."
9719 (interactive "P")
9720 (let (link cpltxt desc description search txt (pos (point)))
9721 (cond
9722
9723 ((eq major-mode 'bbdb-mode)
9724 (setq cpltxt (concat
9725 "bbdb:"
9726 (or (bbdb-record-name (bbdb-current-record))
9727 (bbdb-record-company (bbdb-current-record))))
9728 link (org-make-link cpltxt)))
9729
9730 ((eq major-mode 'Info-mode)
9731 (setq link (org-make-link "info:"
9732 (file-name-nondirectory Info-current-file)
9733 ":" Info-current-node))
9734 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9735 ":" Info-current-node)))
9736
9737 ((eq major-mode 'calendar-mode)
9738 (let ((cd (calendar-cursor-to-date)))
9739 (setq link
9740 (format-time-string
9741 (car org-time-stamp-formats)
9742 (apply 'encode-time
9743 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9744 nil nil nil))))))
9745
9746 ((or (eq major-mode 'vm-summary-mode)
9747 (eq major-mode 'vm-presentation-mode))
9748 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9749 (vm-follow-summary-cursor)
9750 (save-excursion
9751 (vm-select-folder-buffer)
9752 (let* ((message (car vm-message-pointer))
9753 (folder buffer-file-name)
9754 (subject (vm-su-subject message))
9755 (author (vm-su-full-name message))
9756 (message-id (vm-su-message-id message)))
9757 (setq message-id (org-remove-angle-brackets message-id))
9758 (setq folder (abbreviate-file-name folder))
9759 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9760 folder)
9761 (setq folder (replace-match "" t t folder)))
9762 (setq cpltxt (concat author " on: " subject))
9763 (setq link (org-make-link "vm:" folder "#" message-id)))))
9764
9765 ((eq major-mode 'wl-summary-mode)
9766 (let* ((msgnum (wl-summary-message-number))
9767 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9768 msgnum 'message-id))
9769 (wl-message-entity (elmo-msgdb-overview-get-entity
9770 msgnum (wl-summary-buffer-msgdb)))
9771 (author (wl-summary-line-from)) ; FIXME: correct?
9772 (subject "???")) ; FIXME:
9773 (setq message-id (org-remove-angle-brackets message-id))
9774 (setq cpltxt (concat author " on: " subject))
9775 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9776 "#" message-id))))
9777
9778 ((or (equal major-mode 'mh-folder-mode)
9779 (equal major-mode 'mh-show-mode))
9780 (let ((from-header (org-mhe-get-header "From:"))
9781 (to-header (org-mhe-get-header "To:"))
9782 (subject (org-mhe-get-header "Subject:")))
9783 (setq cpltxt (concat from-header " on: " subject))
9784 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9785 (org-remove-angle-brackets
9786 (org-mhe-get-header "Message-Id:"))))))
9787
9788 ((eq major-mode 'rmail-mode)
9789 (save-excursion
9790 (save-restriction
9791 (rmail-narrow-to-non-pruned-header)
9792 (let ((folder buffer-file-name)
9793 (message-id (mail-fetch-field "message-id"))
9794 (author (mail-fetch-field "from"))
9795 (subject (mail-fetch-field "subject")))
9796 (setq message-id (org-remove-angle-brackets message-id))
9797 (setq cpltxt (concat author " on: " subject))
9798 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9799
9800 ((eq major-mode 'gnus-group-mode)
9801 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9802 (gnus-group-group-name)) ; version
9803 ((fboundp 'gnus-group-name)
9804 (gnus-group-name))
9805 (t "???"))))
9806 (setq cpltxt (concat
9807 (if (org-xor arg org-usenet-links-prefer-google)
9808 "http://groups.google.com/groups?group="
9809 "gnus:")
9810 group)
9811 link (org-make-link cpltxt))))
9812
9813 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9814 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9815 (gnus-summary-beginning-of-article)
9816 (let* ((group (car gnus-article-current))
9817 (article (cdr gnus-article-current))
9818 (header (gnus-summary-article-header article))
9819 (author (mail-header-from header))
9820 (message-id (mail-header-id header))
9821 (date (mail-header-date header))
9822 (subject (gnus-summary-subject-string)))
9823 (setq cpltxt (concat author " on: " subject))
9824 (if (org-xor arg org-usenet-links-prefer-google)
9825 (setq link
9826 (concat
9827 cpltxt "\n "
9828 (format "http://groups.google.com/groups?as_umsgid=%s"
9829 (org-fixup-message-id-for-http message-id))))
9830 (setq link (org-make-link "gnus:" group
9831 "#" (number-to-string article))))))
9832
9833 ((eq major-mode 'w3-mode)
9834 (setq cpltxt (url-view-url t)
9835 link (org-make-link cpltxt)))
9836 ((eq major-mode 'w3m-mode)
9837 (setq cpltxt (or w3m-current-title w3m-current-url)
9838 link (org-make-link w3m-current-url)))
9839
9840 ((setq search (run-hook-with-args-until-success
9841 'org-create-file-search-functions))
9842 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9843 "::" search))
9844 (setq cpltxt (or description link)))
9845
9846 ((eq major-mode 'image-mode)
9847 (setq cpltxt (concat "file:"
9848 (abbreviate-file-name buffer-file-name))
9849 link (org-make-link cpltxt)))
9850
9851 ((org-mode-p)
9852 ;; Just link to current headline
9853 (setq cpltxt (concat "file:"
9854 (abbreviate-file-name buffer-file-name)))
9855 ;; Add a context search string
9856 (when (org-xor org-context-in-file-links arg)
9857 ;; Check if we are on a target
9858 (if (save-excursion
9859 (skip-chars-forward "^>\n\r")
9860 (and (re-search-backward "<<" nil t)
9861 (looking-at "<<\\(.*?\\)>>")
9862 (<= (match-beginning 0) pos)
9863 (>= (match-end 0) pos)))
9864 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9865 (setq txt (cond
9866 ((org-on-heading-p) nil)
9867 ((org-region-active-p)
9868 (buffer-substring (region-beginning) (region-end)))
9869 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9870 (when (or (null txt) (string-match "\\S-" txt))
9871 (setq cpltxt
9872 (concat cpltxt "::"
9873 (if org-file-link-context-use-camel-case
9874 (org-make-org-heading-camel txt)
9875 (org-make-org-heading-search-string txt)))
9876 desc "NONE"))))
9877 (if (string-match "::\\'" cpltxt)
9878 (setq cpltxt (substring cpltxt 0 -2)))
9879 (setq link (org-make-link cpltxt)))
9880
9881 (buffer-file-name
9882 ;; Just link to this file here.
9883 (setq cpltxt (concat "file:"
9884 (abbreviate-file-name buffer-file-name)))
9885 ;; Add a context string
9886 (when (org-xor org-context-in-file-links arg)
9887 (setq txt (if (org-region-active-p)
9888 (buffer-substring (region-beginning) (region-end))
9889 (buffer-substring (point-at-bol) (point-at-eol))))
9890 ;; Only use search option if there is some text.
9891 (when (string-match "\\S-" txt)
9892 (setq cpltxt
9893 (concat cpltxt "::"
9894 (if org-file-link-context-use-camel-case
9895 (org-make-org-heading-camel txt)
9896 (org-make-org-heading-search-string txt)))
9897 desc "NONE")))
9898 (setq link (org-make-link cpltxt)))
9899
9900 ((interactive-p)
9901 (error "Cannot link to a buffer which is not visiting a file"))
9902
9903 (t (setq link nil)))
9904
9905 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9906 (setq link (or link cpltxt)
9907 desc (or desc cpltxt))
9908 (if (equal desc "NONE") (setq desc nil))
9909
9910 (if (and (interactive-p) link)
9911 (progn
9912 (setq org-stored-links
9913 (cons (list cpltxt link desc) org-stored-links))
9914 (message "Stored: %s" (or cpltxt link)))
9915 (org-make-link-string link desc))))
9916
9917 (defun org-make-org-heading-search-string (&optional string heading)
9918 "Make search string for STRING or current headline."
9919 (interactive)
9920 (let ((s (or string (org-get-heading))))
9921 (unless (and string (not heading))
9922 ;; We are using a headline, clean up garbage in there.
9923 (if (string-match org-todo-regexp s)
9924 (setq s (replace-match "" t t s)))
9925 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9926 (setq s (replace-match "" t t s)))
9927 (setq s (org-trim s))
9928 (if (string-match (concat "^\\(" org-quote-string "\\|"
9929 org-comment-string "\\)") s)
9930 (setq s (replace-match "" t t s)))
9931 (while (string-match org-ts-regexp s)
9932 (setq s (replace-match "" t t s))))
9933 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
9934 (setq s (replace-match " " t t s)))
9935 (or string (setq s (concat "*" s))) ; Add * for headlines
9936 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9937
9938 (defun org-make-org-heading-camel (&optional string heading)
9939 "Make a CamelCase string for STRING or the current headline."
9940 (interactive)
9941 (let ((s (or string (org-get-heading))))
9942 (unless (and string (not heading))
9943 ;; We are using a headline, clean up garbage in there.
9944 (if (string-match org-todo-regexp s)
9945 (setq s (replace-match "" t t s)))
9946 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9947 (setq s (replace-match "" t t s)))
9948 (setq s (org-trim s))
9949 (if (string-match (concat "^\\(" org-quote-string "\\|"
9950 org-comment-string "\\)") s)
9951 (setq s (replace-match "" t t s)))
9952 (while (string-match org-ts-regexp s)
9953 (setq s (replace-match "" t t s))))
9954 (while (string-match "[^a-zA-Z_ \t]+" s)
9955 (setq s (replace-match " " t t s)))
9956 (or string (setq s (concat "*" s))) ; Add * for headlines
9957 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
9958
9959 (defun org-make-link (&rest strings)
9960 "Concatenate STRINGS, format resulting string with `org-link-format'."
9961 (format org-link-format (apply 'concat strings)))
9962
9963 (defun org-make-link-string (link &optional description)
9964 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9965 (if (eq org-link-style 'plain)
9966 (if (equal description link)
9967 link
9968 (concat description "\n" link))
9969 (when (stringp description)
9970 ;; Remove brackets from the description, they are fatal.
9971 (while (string-match "\\[\\|\\]" description)
9972 (setq description (replace-match "" t t description))))
9973 (when (equal (org-link-escape link) description)
9974 ;; No description needed, it is identical
9975 (setq description nil))
9976 (when (and (not description)
9977 (not (equal link (org-link-escape link))))
9978 (setq description link))
9979 (concat "[[" (org-link-escape link) "]"
9980 (if description (concat "[" description "]") "")
9981 "]")))
9982
9983 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
9984 "Association list of escapes for some characters problematic in links.")
9985
9986 (defun org-link-escape (text)
9987 "Escape charaters in TEXT that are problematic for links."
9988 (when text
9989 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
9990 org-link-escape-chars "\\|")))
9991 (while (string-match re text)
9992 (setq text
9993 (replace-match
9994 (cdr (assoc (match-string 0 text) org-link-escape-chars))
9995 t t text)))
9996 text)))
9997
9998 (defun org-link-unescape (text)
9999 "Reverse the action of `org-link-escape'."
10000 (when text
10001 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10002 org-link-escape-chars "\\|")))
10003 (while (string-match re text)
10004 (setq text
10005 (replace-match
10006 (car (rassoc (match-string 0 text) org-link-escape-chars))
10007 t t text)))
10008 text)))
10009
10010 (defun org-xor (a b)
10011 "Exclusive or."
10012 (if a (not b) b))
10013
10014 (defun org-get-header (header)
10015 "Find a header field in the current buffer."
10016 (save-excursion
10017 (goto-char (point-min))
10018 (let ((case-fold-search t) s)
10019 (cond
10020 ((eq header 'from)
10021 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10022 (setq s (match-string 1)))
10023 (while (string-match "\"" s)
10024 (setq s (replace-match "" t t s)))
10025 (if (string-match "[<(].*" s)
10026 (setq s (replace-match "" t t s))))
10027 ((eq header 'message-id)
10028 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10029 (setq s (match-string 1))))
10030 ((eq header 'subject)
10031 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10032 (setq s (match-string 1)))))
10033 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10034 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10035 s)))
10036
10037
10038 (defun org-fixup-message-id-for-http (s)
10039 "Replace special characters in a message id, so it can be used in an http query."
10040 (while (string-match "<" s)
10041 (setq s (replace-match "%3C" t t s)))
10042 (while (string-match ">" s)
10043 (setq s (replace-match "%3E" t t s)))
10044 (while (string-match "@" s)
10045 (setq s (replace-match "%40" t t s)))
10046 s)
10047
10048 (defun org-insert-link (&optional complete-file)
10049 "Insert a link. At the prompt, enter the link.
10050
10051 Completion can be used to select a link previously stored with
10052 `org-store-link'. When the empty string is entered (i.e. if you just
10053 press RET at the prompt), the link defaults to the most recently
10054 stored link. As SPC triggers completion in the minibuffer, you need to
10055 use M-SPC or C-q SPC to force the insertion of a space character.
10056
10057 You will also be prompted for a description, and if one is given, it will
10058 be displayed in the buffer instead of the link.
10059
10060 If there is already a link at point, this command will allow you to edit link
10061 and description parts.
10062
10063 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10064 selected using completion. The path to the file will be relative to
10065 the current directory if the file is in the current directory or a
10066 subdirectory. Otherwise, the link will be the absolute path as
10067 completed in the minibuffer (i.e. normally ~/path/to/file).
10068
10069 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10070 is in the current directory or below.
10071 With three \\[universal-argument] prefixes, negate the meaning of
10072 `org-keep-stored-link-after-insertion'."
10073 (interactive "P")
10074 (let (link desc entry remove file (pos (point)))
10075 (cond
10076 ((save-excursion
10077 (skip-chars-forward "^]\n\r")
10078 (and (re-search-backward "\\[\\[" nil t)
10079 (looking-at org-bracket-link-regexp)
10080 (<= (match-beginning 0) pos)
10081 (>= (match-end 0) pos)))
10082 ;; We do have a link at point, and we are going to edit it.
10083 (setq remove (list (match-beginning 0) (match-end 0)))
10084 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10085 (setq link (read-string "Link: "
10086 (org-link-unescape
10087 (org-match-string-no-properties 1)))))
10088 ((equal complete-file '(4))
10089 ;; Completing read for file names.
10090 (setq file (read-file-name "File: "))
10091 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10092 (pwd1 (file-name-as-directory (abbreviate-file-name
10093 (expand-file-name ".")))))
10094 (cond
10095 ((equal complete-file '(16))
10096 (setq link (org-make-link
10097 "file:"
10098 (abbreviate-file-name (expand-file-name file)))))
10099 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10100 (setq link (org-make-link "file:" (match-string 1 file))))
10101 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10102 (expand-file-name file))
10103 (setq link (org-make-link
10104 "file:" (match-string 1 (expand-file-name file)))))
10105 (t (setq link (org-make-link "file:" file))))))
10106 (t
10107 ;; Read link, with completion for stored links.
10108 (setq link (org-completing-read
10109 "Link: " org-stored-links nil nil nil
10110 org-insert-link-history
10111 (or (car (car org-stored-links)))))
10112 (setq entry (assoc link org-stored-links))
10113 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10114 (not org-keep-stored-link-after-insertion))
10115 (setq org-stored-links (delq (assoc link org-stored-links)
10116 org-stored-links)))
10117 (setq link (if entry (nth 1 entry) link)
10118 desc (or desc (nth 2 entry)))))
10119
10120 (if (string-match org-plain-link-re link)
10121 ;; URL-like link, normalize the use of angular brackets.
10122 (setq link (org-make-link (org-remove-angle-brackets link))))
10123
10124 ;; Check if we are linking to the current file with a search option
10125 ;; If yes, simplify the link by using only the search option.
10126 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
10127 (let* ((path (match-string 1 link))
10128 (case-fold-search nil)
10129 (search (match-string 2 link)))
10130 (save-match-data
10131 (if (equal (file-truename buffer-file-name) (file-truename path))
10132 ;; We are linking to this same file, with a search option
10133 (setq link search)))))
10134
10135 ;; Check if we can/should use a relative path. If yes, simplify the link
10136 (when (string-match "\\<file:\\(.*\\)" link)
10137 (let* ((path (match-string 1 link))
10138 (case-fold-search nil))
10139 (cond
10140 ((eq org-link-file-path-type 'absolute)
10141 (setq path (abbreviate-file-name (expand-file-name path))))
10142 ((eq org-link-file-path-type 'noabbrev)
10143 (setq path (expand-file-name path)))
10144 ((eq org-link-file-path-type 'relative)
10145 (setq path (file-relative-name path)))
10146 (t
10147 (save-match-data
10148 (if (string-match (concat "^" (regexp-quote
10149 (file-name-as-directory
10150 (expand-file-name "."))))
10151 (expand-file-name path))
10152 ;; We are linking a file with relative path name.
10153 (setq path (substring (expand-file-name path)
10154 (match-end 0)))))))
10155 (setq link (concat "file:" path))))
10156
10157 (setq desc (read-string "Description: " desc))
10158 (unless (string-match "\\S-" desc) (setq desc nil))
10159 (if remove (apply 'delete-region remove))
10160 (insert (org-make-link-string link desc))))
10161
10162 (defun org-completing-read (&rest args)
10163 (let ((minibuffer-local-completion-map
10164 (copy-keymap minibuffer-local-completion-map)))
10165 (define-key minibuffer-local-completion-map " " 'self-insert-command)
10166 (apply 'completing-read args)))
10167
10168 ;;; Hooks for remember.el
10169
10170 (defvar org-finish-function nil)
10171
10172 ;;;###autoload
10173 (defun org-remember-annotation ()
10174 "Return a link to the current location as an annotation for remember.el.
10175 If you are using Org-mode files as target for data storage with
10176 remember.el, then the annotations should include a link compatible with the
10177 conventions in Org-mode. This function returns such a link."
10178 (org-store-link nil))
10179
10180 (defconst org-remember-help
10181 "Select a destination location for the note.
10182 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10183 RET at beg-of-buf -> Append to file as level 2 headline
10184 RET on headline -> Store as sublevel entry to current headline
10185 <left>/<right> -> before/after current headline, same headings level")
10186
10187 ;;;###autoload
10188 (defun org-remember-apply-template ()
10189 "Initialize *remember* buffer with template, invoke `org-mode'.
10190 This function should be placed into `remember-mode-hook' and in fact requires
10191 to be run from that hook to fucntion properly."
10192 (if org-remember-templates
10193
10194 (let* ((entry (if (= (length org-remember-templates) 1)
10195 (cdar org-remember-templates)
10196 (message "Select template: %s"
10197 (mapconcat
10198 (lambda (x) (char-to-string (car x)))
10199 org-remember-templates " "))
10200 (cdr (assoc (read-char-exclusive) org-remember-templates))))
10201 (tpl (car entry))
10202 (file (if (consp (cdr entry)) (nth 1 entry)))
10203 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10204 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10205 (v-u (concat "[" (substring v-t 1 -1) "]"))
10206 (v-U (concat "[" (substring v-T 1 -1) "]"))
10207 (v-a annotation) ; defined in `remember-mode'
10208 (v-i initial) ; defined in `remember-mode'
10209 (v-n user-full-name)
10210 )
10211 (unless tpl (setq tpl "") (message "No template") (ding))
10212 (insert tpl) (goto-char (point-min))
10213 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
10214 (when (and initial (equal (match-string 0) "%i"))
10215 (save-match-data
10216 (let* ((lead (buffer-substring
10217 (point-at-bol) (match-beginning 0))))
10218 (setq v-i (mapconcat 'identity
10219 (org-split-string initial "\n")
10220 (concat "\n" lead))))))
10221 (replace-match
10222 (or (eval (intern (concat "v-" (match-string 1)))) "")
10223 t t))
10224 (let ((org-startup-folded nil)
10225 (org-startup-with-deadline-check nil))
10226 (org-mode))
10227 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10228 (set (make-local-variable 'org-default-notes-file) file))
10229 (goto-char (point-min))
10230 (if (re-search-forward "%\\?" nil t) (replace-match "")))
10231 (let ((org-startup-folded nil)
10232 (org-startup-with-deadline-check nil))
10233 (org-mode)))
10234 (set (make-local-variable 'org-finish-function) 'remember-buffer))
10235
10236 ;;;###autoload
10237 (defun org-remember-handler ()
10238 "Store stuff from remember.el into an org file.
10239 First prompts for an org file. If the user just presses return, the value
10240 of `org-default-notes-file' is used.
10241 Then the command offers the headings tree of the selected file in order to
10242 file the text at a specific location.
10243 You can either immediately press RET to get the note appended to the
10244 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10245 find a better place. Then press RET or <left> or <right> in insert the note.
10246
10247 Key Cursor position Note gets inserted
10248 -----------------------------------------------------------------------------
10249 RET buffer-start as level 2 heading at end of file
10250 RET on headline as sublevel of the heading at cursor
10251 RET no heading at cursor position, level taken from context.
10252 Or use prefix arg to specify level manually.
10253 <left> on headline as same level, before current heading
10254 <right> on headline as same level, after current heading
10255
10256 So the fastest way to store the note is to press RET RET to append it to
10257 the default file. This way your current train of thought is not
10258 interrupted, in accordance with the principles of remember.el. But with
10259 little extra effort, you can push it directly to the correct location.
10260
10261 Before being stored away, the function ensures that the text has a
10262 headline, i.e. a first line that starts with a \"*\". If not, a headline
10263 is constructed from the current date and some additional data.
10264
10265 If the variable `org-adapt-indentation' is non-nil, the entire text is
10266 also indented so that it starts in the same column as the headline
10267 \(i.e. after the stars).
10268
10269 See also the variable `org-reverse-note-order'."
10270 (catch 'quit
10271 (let* ((txt (buffer-substring (point-min) (point-max)))
10272 (fastp current-prefix-arg)
10273 (file (if fastp org-default-notes-file (org-get-org-file)))
10274 (visiting (find-buffer-visiting file))
10275 (org-startup-with-deadline-check nil)
10276 (org-startup-folded nil)
10277 (org-startup-align-all-tables nil)
10278 spos level indent reversed)
10279 ;; Modify text so that it becomes a nice subtree which can be inserted
10280 ;; into an org tree.
10281 (let* ((lines (split-string txt "\n"))
10282 first)
10283 ;; remove empty lines at the beginning
10284 (while (and lines (string-match "^[ \t]*\n" (car lines)))
10285 (setq lines (cdr lines)))
10286 (setq first (car lines) lines (cdr lines))
10287 (if (string-match "^\\*+" first)
10288 ;; Is already a headline
10289 (setq indent nil)
10290 ;; We need to add a headline: Use time and first buffer line
10291 (setq lines (cons first lines)
10292 first (concat "* " (current-time-string)
10293 " (" (remember-buffer-desc) ")")
10294 indent " "))
10295 (if (and org-adapt-indentation indent)
10296 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10297 (setq txt (concat first "\n"
10298 (mapconcat 'identity lines "\n"))))
10299 ;; Find the file
10300 (if (not visiting)
10301 (find-file-noselect file))
10302 (with-current-buffer (get-file-buffer file)
10303 (save-excursion (and (goto-char (point-min))
10304 (not (re-search-forward "^\\* " nil t))
10305 (insert "\n* Notes\n")))
10306 (setq reversed (org-notes-order-reversed-p))
10307 (save-excursion
10308 (save-restriction
10309 (widen)
10310 ;; Ask the User for a location
10311 (setq spos (if fastp 1 (org-get-location
10312 (current-buffer)
10313 org-remember-help)))
10314 (if (not spos) (throw 'quit nil)) ; return nil to show we did
10315 ; not handle this note
10316 (goto-char spos)
10317 (cond ((bobp)
10318 ;; Put it at the start or end, as level 2
10319 (save-restriction
10320 (widen)
10321 (goto-char (if reversed (point-min) (point-max)))
10322 (if (not (bolp)) (newline))
10323 (org-paste-subtree 2 txt)))
10324 ((and (org-on-heading-p nil) (not current-prefix-arg))
10325 ;; Put it below this entry, at the beg/end of the subtree
10326 (org-back-to-heading)
10327 (setq level (funcall outline-level))
10328 (if reversed
10329 (outline-end-of-heading)
10330 (outline-end-of-subtree))
10331 (if (not (bolp)) (newline))
10332 (beginning-of-line 1)
10333 (org-paste-subtree (1+ level) txt))
10334 (t
10335 ;; Put it right there, with automatic level determined by
10336 ;; org-paste-subtree or from prefix arg
10337 (org-paste-subtree current-prefix-arg txt)))
10338 (when remember-save-after-remembering
10339 (save-buffer)
10340 (if (not visiting) (kill-buffer (current-buffer)))))))))
10341 t) ;; return t to indicate that we took care of this note.
10342
10343 (defun org-get-org-file ()
10344 "Read a filename, with default directory `org-directory'."
10345 (let ((default (or org-default-notes-file remember-data-file)))
10346 (read-file-name (format "File name [%s]: " default)
10347 (file-name-as-directory org-directory)
10348 default)))
10349
10350 (defun org-notes-order-reversed-p ()
10351 "Check if the current file should receive notes in reversed order."
10352 (cond
10353 ((not org-reverse-note-order) nil)
10354 ((eq t org-reverse-note-order) t)
10355 ((not (listp org-reverse-note-order)) nil)
10356 (t (catch 'exit
10357 (let ((all org-reverse-note-order)
10358 entry)
10359 (while (setq entry (pop all))
10360 (if (string-match (car entry) buffer-file-name)
10361 (throw 'exit (cdr entry))))
10362 nil)))))
10363
10364 ;;; Tables
10365
10366 ;; Watch out: Here we are talking about two different kind of tables.
10367 ;; Most of the code is for the tables created with the Org-mode table editor.
10368 ;; Sometimes, we talk about tables created and edited with the table.el
10369 ;; Emacs package. We call the former org-type tables, and the latter
10370 ;; table.el-type tables.
10371
10372
10373 (defun org-before-change-function (beg end)
10374 "Every change indicates that a table might need an update."
10375 (setq org-table-may-need-update t))
10376
10377 (defconst org-table-line-regexp "^[ \t]*|"
10378 "Detects an org-type table line.")
10379 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
10380 "Detects an org-type table line.")
10381 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
10382 "Detects a table line marked for automatic recalculation.")
10383 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
10384 "Detects a table line marked for automatic recalculation.")
10385 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
10386 "Detects a table line marked for automatic recalculation.")
10387 (defconst org-table-hline-regexp "^[ \t]*|-"
10388 "Detects an org-type table hline.")
10389 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
10390 "Detects a table-type table hline.")
10391 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
10392 "Detects an org-type or table-type table.")
10393 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
10394 "Searching from within a table (any type) this finds the first line
10395 outside the table.")
10396 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
10397 "Searching from within a table (any type) this finds the first line
10398 outside the table.")
10399
10400 (defun org-table-create-with-table.el ()
10401 "Use the table.el package to insert a new table.
10402 If there is already a table at point, convert between Org-mode tables
10403 and table.el tables."
10404 (interactive)
10405 (require 'table)
10406 (cond
10407 ((org-at-table.el-p)
10408 (if (y-or-n-p "Convert table to Org-mode table? ")
10409 (org-table-convert)))
10410 ((org-at-table-p)
10411 (if (y-or-n-p "Convert table to table.el table? ")
10412 (org-table-convert)))
10413 (t (call-interactively 'table-insert))))
10414
10415 (defun org-table-create-or-convert-from-region (arg)
10416 "Convert region to table, or create an empty table.
10417 If there is an active region, convert it to a table. If there is no such
10418 region, create an empty table."
10419 (interactive "P")
10420 (if (org-region-active-p)
10421 (org-table-convert-region (region-beginning) (region-end) arg)
10422 (org-table-create arg)))
10423
10424 (defun org-table-create (&optional size)
10425 "Query for a size and insert a table skeleton.
10426 SIZE is a string Columns x Rows like for example \"3x2\"."
10427 (interactive "P")
10428 (unless size
10429 (setq size (read-string
10430 (concat "Table size Columns x Rows [e.g. "
10431 org-table-default-size "]: ")
10432 "" nil org-table-default-size)))
10433
10434 (let* ((pos (point))
10435 (indent (make-string (current-column) ?\ ))
10436 (split (org-split-string size " *x *"))
10437 (rows (string-to-number (nth 1 split)))
10438 (columns (string-to-number (car split)))
10439 (line (concat (apply 'concat indent "|" (make-list columns " |"))
10440 "\n")))
10441 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
10442 (point-at-bol) (point)))
10443 (beginning-of-line 1)
10444 (newline))
10445 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
10446 (dotimes (i rows) (insert line))
10447 (goto-char pos)
10448 (if (> rows 1)
10449 ;; Insert a hline after the first row.
10450 (progn
10451 (end-of-line 1)
10452 (insert "\n|-")
10453 (goto-char pos)))
10454 (org-table-align)))
10455
10456 (defun org-table-convert-region (beg0 end0 &optional nspace)
10457 "Convert region to a table.
10458 The region goes from BEG0 to END0, but these borders will be moved
10459 slightly, to make sure a beginning of line in the first line is included.
10460 When NSPACE is non-nil, it indicates the minimum number of spaces that
10461 separate columns (default: just one space)."
10462 (interactive "rP")
10463 (let* ((beg (min beg0 end0))
10464 (end (max beg0 end0))
10465 (tabsep t)
10466 re)
10467 (goto-char beg)
10468 (beginning-of-line 1)
10469 (setq beg (move-marker (make-marker) (point)))
10470 (goto-char end)
10471 (if (bolp) (backward-char 1) (end-of-line 1))
10472 (setq end (move-marker (make-marker) (point)))
10473 ;; Lets see if this is tab-separated material. If every nonempty line
10474 ;; contains a tab, we will assume that it is tab-separated material
10475 (if nspace
10476 (setq tabsep nil)
10477 (goto-char beg)
10478 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
10479 (if nspace (setq tabsep nil))
10480 (if tabsep
10481 (setq re "^\\|\t")
10482 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
10483 (max 1 (prefix-numeric-value nspace)))))
10484 (goto-char beg)
10485 (while (re-search-forward re end t)
10486 (replace-match "|" t t))
10487 (goto-char beg)
10488 (insert " ")
10489 (org-table-align)))
10490
10491 (defun org-table-import (file arg)
10492 "Import FILE as a table.
10493 The file is assumed to be tab-separated. Such files can be produced by most
10494 spreadsheet and database applications. If no tabs (at least one per line)
10495 are found, lines will be split on whitespace into fields."
10496 (interactive "f\nP")
10497 (or (bolp) (newline))
10498 (let ((beg (point))
10499 (pm (point-max)))
10500 (insert-file-contents file)
10501 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
10502
10503 (defun org-table-export ()
10504 "Export table as a tab-separated file.
10505 Such a file can be imported into a spreadsheet program like Excel."
10506 (interactive)
10507 (let* ((beg (org-table-begin))
10508 (end (org-table-end))
10509 (table (buffer-substring beg end))
10510 (file (read-file-name "Export table to: "))
10511 buf)
10512 (unless (or (not (file-exists-p file))
10513 (y-or-n-p (format "Overwrite file %s? " file)))
10514 (error "Abort"))
10515 (with-current-buffer (find-file-noselect file)
10516 (setq buf (current-buffer))
10517 (erase-buffer)
10518 (fundamental-mode)
10519 (insert table)
10520 (goto-char (point-min))
10521 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
10522 (replace-match "" t t)
10523 (end-of-line 1))
10524 (goto-char (point-min))
10525 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
10526 (replace-match "" t t)
10527 (goto-char (min (1+ (point)) (point-max))))
10528 (goto-char (point-min))
10529 (while (re-search-forward "^-[-+]*$" nil t)
10530 (replace-match "")
10531 (if (looking-at "\n")
10532 (delete-char 1)))
10533 (goto-char (point-min))
10534 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
10535 (replace-match "\t" t t))
10536 (save-buffer))
10537 (kill-buffer buf)))
10538
10539 (defvar org-table-aligned-begin-marker (make-marker)
10540 "Marker at the beginning of the table last aligned.
10541 Used to check if cursor still is in that table, to minimize realignment.")
10542 (defvar org-table-aligned-end-marker (make-marker)
10543 "Marker at the end of the table last aligned.
10544 Used to check if cursor still is in that table, to minimize realignment.")
10545 (defvar org-table-last-alignment nil
10546 "List of flags for flushright alignment, from the last re-alignment.
10547 This is being used to correctly align a single field after TAB or RET.")
10548 (defvar org-table-last-column-widths nil
10549 "List of max width of fields in each column.
10550 This is being used to correctly align a single field after TAB or RET.")
10551
10552 (defvar org-last-recalc-line nil)
10553 (defconst org-narrow-column-arrow "=>"
10554 "Used as display property in narrowed table columns.")
10555
10556 (defun org-table-align ()
10557 "Align the table at point by aligning all vertical bars."
10558 (interactive)
10559 (let* (
10560 ;; Limits of table
10561 (beg (org-table-begin))
10562 (end (org-table-end))
10563 ;; Current cursor position
10564 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10565 (colpos (org-table-current-column))
10566 (winstart (window-start))
10567 lines (new "") lengths l typenums ty fields maxfields i
10568 column
10569 (indent "") cnt frac
10570 rfmt hfmt
10571 (spaces '(1 . 1))
10572 (sp1 (car spaces))
10573 (sp2 (cdr spaces))
10574 (rfmt1 (concat
10575 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
10576 (hfmt1 (concat
10577 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
10578 emptystrings links narrow fmax f1 len c e)
10579 (untabify beg end)
10580 (remove-text-properties beg end '(org-cwidth t display t))
10581 ;; Check if we have links
10582 (goto-char beg)
10583 (setq links (re-search-forward org-bracket-link-regexp end t))
10584 ;; Make sure the link properties are right
10585 (when links (goto-char beg) (while (org-activate-bracket-links end)))
10586 ;; Check if we are narrowing any columns
10587 (goto-char beg)
10588 (setq narrow (and org-format-transports-properties-p
10589 (re-search-forward "<[0-9]+>" end t)))
10590 ;; Get the rows
10591 (setq lines (org-split-string
10592 (buffer-substring beg end) "\n"))
10593 ;; Store the indentation of the first line
10594 (if (string-match "^ *" (car lines))
10595 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
10596 ;; Mark the hlines by setting the corresponding element to nil
10597 ;; At the same time, we remove trailing space.
10598 (setq lines (mapcar (lambda (l)
10599 (if (string-match "^ *|-" l)
10600 nil
10601 (if (string-match "[ \t]+$" l)
10602 (substring l 0 (match-beginning 0))
10603 l)))
10604 lines))
10605 ;; Get the data fields by splitting the lines.
10606 (setq fields (mapcar
10607 (lambda (l)
10608 (org-split-string l " *| *"))
10609 (delq nil (copy-sequence lines))))
10610 ;; How many fields in the longest line?
10611 (condition-case nil
10612 (setq maxfields (apply 'max (mapcar 'length fields)))
10613 (error
10614 (kill-region beg end)
10615 (org-table-create org-table-default-size)
10616 (error "Empty table - created default table")))
10617 ;; A list of empty string to fill any short rows on output
10618 (setq emptystrings (make-list maxfields ""))
10619 ;; Check for special formatting.
10620 (setq i -1)
10621 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
10622 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
10623 ;; Check if there is an explicit width specified
10624 (when (and org-table-limit-column-width narrow)
10625 (setq c column fmax nil)
10626 (while c
10627 (setq e (pop c))
10628 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
10629 (setq fmax (string-to-number (match-string 1 e)) c nil)))
10630 ;; Find fields that are wider than fmax, and shorten them
10631 (when fmax
10632 (loop for xx in column do
10633 (when (and (stringp xx)
10634 (> (org-string-width xx) fmax))
10635 (org-add-props xx nil
10636 'help-echo
10637 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
10638 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
10639 (unless (> f1 1)
10640 (error "Cannot narrow field starting with wide link \"%s\""
10641 (match-string 0 xx)))
10642 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
10643 (add-text-properties (- f1 2) f1
10644 (list 'display org-narrow-column-arrow)
10645 xx)))))
10646 ;; Get the maximum width for each column
10647 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
10648 ;; Get the fraction of numbers, to decide about alignment of the column
10649 (setq cnt 0 frac 0.0)
10650 (loop for x in column do
10651 (if (equal x "")
10652 nil
10653 (setq frac ( / (+ (* frac cnt)
10654 (if (string-match org-table-number-regexp x) 1 0))
10655 (setq cnt (1+ cnt))))))
10656 (push (>= frac org-table-number-fraction) typenums))
10657 (setq lengths (nreverse lengths) typenums (nreverse typenums))
10658
10659 ;; Store the alignment of this table, for later editing of single fields
10660 (setq org-table-last-alignment typenums
10661 org-table-last-column-widths lengths)
10662
10663 ;; With invisible characters, `format' does not get the field width right
10664 ;; So we need to make these fields wide by hand.
10665 (when links
10666 (loop for i from 0 upto (1- maxfields) do
10667 (setq len (nth i lengths))
10668 (loop for j from 0 upto (1- (length fields)) do
10669 (setq c (nthcdr i (car (nthcdr j fields))))
10670 (if (and (stringp (car c))
10671 (string-match org-bracket-link-regexp (car c))
10672 (< (org-string-width (car c)) len))
10673 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
10674
10675 ;; Compute the formats needed for output of the table
10676 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
10677 (while (setq l (pop lengths))
10678 (setq ty (if (pop typenums) "" "-")) ; number types flushright
10679 (setq rfmt (concat rfmt (format rfmt1 ty l))
10680 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
10681 (setq rfmt (concat rfmt "\n")
10682 hfmt (concat (substring hfmt 0 -1) "|\n"))
10683
10684 (setq new (mapconcat
10685 (lambda (l)
10686 (if l (apply 'format rfmt
10687 (append (pop fields) emptystrings))
10688 hfmt))
10689 lines ""))
10690 ;; Replace the old one
10691 (delete-region beg end)
10692 (move-marker end nil)
10693 (move-marker org-table-aligned-begin-marker (point))
10694 (insert new)
10695 (move-marker org-table-aligned-end-marker (point))
10696 (when (and orgtbl-mode (not (org-mode-p)))
10697 (goto-char org-table-aligned-begin-marker)
10698 (while (org-hide-wide-columns org-table-aligned-end-marker)))
10699 ;; Try to move to the old location (approximately)
10700 (goto-line linepos)
10701 (set-window-start (selected-window) winstart 'noforce)
10702 (org-table-goto-column colpos)
10703 (setq org-table-may-need-update nil)
10704 ))
10705
10706 (defun org-string-width (s)
10707 "Compute width of string, ignoring invisible characters.
10708 This ignores character with invisibility property `org-link', and also
10709 characters with property `org-cwidth', because these will become invisible
10710 upon the next fontification round."
10711 (let (b)
10712 (when (or (eq t buffer-invisibility-spec)
10713 (assq 'org-link buffer-invisibility-spec))
10714 (while (setq b (text-property-any 0 (length s)
10715 'invisible 'org-link s))
10716 (setq s (concat (substring s 0 b)
10717 (substring s (or (next-single-property-change
10718 b 'invisible s) (length s)))))))
10719 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
10720 (setq s (concat (substring s 0 b)
10721 (substring s (or (next-single-property-change
10722 b 'org-cwidth s) (length s))))))
10723 (string-width s)))
10724
10725 (defun org-table-begin (&optional table-type)
10726 "Find the beginning of the table and return its position.
10727 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
10728 (save-excursion
10729 (if (not (re-search-backward
10730 (if table-type org-table-any-border-regexp
10731 org-table-border-regexp)
10732 nil t))
10733 (progn (goto-char (point-min)) (point))
10734 (goto-char (match-beginning 0))
10735 (beginning-of-line 2)
10736 (point))))
10737
10738 (defun org-table-end (&optional table-type)
10739 "Find the end of the table and return its position.
10740 With argument TABLE-TYPE, go to the end of a table.el-type table."
10741 (save-excursion
10742 (if (not (re-search-forward
10743 (if table-type org-table-any-border-regexp
10744 org-table-border-regexp)
10745 nil t))
10746 (goto-char (point-max))
10747 (goto-char (match-beginning 0)))
10748 (point-marker)))
10749
10750 (defun org-table-justify-field-maybe (&optional new)
10751 "Justify the current field, text to left, number to right.
10752 Optional argument NEW may specify text to replace the current field content."
10753 (cond
10754 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
10755 ((org-at-table-hline-p))
10756 ((and (not new)
10757 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
10758 (current-buffer)))
10759 (< (point) org-table-aligned-begin-marker)
10760 (>= (point) org-table-aligned-end-marker)))
10761 ;; This is not the same table, force a full re-align
10762 (setq org-table-may-need-update t))
10763 (t ;; realign the current field, based on previous full realign
10764 (let* ((pos (point)) s
10765 (col (org-table-current-column))
10766 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
10767 l f n o e)
10768 (when (> col 0)
10769 (skip-chars-backward "^|\n")
10770 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
10771 (progn
10772 (setq s (match-string 1)
10773 o (match-string 0)
10774 l (max 1 (- (match-end 0) (match-beginning 0) 3))
10775 e (not (= (match-beginning 2) (match-end 2))))
10776 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
10777 l (if e "|" (setq org-table-may-need-update t) ""))
10778 n (format f s))
10779 (if new
10780 (if (<= (length new) l) ;; FIXME: length -> str-width?
10781 (setq n (format f new))
10782 (setq n (concat new "|") org-table-may-need-update t)))
10783 (or (equal n o)
10784 (let (org-table-may-need-update)
10785 (replace-match n))))
10786 (setq org-table-may-need-update t))
10787 (goto-char pos))))))
10788
10789 (defun org-table-next-field ()
10790 "Go to the next field in the current table, creating new lines as needed.
10791 Before doing so, re-align the table if necessary."
10792 (interactive)
10793 (org-table-maybe-eval-formula)
10794 (org-table-maybe-recalculate-line)
10795 (if (and org-table-automatic-realign
10796 org-table-may-need-update)
10797 (org-table-align))
10798 (let ((end (org-table-end)))
10799 (if (org-at-table-hline-p)
10800 (end-of-line 1))
10801 (condition-case nil
10802 (progn
10803 (re-search-forward "|" end)
10804 (if (looking-at "[ \t]*$")
10805 (re-search-forward "|" end))
10806 (if (and (looking-at "-")
10807 org-table-tab-jumps-over-hlines
10808 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
10809 (goto-char (match-beginning 1)))
10810 (if (looking-at "-")
10811 (progn
10812 (beginning-of-line 0)
10813 (org-table-insert-row 'below))
10814 (if (looking-at " ") (forward-char 1))))
10815 (error
10816 (org-table-insert-row 'below)))))
10817
10818 (defun org-table-previous-field ()
10819 "Go to the previous field in the table.
10820 Before doing so, re-align the table if necessary."
10821 (interactive)
10822 (org-table-justify-field-maybe)
10823 (org-table-maybe-recalculate-line)
10824 (if (and org-table-automatic-realign
10825 org-table-may-need-update)
10826 (org-table-align))
10827 (if (org-at-table-hline-p)
10828 (end-of-line 1))
10829 (re-search-backward "|" (org-table-begin))
10830 (re-search-backward "|" (org-table-begin))
10831 (while (looking-at "|\\(-\\|[ \t]*$\\)")
10832 (re-search-backward "|" (org-table-begin)))
10833 (if (looking-at "| ?")
10834 (goto-char (match-end 0))))
10835
10836 (defun org-table-next-row ()
10837 "Go to the next row (same column) in the current table.
10838 Before doing so, re-align the table if necessary."
10839 (interactive)
10840 (org-table-maybe-eval-formula)
10841 (org-table-maybe-recalculate-line)
10842 (if (or (looking-at "[ \t]*$")
10843 (save-excursion (skip-chars-backward " \t") (bolp)))
10844 (newline)
10845 (if (and org-table-automatic-realign
10846 org-table-may-need-update)
10847 (org-table-align))
10848 (let ((col (org-table-current-column)))
10849 (beginning-of-line 2)
10850 (if (or (not (org-at-table-p))
10851 (org-at-table-hline-p))
10852 (progn
10853 (beginning-of-line 0)
10854 (org-table-insert-row 'below)))
10855 (org-table-goto-column col)
10856 (skip-chars-backward "^|\n\r")
10857 (if (looking-at " ") (forward-char 1)))))
10858
10859 (defun org-table-copy-down (n)
10860 "Copy a field down in the current column.
10861 If the field at the cursor is empty, copy into it the content of the nearest
10862 non-empty field above. With argument N, use the Nth non-empty field.
10863 If the current field is not empty, it is copied down to the next row, and
10864 the cursor is moved with it. Therefore, repeating this command causes the
10865 column to be filled row-by-row.
10866 If the variable `org-table-copy-increment' is non-nil and the field is an
10867 integer, it will be incremented while copying."
10868 (interactive "p")
10869 (let* ((colpos (org-table-current-column))
10870 (field (org-table-get-field))
10871 (non-empty (string-match "[^ \t]" field))
10872 (beg (org-table-begin))
10873 txt)
10874 (org-table-check-inside-data-field)
10875 (if non-empty
10876 (progn
10877 (setq txt (org-trim field))
10878 (org-table-next-row)
10879 (org-table-blank-field))
10880 (save-excursion
10881 (setq txt
10882 (catch 'exit
10883 (while (progn (beginning-of-line 1)
10884 (re-search-backward org-table-dataline-regexp
10885 beg t))
10886 (org-table-goto-column colpos t)
10887 (if (and (looking-at
10888 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
10889 (= (setq n (1- n)) 0))
10890 (throw 'exit (match-string 1))))))))
10891 (if txt
10892 (progn
10893 (if (and org-table-copy-increment
10894 (string-match "^[0-9]+$" txt))
10895 (setq txt (format "%d" (+ (string-to-number txt) 1))))
10896 (insert txt)
10897 (org-table-maybe-recalculate-line)
10898 (org-table-align))
10899 (error "No non-empty field found"))))
10900
10901 (defun org-table-check-inside-data-field ()
10902 "Is point inside a table data field?
10903 I.e. not on a hline or before the first or after the last column?
10904 This actually throws an error, so it aborts the current command."
10905 (if (or (not (org-at-table-p))
10906 (= (org-table-current-column) 0)
10907 (org-at-table-hline-p)
10908 (looking-at "[ \t]*$"))
10909 (error "Not in table data field")))
10910
10911 (defvar org-table-clip nil
10912 "Clipboard for table regions.")
10913
10914 (defun org-table-blank-field ()
10915 "Blank the current table field or active region."
10916 (interactive)
10917 (org-table-check-inside-data-field)
10918 (if (and (interactive-p) (org-region-active-p))
10919 (let (org-table-clip)
10920 (org-table-cut-region (region-beginning) (region-end)))
10921 (skip-chars-backward "^|")
10922 (backward-char 1)
10923 (if (looking-at "|[^|\n]+")
10924 (let* ((pos (match-beginning 0))
10925 (match (match-string 0))
10926 (len (org-string-width match)))
10927 (replace-match (concat "|" (make-string (1- len) ?\ )))
10928 (goto-char (+ 2 pos))
10929 (substring match 1)))))
10930
10931 (defun org-table-get-field (&optional n replace)
10932 "Return the value of the field in column N of current row.
10933 N defaults to current field.
10934 If REPLACE is a string, replace field with this value. The return value
10935 is always the old value."
10936 (and n (org-table-goto-column n))
10937 (skip-chars-backward "^|\n")
10938 (backward-char 1)
10939 (if (looking-at "|[^|\r\n]*")
10940 (let* ((pos (match-beginning 0))
10941 (val (buffer-substring (1+ pos) (match-end 0))))
10942 (if replace
10943 (replace-match (concat "|" replace)))
10944 (goto-char (min (point-at-eol) (+ 2 pos)))
10945 val)
10946 (forward-char 1) ""))
10947
10948 (defun org-table-current-column ()
10949 "Find out which column we are in.
10950 When called interactively, column is also displayed in echo area."
10951 (interactive)
10952 (if (interactive-p) (org-table-check-inside-data-field))
10953 (save-excursion
10954 (let ((cnt 0) (pos (point)))
10955 (beginning-of-line 1)
10956 (while (search-forward "|" pos t)
10957 (setq cnt (1+ cnt)))
10958 (if (interactive-p) (message "This is table column %d" cnt))
10959 cnt)))
10960
10961 (defun org-table-goto-column (n &optional on-delim force)
10962 "Move the cursor to the Nth column in the current table line.
10963 With optional argument ON-DELIM, stop with point before the left delimiter
10964 of the field.
10965 If there are less than N fields, just go to after the last delimiter.
10966 However, when FORCE is non-nil, create new columns if necessary."
10967 (interactive "p")
10968 (let ((pos (point-at-eol)))
10969 (beginning-of-line 1)
10970 (when (> n 0)
10971 (while (and (> (setq n (1- n)) -1)
10972 (or (search-forward "|" pos t)
10973 (and force
10974 (progn (end-of-line 1)
10975 (skip-chars-backward "^|")
10976 (insert " | "))))))
10977 ; (backward-char 2) t)))))
10978 (when (and force (not (looking-at ".*|")))
10979 (save-excursion (end-of-line 1) (insert " | ")))
10980 (if on-delim
10981 (backward-char 1)
10982 (if (looking-at " ") (forward-char 1))))))
10983
10984 (defun org-at-table-p (&optional table-type)
10985 "Return t if the cursor is inside an org-type table.
10986 If TABLE-TYPE is non-nil, also check for table.el-type tables."
10987 (if org-enable-table-editor
10988 (save-excursion
10989 (beginning-of-line 1)
10990 (looking-at (if table-type org-table-any-line-regexp
10991 org-table-line-regexp)))
10992 nil))
10993
10994 (defun org-at-table.el-p ()
10995 "Return t if and only if we are at a table.el table."
10996 (and (org-at-table-p 'any)
10997 (save-excursion
10998 (goto-char (org-table-begin 'any))
10999 (looking-at org-table1-hline-regexp))))
11000
11001 (defun org-table-recognize-table.el ()
11002 "If there is a table.el table nearby, recognize it and move into it."
11003 (if org-table-tab-recognizes-table.el
11004 (if (org-at-table.el-p)
11005 (progn
11006 (beginning-of-line 1)
11007 (if (looking-at org-table-dataline-regexp)
11008 nil
11009 (if (looking-at org-table1-hline-regexp)
11010 (progn
11011 (beginning-of-line 2)
11012 (if (looking-at org-table-any-border-regexp)
11013 (beginning-of-line -1)))))
11014 (if (re-search-forward "|" (org-table-end t) t)
11015 (progn
11016 (require 'table)
11017 (if (table--at-cell-p (point))
11018 t
11019 (message "recognizing table.el table...")
11020 (table-recognize-table)
11021 (message "recognizing table.el table...done")))
11022 (error "This should not happen..."))
11023 t)
11024 nil)
11025 nil))
11026
11027 (defun org-at-table-hline-p ()
11028 "Return t if the cursor is inside a hline in a table."
11029 (if org-enable-table-editor
11030 (save-excursion
11031 (beginning-of-line 1)
11032 (looking-at org-table-hline-regexp))
11033 nil))
11034
11035 (defun org-table-insert-column ()
11036 "Insert a new column into the table."
11037 (interactive)
11038 (if (not (org-at-table-p))
11039 (error "Not at a table"))
11040 (org-table-find-dataline)
11041 (let* ((col (max 1 (org-table-current-column)))
11042 (beg (org-table-begin))
11043 (end (org-table-end))
11044 ;; Current cursor position
11045 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11046 (colpos col))
11047 (goto-char beg)
11048 (while (< (point) end)
11049 (if (org-at-table-hline-p)
11050 nil
11051 (org-table-goto-column col t)
11052 (insert "| "))
11053 (beginning-of-line 2))
11054 (move-marker end nil)
11055 (goto-line linepos)
11056 (org-table-goto-column colpos)
11057 (org-table-align)
11058 (org-table-modify-formulas 'insert col)))
11059
11060 (defun org-table-find-dataline ()
11061 "Find a dataline in the current table, which is needed for column commands."
11062 (if (and (org-at-table-p)
11063 (not (org-at-table-hline-p)))
11064 t
11065 (let ((col (current-column))
11066 (end (org-table-end)))
11067 (move-to-column col)
11068 (while (and (< (point) end)
11069 (or (not (= (current-column) col))
11070 (org-at-table-hline-p)))
11071 (beginning-of-line 2)
11072 (move-to-column col))
11073 (if (and (org-at-table-p)
11074 (not (org-at-table-hline-p)))
11075 t
11076 (error
11077 "Please position cursor in a data line for column operations")))))
11078
11079 (defun org-table-delete-column ()
11080 "Delete a column from the table."
11081 (interactive)
11082 (if (not (org-at-table-p))
11083 (error "Not at a table"))
11084 (org-table-find-dataline)
11085 (org-table-check-inside-data-field)
11086 (let* ((col (org-table-current-column))
11087 (beg (org-table-begin))
11088 (end (org-table-end))
11089 ;; Current cursor position
11090 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11091 (colpos col))
11092 (goto-char beg)
11093 (while (< (point) end)
11094 (if (org-at-table-hline-p)
11095 nil
11096 (org-table-goto-column col t)
11097 (and (looking-at "|[^|\n]+|")
11098 (replace-match "|")))
11099 (beginning-of-line 2))
11100 (move-marker end nil)
11101 (goto-line linepos)
11102 (org-table-goto-column colpos)
11103 (org-table-align)
11104 (org-table-modify-formulas 'remove col)))
11105
11106 (defun org-table-move-column-right ()
11107 "Move column to the right."
11108 (interactive)
11109 (org-table-move-column nil))
11110 (defun org-table-move-column-left ()
11111 "Move column to the left."
11112 (interactive)
11113 (org-table-move-column 'left))
11114
11115 (defun org-table-move-column (&optional left)
11116 "Move the current column to the right. With arg LEFT, move to the left."
11117 (interactive "P")
11118 (if (not (org-at-table-p))
11119 (error "Not at a table"))
11120 (org-table-find-dataline)
11121 (org-table-check-inside-data-field)
11122 (let* ((col (org-table-current-column))
11123 (col1 (if left (1- col) col))
11124 (beg (org-table-begin))
11125 (end (org-table-end))
11126 ;; Current cursor position
11127 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11128 (colpos (if left (1- col) (1+ col))))
11129 (if (and left (= col 1))
11130 (error "Cannot move column further left"))
11131 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
11132 (error "Cannot move column further right"))
11133 (goto-char beg)
11134 (while (< (point) end)
11135 (if (org-at-table-hline-p)
11136 nil
11137 (org-table-goto-column col1 t)
11138 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
11139 (replace-match "|\\2|\\1|")))
11140 (beginning-of-line 2))
11141 (move-marker end nil)
11142 (goto-line linepos)
11143 (org-table-goto-column colpos)
11144 (org-table-align)
11145 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
11146
11147 (defun org-table-move-row-down ()
11148 "Move table row down."
11149 (interactive)
11150 (org-table-move-row nil))
11151 (defun org-table-move-row-up ()
11152 "Move table row up."
11153 (interactive)
11154 (org-table-move-row 'up))
11155
11156 (defun org-table-move-row (&optional up)
11157 "Move the current table line down. With arg UP, move it up."
11158 (interactive "P")
11159 (let ((col (current-column))
11160 (pos (point))
11161 (tonew (if up 0 2))
11162 txt)
11163 (beginning-of-line tonew)
11164 (if (not (org-at-table-p))
11165 (progn
11166 (goto-char pos)
11167 (error "Cannot move row further")))
11168 (goto-char pos)
11169 (beginning-of-line 1)
11170 (setq pos (point))
11171 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
11172 (delete-region (point) (1+ (point-at-eol)))
11173 (beginning-of-line tonew)
11174 (insert txt)
11175 (beginning-of-line 0)
11176 (move-to-column col)))
11177
11178 (defun org-table-insert-row (&optional arg)
11179 "Insert a new row above the current line into the table.
11180 With prefix ARG, insert below the current line."
11181 (interactive "P")
11182 (if (not (org-at-table-p))
11183 (error "Not at a table"))
11184 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
11185 (new (org-table-clean-line line)))
11186 ;; Fix the first field if necessary
11187 (if (string-match "^[ \t]*| *[#$] *|" line)
11188 (setq new (replace-match (match-string 0 line) t t new)))
11189 (beginning-of-line (if arg 2 1))
11190 (let (org-table-may-need-update) (insert-before-markers new "\n"))
11191 (beginning-of-line 0)
11192 (re-search-forward "| ?" (point-at-eol) t)
11193 (and org-table-may-need-update (org-table-align))))
11194
11195 (defun org-table-insert-hline (&optional arg)
11196 "Insert a horizontal-line below the current line into the table.
11197 With prefix ARG, insert above the current line."
11198 (interactive "P")
11199 (if (not (org-at-table-p))
11200 (error "Not at a table"))
11201 (let ((line (org-table-clean-line
11202 (buffer-substring (point-at-bol) (point-at-eol))))
11203 (col (current-column)))
11204 (while (string-match "|\\( +\\)|" line)
11205 (setq line (replace-match
11206 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
11207 ?-) "|") t t line)))
11208 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
11209 (beginning-of-line (if arg 1 2))
11210 (insert line "\n")
11211 (beginning-of-line (if arg 1 -1))
11212 (move-to-column col)))
11213
11214 (defun org-table-clean-line (s)
11215 "Convert a table line S into a string with only \"|\" and space.
11216 In particular, this does handle wide and invisible characters."
11217 (if (string-match "^[ \t]*|-" s)
11218 ;; It's a hline, just map the characters
11219 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
11220 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
11221 (setq s (replace-match
11222 (concat "|" (make-string (org-string-width (match-string 1 s))
11223 ?\ ) "|")
11224 t t s)))
11225 s))
11226
11227 (defun org-table-kill-row ()
11228 "Delete the current row or horizontal line from the table."
11229 (interactive)
11230 (if (not (org-at-table-p))
11231 (error "Not at a table"))
11232 (let ((col (current-column)))
11233 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
11234 (if (not (org-at-table-p)) (beginning-of-line 0))
11235 (move-to-column col)))
11236
11237 (defun org-table-sort-lines (beg end numericp)
11238 "Sort table lines in region.
11239 Point and mark define the first and last line to include. Both point and
11240 mark should be in the column that is used for sorting. For example, to
11241 sort according to column 3, put the mark in the first line to sort, in
11242 table column 3. Put point into the last line to be included in the sorting,
11243 also in table column 3. The command will prompt for the sorting method
11244 \(n for numerical, a for alphanumeric)."
11245 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
11246 (setq numericp (string-match "[nN]" numericp))
11247 (org-table-align) ;; Just to be safe
11248 (let* (bcol ecol cmp column lns)
11249 (goto-char beg)
11250 (org-table-check-inside-data-field)
11251 (setq column (org-table-current-column)
11252 beg (move-marker (make-marker) (point-at-bol)))
11253 (goto-char end)
11254 (org-table-check-inside-data-field)
11255 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
11256 (untabify beg end)
11257 (goto-char beg)
11258 (org-table-goto-column column)
11259 (skip-chars-backward "^|")
11260 (setq bcol (current-column))
11261 (org-table-goto-column (1+ column))
11262 (skip-chars-backward "^|")
11263 (setq ecol (1- (current-column)))
11264 (setq cmp (if numericp
11265 (lambda (a b) (< (car a) (car b)))
11266 (lambda (a b) (string< (car a) (car b)))))
11267 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
11268 (org-split-string (buffer-substring beg end) "\n")))
11269 (if numericp
11270 (setq lns (mapcar (lambda(x)
11271 (cons (string-to-number (car x)) (cdr x)))
11272 lns)))
11273 (delete-region beg end)
11274 (move-marker beg nil)
11275 (move-marker end nil)
11276 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
11277 (message "%d lines sorted %s based on column %d"
11278 (length lns)
11279 (if numericp "numerically" "alphabetically") column)))
11280
11281 (defun org-table-cut-region (beg end)
11282 "Copy region in table to the clipboard and blank all relevant fields."
11283 (interactive "r")
11284 (org-table-copy-region beg end 'cut))
11285
11286 (defun org-table-copy-region (beg end &optional cut)
11287 "Copy rectangular region in table to clipboard.
11288 A special clipboard is used which can only be accessed
11289 with `org-table-paste-rectangle'."
11290 (interactive "rP")
11291 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
11292 region cols
11293 (rpl (if cut " " nil)))
11294 (goto-char beg)
11295 (org-table-check-inside-data-field)
11296 (setq l01 (count-lines (point-min) (point))
11297 c01 (org-table-current-column))
11298 (goto-char end)
11299 (org-table-check-inside-data-field)
11300 (setq l02 (count-lines (point-min) (point))
11301 c02 (org-table-current-column))
11302 (setq l1 (min l01 l02) l2 (max l01 l02)
11303 c1 (min c01 c02) c2 (max c01 c02))
11304 (catch 'exit
11305 (while t
11306 (catch 'nextline
11307 (if (> l1 l2) (throw 'exit t))
11308 (goto-line l1)
11309 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
11310 (setq cols nil ic1 c1 ic2 c2)
11311 (while (< ic1 (1+ ic2))
11312 (push (org-table-get-field ic1 rpl) cols)
11313 (setq ic1 (1+ ic1)))
11314 (push (nreverse cols) region)
11315 (setq l1 (1+ l1)))))
11316 (setq org-table-clip (nreverse region))
11317 (if cut (org-table-align))
11318 org-table-clip))
11319
11320 (defun org-table-paste-rectangle ()
11321 "Paste a rectangular region into a table.
11322 The upper right corner ends up in the current field. All involved fields
11323 will be overwritten. If the rectangle does not fit into the present table,
11324 the table is enlarged as needed. The process ignores horizontal separator
11325 lines."
11326 (interactive)
11327 (unless (and org-table-clip (listp org-table-clip))
11328 (error "First cut/copy a region to paste!"))
11329 (org-table-check-inside-data-field)
11330 (let* ((clip org-table-clip)
11331 (line (count-lines (point-min) (point)))
11332 (col (org-table-current-column))
11333 (org-enable-table-editor t)
11334 (org-table-automatic-realign nil)
11335 c cols field)
11336 (while (setq cols (pop clip))
11337 (while (org-at-table-hline-p) (beginning-of-line 2))
11338 (if (not (org-at-table-p))
11339 (progn (end-of-line 0) (org-table-next-field)))
11340 (setq c col)
11341 (while (setq field (pop cols))
11342 (org-table-goto-column c nil 'force)
11343 (org-table-get-field nil field)
11344 (setq c (1+ c)))
11345 (beginning-of-line 2))
11346 (goto-line line)
11347 (org-table-goto-column col)
11348 (org-table-align)))
11349
11350 (defun org-table-convert ()
11351 "Convert from `org-mode' table to table.el and back.
11352 Obviously, this only works within limits. When an Org-mode table is
11353 converted to table.el, all horizontal separator lines get lost, because
11354 table.el uses these as cell boundaries and has no notion of horizontal lines.
11355 A table.el table can be converted to an Org-mode table only if it does not
11356 do row or column spanning. Multiline cells will become multiple cells.
11357 Beware, Org-mode does not test if the table can be successfully converted - it
11358 blindly applies a recipe that works for simple tables."
11359 (interactive)
11360 (require 'table)
11361 (if (org-at-table.el-p)
11362 ;; convert to Org-mode table
11363 (let ((beg (move-marker (make-marker) (org-table-begin t)))
11364 (end (move-marker (make-marker) (org-table-end t))))
11365 (table-unrecognize-region beg end)
11366 (goto-char beg)
11367 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
11368 (replace-match ""))
11369 (goto-char beg))
11370 (if (org-at-table-p)
11371 ;; convert to table.el table
11372 (let ((beg (move-marker (make-marker) (org-table-begin)))
11373 (end (move-marker (make-marker) (org-table-end))))
11374 ;; first, get rid of all horizontal lines
11375 (goto-char beg)
11376 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
11377 (replace-match ""))
11378 ;; insert a hline before first
11379 (goto-char beg)
11380 (org-table-insert-hline 'above)
11381 (beginning-of-line -1)
11382 ;; insert a hline after each line
11383 (while (progn (beginning-of-line 3) (< (point) end))
11384 (org-table-insert-hline))
11385 (goto-char beg)
11386 (setq end (move-marker end (org-table-end)))
11387 ;; replace "+" at beginning and ending of hlines
11388 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
11389 (replace-match "\\1+-"))
11390 (goto-char beg)
11391 (while (re-search-forward "-|[ \t]*$" end t)
11392 (replace-match "-+"))
11393 (goto-char beg)))))
11394
11395 (defun org-table-wrap-region (arg)
11396 "Wrap several fields in a column like a paragraph.
11397 This is useful if you'd like to spread the contents of a field over several
11398 lines, in order to keep the table compact.
11399
11400 If there is an active region, and both point and mark are in the same column,
11401 the text in the column is wrapped to minimum width for the given number of
11402 lines. Generally, this makes the table more compact. A prefix ARG may be
11403 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
11404 formats the selected text to two lines. If the region was longer than two
11405 lines, the remaining lines remain empty. A negative prefix argument reduces
11406 the current number of lines by that amount. The wrapped text is pasted back
11407 into the table. If you formatted it to more lines than it was before, fields
11408 further down in the table get overwritten - so you might need to make space in
11409 the table first.
11410
11411 If there is no region, the current field is split at the cursor position and
11412 the text fragment to the right of the cursor is prepended to the field one
11413 line down.
11414
11415 If there is no region, but you specify a prefix ARG, the current field gets
11416 blank, and the content is appended to the field above."
11417 (interactive "P")
11418 (org-table-check-inside-data-field)
11419 (if (org-region-active-p)
11420 ;; There is a region: fill as a paragraph
11421 (let ((beg (region-beginning))
11422 nlines)
11423 (org-table-cut-region (region-beginning) (region-end))
11424 (if (> (length (car org-table-clip)) 1)
11425 (error "Region must be limited to single column"))
11426 (setq nlines (if arg
11427 (if (< arg 1)
11428 (+ (length org-table-clip) arg)
11429 arg)
11430 (length org-table-clip)))
11431 (setq org-table-clip
11432 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
11433 nil nlines)))
11434 (goto-char beg)
11435 (org-table-paste-rectangle))
11436 ;; No region, split the current field at point
11437 (if arg
11438 ;; combine with field above
11439 (let ((s (org-table-blank-field))
11440 (col (org-table-current-column)))
11441 (beginning-of-line 0)
11442 (while (org-at-table-hline-p) (beginning-of-line 0))
11443 (org-table-goto-column col)
11444 (skip-chars-forward "^|")
11445 (skip-chars-backward " ")
11446 (insert " " (org-trim s))
11447 (org-table-align))
11448 ;; split field
11449 (when (looking-at "\\([^|]+\\)+|")
11450 (let ((s (match-string 1)))
11451 (replace-match " |")
11452 (goto-char (match-beginning 0))
11453 (org-table-next-row)
11454 (insert (org-trim s) " ")
11455 (org-table-align))))))
11456
11457 (defvar org-field-marker nil)
11458
11459 (defun org-table-edit-field (arg)
11460 "Edit table field in a different window.
11461 This is mainly useful for fields that contain hidden parts.
11462 When called with a \\[universal-argument] prefix, just make the full field visible so that
11463 it can be edited in place."
11464 (interactive "P")
11465 (if arg
11466 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
11467 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
11468 (remove-text-properties b e '(org-cwidth t invisible t
11469 display t intangible t))
11470 (if (and (boundp 'font-lock-mode) font-lock-mode)
11471 (font-lock-fontify-block)))
11472 (let ((pos (move-marker (make-marker) (point)))
11473 (field (org-table-get-field))
11474 (cw (current-window-configuration))
11475 p)
11476 (switch-to-buffer-other-window "*Org tmp*")
11477 (erase-buffer)
11478 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
11479 (org-mode)
11480 (goto-char (setq p (point-max)))
11481 (insert (org-trim field))
11482 (remove-text-properties p (point-max)
11483 '(invisible t org-cwidth t display t
11484 intangible t))
11485 (goto-char p)
11486 (set (make-local-variable 'org-finish-function)
11487 'org-table-finish-edit-field)
11488 (set (make-local-variable 'org-window-configuration) cw)
11489 (set (make-local-variable 'org-field-marker) pos)
11490 (message "Edit and finish with C-c C-c"))))
11491
11492 (defun org-table-finish-edit-field ()
11493 "Finish editing a table data field.
11494 Remove all newline characters, insert the result into the table, realign
11495 the table and kill the editing buffer."
11496 (let ((pos org-field-marker)
11497 (cw org-window-configuration)
11498 (cb (current-buffer))
11499 text)
11500 (goto-char (point-min))
11501 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
11502 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
11503 (replace-match " "))
11504 (setq text (org-trim (buffer-string)))
11505 (set-window-configuration cw)
11506 (kill-buffer cb)
11507 (select-window (get-buffer-window (marker-buffer pos)))
11508 (goto-char pos)
11509 (move-marker pos nil)
11510 (org-table-check-inside-data-field)
11511 (org-table-get-field nil text)
11512 (org-table-align)
11513 (message "New field value inserted")))
11514
11515 (defun org-trim (s)
11516 "Remove whitespace at beginning and end of string."
11517 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
11518 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
11519 s)
11520
11521 (defun org-wrap (string &optional width lines)
11522 "Wrap string to either a number of lines, or a width in characters.
11523 If WIDTH is non-nil, the string is wrapped to that width, however many lines
11524 that costs. If there is a word longer than WIDTH, the text is actually
11525 wrapped to the length of that word.
11526 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
11527 many lines, whatever width that takes.
11528 The return value is a list of lines, without newlines at the end."
11529 (let* ((words (org-split-string string "[ \t\n]+"))
11530 (maxword (apply 'max (mapcar 'org-string-width words)))
11531 w ll)
11532 (cond (width
11533 (org-do-wrap words (max maxword width)))
11534 (lines
11535 (setq w maxword)
11536 (setq ll (org-do-wrap words maxword))
11537 (if (<= (length ll) lines)
11538 ll
11539 (setq ll words)
11540 (while (> (length ll) lines)
11541 (setq w (1+ w))
11542 (setq ll (org-do-wrap words w)))
11543 ll))
11544 (t (error "Cannot wrap this")))))
11545
11546
11547 (defun org-do-wrap (words width)
11548 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
11549 (let (lines line)
11550 (while words
11551 (setq line (pop words))
11552 (while (and words (< (+ (length line) (length (car words))) width))
11553 (setq line (concat line " " (pop words))))
11554 (setq lines (push line lines)))
11555 (nreverse lines)))
11556
11557 (defun org-split-string (string &optional separators)
11558 "Splits STRING into substrings at SEPARATORS.
11559 No empty strings are returned if there are matches at the beginning
11560 and end of string."
11561 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
11562 (start 0)
11563 notfirst
11564 (list nil))
11565 (while (and (string-match rexp string
11566 (if (and notfirst
11567 (= start (match-beginning 0))
11568 (< start (length string)))
11569 (1+ start) start))
11570 (< (match-beginning 0) (length string)))
11571 (setq notfirst t)
11572 (or (eq (match-beginning 0) 0)
11573 (and (eq (match-beginning 0) (match-end 0))
11574 (eq (match-beginning 0) start))
11575 (setq list
11576 (cons (substring string start (match-beginning 0))
11577 list)))
11578 (setq start (match-end 0)))
11579 (or (eq start (length string))
11580 (setq list
11581 (cons (substring string start)
11582 list)))
11583 (nreverse list)))
11584
11585 (defun org-table-map-tables (function)
11586 "Apply FUNCTION to the start of all tables in the buffer."
11587 (save-excursion
11588 (save-restriction
11589 (widen)
11590 (goto-char (point-min))
11591 (while (re-search-forward org-table-any-line-regexp nil t)
11592 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
11593 (beginning-of-line 1)
11594 (if (looking-at org-table-line-regexp)
11595 (save-excursion (funcall function)))
11596 (re-search-forward org-table-any-border-regexp nil 1))))
11597 (message "Mapping tables: done"))
11598
11599 (defun org-table-sum (&optional beg end nlast)
11600 "Sum numbers in region of current table column.
11601 The result will be displayed in the echo area, and will be available
11602 as kill to be inserted with \\[yank].
11603
11604 If there is an active region, it is interpreted as a rectangle and all
11605 numbers in that rectangle will be summed. If there is no active
11606 region and point is located in a table column, sum all numbers in that
11607 column.
11608
11609 If at least one number looks like a time HH:MM or HH:MM:SS, all other
11610 numbers are assumed to be times as well (in decimal hours) and the
11611 numbers are added as such.
11612
11613 If NLAST is a number, only the NLAST fields will actually be summed."
11614 (interactive)
11615 (save-excursion
11616 (let (col (timecnt 0) diff h m s org-table-clip)
11617 (cond
11618 ((and beg end)) ; beg and end given explicitly
11619 ((org-region-active-p)
11620 (setq beg (region-beginning) end (region-end)))
11621 (t
11622 (setq col (org-table-current-column))
11623 (goto-char (org-table-begin))
11624 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
11625 (error "No table data"))
11626 (org-table-goto-column col)
11627 ;not needed? (skip-chars-backward "^|")
11628 (setq beg (point))
11629 (goto-char (org-table-end))
11630 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
11631 (error "No table data"))
11632 (org-table-goto-column col)
11633 ;not needed? (skip-chars-forward "^|")
11634 (setq end (point))))
11635 (let* ((items (apply 'append (org-table-copy-region beg end)))
11636 (items1 (cond ((not nlast) items)
11637 ((>= nlast (length items)) items)
11638 (t (setq items (reverse items))
11639 (setcdr (nthcdr (1- nlast) items) nil)
11640 (nreverse items))))
11641 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
11642 items1)))
11643 (res (apply '+ numbers))
11644 (sres (if (= timecnt 0)
11645 (format "%g" res)
11646 (setq diff (* 3600 res)
11647 h (floor (/ diff 3600)) diff (mod diff 3600)
11648 m (floor (/ diff 60)) diff (mod diff 60)
11649 s diff)
11650 (format "%d:%02d:%02d" h m s))))
11651 (kill-new sres)
11652 (if (interactive-p)
11653 (message "%s"
11654 (substitute-command-keys
11655 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
11656 (length numbers) sres))))
11657 sres))))
11658
11659 (defun org-table-get-number-for-summing (s)
11660 (let (n)
11661 (if (string-match "^ *|? *" s)
11662 (setq s (replace-match "" nil nil s)))
11663 (if (string-match " *|? *$" s)
11664 (setq s (replace-match "" nil nil s)))
11665 (setq n (string-to-number s))
11666 (cond
11667 ((and (string-match "0" s)
11668 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
11669 ((string-match "\\`[ \t]+\\'" s) nil)
11670 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
11671 (let ((h (string-to-number (or (match-string 1 s) "0")))
11672 (m (string-to-number (or (match-string 2 s) "0")))
11673 (s (string-to-number (or (match-string 4 s) "0"))))
11674 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
11675 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
11676 ((equal n 0) nil)
11677 (t n))))
11678
11679 (defun org-table-get-vertical-vector (desc &optional tbeg col)
11680 "Get a calc vector from a column, accorting to descriptor DESC.
11681 Optional arguments TBEG and COL can give the beginning of the table and
11682 the current column, to avoid unnecessary parsing."
11683 (save-excursion
11684 (or tbeg (setq tbeg (org-table-begin)))
11685 (or col (setq col (org-table-current-column)))
11686 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
11687 (cond
11688 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
11689 (setq n1 (- (match-end 1) (match-beginning 1)))
11690 (if (match-beginning 3)
11691 (setq n2 (- (match-end 2) (match-beginning 3))))
11692 (setq n (if n2 (max n1 n2) n1))
11693 (setq n1 (if n2 (min n1 n2)))
11694 (setq nn n)
11695 (while (and (> nn 0)
11696 (re-search-backward org-table-hline-regexp tbeg t))
11697 (push (org-current-line) hline-list)
11698 (setq nn (1- nn)))
11699 (setq hline-list (nreverse hline-list))
11700 (goto-line (nth (1- n) hline-list))
11701 (when (re-search-forward org-table-dataline-regexp)
11702 (org-table-goto-column col)
11703 (setq beg (point)))
11704 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
11705 (when (re-search-backward org-table-dataline-regexp)
11706 (org-table-goto-column col)
11707 (setq end (point)))
11708 (setq l (apply 'append (org-table-copy-region beg end)))
11709 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
11710 (if (equal x "") "0" x))
11711 l ",") "]"))
11712 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
11713 (setq n1 (string-to-number (match-string 1 desc))
11714 n2 (string-to-number (match-string 2 desc)))
11715 (beginning-of-line 1)
11716 (save-excursion
11717 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
11718 (org-table-goto-column col)
11719 (setq beg (point))))
11720 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
11721 (org-table-goto-column col)
11722 (setq end (point)))
11723 (setq l (apply 'append (org-table-copy-region beg end)))
11724 (concat "[" (mapconcat
11725 (lambda (x) (setq x (org-trim x))
11726 (if (equal x "") "0" x))
11727 l ",") "]"))
11728 ((string-match "\\([0-9]+\\)" desc)
11729 (beginning-of-line 1)
11730 (when (re-search-backward org-table-dataline-regexp tbeg t
11731 (string-to-number (match-string 0 desc)))
11732 (org-table-goto-column col)
11733 (org-trim (org-table-get-field))))))))
11734
11735 (defvar org-table-formula-history nil)
11736
11737 (defvar org-table-column-names nil
11738 "Alist with column names, derived from the `!' line.")
11739 (defvar org-table-column-name-regexp nil
11740 "Regular expression matching the current column names.")
11741 (defvar org-table-local-parameters nil
11742 "Alist with parameter names, derived from the `$' line.")
11743 (defvar org-table-named-field-locations nil
11744 "Alist with locations of named fields.")
11745
11746 (defun org-table-get-formula (&optional equation named)
11747 "Read a formula from the minibuffer, offer stored formula as default."
11748 (let* ((name (car (rassoc (list (org-current-line)
11749 (org-table-current-column))
11750 org-table-named-field-locations)))
11751 (scol (if named
11752 (if name name
11753 (error "Not in a named field"))
11754 (int-to-string (org-table-current-column))))
11755 (dummy (and name (not named)
11756 (not (y-or-n-p "Replace named-field formula with column equation? " ))
11757 (error "Abort")))
11758 (org-table-may-need-update nil)
11759 (stored-list (org-table-get-stored-formulas))
11760 (stored (cdr (assoc scol stored-list)))
11761 (eq (cond
11762 ((and stored equation (string-match "^ *=? *$" equation))
11763 stored)
11764 ((stringp equation)
11765 equation)
11766 (t (read-string
11767 (format "%s formula $%s=" (if named "Field" "Column") scol)
11768 (or stored "") 'org-table-formula-history
11769 ;stored
11770 ))))
11771 mustsave)
11772 (when (not (string-match "\\S-" eq))
11773 ;; remove formula
11774 (setq stored-list (delq (assoc scol stored-list) stored-list))
11775 (org-table-store-formulas stored-list)
11776 (error "Formula removed"))
11777 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
11778 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
11779 (if (and name (not named))
11780 ;; We set the column equation, delete the named one.
11781 (setq stored-list (delq (assoc name stored-list) stored-list)
11782 mustsave t))
11783 (if stored
11784 (setcdr (assoc scol stored-list) eq)
11785 (setq stored-list (cons (cons scol eq) stored-list)))
11786 (if (or mustsave (not (equal stored eq)))
11787 (org-table-store-formulas stored-list))
11788 eq))
11789
11790 (defun org-table-store-formulas (alist)
11791 "Store the list of formulas below the current table."
11792 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
11793 (save-excursion
11794 (goto-char (org-table-end))
11795 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
11796 (delete-region (point) (match-end 0)))
11797 (insert "#+TBLFM: "
11798 (mapconcat (lambda (x)
11799 (concat "$" (car x) "=" (cdr x)))
11800 alist "::")
11801 "\n")))
11802
11803 (defun org-table-get-stored-formulas ()
11804 "Return an alist with the stored formulas directly after current table."
11805 (interactive)
11806 (let (scol eq eq-alist strings string seen)
11807 (save-excursion
11808 (goto-char (org-table-end))
11809 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
11810 (setq strings (org-split-string (match-string 2) " *:: *"))
11811 (while (setq string (pop strings))
11812 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
11813 (setq scol (match-string 1 string)
11814 eq (match-string 2 string)
11815 eq-alist (cons (cons scol eq) eq-alist))
11816 (if (member scol seen)
11817 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
11818 (push scol seen))))))
11819 (nreverse eq-alist)))
11820
11821 (defun org-table-modify-formulas (action &rest columns)
11822 "Modify the formulas stored below the current table.
11823 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
11824 expected, for the other actions only a single column number is needed."
11825 (let ((list (org-table-get-stored-formulas))
11826 (nmax (length (org-split-string
11827 (buffer-substring (point-at-bol) (point-at-eol))
11828 "|")))
11829 col col1 col2 scol si sc1 sc2)
11830 (cond
11831 ((null list)) ; No action needed if there are no stored formulas
11832 ((eq action 'remove)
11833 (setq col (car columns)
11834 scol (int-to-string col))
11835 (org-table-replace-in-formulas list scol "INVALID")
11836 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
11837 (loop for i from (1+ col) upto nmax by 1 do
11838 (setq si (int-to-string i))
11839 (org-table-replace-in-formulas list si (int-to-string (1- i)))
11840 (if (assoc si list) (setcar (assoc si list)
11841 (int-to-string (1- i))))))
11842 ((eq action 'insert)
11843 (setq col (car columns))
11844 (loop for i from nmax downto col by 1 do
11845 (setq si (int-to-string i))
11846 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
11847 (if (assoc si list) (setcar (assoc si list)
11848 (int-to-string (1+ i))))))
11849 ((eq action 'swap)
11850 (setq col1 (car columns) col2 (nth 1 columns)
11851 sc1 (int-to-string col1) sc2 (int-to-string col2))
11852 ;; Hopefully, ZqZtZ will never be a name in a table
11853 (org-table-replace-in-formulas list sc1 "ZqZtZ")
11854 (org-table-replace-in-formulas list sc2 sc1)
11855 (org-table-replace-in-formulas list "ZqZtZ" sc2)
11856 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
11857 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
11858 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
11859 (t (error "Invalid action in `org-table-modify-formulas'")))
11860 (if list (org-table-store-formulas list))))
11861
11862 (defun org-table-replace-in-formulas (list s1 s2)
11863 (let (elt re s)
11864 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
11865 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
11866 re (concat (regexp-quote s1) "\\>"))
11867 (while (setq elt (pop list))
11868 (setq s (cdr elt))
11869 (while (string-match re s)
11870 (setq s (replace-match s2 t t s)))
11871 (setcdr elt s))))
11872
11873 (defun org-table-get-specials ()
11874 "Get the column names and local parameters for this table."
11875 (save-excursion
11876 (let ((beg (org-table-begin)) (end (org-table-end))
11877 names name fields fields1 field cnt c v line col)
11878 (setq org-table-column-names nil
11879 org-table-local-parameters nil
11880 org-table-named-field-locations nil)
11881 (goto-char beg)
11882 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
11883 (setq names (org-split-string (match-string 1) " *| *")
11884 cnt 1)
11885 (while (setq name (pop names))
11886 (setq cnt (1+ cnt))
11887 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
11888 (push (cons name (int-to-string cnt)) org-table-column-names))))
11889 (setq org-table-column-names (nreverse org-table-column-names))
11890 (setq org-table-column-name-regexp
11891 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
11892 (goto-char beg)
11893 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
11894 (setq fields (org-split-string (match-string 1) " *| *"))
11895 (while (setq field (pop fields))
11896 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
11897 (push (cons (match-string 1 field) (match-string 2 field))
11898 org-table-local-parameters))))
11899 (goto-char beg)
11900 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
11901 (setq c (match-string 1)
11902 fields (org-split-string (match-string 2) " *| *"))
11903 (save-excursion
11904 (beginning-of-line (if (equal c "_") 2 0))
11905 (setq line (org-current-line) col 1)
11906 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
11907 (setq fields1 (org-split-string (match-string 1) " *| *"))))
11908 (while (and fields1 (setq field (pop fields)))
11909 (setq v (pop fields1) col (1+ col))
11910 (when (and (stringp field) (stringp v)
11911 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
11912 (push (cons field v) org-table-local-parameters)
11913 (push (list field line col) org-table-named-field-locations)))))))
11914
11915 (defun org-this-word ()
11916 ;; Get the current word
11917 (save-excursion
11918 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
11919 (end (progn (skip-chars-forward "^ \t\n") (point))))
11920 (buffer-substring-no-properties beg end))))
11921
11922 (defun org-table-maybe-eval-formula ()
11923 "Check if the current field starts with \"=\" or \":=\".
11924 If yes, store the formula and apply it."
11925 ;; We already know we are in a table. Get field will only return a formula
11926 ;; when appropriate. It might return a separator line, but no problem.
11927 (when org-table-formula-evaluate-inline
11928 (let* ((field (org-trim (or (org-table-get-field) "")))
11929 named eq)
11930 (when (string-match "^:?=\\(.*\\)" field)
11931 (setq named (equal (string-to-char field) ?:)
11932 eq (match-string 1 field))
11933 (if (fboundp 'calc-eval)
11934 (org-table-eval-formula (if named '(4) nil) eq))))))
11935
11936 (defvar org-recalc-commands nil
11937 "List of commands triggering the recalculation of a line.
11938 Will be filled automatically during use.")
11939
11940 (defvar org-recalc-marks
11941 '((" " . "Unmarked: no special line, no automatic recalculation")
11942 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
11943 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
11944 ("!" . "Column name definition line. Reference in formula as $name.")
11945 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
11946 ("_" . "Names for values in row below this one.")
11947 ("^" . "Names for values in row above this one.")))
11948
11949 (defun org-table-rotate-recalc-marks (&optional newchar)
11950 "Rotate the recalculation mark in the first column.
11951 If in any row, the first field is not consistent with a mark,
11952 insert a new column for the markers.
11953 When there is an active region, change all the lines in the region,
11954 after prompting for the marking character.
11955 After each change, a message will be displayed indicating the meaning
11956 of the new mark."
11957 (interactive)
11958 (unless (org-at-table-p) (error "Not at a table"))
11959 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
11960 (beg (org-table-begin))
11961 (end (org-table-end))
11962 (l (org-current-line))
11963 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
11964 (l2 (if (org-region-active-p) (org-current-line (region-end))))
11965 (have-col
11966 (save-excursion
11967 (goto-char beg)
11968 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
11969 (col (org-table-current-column))
11970 (forcenew (car (assoc newchar org-recalc-marks)))
11971 epos new)
11972 (when l1
11973 (message "Change region to what mark? Type # * ! $ or SPC: ")
11974 (setq newchar (char-to-string (read-char-exclusive))
11975 forcenew (car (assoc newchar org-recalc-marks))))
11976 (if (and newchar (not forcenew))
11977 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
11978 newchar))
11979 (if l1 (goto-line l1))
11980 (save-excursion
11981 (beginning-of-line 1)
11982 (unless (looking-at org-table-dataline-regexp)
11983 (error "Not at a table data line")))
11984 (unless have-col
11985 (org-table-goto-column 1)
11986 (org-table-insert-column)
11987 (org-table-goto-column (1+ col)))
11988 (setq epos (point-at-eol))
11989 (save-excursion
11990 (beginning-of-line 1)
11991 (org-table-get-field
11992 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
11993 (concat " "
11994 (setq new (or forcenew
11995 (cadr (member (match-string 1) marks))))
11996 " ")
11997 " # ")))
11998 (if (and l1 l2)
11999 (progn
12000 (goto-line l1)
12001 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
12002 (and (looking-at org-table-dataline-regexp)
12003 (org-table-get-field 1 (concat " " new " "))))
12004 (goto-line l1)))
12005 (if (not (= epos (point-at-eol))) (org-table-align))
12006 (goto-line l)
12007 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
12008
12009 (defun org-table-maybe-recalculate-line ()
12010 "Recompute the current line if marked for it, and if we haven't just done it."
12011 (interactive)
12012 (and org-table-allow-automatic-line-recalculation
12013 (not (and (memq last-command org-recalc-commands)
12014 (equal org-last-recalc-line (org-current-line))))
12015 (save-excursion (beginning-of-line 1)
12016 (looking-at org-table-auto-recalculate-regexp))
12017 (fboundp 'calc-eval)
12018 (org-table-recalculate) t))
12019
12020 (defvar org-table-formula-debug nil
12021 "Non-nil means, debug table formulas.
12022 When nil, simply write \"#ERROR\" in corrupted fields.")
12023
12024 (defvar modes)
12025 (defsubst org-set-calc-mode (var &optional value)
12026 (if (stringp var)
12027 (setq var (assoc var '(("D" calc-angle-mode deg)
12028 ("R" calc-angle-mode rad)
12029 ("F" calc-prefer-frac t)
12030 ("S" calc-symbolic-mode t)))
12031 value (nth 2 var) var (nth 1 var)))
12032 (if (memq var modes)
12033 (setcar (cdr (memq var modes)) value)
12034 (cons var (cons value modes)))
12035 modes)
12036
12037 (defun org-table-eval-formula (&optional arg equation
12038 suppress-align suppress-const
12039 suppress-store)
12040 "Replace the table field value at the cursor by the result of a calculation.
12041
12042 This function makes use of Dave Gillespie's Calc package, in my view the
12043 most exciting program ever written for GNU Emacs. So you need to have Calc
12044 installed in order to use this function.
12045
12046 In a table, this command replaces the value in the current field with the
12047 result of a formula. It also installs the formula as the \"current\" column
12048 formula, by storing it in a special line below the table. When called
12049 with a `C-u' prefix, the current field must ba a named field, and the
12050 formula is installed as valid in only this specific field.
12051
12052 When called, the command first prompts for a formula, which is read in
12053 the minibuffer. Previously entered formulas are available through the
12054 history list, and the last used formula is offered as a default.
12055 These stored formulas are adapted correctly when moving, inserting, or
12056 deleting columns with the corresponding commands.
12057
12058 The formula can be any algebraic expression understood by the Calc package.
12059 For details, see the Org-mode manual.
12060
12061 This function can also be called from Lisp programs and offers
12062 additional arguments: EQUATION can be the formula to apply. If this
12063 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
12064 used to speed-up recursive calls by by-passing unnecessary aligns.
12065 SUPPRESS-CONST suppresses the interpretation of constants in the
12066 formula, assuming that this has been done already outside the function.
12067 SUPPRESS-STORE means the formula should not be stored, either because
12068 it is already stored, or because it is a modified equation that should
12069 not overwrite the stored one."
12070 (interactive "P")
12071 (require 'calc)
12072 (org-table-check-inside-data-field)
12073 (org-table-get-specials)
12074 (let* (fields
12075 (ndown (if (integerp arg) arg 1))
12076 (org-table-automatic-realign nil)
12077 (case-fold-search nil)
12078 (down (> ndown 1))
12079 (formula (if (and equation suppress-store)
12080 equation
12081 (org-table-get-formula equation (equal arg '(4)))))
12082 (n0 (org-table-current-column))
12083 (modes (copy-sequence org-calc-default-modes))
12084 n form fmt x ev orig c lispp)
12085 ;; Parse the format string. Since we have a lot of modes, this is
12086 ;; a lot of work. However, I think calc still uses most of the time.
12087 (if (string-match ";" formula)
12088 (let ((tmp (org-split-string formula ";")))
12089 (setq formula (car tmp)
12090 fmt (concat (cdr (assoc "%" org-table-local-parameters))
12091 (nth 1 tmp)))
12092 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
12093 (setq c (string-to-char (match-string 1 fmt))
12094 n (string-to-number (or (match-string 1 fmt) "")))
12095 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
12096 (setq modes (org-set-calc-mode
12097 'calc-float-format
12098 (list (cdr (assoc c '((?n . float) (?f . fix)
12099 (?s . sci) (?e . eng))))
12100 n))))
12101 (setq fmt (replace-match "" t t fmt)))
12102 (while (string-match "[DRFS]" fmt)
12103 (setq modes (org-set-calc-mode (match-string 0 fmt)))
12104 (setq fmt (replace-match "" t t fmt)))
12105 (unless (string-match "\\S-" fmt)
12106 (setq fmt nil))))
12107 (if (and (not suppress-const) org-table-formula-use-constants)
12108 (setq formula (org-table-formula-substitute-names formula)))
12109 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
12110 (while (> ndown 0)
12111 (setq fields (org-split-string
12112 (buffer-substring
12113 (point-at-bol) (point-at-eol)) " *| *"))
12114 (if org-table-formula-numbers-only
12115 (setq fields (mapcar
12116 (lambda (x) (number-to-string (string-to-number x)))
12117 fields)))
12118 (setq ndown (1- ndown))
12119 (setq form (copy-sequence formula)
12120 lispp (equal (substring form 0 2) "'("))
12121 ;; Insert the references to fields in same row
12122 (while (string-match "\\$\\([0-9]+\\)?" form)
12123 (setq n (if (match-beginning 1)
12124 (string-to-number (match-string 1 form))
12125 n0)
12126 x (nth (1- n) fields))
12127 (unless x (error "Invalid field specifier \"%s\""
12128 (match-string 0 form)))
12129 (if (equal x "") (setq x "0"))
12130 (setq form (replace-match
12131 (if lispp x (concat "(" x ")"))
12132 t t form)))
12133 ;; Insert ranges in current column
12134 (while (string-match "\\&[-I0-9]+" form)
12135 (setq form (replace-match
12136 (save-match-data
12137 (org-table-get-vertical-vector (match-string 0 form)
12138 nil n0))
12139 t t form)))
12140 (if lispp
12141 (setq ev (eval (eval (read form)))
12142 ev (if (numberp ev) (number-to-string ev) ev))
12143 (setq ev (calc-eval (cons form modes)
12144 (if org-table-formula-numbers-only 'num))))
12145
12146 (when org-table-formula-debug
12147 (with-output-to-temp-buffer "*Help*"
12148 (princ (format "Substitution history of formula
12149 Orig: %s
12150 $xyz-> %s
12151 $1-> %s\n" orig formula form))
12152 (if (listp ev)
12153 (princ (format " %s^\nError: %s"
12154 (make-string (car ev) ?\-) (nth 1 ev)))
12155 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
12156 ev (or fmt "NONE")
12157 (if fmt (format fmt (string-to-number ev)) ev)))))
12158 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
12159 (unless (and (interactive-p) (not ndown))
12160 (unless (let (inhibit-redisplay)
12161 (y-or-n-p "Debugging Formula. Continue to next? "))
12162 (org-table-align)
12163 (error "Abort"))
12164 (delete-window (get-buffer-window "*Help*"))
12165 (message "")))
12166 (if (listp ev) (setq fmt nil ev "#ERROR"))
12167 (org-table-justify-field-maybe
12168 (if fmt (format fmt (string-to-number ev)) ev))
12169 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
12170 (call-interactively 'org-return)
12171 (setq ndown 0)))
12172 (and down (org-table-maybe-recalculate-line))
12173 (or suppress-align (and org-table-may-need-update
12174 (org-table-align)))))
12175
12176 (defun org-table-recalculate (&optional all noalign)
12177 "Recalculate the current table line by applying all stored formulas.
12178 With prefix arg ALL, do this for all lines in the table."
12179 (interactive "P")
12180 (or (memq this-command org-recalc-commands)
12181 (setq org-recalc-commands (cons this-command org-recalc-commands)))
12182 (unless (org-at-table-p) (error "Not at a table"))
12183 (org-table-get-specials)
12184 (let* ((eqlist (sort (org-table-get-stored-formulas)
12185 (lambda (a b) (string< (car a) (car b)))))
12186 (inhibit-redisplay t)
12187 (line-re org-table-dataline-regexp)
12188 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
12189 (thiscol (org-table-current-column))
12190 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
12191 ;; Insert constants in all formulas
12192 (setq eqlist
12193 (mapcar (lambda (x)
12194 (setcdr x (org-table-formula-substitute-names (cdr x)))
12195 x)
12196 eqlist))
12197 ;; Split the equation list
12198 (while (setq eq (pop eqlist))
12199 (if (<= (string-to-char (car eq)) ?9)
12200 (push eq eqlnum)
12201 (push eq eqlname)))
12202 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
12203 (if all
12204 (progn
12205 (setq end (move-marker (make-marker) (1+ (org-table-end))))
12206 (goto-char (setq beg (org-table-begin)))
12207 (if (re-search-forward org-table-calculate-mark-regexp end t)
12208 ;; This is a table with marked lines, only compute selected lines
12209 (setq line-re org-table-recalculate-regexp)
12210 ;; Move forward to the first non-header line
12211 (if (and (re-search-forward org-table-dataline-regexp end t)
12212 (re-search-forward org-table-hline-regexp end t)
12213 (re-search-forward org-table-dataline-regexp end t))
12214 (setq beg (match-beginning 0))
12215 nil))) ;; just leave beg where it is
12216 (setq beg (point-at-bol)
12217 end (move-marker (make-marker) (1+ (point-at-eol)))))
12218 (goto-char beg)
12219 (and all (message "Re-applying formulas to full table..."))
12220 (while (re-search-forward line-re end t)
12221 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
12222 ;; Unprotected line, recalculate
12223 (and all (message "Re-applying formulas to full table...(line %d)"
12224 (setq cnt (1+ cnt))))
12225 (setq org-last-recalc-line (org-current-line))
12226 (setq eql eqlnum)
12227 (while (setq entry (pop eql))
12228 (goto-line org-last-recalc-line)
12229 (org-table-goto-column (string-to-number (car entry)) nil 'force)
12230 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
12231 (goto-line thisline)
12232 (org-table-goto-column thiscol)
12233 (or noalign (and org-table-may-need-update (org-table-align))
12234 (and all (message "Re-applying formulas to %d lines...done" cnt)))
12235 ;; Now do the names fields
12236 (while (setq eq (pop eqlname))
12237 (setq name (car eq)
12238 a (assoc name org-table-named-field-locations))
12239 (when a
12240 (message "Re-applying formula to named field: %s" name)
12241 (goto-line (nth 1 a))
12242 (org-table-goto-column (nth 2 a))
12243 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
12244 ;; back to initial position
12245 (goto-line thisline)
12246 (org-table-goto-column thiscol)
12247 (or noalign (and org-table-may-need-update (org-table-align))
12248 (and all (message "Re-applying formulas...done")))))
12249
12250 (defun org-table-formula-substitute-names (f)
12251 "Replace $const with values in string F."
12252 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
12253 ;; First, check for column names
12254 (while (setq start (string-match org-table-column-name-regexp f start))
12255 (setq start (1+ start))
12256 (setq a (assoc (match-string 1 f) org-table-column-names))
12257 (setq f (replace-match (concat "$" (cdr a)) t t f)))
12258 ;; Expand ranges to vectors
12259 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
12260 (setq n1 (string-to-number (match-string 1 f))
12261 n2 (string-to-number (match-string 2 f))
12262 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
12263 s (concat "[($" (number-to-string (1- nn1)) ")"))
12264 (loop for i from nn1 upto nn2 do
12265 (setq s (concat s ",($" (int-to-string i) ")")))
12266 (setq s (concat s "]"))
12267 (if (< n2 n1) (setq s (concat "rev(" s ")")))
12268 (setq f (replace-match s t t f)))
12269 ;; Parameters and constants
12270 (setq start 0)
12271 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
12272 (setq start (1+ start))
12273 (if (setq a (save-match-data
12274 (org-table-get-constant (match-string 1 f))))
12275 (setq f (replace-match (concat "(" a ")") t t f))))
12276 (if org-table-formula-debug
12277 (put-text-property 0 (length f) :orig-formula f1 f))
12278 f))
12279
12280 (defun org-table-get-constant (const)
12281 "Find the value for a parameter or constant in a formula.
12282 Parameters get priority."
12283 (or (cdr (assoc const org-table-local-parameters))
12284 (cdr (assoc const org-table-formula-constants))
12285 (and (fboundp 'constants-get) (constants-get const))
12286 "#UNDEFINED_NAME"))
12287
12288 (defvar org-edit-formulas-map (make-sparse-keymap))
12289 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
12290 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
12291 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
12292
12293 (defvar org-pos)
12294
12295 (defun org-table-edit-formulas ()
12296 "Edit the formulas of the current table in a separate buffer."
12297 (interactive)
12298 (unless (org-at-table-p)
12299 (error "Not at a table"))
12300 (org-table-get-specials)
12301 (let ((eql (org-table-get-stored-formulas))
12302 (pos (move-marker (make-marker) (point)))
12303 (wc (current-window-configuration))
12304 entry loc s)
12305 (switch-to-buffer-other-window "*Edit Formulas*")
12306 (erase-buffer)
12307 (fundamental-mode)
12308 (set (make-local-variable 'org-pos) pos)
12309 (set (make-local-variable 'org-window-configuration) wc)
12310 (use-local-map org-edit-formulas-map)
12311 (setq s "# Edit formulas and finish with `C-c C-c'.
12312 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
12313 # Use `C-c ?' to get information about $name at point.
12314 # To cancel editing, press `C-c C-q'.\n")
12315 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12316 (insert s)
12317 (while (setq entry (pop eql))
12318 (when (setq loc (assoc (car entry) org-table-named-field-locations))
12319 (setq s (format "# Named formula, referring to column %d in line %d\n"
12320 (nth 2 loc) (nth 1 loc)))
12321 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12322 (insert s))
12323 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
12324 (remove-text-properties 0 (length s) '(face nil) s)
12325 (insert s))
12326 (goto-char (point-min))
12327 (message "Edit formulas and finish with `C-c C-c'.")))
12328
12329 (defun org-show-variable ()
12330 "Show the location/value of the $ expression at point."
12331 (interactive)
12332 (let (var (pos org-pos) (win (selected-window)) e)
12333 (save-excursion
12334 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
12335 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
12336 (setq var (match-string 1))
12337 (error "No variable at point")))
12338 (cond
12339 ((setq e (assoc var org-table-named-field-locations))
12340 (switch-to-buffer-other-window (marker-buffer pos))
12341 (goto-line (nth 1 e))
12342 (org-table-goto-column (nth 2 e))
12343 (select-window win)
12344 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
12345 ((setq e (assoc var org-table-column-names))
12346 (switch-to-buffer-other-window (marker-buffer pos))
12347 (goto-char pos)
12348 (goto-char (org-table-begin))
12349 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
12350 (org-table-end) t)
12351 (progn
12352 (goto-char (match-beginning 1))
12353 (message "Named column (column %s)" (cdr e)))
12354 (error "Column name not found"))
12355 (select-window win))
12356 ((string-match "^[0-9]$" var)
12357 ;; column number
12358 (switch-to-buffer-other-window (marker-buffer pos))
12359 (goto-char pos)
12360 (goto-char (org-table-begin))
12361 (recenter 1)
12362 (if (re-search-forward org-table-dataline-regexp
12363 (org-table-end) t)
12364 (progn
12365 (goto-char (match-beginning 0))
12366 (org-table-goto-column (string-to-number var))
12367 (message "Column %s" var))
12368 (error "Column name not found"))
12369 (select-window win))
12370 ((setq e (assoc var org-table-local-parameters))
12371 (switch-to-buffer-other-window (marker-buffer pos))
12372 (goto-char pos)
12373 (goto-char (org-table-begin))
12374 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
12375 (progn
12376 (goto-char (match-beginning 1))
12377 (message "Local parameter."))
12378 (error "Parameter not found"))
12379 (select-window win))
12380 (t
12381 (cond
12382 ((setq e (assoc var org-table-formula-constants))
12383 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
12384 ((setq e (and (fboundp 'constants-get) (constants-get var)))
12385 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
12386 (t (error "Undefined name $%s" var)))))))
12387
12388 (defun org-finish-edit-formulas (&optional arg)
12389 "Parse the buffer for formula definitions and install them.
12390 With prefix ARG, apply the new formulas to the table."
12391 (interactive "P")
12392 (let ((pos org-pos) eql)
12393 (goto-char (point-min))
12394 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
12395 (push (cons (match-string 1) (match-string 2)) eql))
12396 (set-window-configuration org-window-configuration)
12397 (select-window (get-buffer-window (marker-buffer pos)))
12398 (goto-char pos)
12399 (unless (org-at-table-p)
12400 (error "Lost table position - cannot install formulae"))
12401 (org-table-store-formulas eql)
12402 (move-marker pos nil)
12403 (kill-buffer "*Edit Formulas*")
12404 (if arg
12405 (org-table-recalculate 'all)
12406 (message "New formulas installed - press C-u C-c C-c to apply."))))
12407
12408 (defun org-abort-edit-formulas ()
12409 "Abort editing formulas, without installing the changes."
12410 (interactive)
12411 (let ((pos org-pos))
12412 (set-window-configuration org-window-configuration)
12413 (select-window (get-buffer-window (marker-buffer pos)))
12414 (goto-char pos)
12415 (message "Formula editing aborted without installing changes")))
12416
12417 ;;; The orgtbl minor mode
12418
12419 ;; Define a minor mode which can be used in other modes in order to
12420 ;; integrate the org-mode table editor.
12421
12422 ;; This is really a hack, because the org-mode table editor uses several
12423 ;; keys which normally belong to the major mode, for example the TAB and
12424 ;; RET keys. Here is how it works: The minor mode defines all the keys
12425 ;; necessary to operate the table editor, but wraps the commands into a
12426 ;; function which tests if the cursor is currently inside a table. If that
12427 ;; is the case, the table editor command is executed. However, when any of
12428 ;; those keys is used outside a table, the function uses `key-binding' to
12429 ;; look up if the key has an associated command in another currently active
12430 ;; keymap (minor modes, major mode, global), and executes that command.
12431 ;; There might be problems if any of the keys used by the table editor is
12432 ;; otherwise used as a prefix key.
12433
12434 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
12435 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
12436 ;; addresses this by checking explicitly for both bindings.
12437
12438 ;; The optimized version (see variable `orgtbl-optimized') takes over
12439 ;; all keys which are bound to `self-insert-command' in the *global map*.
12440 ;; Some modes bind other commands to simple characters, for example
12441 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
12442 ;; active, this binding is ignored inside tables and replaced with a
12443 ;; modified self-insert.
12444
12445 (defvar orgtbl-mode nil
12446 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
12447 table editor in arbitrary modes.")
12448 (make-variable-buffer-local 'orgtbl-mode)
12449
12450 (defvar orgtbl-mode-map (make-keymap)
12451 "Keymap for `orgtbl-mode'.")
12452
12453 ;;;###autoload
12454 (defun turn-on-orgtbl ()
12455 "Unconditionally turn on `orgtbl-mode'."
12456 (orgtbl-mode 1))
12457
12458 ;;;###autoload
12459 (defun orgtbl-mode (&optional arg)
12460 "The `org-mode' table editor as a minor mode for use in other modes."
12461 (interactive)
12462 (if (org-mode-p)
12463 ;; Exit without error, in case some hook functions calls this
12464 ;; by accident in org-mode.
12465 (message "Orgtbl-mode is not useful in org-mode, command ignored")
12466 (setq orgtbl-mode
12467 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
12468 (if orgtbl-mode
12469 (progn
12470 (and (orgtbl-setup) (defun orgtbl-setup () nil))
12471 ;; Make sure we are first in minor-mode-map-alist
12472 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
12473 (and c (setq minor-mode-map-alist
12474 (cons c (delq c minor-mode-map-alist)))))
12475 (set (make-local-variable (quote org-table-may-need-update)) t)
12476 (org-add-hook 'before-change-functions 'org-before-change-function
12477 nil 'local)
12478 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
12479 auto-fill-inhibit-regexp)
12480 (set (make-local-variable 'auto-fill-inhibit-regexp)
12481 (if auto-fill-inhibit-regexp
12482 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
12483 "[ \t]*|"))
12484 (org-add-to-invisibility-spec '(org-cwidth))
12485 (easy-menu-add orgtbl-mode-menu)
12486 (run-hooks 'orgtbl-mode-hook))
12487 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
12488 (org-cleanup-narrow-column-properties)
12489 (org-remove-from-invisibility-spec '(org-cwidth))
12490 (remove-hook 'before-change-functions 'org-before-change-function t)
12491 (easy-menu-remove orgtbl-mode-menu)
12492 (force-mode-line-update 'all))))
12493
12494 (defun org-cleanup-narrow-column-properties ()
12495 "Remove all properties related to narrow-column invisibility."
12496 (let ((s 1))
12497 (while (setq s (text-property-any s (point-max)
12498 'display org-narrow-column-arrow))
12499 (remove-text-properties s (1+ s) '(display t)))
12500 (setq s 1)
12501 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
12502 (remove-text-properties s (1+ s) '(org-cwidth t)))
12503 (setq s 1)
12504 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
12505 (remove-text-properties s (1+ s) '(invisible t)))))
12506
12507 ;; Install it as a minor mode.
12508 (put 'orgtbl-mode :included t)
12509 (put 'orgtbl-mode :menu-tag "Org Table Mode")
12510 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
12511
12512 (defun orgtbl-make-binding (fun n &rest keys)
12513 "Create a function for binding in the table minor mode.
12514 FUN is the command to call inside a table. N is used to create a unique
12515 command name. KEYS are keys that should be checked in for a command
12516 to execute outside of tables."
12517 (eval
12518 (list 'defun
12519 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
12520 '(arg)
12521 (concat "In tables, run `" (symbol-name fun) "'.\n"
12522 "Outside of tables, run the binding of `"
12523 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
12524 "'.")
12525 '(interactive "p")
12526 (list 'if
12527 '(org-at-table-p)
12528 (list 'call-interactively (list 'quote fun))
12529 (list 'let '(orgtbl-mode)
12530 (list 'call-interactively
12531 (append '(or)
12532 (mapcar (lambda (k)
12533 (list 'key-binding k))
12534 keys)
12535 '('orgtbl-error))))))))
12536
12537 (defun orgtbl-error ()
12538 "Error when there is no default binding for a table key."
12539 (interactive)
12540 (error "This key is has no function outside tables"))
12541
12542 (defun orgtbl-setup ()
12543 "Setup orgtbl keymaps."
12544 (let ((nfunc 0)
12545 (bindings
12546 (list
12547 '([(meta shift left)] org-table-delete-column)
12548 '([(meta left)] org-table-move-column-left)
12549 '([(meta right)] org-table-move-column-right)
12550 '([(meta shift right)] org-table-insert-column)
12551 '([(meta shift up)] org-table-kill-row)
12552 '([(meta shift down)] org-table-insert-row)
12553 '([(meta up)] org-table-move-row-up)
12554 '([(meta down)] org-table-move-row-down)
12555 '("\C-c\C-w" org-table-cut-region)
12556 '("\C-c\M-w" org-table-copy-region)
12557 '("\C-c\C-y" org-table-paste-rectangle)
12558 '("\C-c-" org-table-insert-hline)
12559 ; '([(shift tab)] org-table-previous-field)
12560 '("\C-m" org-table-next-row)
12561 (list (org-key 'S-return) 'org-table-copy-down)
12562 '([(meta return)] org-table-wrap-region)
12563 '("\C-c\C-q" org-table-wrap-region)
12564 '("\C-c?" org-table-current-column)
12565 '("\C-c " org-table-blank-field)
12566 '("\C-c+" org-table-sum)
12567 '("\C-c=" org-table-eval-formula)
12568 '("\C-c'" org-table-edit-formulas)
12569 '("\C-c`" org-table-edit-field)
12570 '("\C-c*" org-table-recalculate)
12571 '("\C-c|" org-table-create-or-convert-from-region)
12572 '("\C-c^" org-table-sort-lines)
12573 '([(control ?#)] org-table-rotate-recalc-marks)))
12574 elt key fun cmd)
12575 (while (setq elt (pop bindings))
12576 (setq nfunc (1+ nfunc))
12577 (setq key (car elt)
12578 fun (nth 1 elt)
12579 cmd (orgtbl-make-binding fun nfunc key))
12580 (define-key orgtbl-mode-map key cmd))
12581 ;; Special treatment needed for TAB and RET
12582 (define-key orgtbl-mode-map [(return)]
12583 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
12584 (define-key orgtbl-mode-map "\C-m"
12585 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
12586 (define-key orgtbl-mode-map [(tab)]
12587 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
12588 (define-key orgtbl-mode-map "\C-i"
12589 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
12590 (define-key orgtbl-mode-map "\C-i"
12591 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
12592 (define-key orgtbl-mode-map "\C-c\C-c"
12593 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
12594 (when orgtbl-optimized
12595 ;; If the user wants maximum table support, we need to hijack
12596 ;; some standard editing functions
12597 (org-remap orgtbl-mode-map
12598 'self-insert-command 'orgtbl-self-insert-command
12599 'delete-char 'org-delete-char
12600 'delete-backward-char 'org-delete-backward-char)
12601 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
12602 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
12603 '("OrgTbl"
12604 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
12605 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
12606 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
12607 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
12608 "--"
12609 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
12610 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
12611 ["Copy Field from Above"
12612 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
12613 "--"
12614 ("Column"
12615 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
12616 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
12617 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
12618 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
12619 "--"
12620 ["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])
12621 ("Row"
12622 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
12623 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
12624 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
12625 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
12626 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
12627 "--"
12628 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
12629 ("Rectangle"
12630 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
12631 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
12632 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
12633 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
12634 "--"
12635 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
12636 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12637 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
12638 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
12639 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
12640 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
12641 ["Sum Column/Rectangle" org-table-sum
12642 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
12643 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
12644 ["Debug Formulas"
12645 (setq org-table-formula-debug (not org-table-formula-debug))
12646 :style toggle :selected org-table-formula-debug]
12647 ))
12648 t)
12649
12650 (defun orgtbl-tab (arg)
12651 "Justification and field motion for `orgtbl-mode'."
12652 (interactive "P")
12653 (if arg (org-table-edit-field t)
12654 (org-table-justify-field-maybe)
12655 (org-table-next-field)))
12656
12657 (defun orgtbl-ret ()
12658 "Justification and field motion for `orgtbl-mode'."
12659 (interactive)
12660 (org-table-justify-field-maybe)
12661 (org-table-next-row))
12662
12663 (defun orgtbl-self-insert-command (N)
12664 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12665 If the cursor is in a table looking at whitespace, the whitespace is
12666 overwritten, and the table is not marked as requiring realignment."
12667 (interactive "p")
12668 (if (and (org-at-table-p)
12669 (or
12670 (and org-table-auto-blank-field
12671 (member last-command
12672 '(orgtbl-hijacker-command-100
12673 orgtbl-hijacker-command-101
12674 orgtbl-hijacker-command-102
12675 orgtbl-hijacker-command-103
12676 orgtbl-hijacker-command-104
12677 orgtbl-hijacker-command-105))
12678 (org-table-blank-field))
12679 t)
12680 (eq N 1)
12681 (looking-at "[^|\n]* +|"))
12682 (let (org-table-may-need-update)
12683 (goto-char (1- (match-end 0)))
12684 (delete-backward-char 1)
12685 (goto-char (match-beginning 0))
12686 (self-insert-command N))
12687 (setq org-table-may-need-update t)
12688 (let (orgtbl-mode)
12689 (call-interactively (key-binding (vector last-input-event))))))
12690
12691 (defun org-force-self-insert (N)
12692 "Needed to enforce self-insert under remapping."
12693 (interactive "p")
12694 (self-insert-command N))
12695
12696 ;;; Exporting
12697
12698 (defconst org-level-max 20)
12699
12700 (defvar org-export-html-preamble nil
12701 "Preamble, to be inserted just after <body>. Set by publishing functions.")
12702 (defvar org-export-html-postamble nil
12703 "Preamble, to be inserted just before </body>. Set by publishing functions.")
12704 (defvar org-export-html-auto-preamble t
12705 "Should default preamble be inserted? Set by publishing functions.")
12706 (defvar org-export-html-auto-postamble t
12707 "Should default postamble be inserted? Set by publishing functions.")
12708
12709 (defconst org-export-plist-vars
12710 '((:language . org-export-default-language)
12711 (:headline-levels . org-export-headline-levels)
12712 (:section-numbers . org-export-with-section-numbers)
12713 (:table-of-contents . org-export-with-toc)
12714 (:archived-trees . org-export-with-archived-trees)
12715 (:emphasize . org-export-with-emphasize)
12716 (:sub-superscript . org-export-with-sub-superscripts)
12717 (:TeX-macros . org-export-with-TeX-macros)
12718 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
12719 (:fixed-width . org-export-with-fixed-width)
12720 (:timestamps . org-export-with-timestamps)
12721 (:tables . org-export-with-tables)
12722 (:table-auto-headline . org-export-highlight-first-table-line)
12723 (:style . org-export-html-style)
12724 (:convert-org-links . org-export-html-link-org-files-as-html)
12725 (:inline-images . org-export-html-inline-images)
12726 (:expand-quoted-html . org-export-html-expand)
12727 (:timestamp . org-export-html-with-timestamp)
12728 (:publishing-directory . org-export-publishing-directory)
12729 (:preamble . org-export-html-preamble)
12730 (:postamble . org-export-html-postamble)
12731 (:auto-preamble . org-export-html-auto-preamble)
12732 (:auto-postamble . org-export-html-auto-postamble)
12733 (:author . user-full-name)
12734 (:email . user-mail-address)))
12735
12736 (defun org-default-export-plist ()
12737 "Return the property list with default settings for the export variables."
12738 (let ((l org-export-plist-vars) rtn e)
12739 (while (setq e (pop l))
12740 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
12741 rtn))
12742
12743 (defun org-infile-export-plist ()
12744 "Return the property list with file-local settings for export."
12745 (save-excursion
12746 (goto-char 0)
12747 (let ((re (org-make-options-regexp
12748 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12749 p key val text options)
12750 (while (re-search-forward re nil t)
12751 (setq key (org-match-string-no-properties 1)
12752 val (org-match-string-no-properties 2))
12753 (cond
12754 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
12755 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
12756 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
12757 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
12758 ((string-equal key "TEXT")
12759 (setq text (if text (concat text "\n" val) val)))
12760 ((string-equal key "OPTIONS") (setq options val))))
12761 (setq p (plist-put p :text text))
12762 (when options
12763 (let ((op '(("H" . :headline-levels)
12764 ("num" . :section-numbers)
12765 ("toc" . :table-of-contents)
12766 ("\\n" . :preserve-breaks)
12767 ("@" . :expand-quoted-html)
12768 (":" . :fixed-width)
12769 ("|" . :tables)
12770 ("^" . :sub-superscript)
12771 ("*" . :emphasize)
12772 ("TeX" . :TeX-macros)
12773 ("LaTeX" . :LaTeX-fragments)))
12774 o)
12775 (while (setq o (pop op))
12776 (if (string-match (concat (regexp-quote (car o))
12777 ":\\([^ \t\n\r;,.]*\\)")
12778 options)
12779 (setq p (plist-put p (cdr o)
12780 (car (read-from-string
12781 (match-string 1 options)))))))))
12782 p)))
12783
12784 (defun org-combine-plists (&rest plists)
12785 "Create a single property list from all plists in PLISTS.
12786 The process starts by copying the last list, and then setting properties
12787 from the other lists. Settings in the first list are the most significant
12788 ones and overrule settings in the other lists."
12789 (let ((rtn (copy-sequence (pop plists)))
12790 p v ls)
12791 (while plists
12792 (setq ls (pop plists))
12793 (while ls
12794 (setq p (pop ls) v (pop ls))
12795 (setq rtn (plist-put rtn p v))))
12796 rtn))
12797
12798 (defun org-export-directory (type plist)
12799 (let* ((val (plist-get plist :publishing-directory))
12800 (dir (if (listp val)
12801 (or (cdr (assoc type val)) ".")
12802 val)))
12803 dir))
12804
12805 (defun org-export-find-first-heading-line (list)
12806 "Remove all lines from LIST which are before the first headline."
12807 (let ((orig-list list)
12808 (re (concat "^" outline-regexp)))
12809 (while (and list
12810 (not (string-match re (car list))))
12811 (pop list))
12812 (or list orig-list)))
12813
12814 (defun org-skip-comments (lines)
12815 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
12816 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
12817 (re2 "^\\(\\*+\\)[ \t\n\r]")
12818 rtn line level)
12819 (while (setq line (pop lines))
12820 (cond
12821 ((and (string-match re1 line)
12822 (setq level (- (match-end 1) (match-beginning 1))))
12823 ;; Beginning of a COMMENT subtree. Skip it.
12824 (while (and (setq line (pop lines))
12825 (or (not (string-match re2 line))
12826 (> (- (match-end 1) (match-beginning 1)) level))))
12827 (setq lines (cons line lines)))
12828 ((string-match "^#" line)
12829 ;; an ordinary comment line
12830 )
12831 ((and org-export-table-remove-special-lines
12832 (string-match "^[ \t]*|" line)
12833 (or (string-match "^[ \t]*| *[!_^] *|" line)
12834 (and (string-match "| *<[0-9]+> *|" line)
12835 (not (string-match "| *[^ <|]" line)))))
12836 ;; a special table line that should be removed
12837 )
12838 (t (setq rtn (cons line rtn)))))
12839 (nreverse rtn)))
12840
12841 (defun org-export (&optional arg)
12842 (interactive)
12843 (let ((help "[t] insert the export option template
12844 \[v] limit export to visible part of outline tree
12845
12846 \[a] export as ASCII
12847 \[h] export as HTML
12848 \[b] export as HTML and browse immediately
12849 \[x] export as XOXO
12850
12851 \[i] export current file as iCalendar file
12852 \[I] export all agenda files as iCalendar files
12853 \[c] export agenda files into combined iCalendar file
12854
12855 \[F] publish current file
12856 \[P] publish current project
12857 \[X] publish... (project will be prompted for)
12858 \[A] publish all projects")
12859 (cmds
12860 '((?t . org-insert-export-options-template)
12861 (?v . org-export-visible)
12862 (?a . org-export-as-ascii)
12863 (?h . org-export-as-html)
12864 (?b . org-export-as-html-and-open)
12865 (?x . org-export-as-xoxo)
12866 (?i . org-export-icalendar-this-file)
12867 (?I . org-export-icalendar-all-agenda-files)
12868 (?c . org-export-icalendar-combine-agenda-files)
12869 (?F . org-publish-current-file)
12870 (?P . org-publish-current-project)
12871 (?X . org-publish)
12872 (?A . org-publish-all)))
12873 r1 r2 ass)
12874 (save-window-excursion
12875 (delete-other-windows)
12876 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
12877 (princ help))
12878 (message "Select command: ")
12879 (setq r1 (read-char-exclusive)))
12880 (setq r2 (if (< r1 27) (+ r1 96) r1))
12881 (if (setq ass (assq r2 cmds))
12882 (call-interactively (cdr ass))
12883 (error "No command associated with key %c" r1))))
12884
12885 ;; ASCII
12886
12887 (defconst org-html-entities
12888 '(("nbsp")
12889 ("iexcl")
12890 ("cent")
12891 ("pound")
12892 ("curren")
12893 ("yen")
12894 ("brvbar")
12895 ("sect")
12896 ("uml")
12897 ("copy")
12898 ("ordf")
12899 ("laquo")
12900 ("not")
12901 ("shy")
12902 ("reg")
12903 ("macr")
12904 ("deg")
12905 ("plusmn")
12906 ("sup2")
12907 ("sup3")
12908 ("acute")
12909 ("micro")
12910 ("para")
12911 ("middot")
12912 ("odot"."o")
12913 ("star"."*")
12914 ("cedil")
12915 ("sup1")
12916 ("ordm")
12917 ("raquo")
12918 ("frac14")
12919 ("frac12")
12920 ("frac34")
12921 ("iquest")
12922 ("Agrave")
12923 ("Aacute")
12924 ("Acirc")
12925 ("Atilde")
12926 ("Auml")
12927 ("Aring") ("AA"."&Aring;")
12928 ("AElig")
12929 ("Ccedil")
12930 ("Egrave")
12931 ("Eacute")
12932 ("Ecirc")
12933 ("Euml")
12934 ("Igrave")
12935 ("Iacute")
12936 ("Icirc")
12937 ("Iuml")
12938 ("ETH")
12939 ("Ntilde")
12940 ("Ograve")
12941 ("Oacute")
12942 ("Ocirc")
12943 ("Otilde")
12944 ("Ouml")
12945 ("times")
12946 ("Oslash")
12947 ("Ugrave")
12948 ("Uacute")
12949 ("Ucirc")
12950 ("Uuml")
12951 ("Yacute")
12952 ("THORN")
12953 ("szlig")
12954 ("agrave")
12955 ("aacute")
12956 ("acirc")
12957 ("atilde")
12958 ("auml")
12959 ("aring")
12960 ("aelig")
12961 ("ccedil")
12962 ("egrave")
12963 ("eacute")
12964 ("ecirc")
12965 ("euml")
12966 ("igrave")
12967 ("iacute")
12968 ("icirc")
12969 ("iuml")
12970 ("eth")
12971 ("ntilde")
12972 ("ograve")
12973 ("oacute")
12974 ("ocirc")
12975 ("otilde")
12976 ("ouml")
12977 ("divide")
12978 ("oslash")
12979 ("ugrave")
12980 ("uacute")
12981 ("ucirc")
12982 ("uuml")
12983 ("yacute")
12984 ("thorn")
12985 ("yuml")
12986 ("fnof")
12987 ("Alpha")
12988 ("Beta")
12989 ("Gamma")
12990 ("Delta")
12991 ("Epsilon")
12992 ("Zeta")
12993 ("Eta")
12994 ("Theta")
12995 ("Iota")
12996 ("Kappa")
12997 ("Lambda")
12998 ("Mu")
12999 ("Nu")
13000 ("Xi")
13001 ("Omicron")
13002 ("Pi")
13003 ("Rho")
13004 ("Sigma")
13005 ("Tau")
13006 ("Upsilon")
13007 ("Phi")
13008 ("Chi")
13009 ("Psi")
13010 ("Omega")
13011 ("alpha")
13012 ("beta")
13013 ("gamma")
13014 ("delta")
13015 ("epsilon")
13016 ("varepsilon"."&epsilon;")
13017 ("zeta")
13018 ("eta")
13019 ("theta")
13020 ("iota")
13021 ("kappa")
13022 ("lambda")
13023 ("mu")
13024 ("nu")
13025 ("xi")
13026 ("omicron")
13027 ("pi")
13028 ("rho")
13029 ("sigmaf") ("varsigma"."&sigmaf;")
13030 ("sigma")
13031 ("tau")
13032 ("upsilon")
13033 ("phi")
13034 ("chi")
13035 ("psi")
13036 ("omega")
13037 ("thetasym") ("vartheta"."&thetasym;")
13038 ("upsih")
13039 ("piv")
13040 ("bull") ("bullet"."&bull;")
13041 ("hellip") ("dots"."&hellip;")
13042 ("prime")
13043 ("Prime")
13044 ("oline")
13045 ("frasl")
13046 ("weierp")
13047 ("image")
13048 ("real")
13049 ("trade")
13050 ("alefsym")
13051 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
13052 ("uarr") ("uparrow"."&uarr;")
13053 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
13054 ("darr")("downarrow"."&darr;")
13055 ("harr") ("leftrightarrow"."&harr;")
13056 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
13057 ("lArr") ("Leftarrow"."&lArr;")
13058 ("uArr") ("Uparrow"."&uArr;")
13059 ("rArr") ("Rightarrow"."&rArr;")
13060 ("dArr") ("Downarrow"."&dArr;")
13061 ("hArr") ("Leftrightarrow"."&hArr;")
13062 ("forall")
13063 ("part") ("partial"."&part;")
13064 ("exist") ("exists"."&exist;")
13065 ("empty") ("emptyset"."&empty;")
13066 ("nabla")
13067 ("isin") ("in"."&isin;")
13068 ("notin")
13069 ("ni")
13070 ("prod")
13071 ("sum")
13072 ("minus")
13073 ("lowast") ("ast"."&lowast;")
13074 ("radic")
13075 ("prop") ("proptp"."&prop;")
13076 ("infin") ("infty"."&infin;")
13077 ("ang") ("angle"."&ang;")
13078 ("and") ("vee"."&and;")
13079 ("or") ("wedge"."&or;")
13080 ("cap")
13081 ("cup")
13082 ("int")
13083 ("there4")
13084 ("sim")
13085 ("cong") ("simeq"."&cong;")
13086 ("asymp")("approx"."&asymp;")
13087 ("ne") ("neq"."&ne;")
13088 ("equiv")
13089 ("le")
13090 ("ge")
13091 ("sub") ("subset"."&sub;")
13092 ("sup") ("supset"."&sup;")
13093 ("nsub")
13094 ("sube")
13095 ("supe")
13096 ("oplus")
13097 ("otimes")
13098 ("perp")
13099 ("sdot") ("cdot"."&sdot;")
13100 ("lceil")
13101 ("rceil")
13102 ("lfloor")
13103 ("rfloor")
13104 ("lang")
13105 ("rang")
13106 ("loz") ("Diamond"."&loz;")
13107 ("spades") ("spadesuit"."&spades;")
13108 ("clubs") ("clubsuit"."&clubs;")
13109 ("hearts") ("diamondsuit"."&hearts;")
13110 ("diams") ("diamondsuit"."&diams;")
13111 ("quot")
13112 ("amp")
13113 ("lt")
13114 ("gt")
13115 ("OElig")
13116 ("oelig")
13117 ("Scaron")
13118 ("scaron")
13119 ("Yuml")
13120 ("circ")
13121 ("tilde")
13122 ("ensp")
13123 ("emsp")
13124 ("thinsp")
13125 ("zwnj")
13126 ("zwj")
13127 ("lrm")
13128 ("rlm")
13129 ("ndash")
13130 ("mdash")
13131 ("lsquo")
13132 ("rsquo")
13133 ("sbquo")
13134 ("ldquo")
13135 ("rdquo")
13136 ("bdquo")
13137 ("dagger")
13138 ("Dagger")
13139 ("permil")
13140 ("lsaquo")
13141 ("rsaquo")
13142 ("euro")
13143
13144 ("arccos"."arccos")
13145 ("arcsin"."arcsin")
13146 ("arctan"."arctan")
13147 ("arg"."arg")
13148 ("cos"."cos")
13149 ("cosh"."cosh")
13150 ("cot"."cot")
13151 ("coth"."coth")
13152 ("csc"."csc")
13153 ("deg"."deg")
13154 ("det"."det")
13155 ("dim"."dim")
13156 ("exp"."exp")
13157 ("gcd"."gcd")
13158 ("hom"."hom")
13159 ("inf"."inf")
13160 ("ker"."ker")
13161 ("lg"."lg")
13162 ("lim"."lim")
13163 ("liminf"."liminf")
13164 ("limsup"."limsup")
13165 ("ln"."ln")
13166 ("log"."log")
13167 ("max"."max")
13168 ("min"."min")
13169 ("Pr"."Pr")
13170 ("sec"."sec")
13171 ("sin"."sin")
13172 ("sinh"."sinh")
13173 ("sup"."sup")
13174 ("tan"."tan")
13175 ("tanh"."tanh")
13176 )
13177 "Entities for TeX->HTML translation.
13178 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
13179 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
13180 In that case, \"\\ent\" will be translated to \"&other;\".
13181 The list contains HTML entities for Latin-1, Greek and other symbols.
13182 It is supplemented by a number of commonly used TeX macros with appropriate
13183 translations. There is currently no way for users to extend this.")
13184
13185 (defun org-cleaned-string-for-export (string &rest parameters)
13186 "Cleanup a buffer substring so that links can be created safely."
13187 (interactive)
13188 (let* ((re-radio (and org-target-link-regexp
13189 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
13190 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
13191 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
13192 (re-archive (concat ":" org-archive-tag ":"))
13193 rtn)
13194 (save-excursion
13195 (set-buffer (get-buffer-create " org-mode-tmp"))
13196 (erase-buffer)
13197 (insert string)
13198 (let ((org-inhibit-startup t)) (org-mode))
13199
13200 ;; Get rid of archived trees
13201 (when (not (eq org-export-with-archived-trees t))
13202 (goto-char (point-min))
13203 (while (re-search-forward re-archive nil t)
13204 (if (not (org-on-heading-p))
13205 (org-end-of-subtree t)
13206 (beginning-of-line 1)
13207 (delete-region
13208 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
13209 (org-end-of-subtree)))))
13210
13211 ;; Find targets in comments and move them out of comments,
13212 ;; but mark them as targets that should be invisible
13213 (goto-char (point-min))
13214 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
13215 (replace-match "\\1(INVISIBLE)"))
13216
13217 ;; Find matches for radio targets and turn them into internal links
13218 (goto-char (point-min))
13219 (when re-radio
13220 (while (re-search-forward re-radio nil t)
13221 (replace-match "\\1[[\\2]]")))
13222
13223 ;; Find all links that contain a newline and put them into a single line
13224 (goto-char (point-min))
13225 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
13226 (replace-match "\\1 \\3")
13227 (goto-char (match-beginning 0)))
13228
13229 ;; Convert LaTeX fragments to images
13230 (when (memq :LaTeX-fragments parameters)
13231 (org-format-latex
13232 (concat "ltxpng/" (file-name-sans-extension
13233 (file-name-nondirectory
13234 org-current-export-file)))
13235 org-current-export-dir nil "Creating LaTeX image %s"))
13236 (message "Exporting...")
13237
13238 ;; Normalize links: Convert angle and plain links into bracket links
13239 (goto-char (point-min))
13240 (while (re-search-forward re-plain-link nil t)
13241 (replace-match
13242 (concat
13243 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13244 t t))
13245 (goto-char (point-min))
13246 (while (re-search-forward re-angle-link nil t)
13247 (replace-match
13248 (concat
13249 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13250 t t))
13251
13252 ;; Find multiline emphasis and put them into single line
13253 (when (memq :emph-multiline parameters)
13254 (goto-char (point-min))
13255 (while (re-search-forward org-emph-re nil t)
13256 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
13257 (goto-char (1- (match-end 0)))))
13258
13259 ;; Remove comments
13260 (goto-char (point-min))
13261 (while (re-search-forward "^#.*\n?" nil t)
13262 (replace-match ""))
13263 (setq rtn (buffer-string)))
13264 (kill-buffer " org-mode-tmp")
13265 rtn))
13266
13267 (defun org-solidify-link-text (s &optional alist)
13268 "Take link text and make a safe target out of it."
13269 (save-match-data
13270 (let* ((rtn
13271 (mapconcat
13272 'identity
13273 (org-split-string s "[ \t\r\n]+") "--"))
13274 (a (assoc rtn alist)))
13275 (or (cdr a) rtn))))
13276
13277 (defun org-convert-to-odd-levels ()
13278 "Convert an org-mode file with all levels allowed to one with odd levels.
13279 This will leave level 1 alone, convert level 2 to level 3, level 3 to
13280 level 5 etc."
13281 (interactive)
13282 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
13283 (let ((org-odd-levels-only nil) n)
13284 (save-excursion
13285 (goto-char (point-min))
13286 (while (re-search-forward "^\\*\\*+" nil t)
13287 (setq n (1- (length (match-string 0))))
13288 (while (>= (setq n (1- n)) 0)
13289 (org-demote))
13290 (end-of-line 1))))))
13291
13292
13293 (defun org-convert-to-oddeven-levels ()
13294 "Convert an org-mode file with only odd levels to one with odd and even levels.
13295 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
13296 section with an even level, conversion would destroy the structure of the file. An error
13297 is signaled in this case."
13298 (interactive)
13299 (goto-char (point-min))
13300 ;; First check if there are no even levels
13301 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
13302 (org-show-hierarchy-above)
13303 (error "Not all levels are odd in this file. Conversion not possible."))
13304 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
13305 (let ((org-odd-levels-only nil) n)
13306 (save-excursion
13307 (goto-char (point-min))
13308 (while (re-search-forward "^\\*\\*+" nil t)
13309 (setq n (/ (length (match-string 0)) 2))
13310 (while (>= (setq n (1- n)) 0)
13311 (org-promote))
13312 (end-of-line 1))))))
13313
13314 (defun org-tr-level (n)
13315 "Make N odd if required."
13316 (if org-odd-levels-only (1+ (/ n 2)) n))
13317
13318 (defvar org-last-level nil) ; dynamically scoped variable
13319 (defvar org-ascii-current-indentation nil) ; For communication
13320
13321 (defun org-export-as-ascii (arg)
13322 "Export the outline as a pretty ASCII file.
13323 If there is an active region, export only the region.
13324 The prefix ARG specifies how many levels of the outline should become
13325 underlined headlines. The default is 3."
13326 (interactive "P")
13327 (setq-default org-todo-line-regexp org-todo-line-regexp)
13328 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13329 (org-infile-export-plist)))
13330 (region
13331 (buffer-substring
13332 (if (org-region-active-p) (region-beginning) (point-min))
13333 (if (org-region-active-p) (region-end) (point-max))))
13334 (lines (org-export-find-first-heading-line
13335 (org-skip-comments
13336 (org-split-string
13337 (org-cleaned-string-for-export region)
13338 "[\r\n]"))))
13339 (org-ascii-current-indentation '(0 . 0))
13340 (org-startup-with-deadline-check nil)
13341 (level 0) line txt
13342 (umax nil)
13343 (case-fold-search nil)
13344 (filename (concat (file-name-as-directory
13345 (org-export-directory :ascii opt-plist))
13346 (file-name-sans-extension
13347 (file-name-nondirectory buffer-file-name))
13348 ".txt"))
13349 (buffer (find-file-noselect filename))
13350 (levels-open (make-vector org-level-max nil))
13351 (odd org-odd-levels-only)
13352 (date (format-time-string "%Y/%m/%d" (current-time)))
13353 (time (format-time-string "%X" (org-current-time)))
13354 (author (plist-get opt-plist :author))
13355 (title (or (plist-get opt-plist :title)
13356 (file-name-sans-extension
13357 (file-name-nondirectory buffer-file-name))))
13358 (email (plist-get opt-plist :email))
13359 (language (plist-get opt-plist :language))
13360 (text nil)
13361 (todo nil)
13362 (lang-words nil))
13363
13364 (setq org-last-level 1)
13365 (org-init-section-numbers)
13366
13367 (find-file-noselect filename)
13368
13369 (setq lang-words (or (assoc language org-export-language-setup)
13370 (assoc "en" org-export-language-setup)))
13371 (if org-export-ascii-show-new-buffer
13372 (switch-to-buffer-other-window buffer)
13373 (set-buffer buffer))
13374 (erase-buffer)
13375 (fundamental-mode)
13376 ;; create local variables for all options, to make sure all called
13377 ;; functions get the correct information
13378 (mapcar (lambda (x)
13379 (set (make-local-variable (cdr x))
13380 (plist-get opt-plist (car x))))
13381 org-export-plist-vars)
13382 (set (make-local-variable 'org-odd-levels-only) odd)
13383 (setq umax (if arg (prefix-numeric-value arg)
13384 org-export-headline-levels))
13385
13386 ;; File header
13387 (if title (org-insert-centered title ?=))
13388 (insert "\n")
13389 (if (or author email)
13390 (insert (concat (nth 1 lang-words) ": " (or author "")
13391 (if email (concat " <" email ">") "")
13392 "\n")))
13393 (if (and date time)
13394 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
13395 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
13396
13397 (insert "\n\n")
13398
13399 (if org-export-with-toc
13400 (progn
13401 (insert (nth 3 lang-words) "\n"
13402 (make-string (length (nth 3 lang-words)) ?=) "\n")
13403 (mapcar '(lambda (line)
13404 (if (string-match org-todo-line-regexp
13405 line)
13406 ;; This is a headline
13407 (progn
13408 (setq level (- (match-end 1) (match-beginning 1))
13409 level (org-tr-level level)
13410 txt (match-string 3 line)
13411 todo
13412 (or (and org-export-mark-todo-in-toc
13413 (match-beginning 2)
13414 (not (equal (match-string 2 line)
13415 org-done-string)))
13416 ; TODO, not DONE
13417 (and org-export-mark-todo-in-toc
13418 (= level umax)
13419 (org-search-todo-below
13420 line lines level))))
13421 (setq txt (org-html-expand-for-ascii txt))
13422
13423 (if org-export-with-section-numbers
13424 (setq txt (concat (org-section-number level)
13425 " " txt)))
13426 (if (<= level umax)
13427 (progn
13428 (insert
13429 (make-string (* (1- level) 4) ?\ )
13430 (format (if todo "%s (*)\n" "%s\n") txt))
13431 (setq org-last-level level))
13432 ))))
13433 lines)))
13434
13435 (org-init-section-numbers)
13436 (while (setq line (pop lines))
13437 ;; Remove the quoted HTML tags.
13438 (setq line (org-html-expand-for-ascii line))
13439 ;; Remove targets
13440 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
13441 (setq line (replace-match "" t t line)))
13442 ;; Replace internal links
13443 (while (string-match org-bracket-link-regexp line)
13444 (setq line (replace-match
13445 (if (match-end 3) "[\\3]" "[\\1]")
13446 t nil line)))
13447 (cond
13448 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
13449 ;; a Headline
13450 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
13451 txt (match-string 2 line))
13452 (org-ascii-level-start level txt umax lines))
13453 (t
13454 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
13455 (normal-mode)
13456 (save-buffer)
13457 ;; remove display and invisible chars
13458 (let (beg end)
13459 (goto-char (point-min))
13460 (while (setq beg (next-single-property-change (point) 'display))
13461 (setq end (next-single-property-change beg 'display))
13462 (delete-region beg end)
13463 (goto-char beg)
13464 (insert "=>"))
13465 (goto-char (point-min))
13466 (while (setq beg (next-single-property-change (point) 'org-cwidth))
13467 (setq end (next-single-property-change beg 'org-cwidth))
13468 (delete-region beg end)
13469 (goto-char beg)))
13470 (goto-char (point-min))))
13471
13472 (defun org-search-todo-below (line lines level)
13473 "Search the subtree below LINE for any TODO entries."
13474 (let ((rest (cdr (memq line lines)))
13475 (re org-todo-line-regexp)
13476 line lv todo)
13477 (catch 'exit
13478 (while (setq line (pop rest))
13479 (if (string-match re line)
13480 (progn
13481 (setq lv (- (match-end 1) (match-beginning 1))
13482 todo (and (match-beginning 2)
13483 (not (equal (match-string 2 line)
13484 org-done-string))))
13485 ; TODO, not DONE
13486 (if (<= lv level) (throw 'exit nil))
13487 (if todo (throw 'exit t))))))))
13488
13489 (defun org-html-expand-for-ascii (line)
13490 "Handle quoted HTML for ASCII export."
13491 (if org-export-html-expand
13492 (while (string-match "@<[^<>\n]*>" line)
13493 ;; We just remove the tags for now.
13494 (setq line (replace-match "" nil nil line))))
13495 line)
13496
13497 (defun org-insert-centered (s &optional underline)
13498 "Insert the string S centered and underline it with character UNDERLINE."
13499 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
13500 (insert (make-string ind ?\ ) s "\n")
13501 (if underline
13502 (insert (make-string ind ?\ )
13503 (make-string (string-width s) underline)
13504 "\n"))))
13505
13506 (defun org-ascii-level-start (level title umax &optional lines)
13507 "Insert a new level in ASCII export."
13508 (let (char (n (- level umax 1)) (ind 0))
13509 (if (> level umax)
13510 (progn
13511 (insert (make-string (* 2 n) ?\ )
13512 (char-to-string (nth (% n (length org-export-ascii-bullets))
13513 org-export-ascii-bullets))
13514 " " title "\n")
13515 ;; find the indentation of the next non-empty line
13516 (catch 'stop
13517 (while lines
13518 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
13519 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
13520 (throw 'stop (setq ind (org-get-indentation (car lines)))))
13521 (pop lines)))
13522 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
13523 (if (or (not (equal (char-before) ?\n))
13524 (not (equal (char-before (1- (point))) ?\n)))
13525 (insert "\n"))
13526 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
13527 (if org-export-with-section-numbers
13528 (setq title (concat (org-section-number level) " " title)))
13529 (insert title "\n" (make-string (string-width title) char) "\n")
13530 (setq org-ascii-current-indentation '(0 . 0)))))
13531
13532 (defun org-export-visible (type arg)
13533 "Create a copy of the visible part of the current buffer, and export it.
13534 The copy is created in a temporary buffer and removed after use.
13535 TYPE is the final key (as a string) that also select the export command in
13536 the `C-c C-e' export dispatcher.
13537 As a special case, if the you type SPC at the prompt, the temporary
13538 org-mode file will not be removed but presented to you so that you can
13539 continue to use it. The prefix arg ARG is passed through to the exporting
13540 command."
13541 (interactive
13542 (list (progn
13543 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
13544 (read-char-exclusive))
13545 current-prefix-arg))
13546 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
13547 (error "Invalid export key"))
13548 (let* ((binding (cdr (assoc type
13549 '((?a . org-export-as-ascii)
13550 (?\C-a . org-export-as-ascii)
13551 (?b . org-export-as-html-and-open)
13552 (?\C-b . org-export-as-html-and-open)
13553 (?h . org-export-as-html)
13554 (?x . org-export-as-xoxo)))))
13555 (keepp (equal type ?\ ))
13556 (file buffer-file-name)
13557 (buffer (get-buffer-create "*Org Export Visible*"))
13558 s e)
13559 (with-current-buffer buffer (erase-buffer))
13560 (save-excursion
13561 (setq s (goto-char (point-min)))
13562 (while (not (= (point) (point-max)))
13563 (goto-char (org-find-invisible))
13564 (append-to-buffer buffer s (point))
13565 (setq s (goto-char (org-find-visible))))
13566 (goto-char (point-min))
13567 (unless keepp
13568 ;; Copy all comment lines to the end, to make sure #+ settings are
13569 ;; still available for the second export step. Kind of a hack, but
13570 ;; does do the trick.
13571 (if (looking-at "#[^\r\n]*")
13572 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
13573 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
13574 (append-to-buffer buffer (1+ (match-beginning 0))
13575 (min (point-max) (1+ (match-end 0))))))
13576 (set-buffer buffer)
13577 (let ((buffer-file-name file)
13578 (org-inhibit-startup t))
13579 (org-mode)
13580 (show-all)
13581 (unless keepp (funcall binding arg))))
13582 (if (not keepp)
13583 (kill-buffer buffer)
13584 (switch-to-buffer-other-window buffer)
13585 (goto-char (point-min)))))
13586
13587 (defun org-find-visible ()
13588 (if (featurep 'noutline)
13589 (let ((s (point)))
13590 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13591 (get-char-property s 'invisible)))
13592 s)
13593 (skip-chars-forward "^\n")
13594 (point)))
13595 (defun org-find-invisible ()
13596 (if (featurep 'noutline)
13597 (let ((s (point)))
13598 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13599 (not (get-char-property s 'invisible))))
13600 s)
13601 (skip-chars-forward "^\r")
13602 (point)))
13603
13604
13605 ;; HTML
13606
13607 (defun org-get-current-options ()
13608 "Return a string with current options as keyword options.
13609 Does include HTML export options as well as TODO and CATEGORY stuff."
13610 (format
13611 "#+TITLE: %s
13612 #+AUTHOR: %s
13613 #+EMAIL: %s
13614 #+LANGUAGE: %s
13615 #+TEXT: Some descriptive text to be emitted. Several lines OK.
13616 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
13617 #+CATEGORY: %s
13618 #+SEQ_TODO: %s
13619 #+TYP_TODO: %s
13620 #+STARTUP: %s %s %s %s %s %s
13621 #+TAGS: %s
13622 #+ARCHIVE: %s
13623 "
13624 (buffer-name) (user-full-name) user-mail-address org-export-default-language
13625 org-export-headline-levels
13626 org-export-with-section-numbers
13627 org-export-with-toc
13628 org-export-preserve-breaks
13629 org-export-html-expand
13630 org-export-with-fixed-width
13631 org-export-with-tables
13632 org-export-with-sub-superscripts
13633 org-export-with-emphasize
13634 org-export-with-TeX-macros
13635 org-export-with-LaTeX-fragments
13636 (file-name-nondirectory buffer-file-name)
13637 (if (equal org-todo-interpretation 'sequence)
13638 (mapconcat 'identity org-todo-keywords " ")
13639 "TODO FEEDBACK VERIFY DONE")
13640 (if (equal org-todo-interpretation 'type)
13641 (mapconcat 'identity org-todo-keywords " ")
13642 "Me Jason Marie DONE")
13643 (cdr (assoc org-startup-folded
13644 '((nil . "showall") (t . "overview") (content . "content"))))
13645 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
13646 (if org-odd-levels-only "odd" "oddeven")
13647 (if org-hide-leading-stars "hidestars" "showstars")
13648 (if org-startup-align-all-tables "align" "noalign")
13649 (if org-log-done "logging" "nologging")
13650 (if org-tag-alist (mapconcat 'car org-tag-alist " ") "")
13651 org-archive-location
13652 ))
13653
13654 (defun org-insert-export-options-template ()
13655 "Insert into the buffer a template with information for exporting."
13656 (interactive)
13657 (if (not (bolp)) (newline))
13658 (let ((s (org-get-current-options)))
13659 (and (string-match "#\\+CATEGORY" s)
13660 (setq s (substring s 0 (match-beginning 0))))
13661 (insert s)))
13662
13663 (defun org-toggle-fixed-width-section (arg)
13664 "Toggle the fixed-width export.
13665 If there is no active region, the QUOTE keyword at the current headline is
13666 inserted or removed. When present, it causes the text between this headline
13667 and the next to be exported as fixed-width text, and unmodified.
13668 If there is an active region, this command adds or removes a colon as the
13669 first character of this line. If the first character of a line is a colon,
13670 this line is also exported in fixed-width font."
13671 (interactive "P")
13672 (let* ((cc 0)
13673 (regionp (org-region-active-p))
13674 (beg (if regionp (region-beginning) (point)))
13675 (end (if regionp (region-end)))
13676 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13677 (re "[ \t]*\\(:\\)")
13678 off)
13679 (if regionp
13680 (save-excursion
13681 (goto-char beg)
13682 (setq cc (current-column))
13683 (beginning-of-line 1)
13684 (setq off (looking-at re))
13685 (while (> nlines 0)
13686 (setq nlines (1- nlines))
13687 (beginning-of-line 1)
13688 (cond
13689 (arg
13690 (move-to-column cc t)
13691 (insert ":\n")
13692 (forward-line -1))
13693 ((and off (looking-at re))
13694 (replace-match "" t t nil 1))
13695 ((not off) (move-to-column cc t) (insert ":")))
13696 (forward-line 1)))
13697 (save-excursion
13698 (org-back-to-heading)
13699 (if (looking-at (concat outline-regexp
13700 "\\( +\\<" org-quote-string "\\>\\)"))
13701 (replace-match "" t t nil 1)
13702 (if (looking-at outline-regexp)
13703 (progn
13704 (goto-char (match-end 0))
13705 (insert " " org-quote-string))))))))
13706
13707 (defun org-export-as-html-and-open (arg)
13708 "Export the outline as HTML and immediately open it with a browser.
13709 If there is an active region, export only the region.
13710 The prefix ARG specifies how many levels of the outline should become
13711 headlines. The default is 3. Lower levels will become bulleted lists."
13712 (interactive "P")
13713 (org-export-as-html arg 'hidden)
13714 (org-open-file buffer-file-name))
13715
13716 (defun org-export-as-html-batch ()
13717 "Call `org-export-as-html', may be used in batch processing as
13718 emacs --batch
13719 --load=$HOME/lib/emacs/org.el
13720 --eval \"(setq org-export-headline-levels 2)\"
13721 --visit=MyFile --funcall org-export-as-html-batch"
13722 (org-export-as-html org-export-headline-levels 'hidden))
13723
13724 (defun org-export-as-html (arg &optional hidden ext-plist)
13725 "Export the outline as a pretty HTML file.
13726 If there is an active region, export only the region.
13727 The prefix ARG specifies how many levels of the outline should become
13728 headlines. The default is 3. Lower levels will become bulleted lists.
13729 When HIDDEN is non-nil, don't display the HTML buffer.
13730 EXT-PLIST is a property list with external parameters overriding
13731 org-mode's default settings, but still inferior to file-local settings."
13732 (interactive "P")
13733 (message "Exporting...")
13734 (setq-default org-todo-line-regexp org-todo-line-regexp)
13735 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
13736 (setq-default org-done-string org-done-string)
13737 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13738 ext-plist
13739 (org-infile-export-plist)))
13740
13741 (style (plist-get opt-plist :style))
13742 (link-validate (plist-get opt-plist :link-validation-function))
13743 valid
13744 (odd org-odd-levels-only)
13745 (region-p (org-region-active-p))
13746 (region
13747 (buffer-substring
13748 (if region-p (region-beginning) (point-min))
13749 (if region-p (region-end) (point-max))))
13750 ;; The following two are dynamically scoped into other
13751 ;; routines below.
13752 (org-current-export-dir (org-export-directory :html opt-plist))
13753 (org-current-export-file buffer-file-name)
13754 (all_lines
13755 (org-skip-comments (org-split-string
13756 (org-cleaned-string-for-export
13757 region :emph-multiline
13758 (if (plist-get opt-plist :LaTeX-fragments)
13759 :LaTeX-fragments))
13760 "[\r\n]")))
13761 (lines (org-export-find-first-heading-line all_lines))
13762 (level 0) (line "") (origline "") txt todo
13763 (umax nil)
13764 (filename (concat (file-name-as-directory
13765 (org-export-directory :html opt-plist))
13766 (file-name-sans-extension
13767 (file-name-nondirectory buffer-file-name))
13768 ".html"))
13769 (current-dir (file-name-directory buffer-file-name))
13770 (buffer (find-file-noselect filename))
13771 (levels-open (make-vector org-level-max nil))
13772 (date (format-time-string "%Y/%m/%d" (current-time)))
13773 (time (format-time-string "%X" (org-current-time)))
13774 (author (plist-get opt-plist :author))
13775 (title (or (plist-get opt-plist :title)
13776 (file-name-sans-extension
13777 (file-name-nondirectory buffer-file-name))))
13778 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
13779 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
13780 (inquote nil)
13781 (infixed nil)
13782 (in-local-list nil)
13783 (local-list-num nil)
13784 (local-list-indent nil)
13785 (llt org-plain-list-ordered-item-terminator)
13786 (email (plist-get opt-plist :email))
13787 (language (plist-get opt-plist :language))
13788 (text (plist-get opt-plist :text))
13789 (lang-words nil)
13790 (target-alist nil) tg
13791 (head-count 0) cnt
13792 (start 0)
13793 (coding-system (and (fboundp 'coding-system-get)
13794 (boundp 'buffer-file-coding-system)
13795 buffer-file-coding-system))
13796 (coding-system-for-write (or coding-system coding-system-for-write))
13797 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
13798 (charset (and coding-system
13799 (coding-system-get coding-system 'mime-charset)))
13800 table-open type
13801 table-buffer table-orig-buffer
13802 ind start-is-num starter
13803 rpl path desc descp desc1 desc2 link
13804 )
13805 (message "Exporting...")
13806
13807 (setq org-last-level 1)
13808 (org-init-section-numbers)
13809
13810 ;; Get the language-dependent settings
13811 (setq lang-words (or (assoc language org-export-language-setup)
13812 (assoc "en" org-export-language-setup)))
13813
13814 ;; Switch to the output buffer
13815 (if (or hidden (not org-export-html-show-new-buffer))
13816 (set-buffer buffer)
13817 (switch-to-buffer-other-window buffer))
13818 (erase-buffer)
13819 (fundamental-mode)
13820 (let ((case-fold-search nil)
13821 (org-odd-levels-only odd))
13822 ;; create local variables for all options, to make sure all called
13823 ;; functions get the correct information
13824 (mapcar (lambda (x)
13825 (set (make-local-variable (cdr x))
13826 (plist-get opt-plist (car x))))
13827 org-export-plist-vars)
13828 (setq umax (if arg (prefix-numeric-value arg)
13829 org-export-headline-levels))
13830
13831 ;; File header
13832 (insert (format
13833 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
13834 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
13835 <html xmlns=\"http://www.w3.org/1999/xhtml\"
13836 lang=\"%s\" xml:lang=\"%s\">
13837 <head>
13838 <title>%s</title>
13839 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
13840 <meta name=\"generator\" content=\"Org-mode\"/>
13841 <meta name=\"generated\" content=\"%s %s\"/>
13842 <meta name=\"author\" content=\"%s\"/>
13843 %s
13844 </head><body>
13845 "
13846 language language (org-html-expand title) (or charset "iso-8859-1")
13847 date time author style))
13848
13849
13850 (insert (or (plist-get opt-plist :preamble) ""))
13851
13852 (when (plist-get opt-plist :auto-preamble)
13853 (if title (insert (concat "<h1 class=\"title\">"
13854 (org-html-expand title) "</h1>\n")))
13855
13856 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
13857
13858 (if org-export-with-toc
13859 (progn
13860 (insert (format "<h2>%s</h2>\n" (nth 3 lang-words)))
13861 (insert "<ul>\n<li>")
13862 (setq lines
13863 (mapcar '(lambda (line)
13864 (if (string-match org-todo-line-regexp line)
13865 ;; This is a headline
13866 (progn
13867 (setq level (- (match-end 1) (match-beginning 1))
13868 level (org-tr-level level)
13869 txt (save-match-data
13870 (org-html-expand
13871 (org-export-cleanup-toc-line
13872 (match-string 3 line))))
13873 todo
13874 (or (and org-export-mark-todo-in-toc
13875 (match-beginning 2)
13876 (not (equal (match-string 2 line)
13877 org-done-string)))
13878 ; TODO, not DONE
13879 (and org-export-mark-todo-in-toc
13880 (= level umax)
13881 (org-search-todo-below
13882 line lines level))))
13883 (if org-export-with-section-numbers
13884 (setq txt (concat (org-section-number level)
13885 " " txt)))
13886 (if (<= level umax)
13887 (progn
13888 (setq head-count (+ head-count 1))
13889 (if (> level org-last-level)
13890 (progn
13891 (setq cnt (- level org-last-level))
13892 (while (>= (setq cnt (1- cnt)) 0)
13893 (insert "\n<ul>\n<li>"))
13894 (insert "\n")))
13895 (if (< level org-last-level)
13896 (progn
13897 (setq cnt (- org-last-level level))
13898 (while (>= (setq cnt (1- cnt)) 0)
13899 (insert "</li>\n</ul>"))
13900 (insert "\n")))
13901 ;; Check for targets
13902 (while (string-match org-target-regexp line)
13903 (setq tg (match-string 1 line)
13904 line (replace-match
13905 (concat "@<span class=\"target\">" tg "@</span> ")
13906 t t line))
13907 (push (cons (org-solidify-link-text tg)
13908 (format "sec-%d" head-count))
13909 target-alist))
13910 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
13911 (setq txt (replace-match "" t t txt)))
13912 (insert
13913 (format
13914 (if todo
13915 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
13916 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
13917 head-count txt))
13918
13919 (setq org-last-level level))
13920 )))
13921 line)
13922 lines))
13923 (while (> org-last-level 0)
13924 (setq org-last-level (1- org-last-level))
13925 (insert "</li>\n</ul>\n"))
13926 ))
13927 (setq head-count 0)
13928 (org-init-section-numbers)
13929
13930 (while (setq line (pop lines) origline line)
13931 (catch 'nextline
13932
13933 ;; end of quote section?
13934 (when (and inquote (string-match "^\\*+" line))
13935 (insert "</pre>\n")
13936 (setq inquote nil))
13937 ;; inside a quote section?
13938 (when inquote
13939 (insert (org-html-protect line) "\n")
13940 (throw 'nextline nil))
13941
13942 ;; verbatim lines
13943 (when (and org-export-with-fixed-width
13944 (string-match "^[ \t]*:\\(.*\\)" line))
13945 (when (not infixed)
13946 (setq infixed t)
13947 (insert "<pre>\n"))
13948 (insert (org-html-protect (match-string 1 line)) "\n")
13949 (when (and lines
13950 (not (string-match "^[ \t]*\\(:.*\\)"
13951 (car lines))))
13952 (setq infixed nil)
13953 (insert "</pre>\n"))
13954 (throw 'nextline nil))
13955
13956
13957 ;; make targets to anchors
13958 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
13959 (cond
13960 ((match-end 2)
13961 (setq line (replace-match
13962 (concat "@<a name=\""
13963 (org-solidify-link-text (match-string 1 line))
13964 "\">\\nbsp@</a>")
13965 t t line)))
13966 ((and org-export-with-toc (equal (string-to-char line) ?*))
13967 (setq line (replace-match
13968 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
13969 ; (concat "@<i>" (match-string 1 line) "@</i> ")
13970 t t line)))
13971 (t
13972 (setq line (replace-match
13973 (concat "@<a name=\""
13974 (org-solidify-link-text (match-string 1 line))
13975 "\" class=\"target\">" (match-string 1 line) "@</a> ")
13976 t t line)))))
13977
13978 (setq line (org-html-handle-time-stamps line))
13979
13980 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
13981 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
13982 ;; Also handle sub_superscripts and checkboxes
13983 (setq line (org-html-expand line))
13984
13985 ;; Format the links
13986 (setq start 0)
13987 (while (string-match org-bracket-link-analytic-regexp line start)
13988 (setq start (match-beginning 0))
13989 (setq type (if (match-end 2) (match-string 2 line) "internal"))
13990 (setq path (match-string 3 line))
13991 (setq desc1 (if (match-end 5) (match-string 5 line))
13992 desc2 (if (match-end 2) (concat type ":" path) path)
13993 descp (and desc1 (not (equal desc1 desc2)))
13994 desc (or desc1 desc2))
13995 ;; FIXME: do we need to unescape here somewhere?
13996 (cond
13997 ((equal type "internal")
13998 (setq rpl
13999 (concat
14000 "<a href=\"#"
14001 (org-solidify-link-text path target-alist)
14002 "\">" desc "</a>")))
14003 ((member type '("http" "https" "ftp" "mailto" "news"))
14004 ;; standard URL
14005 (setq link (concat type ":" path))
14006 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
14007 ((string= type "file")
14008 ;; FILE link
14009 (let* ((filename path)
14010 (abs-p (file-name-absolute-p filename))
14011 thefile file-is-image-p search)
14012 (save-match-data
14013 (if (string-match "::\\(.*\\)" filename)
14014 (setq search (match-string 1 filename)
14015 filename (replace-match "" t nil filename)))
14016 (setq valid
14017 (if (functionp link-validate)
14018 (funcall link-validate filename current-dir)
14019 t))
14020 (setq file-is-image-p
14021 (string-match (org-image-file-name-regexp) filename))
14022 (setq thefile (if abs-p (expand-file-name filename) filename))
14023 (when (and org-export-html-link-org-files-as-html
14024 (string-match "\\.org$" thefile))
14025 (setq thefile (concat (substring thefile 0
14026 (match-beginning 0))
14027 ".html"))
14028 (if (and search
14029 ;; make sure this is can be used as target search
14030 (not (string-match "^[0-9]*$" search))
14031 (not (string-match "^\\*" search))
14032 (not (string-match "^/.*/$" search)))
14033 (setq thefile (concat thefile "#"
14034 (org-solidify-link-text
14035 (org-link-unescape search)))))
14036 (when (string-match "^file:" desc)
14037 (setq desc (replace-match "" t t desc))
14038 (if (string-match "\\.org$" desc)
14039 (setq desc (replace-match "" t t desc))))))
14040 (setq rpl (if (and file-is-image-p
14041 (or (eq t org-export-html-inline-images)
14042 (and org-export-html-inline-images
14043 (not descp))))
14044 (concat "<img src=\"" thefile "\"/>")
14045 (concat "<a href=\"" thefile "\">" desc "</a>")))
14046 (if (not valid) (setq rpl desc))))
14047 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
14048 (setq rpl (concat "<i>&lt;" type ":"
14049 (save-match-data (org-link-unescape path))
14050 "&gt;</i>"))))
14051 (setq line (replace-match rpl t t line)
14052 start (+ start (length rpl))))
14053 ;; TODO items
14054 (if (and (string-match org-todo-line-regexp line)
14055 (match-beginning 2))
14056 (if (equal (match-string 2 line) org-done-string)
14057 (setq line (replace-match
14058 "<span class=\"done\">\\2</span>"
14059 t nil line 2))
14060 (setq line (replace-match "<span class=\"todo\">\\2</span>"
14061 t nil line 2))))
14062
14063 (cond
14064 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14065 ;; This is a headline
14066 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14067 txt (match-string 2 line))
14068 (if (string-match quote-re0 txt)
14069 (setq txt (replace-match "" t t txt)))
14070 (if (<= level umax) (setq head-count (+ head-count 1)))
14071 (when in-local-list
14072 ;; Close any local lists before inserting a new header line
14073 (while local-list-num
14074 (org-close-li)
14075 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14076 (pop local-list-num))
14077 (setq local-list-indent nil
14078 in-local-list nil))
14079 (org-html-level-start level txt umax
14080 (and org-export-with-toc (<= level umax))
14081 head-count)
14082 ;; QUOTES
14083 (when (string-match quote-re line)
14084 (insert "<pre>")
14085 (setq inquote t)))
14086
14087 ((and org-export-with-tables
14088 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
14089 (if (not table-open)
14090 ;; New table starts
14091 (setq table-open t table-buffer nil table-orig-buffer nil))
14092 ;; Accumulate lines
14093 (setq table-buffer (cons line table-buffer)
14094 table-orig-buffer (cons origline table-orig-buffer))
14095 (when (or (not lines)
14096 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
14097 (car lines))))
14098 (setq table-open nil
14099 table-buffer (nreverse table-buffer)
14100 table-orig-buffer (nreverse table-orig-buffer))
14101 (org-close-par-maybe)
14102 (insert (org-format-table-html table-buffer table-orig-buffer))))
14103 (t
14104 ;; Normal lines
14105 (when (string-match
14106 (cond
14107 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14108 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14109 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14110 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
14111 line)
14112 (setq ind (org-get-string-indentation line)
14113 start-is-num (match-beginning 4)
14114 starter (if (match-beginning 2)
14115 (substring (match-string 2 line) 0 -1))
14116 line (substring line (match-beginning 5)))
14117 (unless (string-match "[^ \t]" line)
14118 ;; empty line. Pretend indentation is large.
14119 (setq ind (1+ (or (car local-list-indent) 1))))
14120 (while (and in-local-list
14121 (or (and (= ind (car local-list-indent))
14122 (not starter))
14123 (< ind (car local-list-indent))))
14124 (org-close-li)
14125 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14126 (pop local-list-num) (pop local-list-indent)
14127 (setq in-local-list local-list-indent))
14128 (cond
14129 ((and starter
14130 (or (not in-local-list)
14131 (> ind (car local-list-indent))))
14132 ;; Start new (level of ) list
14133 (org-close-par-maybe)
14134 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
14135 (push start-is-num local-list-num)
14136 (push ind local-list-indent)
14137 (setq in-local-list t))
14138 (starter
14139 ;; continue current list
14140 (org-close-li)
14141 (insert "<li>\n")))
14142 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
14143 (setq line
14144 (replace-match
14145 (if (equal (match-string 1 line) "X")
14146 "<b>[X]</b>"
14147 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
14148 t t line))))
14149
14150 ;; Empty lines start a new paragraph. If hand-formatted lists
14151 ;; are not fully interpreted, lines starting with "-", "+", "*"
14152 ;; also start a new paragraph.
14153 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
14154
14155 ;; Check if the line break needs to be conserved
14156 (cond
14157 ((string-match "\\\\\\\\[ \t]*$" line)
14158 (setq line (replace-match "<br/>" t t line)))
14159 (org-export-preserve-breaks
14160 (setq line (concat line "<br/>"))))
14161
14162 (insert line "\n")))))
14163
14164 ;; Properly close all local lists and other lists
14165 (when inquote (insert "</pre>\n"))
14166 (when in-local-list
14167 ;; Close any local lists before inserting a new header line
14168 (while local-list-num
14169 (org-close-li)
14170 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
14171 (pop local-list-num))
14172 (setq local-list-indent nil
14173 in-local-list nil))
14174 (org-html-level-start 1 nil umax
14175 (and org-export-with-toc (<= level umax))
14176 head-count)
14177
14178 (when (plist-get opt-plist :auto-postamble)
14179 (when author
14180 (insert "<p class=\"author\"> "
14181 (nth 1 lang-words) ": " author "\n")
14182 (when email
14183 (insert "<a href=\"mailto:" email "\">&lt;"
14184 email "&gt;</a>\n"))
14185 (insert "</p>\n"))
14186 (when (and date time)
14187 (insert "<p class=\"date\"> "
14188 (nth 2 lang-words) ": "
14189 date " " time "</p>\n")))
14190
14191 (if org-export-html-with-timestamp
14192 (insert org-export-html-html-helper-timestamp))
14193 (insert (or (plist-get opt-plist :postamble) ""))
14194 (insert "</body>\n</html>\n")
14195 (normal-mode)
14196 ;; remove empty paragraphs and lists
14197 (goto-char (point-min))
14198 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
14199 (replace-match ""))
14200 (goto-char (point-min))
14201 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
14202 (replace-match ""))
14203 (save-buffer)
14204 (goto-char (point-min))
14205 (message "Exporting... done"))))
14206
14207
14208 (defun org-format-table-html (lines olines)
14209 "Find out which HTML converter to use and return the HTML code."
14210 (if (string-match "^[ \t]*|" (car lines))
14211 ;; A normal org table
14212 (org-format-org-table-html lines)
14213 ;; Table made by table.el - test for spanning
14214 (let* ((hlines (delq nil (mapcar
14215 (lambda (x)
14216 (if (string-match "^[ \t]*\\+-" x) x
14217 nil))
14218 lines)))
14219 (first (car hlines))
14220 (ll (and (string-match "\\S-+" first)
14221 (match-string 0 first)))
14222 (re (concat "^[ \t]*" (regexp-quote ll)))
14223 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
14224 hlines))))
14225 (if (and (not spanning)
14226 (not org-export-prefer-native-exporter-for-tables))
14227 ;; We can use my own converter with HTML conversions
14228 (org-format-table-table-html lines)
14229 ;; Need to use the code generator in table.el, with the original text.
14230 (org-format-table-table-html-using-table-generate-source olines)))))
14231
14232 (defun org-format-org-table-html (lines)
14233 "Format a table into HTML."
14234 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14235 (setq lines (nreverse lines))
14236 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14237 (setq lines (nreverse lines))
14238 (when org-export-table-remove-special-lines
14239 ;; Check if the table has a marking column. If yes remove the
14240 ;; column and the special lines
14241 (let* ((special
14242 (not
14243 (memq nil
14244 (mapcar
14245 (lambda (x)
14246 (or (string-match "^[ \t]*|-" x)
14247 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
14248 lines)))))
14249 (if special
14250 (setq lines
14251 (delq nil
14252 (mapcar
14253 (lambda (x)
14254 (if (string-match "^[ \t]*| *[!_^] *|" x)
14255 nil ; ignore this line
14256 (and (or (string-match "^[ \t]*|-+\\+" x)
14257 (string-match "^[ \t]*|[^|]*|" x))
14258 (replace-match "|" t t x))))
14259 lines))))))
14260
14261 (let ((head (and org-export-highlight-first-table-line
14262 (delq nil (mapcar
14263 (lambda (x) (string-match "^[ \t]*|-" x))
14264 (cdr lines)))))
14265 line fields html)
14266 (setq html (concat org-export-html-table-tag "\n"))
14267 (while (setq line (pop lines))
14268 (catch 'next-line
14269 (if (string-match "^[ \t]*|-" line)
14270 (progn
14271 (setq head nil) ;; head ends here, first time around
14272 ;; ignore this line
14273 (throw 'next-line t)))
14274 ;; Break the line into fields
14275 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14276 (setq html (concat
14277 html
14278 "<tr>"
14279 (mapconcat (lambda (x)
14280 (if head
14281 (concat "<th>" x "</th>")
14282 (concat "<td>" x "</td>")))
14283 fields "")
14284 "</tr>\n"))))
14285 (setq html (concat html "</table>\n"))
14286 html))
14287
14288 (defun org-fake-empty-table-line (line)
14289 "Replace everything except \"|\" with spaces."
14290 (let ((i (length line))
14291 (newstr (copy-sequence line)))
14292 (while (> i 0)
14293 (setq i (1- i))
14294 (if (not (eq (aref newstr i) ?|))
14295 (aset newstr i ?\ )))
14296 newstr))
14297
14298 (defun org-format-table-table-html (lines)
14299 "Format a table generated by table.el into HTML.
14300 This conversion does *not* use `table-generate-source' from table.el.
14301 This has the advantage that Org-mode's HTML conversions can be used.
14302 But it has the disadvantage, that no cell- or row-spanning is allowed."
14303 (let (line field-buffer
14304 (head org-export-highlight-first-table-line)
14305 fields html empty)
14306 (setq html (concat org-export-html-table-tag "\n"))
14307 (while (setq line (pop lines))
14308 (setq empty "&nbsp;")
14309 (catch 'next-line
14310 (if (string-match "^[ \t]*\\+-" line)
14311 (progn
14312 (if field-buffer
14313 (progn
14314 (setq html (concat
14315 html
14316 "<tr>"
14317 (mapconcat
14318 (lambda (x)
14319 (if (equal x "") (setq x empty))
14320 (if head
14321 (concat "<th>" x "</th>\n")
14322 (concat "<td>" x "</td>\n")))
14323 field-buffer "\n")
14324 "</tr>\n"))
14325 (setq head nil)
14326 (setq field-buffer nil)))
14327 ;; Ignore this line
14328 (throw 'next-line t)))
14329 ;; Break the line into fields and store the fields
14330 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14331 (if field-buffer
14332 (setq field-buffer (mapcar
14333 (lambda (x)
14334 (concat x "<br/>" (pop fields)))
14335 field-buffer))
14336 (setq field-buffer fields))))
14337 (setq html (concat html "</table>\n"))
14338 html))
14339
14340 (defun org-format-table-table-html-using-table-generate-source (lines)
14341 "Format a table into html, using `table-generate-source' from table.el.
14342 This has the advantage that cell- or row-spanning is allowed.
14343 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
14344 (require 'table)
14345 (with-current-buffer (get-buffer-create " org-tmp1 ")
14346 (erase-buffer)
14347 (insert (mapconcat 'identity lines "\n"))
14348 (goto-char (point-min))
14349 (if (not (re-search-forward "|[^+]" nil t))
14350 (error "Error processing table"))
14351 (table-recognize-table)
14352 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
14353 (table-generate-source 'html " org-tmp2 ")
14354 (set-buffer " org-tmp2 ")
14355 (buffer-substring (point-min) (point-max))))
14356
14357 (defun org-html-handle-time-stamps (s)
14358 "Format time stamps in string S, or remove them."
14359 (catch 'exit
14360 (let (r b)
14361 (while (string-match org-maybe-keyword-time-regexp s)
14362 ;; FIXME: is it good to never export CLOCK, or do we need control?
14363 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
14364 (throw 'exit ""))
14365 (or b (setq b (substring s 0 (match-beginning 0))))
14366 (if (not org-export-with-timestamps)
14367 (setq r (concat r (substring s 0 (match-beginning 0)))
14368 s (substring s (match-end 0)))
14369 (setq r (concat
14370 r (substring s 0 (match-beginning 0))
14371 (if (match-end 1)
14372 (format "@<span class=\"timestamp-kwd\">%s @</span>"
14373 (match-string 1 s)))
14374 (format " @<span class=\"timestamp\">%s@</span>"
14375 (substring (match-string 3 s) 1 -1)))
14376 s (substring s (match-end 0)))))
14377 ;; Line break if line started and ended with time stamp stuff
14378 (if (not r)
14379 s
14380 (setq r (concat r s))
14381 (unless (string-match "\\S-" (concat b s))
14382 (setq r (concat r "@<br/>")))
14383 r))))
14384
14385 (defun org-html-protect (s)
14386 ;; convert & to &amp;, < to &lt; and > to &gt;
14387 (let ((start 0))
14388 (while (string-match "&" s start)
14389 (setq s (replace-match "&amp;" t t s)
14390 start (1+ (match-beginning 0))))
14391 (while (string-match "<" s)
14392 (setq s (replace-match "&lt;" t t s)))
14393 (while (string-match ">" s)
14394 (setq s (replace-match "&gt;" t t s))))
14395 s)
14396
14397 (defun org-export-cleanup-toc-line (s)
14398 "Remove tags and time staps from lines going into the toc."
14399 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
14400 (setq s (replace-match "" t t s)))
14401 (when org-export-remove-timestamps-from-toc
14402 (while (string-match org-maybe-keyword-time-regexp s)
14403 (setq s (replace-match "" t t s))))
14404 s)
14405
14406 (defun org-html-expand (string)
14407 "Prepare STRING for HTML export. Applies all active conversions.
14408 If there are links in the string, don't modify these."
14409 (let* (m s l res)
14410 (while (setq m (string-match org-bracket-link-regexp string))
14411 (setq s (substring string 0 m)
14412 l (match-string 0 string)
14413 string (substring string (match-end 0)))
14414 (push (org-html-do-expand s) res)
14415 (push l res))
14416 (push (org-html-do-expand string) res)
14417 (apply 'concat (nreverse res))))
14418
14419 (defun org-html-do-expand (s)
14420 "Apply all active conversions to translate special ASCII to HTML."
14421 (setq s (org-html-protect s))
14422 (if org-export-html-expand
14423 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
14424 (setq s (replace-match "<\\1>" t nil s))))
14425 (if org-export-with-emphasize
14426 (setq s (org-export-html-convert-emphasize s)))
14427 (if org-export-with-sub-superscripts
14428 (setq s (org-export-html-convert-sub-super s)))
14429 (if org-export-with-TeX-macros
14430 (let ((start 0) wd ass)
14431 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
14432 (setq wd (match-string 1 s))
14433 (if (setq ass (assoc wd org-html-entities))
14434 (setq s (replace-match (or (cdr ass)
14435 (concat "&" (car ass) ";"))
14436 t t s))
14437 (setq start (+ start (length wd)))))))
14438 s)
14439
14440 (defun org-create-multibrace-regexp (left right n)
14441 "Create a regular expression which will match a balanced sexp.
14442 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
14443 as single character strings.
14444 The regexp returned will match the entire expression including the
14445 delimiters. It will also define a single group which contains the
14446 match except for the outermost delimiters. The maximum depth of
14447 stacked delimiters is N. Escaping delimiters is not possible."
14448 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
14449 (or "\\|")
14450 (re nothing)
14451 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
14452 (while (> n 1)
14453 (setq n (1- n)
14454 re (concat re or next)
14455 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
14456 (concat left "\\(" re "\\)" right)))
14457
14458 (defvar org-match-substring-regexp
14459 (concat
14460 "\\([^\\]\\)\\([_^]\\)\\("
14461 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
14462 "\\|"
14463 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
14464 "\\|"
14465 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
14466 "The regular expression matching a sub- or superscript.")
14467
14468 (defun org-export-html-convert-sub-super (string)
14469 "Convert sub- and superscripts in STRING to HTML."
14470 (let (key c)
14471 (while (string-match org-match-substring-regexp string)
14472 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
14473 (setq c (or (match-string 8 string)
14474 (match-string 6 string)
14475 (match-string 5 string)))
14476 (setq string (replace-match
14477 (concat (match-string 1 string)
14478 "<" key ">" c "</" key ">")
14479 t t string)))
14480 (while (string-match "\\\\\\([_^]\\)" string)
14481 (setq string (replace-match (match-string 1 string) t t string))))
14482 string)
14483
14484 (defun org-export-html-convert-emphasize (string)
14485 "Apply emphasis."
14486 (while (string-match org-emph-re string)
14487 (setq string (replace-match (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist)) "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist)) "\\5") t nil string)))
14488 string)
14489
14490 (defvar org-par-open nil)
14491 (defun org-open-par ()
14492 "Insert <p>, but first close previous paragraph if any."
14493 (org-close-par-maybe)
14494 (insert "\n<p>")
14495 (setq org-par-open t))
14496 (defun org-close-par-maybe ()
14497 "Close paragraph if there is one open."
14498 (when org-par-open
14499 (insert "</p>")
14500 (setq org-par-open nil)))
14501 (defun org-close-li ()
14502 "Close <li> if necessary."
14503 (org-close-par-maybe)
14504 (insert "</li>\n"))
14505 ; (when (save-excursion
14506 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
14507 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
14508 ; (insert "</li>"))))
14509
14510 (defun org-html-level-start (level title umax with-toc head-count)
14511 "Insert a new level in HTML export.
14512 When TITLE is nil, just close all open levels."
14513 (org-close-par-maybe)
14514 (let ((l (1+ (max level umax))))
14515 (while (<= l org-level-max)
14516 (if (aref levels-open (1- l))
14517 (progn
14518 (org-html-level-close l)
14519 (aset levels-open (1- l) nil)))
14520 (setq l (1+ l)))
14521 (when title
14522 ;; If title is nil, this means this function is called to close
14523 ;; all levels, so the rest is done only if title is given
14524 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14525 (setq title (replace-match
14526 (if org-export-with-tags
14527 (save-match-data
14528 (concat
14529 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
14530 (mapconcat 'identity (org-split-string
14531 (match-string 1 title) ":")
14532 "&nbsp;")
14533 "</span>"))
14534 "")
14535 t t title)))
14536 (if (> level umax)
14537 (progn
14538 (if (aref levels-open (1- level))
14539 (progn
14540 (org-close-li)
14541 (insert "<li>" title "<br/>\n"))
14542 (aset levels-open (1- level) t)
14543 (org-close-par-maybe)
14544 (insert "<ul>\n<li>" title "<br/>\n")))
14545 (if org-export-with-section-numbers
14546 (setq title (concat (org-section-number level) " " title)))
14547 (setq level (+ level 1))
14548 (if with-toc
14549 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
14550 level head-count title level))
14551 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
14552 (org-open-par)))))
14553
14554 (defun org-html-level-close (&rest args)
14555 "Terminate one level in HTML export."
14556 (org-close-li)
14557 (insert "</ul>"))
14558
14559 ;; Variable holding the vector with section numbers
14560 (defvar org-section-numbers (make-vector org-level-max 0))
14561
14562 (defun org-init-section-numbers ()
14563 "Initialize the vector for the section numbers."
14564 (let* ((level -1)
14565 (numbers (nreverse (org-split-string "" "\\.")))
14566 (depth (1- (length org-section-numbers)))
14567 (i depth) number-string)
14568 (while (>= i 0)
14569 (if (> i level)
14570 (aset org-section-numbers i 0)
14571 (setq number-string (or (car numbers) "0"))
14572 (if (string-match "\\`[A-Z]\\'" number-string)
14573 (aset org-section-numbers i
14574 (- (string-to-char number-string) ?A -1))
14575 (aset org-section-numbers i (string-to-number number-string)))
14576 (pop numbers))
14577 (setq i (1- i)))))
14578
14579 (defun org-section-number (&optional level)
14580 "Return a string with the current section number.
14581 When LEVEL is non-nil, increase section numbers on that level."
14582 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
14583 (when level
14584 (when (> level -1)
14585 (aset org-section-numbers
14586 level (1+ (aref org-section-numbers level))))
14587 (setq idx (1+ level))
14588 (while (<= idx depth)
14589 (if (not (= idx 1))
14590 (aset org-section-numbers idx 0))
14591 (setq idx (1+ idx))))
14592 (setq idx 0)
14593 (while (<= idx depth)
14594 (setq n (aref org-section-numbers idx))
14595 (setq string (concat string (if (not (string= string "")) "." "")
14596 (int-to-string n)))
14597 (setq idx (1+ idx)))
14598 (save-match-data
14599 (if (string-match "\\`\\([@0]\\.\\)+" string)
14600 (setq string (replace-match "" t nil string)))
14601 (if (string-match "\\(\\.0\\)+\\'" string)
14602 (setq string (replace-match "" t nil string))))
14603 string))
14604
14605
14606 ;;;###autoload
14607 (defun org-export-icalendar-this-file ()
14608 "Export current file as an iCalendar file.
14609 The iCalendar file will be located in the same directory as the Org-mode
14610 file, but with extension `.ics'."
14611 (interactive)
14612 (org-export-icalendar nil buffer-file-name))
14613
14614 (defun org-export-as-xoxo-insert-into (buffer &rest output)
14615 (with-current-buffer buffer
14616 (apply 'insert output)))
14617
14618 (defun org-export-as-xoxo (&optional buffer)
14619 "Export the org buffer as XOXO.
14620 The XOXO buffer is named *xoxo-<source buffer name>*"
14621 (interactive (list (current-buffer)))
14622 ;; A quickie abstraction
14623
14624 ;; Output everything as XOXO
14625 (with-current-buffer (get-buffer buffer)
14626 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
14627 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14628 (org-infile-export-plist)))
14629 (filename (concat (file-name-as-directory
14630 (org-export-directory :xoxo opt-plist))
14631 (file-name-sans-extension
14632 (file-name-nondirectory buffer-file-name))
14633 ".html"))
14634 (out (find-file-noselect filename))
14635 (last-level 1)
14636 (hanging-li nil))
14637 ;; Check the output buffer is empty.
14638 (with-current-buffer out (erase-buffer))
14639 ;; Kick off the output
14640 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
14641 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
14642 (let* ((hd (match-string-no-properties 1))
14643 (level (length hd))
14644 (text (concat
14645 (match-string-no-properties 2)
14646 (save-excursion
14647 (goto-char (match-end 0))
14648 (let ((str ""))
14649 (catch 'loop
14650 (while 't
14651 (forward-line)
14652 (if (looking-at "^[ \t]\\(.*\\)")
14653 (setq str (concat str (match-string-no-properties 1)))
14654 (throw 'loop str)))))))))
14655
14656 ;; Handle level rendering
14657 (cond
14658 ((> level last-level)
14659 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
14660
14661 ((< level last-level)
14662 (dotimes (- (- last-level level) 1)
14663 (if hanging-li
14664 (org-export-as-xoxo-insert-into out "</li>\n"))
14665 (org-export-as-xoxo-insert-into out "</ol>\n"))
14666 (when hanging-li
14667 (org-export-as-xoxo-insert-into out "</li>\n")
14668 (setq hanging-li nil)))
14669
14670 ((equal level last-level)
14671 (if hanging-li
14672 (org-export-as-xoxo-insert-into out "</li>\n")))
14673 )
14674
14675 (setq last-level level)
14676
14677 ;; And output the new li
14678 (setq hanging-li 't)
14679 (if (equal ?+ (elt text 0))
14680 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
14681 (org-export-as-xoxo-insert-into out "<li>" text))))
14682
14683 ;; Finally finish off the ol
14684 (dotimes (- last-level 1)
14685 (if hanging-li
14686 (org-export-as-xoxo-insert-into out "</li>\n"))
14687 (org-export-as-xoxo-insert-into out "</ol>\n"))
14688
14689 ;; Finish the buffer off and clean it up.
14690 (switch-to-buffer-other-window out)
14691 (indent-region (point-min) (point-max) nil)
14692 (save-buffer)
14693 (goto-char (point-min))
14694 )))
14695
14696 ;;;###autoload
14697 (defun org-export-icalendar-all-agenda-files ()
14698 "Export all files in `org-agenda-files' to iCalendar .ics files.
14699 Each iCalendar file will be located in the same directory as the Org-mode
14700 file, but with extension `.ics'."
14701 (interactive)
14702 (apply 'org-export-icalendar nil (org-agenda-files t)))
14703
14704 ;;;###autoload
14705 (defun org-export-icalendar-combine-agenda-files ()
14706 "Export all files in `org-agenda-files' to a single combined iCalendar file.
14707 The file is stored under the name `org-combined-agenda-icalendar-file'."
14708 (interactive)
14709 (apply 'org-export-icalendar t (org-agenda-files t)))
14710
14711 (defun org-export-icalendar (combine &rest files)
14712 "Create iCalendar files for all elements of FILES.
14713 If COMBINE is non-nil, combine all calendar entries into a single large
14714 file and store it under the name `org-combined-agenda-icalendar-file'."
14715 (save-excursion
14716 (let* ((dir (org-export-directory
14717 :ical (list :publishing-directory
14718 org-export-publishing-directory)))
14719 file ical-file ical-buffer category started org-agenda-new-buffers)
14720
14721 (when combine
14722 (setq ical-file
14723 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
14724 org-combined-agenda-icalendar-file
14725 (expand-file-name org-combined-agenda-icalendar-file dir))
14726 ical-buffer (org-get-agenda-file-buffer ical-file))
14727 (set-buffer ical-buffer) (erase-buffer))
14728 (while (setq file (pop files))
14729 (catch 'nextfile
14730 (org-check-agenda-file file)
14731 (set-buffer (org-get-agenda-file-buffer file))
14732 (unless combine
14733 (setq ical-file (concat (file-name-as-directory dir)
14734 (file-name-sans-extension
14735 (file-name-nondirectory buffer-file-name))
14736 ".ics"))
14737 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
14738 (with-current-buffer ical-buffer (erase-buffer)))
14739 (setq category (or org-category
14740 (file-name-sans-extension
14741 (file-name-nondirectory buffer-file-name))))
14742 (if (symbolp category) (setq category (symbol-name category)))
14743 (let ((standard-output ical-buffer))
14744 (if combine
14745 (and (not started) (setq started t)
14746 (org-start-icalendar-file org-icalendar-combined-name))
14747 (org-start-icalendar-file category))
14748 (org-print-icalendar-entries combine category)
14749 (when (or (and combine (not files)) (not combine))
14750 (org-finish-icalendar-file)
14751 (set-buffer ical-buffer)
14752 (save-buffer)
14753 (run-hooks 'org-after-save-iCalendar-file-hook)))))
14754 (org-release-buffers org-agenda-new-buffers))))
14755
14756 (defvar org-after-save-iCalendar-file-hook nil
14757 "Hook run after an iCalendar file has been saved.
14758 The iCalendar buffer is still current when this hook is run.
14759 A good way to use this is to tell a desktop calenndar application to re-read
14760 the iCalendar file.")
14761
14762 (defun org-print-icalendar-entries (&optional combine category)
14763 "Print iCalendar entries for the current Org-mode file to `standard-output'.
14764 When COMBINE is non nil, add the category to each line."
14765 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
14766 (dts (org-ical-ts-to-string
14767 (format-time-string (cdr org-time-stamp-formats) (current-time))
14768 "DTSTART"))
14769 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
14770 (save-excursion
14771 (goto-char (point-min))
14772 (while (re-search-forward org-ts-regexp nil t)
14773 (setq pos (match-beginning 0)
14774 ts (match-string 0)
14775 inc t
14776 hd (org-get-heading))
14777 (if (looking-at re2)
14778 (progn
14779 (goto-char (match-end 0))
14780 (setq ts2 (match-string 1) inc nil))
14781 (setq ts2 ts
14782 tmp (buffer-substring (max (point-min)
14783 (- pos org-ds-keyword-length))
14784 pos)
14785 deadlinep (string-match org-deadline-regexp tmp)
14786 scheduledp (string-match org-scheduled-regexp tmp)
14787 ;; donep (org-entry-is-done-p)
14788 ))
14789 (if (or (string-match org-tr-regexp hd)
14790 (string-match org-ts-regexp hd))
14791 (setq hd (replace-match "" t t hd)))
14792 (if combine
14793 (setq hd (concat hd " (category " category ")")))
14794 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
14795 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
14796 (princ (format "BEGIN:VEVENT
14797 %s
14798 %s
14799 SUMMARY:%s
14800 END:VEVENT\n"
14801 (org-ical-ts-to-string ts "DTSTART")
14802 (org-ical-ts-to-string ts2 "DTEND" inc)
14803 hd)))
14804 (when org-icalendar-include-todo
14805 (goto-char (point-min))
14806 (while (re-search-forward org-todo-line-regexp nil t)
14807 (setq state (match-string 1))
14808 (unless (equal state org-done-string)
14809 (setq hd (match-string 3))
14810 (if (string-match org-priority-regexp hd)
14811 (setq pri (string-to-char (match-string 2 hd))
14812 hd (concat (substring hd 0 (match-beginning 1))
14813 (substring hd (- (match-end 1)))))
14814 (setq pri org-default-priority))
14815 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
14816 (- org-lowest-priority ?A))))))
14817
14818 (princ (format "BEGIN:VTODO
14819 %s
14820 SUMMARY:%s
14821 SEQUENCE:1
14822 PRIORITY:%d
14823 END:VTODO\n"
14824 dts hd pri))))))))
14825
14826 (defun org-start-icalendar-file (name)
14827 "Start an iCalendar file by inserting the header."
14828 (let ((user user-full-name)
14829 (name (or name "unknown"))
14830 (timezone (cadr (current-time-zone))))
14831 (princ
14832 (format "BEGIN:VCALENDAR
14833 VERSION:2.0
14834 X-WR-CALNAME:%s
14835 PRODID:-//%s//Emacs with Org-mode//EN
14836 X-WR-TIMEZONE:%s
14837 CALSCALE:GREGORIAN\n" name user timezone))))
14838
14839 (defun org-finish-icalendar-file ()
14840 "Finish an iCalendar file by inserting the END statement."
14841 (princ "END:VCALENDAR\n"))
14842
14843 (defun org-ical-ts-to-string (s keyword &optional inc)
14844 "Take a time string S and convert it to iCalendar format.
14845 KEYWORD is added in front, to make a complete line like DTSTART....
14846 When INC is non-nil, increase the hour by two (if time string contains
14847 a time), or the day by one (if it does not contain a time)."
14848 (let ((t1 (org-parse-time-string s 'nodefault))
14849 t2 fmt have-time time)
14850 (if (and (car t1) (nth 1 t1) (nth 2 t1))
14851 (setq t2 t1 have-time t)
14852 (setq t2 (org-parse-time-string s)))
14853 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
14854 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
14855 (when inc
14856 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
14857 (setq time (encode-time s mi h d m y)))
14858 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
14859 (concat keyword (format-time-string fmt time))))
14860
14861 ;;; LaTeX stuff
14862
14863 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14864 "Keymap for the minor `org-cdlatex-mode'.")
14865
14866 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14867 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14868 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14869 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14870 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14871
14872 (defvar org-cdlatex-texmathp-advice-is-done nil
14873 "Flag remembering if we have applied the advice to texmathp already.")
14874
14875 (define-minor-mode org-cdlatex-mode
14876 "Toggle the minor `org-cdlatex-mode'.
14877 This mode supports entering LaTeX environment and math in LaTeX fragments
14878 in Org-mode.
14879 \\{org-cdlatex-mode-map}"
14880 nil " OCDL" nil
14881 (when org-cdlatex-mode (require 'cdlatex))
14882 (unless org-cdlatex-texmathp-advice-is-done
14883 (setq org-cdlatex-texmathp-advice-is-done t)
14884 (defadvice texmathp (around org-math-always-on activate)
14885 "Always return t in org-mode buffers.
14886 This is because we want to insert math symbols without dollars even outside
14887 the LaTeX math segments. If Orgmode thinks that point is actually inside
14888 en embedded LaTeX fragement, let texmathp do its job.
14889 \\[org-cdlatex-mode-map]"
14890 (interactive)
14891 (let (p)
14892 (cond
14893 ((not (org-mode-p)) ad-do-it)
14894 ((eq this-command 'cdlatex-math-symbol)
14895 (setq ad-return-value t
14896 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14897 (t
14898 (let ((p (org-inside-LaTeX-fragment-p)))
14899 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14900 (setq ad-return-value t
14901 texmathp-why '("Org-mode embedded math" . 0))
14902 (if p ad-do-it)))))))))
14903
14904 (defun turn-on-org-cdlatex ()
14905 "Unconditionally turn on `org-cdlatex-mode'."
14906 (org-cdlatex-mode 1))
14907
14908 (defun org-inside-LaTeX-fragment-p ()
14909 "Test if point is inside a LaTeX fragment.
14910 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14911 sequence appearing also before point.
14912 Even though the matchers for math are configurable, this function assumes
14913 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14914 delimiters are skipped when they have been removed by customization.
14915 The return value is nil, or a cons cell with the delimiter and
14916 and the position of this delimiter.
14917
14918 This function does a reasonably good job, but can locally be fooled by
14919 for example currency specifications. For example it will assume being in
14920 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14921 fragments that are properly closed, but during editing, we have to live
14922 with the uncertainty caused by missing closing delimiters. This function
14923 looks only before point, not after."
14924 (catch 'exit
14925 (let ((pos (point))
14926 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14927 (lim (progn
14928 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14929 (point)))
14930 dd-on str (start 0) m re)
14931 (goto-char pos)
14932 (when dodollar
14933 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14934 re (nth 1 (assoc "$" org-latex-regexps)))
14935 (while (string-match re str start)
14936 (cond
14937 ((= (match-end 0) (length str))
14938 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
14939 ((= (match-end 0) (- (length str) 5))
14940 (throw 'exit nil))
14941 (t (setq start (match-end 0))))))
14942 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14943 (goto-char pos)
14944 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14945 (and (match-beginning 2) (throw 'exit nil))
14946 ;; count $$
14947 (while (re-search-backward "\\$\\$" lim t)
14948 (setq dd-on (not dd-on)))
14949 (goto-char pos)
14950 (if dd-on (cons "$$" m))))))
14951
14952
14953 (defun org-try-cdlatex-tab ()
14954 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14955 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14956 - inside a LaTeX fragment, or
14957 - after the first word in a line, where an abbreviation expansion could
14958 insert a LaTeX environment."
14959 ;; FIXME: This may still need refinement.
14960 (when org-cdlatex-mode
14961 (cond
14962 ((save-excursion
14963 (skip-chars-backward "a-zA-Z0-9*")
14964 (skip-chars-backward " \t")
14965 (bolp))
14966 (cdlatex-tab) t)
14967 ((org-inside-LaTeX-fragment-p)
14968 (cdlatex-tab) t)
14969 (t nil))))
14970
14971 (defun org-cdlatex-underscore-caret (&optional arg)
14972 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14973 Revert to the normal definition outside of these fragments."
14974 (interactive "P")
14975 (if (org-inside-LaTeX-fragment-p)
14976 (call-interactively 'cdlatex-sub-superscript)
14977 (let (org-cdlatex-mode)
14978 (call-interactively (key-binding (vector last-input-event))))))
14979
14980 (defun org-cdlatex-math-modify (&optional arg)
14981 "Execute `cdlatex-math-modify' in LaTeX fragments.
14982 Revert to the normal definition outside of these fragments."
14983 (interactive "P")
14984 (if (org-inside-LaTeX-fragment-p)
14985 (call-interactively 'cdlatex-math-modify)
14986 (let (org-cdlatex-mode)
14987 (call-interactively (key-binding (vector last-input-event))))))
14988
14989 (defvar org-latex-fragment-image-overlays nil
14990 "List of overlays carrying the images of latex fragments.")
14991 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14992
14993 (defun org-remove-latex-fragment-image-overlays ()
14994 "Remove all overlays with LaTeX fragment images in current buffer."
14995 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14996 (setq org-latex-fragment-image-overlays nil))
14997
14998 (defun org-preview-latex-fragment (&optional subtree)
14999 "Preview the LaTeX fragment at point, or all locally or globally.
15000 If the cursor is in a LaTeX fragment, create the image and overlay
15001 it over the source code. If there is no fragment at point, display
15002 all fragments in the current text, from one headline to the next. With
15003 prefix SUBTREE, display all fragments in the current subtree. With a
15004 double prefix `C-u C-u', or when the cursor is before the first headline,
15005 display all fragments in the buffer.
15006 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15007 (interactive "P")
15008 (org-remove-latex-fragment-image-overlays)
15009 (save-excursion
15010 (save-restriction
15011 (let (beg end at msg)
15012 (cond
15013 ((or (equal subtree '(16))
15014 (not (save-excursion
15015 (re-search-backward (concat "^" outline-regexp) nil t))))
15016 (setq beg (point-min) end (point-max)
15017 msg "Creating images for buffer...%s"))
15018 ((equal subtree '(4))
15019 (org-back-to-heading)
15020 (setq beg (point) end (org-end-of-subtree)
15021 msg "Creating images for subtree...%s"))
15022 (t
15023 (if (setq at (org-inside-LaTeX-fragment-p))
15024 (goto-char (max (point-min) (- (cdr at) 2)))
15025 (org-back-to-heading))
15026 (setq beg (point) end (progn (outline-next-heading) (point))
15027 msg (if at "Creating image...%s"
15028 "Creating images for entry...%s"))))
15029 (message msg "")
15030 (narrow-to-region beg end)
15031 (org-format-latex
15032 (concat "ltxpng/" (file-name-sans-extension
15033 (file-name-nondirectory
15034 buffer-file-name)))
15035 default-directory 'overlays msg at)
15036 (message msg "done. Use `C-c C-c' to remove images.")))))
15037
15038 (defvar org-latex-regexps
15039 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15040 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15041 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15042 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
15043 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15044 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
15045 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
15046 "Regular expressions for matching embedded LaTeX.")
15047
15048 (defun org-format-latex (prefix &optional dir overlays msg at)
15049 "Replace LaTeX fragments with links to an image, and produce images."
15050 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15051 (let* ((prefixnodir (file-name-nondirectory prefix))
15052 (absprefix (expand-file-name prefix dir))
15053 (todir (file-name-directory absprefix))
15054 (opt org-format-latex-options)
15055 (matchers (plist-get opt :matchers))
15056 (re-list org-latex-regexps)
15057 (cnt 0) txt link beg end re e oldfiles
15058 m n block linkfile movefile ov)
15059 ;; Make sure the directory exists
15060 (or (file-directory-p todir) (make-directory todir))
15061 ;; Check if there are old images files with this prefix, and remove them
15062 (setq oldfiles (directory-files
15063 todir 'full
15064 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
15065 (while oldfiles (delete-file (pop oldfiles)))
15066 ;; Check the different regular expressions
15067 (while (setq e (pop re-list))
15068 (setq m (car e) re (nth 1 e) n (nth 2 e)
15069 block (if (nth 3 e) "\n\n" ""))
15070 (when (member m matchers)
15071 (goto-char (point-min))
15072 (while (re-search-forward re nil t)
15073 (when (or (not at) (equal (cdr at) (match-beginning n)))
15074 (setq txt (match-string n)
15075 beg (match-beginning n) end (match-end n)
15076 cnt (1+ cnt)
15077 linkfile (format "%s_%04d.png" prefix cnt)
15078 movefile (format "%s_%04d.png" absprefix cnt)
15079 link (concat block "[[file:" linkfile "]]" block))
15080 (if msg (message msg cnt))
15081 (goto-char beg)
15082 (org-create-formula-image
15083 txt movefile opt)
15084 (if overlays
15085 (progn
15086 (setq ov (org-make-overlay beg end))
15087 (if (featurep 'xemacs)
15088 (progn
15089 (org-overlay-put ov 'invisible t)
15090 (org-overlay-put
15091 ov 'end-glyph
15092 (make-glyph (vector 'png :file movefile))))
15093 (org-overlay-put
15094 ov 'display
15095 (list 'image :type 'png :file movefile :ascent 'center)))
15096 (push ov org-latex-fragment-image-overlays)
15097 (goto-char end))
15098 (delete-region beg end)
15099 (insert link))))))))
15100
15101 ;; This function borrows from Ganesh Swami's latex2png.el
15102 (defun org-create-formula-image (string tofile options)
15103 (let* ((tmpdir (if (featurep 'xemacs)
15104 (temp-directory)
15105 temporary-file-directory))
15106 (texfilebase (make-temp-name
15107 (expand-file-name "orgtex" tmpdir)))
15108
15109 ;(texfilebase (make-temp-file "orgtex"))
15110 ; (dummy (delete-file texfilebase))
15111 (texfile (concat texfilebase ".tex"))
15112 (dvifile (concat texfilebase ".dvi"))
15113 (pngfile (concat texfilebase ".png"))
15114 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
15115 (fg (or (plist-get options :foreground) "Black"))
15116 (bg (or (plist-get options :background) "Transparent")))
15117 (with-temp-file texfile
15118 (insert "\\documentclass{article}
15119 \\usepackage{fullpage}
15120 \\usepackage{amssymb}
15121 \\usepackage[usenames]{color}
15122 \\usepackage{amsmath}
15123 \\usepackage{latexsym}
15124 \\usepackage[mathscr]{eucal}
15125 \\pagestyle{empty}
15126 \\begin{document}\n" string "\n\\end{document}\n"))
15127 (let ((dir default-directory))
15128 (condition-case nil
15129 (progn
15130 (cd tmpdir)
15131 (call-process "latex" nil nil nil texfile))
15132 (error nil))
15133 (cd dir))
15134 (if (not (file-exists-p dvifile))
15135 (progn (message "Failed to create dvi file from %s" texfile) nil)
15136 (call-process "dvipng" nil nil nil
15137 "-E" "-fg" fg "-bg" bg
15138 "-x" scale "-y" scale "-T" "tight"
15139 "-o" pngfile
15140 dvifile)
15141 (if (not (file-exists-p pngfile))
15142 (progn (message "Failed to create png file from %s" texfile) nil)
15143 ;; Use the requested file name and clean up
15144 (copy-file pngfile tofile 'replace)
15145 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15146 (delete-file (concat texfilebase e)))
15147 pngfile))))
15148
15149 ;;; Key bindings
15150
15151 ;; - Bindings in Org-mode map are currently
15152 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
15153 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
15154 ;; e (?) useful from outline-mode
15155 ;; i k @ expendable from outline-mode
15156 ;; 0123456789 % & ()_{} " ` free
15157
15158 ;; Make `C-c C-x' a prefix key
15159 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
15160
15161 ;; TAB key with modifiers
15162 (define-key org-mode-map "\C-i" 'org-cycle)
15163 (define-key org-mode-map [(tab)] 'org-cycle)
15164 (define-key org-mode-map [(meta tab)] 'org-complete)
15165 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
15166 ;; The following line is necessary under Suse GNU/Linux
15167 (unless (featurep 'xemacs)
15168 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
15169 (define-key org-mode-map [(shift tab)] 'org-shifttab)
15170
15171 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
15172 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
15173 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15174 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
15175 (define-key org-mode-map [(meta return)] 'org-meta-return)
15176 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
15177 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
15178
15179 ;; Cursor keys with modifiers
15180 (define-key org-mode-map [(meta left)] 'org-metaleft)
15181 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
15182 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
15183 (define-key org-mode-map [(meta right)] 'org-metaright)
15184 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
15185 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
15186 (define-key org-mode-map [(meta up)] 'org-metaup)
15187 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
15188 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
15189 (define-key org-mode-map [(meta down)] 'org-metadown)
15190 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
15191 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
15192
15193 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15194 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
15195 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
15196 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
15197 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
15198 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
15199 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
15200 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
15201 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
15202 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
15203 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
15204 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
15205 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
15206 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
15207 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
15208 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
15209
15210 ;; All the other keys
15211
15212 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15213 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
15214 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
15215 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
15216 (define-key org-mode-map "\C-c\C-j" 'org-goto)
15217 (define-key org-mode-map "\C-c\C-t" 'org-todo)
15218 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
15219 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
15220 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
15221 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15222 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
15223 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
15224 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
15225 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
15226 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
15227 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
15228 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
15229 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
15230 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
15231 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
15232 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15233 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15234 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15235 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15236 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
15237 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
15238 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15239 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
15240 (define-key org-mode-map "\C-c]" 'org-remove-file)
15241 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
15242 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
15243 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
15244 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15245 (define-key org-mode-map "\C-m" 'org-return)
15246 (define-key org-mode-map "\C-c?" 'org-table-current-column)
15247 (define-key org-mode-map "\C-c " 'org-table-blank-field)
15248 (define-key org-mode-map "\C-c+" 'org-table-sum)
15249 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
15250 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
15251 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
15252 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15253 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
15254 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15255 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
15256 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
15257 (define-key org-mode-map "\C-c\C-e" 'org-export)
15258 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15259
15260 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
15261 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15262 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15263 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15264
15265 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15266 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15267 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15268 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15269 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15270 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15271 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15272 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15273
15274 (when (featurep 'xemacs)
15275 (define-key org-mode-map 'button3 'popup-mode-menu))
15276
15277 (defsubst org-table-p () (org-at-table-p))
15278
15279 (defun org-self-insert-command (N)
15280 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15281 If the cursor is in a table looking at whitespace, the whitespace is
15282 overwritten, and the table is not marked as requiring realignment."
15283 (interactive "p")
15284 (if (and (org-table-p)
15285 (progn
15286 ;; check if we blank the field, and if that triggers align
15287 (and org-table-auto-blank-field
15288 (member last-command
15289 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
15290 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15291 ;; got extra space, this field does not determine column width
15292 (let (org-table-may-need-update) (org-table-blank-field))
15293 ;; no extra space, this field may determine column width
15294 (org-table-blank-field)))
15295 t)
15296 (eq N 1)
15297 (looking-at "[^|\n]* |"))
15298 (let (org-table-may-need-update)
15299 (goto-char (1- (match-end 0)))
15300 (delete-backward-char 1)
15301 (goto-char (match-beginning 0))
15302 (self-insert-command N))
15303 (setq org-table-may-need-update t)
15304 (self-insert-command N)))
15305
15306 (defun org-delete-backward-char (N)
15307 "Like `delete-backward-char', insert whitespace at field end in tables.
15308 When deleting backwards, in tables this function will insert whitespace in
15309 front of the next \"|\" separator, to keep the table aligned. The table will
15310 still be marked for re-alignment if the field did fill the entire column,
15311 because, in this case the deletion might narrow the column."
15312 (interactive "p")
15313 (if (and (org-table-p)
15314 (eq N 1)
15315 (string-match "|" (buffer-substring (point-at-bol) (point)))
15316 (looking-at ".*?|"))
15317 (let ((pos (point))
15318 (noalign (looking-at "[^|\n\r]* |"))
15319 (c org-table-may-need-update))
15320 (backward-delete-char N)
15321 (skip-chars-forward "^|")
15322 (insert " ")
15323 (goto-char (1- pos))
15324 ;; noalign: if there were two spaces at the end, this field
15325 ;; does not determine the width of the column.
15326 (if noalign (setq org-table-may-need-update c)))
15327 (backward-delete-char N)))
15328
15329 (defun org-delete-char (N)
15330 "Like `delete-char', but insert whitespace at field end in tables.
15331 When deleting characters, in tables this function will insert whitespace in
15332 front of the next \"|\" separator, to keep the table aligned. The table will
15333 still be marked for re-alignment if the field did fill the entire column,
15334 because, in this case the deletion might narrow the column."
15335 (interactive "p")
15336 (if (and (org-table-p)
15337 (not (bolp))
15338 (not (= (char-after) ?|))
15339 (eq N 1))
15340 (if (looking-at ".*?|")
15341 (let ((pos (point))
15342 (noalign (looking-at "[^|\n\r]* |"))
15343 (c org-table-may-need-update))
15344 (replace-match (concat
15345 (substring (match-string 0) 1 -1)
15346 " |"))
15347 (goto-char pos)
15348 ;; noalign: if there were two spaces at the end, this field
15349 ;; does not determine the width of the column.
15350 (if noalign (setq org-table-may-need-update c)))
15351 (delete-char N))
15352 (delete-char N)))
15353
15354 ;; How to do this: Measure non-white length of current string
15355 ;; If equal to column width, we should realign.
15356
15357 (defun org-remap (map &rest commands)
15358 "In MAP, remap the functions given in COMMANDS.
15359 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15360 (let (new old)
15361 (while commands
15362 (setq old (pop commands) new (pop commands))
15363 (if (fboundp 'command-remapping)
15364 (define-key map (vector 'remap old) new)
15365 (substitute-key-definition old new map global-map)))))
15366
15367 (when (eq org-enable-table-editor 'optimized)
15368 ;; If the user wants maximum table support, we need to hijack
15369 ;; some standard editing functions
15370 (org-remap org-mode-map
15371 'self-insert-command 'org-self-insert-command
15372 'delete-char 'org-delete-char
15373 'delete-backward-char 'org-delete-backward-char)
15374 (define-key org-mode-map "|" 'org-force-self-insert))
15375
15376 (defun org-shiftcursor-error ()
15377 "Throw an error because Shift-Cursor command was applied in wrong context."
15378 (error "This command is active in special context like tables, headlines or timestamps"))
15379
15380 (defun org-shifttab (&optional arg)
15381 "Global visibility cycling or move to previous table field.
15382 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15383 on context.
15384 See the individual commands for more information."
15385 (interactive "P")
15386 (cond
15387 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15388 (t (call-interactively 'org-global-cycle))))
15389
15390 (defun org-shiftmetaleft ()
15391 "Promote subtree or delete table column.
15392 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
15393 See the individual commands for more information."
15394 (interactive)
15395 (cond
15396 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15397 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15398 ((org-at-item-p) (call-interactively 'org-outdent-item))
15399 (t (org-shiftcursor-error))))
15400
15401 (defun org-shiftmetaright ()
15402 "Demote subtree or insert table column.
15403 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
15404 See the individual commands for more information."
15405 (interactive)
15406 (cond
15407 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15408 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15409 ((org-at-item-p) (call-interactively 'org-indent-item))
15410 (t (org-shiftcursor-error))))
15411
15412 (defun org-shiftmetaup (&optional arg)
15413 "Move subtree up or kill table row.
15414 Calls `org-move-subtree-up' or `org-table-kill-row' or
15415 `org-move-item-up' depending on context. See the individual commands
15416 for more information."
15417 (interactive "P")
15418 (cond
15419 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15420 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15421 ((org-at-item-p) (call-interactively 'org-move-item-up))
15422 (t (org-shiftcursor-error))))
15423 (defun org-shiftmetadown (&optional arg)
15424 "Move subtree down or insert table row.
15425 Calls `org-move-subtree-down' or `org-table-insert-row' or
15426 `org-move-item-down', depending on context. See the individual
15427 commands for more information."
15428 (interactive "P")
15429 (cond
15430 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15431 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15432 ((org-at-item-p) (call-interactively 'org-move-item-down))
15433 (t (org-shiftcursor-error))))
15434
15435 (defun org-metaleft (&optional arg)
15436 "Promote heading or move table column to left.
15437 Calls `org-do-promote' or `org-table-move-column', depending on context.
15438 With no specific context, calls the Emacs default `backward-word'.
15439 See the individual commands for more information."
15440 (interactive "P")
15441 (cond
15442 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15443 ((or (org-on-heading-p) (org-region-active-p))
15444 (call-interactively 'org-do-promote))
15445 (t (call-interactively 'backward-word))))
15446
15447 (defun org-metaright (&optional arg)
15448 "Demote subtree or move table column to right.
15449 Calls `org-do-demote' or `org-table-move-column', depending on context.
15450 With no specific context, calls the Emacs default `forward-word'.
15451 See the individual commands for more information."
15452 (interactive "P")
15453 (cond
15454 ((org-at-table-p) (call-interactively 'org-table-move-column))
15455 ((or (org-on-heading-p) (org-region-active-p))
15456 (call-interactively 'org-do-demote))
15457 (t (call-interactively 'forward-word))))
15458
15459 (defun org-metaup (&optional arg)
15460 "Move subtree up or move table row up.
15461 Calls `org-move-subtree-up' or `org-table-move-row' or
15462 `org-move-item-up', depending on context. See the individual commands
15463 for more information."
15464 (interactive "P")
15465 (cond
15466 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15467 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15468 ((org-at-item-p) (call-interactively 'org-move-item-up))
15469 (t (org-shiftcursor-error))))
15470
15471 (defun org-metadown (&optional arg)
15472 "Move subtree down or move table row down.
15473 Calls `org-move-subtree-down' or `org-table-move-row' or
15474 `org-move-item-down', depending on context. See the individual
15475 commands for more information."
15476 (interactive "P")
15477 (cond
15478 ((org-at-table-p) (call-interactively 'org-table-move-row))
15479 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15480 ((org-at-item-p) (call-interactively 'org-move-item-down))
15481 (t (org-shiftcursor-error))))
15482
15483 (defun org-shiftup (&optional arg)
15484 "Increase item in timestamp or increase priority of current headline.
15485 Calls `org-timestamp-up' or `org-priority-up', depending on context.
15486 See the individual commands for more information."
15487 (interactive "P")
15488 (cond
15489 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
15490 ((org-on-heading-p) (call-interactively 'org-priority-up))
15491 ((org-at-item-p) (call-interactively 'org-previous-item))
15492 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
15493
15494 (defun org-shiftdown (&optional arg)
15495 "Decrease item in timestamp or decrease priority of current headline.
15496 Calls `org-timestamp-down' or `org-priority-down', depending on context.
15497 See the individual commands for more information."
15498 (interactive "P")
15499 (cond
15500 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
15501 ((org-on-heading-p) (call-interactively 'org-priority-down))
15502 (t (call-interactively 'org-next-item))))
15503
15504 (defun org-shiftright ()
15505 "Next TODO keyword or timestamp one day later, depending on context."
15506 (interactive)
15507 (cond
15508 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15509 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
15510 (t (org-shiftcursor-error))))
15511
15512 (defun org-shiftleft ()
15513 "Previous TODO keyword or timestamp one day earlier, depending on context."
15514 (interactive)
15515 (cond
15516 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15517 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
15518 (t (org-shiftcursor-error))))
15519
15520 (defun org-copy-special ()
15521 "Copy region in table or copy current subtree.
15522 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15523 See the individual commands for more information."
15524 (interactive)
15525 (call-interactively
15526 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15527
15528 (defun org-cut-special ()
15529 "Cut region in table or cut current subtree.
15530 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15531 See the individual commands for more information."
15532 (interactive)
15533 (call-interactively
15534 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15535
15536 (defun org-paste-special (arg)
15537 "Paste rectangular region into table, or past subtree relative to level.
15538 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15539 See the individual commands for more information."
15540 (interactive "P")
15541 (if (org-at-table-p)
15542 (org-table-paste-rectangle)
15543 (org-paste-subtree arg)))
15544
15545 (defun org-ctrl-c-ctrl-c (&optional arg)
15546 "Set tags in headline, or update according to changed information at point.
15547
15548 This command does many different things, depending on context:
15549
15550 - If the cursor is in a headline, prompt for tags and insert them
15551 into the current line, aligned to `org-tags-column'. When called
15552 with prefix arg, realign all tags in the current buffer.
15553
15554 - If the cursor is in one of the special #+KEYWORD lines, this
15555 triggers scanning the buffer for these lines and updating the
15556 information.
15557
15558 - If the cursor is inside a table, realign the table. This command
15559 works even if the automatic table editor has been turned off.
15560
15561 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15562 the entire table.
15563
15564 - If the cursor is inside a table created by the table.el package,
15565 activate that table.
15566
15567 - If the current buffer is a remember buffer, close note and file it.
15568 with a prefix argument, file it without further interaction to the default
15569 location.
15570
15571 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15572 links in this buffer.
15573
15574 - If the cursor is on a numbered item in a plain list, renumber the
15575 ordered list."
15576 (interactive "P")
15577 (let ((org-enable-table-editor t))
15578 (cond
15579 ((or org-clock-overlays org-occur-highlights
15580 org-latex-fragment-image-overlays)
15581 (org-remove-clock-overlays)
15582 (org-remove-occur-highlights)
15583 (org-remove-latex-fragment-image-overlays)
15584 (message "Temporary highlights/overlays removed from current buffer"))
15585 ((and (local-variable-p 'org-finish-function (current-buffer))
15586 (fboundp org-finish-function))
15587 (funcall org-finish-function))
15588 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15589 ((org-on-heading-p) (call-interactively 'org-set-tags))
15590 ((org-at-table.el-p)
15591 (require 'table)
15592 (beginning-of-line 1)
15593 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15594 (call-interactively 'table-recognize-table))
15595 ((org-at-table-p)
15596 (org-table-maybe-eval-formula)
15597 (if arg
15598 (call-interactively 'org-table-recalculate)
15599 (org-table-maybe-recalculate-line))
15600 (call-interactively 'org-table-align))
15601 ((org-at-item-checkbox-p)
15602 (call-interactively 'org-toggle-checkbox))
15603 ((org-at-item-p)
15604 (call-interactively 'org-renumber-ordered-list))
15605 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
15606 (cond
15607 ((equal (match-string 1) "TBLFM")
15608 ;; Recalculate the table before this line
15609 (save-excursion
15610 (beginning-of-line 1)
15611 (skip-chars-backward " \r\n\t")
15612 (if (org-at-table-p)
15613 (org-call-with-arg 'org-table-recalculate t))))
15614 (t
15615 (call-interactively 'org-mode-restart))))
15616 (t (error "C-c C-c can do nothing useful at this location.")))))
15617
15618 (defun org-mode-restart ()
15619 "Restart Org-mode, to scan again for special lines.
15620 Also updates the keyword regular expressions."
15621 (interactive)
15622 (let ((org-inhibit-startup t)) (org-mode))
15623 (message "Org-mode restarted to refresh keyword and special line setup"))
15624
15625 (defun org-return ()
15626 "Goto next table row or insert a newline.
15627 Calls `org-table-next-row' or `newline', depending on context.
15628 See the individual commands for more information."
15629 (interactive)
15630 (cond
15631 ((org-at-table-p)
15632 (org-table-justify-field-maybe)
15633 (call-interactively 'org-table-next-row))
15634 (t (newline))))
15635
15636 (defun org-meta-return (&optional arg)
15637 "Insert a new heading or wrap a region in a table.
15638 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15639 See the individual commands for more information."
15640 (interactive "P")
15641 (cond
15642 ((org-at-table-p)
15643 (call-interactively 'org-table-wrap-region))
15644 (t (call-interactively 'org-insert-heading))))
15645
15646 ;;; Menu entries
15647
15648 ;; Define the Org-mode menus
15649 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15650 '("Tbl"
15651 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
15652 ["Next Field" org-cycle (org-at-table-p)]
15653 ["Previous Field" org-shifttab (org-at-table-p)]
15654 ["Next Row" org-return (org-at-table-p)]
15655 "--"
15656 ["Blank Field" org-table-blank-field (org-at-table-p)]
15657 ["Edit Field" org-table-edit-field (org-at-table-p)]
15658 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15659 "--"
15660 ("Column"
15661 ["Move Column Left" org-metaleft (org-at-table-p)]
15662 ["Move Column Right" org-metaright (org-at-table-p)]
15663 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15664 ["Insert Column" org-shiftmetaright (org-at-table-p)]
15665 "--"
15666 ["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])
15667 ("Row"
15668 ["Move Row Up" org-metaup (org-at-table-p)]
15669 ["Move Row Down" org-metadown (org-at-table-p)]
15670 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15671 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15672 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15673 "--"
15674 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
15675 ("Rectangle"
15676 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15677 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15678 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15679 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15680 "--"
15681 ("Calculate"
15682 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15683 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15684 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
15685 "--"
15686 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15687 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15688 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15689 "--"
15690 ["Sum Column/Rectangle" org-table-sum
15691 (or (org-at-table-p) (org-region-active-p))]
15692 ["Which Column?" org-table-current-column (org-at-table-p)])
15693 ["Debug Formulas"
15694 (setq org-table-formula-debug (not org-table-formula-debug))
15695 :style toggle :selected org-table-formula-debug]
15696 "--"
15697 ["Create" org-table-create (and (not (org-at-table-p))
15698 org-enable-table-editor)]
15699 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15700 ["Import from File" org-table-import (not (org-at-table-p))]
15701 ["Export to File" org-table-export (org-at-table-p)]
15702 "--"
15703 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15704
15705 (easy-menu-define org-org-menu org-mode-map "Org menu"
15706 '("Org"
15707 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
15708 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
15709 ["Sparse Tree" org-occur t]
15710 ["Show All" show-all t]
15711 "--"
15712 ["New Heading" org-insert-heading t]
15713 ("Navigate Headings"
15714 ["Up" outline-up-heading t]
15715 ["Next" outline-next-visible-heading t]
15716 ["Previous" outline-previous-visible-heading t]
15717 ["Next Same Level" outline-forward-same-level t]
15718 ["Previous Same Level" outline-backward-same-level t]
15719 "--"
15720 ["Jump" org-goto t])
15721 ("Edit Structure"
15722 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15723 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15724 "--"
15725 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15726 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15727 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15728 "--"
15729 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15730 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15731 ["Demote Heading" org-metaright (not (org-at-table-p))]
15732 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15733 "--"
15734 ["Convert to odd levels" org-convert-to-odd-levels t]
15735 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15736 ("Archive"
15737 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15738 ["Check and Tag Children" (org-toggle-archive-tag (4))
15739 :active t :keys "C-u C-c C-x C-a"]
15740 ["Sparse trees open ARCHIVE trees"
15741 (setq org-sparse-tree-open-archived-trees
15742 (not org-sparse-tree-open-archived-trees))
15743 :style toggle :selected org-sparse-tree-open-archived-trees]
15744 ["Cycling opens ARCHIVE trees"
15745 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15746 :style toggle :selected org-cycle-open-archived-trees]
15747 ["Agenda includes ARCHIVE trees"
15748 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
15749 :style toggle :selected (not org-agenda-skip-archived-trees)]
15750 "--"
15751 ["Move Subtree to Archive" org-archive-subtree t]
15752 ["Check and Move Children" (org-archive-subtree '(4))
15753 :active t :keys "C-u C-c $"])
15754 "--"
15755 ("TODO Lists"
15756 ["TODO/DONE/-" org-todo t]
15757 ["Show TODO Tree" org-show-todo-tree t]
15758 ["Global TODO list" org-todo-list t]
15759 "--"
15760 ["Set Priority" org-priority t]
15761 ["Priority Up" org-shiftup t]
15762 ["Priority Down" org-shiftdown t])
15763 ("Dates and Scheduling"
15764 ["Timestamp" org-time-stamp t]
15765 ["Timestamp (inactive)" org-time-stamp-inactive t]
15766 ("Change Date"
15767 ["1 Day Later" org-timestamp-up-day t]
15768 ["1 Day Earlier" org-timestamp-down-day t]
15769 ["1 ... Later" org-shiftup t]
15770 ["1 ... Earlier" org-shiftdown t])
15771 ["Compute Time Range" org-evaluate-time-range t]
15772 ["Schedule Item" org-schedule t]
15773 ["Deadline" org-deadline t]
15774 "--"
15775 ["Goto Calendar" org-goto-calendar t]
15776 ["Date from Calendar" org-date-from-calendar t])
15777 ("Logging work"
15778 ["Clock in" org-clock-in t]
15779 ["Clock out" org-clock-out t]
15780 ["Clock cancel" org-clock-cancel t]
15781 ["Display times" org-clock-display t]
15782 ["Create clock table" org-clock-report t]
15783 "--"
15784 ["Record DONE time"
15785 (progn (setq org-log-done (not org-log-done))
15786 (message "Switching to %s will %s record a timestamp"
15787 org-done-string
15788 (if org-log-done "automatically" "not")))
15789 :style toggle :selected org-log-done])
15790 "--"
15791 ["Agenda Command" org-agenda t]
15792 ("File List for Agenda")
15793 ("Special views current file"
15794 ["TODO Tree" org-show-todo-tree t]
15795 ["Check Deadlines" org-check-deadlines t]
15796 ["Timeline" org-timeline t]
15797 ["Tags Tree" org-tags-sparse-tree t])
15798 "--"
15799 ("Hyperlinks"
15800 ["Store Link (Global)" org-store-link t]
15801 ["Insert Link" org-insert-link t]
15802 ["Follow Link" org-open-at-point t]
15803 "--"
15804 ["Descriptive Links"
15805 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15806 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
15807 ["Literal Links"
15808 (progn
15809 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15810 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
15811 "--"
15812 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
15813 (save-excursion (goto-char (point-min))
15814 (re-search-forward "<[a-z]+:" nil t))])
15815 "--"
15816 ["Export/Publish" org-export t]
15817 ("LaTeX"
15818 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15819 :selected org-cdlatex-mode]
15820 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15821 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15822 ["Modify math symbol" org-cdlatex-math-modify
15823 (org-inside-LaTeX-fragment-p)]
15824 ["Export LaTeX fragments as images"
15825 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
15826 :style toggle :selected org-export-with-LaTeX-fragments])
15827 "--"
15828 ("Documentation"
15829 ["Show Version" org-version t]
15830 ["Info Documentation" org-info t])
15831 ("Customize"
15832 ["Browse Org Group" org-customize t]
15833 "--"
15834 ["Expand This Menu" org-create-customize-menu
15835 (fboundp 'customize-menu-create)])
15836 "--"
15837 ["Refresh setup" org-mode-restart t]
15838 ))
15839
15840 (defun org-info (&optional node)
15841 "Read documentation for Org-mode in the info system.
15842 With optional NODE, go directly to that node."
15843 (interactive)
15844 (require 'info)
15845 (Info-goto-node (format "(org)%s" (or node ""))))
15846
15847 (defun org-install-agenda-files-menu ()
15848 (let ((bl (buffer-list)))
15849 (save-excursion
15850 (while bl
15851 (set-buffer (pop bl))
15852 (if (org-mode-p) (setq bl nil)))
15853 (when (org-mode-p)
15854 (easy-menu-change
15855 '("Org") "File List for Agenda"
15856 (append
15857 (list
15858 ["Edit File List" (org-edit-agenda-file-list) t]
15859 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15860 ["Remove Current File from List" org-remove-file t]
15861 ["Cycle through agenda files" org-cycle-agenda-files t]
15862 "--")
15863 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15864
15865 ;;; Documentation
15866
15867 (defun org-customize ()
15868 "Call the customize function with org as argument."
15869 (interactive)
15870 (customize-browse 'org))
15871
15872 (defun org-create-customize-menu ()
15873 "Create a full customization menu for Org-mode, insert it into the menu."
15874 (interactive)
15875 (if (fboundp 'customize-menu-create)
15876 (progn
15877 (easy-menu-change
15878 '("Org") "Customize"
15879 `(["Browse Org group" org-customize t]
15880 "--"
15881 ,(customize-menu-create 'org)
15882 ["Set" Custom-set t]
15883 ["Save" Custom-save t]
15884 ["Reset to Current" Custom-reset-current t]
15885 ["Reset to Saved" Custom-reset-saved t]
15886 ["Reset to Standard Settings" Custom-reset-standard t]))
15887 (message "\"Org\"-menu now contains full customization menu"))
15888 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15889
15890 ;;; Miscellaneous stuff
15891
15892 (defun org-context ()
15893 "Return a list of contexts of the current cursor position.
15894 If several contexts apply, all are returned.
15895 Each context entry is a list with a symbol naming the context, and
15896 two positions indicating start and end of the context. Possible
15897 contexts are:
15898
15899 :headline anywhere in a headline
15900 :headline-stars on the leading stars in a headline
15901 :todo-keyword on a TODO keyword (including DONE) in a headline
15902 :tags on the TAGS in a headline
15903 :priority on the priority cookie in a headline
15904 :item on the first line of a plain list item
15905 :item-bullet on the bullet/number of a plain list item
15906 :checkbox on the checkbox in a plain list item
15907 :table in an org-mode table
15908 :table-special on a special filed in a table
15909 :table-table in a table.el table
15910 :link on a hyperline
15911 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15912 :target on a <<target>>
15913 :radio-target on a <<<radio-target>>>
15914 :latex-fragment on a LaTeX fragment
15915 :latex-preview on a LaTeX fragment with overlayed preview image
15916
15917 This function expects the position to be visible because it uses font-lock
15918 faces as a help to recognize the following contexts: :table-special, :link,
15919 and :keyword."
15920 (let* ((f (get-text-property (point) 'face))
15921 (faces (if (listp f) f (list f)))
15922 (p (point)) clist o)
15923 ;; First the large context
15924 (cond
15925 ((org-on-heading-p)
15926 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15927 (when (progn
15928 (beginning-of-line 1)
15929 (looking-at org-todo-line-tags-regexp))
15930 (push (org-point-in-group p 1 :headline-stars) clist)
15931 (push (org-point-in-group p 2 :todo-keyword) clist)
15932 (push (org-point-in-group p 4 :tags) clist))
15933 (goto-char p)
15934 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15935 (if (looking-at "\\[#[A-Z]\\]")
15936 (push (org-point-in-group p 0 :priority) clist)))
15937
15938 ((org-at-item-p)
15939 (push (org-point-in-group p 2 :item-bullet) clist)
15940 (push (list :item (point-at-bol)
15941 (save-excursion (org-end-of-item) (point)))
15942 clist)
15943 (and (org-at-item-checkbox-p)
15944 (push (org-point-in-group p 0 :checkbox) clist)))
15945
15946 ((org-at-table-p)
15947 (push (list :table (org-table-begin) (org-table-end)) clist)
15948 (if (memq 'org-formula faces)
15949 (push (list :table-special
15950 (previous-single-property-change p 'face)
15951 (next-single-property-change p 'face)) clist)))
15952 ((org-at-table-p 'any)
15953 (push (list :table-table) clist)))
15954 (goto-char p)
15955
15956 ;; Now the small context
15957 (cond
15958 ((org-at-timestamp-p)
15959 (push (org-point-in-group p 0 :timestamp) clist))
15960 ((memq 'org-link faces)
15961 (push (list :link
15962 (previous-single-property-change p 'face)
15963 (next-single-property-change p 'face)) clist))
15964 ((memq 'org-special-keyword faces)
15965 (push (list :keyword
15966 (previous-single-property-change p 'face)
15967 (next-single-property-change p 'face)) clist))
15968 ((org-on-target-p)
15969 (push (org-point-in-group p 0 :target) clist)
15970 (goto-char (1- (match-beginning 0)))
15971 (if (looking-at org-radio-target-regexp)
15972 (push (org-point-in-group p 0 :radio-target) clist))
15973 (goto-char p))
15974 ((setq o (car (delq nil
15975 (mapcar
15976 (lambda (x)
15977 (if (memq x org-latex-fragment-image-overlays) x))
15978 (org-overlays-at (point))))))
15979 (push (list :latex-fragment
15980 (org-overlay-start o) (org-overlay-end o)) clist)
15981 (push (list :latex-preview
15982 (org-overlay-start o) (org-overlay-end o)) clist))
15983 ((org-inside-LaTeX-fragment-p)
15984 ;; FIXME: positions wring.
15985 (push (list :latex-fragment (point) (point)) clist)))
15986
15987 (setq clist (nreverse (delq nil clist)))
15988 clist))
15989
15990 (defun org-point-in-group (point group &optional context)
15991 "Check if POINT is in match-group GROUP.
15992 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15993 match. If the match group does ot exist or point is not inside it,
15994 return nil."
15995 (and (match-beginning group)
15996 (>= point (match-beginning group))
15997 (<= point (match-end group))
15998 (if context
15999 (list context (match-beginning group) (match-end group))
16000 t)))
16001
16002 (defun org-move-line-down (arg)
16003 "Move the current line down. With prefix argument, move it past ARG lines."
16004 (interactive "p")
16005 (let ((col (current-column))
16006 beg end pos)
16007 (beginning-of-line 1) (setq beg (point))
16008 (beginning-of-line 2) (setq end (point))
16009 (beginning-of-line (+ 1 arg))
16010 (setq pos (move-marker (make-marker) (point)))
16011 (insert (delete-and-extract-region beg end))
16012 (goto-char pos)
16013 (move-to-column col)))
16014
16015 (defun org-move-line-up (arg)
16016 "Move the current line up. With prefix argument, move it past ARG lines."
16017 (interactive "p")
16018 (let ((col (current-column))
16019 beg end pos)
16020 (beginning-of-line 1) (setq beg (point))
16021 (beginning-of-line 2) (setq end (point))
16022 (beginning-of-line (- arg))
16023 (setq pos (move-marker (make-marker) (point)))
16024 (insert (delete-and-extract-region beg end))
16025 (goto-char pos)
16026 (move-to-column col)))
16027
16028 ;; Paragraph filling stuff.
16029 ;; We want this to be just right, so use the full arsenal.
16030
16031 (defun org-set-autofill-regexps ()
16032 (interactive)
16033 ;; In the paragraph separator we include headlines, because filling
16034 ;; text in a line directly attached to a headline would otherwise
16035 ;; fill the headline as well.
16036 (set (make-local-variable 'comment-start-skip) "^#+[ \t]*")
16037 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
16038 ;; The paragraph starter includes hand-formatted lists.
16039 (set (make-local-variable 'paragraph-start)
16040 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
16041 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16042 ;; But only if the user has not turned off tables or fixed-width regions
16043 (set (make-local-variable 'auto-fill-inhibit-regexp)
16044 (concat "\\*\\|#"
16045 "\\|[ \t]*" org-keyword-time-regexp
16046 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16047 (concat
16048 "\\|[ \t]*["
16049 (if org-enable-table-editor "|" "")
16050 (if org-enable-fixed-width-editor ":" "")
16051 "]"))))
16052 ;; We use our own fill-paragraph function, to make sure that tables
16053 ;; and fixed-width regions are not wrapped. That function will pass
16054 ;; through to `fill-paragraph' when appropriate.
16055 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
16056 ;; Adaptive filling: To get full control, first make sure that
16057 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16058 (set (make-local-variable 'adaptive-fill-regexp) "\000")
16059 (set (make-local-variable 'adaptive-fill-function)
16060 'org-adaptive-fill-function))
16061
16062 (defun org-fill-paragraph (&optional justify)
16063 "Re-align a table, pass through to fill-paragraph if no table."
16064 (let ((table-p (org-at-table-p))
16065 (table.el-p (org-at-table.el-p)))
16066 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
16067 (table.el-p t) ; skip table.el tables
16068 (table-p (org-table-align) t) ; align org-mode tables
16069 (t nil)))) ; call paragraph-fill
16070
16071 ;; For reference, this is the default value of adaptive-fill-regexp
16072 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16073
16074 (defun org-adaptive-fill-function ()
16075 "Return a fill prefix for org-mode files.
16076 In particular, this makes sure hanging paragraphs for hand-formatted lists
16077 work correctly."
16078 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
16079 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
16080
16081 ;; Functions needed for Emacs/XEmacs region compatibility
16082
16083 (defun org-add-hook (hook function &optional append local)
16084 "Add-hook, compatible with both Emacsen."
16085 (if (and local (featurep 'xemacs))
16086 (add-local-hook hook function append)
16087 (add-hook hook function append local)))
16088
16089 (defun org-region-active-p ()
16090 "Is `transient-mark-mode' on and the region active?
16091 Works on both Emacs and XEmacs."
16092 (if org-ignore-region
16093 nil
16094 (if (featurep 'xemacs)
16095 (and zmacs-regions (region-active-p))
16096 (and transient-mark-mode mark-active))))
16097
16098 (defun org-add-to-invisibility-spec (arg)
16099 "Add elements to `buffer-invisibility-spec'.
16100 See documentation for `buffer-invisibility-spec' for the kind of elements
16101 that can be added."
16102 (cond
16103 ((fboundp 'add-to-invisibility-spec)
16104 (add-to-invisibility-spec arg))
16105 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
16106 (setq buffer-invisibility-spec (list arg)))
16107 (t
16108 (setq buffer-invisibility-spec
16109 (cons arg buffer-invisibility-spec)))))
16110
16111 (defun org-remove-from-invisibility-spec (arg)
16112 "Remove elements from `buffer-invisibility-spec'."
16113 (if (fboundp 'remove-from-invisibility-spec)
16114 (remove-from-invisibility-spec arg)
16115 (if (consp buffer-invisibility-spec)
16116 (setq buffer-invisibility-spec
16117 (delete arg buffer-invisibility-spec)))))
16118
16119 (defun org-in-invisibility-spec-p (arg)
16120 "Is ARG a member of `buffer-invisibility-spec'?"
16121 (if (consp buffer-invisibility-spec)
16122 (member arg buffer-invisibility-spec)
16123 nil))
16124
16125 (defun org-image-file-name-regexp ()
16126 "Return regexp matching the file names of images."
16127 (if (fboundp 'image-file-name-regexp)
16128 (image-file-name-regexp)
16129 (let ((image-file-name-extensions
16130 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16131 "xbm" "xpm" "pbm" "pgm" "ppm")))
16132 (concat "\\."
16133 (regexp-opt (nconc (mapcar 'upcase
16134 image-file-name-extensions)
16135 image-file-name-extensions)
16136 t)
16137 "\\'"))))
16138
16139 ;; Functions needed for compatibility with old outline.el.
16140
16141 ;; Programming for the old outline.el (that uses selective display
16142 ;; instead of `invisible' text properties) is a nightmare, mostly
16143 ;; because regular expressions can no longer be anchored at
16144 ;; beginning/end of line. Therefore a number of function need special
16145 ;; treatment when the old outline.el is being used.
16146
16147 ;; The following functions capture almost the entire compatibility code
16148 ;; between the different versions of outline-mode. The only other
16149 ;; places where this is important are the font-lock-keywords, and in
16150 ;; `org-export-visible'. Search for `org-noutline-p' to find them.
16151
16152 ;; C-a should go to the beginning of a *visible* line, also in the
16153 ;; new outline.el. I guess this should be patched into Emacs?
16154 (defun org-beginning-of-line ()
16155 "Go to the beginning of the current line. If that is invisible, continue
16156 to a visible line beginning. This makes the function of C-a more intuitive."
16157 (interactive)
16158 (beginning-of-line 1)
16159 (if (bobp)
16160 nil
16161 (backward-char 1)
16162 (if (org-invisible-p)
16163 (while (and (not (bobp)) (org-invisible-p))
16164 (backward-char 1)
16165 (beginning-of-line 1))
16166 (forward-char 1))))
16167
16168 (when org-noutline-p
16169 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
16170
16171 (defun org-invisible-p ()
16172 "Check if point is at a character currently not visible."
16173 (if org-noutline-p
16174 ;; Early versions of noutline don't have `outline-invisible-p'.
16175 (if (fboundp 'outline-invisible-p)
16176 (outline-invisible-p)
16177 (get-char-property (point) 'invisible))
16178 (save-excursion
16179 (skip-chars-backward "^\r\n")
16180 (equal (char-before) ?\r))))
16181
16182 (defun org-invisible-p2 ()
16183 "Check if point is at a character currently not visible."
16184 (save-excursion
16185 (if org-noutline-p
16186 (progn
16187 (if (and (eolp) (not (bobp))) (backward-char 1))
16188 ;; Early versions of noutline don't have `outline-invisible-p'.
16189 (if (fboundp 'outline-invisible-p)
16190 (outline-invisible-p)
16191 (get-char-property (point) 'invisible)))
16192 (skip-chars-backward "^\r\n")
16193 (equal (char-before) ?\r))))
16194
16195 (defun org-back-to-heading (&optional invisible-ok)
16196 "Move to previous heading line, or beg of this line if it's a heading.
16197 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
16198 (if org-noutline-p
16199 (outline-back-to-heading invisible-ok)
16200 (if (and (or (bobp) (memq (char-before) '(?\n ?\r)))
16201 (looking-at outline-regexp))
16202 t
16203 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
16204 outline-regexp)
16205 nil t)
16206 (if invisible-ok
16207 (progn (goto-char (or (match-end 1) (match-beginning 0)))
16208 (looking-at outline-regexp)))
16209 (error "Before first heading")))))
16210
16211 (defun org-on-heading-p (&optional invisible-ok)
16212 "Return t if point is on a (visible) heading line.
16213 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
16214 (if org-noutline-p
16215 (outline-on-heading-p 'invisible-ok)
16216 (save-excursion
16217 (skip-chars-backward "^\n\r")
16218 (and (looking-at outline-regexp)
16219 (or invisible-ok
16220 (bobp)
16221 (equal (char-before) ?\n))))))
16222
16223 (defun org-on-target-p ()
16224 (let ((pos (point)))
16225 (save-excursion
16226 (skip-chars-forward "<")
16227 (and (re-search-backward "<<" nil t)
16228 (or (looking-at org-radio-target-regexp)
16229 (looking-at org-target-regexp))
16230 (<= (match-beginning 0) pos)
16231 (>= (1+ (match-end 0)) pos)))))
16232
16233 (defun org-up-heading-all (arg)
16234 "Move to the heading line of which the present line is a subheading.
16235 This function considers both visible and invisible heading lines.
16236 With argument, move up ARG levels."
16237 (if org-noutline-p
16238 (if (fboundp 'outline-up-heading-all)
16239 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16240 (outline-up-heading arg t)) ; emacs 22 version of outline.el
16241 (org-back-to-heading t)
16242 (looking-at outline-regexp)
16243 (if (<= (- (match-end 0) (match-beginning 0)) arg)
16244 (error "Cannot move up %d levels" arg)
16245 (re-search-backward
16246 (concat "[\n\r]" (regexp-quote
16247 (make-string (- (match-end 0) (match-beginning 0) arg)
16248 ?*))
16249 "[^*]"))
16250 (forward-char 1))))
16251
16252 (defun org-show-hidden-entry ()
16253 "Show an entry where even the heading is hidden."
16254 (save-excursion
16255 (if (not org-noutline-p)
16256 (progn
16257 (org-back-to-heading t)
16258 (org-flag-heading nil)))
16259 (org-show-entry)))
16260
16261 (defun org-check-occur-regexp (regexp)
16262 "If REGEXP starts with \"^\", modify it to check for \\r as well.
16263 Of course, only for the old outline mode."
16264 (if org-noutline-p
16265 regexp
16266 (if (string-match "^\\^" regexp)
16267 (concat "[\n\r]" (substring regexp 1))
16268 regexp)))
16269
16270 (defun org-flag-heading (flag &optional entry)
16271 "Flag the current heading. FLAG non-nil means make invisible.
16272 When ENTRY is non-nil, show the entire entry."
16273 (save-excursion
16274 (org-back-to-heading t)
16275 (if (not org-noutline-p)
16276 ;; Make the current headline visible
16277 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
16278 ;; Check if we should show the entire entry
16279 (if entry
16280 (progn
16281 (org-show-entry)
16282 (save-excursion
16283 (and (outline-next-heading)
16284 (org-flag-heading nil))))
16285 (outline-flag-region (max 1 (1- (point)))
16286 (save-excursion (outline-end-of-heading) (point))
16287 (if org-noutline-p
16288 flag
16289 (if flag ?\r ?\n))))))
16290
16291 (defun org-end-of-subtree (&optional invisible-OK)
16292 ;; This is an exact copy of the original function, but it uses
16293 ;; `org-back-to-heading', to make it work also in invisible
16294 ;; trees. And is uses an invisible-OK argument.
16295 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16296 (org-back-to-heading invisible-OK)
16297 (let ((first t)
16298 (level (funcall outline-level)))
16299 (while (and (not (eobp))
16300 (or first (> (funcall outline-level) level)))
16301 (setq first nil)
16302 (outline-next-heading))
16303 (if (memq (preceding-char) '(?\n ?\^M))
16304 (progn
16305 ;; Go to end of line before heading
16306 (forward-char -1)
16307 (if (memq (preceding-char) '(?\n ?\^M))
16308 ;; leave blank line before heading
16309 (forward-char -1)))))
16310 (point))
16311
16312 (defun org-show-subtree ()
16313 "Show everything after this heading at deeper levels."
16314 (outline-flag-region
16315 (point)
16316 (save-excursion
16317 (outline-end-of-subtree) (outline-next-heading) (point))
16318 (if org-noutline-p nil ?\n)))
16319
16320 (defun org-show-entry ()
16321 "Show the body directly following this heading.
16322 Show the heading too, if it is currently invisible."
16323 (interactive)
16324 (save-excursion
16325 (org-back-to-heading t)
16326 (outline-flag-region
16327 (max 1 (1- (point)))
16328 (save-excursion
16329 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
16330 (or (match-beginning 1) (point-max)))
16331 (if org-noutline-p nil ?\n))))
16332
16333 (defun org-make-options-regexp (kwds)
16334 "Make a regular expression for keyword lines."
16335 (concat
16336 (if org-noutline-p "^" "[\n\r]")
16337 "#?[ \t]*\\+\\("
16338 (mapconcat 'regexp-quote kwds "\\|")
16339 "\\):[ \t]*"
16340 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
16341
16342 ;; Make `bookmark-jump' show the jump location if it was hidden.
16343 (eval-after-load "bookmark"
16344 '(if (boundp 'bookmark-after-jump-hook)
16345 ;; We can use the hook
16346 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16347 ;; Hook not available, use advice
16348 (defadvice bookmark-jump (after org-make-visible activate)
16349 "Make the position visible."
16350 (org-bookmark-jump-unhide))))
16351
16352 (defun org-bookmark-jump-unhide ()
16353 "Unhide the current position, to show the bookmark location."
16354 (and (org-mode-p)
16355 (or (org-invisible-p)
16356 (save-excursion (goto-char (max (point-min) (1- (point))))
16357 (org-invisible-p)))
16358 (org-show-hierarchy-above)))
16359
16360 ;;; Experimental code
16361
16362
16363 ;;; Finish up
16364
16365 (provide 'org)
16366
16367 (run-hooks 'org-load-hook)
16368
16369 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16370 ;;; org.el ends here