]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-prepare-agenda-buffers): Use `invisible-OK' argument
[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.41
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.41
94 ;; - Shift-curser keys can modify inactive time stamps (inactive time
95 ;; stamps are the ones in [...] brackets.
96 ;; - Toggle all checkboxes in a region/below a headline.
97 ;; - Bug fixes.
98 ;;
99 ;; Version 4.40
100 ;; - Bug fixes.
101 ;;
102 ;; Version 4.39
103 ;; - Special tag ARCHIVE keeps a subtree closed and away from agenda lists.
104 ;; - LaTeX code in Org-mode files can be converted to images for HTML.
105 ;; - Bug fixes.
106 ;; - CDLaTeX-mode features can be used in Org-mode to help inserting
107 ;; LaTeX environment and math.
108 ;;
109 ;; Version 4.38
110 ;; - noutline.el is now required (important for XEmacs users only).
111 ;; - Dynamic blocks.
112 ;; - Archiving of all level 1 trees without open TODO items.
113 ;; - Clock reports can be inserted into the file in a special section.
114 ;; - FAQ removed from the manual, now only on the web.
115 ;; - Bug fixes.
116 ;;
117 ;; Version 4.37
118 ;; - Clock-feature for measuring time spent on specific items.
119 ;; - Improved emphasizing allows configuration and stacking.
120 ;;
121 ;; Version 4.36
122 ;; - Improved indentation of ASCII export, when headlines become items.
123 ;; - Handling of 12am and 12pm fixed. Times beyond 24:00 can be used
124 ;; and will not lead to conflicts.
125 ;; - Support for mutually exclusive TAGS with the fast tags interface.
126 ;; - Bug fixes.
127 ;;
128 ;; Version 4.35
129 ;; - HTML export is now valid XHTML.
130 ;; - Timeline can also show dates without entries. See new option
131 ;; `org-timeline-show-empty-dates'.
132 ;; - The bullets created by the ASCII exporter can now be configured.
133 ;; See the new option `org-export-ascii-bullets'.
134 ;; - New face `org-upcoming-deadline' (was `org-scheduled-previously').
135 ;; - New function `org-context' to allow testing for local context.
136 ;;
137 ;; Version 4.34
138 ;; - Bug fixes.
139 ;;
140 ;; Version 4.33
141 ;; - New commands to move through plain lists: S-up and S-down.
142 ;; - Bug fixes and documentation update.
143 ;;
144 ;; Version 4.32
145 ;; - Fast (single-key-per-tag) interface for setting TAGS.
146 ;; - The list of legal tags can be configured globally and locally.
147 ;; - Elisp and Info links (thanks to Todd Neal).
148 ;; - `org-export-publishing-directory' can be an alist, with different
149 ;; directories for different export types.
150 ;; - All context-sensitive commands use `call-interactively' to dispatch.
151 ;; - `org-confirm-shell-links' renamed to `org-confirm-shell-link-function'.
152 ;; - Bug fixes.
153 ;;
154 ;; Version 4.31
155 ;; - Bug fixes.
156 ;;
157 ;; Version 4.30
158 ;; - Modified installation: Autoloads have been collected in org-install.el.
159 ;; - Logging (org-log-done) is now a #+STARTUP option.
160 ;; - Checkboxes in plain list items, following up on Frank Ruell's idea.
161 ;; - File links inserted with C-c C-l will use relative paths if the linked
162 ;; file is in the current directory or a subdirectory of it.
163 ;; - New variable `org-link-file-path-type' to specify preference for
164 ;; relative and absolute paths.
165 ;; - New CSS classes for tags, timestamps, timestamp keywords.
166 ;; - Bug and typo fixes.
167 ;;
168 ;; Version 4.29
169 ;; - Inlining images in HTML export now depends on wheather the link
170 ;; contains a description or not.
171 ;; - TODO items can be scheduled from the global TODO list using C-c C-s.
172 ;; - TODO items already scheduled can be made to disappear from the global
173 ;; todo list, see `org-agenda-todo-ignore-scheduled'.
174 ;; - In Tables, formulas may also be Lisp forms.
175 ;; - Exporting the visible part of an outline with `C-c C-x v' works now
176 ;; for all available exporters.
177 ;; - Bug fixes, lots of them :-(
178 ;;
179 ;; Version 4.28
180 ;; - Bug fixes.
181 ;;
182 ;; Version 4.27
183 ;; - HTML exporter generalized to receive external options.
184 ;; As part of the process, author, email and date have been moved to the
185 ;; end of the HTML file.
186 ;; - Support for customizable file search in file links.
187 ;; - BibTeX database links as first application of the above.
188 ;; - New option `org-agenda-todo-list-sublevels' to turn off listing TODO
189 ;; entries that are sublevels of another TODO entry.
190 ;;
191 ;;
192 ;;; Code:
193
194 (eval-when-compile
195 (require 'cl)
196 (require 'calendar))
197 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
198 ;; the file noutline.el being loaded.
199 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
200 ;; We require noutline, which might be provided in outline.el
201 (require 'outline) (require 'noutline)
202 ;; Other stuff we need.
203 (require 'time-date)
204 (require 'easymenu)
205
206 ;;; Customization variables
207
208 (defvar org-version "4.41"
209 "The version number of the file org.el.")
210 (defun org-version ()
211 (interactive)
212 (message "Org-mode version %s" org-version))
213
214 ;; The following constant is for compatibility with different versions
215 ;; of outline.el.
216 (defconst org-noutline-p (featurep 'noutline)
217 "Are we using the new outline mode?")
218 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
219 (defconst org-format-transports-properties-p
220 (let ((x "a"))
221 (add-text-properties 0 1 '(test t) x)
222 (get-text-property 0 'test (format "%s" x)))
223 "Does format transport text properties?")
224
225 (defgroup org nil
226 "Outline-based notes management and organizer."
227 :tag "Org"
228 :group 'outlines
229 :group 'hypermedia
230 :group 'calendar)
231
232 (defgroup org-startup nil
233 "Options concerning startup of Org-mode."
234 :tag "Org Startup"
235 :group 'org)
236
237 (defcustom org-startup-folded t
238 "Non-nil means, entering Org-mode will switch to OVERVIEW.
239 This can also be configured on a per-file basis by adding one of
240 the following lines anywhere in the buffer:
241
242 #+STARTUP: fold
243 #+STARTUP: nofold
244 #+STARTUP: content"
245 :group 'org-startup
246 :type '(choice
247 (const :tag "nofold: show all" nil)
248 (const :tag "fold: overview" t)
249 (const :tag "content: all headlines" content)))
250
251 (defcustom org-startup-truncated t
252 "Non-nil means, entering Org-mode will set `truncate-lines'.
253 This is useful since some lines containing links can be very long and
254 uninteresting. Also tables look terrible when wrapped."
255 :group 'org-startup
256 :type 'boolean)
257
258 (defcustom org-startup-align-all-tables nil
259 "Non-nil means, align all tables when visiting a file.
260 This is useful when the column width in tables is forced with <N> cookies
261 in table fields. Such tables will look correct only after the first re-align.
262 This can also be configured on a per-file basis by adding one of
263 the following lines anywhere in the buffer:
264 #+STARTUP: align
265 #+STARTUP: noalign"
266 :group 'org-startup
267 :type 'boolean)
268
269 (defcustom org-startup-with-deadline-check nil
270 "Non-nil means, entering Org-mode will run the deadline check.
271 This means, if you start editing an org file, you will get an
272 immediate reminder of any due deadlines.
273 This can also be configured on a per-file basis by adding one of
274 the following lines anywhere in the buffer:
275 #+STARTUP: dlcheck
276 #+STARTUP: nodlcheck"
277 :group 'org-startup
278 :type 'boolean)
279
280 (defcustom org-insert-mode-line-in-empty-file nil
281 "Non-nil means insert the first line setting Org-mode in empty files.
282 When the function `org-mode' is called interactively in an empty file, this
283 normally means that the file name does not automatically trigger Org-mode.
284 To ensure that the file will always be in Org-mode in the future, a
285 line enforcing Org-mode will be inserted into the buffer, if this option
286 has been set."
287 :group 'org-startup
288 :type 'boolean)
289
290 (defcustom org-CUA-compatible nil
291 "Non-nil means use alternative key bindings for S-<cursor movement>.
292 Org-mode used S-<cursor movement> for changing timestamps and priorities.
293 S-<cursor movement> is also used for example by `CUA-mode' to select text.
294 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
295 alternative bindings. Setting this variable to t will replace the following
296 keys both in Org-mode and in the Org-agenda buffer.
297
298 S-RET -> C-S-RET
299 S-up -> M-p
300 S-down -> M-n
301 S-left -> M--
302 S-right -> M-+
303
304 If you do not like the alternative keys, take a look at the variable
305 `org-disputed-keys'.
306
307 This option is only relevant at load-time of Org-mode. Changing it requires
308 a restart of Emacs to become effective."
309 :group 'org-startup
310 :type 'boolean)
311
312 (defvar org-disputed-keys
313 '((S-up [(shift up)] [(meta ?p)])
314 (S-down [(shift down)] [(meta ?n)])
315 (S-left [(shift left)] [(meta ?-)])
316 (S-right [(shift right)] [(meta ?+)])
317 (S-return [(shift return)] [(control shift return)]))
318 "Keys for which Org-mode and other modes compete.
319 This is an alist, cars are symbols for lookup, 1st element is the default key,
320 second element will be used when `org-CUA-compatible' is t.")
321
322 (defun org-key (key)
323 "Select a key according to `org-CUA-compatible'."
324 (nth (if org-CUA-compatible 2 1)
325 (or (assq key org-disputed-keys)
326 (error "Invalid Key %s in `org-key'" key))))
327
328 (defcustom org-ellipsis nil
329 "The ellipsis to use in the Org-mode outline.
330 When nil, just use the standard three dots. When a string, use that instead,
331 and just in Org-mode (which will then use its own display table).
332 Changing this requires executing `M-x org-mode' in a buffer to become
333 effective."
334 :group 'org-startup
335 :type '(choice (const :tag "Default" nil)
336 (string :tag "String" :value "...#")))
337
338 (defvar org-display-table nil
339 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
340
341 (defgroup org-keywords nil
342 "Keywords in Org-mode."
343 :tag "Org Keywords"
344 :group 'org)
345
346 (defcustom org-deadline-string "DEADLINE:"
347 "String to mark deadline entries.
348 A deadline is this string, followed by a time stamp. Should be a word,
349 terminated by a colon. You can insert a schedule keyword and
350 a timestamp with \\[org-deadline].
351 Changes become only effective after restarting Emacs."
352 :group 'org-keywords
353 :type 'string)
354
355 (defcustom org-scheduled-string "SCHEDULED:"
356 "String to mark scheduled TODO entries.
357 A schedule is this string, followed by a time stamp. Should be a word,
358 terminated by a colon. You can insert a schedule keyword and
359 a timestamp with \\[org-schedule].
360 Changes become only effective after restarting Emacs."
361 :group 'org-keywords
362 :type 'string)
363
364 (defcustom org-closed-string "CLOSED:"
365 "String used as the prefix for timestamps logging closing a TODO entry."
366 :group 'org-keywords
367 :type 'string)
368
369 (defcustom org-clock-string "CLOCK:"
370 "String used as prefix for timestamps clocking work hours on an item."
371 :group 'org-keywords
372 :type 'string)
373
374 (defcustom org-comment-string "COMMENT"
375 "Entries starting with this keyword will never be exported.
376 An entry can be toggled between COMMENT and normal with
377 \\[org-toggle-comment].
378 Changes become only effective after restarting Emacs."
379 :group 'org-keywords
380 :type 'string)
381
382 (defcustom org-quote-string "QUOTE"
383 "Entries starting with this keyword will be exported in fixed-width font.
384 Quoting applies only to the text in the entry following the headline, and does
385 not extend beyond the next headline, even if that is lower level.
386 An entry can be toggled between QUOTE and normal with
387 \\[org-toggle-fixed-width-section]."
388 :group 'org-keywords
389 :type 'string)
390
391 (defgroup org-structure nil
392 "Options concerning the general structure of Org-mode files."
393 :tag "Org Structure"
394 :group 'org)
395
396 (defgroup org-cycle nil
397 "Options concerning visibility cycling in Org-mode."
398 :tag "Org Cycle"
399 :group 'org-structure)
400
401 (defcustom org-cycle-global-at-bob t
402 "Cycle globally if cursor is at beginning of buffer and not at a headline.
403 This makes it possible to do global cycling without having to use S-TAB or
404 C-u TAB. For this special case to work, the first line of the buffer
405 must not be a headline - it may be empty ot some other text. When used in
406 this way, `org-cycle-hook' is disables temporarily, to make sure the
407 cursor stays at the beginning of the buffer.
408 When this option is nil, don't do anything special at the beginning
409 of the buffer."
410 :group 'org-cycle
411 :type 'boolean)
412
413 (defcustom org-cycle-emulate-tab t
414 "Where should `org-cycle' emulate TAB.
415 nil Never
416 white Only in completely white lines
417 whitestart Only at the beginning of lines, before the first non-white char.
418 t Everywhere except in headlines
419 If TAB is used in a place where it does not emulate TAB, the current subtree
420 visibility is cycled."
421 :group 'org-cycle
422 :type '(choice (const :tag "Never" nil)
423 (const :tag "Only in completely white lines" white)
424 (const :tag "Before first char in a line" whitestart)
425 (const :tag "Everywhere except in headlines" t)
426 ))
427
428 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
429 org-optimize-window-after-visibility-change)
430 "Hook that is run after `org-cycle' has changed the buffer visibility.
431 The function(s) in this hook must accept a single argument which indicates
432 the new state that was set by the most recent `org-cycle' command. The
433 argument is a symbol. After a global state change, it can have the values
434 `overview', `content', or `all'. After a local state change, it can have
435 the values `folded', `children', or `subtree'."
436 :group 'org-cycle
437 :type 'hook)
438
439 (defgroup org-edit-structure nil
440 "Options concerning structure editing in Org-mode."
441 :tag "Org Edit Structure"
442 :group 'org-structure)
443
444 (defcustom org-odd-levels-only nil
445 "Non-nil means, skip even levels and only use odd levels for the outline.
446 This has the effect that two stars are being added/taken away in
447 promotion/demotion commands. It also influences how levels are
448 handled by the exporters.
449 Changing it requires restart of `font-lock-mode' to become effective
450 for fontification also in regions already fontified.
451 You may also set this on a per-file basis by adding one of the following
452 lines to the buffer:
453
454 #+STARTUP: odd
455 #+STARTUP: oddeven"
456 :group 'org-edit-structure
457 :group 'org-font-lock
458 :type 'boolean)
459
460 (defcustom org-adapt-indentation t
461 "Non-nil means, adapt indentation when promoting and demoting.
462 When this is set and the *entire* text in an entry is indented, the
463 indentation is increased by one space in a demotion command, and
464 decreased by one in a promotion command. If any line in the entry
465 body starts at column 0, indentation is not changed at all."
466 :group 'org-edit-structure
467 :type 'boolean)
468
469 (defcustom org-insert-heading-hook nil
470 "Hook being run after inserting a new heading."
471 :group 'org-edit-structure
472 :type 'boolean)
473
474 (defcustom org-enable-fixed-width-editor t
475 "Non-nil means, lines starting with \":\" are treated as fixed-width.
476 This currently only means, they are never auto-wrapped.
477 When nil, such lines will be treated like ordinary lines.
478 See also the QUOTE keyword."
479 :group 'org-edit-structure
480 :type 'boolean)
481
482 (defgroup org-sparse-trees nil
483 "Options concerning sparse trees in Org-mode."
484 :tag "Org Sparse Trees"
485 :group 'org-structure)
486
487 (defcustom org-highlight-sparse-tree-matches t
488 "Non-nil means, highlight all matches that define a sparse tree.
489 The highlights will automatically disappear the next time the buffer is
490 changed by an edit command."
491 :group 'org-sparse-trees
492 :type 'boolean)
493
494 (defcustom org-show-hierarchy-above t
495 "Non-nil means, show full hierarchy when showing a spot in the tree.
496 Turning this off makes sparse trees more compact, but also less clear."
497 :group 'org-sparse-trees
498 :type 'boolean)
499
500 (defcustom org-show-following-heading t
501 "Non-nil means, show heading following match in `org-occur'.
502 When doing an `org-occur' it is useful to show the headline which
503 follows the match, even if they do not match the regexp. This makes it
504 easier to edit directly inside the sparse tree. However, if you use
505 `org-occur' mainly as an overview, the following headlines are
506 unnecessary clutter."
507 :group 'org-sparse-trees
508 :type 'boolean)
509
510 (defcustom org-occur-hook '(org-first-headline-recenter)
511 "Hook that is run after `org-occur' has constructed a sparse tree.
512 This can be used to recenter the window to show as much of the structure
513 as possible."
514 :group 'org-sparse-trees
515 :type 'hook)
516
517 (defgroup org-plain-lists nil
518 "Options concerning plain lists in Org-mode."
519 :tag "Org Plain lists"
520 :group 'org-structure)
521
522 (defcustom org-cycle-include-plain-lists nil
523 "Non-nil means, include plain lists into visibility cycling.
524 This means that during cycling, plain list items will *temporarily* be
525 interpreted as outline headlines with a level given by 1000+i where i is the
526 indentation of the bullet. In all other operations, plain list items are
527 not seen as headlines. For example, you cannot assign a TODO keyword to
528 such an item."
529 :group 'org-plain-lists
530 :type 'boolean)
531
532
533 (defcustom org-plain-list-ordered-item-terminator t
534 "The character that makes a line with leading number an ordered list item.
535 Valid values are ?. and ?\). To get both terminators, use t. While
536 ?. may look nicer, it creates the danger that a line with leading
537 number may be incorrectly interpreted as an item. ?\) therefore is
538 the safe choice."
539 :group 'org-plain-lists
540 :type '(choice (const :tag "dot like in \"2.\"" ?.)
541 (const :tag "paren like in \"2)\"" ?\))
542 (const :tab "both" t)))
543
544 (defcustom org-auto-renumber-ordered-lists t
545 "Non-nil means, automatically renumber ordered plain lists.
546 Renumbering happens when the sequence have been changed with
547 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
548 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
549 :group 'org-plain-lists
550 :type 'boolean)
551
552 (defgroup org-archive nil
553 "Options concerning archiving in Org-mode."
554 :tag "Org Archive"
555 :group 'org-structure)
556
557 (defcustom org-archive-tag "ARCHIVE"
558 "The tag that marks a subtree as archived.
559 An archived subtree does not open during visibility cycling, and does
560 not contribute to the agenda listings."
561 :group 'org-archive
562 :group 'org-keywords
563 :type 'string)
564
565 (defcustom org-agenda-skip-archived-trees t
566 "Non-nil means, the agenda will skip any items located in archived trees.
567 An archived tree is a tree marked with the tag ARCHIVE."
568 :group 'org-archive
569 :group 'org-agenda-display
570 :type 'boolean)
571
572 (defcustom org-cycle-open-archived-trees nil
573 "Non-nil means, `org-cycle' will open archived trees.
574 An archived tree is a tree marked with the tag ARCHIVE.
575 When nil, archived trees will stay folded. You can still open them with
576 normal outline commands like `show-all', but not with the cycling commands."
577 :group 'org-archive
578 :group 'org-cycle
579 :type 'boolean)
580
581 (defcustom org-sparse-tree-open-archived-trees nil
582 "Non-nil means sparse tree construction shows matches in archived trees.
583 When nil, matches in these trees are highlighted, but the trees are kept in
584 collapsed state."
585 :group 'org-archive
586 :group 'org-sparse-trees
587 :type 'boolean)
588
589 (defcustom org-archive-location "%s_archive::"
590 "The location where subtrees should be archived.
591 This string consists of two parts, separated by a double-colon.
592
593 The first part is a file name - when omitted, archiving happens in the same
594 file. %s will be replaced by the current file name (without directory part).
595 Archiving to a different file is useful to keep archived entries from
596 contributing to the Org-mode Agenda.
597
598 The part after the double colon is a headline. The archived entries will be
599 filed under that headline. When omitted, the subtrees are simply filed away
600 at the end of the file, as top-level entries.
601
602 Here are a few examples:
603 \"%s_archive::\"
604 If the current file is Projects.org, archive in file
605 Projects.org_archive, as top-level trees. This is the default.
606
607 \"::* Archived Tasks\"
608 Archive in the current file, under the top-level headline
609 \"* Archived Tasks\".
610
611 \"~/org/archive.org::\"
612 Archive in file ~/org/archive.org (absolute path), as top-level trees.
613
614 \"basement::** Finished Tasks\"
615 Archive in file ./basement (relative path), as level 3 trees
616 below the level 2 heading \"** Finished Tasks\".
617
618 You may set this option on a per-file basis by adding to the buffer a
619 line like
620
621 #+ARCHIVE: basement::** Finished Tasks"
622 :group 'org-archive
623 :type 'string)
624
625 (defcustom org-archive-mark-done t
626 "Non-nil means, mark entries as DONE when they are moved to the archive file."
627 :group 'org-archive
628 :type 'boolean)
629
630 (defcustom org-archive-stamp-time t
631 "Non-nil means, add a time stamp to entries moved to an archive file.
632 The time stamp will be added directly after the TODO state keyword in the
633 first line, so it is probably best to use this in combinations with
634 `org-archive-mark-done'."
635 :group 'org-archive
636 :type 'boolean)
637
638 (defgroup org-table nil
639 "Options concerning tables in Org-mode."
640 :tag "Org Table"
641 :group 'org)
642
643 (defcustom org-enable-table-editor 'optimized
644 "Non-nil means, lines starting with \"|\" are handled by the table editor.
645 When nil, such lines will be treated like ordinary lines.
646
647 When equal to the symbol `optimized', the table editor will be optimized to
648 do the following:
649 - Use automatic overwrite mode in front of whitespace in table fields.
650 This make the structure of the table stay in tact as long as the edited
651 field does not exceed the column width.
652 - Minimize the number of realigns. Normally, the table is aligned each time
653 TAB or RET are pressed to move to another field. With optimization this
654 happens only if changes to a field might have changed the column width.
655 Optimization requires replacing the functions `self-insert-command',
656 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
657 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
658 very good at guessing when a re-align will be necessary, but you can always
659 force one with \\[org-ctrl-c-ctrl-c].
660
661 If you would like to use the optimized version in Org-mode, but the
662 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
663
664 This variable can be used to turn on and off the table editor during a session,
665 but in order to toggle optimization, a restart is required.
666
667 See also the variable `org-table-auto-blank-field'."
668 :group 'org-table
669 :type '(choice
670 (const :tag "off" nil)
671 (const :tag "on" t)
672 (const :tag "on, optimized" optimized)))
673
674 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
675 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
676 In the optimized version, the table editor takes over all simple keys that
677 normally just insert a character. In tables, the characters are inserted
678 in a way to minimize disturbing the table structure (i.e. in overwrite mode
679 for empty fields). Outside tables, the correct binding of the keys is
680 restored.
681
682 The default for this option is t if the optimized version is also used in
683 Org-mode. See the variable `org-enable-table-editor' for details. Changing
684 this variable requires a restart of Emacs to become effective."
685 :group 'org-table
686 :type 'boolean)
687
688 (defgroup org-table-settings nil
689 "Settings for tables in Org-mode."
690 :tag "Org Table Settings"
691 :group 'org-table)
692
693 (defcustom org-table-default-size "5x2"
694 "The default size for newly created tables, Columns x Rows."
695 :group 'org-table-settings
696 :type 'string)
697
698 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
699 "Regular expression for recognizing numbers in table columns.
700 If a table column contains mostly numbers, it will be aligned to the
701 right. If not, it will be aligned to the left.
702
703 The default value of this option is a regular expression which allows
704 anything which looks remotely like a number as used in scientific
705 context. For example, all of the following will be considered a
706 number:
707 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
708
709 Other options offered by the customize interface are more restrictive."
710 :group 'org-table-settings
711 :type '(choice
712 (const :tag "Positive Integers"
713 "^[0-9]+$")
714 (const :tag "Integers"
715 "^[-+]?[0-9]+$")
716 (const :tag "Floating Point Numbers"
717 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
718 (const :tag "Floating Point Number or Integer"
719 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
720 (const :tag "Exponential, Floating point, Integer"
721 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
722 (const :tag "Very General Number-Like"
723 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
724 (string :tag "Regexp:")))
725
726 (defcustom org-table-number-fraction 0.5
727 "Fraction of numbers in a column required to make the column align right.
728 In a column all non-white fields are considered. If at least this
729 fraction of fields is matched by `org-table-number-fraction',
730 alignment to the right border applies."
731 :group 'org-table-settings
732 :type 'number)
733
734 (defgroup org-table-editing nil
735 "Bahavior of tables during editing in Org-mode."
736 :tag "Org Table Editing"
737 :group 'org-table)
738
739 (defcustom org-table-automatic-realign t
740 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
741 When nil, aligning is only done with \\[org-table-align], or after column
742 removal/insertion."
743 :group 'org-table-editing
744 :type 'boolean)
745
746 (defcustom org-table-limit-column-width t ;kw
747 "Non-nil means, allow to limit the width of table columns with <N> fields."
748 :group 'org-table-editing
749 :type 'boolean)
750
751 (defcustom org-table-auto-blank-field t
752 "Non-nil means, automatically blank table field when starting to type into it.
753 This only happens when typing immediately after a field motion
754 command (TAB, S-TAB or RET).
755 Only relevant when `org-enable-table-editor' is equal to `optimized'."
756 :group 'org-table-editing
757 :type 'boolean)
758
759 (defcustom org-table-tab-jumps-over-hlines t
760 "Non-nil means, tab in the last column of a table with jump over a hline.
761 If a horizontal separator line is following the current line,
762 `org-table-next-field' can either create a new row before that line, or jump
763 over the line. When this option is nil, a new line will be created before
764 this line."
765 :group 'org-table-editing
766 :type 'boolean)
767
768 (defcustom org-table-tab-recognizes-table.el t
769 "Non-nil means, TAB will automatically notice a table.el table.
770 When it sees such a table, it moves point into it and - if necessary -
771 calls `table-recognize-table'."
772 :group 'org-table-editing
773 :type 'boolean)
774
775 (defgroup org-table-calculation nil
776 "Options concerning tables in Org-mode."
777 :tag "Org Table Calculation"
778 :group 'org-table)
779
780 (defcustom org-table-copy-increment t
781 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
782 :group 'org-table-calculation
783 :type 'boolean)
784
785 (defcustom org-calc-default-modes
786 '(calc-internal-prec 12
787 calc-float-format (float 5)
788 calc-angle-mode deg
789 calc-prefer-frac nil
790 calc-symbolic-mode nil
791 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
792 calc-display-working-message t
793 )
794 "List with Calc mode settings for use in calc-eval for table formulas.
795 The list must contain alternating symbols (Calc modes variables and values).
796 Don't remove any of the default settings, just change the values. Org-mode
797 relies on the variables to be present in the list."
798 :group 'org-table-calculation
799 :type 'plist)
800
801 (defcustom org-table-formula-evaluate-inline t
802 "Non-nil means, TAB and RET evaluate a formula in current table field.
803 If the current field starts with an equal sign, it is assumed to be a formula
804 which should be evaluated as described in the manual and in the documentation
805 string of the command `org-table-eval-formula'. This feature requires the
806 Emacs calc package.
807 When this variable is nil, formula calculation is only available through
808 the command \\[org-table-eval-formula]."
809 :group 'org-table-calculation
810 :type 'boolean)
811
812
813 (defcustom org-table-formula-use-constants t
814 "Non-nil means, interpret constants in formulas in tables.
815 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
816 by the value given in `org-table-formula-constants', or by a value obtained
817 from the `constants.el' package."
818 :group 'org-table-calculation
819 :type 'boolean)
820
821 (defcustom org-table-formula-constants nil
822 "Alist with constant names and values, for use in table formulas.
823 The car of each element is a name of a constant, without the `$' before it.
824 The cdr is the value as a string. For example, if you'd like to use the
825 speed of light in a formula, you would configure
826
827 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
828
829 and then use it in an equation like `$1*$c'."
830 :group 'org-table-calculation
831 :type '(repeat
832 (cons (string :tag "name")
833 (string :tag "value"))))
834
835 (defcustom org-table-formula-numbers-only nil
836 "Non-nil means, calculate only with numbers in table formulas.
837 Then all input fields will be converted to a number, and the result
838 must also be a number. When nil, calc's full potential is available
839 in table calculations, including symbolics etc."
840 :group 'org-table-calculation
841 :type 'boolean)
842
843 (defcustom org-table-allow-automatic-line-recalculation t
844 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
845 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
846 :group 'org-table-calculation
847 :type 'boolean)
848
849 (defgroup org-link nil
850 "Options concerning links in Org-mode."
851 :tag "Org Link"
852 :group 'org)
853
854 (defcustom org-descriptive-links t
855 "Non-nil means, hide link part and only show description of bracket links.
856 Bracket links are like [[link][descritpion]]. This variable sets the initial
857 state in new org-mode buffers. The setting can then be toggled on a
858 per-buffer basis from the Org->Hyperlinks menu."
859 :group 'org-link
860 :type 'boolean)
861
862 (defcustom org-link-style 'bracket
863 "The style of links to be inserted with \\[org-insert-link].
864 Possible values are:
865 bracket [[link][description]]. This is recommended
866 plain Description \\n link. The old way, no longer recommended."
867 :group 'org-link
868 :type '(choice
869 (const :tag "Bracket (recommended)" bracket)
870 (const :tag "Plain (no longer recommended)" plain)))
871
872 (defcustom org-link-format "%s"
873 "Default format for external, URL-like linkes in the buffer.
874 This is a format string for printf, %s will be replaced by the link text.
875 The recommended value is just \"%s\", since links will be protected by
876 enclosing them in double brackets. If you prefer plain links (see variable
877 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
878 additional URL: prefix, so the format would be \"<URL:%s>\"."
879 :group 'org-link
880 :type '(choice
881 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
882 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
883 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
884 (string :tag "Other" :value "<%s>")))
885
886 (defcustom org-link-file-path-type 'adaptive
887 "How the path name in file links should be stored.
888 Valid values are:
889
890 relative relative to the current directory, i.e. the directory of the file
891 into which the link is being inserted.
892 absolute absolute path, if possible with ~ for home directory.
893 noabbrev absolute path, no abbreviation of home directory.
894 adaptive Use relative path for files in the current directory and sub-
895 directories of it. For other files, use an absolute path."
896 :group 'org-link
897 :type '(choice
898 (const relative)
899 (const absolute)
900 (const noabbrev)
901 (const adaptive)))
902
903 (defcustom org-activate-links '(bracket angle plain radio tag date)
904 "Types of links that should be activated in Org-mode files.
905 This is a list of symbols, each leading to the activation of a certain link
906 type. In principle, it does not hurt to turn on most link types - there may
907 be a small gain when turning off unused link types. The types are:
908
909 bracket The recommended [[link][description]] or [[link]] links with hiding.
910 angular Links in angular brackes that may contain whitespace like
911 <bbdb:Carsten Dominik>.
912 plain Plain links in normal text, no whitespace, like http://google.com.
913 radio Text that is matched by a radio target, see manual for details.
914 tag Tag settings in a headline (link to tag search).
915 date Time stamps (link to calendar).
916 camel CamelCase words defining text searches.
917
918 Changing this variable requires a restart of Emacs to become effective."
919 :group 'org-link
920 :type '(set (const :tag "Double bracket links (new style)" bracket)
921 (const :tag "Angular bracket links (old style)" angular)
922 (const :tag "plain text links" plain)
923 (const :tag "Radio target matches" radio)
924 (const :tag "Tags" tag)
925 (const :tag "Timestamps" date)
926 (const :tag "CamelCase words" camel)))
927
928 (defgroup org-link-store nil
929 "Options concerning storing links in Org-mode"
930 :tag "Org Store Link"
931 :group 'org-link)
932
933 (defcustom org-context-in-file-links t
934 "Non-nil means, file links from `org-store-link' contain context.
935 A search string will be added to the file name with :: as separator and
936 used to find the context when the link is activated by the command
937 `org-open-at-point'.
938 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
939 negates this setting for the duration of the command."
940 :group 'org-link-store
941 :type 'boolean)
942
943 (defcustom org-file-link-context-use-camel-case nil
944 "Non-nil means, use CamelCase to store a search context in a file link.
945 When nil, the search string simply consists of the words of the string.
946 CamelCase is deprecated, and support for it may be dropped in the future."
947 :group 'org-link-store
948 :type 'boolean)
949
950 (defcustom org-keep-stored-link-after-insertion nil
951 "Non-nil means, keep link in list for entire session.
952
953 The command `org-store-link' adds a link pointing to the current
954 location to an internal list. These links accumulate during a session.
955 The command `org-insert-link' can be used to insert links into any
956 Org-mode file (offering completion for all stored links). When this
957 option is nil, every link which has been inserted once using \\[org-insert-link]
958 will be removed from the list, to make completing the unused links
959 more efficient."
960 :group 'org-link-store
961 :type 'boolean)
962
963 (defcustom org-usenet-links-prefer-google nil
964 "Non-nil means, `org-store-link' will create web links to Google groups.
965 When nil, Gnus will be used for such links.
966 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
967 negates this setting for the duration of the command."
968 :group 'org-link-store
969 :type 'boolean)
970
971 (defgroup org-link-follow nil
972 "Options concerning following links in Org-mode"
973 :tag "Org Follow Link"
974 :group 'org-link)
975
976 (defcustom org-tab-follows-link nil
977 "Non-nil means, on links TAB will follow the link.
978 Needs to be set before org.el is loaded."
979 :group 'org-link-follow
980 :type 'boolean)
981
982 (defcustom org-return-follows-link nil
983 "Non-nil means, on links RET will follow the link.
984 Needs to be set before org.el is loaded."
985 :group 'org-link-follow
986 :type 'boolean)
987
988 (defcustom org-mouse-1-follows-link t
989 "Non-nil means, mouse-1 on a link will follow the link.
990 A longer mouse click will still set point. Does not wortk on XEmacs.
991 Needs to be set before org.el is loaded."
992 :group 'org-link-follow
993 :type 'boolean)
994
995 (defcustom org-mark-ring-length 4
996 "Number of different positions to be recorded in the ring
997 Changing this requires a restart of Emacs to work correctly."
998 :group 'org-link-follow
999 :type 'interger)
1000
1001 (defcustom org-link-frame-setup
1002 '((vm . vm-visit-folder-other-frame)
1003 (gnus . gnus-other-frame)
1004 (file . find-file-other-window))
1005 "Setup the frame configuration for following links.
1006 When following a link with Emacs, it may often be useful to display
1007 this link in another window or frame. This variable can be used to
1008 set this up for the different types of links.
1009 For VM, use any of
1010 `vm-visit-folder'
1011 `vm-visit-folder-other-frame'
1012 For Gnus, use any of
1013 `gnus'
1014 `gnus-other-frame'
1015 For FILE, use any of
1016 `find-file'
1017 `find-file-other-window'
1018 `find-file-other-frame'
1019 For the calendar, use the variable `calendar-setup'.
1020 For BBDB, it is currently only possible to display the matches in
1021 another window."
1022 :group 'org-link-follow
1023 :type '(list
1024 (cons (const vm)
1025 (choice
1026 (const vm-visit-folder)
1027 (const vm-visit-folder-other-window)
1028 (const vm-visit-folder-other-frame)))
1029 (cons (const gnus)
1030 (choice
1031 (const gnus)
1032 (const gnus-other-frame)))
1033 (cons (const file)
1034 (choice
1035 (const find-file)
1036 (const find-file-other-window)
1037 (const find-file-other-frame)))))
1038
1039 (defcustom org-open-non-existing-files nil
1040 "Non-nil means, `org-open-file' will open non-existing file.
1041 When nil, an error will be generated."
1042 :group 'org-link-follow
1043 :type 'boolean)
1044
1045 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1046 "Non-nil means, ask for confirmation before executing shell links.
1047 Shell links can be dangerous, just thing about a link
1048
1049 [[shell:rm -rf ~/*][Google Search]]
1050
1051 This link would show up in your Org-mode document as \"Google Search\"
1052 but really it would remove your entire home directory.
1053 Therefore I *definitely* advise against setting this variable to nil.
1054 Just change it to `y-or-n-p' of you want to confirm with a single key press
1055 rather than having to type \"yes\"."
1056 :group 'org-link-follow
1057 :type '(choice
1058 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1059 (const :tag "with y-or-n (faster)" y-or-n-p)
1060 (const :tag "no confirmation (dangerous)" nil)))
1061
1062 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1063 "Non-nil means, ask for confirmation before executing elisp links.
1064 Elisp links can be dangerous, just thing about a link
1065
1066 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1067
1068 This link would show up in your Org-mode document as \"Google Search\"
1069 but really it would remove your entire home directory.
1070 Therefore I *definitely* advise against setting this variable to nil.
1071 Just change it to `y-or-n-p' of you want to confirm with a single key press
1072 rather than having to type \"yes\"."
1073 :group 'org-link-follow
1074 :type '(choice
1075 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1076 (const :tag "with y-or-n (faster)" y-or-n-p)
1077 (const :tag "no confirmation (dangerous)" nil)))
1078
1079 (defconst org-file-apps-defaults-gnu
1080 '((remote . emacs)
1081 (t . mailcap))
1082 "Default file applications on a UNIX or GNU/Linux system.
1083 See `org-file-apps'.")
1084
1085 (defconst org-file-apps-defaults-macosx
1086 '((remote . emacs)
1087 (t . "open %s")
1088 ("ps" . "gv %s")
1089 ("ps.gz" . "gv %s")
1090 ("eps" . "gv %s")
1091 ("eps.gz" . "gv %s")
1092 ("dvi" . "xdvi %s")
1093 ("fig" . "xfig %s"))
1094 "Default file applications on a MacOS X system.
1095 The system \"open\" is known as a default, but we use X11 applications
1096 for some files for which the OS does not have a good default.
1097 See `org-file-apps'.")
1098
1099 (defconst org-file-apps-defaults-windowsnt
1100 (list
1101 '(remote . emacs)
1102 (cons t
1103 (list (if (featurep 'xemacs)
1104 'mswindows-shell-execute
1105 'w32-shell-execute)
1106 "open" 'file)))
1107 "Default file applications on a Windows NT system.
1108 The system \"open\" is used for most files.
1109 See `org-file-apps'.")
1110
1111 (defcustom org-file-apps
1112 '(
1113 ("txt" . emacs)
1114 ("tex" . emacs)
1115 ("ltx" . emacs)
1116 ("org" . emacs)
1117 ("el" . emacs)
1118 ("bib" . emacs)
1119 )
1120 "External applications for opening `file:path' items in a document.
1121 Org-mode uses system defaults for different file types, but
1122 you can use this variable to set the application for a given file
1123 extension. The entries in this list are cons cells where the car identifies
1124 files and the cdr the corresponding command. Possible values for the
1125 file identifier are
1126 \"ext\" A string identifying an extension
1127 `directory' Matches a directory
1128 `remote' Matches a remove file, accessible through tramp or efs.
1129 Remote files most likely should be visited through emacs
1130 because external applications cannot handle such paths.
1131 t Default for all remaining files
1132
1133 Possible values for the command are:
1134 `emacs' The file will be visited by the current Emacs process.
1135 `default' Use the default application for this file type.
1136 string A command to be executed by a shell; %s will be replaced
1137 by the path to the file.
1138 sexp A Lisp form which will be evaluated. The file path will
1139 be available in the Lisp variable `file'.
1140 For more examples, see the system specific constants
1141 `org-file-apps-defaults-macosx'
1142 `org-file-apps-defaults-windowsnt'
1143 `org-file-apps-defaults-gnu'."
1144 :group 'org-link-follow
1145 :type '(repeat
1146 (cons (choice :value ""
1147 (string :tag "Extension")
1148 (const :tag "Default for unrecognized files" t)
1149 (const :tag "Remote file" remote)
1150 (const :tag "Links to a directory" directory))
1151 (choice :value ""
1152 (const :tag "Visit with Emacs" emacs)
1153 (const :tag "Use system default" default)
1154 (string :tag "Command")
1155 (sexp :tag "Lisp form")))))
1156
1157 (defcustom org-mhe-search-all-folders nil
1158 "Non-nil means, that the search for the mh-message will be extended to
1159 all folders if the message cannot be found in the folder given in the link.
1160 Searching all folders is very effective with one of the search engines
1161 supported by MH-E, but will be slow with pick."
1162 :group 'org-link-follow
1163 :type 'boolean)
1164
1165 (defgroup org-remember nil
1166 "Options concerning interaction with remember.el."
1167 :tag "Org Remember"
1168 :group 'org)
1169
1170 (defcustom org-directory "~/org"
1171 "Directory with org files.
1172 This directory will be used as default to prompt for org files.
1173 Used by the hooks for remember.el."
1174 :group 'org-remember
1175 :type 'directory)
1176
1177 (defcustom org-default-notes-file "~/.notes"
1178 "Default target for storing notes.
1179 Used by the hooks for remember.el. This can be a string, or nil to mean
1180 the value of `remember-data-file'."
1181 :group 'org-remember
1182 :type '(choice
1183 (const :tag "Default from remember-data-file" nil)
1184 file))
1185
1186 (defcustom org-remember-templates nil
1187 "Templates for the creation of remember buffers.
1188 When nil, just let remember make the buffer.
1189 When not nil, this is a list of 3-element lists. In each entry, the first
1190 element is a character, a unique key to select this template.
1191 The second element is the template. The third element is optional and can
1192 specify a destination file for remember items created with this template.
1193 The default file is given by `org-default-notes-file'.
1194
1195 The template specifies the structure of the remember buffer. It should have
1196 a first line starting with a star, to act as the org-mode headline.
1197 Furthermore, the following %-escapes will be replaced with content:
1198 %t time stamp, date only
1199 %T time stamp with date and time
1200 %u inactive time stamp, date only
1201 %U inactive time stamp with date and time
1202 %n user name
1203 %a annotation, normally the link created with org-store-link
1204 %i initial content, the region when remember is called with C-u.
1205 If %i is indented, the entire inserted text will be indented as well.
1206 %? This will be removed, and the cursor placed at this position."
1207 :group 'org-remember
1208 :type '(repeat :tag "enabled"
1209 (list :value (?a "\n" nil)
1210 (character :tag "Selection Key")
1211 (string :tag "Template")
1212 (file :tag "Destination file (optional)"))))
1213
1214 (defcustom org-reverse-note-order nil
1215 "Non-nil means, store new notes at the beginning of a file or entry.
1216 When nil, new notes will be filed to the end of a file or entry."
1217 :group 'org-remember
1218 :type '(choice
1219 (const :tag "Reverse always" t)
1220 (const :tag "Reverse never" nil)
1221 (repeat :tag "By file name regexp"
1222 (cons regexp boolean))))
1223
1224 (defgroup org-todo nil
1225 "Options concerning TODO items in Org-mode."
1226 :tag "Org TODO"
1227 :group 'org)
1228
1229 (defcustom org-todo-keywords '("TODO" "DONE")
1230 "List of TODO entry keywords.
1231 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1232 considered to mean that the entry is \"done\". All the other mean that
1233 action is required, and will make the entry show up in todo lists, diaries
1234 etc.
1235 The command \\[org-todo] cycles an entry through these states, and an
1236 additional state where no keyword is present. For details about this
1237 cycling, see also the variable `org-todo-interpretation'
1238 Changes become only effective after restarting Emacs."
1239 :group 'org-todo
1240 :group 'org-keywords
1241 :type '(repeat (string :tag "Keyword")))
1242
1243 (defcustom org-todo-interpretation 'sequence
1244 "Controls how TODO keywords are interpreted.
1245 This variable is only relevant if `org-todo-keywords' contains more than two
1246 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1247
1248 When `sequence', \\[org-todo] will always switch to the next state in the
1249 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1250 to state when executed several times in direct succession. Otherwise, it
1251 switches directly to DONE from any state.
1252 See the manual for more information."
1253 :group 'org-todo
1254 :group 'org-keywords
1255 :type '(choice (const sequence)
1256 (const type)))
1257
1258 (defcustom org-after-todo-state-change-hook nil
1259 "Hook which is run after the state of a TODO item was changed.
1260 The new state (a string with a TODO keyword, or nil) is available in the
1261 Lisp variable `state'."
1262 :group 'org-todo
1263 :type 'hook)
1264
1265 (defcustom org-log-done nil
1266 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1267 When the state of an entry is changed from nothing to TODO, remove a previous
1268 closing date.
1269 This can also be configured on a per-file basis by adding one of
1270 the following lines anywhere in the buffer:
1271
1272 #+STARTUP: logging
1273 #+STARTUP: nologging"
1274 :group 'org-todo
1275 :type 'boolean)
1276
1277 (defgroup org-priorities nil
1278 "Priorities in Org-mode."
1279 :tag "Org Priorities"
1280 :group 'org-todo)
1281
1282 (defcustom org-default-priority ?B
1283 "The default priority of TODO items.
1284 This is the priority an item get if no explicit priority is given."
1285 :group 'org-priorities
1286 :type 'character)
1287
1288 (defcustom org-lowest-priority ?C
1289 "The lowest priority of TODO items. A character like ?A, ?B etc."
1290 :group 'org-priorities
1291 :type 'character)
1292
1293 (defgroup org-time nil
1294 "Options concerning time stamps and deadlines in Org-mode."
1295 :tag "Org Time"
1296 :group 'org)
1297
1298 (defcustom org-insert-labeled-timestamps-at-point nil
1299 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1300 When nil, these labeled time stamps are forces into the second line of an
1301 entry, just after the headline. When scheduling from the global TODO list,
1302 the time stamp will always be forced into the second line."
1303 :group 'org-time
1304 :type 'boolean)
1305
1306 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1307 "Formats for `format-time-string' which are used for time stamps.
1308 It is not recommended to change this constant.")
1309
1310 (defcustom org-time-stamp-rounding-minutes 0
1311 "Number of minutes to round time stamps to upon insertion.
1312 When zero, insert the time unmodified. Useful rounding numbers
1313 should be factors of 60, so for example 5, 10, 15.
1314 When this is not zero, you can still force an exact time-stamp by using
1315 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1316 :group 'org-time
1317 :type 'integer)
1318
1319 (defcustom org-deadline-warning-days 30
1320 "No. of days before expiration during which a deadline becomes active.
1321 This variable governs the display in the org file."
1322 :group 'org-time
1323 :type 'number)
1324
1325 (defcustom org-popup-calendar-for-date-prompt t
1326 "Non-nil means, pop up a calendar when prompting for a date.
1327 In the calendar, the date can be selected with mouse-1. However, the
1328 minibuffer will also be active, and you can simply enter the date as well.
1329 When nil, only the minibuffer will be available."
1330 :group 'org-time
1331 :type 'boolean)
1332
1333 (defcustom org-calendar-follow-timestamp-change t
1334 "Non-nil means, make the calendar window follow timestamp changes.
1335 When a timestamp is modified and the calendar window is visible, it will be
1336 moved to the new date."
1337 :group 'org-time
1338 :type 'boolean)
1339
1340 (defgroup org-tags nil
1341 "Options concerning tags in Org-mode."
1342 :tag "Org Tags"
1343 :group 'org)
1344
1345 (defcustom org-tag-alist nil
1346 "List of tags allowed in Org-mode files.
1347 When this list is nil, Org-mode will base TAG input on what is already in the
1348 buffer.
1349 The value of this variable is an alist, the car may be (and should) be a
1350 character that is used to select that tag through the fast-tag-selection
1351 interface. See the manual for details."
1352 :group 'org-tags
1353 :type '(repeat
1354 (choice
1355 (cons (string :tag "Tag name")
1356 (character :tag "Access char"))
1357 (const :tag "Start radio group" (:startgroup))
1358 (const :tag "End radio group" (:endgroup)))))
1359
1360 (defcustom org-use-fast-tag-selection 'auto
1361 "Non-nil means, use fast tag selection scheme.
1362 This is a special interface to select and deselect tags with single keys.
1363 When nil, fast selection is never used.
1364 When the symbol `auto', fast selection is used if and only if selection
1365 characters for tags have been configured, either through the variable
1366 `org-tag-alist' or through a #+TAGS line in the buffer.
1367 When t, fast selection is always used and selection keys are assigned
1368 automatically if necessary."
1369 :group 'org-tags
1370 :type '(choice
1371 (const :tag "Always" t)
1372 (const :tag "Never" nil)
1373 (const :tag "When selection characters are configured" 'auto)))
1374
1375 (defcustom org-tags-column 48
1376 "The column to which tags should be indented in a headline.
1377 If this number is positive, it specifies the column. If it is negative,
1378 it means that the tags should be flushright to that column. For example,
1379 -79 works well for a normal 80 character screen."
1380 :group 'org-tags
1381 :type 'integer)
1382
1383 (defcustom org-auto-align-tags t
1384 "Non-nil means, realign tags after pro/demotion of TODO state change.
1385 These operations change the length of a headline and therefore shift
1386 the tags around. With this options turned on, after each such operation
1387 the tags are again aligned to `org-tags-column'."
1388 :group 'org-tags
1389 :type 'boolean)
1390
1391 (defcustom org-use-tag-inheritance t
1392 "Non-nil means, tags in levels apply also for sublevels.
1393 When nil, only the tags directly given in a specific line apply there.
1394 If you turn off this option, you very likely want to turn on the
1395 companion option `org-tags-match-list-sublevels'."
1396 :group 'org-tags
1397 :type 'boolean)
1398
1399 (defcustom org-tags-match-list-sublevels nil
1400 "Non-nil means list also sublevels of headlines matching tag search.
1401 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1402 the sublevels of a headline matching a tag search often also match
1403 the same search. Listing all of them can create very long lists.
1404 Setting this variable to nil causes subtrees of a match to be skipped.
1405 This option is off by default, because inheritance in on. If you turn
1406 inheritance off, you very likely want to turn this option on.
1407
1408 As a special case, if the tag search is restricted to TODO items, the
1409 value of this variable is ignored and sublevels are always checked, to
1410 make sure all corresponding TODO items find their way into the list."
1411 :group 'org-tags
1412 :type 'boolean)
1413
1414 (defvar org-tags-history nil
1415 "History of minibuffer reads for tags.")
1416 (defvar org-last-tags-completion-table nil
1417 "The last used completion table for tags.")
1418
1419 (defgroup org-agenda nil
1420 "Options concerning agenda display Org-mode."
1421 :tag "Org Agenda"
1422 :group 'org)
1423
1424 (defvar org-category nil
1425 "Variable used by org files to set a category for agenda display.
1426 Such files should use a file variable to set it, for example
1427
1428 -*- mode: org; org-category: \"ELisp\"
1429
1430 or contain a special line
1431
1432 #+CATEGORY: ELisp
1433
1434 If the file does not specify a category, then file's base name
1435 is used instead.")
1436 (make-variable-buffer-local 'org-category)
1437
1438 (defcustom org-agenda-files nil
1439 "The files to be used for agenda display.
1440 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1441 \\[org-remove-file]. You can also use customize to edit the list.
1442
1443 If the value of the variable is not a list but a single file name, then
1444 the list of agenda files is actually stored and maintained in that file, one
1445 agenda file per line."
1446 :group 'org-agenda
1447 :type '(choice
1448 (repeat :tag "List of files" file)
1449 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1450
1451 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1452 "Custom commands for the agenda.
1453 These commands will be offered on the splash screen displayed by the
1454 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1455
1456 key The key (a single char as a string) to be associated with the command.
1457 type The command type, any of the following symbols:
1458 todo Entries with a specific TODO keyword, in all agenda files.
1459 tags Tags match in all agenda files.
1460 tags-todo Tags match in all agenda files, TODO entries only.
1461 todo-tree Sparse tree of specific TODO keyword in *current* file.
1462 tags-tree Sparse tree with all tags matches in *current* file.
1463 occur-tree Occur sparse tree for current file.
1464 match What to search for:
1465 - a single keyword for TODO keyword searches
1466 - a tags match expression for tags searches
1467 - a regular expression for occur searches"
1468 :group 'org-agenda
1469 :type '(repeat
1470 (list (string :tag "Key")
1471 (choice :tag "Type"
1472 (const :tag "Tags search in all agenda files" tags)
1473 (const :tag "Tags search of TODO entries, all agenda files" tags-todo)
1474 (const :tag "TODO keyword search in all agenda files" todo)
1475 (const :tag "Tags sparse tree in current buffer" tags-tree)
1476 (const :tag "TODO keyword tree in current buffer" todo-tree)
1477 (const :tag "Occur tree in current buffer" occur-tree))
1478 (string :tag "Match"))))
1479
1480 (defcustom org-agenda-todo-list-sublevels t
1481 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1482 When nil, the sublevels of a TODO entry are not checked, resulting in
1483 potentially much shorter TODO lists."
1484 :group 'org-agenda
1485 :group 'org-todo
1486 :type 'boolean)
1487
1488 (defcustom org-agenda-todo-ignore-scheduled nil
1489 "Non-nil means, don't show scheduled entries in the global todo list.
1490 The idea behind this is that by scheduling it, you have already taken care
1491 of this item."
1492 :group 'org-agenda
1493 :group 'org-todo
1494 :type 'boolean)
1495
1496 (defcustom org-agenda-include-all-todo nil
1497 "Non-nil means, the agenda will always contain all TODO entries.
1498 When nil, date-less entries will only be shown if `org-agenda' is called
1499 with a prefix argument.
1500 When non-nil, the TODO entries will be listed at the top of the agenda, before
1501 the entries for specific days."
1502 :group 'org-agenda
1503 :type 'boolean)
1504
1505 (defcustom org-agenda-include-diary nil
1506 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1507 :group 'org-agenda
1508 :type 'boolean)
1509
1510 (defcustom org-calendar-to-agenda-key [?c]
1511 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1512 The command `org-calendar-goto-agenda' will be bound to this key. The
1513 default is the character `c' because then `c' can be used to switch back and
1514 forth between agenda and calendar."
1515 :group 'org-agenda
1516 :type 'sexp)
1517
1518 (defgroup org-agenda-setup nil
1519 "Options concerning setting up the Agenda window in Org Mode."
1520 :tag "Org Agenda Window Setup"
1521 :group 'org-agenda)
1522
1523 (defcustom org-agenda-mouse-1-follows-link nil
1524 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1525 A longer mouse click will still set point. Does not wortk on XEmacs.
1526 Needs to be set before org.el is loaded."
1527 :group 'org-agenda-setup
1528 :type 'boolean)
1529
1530 (defcustom org-agenda-start-with-follow-mode nil
1531 "The initial value of follwo-mode in a newly created agenda window."
1532 :group 'org-agenda-setup
1533 :type 'boolean)
1534
1535 (defcustom org-select-agenda-window t
1536 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1537 When nil, cursor will remain in the current window."
1538 :group 'org-agenda-setup
1539 :type 'boolean)
1540
1541 (defcustom org-fit-agenda-window t
1542 "Non-nil means, change window size of agenda to fit content."
1543 :group 'org-agenda-setup
1544 :type 'boolean)
1545
1546 (defgroup org-agenda-display nil
1547 "Options concerning what to display initially in Agenda."
1548 :tag "Org Agenda Display"
1549 :group 'org-agenda)
1550
1551 (defcustom org-agenda-show-all-dates t
1552 "Non-nil means, `org-agenda' shows every day in the selected range.
1553 When nil, only the days which actually have entries are shown."
1554 :group 'org-agenda-display
1555 :type 'boolean)
1556
1557 (defcustom org-agenda-start-on-weekday 1
1558 "Non-nil means, start the overview always on the specified weekday.
1559 0 denotes Sunday, 1 denotes Monday etc.
1560 When nil, always start on the current day."
1561 :group 'org-agenda-display
1562 :type '(choice (const :tag "Today" nil)
1563 (number :tag "Weekday No.")))
1564
1565 (defcustom org-agenda-ndays 7
1566 "Number of days to include in overview display.
1567 Should be 1 or 7."
1568 :group 'org-agenda-display
1569 :type 'number)
1570
1571 (defcustom org-agenda-use-time-grid t
1572 "Non-nil means, show a time grid in the agenda schedule.
1573 A time grid is a set of lines for specific times (like every two hours between
1574 8:00 and 20:00). The items scheduled for a day at specific times are
1575 sorted in between these lines.
1576 For details about when the grid will be shown, and what it will look like, see
1577 the variable `org-agenda-time-grid'."
1578 :group 'org-agenda-display
1579 :type 'boolean)
1580
1581 (defcustom org-agenda-time-grid
1582 '((daily today require-timed)
1583 "----------------"
1584 (800 1000 1200 1400 1600 1800 2000))
1585
1586 "The settings for time grid for agenda display.
1587 This is a list of three items. The first item is again a list. It contains
1588 symbols specifying conditions when the grid should be displayed:
1589
1590 daily if the agenda shows a single day
1591 weekly if the agenda shows an entire week
1592 today show grid on current date, independent of daily/weekly display
1593 require-timed show grid only if at least on item has a time specification
1594
1595 The second item is a string which will be places behing the grid time.
1596
1597 The third item is a list of integers, indicating the times that should have
1598 a grid line."
1599 :group 'org-agenda-display
1600 :type
1601 '(list
1602 (set :greedy t :tag "Grid Display Options"
1603 (const :tag "Show grid in single day agenda display" daily)
1604 (const :tag "Show grid in weekly agenda display" weekly)
1605 (const :tag "Always show grid for today" today)
1606 (const :tag "Show grid only if any timed entries are present"
1607 require-timed)
1608 (const :tag "Skip grid times already present in an entry"
1609 remove-match))
1610 (string :tag "Grid String")
1611 (repeat :tag "Grid Times" (integer :tag "Time"))))
1612
1613 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1614 "Sorting structure for the agenda items of a single day.
1615 This is a list of symbols which will be used in sequence to determine
1616 if an entry should be listed before another entry. The following
1617 symbols are recognized:
1618
1619 time-up Put entries with time-of-day indications first, early first
1620 time-down Put entries with time-of-day indications first, late first
1621 category-keep Keep the default order of categories, corresponding to the
1622 sequence in `org-agenda-files'.
1623 category-up Sort alphabetically by category, A-Z.
1624 category-down Sort alphabetically by category, Z-A.
1625 priority-up Sort numerically by priority, high priority last.
1626 priority-down Sort numerically by priority, high priority first.
1627
1628 The different possibilities will be tried in sequence, and testing stops
1629 if one comparison returns a \"not-equal\". For example, the default
1630 '(time-up category-keep priority-down)
1631 means: Pull out all entries having a specified time of day and sort them,
1632 in order to make a time schedule for the current day the first thing in the
1633 agenda listing for the day. Of the entries without a time indication, keep
1634 the grouped in categories, don't sort the categories, but keep them in
1635 the sequence given in `org-agenda-files'. Within each category sort by
1636 priority.
1637
1638 Leaving out `category-keep' would mean that items will be sorted across
1639 categories by priority."
1640 :group 'org-agenda-display
1641 :type '(repeat
1642 (choice
1643 (const time-up)
1644 (const time-down)
1645 (const category-keep)
1646 (const category-up)
1647 (const category-down)
1648 (const priority-up)
1649 (const priority-down))))
1650
1651 (defcustom org-sort-agenda-notime-is-late t
1652 "Non-nil means, items without time are considered late.
1653 This is only relevant for sorting. When t, items which have no explicit
1654 time like 15:30 will be considered as 99:01, i.e. later than any items which
1655 do have a time. When nil, the default time is before 0:00. You can use this
1656 option to decide if the schedule for today should come before or after timeless
1657 agenda entries."
1658 :group 'org-agenda-display
1659 :type 'boolean)
1660
1661
1662 (defgroup org-agenda-prefix nil
1663 "Options concerning the entry prefix in the Org-mode agenda display."
1664 :tag "Org Agenda Prefix"
1665 :group 'org-agenda)
1666
1667 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1668 "Format specification for the prefix of items in the agenda buffer.
1669 This format works similar to a printf format, with the following meaning:
1670
1671 %c the category of the item, \"Diary\" for entries from the diary, or
1672 as given by the CATEGORY keyword or derived from the file name.
1673 %T the first tag of the item.
1674 %t the time-of-day specification if one applies to the entry, in the
1675 format HH:MM
1676 %s Scheduling/Deadline information, a short string
1677
1678 All specifiers work basically like the standard `%s' of printf, but may
1679 contain two additional characters: A question mark just after the `%' and
1680 a whitespace/punctuation character just before the final letter.
1681
1682 If the first character after `%' is a question mark, the entire field
1683 will only be included if the corresponding value applies to the
1684 current entry. This is useful for fields which should have fixed
1685 width when present, but zero width when absent. For example,
1686 \"%?-12t\" will result in a 12 character time field if a time of the
1687 day is specified, but will completely disappear in entries which do
1688 not contain a time.
1689
1690 If there is punctuation or whitespace character just before the final
1691 format letter, this character will be appended to the field value if
1692 the value is not empty. For example, the format \"%-12:c\" leads to
1693 \"Diary: \" if the category is \"Diary\". If the category were be
1694 empty, no additional colon would be interted.
1695
1696 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1697 - Indent the line with two space characters
1698 - Give the category in a 12 chars wide field, padded with whitespace on
1699 the right (because of `-'). Append a colon if there is a category
1700 (because of `:').
1701 - If there is a time-of-day, put it into a 12 chars wide field. If no
1702 time, don't put in an empty field, just skip it (because of '?').
1703 - Finally, put the scheduling information and append a whitespace.
1704
1705 As another example, if you don't want the time-of-day of entries in
1706 the prefix, you could use:
1707
1708 (setq org-agenda-prefix-format \" %-11:c% s\")
1709
1710 See also the variables `org-agenda-remove-times-when-in-prefix' and
1711 `org-agenda-remove-tags-when-in-prefix'."
1712 :type 'string
1713 :group 'org-agenda-prefix)
1714
1715 (defvar org-prefix-format-compiled nil
1716 "The compiled version of the most recently used prefix format.
1717 Depending on which command was used last, this may be the compiled version
1718 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1719
1720 (defcustom org-agenda-remove-times-when-in-prefix t
1721 "Non-nil means, remove duplicate time specifications in agenda items.
1722 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1723 time-of-day specification in a headline or diary entry is extracted and
1724 placed into the prefix. If this option is non-nil, the original specification
1725 \(a timestamp or -range, or just a plain time(range) specification like
1726 11:30-4pm) will be removed for agenda display. This makes the agenda less
1727 cluttered.
1728 The option can be t or nil. It may also be the symbol `beg', indicating
1729 that the time should only be removed what it is located at the beginning of
1730 the headline/diary entry."
1731 :group 'org-agenda-prefix
1732 :type '(choice
1733 (const :tag "Always" t)
1734 (const :tag "Never" nil)
1735 (const :tag "When at beginning of entry" beg)))
1736
1737 (defcustom org-agenda-remove-tags-when-in-prefix nil
1738 "Non-nil means, remove the tags from the headline copy in the agenda.
1739 When this is the symbol `prefix', only remove tags when
1740 `org-agenda-prefix-format' contains a `%T' specifier."
1741 :group 'org-agenda-prefix
1742 :type '(choice
1743 (const :tag "Always" t)
1744 (const :tag "Never" nil)
1745 (const :tag "When prefix format contains %T" prefix)))
1746
1747 (defgroup org-agenda-timeline nil
1748 "Options concerning the timeline buffer in Org Mode."
1749 :tag "Org Agenda Timeline"
1750 :group 'org-agenda)
1751
1752 (defcustom org-timeline-prefix-format " % s"
1753 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1754 :type 'string
1755 :group 'org-agenda-timeline)
1756
1757 (defcustom org-select-timeline-window t
1758 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1759 When nil, cursor will remain in the current window."
1760 :group 'org-agenda-timeline
1761 :type 'boolean)
1762
1763 (defcustom org-timeline-show-empty-dates 3
1764 "Non-nil means, `org-timeline' also shows dates without an entry.
1765 When nil, only the days which actually have entries are shown.
1766 When t, all days between the first and the last date are shown.
1767 When an integer, show also empty dates, but if there is a gap of more than
1768 N days, just insert a special line indicating the size of the gap."
1769 :group 'org-agenda-timeline
1770 :type '(choice
1771 (const :tag "None" nil)
1772 (const :tag "All" t)
1773 (number :tag "at most")))
1774
1775 (defgroup org-latex nil
1776 "Options for embedding LaTeX code into Org-mode"
1777 :tag "Org LaTeX"
1778 :group 'org)
1779
1780 (defcustom org-format-latex-options
1781 '(:foreground "Black" :background "Transparent" :scale 1.0
1782 :matchers ("begin" "$" "$$" "\\(" "\\["))
1783 "Options for creating images from LaTeX fragments.
1784 This is a property list with the following properties:
1785 :foreground the foreground color, for example \"Black\".
1786 :background the background color, or \"Transparent\".
1787 :scale a scaling factor for the size of the images
1788 :matchers a list indicating which matchers should be used to
1789 find LaTeX fragments. Valid members of this list are:
1790 \"begin\" find environments
1791 \"$\" find math expressions surrounded by $...$
1792 \"$$\" find math expressions surrounded by $$....$$
1793 \"\\(\" find math expressions surrounded by \\(...\\)
1794 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1795 :group 'org-latex
1796 :type 'plist)
1797
1798 (defgroup org-export nil
1799 "Options for exporting org-listings."
1800 :tag "Org Export"
1801 :group 'org)
1802
1803 (defgroup org-export-general nil
1804 "General options for exporting Org-mode files."
1805 :tag "Org Export General"
1806 :group 'org-export)
1807
1808 (defcustom org-export-publishing-directory "."
1809 "Path to the location where exported files should be located.
1810 This path may be relative to the directory where the Org-mode file lives.
1811 The default is to put them into the same directory as the Org-mode file.
1812 The variable may also be an alist with export types `:html', `:ascii',
1813 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1814 is relative, it is interpreted relative to the directory where the exported
1815 Org-mode files lives."
1816 :group 'org-export-general
1817 :type '(choice
1818 (directory)
1819 (repeat
1820 (cons
1821 (choice :tag "Type"
1822 (const :html) (const :ascii) (const :ical) (const :xoxo))
1823 (directory)))))
1824
1825 (defcustom org-export-language-setup
1826 '(("en" "Author" "Date" "Table of Contents")
1827 ("da" "Ophavsmand" "Dato" "Indhold")
1828 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1829 ("es" "Autor" "Fecha" "\xccndice")
1830 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1831 ("it" "Autore" "Data" "Indice")
1832 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1833 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1834 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1835 "Terms used in export text, translated to different languages.
1836 Use the variable `org-export-default-language' to set the language,
1837 or use the +OPTION lines for a per-file setting."
1838 :group 'org-export-general
1839 :type '(repeat
1840 (list
1841 (string :tag "HTML language tag")
1842 (string :tag "Author")
1843 (string :tag "Date")
1844 (string :tag "Table of Contents"))))
1845
1846 (defcustom org-export-default-language "en"
1847 "The default language of HTML export, as a string.
1848 This should have an association in `org-export-language-setup'."
1849 :group 'org-export-general
1850 :type 'string)
1851
1852 (defcustom org-export-headline-levels 3
1853 "The last level which is still exported as a headline.
1854 Inferior levels will produce itemize lists when exported.
1855 Note that a numeric prefix argument to an exporter function overrides
1856 this setting.
1857
1858 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1859 :group 'org-export-general
1860 :type 'number)
1861
1862 (defcustom org-export-with-section-numbers t
1863 "Non-nil means, add section numbers to headlines when exporting.
1864
1865 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1866 :group 'org-export-general
1867 :type 'boolean)
1868
1869 (defcustom org-export-with-toc t
1870 "Non-nil means, create a table of contents in exported files.
1871 The TOC contains headlines with levels up to`org-export-headline-levels'.
1872
1873 Headlines which contain any TODO items will be marked with \"(*)\" in
1874 ASCII export, and with red color in HTML output.
1875
1876 In HTML output, the TOC will be clickable.
1877
1878 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1879 :group 'org-export-general
1880 :type 'boolean)
1881
1882 (defcustom org-export-mark-todo-in-toc nil
1883 "Non-nil means, mark TOC lines that contain any open TODO items."
1884 :group 'org-export-general
1885 :type 'boolean)
1886
1887 (defcustom org-export-preserve-breaks nil
1888 "Non-nil means, preserve all line breaks when exporting.
1889 Normally, in HTML output paragraphs will be reformatted. In ASCII
1890 export, line breaks will always be preserved, regardless of this variable.
1891
1892 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1893 :group 'org-export-general
1894 :type 'boolean)
1895
1896 (defcustom org-export-with-archived-trees 'headline
1897 "Whether subtrees with the ARCHIVE tag should be exported.
1898 This can have three different values
1899 nil Do not export, pretend this tree is not present
1900 t Do export the entire tree
1901 headline Only export the headline, but skip the tree below it."
1902 :group 'org-export-general
1903 :group 'org-archive
1904 :type '(choice
1905 (const :tag "not at all" nil)
1906 (const :tag "headline only" 'headline)
1907 (const :tag "entirely" t)))
1908
1909 (defcustom org-export-with-timestamps t
1910 "Nil means, do not export time stamps and associated keywords."
1911 :group 'org-export
1912 :type 'boolean)
1913
1914 (defcustom org-export-remove-timestamps-from-toc t
1915 "Nil means, remove timestamps from the table of contents entries."
1916 :group 'org-export
1917 :type 'boolean)
1918
1919 (defcustom org-export-with-tags t
1920 "Nil means, do not export tags, just remove them from headlines."
1921 :group 'org-export-general
1922 :type 'boolean)
1923
1924 (defcustom org-export-with-timestamps t
1925 "Nil means, do not export timestamps and associated keywords."
1926 :group 'org-export-general
1927 :type 'boolean)
1928
1929 (defgroup org-export-translation nil
1930 "Options for translating special ascii sequences for the export backends."
1931 :tag "Org Export Translation"
1932 :group 'org-export)
1933
1934 (defcustom org-export-with-emphasize t
1935 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1936 If the export target supports emphasizing text, the word will be
1937 typeset in bold, italic, or underlined, respectively. Works only for
1938 single words, but you can say: I *really* *mean* *this*.
1939 Not all export backends support this.
1940
1941 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1942 :group 'org-export-translation
1943 :type 'boolean)
1944
1945 (defcustom org-export-with-sub-superscripts t
1946 "Non-nil means, interpret \"_\" and \"^\" for export.
1947 When this option is turned on, you can use TeX-like syntax for sub- and
1948 superscripts. Several characters after \"_\" or \"^\" will be
1949 considered as a single item - so grouping with {} is normally not
1950 needed. For example, the following things will be parsed as single
1951 sub- or superscripts.
1952
1953 10^24 or 10^tau several digits will be considered 1 item.
1954 10^-12 or 10^-tau a leading sign with digits or a word
1955 x^2-y^3 will be read as x^2 - y^3, because items are
1956 terminated by almost any nonword/nondigit char.
1957 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1958
1959 Still, ambiguity is possible - so when in doubt use {} to enclose the
1960 sub/superscript.
1961 Not all export backends support this, but HTML does.
1962
1963 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1964 :group 'org-export-translation
1965 :type 'boolean)
1966
1967 (defcustom org-export-with-TeX-macros t
1968 "Non-nil means, interpret simple TeX-like macros when exporting.
1969 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1970 No only real TeX macros will work here, but the standard HTML entities
1971 for math can be used as macro names as well. For a list of supported
1972 names in HTML export, see the constant `org-html-entities'.
1973 Not all export backends support this.
1974
1975 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1976 :group 'org-export-translation
1977 :group 'org-latex
1978 :type 'boolean)
1979
1980 (defcustom org-export-with-LaTeX-fragments nil
1981 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
1982 When set, the exporter will find LaTeX environments if the \\begin line is
1983 the first non-white thing on a line. It will also find the math delimiters
1984 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
1985 display math.
1986
1987 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
1988 :group 'org-export-translation
1989 :group 'org-latex
1990 :type 'boolean)
1991
1992 (defcustom org-export-with-fixed-width t
1993 "Non-nil means, lines starting with \":\" will be in fixed width font.
1994 This can be used to have pre-formatted text, fragments of code etc. For
1995 example:
1996 : ;; Some Lisp examples
1997 : (while (defc cnt)
1998 : (ding))
1999 will be looking just like this in also HTML. See also the QUOTE keyword.
2000 Not all export backends support this.
2001
2002 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2003 :group 'org-export-translation
2004 :type 'boolean)
2005
2006 (defcustom org-match-sexp-depth 3
2007 "Number of stacked braces for sub/superscript matching.
2008 This has to be set before loading org.el to be effective."
2009 :group 'org-export-translation
2010 :type 'integer)
2011
2012 (defgroup org-export-tables nil
2013 "Options for exporting tables in Org-mode."
2014 :tag "Org Export Tables"
2015 :group 'org-export)
2016
2017 (defcustom org-export-with-tables t
2018 "If non-nil, lines starting with \"|\" define a table.
2019 For example:
2020
2021 | Name | Address | Birthday |
2022 |-------------+----------+-----------|
2023 | Arthur Dent | England | 29.2.2100 |
2024
2025 Not all export backends support this.
2026
2027 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2028 :group 'org-export-tables
2029 :type 'boolean)
2030
2031 (defcustom org-export-highlight-first-table-line t
2032 "Non-nil means, highlight the first table line.
2033 In HTML export, this means use <th> instead of <td>.
2034 In tables created with table.el, this applies to the first table line.
2035 In Org-mode tables, all lines before the first horizontal separator
2036 line will be formatted with <th> tags."
2037 :group 'org-export-tables
2038 :type 'boolean)
2039
2040 (defcustom org-export-table-remove-special-lines t
2041 "Remove special lines and marking characters in calculating tables.
2042 This removes the special marking character column from tables that are set
2043 up for spreadsheet calculations. It also removes the entire lines
2044 marked with `!', `_', or `^'. The lines with `$' are kept, because
2045 the values of constants may be useful to have."
2046 :group 'org-export-tables
2047 :type 'boolean)
2048
2049 (defcustom org-export-prefer-native-exporter-for-tables nil
2050 "Non-nil means, always export tables created with table.el natively.
2051 Natively means, use the HTML code generator in table.el.
2052 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2053 the table does not use row- or column-spanning). This has the
2054 advantage, that the automatic HTML conversions for math symbols and
2055 sub/superscripts can be applied. Org-mode's HTML generator is also
2056 much faster."
2057 :group 'org-export-tables
2058 :type 'boolean)
2059
2060 (defgroup org-export-ascii nil
2061 "Options specific for ASCII export of Org-mode files."
2062 :tag "Org Export ASCII"
2063 :group 'org-export)
2064
2065 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2066 "Characters for underlining headings in ASCII export.
2067 In the given sequence, these characters will be used for level 1, 2, ..."
2068 :group 'org-export-ascii
2069 :type '(repeat character))
2070
2071 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2072 "Bullet characters for headlines converted to lists in ASCII export.
2073 The first character is is used for the first lest level generated in this
2074 way, and so on. If there are more levels than characters given here,
2075 the list will be repeated.
2076 Note that plain lists will keep the same bullets as the have in the
2077 Org-mode file."
2078 :group 'org-export-ascii
2079 :type '(repeat character))
2080
2081 (defcustom org-export-ascii-show-new-buffer t
2082 "Non-nil means, popup buffer containing the exported ASCII text.
2083 Otherwise the buffer will just be saved to a file and stay hidden."
2084 :group 'org-export-ascii
2085 :type 'boolean)
2086
2087 (defgroup org-export-xml nil
2088 "Options specific for XML export of Org-mode files."
2089 :tag "Org Export XML"
2090 :group 'org-export)
2091
2092 (defgroup org-export-html nil
2093 "Options specific for HTML export of Org-mode files."
2094 :tag "Org Export HTML"
2095 :group 'org-export)
2096
2097 (defcustom org-export-html-style
2098 "<style type=\"text/css\">
2099 html {
2100 font-family: Times, serif;
2101 font-size: 12pt;
2102 }
2103 .title { text-align: center; }
2104 .todo { color: red; }
2105 .done { color: green; }
2106 .timestamp { color: grey }
2107 .timestamp-kwd { color: CadetBlue }
2108 .tag { background-color:lightblue; font-weight:normal }
2109 .target { background-color: lavender; }
2110 pre {
2111 border: 1pt solid #AEBDCC;
2112 background-color: #F3F5F7;
2113 padding: 5pt;
2114 font-family: courier, monospace;
2115 }
2116 table { border-collapse: collapse; }
2117 td, th {
2118 vertical-align: top;
2119 border: 1pt solid #ADB9CC;
2120 }
2121 </style>"
2122 "The default style specification for exported HTML files.
2123 Since there are different ways of setting style information, this variable
2124 needs to contain the full HTML structure to provide a style, including the
2125 surrounding HTML tags. The style specifications should include definitions
2126 for new classes todo, done, title, and deadline. For example, legal values
2127 would be:
2128
2129 <style type=\"text/css\">
2130 p { font-weight: normal; color: gray; }
2131 h1 { color: black; }
2132 .title { text-align: center; }
2133 .todo, .deadline { color: red; }
2134 .done { color: green; }
2135 </style>
2136
2137 or, if you want to keep the style in a file,
2138
2139 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2140
2141 As the value of this option simply gets inserted into the HTML <head> header,
2142 you can \"misuse\" it to add arbitrary text to the header."
2143 :group 'org-export-html
2144 :type 'string)
2145
2146 (defcustom org-export-html-link-org-files-as-html t
2147 "Non-nil means, make file links to `file.org' point to `file.html'.
2148 When org-mode is exporting an org-mode file to HTML, links to
2149 non-html files are directly put into a href tag in HTML.
2150 However, links to other Org-mode files (recognized by the
2151 extension `.org.) should become links to the corresponding html
2152 file, assuming that the linked org-mode file will also be
2153 converted to HTML.
2154 When nil, the links still point to the plain `.org' file."
2155 :group 'org-export-html
2156 :type 'boolean)
2157
2158 (defcustom org-export-html-inline-images 'maybe
2159 "Non-nil means, inline images into exported HTML pages.
2160 This is done using an <img> tag. When nil, an anchor with href is used to
2161 link to the image. If this option is `maybe', then images in links with
2162 an empty description will be inlined, while images with a description will
2163 be linked only."
2164 :group 'org-export-html
2165 :type '(choice (const :tag "Never" nil)
2166 (const :tag "Always" t)
2167 (const :tag "When there is no description" maybe)))
2168
2169 (defcustom org-export-html-expand t
2170 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2171 When nil, these tags will be exported as plain text and therefore
2172 not be interpreted by a browser.
2173
2174 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2175 :group 'org-export-html
2176 :type 'boolean)
2177
2178 (defcustom org-export-html-table-tag
2179 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2180 "The HTML tag used to start a table.
2181 This must be a <table> tag, but you may change the options like
2182 borders and spacing."
2183 :group 'org-export-html
2184 :type 'string)
2185
2186 (defcustom org-export-html-with-timestamp nil
2187 "If non-nil, write `org-export-html-html-helper-timestamp'
2188 into the exported HTML text. Otherwise, the buffer will just be saved
2189 to a file."
2190 :group 'org-export-html
2191 :type 'boolean)
2192
2193 (defcustom org-export-html-html-helper-timestamp
2194 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2195 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2196 :group 'org-export-html
2197 :type 'string)
2198
2199 (defcustom org-export-html-show-new-buffer nil
2200 "Non-nil means, popup buffer containing the exported html text.
2201 Otherwise, the buffer will just be saved to a file and stay hidden."
2202 :group 'org-export-html
2203 :type 'boolean)
2204
2205 (defgroup org-export-icalendar nil
2206 "Options specific for iCalendar export of Org-mode files."
2207 :tag "Org Export iCalendar"
2208 :group 'org-export)
2209
2210 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2211 "The file name for the iCalendar file covering all agenda files.
2212 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2213 The file name should be absolute."
2214 :group 'org-export-icalendar
2215 :type 'file)
2216
2217 (defcustom org-icalendar-include-todo nil
2218 "Non-nil means, export to iCalendar files should also cover TODO items."
2219 :group 'org-export-icalendar
2220 :type 'boolean)
2221
2222 (defcustom org-icalendar-combined-name "OrgMode"
2223 "Calendar name for the combined iCalendar representing all agenda files."
2224 :group 'org-export-icalendar
2225 :type 'string)
2226
2227 (defgroup org-font-lock nil
2228 "Font-lock settings for highlighting in Org-mode."
2229 :tag "Org Font Lock"
2230 :group 'org)
2231
2232 (defcustom org-level-color-stars-only nil
2233 "Non-nil means fontify only the stars in each headline.
2234 When nil, the entire headline is fontified.
2235 Changing it requires restart of `font-lock-mode' to become effective
2236 also in regions already fontified."
2237 :group 'org-font-lock
2238 :type 'boolean)
2239
2240 (defcustom org-hide-leading-stars nil
2241 "Non-nil means, hide the first N-1 stars in a headline.
2242 This works by using the face `org-hide' for these stars. This
2243 face is white for a light background, and black for a dark
2244 background. You may have to customize the face `org-hide' to
2245 make this work.
2246 Changing it requires restart of `font-lock-mode' to become effective
2247 also in regions already fontified.
2248 You may also set this on a per-file basis by adding one of the following
2249 lines to the buffer:
2250
2251 #+STARTUP: hidestars
2252 #+STARTUP: showstars"
2253 :group 'org-font-lock
2254 :type 'boolean)
2255
2256 (defcustom org-fontify-done-headline nil
2257 "Non-nil means, change the face of a headline if it is marked DONE.
2258 Normally, only the TODO/DONE keyword indicates the state of a headline.
2259 When this is non-nil, the headline after the keyword is set to the
2260 `org-headline-done' as an additional indication."
2261 :group 'org-font-lock
2262 :type 'boolean)
2263
2264 (defcustom org-fontify-emphasized-text t
2265 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2266 Changing this variable requires a restart of Emacs to take effect."
2267 :group 'org-font-lock
2268 :type 'boolean)
2269
2270 (defvar org-emph-re nil
2271 "Regular expression for matching emphasis.")
2272 (defvar org-emphasis-regexp-components) ; defined just below
2273 (defvar org-emphasis-alist) ; defined just below
2274 (defun org-set-emph-re (var val)
2275 "Set variable and compute the emphasis regular expression."
2276 (set var val)
2277 (when (and (boundp 'org-emphasis-alist)
2278 (boundp 'org-emphasis-regexp-components)
2279 org-emphasis-alist org-emphasis-regexp-components)
2280 (let* ((e org-emphasis-regexp-components)
2281 (pre (car e))
2282 (post (nth 1 e))
2283 (border (nth 2 e))
2284 (body (nth 3 e))
2285 (nl (nth 4 e))
2286 (stacked (nth 5 e))
2287 (body1 (concat body "*?"))
2288 (markers (mapconcat 'car org-emphasis-alist "")))
2289 ;; make sure special characters appear at the right position in the class
2290 (if (string-match "\\^" markers)
2291 (setq markers (concat (replace-match "" t t markers) "^")))
2292 (if (string-match "-" markers)
2293 (setq markers (concat (replace-match "" t t markers) "-")))
2294 (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2295 ;; Make the regexp
2296 (setq org-emph-re
2297 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2298 "\\("
2299 "\\([" markers "]\\)"
2300 "\\("
2301 "[^" border markers "]"
2302 body1
2303 "[^" border markers "]"
2304 "\\)"
2305 "\\3\\)"
2306 "\\([" post (if stacked markers) "]\\|$\\)")))))
2307
2308 (defcustom org-emphasis-regexp-components
2309 '(" \t(" " \t.,?;:'\")" " \t\r\n,." "." 1 nil)
2310 "Components used to build the reqular expression for emphasis.
2311 This is a list with 6 entries. Terminology: In an emphasis string
2312 like \" *strong word* \", we call the initial space PREMATCH, the final
2313 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2314 and \"trong wor\" is the body. The different components in this variable
2315 specify what is allowed/forbidden in each part:
2316
2317 pre Chars allowed as prematch. Beginning of line will be allowed too.
2318 post Chars allowed as postmatch. End of line will be allowed too.
2319 border The chars *forbidden* as border characters. In addition to the
2320 characters given here, all marker characters are forbidden too.
2321 body-regexp A regexp like \".\" to match a body character. Don't use
2322 non-shy groups here, and don't allow newline here.
2323 newline The maximum number of newlines allowed in an emphasis exp.
2324 stacked Non-nil means, allow stacked styles. This works only in HTML
2325 export. When this is set, all marker characters (as given in
2326 `org-emphasis-alist') will be allowed as pre/post, aiding
2327 inside-out matching.
2328 Use customize to modify this, or restart emacs after changing it."
2329 :group 'org-font-lock
2330 :set 'org-set-emph-re
2331 :type '(list
2332 (sexp :tag "Allowed chars in pre ")
2333 (sexp :tag "Allowed chars in post ")
2334 (sexp :tag "Forbidden chars in border ")
2335 (sexp :tag "Regexp for body ")
2336 (integer :tag "number of newlines allowed")
2337 (boolean :tag "Stacking allowed ")))
2338
2339 (defcustom org-emphasis-alist
2340 '(("*" bold "<b>" "</b>")
2341 ("/" italic "<i>" "</i>")
2342 ("_" underline "<u>" "</u>")
2343 ("=" shadow "<code>" "</code>")
2344 ("+" (:strike-through t) "<del>" "</del>")
2345 )
2346 "Special syntax for emphasised text.
2347 Text starting and ending with a special character will be emphasized, for
2348 example *bold*, _underlined_ and /italic/. This variable sets the marker
2349 characters, the face to bbe used by font-lock for highlighting in Org-mode
2350 emacs buffers, and the HTML tags to be used for this.
2351 Use customize to modify this, or restart emacs after changing it."
2352 :group 'org-font-lock
2353 :set 'org-set-emph-re
2354 :type '(repeat
2355 (list
2356 (string :tag "Marker character")
2357 (choice
2358 (face :tag "Font-lock-face")
2359 (plist :tag "Face property list"))
2360 (string :tag "HTML start tag")
2361 (string :tag "HTML end tag"))))
2362
2363 (defgroup org-faces nil
2364 "Faces in Org-mode."
2365 :tag "Org Faces"
2366 :group 'org-font-lock)
2367
2368 (defun org-compatible-face (specs)
2369 "Make a compatible face specification.
2370 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2371 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2372 to the top of the list. The `min-colors' attribute will be removed from
2373 any other entries, and any resulting duplicates will be removed entirely."
2374 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2375 (let (r e a)
2376 (while (setq e (pop specs))
2377 (cond
2378 ((memq (car e) '(t default)) (push e r))
2379 ((setq a (member '(min-colors 8) (car e)))
2380 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2381 (cdr e)))))
2382 ((setq a (assq 'min-colors (car e)))
2383 (setq e (cons (delq a (car e)) (cdr e)))
2384 (or (assoc (car e) r) (push e r)))
2385 (t (or (assoc (car e) r) (push e r)))))
2386 (nreverse r))
2387 specs))
2388
2389 (defface org-hide
2390 '((((background light)) (:foreground "white"))
2391 (((background dark)) (:foreground "black")))
2392 "Face used to hide leading stars in headlines.
2393 The forground color of this face should be equal to the background
2394 color of the frame."
2395 :group 'org-faces)
2396
2397 (defface org-level-1 ;; font-lock-function-name-face
2398 (org-compatible-face
2399 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2400 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2401 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2402 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2403 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2404 (t (:bold t))))
2405 "Face used for level 1 headlines."
2406 :group 'org-faces)
2407
2408 (defface org-level-2 ;; font-lock-variable-name-face
2409 (org-compatible-face
2410 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2411 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2412 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2413 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2414 (t (:bold t))))
2415 "Face used for level 2 headlines."
2416 :group 'org-faces)
2417
2418 (defface org-level-3 ;; font-lock-keyword-face
2419 (org-compatible-face
2420 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2421 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2422 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2423 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2424 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2425 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2426 (t (:bold t))))
2427 "Face used for level 3 headlines."
2428 :group 'org-faces)
2429
2430 (defface org-level-4 ;; font-lock-comment-face
2431 (org-compatible-face
2432 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2433 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2434 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2435 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2436 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2437 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2438 (t (:bold t))))
2439 "Face used for level 4 headlines."
2440 :group 'org-faces)
2441
2442 (defface org-level-5 ;; font-lock-type-face
2443 (org-compatible-face
2444 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2445 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2446 (((class color) (min-colors 8)) (:foreground "green"))))
2447 "Face used for level 5 headlines."
2448 :group 'org-faces)
2449
2450 (defface org-level-6 ;; font-lock-constant-face
2451 (org-compatible-face
2452 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2453 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2454 (((class color) (min-colors 8)) (:foreground "magenta"))))
2455 "Face used for level 6 headlines."
2456 :group 'org-faces)
2457
2458 (defface org-level-7 ;; font-lock-builtin-face
2459 (org-compatible-face
2460 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2461 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2462 (((class color) (min-colors 8)) (:foreground "blue"))))
2463 "Face used for level 7 headlines."
2464 :group 'org-faces)
2465
2466 (defface org-level-8 ;; font-lock-string-face
2467 (org-compatible-face
2468 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2469 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2470 (((class color) (min-colors 8)) (:foreground "green"))))
2471 "Face used for level 8 headlines."
2472 :group 'org-faces)
2473
2474 (defface org-special-keyword ;; font-lock-string-face
2475 (org-compatible-face
2476 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2477 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2478 (t (:italic t))))
2479 "Face used for special keywords."
2480 :group 'org-faces)
2481
2482 (defface org-warning ;; font-lock-warning-face
2483 (org-compatible-face
2484 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2485 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2486 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2487 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2488 (t (:bold t))))
2489 "Face for deadlines and TODO keywords."
2490 :group 'org-faces)
2491
2492 (defface org-headline-done ;; font-lock-string-face
2493 (org-compatible-face
2494 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2495 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2496 (((class color) (min-colors 8) (background light)) (:bold nil))))
2497 "Face used to indicate that a headline is DONE.
2498 This face is only used if `org-fontify-done-headline' is set."
2499 :group 'org-faces)
2500
2501 (defface org-archived ; similar to shadow
2502 (org-compatible-face
2503 '((((class color grayscale) (min-colors 88) (background light))
2504 (:foreground "grey50"))
2505 (((class color grayscale) (min-colors 88) (background dark))
2506 (:foreground "grey70"))
2507 (((class color) (min-colors 8) (background light))
2508 (:foreground "green"))
2509 (((class color) (min-colors 8) (background dark))
2510 (:foreground "yellow"))))
2511 "Face for headline with the ARCHIVE tag."
2512 :group 'org-faces)
2513
2514 (defface org-link
2515 '((((class color) (background light)) (:foreground "Purple" :underline t))
2516 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2517 (t (:underline t)))
2518 "Face for links."
2519 :group 'org-faces)
2520
2521 (defface org-date
2522 '((((class color) (background light)) (:foreground "Purple" :underline t))
2523 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2524 (t (:underline t)))
2525 "Face for links."
2526 :group 'org-faces)
2527
2528 (defface org-tag
2529 '((t (:bold t)))
2530 "Face for tags."
2531 :group 'org-faces)
2532
2533 (defface org-todo ;; font-lock-warning-face
2534 (org-compatible-face
2535 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2536 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2537 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2538 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2539 (t (:inverse-video t :bold t))))
2540 "Face for TODO keywords."
2541 :group 'org-faces)
2542
2543 (defface org-done ;; font-lock-type-face
2544 (org-compatible-face
2545 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2546 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2547 (((class color) (min-colors 8)) (:foreground "green"))
2548 (t (:bold t))))
2549 "Face used for DONE."
2550 :group 'org-faces)
2551
2552 (defface org-table ;; font-lock-function-name-face
2553 (org-compatible-face
2554 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2555 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2556 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2557 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2558 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2559 (((class color) (min-colors 8) (background dark)))))
2560 "Face used for tables."
2561 :group 'org-faces)
2562
2563 (defface org-formula
2564 (org-compatible-face
2565 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2566 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2567 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2568 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2569 (t (:bold t :italic t))))
2570 "Face for formulas."
2571 :group 'org-faces)
2572
2573 (defface org-scheduled-today
2574 (org-compatible-face
2575 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2576 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2577 (((class color) (min-colors 8)) (:foreground "green"))
2578 (t (:bold t :italic t))))
2579 "Face for items scheduled for a certain day."
2580 :group 'org-faces)
2581
2582 (defface org-scheduled-previously
2583 (org-compatible-face
2584 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2585 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2586 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2587 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2588 (t (:bold t))))
2589 "Face for items scheduled previously, and not yet done."
2590 :group 'org-faces)
2591
2592 (defface org-upcoming-deadline
2593 (org-compatible-face
2594 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2595 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2596 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2597 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2598 (t (:bold t))))
2599 "Face for items scheduled previously, and not yet done."
2600 :group 'org-faces)
2601
2602 (defface org-time-grid ;; font-lock-variable-name-face
2603 (org-compatible-face
2604 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2605 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2606 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2607 "Face used for time grids."
2608 :group 'org-faces)
2609
2610 (defconst org-level-faces
2611 '(org-level-1 org-level-2 org-level-3 org-level-4
2612 org-level-5 org-level-6 org-level-7 org-level-8
2613 ))
2614 (defconst org-n-levels (length org-level-faces))
2615
2616
2617 ;; Variables for pre-computed regular expressions, all buffer local
2618 (defvar org-done-string nil
2619 "The last string in `org-todo-keywords', indicating an item is DONE.")
2620 (make-variable-buffer-local 'org-done-string)
2621 (defvar org-todo-regexp nil
2622 "Matches any of the TODO state keywords.")
2623 (make-variable-buffer-local 'org-todo-regexp)
2624 (defvar org-not-done-regexp nil
2625 "Matches any of the TODO state keywords except the last one.")
2626 (make-variable-buffer-local 'org-not-done-regexp)
2627 (defvar org-todo-line-regexp nil
2628 "Matches a headline and puts TODO state into group 2 if present.")
2629 (make-variable-buffer-local 'org-todo-line-regexp)
2630 (defvar org-todo-line-tags-regexp nil
2631 "Matches a headline and puts TODO state into group 2 if present.
2632 Also put tags into group 4 if tags are present.")
2633 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2634 (defvar org-nl-done-regexp nil
2635 "Matches newline followed by a headline with the DONE keyword.")
2636 (make-variable-buffer-local 'org-nl-done-regexp)
2637 (defvar org-looking-at-done-regexp nil
2638 "Matches the DONE keyword a point.")
2639 (make-variable-buffer-local 'org-looking-at-done-regexp)
2640 (defvar org-todo-kwd-priority-p nil
2641 "Do TODO items have priorities?")
2642 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2643 (defvar org-todo-kwd-max-priority nil
2644 "Maximum priority of TODO items.")
2645 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2646 (defvar org-ds-keyword-length 12
2647 "Maximum length of the Deadline and SCHEDULED keywords.")
2648 (make-variable-buffer-local 'org-ds-keyword-length)
2649 (defvar org-deadline-regexp nil
2650 "Matches the DEADLINE keyword.")
2651 (make-variable-buffer-local 'org-deadline-regexp)
2652 (defvar org-deadline-time-regexp nil
2653 "Matches the DEADLINE keyword together with a time stamp.")
2654 (make-variable-buffer-local 'org-deadline-time-regexp)
2655 (defvar org-deadline-line-regexp nil
2656 "Matches the DEADLINE keyword and the rest of the line.")
2657 (make-variable-buffer-local 'org-deadline-line-regexp)
2658 (defvar org-scheduled-regexp nil
2659 "Matches the SCHEDULED keyword.")
2660 (make-variable-buffer-local 'org-scheduled-regexp)
2661 (defvar org-scheduled-time-regexp nil
2662 "Matches the SCHEDULED keyword together with a time stamp.")
2663 (make-variable-buffer-local 'org-scheduled-time-regexp)
2664 (defvar org-closed-time-regexp nil
2665 "Matches the CLOSED keyword together with a time stamp.")
2666 (make-variable-buffer-local 'org-closed-time-regexp)
2667
2668 (defvar org-keyword-time-regexp nil
2669 "Matches any of the 3 keywords, together with the time stamp.")
2670 (make-variable-buffer-local 'org-keyword-time-regexp)
2671 (defvar org-maybe-keyword-time-regexp nil
2672 "Matches a timestamp, possibly preceeded by a keyword.")
2673 (make-variable-buffer-local 'org-keyword-time-regexp)
2674
2675 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2676 mouse-map t)
2677 "Properties to remove when a string without properties is wanted.")
2678
2679 (defsubst org-match-string-no-properties (num &optional string)
2680 (if (featurep 'xemacs)
2681 (let ((s (match-string num string)))
2682 (remove-text-properties 0 (length s) org-rm-props s)
2683 s)
2684 (match-string-no-properties num string)))
2685
2686 (defsubst org-no-properties (s)
2687 (remove-text-properties 0 (length s) org-rm-props s)
2688 s)
2689
2690 (defun org-set-regexps-and-options ()
2691 "Precompute regular expressions for current buffer."
2692 (when (eq major-mode 'org-mode)
2693 (let ((re (org-make-options-regexp
2694 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2695 "STARTUP" "ARCHIVE" "TAGS")))
2696 (splitre "[ \t]+")
2697 kwds int key value cat arch tags)
2698 (save-excursion
2699 (save-restriction
2700 (widen)
2701 (goto-char (point-min))
2702 (while (re-search-forward re nil t)
2703 (setq key (match-string 1) value (org-match-string-no-properties 2))
2704 (cond
2705 ((equal key "CATEGORY")
2706 (if (string-match "[ \t]+$" value)
2707 (setq value (replace-match "" t t value)))
2708 (setq cat (intern value)))
2709 ((equal key "SEQ_TODO")
2710 (setq int 'sequence
2711 kwds (append kwds (org-split-string value splitre))))
2712 ((equal key "PRI_TODO")
2713 (setq int 'priority
2714 kwds (append kwds (org-split-string value splitre))))
2715 ((equal key "TYP_TODO")
2716 (setq int 'type
2717 kwds (append kwds (org-split-string value splitre))))
2718 ((equal key "TAGS")
2719 (setq tags (append tags (org-split-string value splitre))))
2720 ((equal key "STARTUP")
2721 (let ((opts (org-split-string value splitre))
2722 (set '(("fold" org-startup-folded t)
2723 ("overview" org-startup-folded t)
2724 ("nofold" org-startup-folded nil)
2725 ("showall" org-startup-folded nil)
2726 ("content" org-startup-folded content)
2727 ("hidestars" org-hide-leading-stars t)
2728 ("showstars" org-hide-leading-stars nil)
2729 ("odd" org-odd-levels-only t)
2730 ("oddeven" org-odd-levels-only nil)
2731 ("align" org-startup-align-all-tables t)
2732 ("noalign" org-startup-align-all-tables nil)
2733 ("logging" org-log-done t)
2734 ("nologging" org-log-done nil)
2735 ("dlcheck" org-startup-with-deadline-check t)
2736 ("nodlcheck" org-startup-with-deadline-check nil)))
2737 l var val)
2738 (while (setq l (assoc (pop opts) set))
2739 (setq var (nth 1 l) val (nth 2 l))
2740 (set (make-local-variable var) val))))
2741 ((equal key "ARCHIVE")
2742 (string-match " *$" value)
2743 (setq arch (replace-match "" t t value))
2744 (remove-text-properties 0 (length arch)
2745 '(face t fontified t) arch)))
2746 )))
2747 (and cat (set (make-local-variable 'org-category) cat))
2748 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2749 (and arch (set (make-local-variable 'org-archive-location) arch))
2750 (and int (set (make-local-variable 'org-todo-interpretation) int))
2751 (when tags
2752 (let (e tgs)
2753 (while (setq e (pop tags))
2754 (cond
2755 ((equal e "{") (push '(:startgroup) tgs))
2756 ((equal e "}") (push '(:endgroup) tgs))
2757 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2758 (push (cons (match-string 1 e)
2759 (string-to-char (match-string 2 e)))
2760 tgs))
2761 (t (push (list e) tgs))))
2762 (set (make-local-variable 'org-tag-alist) nil)
2763 (while (setq e (pop tgs))
2764 (or (and (stringp (car e))
2765 (assoc (car e) org-tag-alist))
2766 (push e org-tag-alist))))))
2767
2768 ;; Compute the regular expressions and other local variables
2769 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2770 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2771 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2772 (length org-scheduled-string)))
2773 org-done-string
2774 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2775 org-todo-regexp
2776 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2777 "\\|") "\\)\\>")
2778 org-not-done-regexp
2779 (concat "\\<\\("
2780 (mapconcat 'regexp-quote
2781 (nreverse (cdr (reverse org-todo-keywords)))
2782 "\\|")
2783 "\\)\\>")
2784 org-todo-line-regexp
2785 (concat "^\\(\\*+\\)[ \t]*\\("
2786 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2787 "\\)? *\\(.*\\)")
2788 org-nl-done-regexp
2789 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2790 org-todo-line-tags-regexp
2791 (concat "^\\(\\*+\\)[ \t]*\\("
2792 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2793 "\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
2794 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2795 org-deadline-regexp (concat "\\<" org-deadline-string)
2796 org-deadline-time-regexp
2797 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2798 org-deadline-line-regexp
2799 (concat "\\<\\(" org-deadline-string "\\).*")
2800 org-scheduled-regexp
2801 (concat "\\<" org-scheduled-string)
2802 org-scheduled-time-regexp
2803 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2804 org-closed-time-regexp
2805 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2806 org-keyword-time-regexp
2807 (concat "\\<\\(" org-scheduled-string
2808 "\\|" org-deadline-string
2809 "\\|" org-closed-string
2810 "\\|" org-clock-string "\\)"
2811 " *[[<]\\([^]>]+\\)[]>]")
2812 org-maybe-keyword-time-regexp
2813 (concat "\\(\\<\\(" org-scheduled-string
2814 "\\|" org-deadline-string
2815 "\\|" org-closed-string
2816 "\\|" org-clock-string "\\)\\)?"
2817 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
2818
2819 (org-set-font-lock-defaults)))
2820
2821 ;; Tell the compiler about dynamically scoped variables,
2822 ;; and variables from other packages
2823 (defvar calc-embedded-close-formula) ; defined by the calc package
2824 (defvar calc-embedded-open-formula) ; defined by the calc package
2825 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
2826 (defvar zmacs-regions) ; XEmacs regions
2827 (defvar original-date) ; dynamically scoped in calendar
2828 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2829 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2830 (defvar org-html-entities) ; defined later in this file
2831 (defvar org-goto-start-pos) ; dynamically scoped parameter
2832 (defvar org-time-was-given) ; dynamically scoped parameter
2833 (defvar org-ts-what) ; dynamically scoped parameter
2834 (defvar org-current-export-file) ; dynamically scoped parameter
2835 (defvar org-current-export-dir) ; dynamically scoped parameter
2836 (defvar mark-active) ; Emacs only, not available in XEmacs.
2837 (defvar timecnt) ; dynamically scoped parameter
2838 (defvar levels-open) ; dynamically scoped parameter
2839 (defvar entry) ; dynamically scoped parameter
2840 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
2841 (defvar date) ; dynamically scoped parameter
2842 (defvar description) ; dynamically scoped parameter
2843 (defvar ans1) ; dynamically scoped parameter
2844 (defvar ans2) ; dynamically scoped parameter
2845 (defvar starting-day) ; local variable
2846 (defvar include-all-loc) ; local variable
2847 (defvar vm-message-pointer) ; from vm
2848 (defvar vm-folder-directory) ; from vm
2849 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2850 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2851 (defvar gnus-group-name) ; from gnus
2852 (defvar gnus-article-current) ; from gnus
2853 (defvar w3m-current-url) ; from w3m
2854 (defvar w3m-current-title) ; from w3m
2855 (defvar mh-progs) ; from MH-E
2856 (defvar mh-current-folder) ; from MH-E
2857 (defvar mh-show-folder-buffer) ; from MH-E
2858 (defvar mh-index-folder) ; from MH-E
2859 (defvar mh-searcher) ; from MH-E
2860 (defvar org-selected-point) ; dynamically scoped parameter
2861 (defvar calendar-mode-map) ; from calendar.el
2862 (defvar last-arg) ; local variable
2863 (defvar remember-save-after-remembering) ; from remember.el
2864 (defvar remember-data-file) ; from remember.el
2865 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2866 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2867 (defvar orgtbl-mode) ; defined later in this file
2868 (defvar Info-current-file) ; from info.el
2869 (defvar Info-current-node) ; from info.el
2870 (defvar texmathp-why) ; from texmathp.el
2871 (defvar org-latex-regexps)
2872
2873 ;;; Define the mode
2874
2875 (defvar org-mode-map
2876 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2877 (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.")
2878 (copy-keymap outline-mode-map))
2879 "Keymap for Org-mode.")
2880
2881 (defvar org-struct-menu) ; defined later in this file
2882 (defvar org-org-menu) ; defined later in this file
2883 (defvar org-tbl-menu) ; defined later in this file
2884
2885 ;; We use a before-change function to check if a table might need
2886 ;; an update.
2887 (defvar org-table-may-need-update t
2888 "Indicates that a table might need an update.
2889 This variable is set by `org-before-change-function'.
2890 `org-table-align' sets it back to nil.")
2891 (defvar org-mode-hook nil)
2892 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2893 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2894
2895
2896 ;;;###autoload
2897 (define-derived-mode org-mode outline-mode "Org"
2898 "Outline-based notes management and organizer, alias
2899 \"Carsten's outline-mode for keeping track of everything.\"
2900
2901 Org-mode develops organizational tasks around a NOTES file which
2902 contains information about projects as plain text. Org-mode is
2903 implemented on top of outline-mode, which is ideal to keep the content
2904 of large files well structured. It supports ToDo items, deadlines and
2905 time stamps, which magically appear in the diary listing of the Emacs
2906 calendar. Tables are easily created with a built-in table editor.
2907 Plain text URL-like links connect to websites, emails (VM), Usenet
2908 messages (Gnus), BBDB entries, and any files related to the project.
2909 For printing and sharing of notes, an Org-mode file (or a part of it)
2910 can be exported as a structured ASCII or HTML file.
2911
2912 The following commands are available:
2913
2914 \\{org-mode-map}"
2915
2916 ;; Get rid of Outline menus, they are not needed
2917 ;; Need to do this here because define-derived-mode sets up
2918 ;; the keymap so late.
2919 (if (featurep 'xemacs)
2920 (if org-noutline-p
2921 (progn
2922 (easy-menu-remove outline-mode-menu-heading)
2923 (easy-menu-remove outline-mode-menu-show)
2924 (easy-menu-remove outline-mode-menu-hide))
2925 (delete-menu-item '("Headings"))
2926 (delete-menu-item '("Show"))
2927 (delete-menu-item '("Hide"))
2928 (set-menubar-dirty-flag))
2929 (define-key org-mode-map [menu-bar headings] 'undefined)
2930 (define-key org-mode-map [menu-bar hide] 'undefined)
2931 (define-key org-mode-map [menu-bar show] 'undefined))
2932
2933 (easy-menu-add org-org-menu)
2934 (easy-menu-add org-tbl-menu)
2935 (org-install-agenda-files-menu)
2936 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2937 (org-add-to-invisibility-spec '(org-cwidth))
2938 (when (featurep 'xemacs)
2939 (set (make-local-variable 'line-move-ignore-invisible) t))
2940 (setq outline-regexp "\\*+")
2941 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2942 (setq outline-level 'org-outline-level)
2943 (when (and org-ellipsis (stringp org-ellipsis))
2944 (unless org-display-table
2945 (setq org-display-table (make-display-table)))
2946 (set-display-table-slot org-display-table
2947 4 (string-to-vector org-ellipsis))
2948 (setq buffer-display-table org-display-table))
2949 (org-set-regexps-and-options)
2950 (modify-syntax-entry ?# "<")
2951 (if org-startup-truncated (setq truncate-lines t))
2952 (set (make-local-variable 'font-lock-unfontify-region-function)
2953 'org-unfontify-region)
2954 ;; Activate before-change-function
2955 (set (make-local-variable 'org-table-may-need-update) t)
2956 (org-add-hook 'before-change-functions 'org-before-change-function nil
2957 'local)
2958 ;; Check for running clock before killing a buffer
2959 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
2960 ;; Paragraphs and auto-filling
2961 (org-set-autofill-regexps)
2962 (org-update-radio-target-regexp)
2963 ;; Settings for Calc embedded mode
2964 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2965 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2966 (if (and org-insert-mode-line-in-empty-file
2967 (interactive-p)
2968 (= (point-min) (point-max)))
2969 (insert " -*- mode: org -*-\n\n"))
2970
2971 (unless org-inhibit-startup
2972 (when org-startup-align-all-tables
2973 (let ((bmp (buffer-modified-p)))
2974 (org-table-map-tables 'org-table-align)
2975 (set-buffer-modified-p bmp)))
2976 (if org-startup-with-deadline-check
2977 (call-interactively 'org-check-deadlines)
2978 (cond
2979 ((eq org-startup-folded t)
2980 (org-cycle '(4)))
2981 ((eq org-startup-folded 'content)
2982 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2983 (org-cycle '(4)) (org-cycle '(4))))))))
2984
2985 (defsubst org-call-with-arg (command arg)
2986 "Call COMMAND interactively, but pretend prefix are was ARG."
2987 (let ((current-prefix-arg arg)) (call-interactively command)))
2988
2989 (defsubst org-current-line (&optional pos)
2990 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2991
2992 (defun org-current-time ()
2993 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2994 (if (> org-time-stamp-rounding-minutes 0)
2995 (let ((r org-time-stamp-rounding-minutes)
2996 (time (decode-time)))
2997 (apply 'encode-time
2998 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2999 (nthcdr 2 time))))
3000 (current-time)))
3001
3002 (defun org-add-props (string plist &rest props)
3003 "Add text properties to entire string, from beginning to end.
3004 PLIST may be a list of properties, PROPS are individual properties and values
3005 that will be added to PLIST. Returns the string that was modified."
3006 (add-text-properties
3007 0 (length string) (if props (append plist props) plist) string)
3008 string)
3009 (put 'org-add-props 'lisp-indent-function 2)
3010
3011
3012 ;;; Font-Lock stuff
3013
3014 (defvar org-mouse-map (make-sparse-keymap))
3015 (define-key org-mouse-map
3016 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3017 (define-key org-mouse-map
3018 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3019 (when org-mouse-1-follows-link
3020 (define-key org-mouse-map [follow-link] 'mouse-face))
3021 (when org-tab-follows-link
3022 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3023 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3024 (when org-return-follows-link
3025 (define-key org-mouse-map [(return)] 'org-open-at-point)
3026 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3027
3028 (require 'font-lock)
3029
3030 (defconst org-non-link-chars "]\t\n\r<>")
3031 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3032 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3033 (defconst org-link-re-with-space
3034 (concat
3035 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3036 "\\([^" org-non-link-chars " ]"
3037 "[^" org-non-link-chars "]*"
3038 "[^" org-non-link-chars " ]\\)>?")
3039 "Matches a link with spaces, optional angular brackets around it.")
3040
3041 (defconst org-link-re-with-space2
3042 (concat
3043 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3044 "\\([^" org-non-link-chars " ]"
3045 "[^]\t\n\r]*"
3046 "[^" org-non-link-chars " ]\\)>?")
3047 "Matches a link with spaces, optional angular brackets around it.")
3048
3049 (defconst org-angle-link-re
3050 (concat
3051 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3052 "\\([^" org-non-link-chars " ]"
3053 "[^" org-non-link-chars "]*"
3054 "\\)>")
3055 "Matches link with angular brackets, spaces are allowed.")
3056 (defconst org-plain-link-re
3057 (concat
3058 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3059 "\\([^]\t\n\r<>,;() ]+\\)")
3060 "Matches plain link, without spaces.")
3061
3062 (defconst org-bracket-link-regexp
3063 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3064 "Matches a link in double brackets.")
3065
3066 (defconst org-bracket-link-analytic-regexp
3067 (concat
3068 "\\[\\["
3069 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3070 "\\([^]]+\\)"
3071 "\\]"
3072 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3073 "\\]"))
3074 ; 1: http:
3075 ; 2: http
3076 ; 3: path
3077 ; 4: [desc]
3078 ; 5: desc
3079
3080
3081 (defconst org-ts-lengths
3082 (cons (length (format-time-string (car org-time-stamp-formats)))
3083 (length (format-time-string (cdr org-time-stamp-formats))))
3084 "This holds the lengths of the two different time formats.")
3085 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3086 "Regular expression for fast time stamp matching.")
3087 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3088 "Regular expression for fast time stamp matching.")
3089 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3090 "Regular expression matching time strings for analysis.")
3091 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3092 "Regular expression matching time stamps, with groups.")
3093 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3094 "Regular expression matching time stamps (also [..]), with groups.")
3095 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3096 "Regular expression matching a time stamp range.")
3097 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3098 org-ts-regexp "\\)?")
3099 "Regular expression matching a time stamp or time stamp range.")
3100
3101 (defvar org-§emph-face nil)
3102
3103 (defun org-do-emphasis-faces (limit)
3104 "Run through the buffer and add overlays to links."
3105 (if (re-search-forward org-emph-re limit t)
3106 (progn
3107 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3108 'face
3109 (nth 1 (assoc (match-string 3)
3110 org-emphasis-alist)))
3111 (add-text-properties (match-beginning 2) (match-end 2)
3112 '(font-lock-multiline t))
3113 (backward-char 1)
3114 t)))
3115
3116 (defun org-activate-plain-links (limit)
3117 "Run through the buffer and add overlays to links."
3118 (if (re-search-forward org-plain-link-re limit t)
3119 (progn
3120 (add-text-properties (match-beginning 0) (match-end 0)
3121 (list 'mouse-face 'highlight
3122 'keymap org-mouse-map
3123 ))
3124 t)))
3125
3126 (defun org-activate-angle-links (limit)
3127 "Run through the buffer and add overlays to links."
3128 (if (re-search-forward org-angle-link-re limit t)
3129 (progn
3130 (add-text-properties (match-beginning 0) (match-end 0)
3131 (list 'mouse-face 'highlight
3132 'keymap org-mouse-map
3133 ))
3134 t)))
3135
3136 (defun org-activate-bracket-links (limit)
3137 "Run through the buffer and add overlays to bracketed links."
3138 (if (re-search-forward org-bracket-link-regexp limit t)
3139 (let* ((help (concat "LINK: "
3140 (org-match-string-no-properties 1)))
3141 ;; FIXME: above we should remove the escapes.
3142 ;; but that requires another match, protecting match data,
3143 ;; a lot of overhead for font-lock.
3144 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
3145 'keymap org-mouse-map 'mouse-face 'highlight
3146 'help-echo help))
3147 (vp (list 'rear-nonsticky t
3148 'keymap org-mouse-map 'mouse-face 'highlight
3149 'help-echo help)))
3150 ;; We need to remove the invisible property here. Table narrowing
3151 ;; may have made some of this invisible.
3152 (remove-text-properties (match-beginning 0) (match-end 0)
3153 '(invisible nil))
3154 (if (match-end 3)
3155 (progn
3156 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3157 (add-text-properties (match-beginning 3) (match-end 3) vp)
3158 (add-text-properties (match-end 3) (match-end 0) ip))
3159 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3160 (add-text-properties (match-beginning 1) (match-end 1) vp)
3161 (add-text-properties (match-end 1) (match-end 0) ip))
3162 t)))
3163
3164 (defun org-activate-dates (limit)
3165 "Run through the buffer and add overlays to dates."
3166 (if (re-search-forward org-tsr-regexp limit t)
3167 (progn
3168 (add-text-properties (match-beginning 0) (match-end 0)
3169 (list 'mouse-face 'highlight
3170 'keymap org-mouse-map))
3171 t)))
3172
3173 (defvar org-target-link-regexp nil
3174 "Regular expression matching radio targets in plain text.")
3175 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3176 "Regular expression matching a link target.")
3177 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3178 "Regular expression matching a link target.")
3179
3180 (defun org-activate-target-links (limit)
3181 "Run through the buffer and add overlays to target matches."
3182 (when org-target-link-regexp
3183 (let ((case-fold-search t))
3184 (if (re-search-forward org-target-link-regexp limit t)
3185 (progn
3186 (add-text-properties (match-beginning 0) (match-end 0)
3187 (list 'mouse-face 'highlight
3188 'keymap org-mouse-map
3189 'help-echo "Radio target link"
3190 'org-linked-text t))
3191 t)))))
3192
3193 (defun org-update-radio-target-regexp ()
3194 "Find all radio targets in this file and update the regular expression."
3195 (interactive)
3196 (when (memq 'radio org-activate-links)
3197 (setq org-target-link-regexp
3198 (org-make-target-link-regexp (org-all-targets 'radio)))
3199 (org-restart-font-lock)))
3200
3201 (defun org-hide-wide-columns (limit)
3202 (let (s e)
3203 (setq s (text-property-any (point) (or limit (point-max))
3204 'org-cwidth t))
3205 (when s
3206 (setq e (next-single-property-change s 'org-cwidth))
3207 (add-text-properties s e '(invisible org-cwidth intangible t))
3208 (goto-char e)
3209 t)))
3210
3211 (defun org-restart-font-lock ()
3212 "Restart font-lock-mode, to force refontification."
3213 (when (and (boundp 'font-lock-mode) font-lock-mode)
3214 (font-lock-mode -1)
3215 (font-lock-mode 1)))
3216
3217 (defun org-all-targets (&optional radio)
3218 "Return a list of all targets in this file.
3219 With optional argument RADIO, only find radio targets."
3220 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3221 rtn)
3222 (save-excursion
3223 (goto-char (point-min))
3224 (while (re-search-forward re nil t)
3225 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3226 rtn)))
3227
3228 (defun org-make-target-link-regexp (targets)
3229 "Make regular expression matching all strings in TARGETS.
3230 The regular expression finds the targets also if there is a line break
3231 between words."
3232 (and targets
3233 (concat
3234 "\\<\\("
3235 (mapconcat
3236 (lambda (x)
3237 (while (string-match " +" x)
3238 (setq x (replace-match "\\s-+" t t x)))
3239 x)
3240 targets
3241 "\\|")
3242 "\\)\\>")))
3243
3244 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3245 "Matches CamelCase words, possibly with a star before it.")
3246
3247 (defun org-activate-camels (limit)
3248 "Run through the buffer and add overlays to dates."
3249 (if (re-search-forward org-camel-regexp limit t)
3250 (progn
3251 (add-text-properties (match-beginning 0) (match-end 0)
3252 (list 'mouse-face 'highlight
3253 'keymap org-mouse-map))
3254 t)))
3255
3256 (defun org-activate-tags (limit)
3257 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3258 (progn
3259 (add-text-properties (match-beginning 1) (match-end 1)
3260 (list 'mouse-face 'highlight
3261 'keymap org-mouse-map))
3262 t)))
3263
3264 (defun org-font-lock-level ()
3265 (save-excursion
3266 (org-back-to-heading t)
3267 (- (match-end 0) (match-beginning 0))))
3268
3269 (defun org-outline-level ()
3270 (save-excursion
3271 (looking-at outline-regexp)
3272 (if (match-beginning 1)
3273 (+ (org-get-string-indentation (match-string 1)) 1000)
3274 (- (match-end 0) (match-beginning 0)))))
3275
3276 (defvar org-font-lock-keywords nil)
3277
3278 (defun org-set-font-lock-defaults ()
3279 (let* ((em org-fontify-emphasized-text)
3280 (lk org-activate-links)
3281 (org-font-lock-extra-keywords
3282 ;; Headlines
3283 (list
3284 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3285 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3286 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3287 (1 'org-table))
3288 ;; Links
3289 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3290 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3291 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3292 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3293 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3294 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3295 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3296 (if org-table-limit-column-width
3297 '(org-hide-wide-columns (0 nil append)))
3298 ;; TODO lines
3299 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3300 '(1 'org-todo t))
3301 ;; Priorities
3302 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3303 ;; Special keywords
3304 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3305 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3306 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3307 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3308 ;; Emphasis
3309 (if em '(org-do-emphasis-faces))
3310 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3311 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3312 2 'bold prepend)
3313 ;; COMMENT
3314 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3315 "\\|" org-quote-string "\\)\\>")
3316 '(1 'org-special-keyword t))
3317 '("^#.*" (0 'font-lock-comment-face t))
3318 ;; DONE
3319 (if org-fontify-done-headline
3320 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3321 '(1 'org-done t) '(2 'org-headline-done t))
3322 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3323 '(1 'org-done t)))
3324 ;; Table stuff
3325 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3326 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3327 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3328 (if org-format-transports-properties-p
3329 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3330 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3331 )))
3332 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3333 ;; Now set the full font-lock-keywords
3334 (set (make-local-variable 'org-font-lock-keywords)
3335 org-font-lock-extra-keywords)
3336 (set (make-local-variable 'font-lock-defaults)
3337 '(org-font-lock-keywords t nil nil backward-paragraph))
3338 (kill-local-variable 'font-lock-keywords) nil))
3339
3340 (defvar org-m nil)
3341 (defvar org-l nil)
3342 (defvar org-f nil)
3343 (defun org-get-level-face (n)
3344 "Get the right face for match N in font-lock matching of healdines."
3345 (setq org-l (- (match-end 2) (match-beginning 1)))
3346 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3347 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3348 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3349 (cond
3350 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3351 ((eq n 2) org-f)
3352 (t (if org-level-color-stars-only nil org-f))))
3353
3354 (defun org-unfontify-region (beg end &optional maybe_loudly)
3355 "Remove fontification and activation overlays from links."
3356 (font-lock-default-unfontify-region beg end)
3357 (let* ((buffer-undo-list t)
3358 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3359 (inhibit-modification-hooks t)
3360 deactivate-mark buffer-file-name buffer-file-truename)
3361 (remove-text-properties beg end
3362 '(mouse-face nil keymap nil org-linked-text nil
3363 invisible nil intangible nil))))
3364 ;;; Visibility cycling
3365
3366 (defvar org-cycle-global-status nil)
3367 (make-variable-buffer-local 'org-cycle-global-status)
3368 (defvar org-cycle-subtree-status nil)
3369 (make-variable-buffer-local 'org-cycle-subtree-status)
3370
3371 ;;;###autoload
3372 (defun org-cycle (&optional arg)
3373 "Visibility cycling for Org-mode.
3374
3375 - When this function is called with a prefix argument, rotate the entire
3376 buffer through 3 states (global cycling)
3377 1. OVERVIEW: Show only top-level headlines.
3378 2. CONTENTS: Show all headlines of all levels, but no body text.
3379 3. SHOW ALL: Show everything.
3380
3381 - When point is at the beginning of a headline, rotate the subtree started
3382 by this line through 3 different states (local cycling)
3383 1. FOLDED: Only the main headline is shown.
3384 2. CHILDREN: The main headline and the direct children are shown.
3385 From this state, you can move to one of the children
3386 and zoom in further.
3387 3. SUBTREE: Show the entire subtree, including body text.
3388
3389 - When there is a numeric prefix, go up to a heading with level ARG, do
3390 a `show-subtree' and return to the previous cursor position. If ARG
3391 is negative, go up that many levels.
3392
3393 - When point is not at the beginning of a headline, execute
3394 `indent-relative', like TAB normally does. See the option
3395 `org-cycle-emulate-tab' for details.
3396
3397 - Special case: if point is the the beginning of the buffer and there is
3398 no headline in line 1, this function will act as if called with prefix arg."
3399 (interactive "P")
3400
3401 (let* ((outline-regexp
3402 (if org-cycle-include-plain-lists
3403 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
3404 outline-regexp))
3405 (bob-special (and org-cycle-global-at-bob (bobp)
3406 (not (looking-at outline-regexp))))
3407 (org-cycle-hook
3408 (if bob-special
3409 (delq 'org-optimize-window-after-visibility-change
3410 (copy-sequence org-cycle-hook))
3411 org-cycle-hook))
3412 (pos (point)))
3413
3414 (if (or bob-special (equal arg '(4)))
3415 ;; special case: use global cycling
3416 (setq arg t))
3417
3418 (cond
3419
3420 ((org-at-table-p 'any)
3421 ;; Enter the table or move to the next field in the table
3422 (or (org-table-recognize-table.el)
3423 (progn
3424 (if arg (org-table-edit-field t)
3425 (org-table-justify-field-maybe)
3426 (call-interactively 'org-table-next-field)))))
3427
3428 ((eq arg t) ;; Global cycling
3429
3430 (cond
3431 ((and (eq last-command this-command)
3432 (eq org-cycle-global-status 'overview))
3433 ;; We just created the overview - now do table of contents
3434 ;; This can be slow in very large buffers, so indicate action
3435 (message "CONTENTS...")
3436 (org-content)
3437 (message "CONTENTS...done")
3438 (setq org-cycle-global-status 'contents)
3439 (run-hook-with-args 'org-cycle-hook 'contents))
3440
3441 ((and (eq last-command this-command)
3442 (eq org-cycle-global-status 'contents))
3443 ;; We just showed the table of contents - now show everything
3444 (show-all)
3445 (message "SHOW ALL")
3446 (setq org-cycle-global-status 'all)
3447 (run-hook-with-args 'org-cycle-hook 'all))
3448
3449 (t
3450 ;; Default action: go to overview
3451 (org-overview)
3452 (message "OVERVIEW")
3453 (setq org-cycle-global-status 'overview)
3454 (run-hook-with-args 'org-cycle-hook 'overview))))
3455
3456 ((integerp arg)
3457 ;; Show-subtree, ARG levels up from here.
3458 (save-excursion
3459 (org-back-to-heading)
3460 (outline-up-heading (if (< arg 0) (- arg)
3461 (- (funcall outline-level) arg)))
3462 (org-show-subtree)))
3463
3464 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3465 ;; At a heading: rotate between three different views
3466 (org-back-to-heading)
3467 (let ((goal-column 0) eoh eol eos)
3468 ;; First, some boundaries
3469 (save-excursion
3470 (org-back-to-heading)
3471 (save-excursion
3472 (beginning-of-line 2)
3473 (while (and (not (eobp)) ;; this is like `next-line'
3474 (get-char-property (1- (point)) 'invisible))
3475 (beginning-of-line 2)) (setq eol (point)))
3476 (outline-end-of-heading) (setq eoh (point))
3477 (org-end-of-subtree t) (setq eos (point))
3478 (outline-next-heading))
3479 ;; Find out what to do next and set `this-command'
3480 (cond
3481 ((and (= eos eoh)
3482 ;; Nothing is hidden behind this heading
3483 (message "EMPTY ENTRY")
3484 (setq org-cycle-subtree-status nil)))
3485 ((>= eol eos)
3486 ;; Entire subtree is hidden in one line: open it
3487 (org-show-entry)
3488 (show-children)
3489 (message "CHILDREN")
3490 (setq org-cycle-subtree-status 'children)
3491 (run-hook-with-args 'org-cycle-hook 'children))
3492 ((and (eq last-command this-command)
3493 (eq org-cycle-subtree-status 'children))
3494 ;; We just showed the children, now show everything.
3495 (org-show-subtree)
3496 (message "SUBTREE")
3497 (setq org-cycle-subtree-status 'subtree)
3498 (run-hook-with-args 'org-cycle-hook 'subtree))
3499 (t
3500 ;; Default action: hide the subtree.
3501 (hide-subtree)
3502 (message "FOLDED")
3503 (setq org-cycle-subtree-status 'folded)
3504 (run-hook-with-args 'org-cycle-hook 'folded)))))
3505
3506 ;; TAB emulation
3507 (buffer-read-only (org-back-to-heading))
3508
3509 ((org-try-cdlatex-tab))
3510
3511 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3512 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3513 (or (and (eq org-cycle-emulate-tab 'white)
3514 (= (match-end 0) (point-at-eol)))
3515 (and (eq org-cycle-emulate-tab 'whitestart)
3516 (>= (match-end 0) pos))))
3517 t
3518 (eq org-cycle-emulate-tab t))
3519 (if (and (looking-at "[ \n\r\t]")
3520 (string-match "^[ \t]*$" (buffer-substring
3521 (point-at-bol) (point))))
3522 (progn
3523 (beginning-of-line 1)
3524 (and (looking-at "[ \t]+") (replace-match ""))))
3525 (indent-relative))
3526
3527 (t (save-excursion
3528 (org-back-to-heading)
3529 (org-cycle))))))
3530
3531 ;;;###autoload
3532 (defun org-global-cycle (&optional arg)
3533 "Cycle the global visibility. For details see `org-cycle'."
3534 (interactive "P")
3535 (if (integerp arg)
3536 (progn
3537 (show-all)
3538 (hide-sublevels arg)
3539 (setq org-cycle-global-status 'contents))
3540 (org-cycle '(4))))
3541
3542 (defun org-overview ()
3543 "Switch to overview mode, shoing only top-level headlines.
3544 Really, this shows all headlines with level equal or greater than the level
3545 of the first headline in the buffer. This is important, because if the
3546 first headline is not level one, then (hide-sublevels 1) gives confusing
3547 results."
3548 (interactive)
3549 (hide-sublevels (save-excursion
3550 (goto-char (point-min))
3551 (if (re-search-forward (concat "^" outline-regexp) nil t)
3552 (progn
3553 (goto-char (match-beginning 0))
3554 (funcall outline-level))
3555 1))))
3556
3557 ;; FIXME: allow an argument to give a limiting level for this.
3558 (defun org-content ()
3559 "Show all headlines in the buffer, like a table of contents"
3560 (interactive)
3561 (save-excursion
3562 ;; Visit all headings and show their offspring
3563 (goto-char (point-max))
3564 (catch 'exit
3565 (while (and (progn (condition-case nil
3566 (outline-previous-visible-heading 1)
3567 (error (goto-char (point-min))))
3568 t)
3569 (looking-at outline-regexp))
3570 (show-branches)
3571 (if (bobp) (throw 'exit nil))))))
3572
3573
3574 (defun org-optimize-window-after-visibility-change (state)
3575 "Adjust the window after a change in outline visibility.
3576 This function is the default value of the hook `org-cycle-hook'."
3577 (when (get-buffer-window (current-buffer))
3578 (cond
3579 ((eq state 'overview) (org-first-headline-recenter 1))
3580 ((eq state 'content) nil)
3581 ((eq state 'all) nil)
3582 ((eq state 'folded) nil)
3583 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3584 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3585
3586 (defun org-subtree-end-visible-p ()
3587 "Is the end of the current subtree visible?"
3588 (pos-visible-in-window-p
3589 (save-excursion (org-end-of-subtree t) (point))))
3590
3591 (defun org-first-headline-recenter (&optional N)
3592 "Move cursor to the first headline and recenter the headline.
3593 Optional argument N means, put the headline into the Nth line of the window."
3594 (goto-char (point-min))
3595 (when (re-search-forward (concat "^" outline-regexp) nil t)
3596 (beginning-of-line)
3597 (recenter (prefix-numeric-value N))))
3598
3599 (defvar org-goto-window-configuration nil)
3600 (defvar org-goto-marker nil)
3601 (defvar org-goto-map (make-sparse-keymap))
3602 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3603 (while (setq cmd (pop cmds))
3604 (substitute-key-definition cmd cmd org-goto-map global-map)))
3605 (define-key org-goto-map "\C-m" 'org-goto-ret)
3606 (define-key org-goto-map [(left)] 'org-goto-left)
3607 (define-key org-goto-map [(right)] 'org-goto-right)
3608 (define-key org-goto-map [(?q)] 'org-goto-quit)
3609 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3610 (define-key org-goto-map "\C-i" 'org-cycle)
3611 (define-key org-goto-map [(tab)] 'org-cycle)
3612 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3613 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3614 (define-key org-goto-map "n" 'outline-next-visible-heading)
3615 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3616 (define-key org-goto-map "f" 'outline-forward-same-level)
3617 (define-key org-goto-map "b" 'outline-backward-same-level)
3618 (define-key org-goto-map "u" 'outline-up-heading)
3619 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3620 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3621 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3622 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3623 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3624 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3625 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3626
3627 (defconst org-goto-help
3628 "Select a location to jump to, press RET
3629 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3630
3631 (defun org-goto ()
3632 "Go to a different location of the document, keeping current visibility.
3633
3634 When you want to go to a different location in a document, the fastest way
3635 is often to fold the entire buffer and then dive into the tree. This
3636 method has the disadvantage, that the previous location will be folded,
3637 which may not be what you want.
3638
3639 This command works around this by showing a copy of the current buffer in
3640 overview mode. You can dive into the tree in that copy, to find the
3641 location you want to reach. When pressing RET, the command returns to the
3642 original buffer in which the visibility is still unchanged. It then jumps
3643 to the new location, making it and the headline hierarchy above it visible."
3644 (interactive)
3645 (let* ((org-goto-start-pos (point))
3646 (selected-point
3647 (org-get-location (current-buffer) org-goto-help)))
3648 (if selected-point
3649 (progn
3650 (org-mark-ring-push org-goto-start-pos)
3651 (goto-char selected-point)
3652 (if (or (org-invisible-p) (org-invisible-p2))
3653 (org-show-hierarchy-above)))
3654 (error "Quit"))))
3655
3656 (defun org-get-location (buf help)
3657 "Let the user select a location in the Org-mode buffer BUF.
3658 This function uses a recursive edit. It returns the selected position
3659 or nil."
3660 (let (org-selected-point)
3661 (save-excursion
3662 (save-window-excursion
3663 (delete-other-windows)
3664 (switch-to-buffer (get-buffer-create "*org-goto*"))
3665 (with-output-to-temp-buffer "*Help*"
3666 (princ help))
3667 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3668 (setq buffer-read-only nil)
3669 (erase-buffer)
3670 (insert-buffer-substring buf)
3671 (let ((org-startup-truncated t)
3672 (org-startup-folded t)
3673 (org-startup-align-all-tables nil)
3674 (org-startup-with-deadline-check nil))
3675 (org-mode))
3676 (setq buffer-read-only t)
3677 (if (boundp 'org-goto-start-pos)
3678 (goto-char org-goto-start-pos)
3679 (goto-char (point-min)))
3680 (org-beginning-of-line)
3681 (message "Select location and press RET")
3682 ;; now we make sure that during selection, ony very few keys work
3683 ;; and that it is impossible to switch to another window.
3684 (let ((gm (current-global-map))
3685 (overriding-local-map org-goto-map))
3686 (unwind-protect
3687 (progn
3688 (use-global-map org-goto-map)
3689 (recursive-edit))
3690 (use-global-map gm)))))
3691 (kill-buffer "*org-goto*")
3692 org-selected-point))
3693
3694 (defun org-goto-ret (&optional arg)
3695 "Finish `org-goto' by going to the new location."
3696 (interactive "P")
3697 (setq org-selected-point (point)
3698 current-prefix-arg arg)
3699 (throw 'exit nil))
3700
3701 (defun org-goto-left ()
3702 "Finish `org-goto' by going to the new location."
3703 (interactive)
3704 (if (org-on-heading-p)
3705 (progn
3706 (beginning-of-line 1)
3707 (setq org-selected-point (point)
3708 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3709 (throw 'exit nil))
3710 (error "Not on a heading")))
3711
3712 (defun org-goto-right ()
3713 "Finish `org-goto' by going to the new location."
3714 (interactive)
3715 (if (org-on-heading-p)
3716 (progn
3717 (outline-end-of-subtree)
3718 (or (eobp) (forward-char 1))
3719 (setq org-selected-point (point)
3720 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3721 (throw 'exit nil))
3722 (error "Not on a heading")))
3723
3724 (defun org-goto-quit ()
3725 "Finish `org-goto' without cursor motion."
3726 (interactive)
3727 (setq org-selected-point nil)
3728 (throw 'exit nil))
3729
3730 ;;; Promotion, Demotion, Inserting new headlines
3731
3732 (defvar org-ignore-region nil
3733 "To temporarily disable the active region.")
3734
3735 (defun org-insert-heading (&optional force-heading)
3736 "Insert a new heading or item with same depth at point.
3737 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3738 If point is at the beginning of a headline, insert a sibling before the
3739 current headline. If point is in the middle of a headline, split the headline
3740 at that position and make the rest of the headline part of the sibling below
3741 the current headline."
3742 (interactive "P")
3743 (if (= (buffer-size) 0)
3744 (insert "\n* ")
3745 (when (or force-heading (not (org-insert-item)))
3746 (let* ((head (save-excursion
3747 (condition-case nil
3748 (progn
3749 (org-back-to-heading)
3750 (match-string 0))
3751 (error "*"))))
3752 pos)
3753 (cond
3754 ((and (org-on-heading-p) (bolp)
3755 (save-excursion (backward-char 1) (not (org-invisible-p))))
3756 (open-line 1))
3757 ((and (bolp) (save-excursion
3758 (backward-char 1) (not (org-invisible-p))))
3759 nil)
3760 (t (newline)))
3761 (insert head) (just-one-space)
3762 (setq pos (point))
3763 (end-of-line 1)
3764 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3765 (run-hooks 'org-insert-heading-hook)))))
3766
3767 (defun org-insert-item (&optional checkbox)
3768 "Insert a new item at the current level.
3769 Return t when things worked, nil when we are not in an item."
3770 (when (save-excursion
3771 (condition-case nil
3772 (progn
3773 (org-beginning-of-item)
3774 (org-at-item-p)
3775 t)
3776 (error nil)))
3777 (let* ((bul (match-string 0))
3778 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3779 (match-end 0)))
3780 pos)
3781 (cond
3782 ((and (org-at-item-p) (<= (point) eow))
3783 ;; before the bullet
3784 (beginning-of-line 1)
3785 (open-line 1))
3786 ((<= (point) eow)
3787 (beginning-of-line 1))
3788 (t (newline)))
3789 (insert bul (if checkbox "[ ]" ""))
3790 (just-one-space)
3791 (setq pos (point))
3792 (end-of-line 1)
3793 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3794 (org-maybe-renumber-ordered-list)
3795 t))
3796
3797 (defun org-insert-todo-heading (arg)
3798 "Insert a new heading with the same level and TODO state as current heading.
3799 If the heading has no TODO state, or if the state is DONE, use the first
3800 state (TODO by default). Also with prefix arg, force first state."
3801 (interactive "P")
3802 (when (not (org-insert-item 'checkbox))
3803 (org-insert-heading)
3804 (save-excursion
3805 (org-back-to-heading)
3806 (if org-noutline-p
3807 (outline-previous-heading)
3808 (outline-previous-visible-heading t))
3809 (looking-at org-todo-line-regexp))
3810 (if (or arg
3811 (not (match-beginning 2))
3812 (equal (match-string 2) org-done-string))
3813 (insert (car org-todo-keywords) " ")
3814 (insert (match-string 2) " "))))
3815
3816 (defun org-promote-subtree ()
3817 "Promote the entire subtree.
3818 See also `org-promote'."
3819 (interactive)
3820 (save-excursion
3821 (org-map-tree 'org-promote)))
3822
3823 (defun org-demote-subtree ()
3824 "Demote the entire subtree. See `org-demote'.
3825 See also `org-promote'."
3826 (interactive)
3827 (save-excursion
3828 (org-map-tree 'org-demote)))
3829
3830 (defun org-do-promote ()
3831 "Promote the current heading higher up the tree.
3832 If the region is active in `transient-mark-mode', promote all headings
3833 in the region."
3834 (interactive)
3835 (save-excursion
3836 (if (org-region-active-p)
3837 (org-map-region 'org-promote (region-beginning) (region-end))
3838 (org-promote)))
3839 (org-fix-position-after-promote))
3840
3841 (defun org-do-demote ()
3842 "Demote the current heading lower down the tree.
3843 If the region is active in `transient-mark-mode', demote all headings
3844 in the region."
3845 (interactive)
3846 (save-excursion
3847 (if (org-region-active-p)
3848 (org-map-region 'org-demote (region-beginning) (region-end))
3849 (org-demote)))
3850 (org-fix-position-after-promote))
3851
3852 (defun org-fix-position-after-promote ()
3853 "Make sure that after pro/demotion cursor position is right."
3854 (and (equal (char-after) ?\ )
3855 (equal (char-before) ?*)
3856 (forward-char 1)))
3857
3858 (defun org-get-legal-level (level change)
3859 "Rectify a level change under the influence of `org-odd-levels-only'
3860 LEVEL is a current level, CHANGE is by how much the level should be
3861 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3862 even level numbers will become the next higher odd number."
3863 (if org-odd-levels-only
3864 (cond ((not change) (1+ (* 2 (/ level 2))))
3865 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3866 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3867 (max 1 (+ level change))))
3868
3869 (defun org-promote ()
3870 "Promote the current heading higher up the tree.
3871 If the region is active in `transient-mark-mode', promote all headings
3872 in the region."
3873 (org-back-to-heading t)
3874 (let* ((level (save-match-data (funcall outline-level)))
3875 (up-head (make-string (org-get-legal-level level -1) ?*))
3876 (diff (abs (- level (length up-head)))))
3877 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3878 (replace-match up-head nil t)
3879 ;; Fixup tag positioning
3880 (and org-auto-align-tags (org-set-tags nil t))
3881 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
3882
3883 (defun org-demote ()
3884 "Demote the current heading lower down the tree.
3885 If the region is active in `transient-mark-mode', demote all headings
3886 in the region."
3887 (org-back-to-heading t)
3888 (let* ((level (save-match-data (funcall outline-level)))
3889 (down-head (make-string (org-get-legal-level level 1) ?*))
3890 (diff (abs (- level (length down-head)))))
3891 (replace-match down-head nil t)
3892 ;; Fixup tag positioning
3893 (and org-auto-align-tags (org-set-tags nil t))
3894 (if org-adapt-indentation (org-fixup-indentation diff))))
3895
3896 (defun org-map-tree (fun)
3897 "Call FUN for every heading underneath the current one."
3898 (org-back-to-heading)
3899 (let ((level (funcall outline-level)))
3900 (save-excursion
3901 (funcall fun)
3902 (while (and (progn
3903 (outline-next-heading)
3904 (> (funcall outline-level) level))
3905 (not (eobp)))
3906 (funcall fun)))))
3907
3908 (defun org-map-region (fun beg end)
3909 "Call FUN for every heading between BEG and END."
3910 (let ((org-ignore-region t))
3911 (save-excursion
3912 (setq end (copy-marker end))
3913 (goto-char beg)
3914 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3915 (< (point) end))
3916 (funcall fun))
3917 (while (and (progn
3918 (outline-next-heading)
3919 (< (point) end))
3920 (not (eobp)))
3921 (funcall fun)))))
3922
3923 (defun org-fixup-indentation (diff)
3924 "Change the indentation in the current entry by DIFF
3925 However, if any line in the current entry has no indentation, or if it
3926 would end up with no indentation after the change, nothing at all is done."
3927 (save-excursion
3928 (let ((end (save-excursion (outline-next-heading)
3929 (point-marker)))
3930 (prohibit (if (> diff 0)
3931 "^\\S-"
3932 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
3933 col)
3934 (unless (save-excursion (re-search-forward prohibit end t))
3935 (while (re-search-forward "^[ \t]+" end t)
3936 (goto-char (match-end 0))
3937 (setq col (current-column))
3938 (if (< diff 0) (replace-match ""))
3939 (indent-to (+ diff col))))
3940 (move-marker end nil))))
3941
3942 ;;; Vertical tree motion, cutting and pasting of subtrees
3943
3944 (defun org-move-subtree-up (&optional arg)
3945 "Move the current subtree up past ARG headlines of the same level."
3946 (interactive "p")
3947 (org-move-subtree-down (- (prefix-numeric-value arg))))
3948
3949 (defun org-move-subtree-down (&optional arg)
3950 "Move the current subtree down past ARG headlines of the same level."
3951 (interactive "p")
3952 (setq arg (prefix-numeric-value arg))
3953 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3954 'outline-get-last-sibling))
3955 (ins-point (make-marker))
3956 (cnt (abs arg))
3957 beg end txt folded)
3958 ;; Select the tree
3959 (org-back-to-heading)
3960 (setq beg (point))
3961 (save-match-data
3962 (save-excursion (outline-end-of-heading)
3963 (setq folded (org-invisible-p)))
3964 (outline-end-of-subtree))
3965 (outline-next-heading)
3966 (setq end (point))
3967 ;; Find insertion point, with error handling
3968 (goto-char beg)
3969 (while (> cnt 0)
3970 (or (and (funcall movfunc) (looking-at outline-regexp))
3971 (progn (goto-char beg)
3972 (error "Cannot move past superior level or buffer limit")))
3973 (setq cnt (1- cnt)))
3974 (if (> arg 0)
3975 ;; Moving forward - still need to move over subtree
3976 (progn (outline-end-of-subtree)
3977 (outline-next-heading)
3978 (if (not (or (looking-at (concat "^" outline-regexp))
3979 (bolp)))
3980 (newline))))
3981 (move-marker ins-point (point))
3982 (setq txt (buffer-substring beg end))
3983 (delete-region beg end)
3984 (insert txt)
3985 (goto-char ins-point)
3986 (if folded (hide-subtree))
3987 (move-marker ins-point nil)))
3988
3989 (defvar org-subtree-clip ""
3990 "Clipboard for cut and paste of subtrees.
3991 This is actually only a copy of the kill, because we use the normal kill
3992 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3993
3994 (defvar org-subtree-clip-folded nil
3995 "Was the last copied subtree folded?
3996 This is used to fold the tree back after pasting.")
3997
3998 (defun org-cut-subtree ()
3999 "Cut the current subtree into the clipboard.
4000 This is a short-hand for marking the subtree and then cutting it."
4001 (interactive)
4002 (org-copy-subtree 'cut))
4003
4004 (defun org-copy-subtree (&optional cut)
4005 "Cut the current subtree into the clipboard.
4006 This is a short-hand for marking the subtree and then copying it.
4007 If CUT is non nil, actually cut the subtree."
4008 (interactive)
4009 (let (beg end folded)
4010 (org-back-to-heading)
4011 (setq beg (point))
4012 (save-match-data
4013 (save-excursion (outline-end-of-heading)
4014 (setq folded (org-invisible-p)))
4015 (outline-end-of-subtree))
4016 (if (equal (char-after) ?\n) (forward-char 1))
4017 (setq end (point))
4018 (goto-char beg)
4019 (when (> end beg)
4020 (setq org-subtree-clip-folded folded)
4021 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4022 (setq org-subtree-clip (current-kill 0))
4023 (message "%s: Subtree with %d characters"
4024 (if cut "Cut" "Copied")
4025 (length org-subtree-clip)))))
4026
4027 (defun org-paste-subtree (&optional level tree)
4028 "Paste the clipboard as a subtree, with modification of headline level.
4029 The entire subtree is promoted or demoted in order to match a new headline
4030 level. By default, the new level is derived from the visible headings
4031 before and after the insertion point, and taken to be the inferior headline
4032 level of the two. So if the previous visible heading is level 3 and the
4033 next is level 4 (or vice versa), level 4 will be used for insertion.
4034 This makes sure that the subtree remains an independent subtree and does
4035 not swallow low level entries.
4036
4037 You can also force a different level, either by using a numeric prefix
4038 argument, or by inserting the heading marker by hand. For example, if the
4039 cursor is after \"*****\", then the tree will be shifted to level 5.
4040
4041 If you want to insert the tree as is, just use \\[yank].
4042
4043 If optional TREE is given, use this text instead of the kill ring."
4044 (interactive "P")
4045 (unless (org-kill-is-subtree-p tree)
4046 (error
4047 (substitute-command-keys
4048 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4049 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4050 (^re (concat "^\\(" outline-regexp "\\)"))
4051 (re (concat "\\(" outline-regexp "\\)"))
4052 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4053
4054 (old-level (if (string-match ^re txt)
4055 (- (match-end 0) (match-beginning 0))
4056 -1))
4057 (force-level (cond (level (prefix-numeric-value level))
4058 ((string-match
4059 ^re_ (buffer-substring (point-at-bol) (point)))
4060 (- (match-end 0) (match-beginning 0)))
4061 (t nil)))
4062 (previous-level (save-excursion
4063 (condition-case nil
4064 (progn
4065 (outline-previous-visible-heading 1)
4066 (if (looking-at re)
4067 (- (match-end 0) (match-beginning 0))
4068 1))
4069 (error 1))))
4070 (next-level (save-excursion
4071 (condition-case nil
4072 (progn
4073 (outline-next-visible-heading 1)
4074 (if (looking-at re)
4075 (- (match-end 0) (match-beginning 0))
4076 1))
4077 (error 1))))
4078 (new-level (or force-level (max previous-level next-level)))
4079 (shift (if (or (= old-level -1)
4080 (= new-level -1)
4081 (= old-level new-level))
4082 0
4083 (- new-level old-level)))
4084 (shift1 shift)
4085 (delta (if (> shift 0) -1 1))
4086 (func (if (> shift 0) 'org-demote 'org-promote))
4087 (org-odd-levels-only nil)
4088 beg end)
4089 ;; Remove the forces level indicator
4090 (if force-level
4091 (delete-region (point-at-bol) (point)))
4092 ;; Make sure we start at the beginning of an empty line
4093 (if (not (bolp)) (insert "\n"))
4094 (if (not (looking-at "[ \t]*$"))
4095 (progn (insert "\n") (backward-char 1)))
4096 ;; Paste
4097 (setq beg (point))
4098 (if (string-match "[ \t\r\n]+\\'" txt)
4099 (setq txt (replace-match "\n" t t txt)))
4100 (insert txt)
4101 (setq end (point))
4102 (if (looking-at "[ \t\r\n]+")
4103 (replace-match "\n"))
4104 (goto-char beg)
4105 ;; Shift if necessary
4106 (if (= shift 0)
4107 (message "Pasted at level %d, without shift" new-level)
4108 (save-restriction
4109 (narrow-to-region beg end)
4110 (while (not (= shift 0))
4111 (org-map-region func (point-min) (point-max))
4112 (setq shift (+ delta shift)))
4113 (goto-char (point-min))
4114 (message "Pasted at level %d, with shift by %d levels"
4115 new-level shift1)))
4116 (if (and kill-ring
4117 (eq org-subtree-clip (current-kill 0))
4118 org-subtree-clip-folded)
4119 ;; The tree was folded before it was killed/copied
4120 (hide-subtree))))
4121
4122 (defun org-kill-is-subtree-p (&optional txt)
4123 "Check if the current kill is an outline subtree, or a set of trees.
4124 Returns nil if kill does not start with a headline, or if the first
4125 headline level is not the largest headline level in the tree.
4126 So this will actually accept several entries of equal levels as well,
4127 which is OK for `org-paste-subtree'.
4128 If optional TXT is given, check this string instead of the current kill."
4129 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4130 (start-level (and kill
4131 (string-match (concat "\\`" outline-regexp) kill)
4132 (- (match-end 0) (match-beginning 0))))
4133 (re (concat "^" outline-regexp))
4134 (start 1))
4135 (if (not start-level)
4136 nil ;; does not even start with a heading
4137 (catch 'exit
4138 (while (setq start (string-match re kill (1+ start)))
4139 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4140 (throw 'exit nil)))
4141 t))))
4142
4143 (defun org-narrow-to-subtree ()
4144 "Narrow buffer to the current subtree."
4145 (interactive)
4146 (save-excursion
4147 (narrow-to-region
4148 (progn (org-back-to-heading) (point))
4149 (progn (org-end-of-subtree t) (point)))))
4150
4151 ;;; Plain list items
4152
4153 (defun org-at-item-p ()
4154 "Is point in a line starting a hand-formatted item?"
4155 (let ((llt org-plain-list-ordered-item-terminator))
4156 (save-excursion
4157 (goto-char (point-at-bol))
4158 (looking-at
4159 (cond
4160 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4161 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4162 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4163 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4164
4165 (defun org-at-item-checkbox-p ()
4166 "Is point at a line starting a plain-list item with a checklet?"
4167 (and (org-at-item-p)
4168 (save-excursion
4169 (goto-char (match-end 0))
4170 (skip-chars-forward " \t")
4171 (looking-at "\\[[ X]\\]"))))
4172
4173 (defun org-toggle-checkbox (&optional arg)
4174 "Toggle the checkbox in the current line."
4175 (interactive "P")
4176 (catch 'exit
4177 (let (beg end status (firstnew 'unknown))
4178 (cond
4179 ((org-region-active-p)
4180 (setq beg (region-beginning) end (region-end)))
4181 ((org-on-heading-p)
4182 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4183 ((org-at-item-checkbox-p)
4184 (save-excursion
4185 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4186 (throw 'exit t))
4187 (t (error "Not at a checkbox or heading, and no active region")))
4188 (save-excursion
4189 (goto-char beg)
4190 (while (< (point) end)
4191 (when (org-at-item-checkbox-p)
4192 (setq status (equal (match-string 0) "[X]"))
4193 (when (eq firstnew 'unknown)
4194 (setq firstnew (not status)))
4195 (replace-match
4196 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4197 (beginning-of-line 2))))))
4198
4199 (defun org-get-indentation (&optional line)
4200 "Get the indentation of the current line, interpreting tabs.
4201 When LINE is given, assume it represents a line and compute its indentation."
4202 (if line
4203 (if (string-match "^ *" (org-remove-tabs line))
4204 (match-end 0))
4205 (save-excursion
4206 (beginning-of-line 1)
4207 (skip-chars-forward " \t")
4208 (current-column))))
4209
4210 (defun org-remove-tabs (s &optional width)
4211 "Replace tabulators in S with spaces.
4212 Assumes that s is a single line, starting in column 0."
4213 (setq width (or width tab-width))
4214 (while (string-match "\t" s)
4215 (setq s (replace-match
4216 (make-string
4217 (- (* width (/ (+ (match-beginning 0) width) width))
4218 (match-beginning 0)) ?\ )
4219 t t s)))
4220 s)
4221
4222 ;; FIXME: document properly.
4223 (defun org-fix-indentation (line ind)
4224 "If the current indenation is smaller than ind1, leave it alone.
4225 If it is larger than ind, reduce it by ind."
4226 (let* ((l (org-remove-tabs line))
4227 (i (org-get-indentation l))
4228 (i1 (car ind)) (i2 (cdr ind)))
4229 (if (>= i i2) (setq l (substring line i2)))
4230 (if (> i1 0)
4231 (concat (make-string i1 ?\ ) l)
4232 l)))
4233
4234 (defun org-beginning-of-item ()
4235 "Go to the beginning of the current hand-formatted item.
4236 If the cursor is not in an item, throw an error."
4237 (interactive)
4238 (let ((pos (point))
4239 (limit (save-excursion (org-back-to-heading)
4240 (beginning-of-line 2) (point)))
4241 ind ind1)
4242 (if (org-at-item-p)
4243 (beginning-of-line 1)
4244 (beginning-of-line 1)
4245 (skip-chars-forward " \t")
4246 (setq ind (current-column))
4247 (if (catch 'exit
4248 (while t
4249 (beginning-of-line 0)
4250 (if (< (point) limit) (throw 'exit nil))
4251 (unless (looking-at "[ \t]*$")
4252 (skip-chars-forward " \t")
4253 (setq ind1 (current-column))
4254 (if (< ind1 ind)
4255 (throw 'exit (org-at-item-p))))))
4256 nil
4257 (goto-char pos)
4258 (error "Not in an item")))))
4259
4260 (defun org-end-of-item ()
4261 "Go to the end of the current hand-formatted item.
4262 If the cursor is not in an item, throw an error."
4263 (interactive)
4264 (let ((pos (point))
4265 (limit (save-excursion (outline-next-heading) (point)))
4266 (ind (save-excursion
4267 (org-beginning-of-item)
4268 (skip-chars-forward " \t")
4269 (current-column)))
4270 ind1)
4271 (if (catch 'exit
4272 (while t
4273 (beginning-of-line 2)
4274 (if (>= (point) limit) (throw 'exit t))
4275 (unless (looking-at "[ \t]*$")
4276 (skip-chars-forward " \t")
4277 (setq ind1 (current-column))
4278 (if (<= ind1 ind) (throw 'exit t)))))
4279 (beginning-of-line 1)
4280 (goto-char pos)
4281 (error "Not in an item"))))
4282
4283 (defun org-next-item ()
4284 "Move to the beginning of the next item in the current plain list.
4285 Error if not at a plain list, or if this is the last item in the list."
4286 (interactive)
4287 (let (ind ind1 (pos (point)))
4288 (org-beginning-of-item)
4289 (setq ind (org-get-indentation))
4290 (org-end-of-item)
4291 (setq ind1 (org-get-indentation))
4292 (unless (and (org-at-item-p) (= ind ind1))
4293 (goto-char pos)
4294 (error "On last item"))))
4295
4296 (defun org-previous-item ()
4297 "Move to the beginning of the previous item in the current plain list.
4298 Error if not at a plain list, or if this is the last item in the list."
4299 (interactive)
4300 (let (beg ind (pos (point)))
4301 (org-beginning-of-item)
4302 (setq beg (point))
4303 (setq ind (org-get-indentation))
4304 (goto-char beg)
4305 (catch 'exit
4306 (while t
4307 (beginning-of-line 0)
4308 (if (looking-at "[ \t]*$")
4309 nil
4310 (if (<= (org-get-indentation) ind)
4311 (throw 'exit t)))))
4312 (condition-case nil
4313 (org-beginning-of-item)
4314 (error (goto-char pos)
4315 (error "On first item")))))
4316
4317 (defun org-move-item-down ()
4318 "Move the plain list item at point down, i.e. swap with following item.
4319 Subitems (items with larger indentation) are considered part of the item,
4320 so this really moves item trees."
4321 (interactive)
4322 (let (beg end ind ind1 (pos (point)) txt)
4323 (org-beginning-of-item)
4324 (setq beg (point))
4325 (setq ind (org-get-indentation))
4326 (org-end-of-item)
4327 (setq end (point))
4328 (setq ind1 (org-get-indentation))
4329 (if (and (org-at-item-p) (= ind ind1))
4330 (progn
4331 (org-end-of-item)
4332 (setq txt (buffer-substring beg end))
4333 (save-excursion
4334 (delete-region beg end))
4335 (setq pos (point))
4336 (insert txt)
4337 (goto-char pos)
4338 (org-maybe-renumber-ordered-list))
4339 (goto-char pos)
4340 (error "Cannot move this item further down"))))
4341
4342 (defun org-move-item-up (arg)
4343 "Move the plain list item at point up, i.e. swap with previous item.
4344 Subitems (items with larger indentation) are considered part of the item,
4345 so this really moves item trees."
4346 (interactive "p")
4347 (let (beg end ind ind1 (pos (point)) txt)
4348 (org-beginning-of-item)
4349 (setq beg (point))
4350 (setq ind (org-get-indentation))
4351 (org-end-of-item)
4352 (setq end (point))
4353 (goto-char beg)
4354 (catch 'exit
4355 (while t
4356 (beginning-of-line 0)
4357 (if (looking-at "[ \t]*$")
4358 nil
4359 (if (<= (setq ind1 (org-get-indentation)) ind)
4360 (throw 'exit t)))))
4361 (condition-case nil
4362 (org-beginning-of-item)
4363 (error (goto-char beg)
4364 (error "Cannot move this item further up")))
4365 (setq ind1 (org-get-indentation))
4366 (if (and (org-at-item-p) (= ind ind1))
4367 (progn
4368 (setq txt (buffer-substring beg end))
4369 (save-excursion
4370 (delete-region beg end))
4371 (setq pos (point))
4372 (insert txt)
4373 (goto-char pos)
4374 (org-maybe-renumber-ordered-list))
4375 (goto-char pos)
4376 (error "Cannot move this item further up"))))
4377
4378 (defun org-maybe-renumber-ordered-list ()
4379 "Renumber the ordered list at point if setup allows it.
4380 This tests the user option `org-auto-renumber-ordered-lists' before
4381 doing the renumbering."
4382 (and org-auto-renumber-ordered-lists
4383 (org-at-item-p)
4384 (match-beginning 3)
4385 (org-renumber-ordered-list 1)))
4386
4387 (defun org-get-string-indentation (s)
4388 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4389 (let ((n -1) (i 0) (w tab-width) c)
4390 (catch 'exit
4391 (while (< (setq n (1+ n)) (length s))
4392 (setq c (aref s n))
4393 (cond ((= c ?\ ) (setq i (1+ i)))
4394 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4395 (t (throw 'exit t)))))
4396 i))
4397
4398 (defun org-renumber-ordered-list (arg)
4399 "Renumber an ordered plain list.
4400 Cursor needs to be in the first line of an item, the line that starts
4401 with something like \"1.\" or \"2)\"."
4402 (interactive "p")
4403 (unless (and (org-at-item-p)
4404 (match-beginning 3))
4405 (error "This is not an ordered list"))
4406 (let ((line (org-current-line))
4407 (col (current-column))
4408 (ind (org-get-string-indentation
4409 (buffer-substring (point-at-bol) (match-beginning 3))))
4410 ;; (term (substring (match-string 3) -1))
4411 ind1 (n (1- arg)))
4412 ;; find where this list begins
4413 (catch 'exit
4414 (while t
4415 (catch 'next
4416 (beginning-of-line 0)
4417 (if (looking-at "[ \t]*$") (throw 'next t))
4418 (skip-chars-forward " \t") (setq ind1 (current-column))
4419 (if (or (< ind1 ind)
4420 (and (= ind1 ind)
4421 (not (org-at-item-p))))
4422 (throw 'exit t)))))
4423 ;; Walk forward and replace these numbers
4424 (catch 'exit
4425 (while t
4426 (catch 'next
4427 (beginning-of-line 2)
4428 (if (eobp) (throw 'exit nil))
4429 (if (looking-at "[ \t]*$") (throw 'next nil))
4430 (skip-chars-forward " \t") (setq ind1 (current-column))
4431 (if (> ind1 ind) (throw 'next t))
4432 (if (< ind1 ind) (throw 'exit t))
4433 (if (not (org-at-item-p)) (throw 'exit nil))
4434 (if (not (match-beginning 3))
4435 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4436 (delete-region (match-beginning 3) (1- (match-end 3)))
4437 (goto-char (match-beginning 3))
4438 (insert (format "%d" (setq n (1+ n)))))))
4439 (goto-line line)
4440 (move-to-column col)))
4441
4442 (defvar org-last-indent-begin-marker (make-marker))
4443 (defvar org-last-indent-end-marker (make-marker))
4444
4445 (defun org-outdent-item (arg)
4446 "Outdent a local list item."
4447 (interactive "p")
4448 (org-indent-item (- arg)))
4449
4450 (defun org-indent-item (arg)
4451 "Indent a local list item."
4452 (interactive "p")
4453 (unless (org-at-item-p)
4454 (error "Not on an item"))
4455 (save-excursion
4456 (let (beg end ind ind1)
4457 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4458 (setq beg org-last-indent-begin-marker
4459 end org-last-indent-end-marker)
4460 (org-beginning-of-item)
4461 (setq beg (move-marker org-last-indent-begin-marker (point)))
4462 (org-end-of-item)
4463 (setq end (move-marker org-last-indent-end-marker (point))))
4464 (goto-char beg)
4465 (skip-chars-forward " \t") (setq ind (current-column))
4466 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4467 (while (< (point) end)
4468 (beginning-of-line 1)
4469 (skip-chars-forward " \t") (setq ind1 (current-column))
4470 (delete-region (point-at-bol) (point))
4471 (indent-to-column (+ ind1 arg))
4472 (beginning-of-line 2)))))
4473
4474 ;;; Archiving
4475
4476 (defun org-archive-subtree (&optional find-done)
4477 "Move the current subtree to the archive.
4478 The archive can be a certain top-level heading in the current file, or in
4479 a different file. The tree will be moved to that location, the subtree
4480 heading be marked DONE, and the current time will be added.
4481
4482 When called with prefix argument FIND-DONE, find whole trees without any
4483 open TODO items and archive them (after getting confirmation from the user).
4484 If the cursor is not at a headline when this comand is called, try all level
4485 1 trees. If the cursor is on a headline, only try the direct children of
4486 this heading. "
4487 (interactive "P")
4488 (if find-done
4489 (org-archive-all-done)
4490 ;; Save all relevant TODO keyword-relatex variables
4491
4492 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4493 (tr-org-todo-keywords org-todo-keywords)
4494 (tr-org-todo-interpretation org-todo-interpretation)
4495 (tr-org-done-string org-done-string)
4496 (tr-org-todo-regexp org-todo-regexp)
4497 (tr-org-todo-line-regexp org-todo-line-regexp)
4498 (this-buffer (current-buffer))
4499 file heading buffer level newfile-p)
4500 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4501 (progn
4502 (setq file (format (match-string 1 org-archive-location)
4503 (file-name-nondirectory buffer-file-name))
4504 heading (match-string 2 org-archive-location)))
4505 (error "Invalid `org-archive-location'"))
4506 (if (> (length file) 0)
4507 (setq newfile-p (not (file-exists-p file))
4508 buffer (find-file-noselect file))
4509 (setq buffer (current-buffer)))
4510 (unless buffer
4511 (error "Cannot access file \"%s\"" file))
4512 (if (and (> (length heading) 0)
4513 (string-match "^\\*+" heading))
4514 (setq level (match-end 0))
4515 (setq heading nil level 0))
4516 (save-excursion
4517 ;; We first only copy, in case something goes wrong
4518 ;; we need to protect this-command, to avoid kill-region sets it,
4519 ;; which would lead to duplication of subtrees
4520 (let (this-command) (org-copy-subtree))
4521 (set-buffer buffer)
4522 ;; Enforce org-mode for the archive buffer
4523 (if (not (eq major-mode 'org-mode))
4524 ;; Force the mode for future visits.
4525 (let ((org-insert-mode-line-in-empty-file t))
4526 (call-interactively 'org-mode)))
4527 (when newfile-p
4528 (goto-char (point-max))
4529 (insert (format "\nArchived entries from file %s\n\n"
4530 (buffer-file-name this-buffer))))
4531 ;; Force the TODO keywords of the original buffer
4532 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4533 (org-todo-keywords tr-org-todo-keywords)
4534 (org-todo-interpretation tr-org-todo-interpretation)
4535 (org-done-string tr-org-done-string)
4536 (org-todo-regexp tr-org-todo-regexp)
4537 (org-todo-line-regexp tr-org-todo-line-regexp))
4538 (goto-char (point-min))
4539 (if heading
4540 (progn
4541 (if (re-search-forward
4542 (concat "\\(^\\|\r\\)"
4543 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4544 nil t)
4545 (goto-char (match-end 0))
4546 ;; Heading not found, just insert it at the end
4547 (goto-char (point-max))
4548 (or (bolp) (insert "\n"))
4549 (insert "\n" heading "\n")
4550 (end-of-line 0))
4551 ;; Make the subtree visible
4552 (show-subtree)
4553 (org-end-of-subtree t)
4554 (skip-chars-backward " \t\r\n]")
4555 (and (looking-at "[ \t\r\n]*")
4556 (replace-match "\n\n")))
4557 ;; No specific heading, just go to end of file.
4558 (goto-char (point-max)) (insert "\n"))
4559 ;; Paste
4560 (org-paste-subtree (1+ level))
4561 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4562 (if org-archive-mark-done
4563 (org-todo (length org-todo-keywords)))
4564 ;; Move cursor to right after the TODO keyword
4565 (when org-archive-stamp-time
4566 (beginning-of-line 1)
4567 (looking-at org-todo-line-regexp)
4568 (goto-char (or (match-end 2) (match-beginning 3)))
4569 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4570 (org-current-time))
4571 ")"))
4572 ;; Save the buffer, if it is not the same buffer.
4573 (if (not (eq this-buffer buffer)) (save-buffer))))
4574 ;; Here we are back in the original buffer. Everything seems to have
4575 ;; worked. So now cut the tree and finish up.
4576 (let (this-command) (org-cut-subtree))
4577 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4578 (message "Subtree archived %s"
4579 (if (eq this-buffer buffer)
4580 (concat "under heading: " heading)
4581 (concat "in file: " (abbreviate-file-name file)))))))
4582
4583 (defun org-archive-all-done (&optional tag)
4584 "Archive sublevels of the current tree without open TODO items.
4585 If the cursor is not on a headline, try all level 1 trees. If
4586 it is on a headline, try all direct children.
4587 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
4588 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4589 (rea (concat ".*:" org-archive-tag ":"))
4590 (begm (make-marker))
4591 (endm (make-marker))
4592 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
4593 "Move subtree to archive (no open TODO items)? "))
4594 beg end (cntarch 0))
4595 (if (org-on-heading-p)
4596 (progn
4597 (setq re1 (concat "^" (regexp-quote
4598 (make-string
4599 (1+ (- (match-end 0) (match-beginning 0)))
4600 ?*))
4601 " "))
4602 (move-marker begm (point))
4603 (move-marker endm (org-end-of-subtree)))
4604 (setq re1 "^* ")
4605 (move-marker begm (point-min))
4606 (move-marker endm (point-max)))
4607 (save-excursion
4608 (goto-char begm)
4609 (while (re-search-forward re1 endm t)
4610 (setq beg (match-beginning 0)
4611 end (save-excursion (org-end-of-subtree t) (point)))
4612 (goto-char beg)
4613 (if (re-search-forward re end t)
4614 (goto-char end)
4615 (goto-char beg)
4616 (if (and (or (not tag) (not (looking-at rea)))
4617 (y-or-n-p question))
4618 (progn
4619 (if tag
4620 (org-toggle-tag org-archive-tag 'on)
4621 (org-archive-subtree))
4622 (setq cntarch (1+ cntarch)))
4623 (goto-char end)))))
4624 (message "%d trees archived" cntarch)))
4625
4626 (defun org-cycle-hide-archived-subtrees (state)
4627 "Re-hide all archived subtrees after a visibility state change."
4628 (when (and (not org-cycle-open-archived-trees)
4629 (not (memq state '(overview folded))))
4630 (save-excursion
4631 (let* ((globalp (memq state '(contents all)))
4632 (beg (if globalp (point-min) (point)))
4633 (end (if globalp (point-max) (org-end-of-subtree))))
4634 (org-hide-archived-subtrees beg end)))))
4635
4636 (defun org-hide-archived-subtrees (beg end)
4637 "Re-hide all archived subtrees after a visibility state change."
4638 (save-excursion
4639 (let* ((re (concat ":" org-archive-tag ":")))
4640 (goto-char beg)
4641 (while (re-search-forward re end t)
4642 (and (org-on-heading-p) (hide-subtree))
4643 (org-end-of-subtree)))))
4644
4645 (defun org-toggle-tag (tag &optional onoff)
4646 "Toggle the tag TAG for the current line.
4647 If ONOFF is `on' or `off', don't toggle but set to this state."
4648 (unless (org-on-heading-p) (error "Not on headling"))
4649 (let (res current)
4650 (save-excursion
4651 (beginning-of-line)
4652 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
4653 (point-at-eol) t)
4654 (progn
4655 (setq current (match-string 1))
4656 (replace-match ""))
4657 (setq current ""))
4658 (setq current (nreverse (org-split-string current ":")))
4659 (cond
4660 ((eq onoff 'on)
4661 (setq res t)
4662 (or (member tag current) (push tag current)))
4663 ((eq onoff 'off)
4664 (or (not (member tag current)) (setq current (delete tag current))))
4665 (t (if (member tag current)
4666 (setq current (delete tag current))
4667 (setq res t)
4668 (push tag current))))
4669 (end-of-line 1)
4670 (when current
4671 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
4672 (org-set-tags nil t))
4673 res))
4674
4675 (defun org-toggle-archive-tag (&optional arg)
4676 "Toggle the archive tag for the current headline.
4677 With prefix ARG, check all children of current headline and offer tagging
4678 the children that do not contain any open TODO items."
4679 (interactive "P")
4680 (if arg
4681 (org-archive-all-done 'tag)
4682 (let (set)
4683 (save-excursion
4684 (org-back-to-heading t)
4685 (setq set (org-toggle-tag org-archive-tag))
4686 (when set (hide-subtree)))
4687 (and set (beginning-of-line 1))
4688 (message "Subtree %s" (if set "archived" "unarchived")))))
4689
4690 (defun org-prepare-agenda-buffers (files)
4691 "Create buffers for all agenda files, protect archived trees and comments."
4692 (interactive)
4693 (let ((pa '(:org-archived t))
4694 (pc '(:org-comment t))
4695 (pall '(:org-archived t :org-comment t))
4696 (rea (concat ":" org-archive-tag ":"))
4697 file re)
4698 (save-excursion
4699 (while (setq file (pop files))
4700 (org-check-agenda-file file)
4701 (set-buffer (org-get-agenda-file-buffer file))
4702 (widen)
4703 (save-excursion
4704 (remove-text-properties (point-min) (point-max) pall)
4705 (when org-agenda-skip-archived-trees
4706 (goto-char (point-min))
4707 (while (re-search-forward rea nil t)
4708 (if (org-on-heading-p)
4709 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
4710 (goto-char (point-min))
4711 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
4712 (while (re-search-forward re nil t)
4713 (add-text-properties
4714 (match-beginning 0) (org-end-of-subtree t) pc)))))))
4715
4716 (defun org-agenda-skip ()
4717 "Throw to `:skip' in places that should be skipped."
4718 (let ((p (point-at-bol)))
4719 (and org-agenda-skip-archived-trees
4720 (get-text-property p :org-archived)
4721 (org-end-of-subtree)
4722 (throw :skip t))
4723 (and (get-text-property p :org-comment)
4724 (org-end-of-subtree)
4725 (throw :skip t))
4726 (if (equal (char-after p) ?#) (throw :skip t))))
4727
4728 (defun org-agenda-toggle-archive-tag ()
4729 "Toggle the archive tag for the current entry."
4730 (interactive)
4731 (org-agenda-check-no-diary)
4732 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
4733 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
4734 (org-agenda-error)))
4735 (buffer (marker-buffer hdmarker))
4736 (pos (marker-position hdmarker))
4737 (buffer-read-only nil)
4738 newhead)
4739 (with-current-buffer buffer
4740 (widen)
4741 (goto-char pos)
4742 (org-show-hidden-entry)
4743 (save-excursion
4744 (and (outline-next-heading)
4745 (org-flag-heading nil))) ; show the next heading
4746 (call-interactively 'org-toggle-archive-tag)
4747 (end-of-line 1)
4748 (setq newhead (org-get-heading)))
4749 (org-agenda-change-all-lines newhead hdmarker)
4750 (beginning-of-line 1)))
4751
4752 ;;; Dynamic blocks
4753
4754 (defun org-find-dblock (name)
4755 "Find the first dynamic block with name NAME in the buffer.
4756 If not found, stay at current position and return nil."
4757 (let (pos)
4758 (save-excursion
4759 (goto-char (point-min))
4760 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
4761 nil t)
4762 (match-beginning 0))))
4763 (if pos (goto-char pos))
4764 pos))
4765
4766 (defconst org-dblock-start-re
4767 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)[ \t]+\\(.*\\)"
4768 "Matches the startline of a dynamic block, with parameters.")
4769
4770 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
4771 "Matches the end of a dyhamic block.")
4772
4773 (defun org-create-dblock (plist)
4774 "Create a dynamic block section, with parameters taken from PLIST.
4775 PLIST must containe a :name entry which is used as name of the block."
4776 (unless (bolp) (newline))
4777 (let ((name (plist-get plist :name)))
4778 (insert "#+BEGIN: " name)
4779 (while plist
4780 (if (eq (car plist) :name)
4781 (setq plist (cddr plist))
4782 (insert " " (prin1-to-string (pop plist)))))
4783 (insert "\n\n#+END:\n")
4784 (beginning-of-line -2)))
4785
4786 (defun org-prepare-dblock ()
4787 "Prepare dynamic block for refresh.
4788 This empties the block, puts the cursor at the insert position and returns
4789 the property list including an extra property :name with the block name."
4790 (unless (looking-at org-dblock-start-re)
4791 (error "Not at a dynamic block"))
4792 (let* ((begdel (1+ (match-end 0)))
4793 (name (match-string 1))
4794 (params (append (list :name name)
4795 (read (concat "(" (match-string 2) ")")))))
4796 (unless (re-search-forward org-dblock-end-re nil t)
4797 (error "Dynamic block not terminated"))
4798 (delete-region begdel (match-beginning 0))
4799 (goto-char begdel)
4800 (open-line 1)
4801 params))
4802
4803 (defun org-map-dblocks (&optional command)
4804 "Apply COMMAND to all dynamic blocks in the current buffer.
4805 If COMMAND is not given, use `org-update-dblock'."
4806 (let ((cmd (or command 'org-update-dblock))
4807 pos)
4808 (save-excursion
4809 (goto-char (point-min))
4810 (while (re-search-forward org-dblock-start-re nil t)
4811 (goto-char (setq pos (match-beginning 0)))
4812 (condition-case nil
4813 (funcall cmd)
4814 (error (message "Error during update of dynamic block")))
4815 (goto-char pos)
4816 (unless (re-search-forward org-dblock-end-re nil t)
4817 (error "Dynamic block not terminated"))))))
4818
4819 (defun org-dblock-update (&optional arg)
4820 "User command for updating dynamic blocks.
4821 Update the dynamic block at point. With prefix ARG, update all dynamic
4822 blocks in the buffer."
4823 (interactive "P")
4824 (if arg
4825 (org-update-all-dblocks)
4826 (or (looking-at org-dblock-start-re)
4827 (org-beginning-of-dblock))
4828 (org-update-dblock)))
4829
4830 (defun org-update-dblock ()
4831 "Update the dynamic block at point
4832 This means to empty the block, parse for parameters and then call
4833 the correct writing function."
4834 (let* ((pos (point))
4835 (params (org-prepare-dblock))
4836 (name (plist-get params :name))
4837 (cmd (intern (concat "org-dblock-write:" name))))
4838 (funcall cmd params)
4839 (goto-char pos)))
4840
4841 (defun org-beginning-of-dblock ()
4842 "Find the beginning of the dynamic block at point.
4843 Error if there is no scuh block at point."
4844 (let ((pos (point))
4845 beg)
4846 (end-of-line 1)
4847 (if (and (re-search-backward org-dblock-start-re nil t)
4848 (setq beg (match-beginning 0))
4849 (re-search-forward org-dblock-end-re nil t)
4850 (> (match-end 0) pos))
4851 (goto-char beg)
4852 (goto-char pos)
4853 (error "Not in a dynamic block"))))
4854
4855 (defun org-update-all-dblocks ()
4856 "Update all dynamic blocks in the buffer.
4857 This function can be used in a hook."
4858 (when (eq major-mode 'org-mode)
4859 (org-map-dblocks 'org-update-dblock)))
4860
4861
4862 ;;; Completion
4863
4864 (defun org-complete (&optional arg)
4865 "Perform completion on word at point.
4866 At the beginning of a headline, this completes TODO keywords as given in
4867 `org-todo-keywords'.
4868 If the current word is preceded by a backslash, completes the TeX symbols
4869 that are supported for HTML support.
4870 If the current word is preceded by \"#+\", completes special words for
4871 setting file options.
4872 At all other locations, this simply calls `ispell-complete-word'."
4873 (interactive "P")
4874 (catch 'exit
4875 (let* ((end (point))
4876 (beg1 (save-excursion
4877 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4878 (skip-chars-backward "a-zA-Z_@0-9")
4879 (point)))
4880 (beg (save-excursion
4881 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4882 (skip-chars-backward "a-zA-Z0-9_:$")
4883 (point)))
4884 (confirm (lambda (x) (stringp (car x))))
4885 (camel (equal (char-before beg) ?*))
4886 (tag (equal (char-before beg1) ?:))
4887 (texp (equal (char-before beg) ?\\))
4888 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
4889 beg)
4890 "#+"))
4891 (completion-ignore-case opt)
4892 (type nil)
4893 (tbl nil)
4894 (table (cond
4895 (opt
4896 (setq type :opt)
4897 (mapcar (lambda (x)
4898 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
4899 (cons (match-string 2 x) (match-string 1 x)))
4900 (org-split-string (org-get-current-options) "\n")))
4901 (texp
4902 (setq type :tex)
4903 org-html-entities)
4904 ((string-match "\\`\\*+[ \t]*\\'"
4905 (buffer-substring (point-at-bol) beg))
4906 (setq type :todo)
4907 (mapcar 'list org-todo-keywords))
4908 (camel
4909 (setq type :camel)
4910 (save-excursion
4911 (goto-char (point-min))
4912 (while (re-search-forward org-todo-line-regexp nil t)
4913 (push (list
4914 (if org-file-link-context-use-camel-case
4915 (org-make-org-heading-camel (match-string 3) t)
4916 (org-make-org-heading-search-string
4917 (match-string 3) t)))
4918 tbl)))
4919 tbl)
4920 (tag (setq type :tag beg beg1)
4921 (or org-tag-alist (org-get-buffer-tags)))
4922 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
4923 (pattern (buffer-substring-no-properties beg end))
4924 (completion (try-completion pattern table confirm)))
4925 (cond ((eq completion t)
4926 (if (equal type :opt)
4927 (insert (substring (cdr (assoc (upcase pattern) table))
4928 (length pattern)))))
4929 ((null completion)
4930 (message "Can't find completion for \"%s\"" pattern)
4931 (ding))
4932 ((not (string= pattern completion))
4933 (delete-region beg end)
4934 (if (string-match " +$" completion)
4935 (setq completion (replace-match "" t t completion)))
4936 (insert completion)
4937 (if (get-buffer-window "*Completions*")
4938 (delete-window (get-buffer-window "*Completions*")))
4939 (if (assoc completion table)
4940 (if (eq type :todo) (insert " ")
4941 (if (eq type :tag) (insert ":"))))
4942 (if (and (equal type :opt) (assoc completion table))
4943 (message "%s" (substitute-command-keys
4944 "Press \\[org-complete] again to insert example settings"))))
4945 (t
4946 (message "Making completion list...")
4947 (let ((list (sort (all-completions pattern table confirm)
4948 'string<)))
4949 (with-output-to-temp-buffer "*Completions*"
4950 (condition-case nil
4951 ;; Protection needed for XEmacs and emacs 21
4952 (display-completion-list list pattern)
4953 (error (display-completion-list list)))))
4954 (message "Making completion list...%s" "done"))))))
4955
4956 ;;; Comments, TODO and DEADLINE
4957
4958 (defun org-toggle-comment ()
4959 "Change the COMMENT state of an entry."
4960 (interactive)
4961 (save-excursion
4962 (org-back-to-heading)
4963 (if (looking-at (concat outline-regexp
4964 "\\( +\\<" org-comment-string "\\>\\)"))
4965 (replace-match "" t t nil 1)
4966 (if (looking-at outline-regexp)
4967 (progn
4968 (goto-char (match-end 0))
4969 (insert " " org-comment-string))))))
4970
4971 (defvar org-last-todo-state-is-todo nil
4972 "This is non-nil when the last TODO state change led to a TODO state.
4973 If the last change removed the TODO tag or switched to DONE, then
4974 this is nil.")
4975
4976 (defun org-todo (&optional arg)
4977 "Change the TODO state of an item.
4978 The state of an item is given by a keyword at the start of the heading,
4979 like
4980 *** TODO Write paper
4981 *** DONE Call mom
4982
4983 The different keywords are specified in the variable `org-todo-keywords'.
4984 By default the available states are \"TODO\" and \"DONE\".
4985 So for this example: when the item starts with TODO, it is changed to DONE.
4986 When it starts with DONE, the DONE is removed. And when neither TODO nor
4987 DONE are present, add TODO at the beginning of the heading.
4988
4989 With prefix arg, use completion to determine the new state. With numeric
4990 prefix arg, switch to that state."
4991 (interactive "P")
4992 (save-excursion
4993 (org-back-to-heading)
4994 (if (looking-at outline-regexp) (goto-char (match-end 0)))
4995 (or (looking-at (concat " +" org-todo-regexp " *"))
4996 (looking-at " *"))
4997 (let* ((this (match-string 1))
4998 (completion-ignore-case t)
4999 (member (member this org-todo-keywords))
5000 (tail (cdr member))
5001 (state (cond
5002 ((equal arg '(4))
5003 ;; Read a state with completion
5004 (completing-read "State: " (mapcar (lambda(x) (list x))
5005 org-todo-keywords)
5006 nil t))
5007 ((eq arg 'right)
5008 (if this
5009 (if tail (car tail) nil)
5010 (car org-todo-keywords)))
5011 ((eq arg 'left)
5012 (if (equal member org-todo-keywords)
5013 nil
5014 (if this
5015 (nth (- (length org-todo-keywords) (length tail) 2)
5016 org-todo-keywords)
5017 org-done-string)))
5018 (arg
5019 ;; user requests a specific state
5020 (nth (1- (prefix-numeric-value arg))
5021 org-todo-keywords))
5022 ((null member) (car org-todo-keywords))
5023 ((null tail) nil) ;; -> first entry
5024 ((eq org-todo-interpretation 'sequence)
5025 (car tail))
5026 ((memq org-todo-interpretation '(type priority))
5027 (if (eq this-command last-command)
5028 (car tail)
5029 (if (> (length tail) 0) org-done-string nil)))
5030 (t nil)))
5031 (next (if state (concat " " state " ") " ")))
5032 (replace-match next t t)
5033 (setq org-last-todo-state-is-todo
5034 (not (equal state org-done-string)))
5035 (when org-log-done
5036 (if (equal state org-done-string)
5037 (org-add-planning-info 'closed (current-time) 'scheduled)
5038 (if (not this)
5039 (org-add-planning-info nil nil 'closed))))
5040 ;; Fixup tag positioning
5041 (and org-auto-align-tags (org-set-tags nil t))
5042 (run-hooks 'org-after-todo-state-change-hook)))
5043 ;; Fixup cursor location if close to the keyword
5044 (if (and (outline-on-heading-p)
5045 (not (bolp))
5046 (save-excursion (beginning-of-line 1)
5047 (looking-at org-todo-line-regexp))
5048 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5049 (progn
5050 (goto-char (or (match-end 2) (match-end 1)))
5051 (just-one-space))))
5052
5053 (defun org-log-done (&optional undone)
5054 "Add a time stamp logging that a TODO entry has been closed.
5055 When UNDONE is non-nil, remove such a time stamp again."
5056 (interactive)
5057 (let (beg end col)
5058 (save-excursion
5059 (org-back-to-heading t)
5060 (setq beg (point))
5061 (looking-at (concat outline-regexp " *"))
5062 (goto-char (match-end 0))
5063 (setq col (current-column))
5064 (outline-next-heading)
5065 (setq end (point))
5066 (goto-char beg)
5067 (when (re-search-forward (concat
5068 "[\r\n]\\([ \t]*"
5069 (regexp-quote org-closed-string)
5070 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
5071 (delete-region (match-beginning 1) (match-end 1)))
5072 (unless undone
5073 (org-back-to-heading t)
5074 (skip-chars-forward "^\n\r")
5075 (goto-char (min (1+ (point)) (point-max)))
5076 (when (not (member (char-before) '(?\r ?\n)))
5077 (insert "\n"))
5078 (indent-to col)
5079 (insert org-closed-string " "
5080 (format-time-string
5081 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5082 (org-current-time))
5083 "\n")))))
5084
5085 (defun org-show-todo-tree (arg)
5086 "Make a compact tree which shows all headlines marked with TODO.
5087 The tree will show the lines where the regexp matches, and all higher
5088 headlines above the match.
5089 With \\[universal-argument] prefix, also show the DONE entries.
5090 With a numeric prefix N, construct a sparse tree for the Nth element
5091 of `org-todo-keywords'."
5092 (interactive "P")
5093 (let ((case-fold-search nil)
5094 (kwd-re
5095 (cond ((null arg) org-not-done-regexp)
5096 ((equal arg '(4)) org-todo-regexp)
5097 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5098 (regexp-quote (nth (1- (prefix-numeric-value arg))
5099 org-todo-keywords)))
5100 (t (error "Invalid prefix argument: %s" arg)))))
5101 (message "%d TODO entries found"
5102 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5103
5104 (defun org-deadline ()
5105 "Insert the DEADLINE: string to make a deadline.
5106 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5107 to modify it to the correct date."
5108 (interactive)
5109 (org-add-planning-info 'deadline nil 'closed))
5110
5111 (defun org-schedule ()
5112 "Insert the SCHEDULED: string to schedule a TODO item.
5113 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5114 to modify it to the correct date."
5115 (interactive)
5116 (org-add-planning-info 'scheduled nil 'closed))
5117
5118 (defun org-add-planning-info (what &optional time &rest remove)
5119 "Insert new timestamp with keyword in the line directly after the headline.
5120 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5121 If non is given, the user is prompted for a date.
5122 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5123 be removed."
5124 (interactive)
5125 (when what (setq time (or time (org-read-date nil 'to-time))))
5126 (when (and org-insert-labeled-timestamps-at-point
5127 (member what '(scheduled deadline)))
5128 (insert
5129 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
5130 " "
5131 (format-time-string (car org-time-stamp-formats) time))
5132 (setq what nil))
5133 (save-excursion
5134 (let (col list elt (buffer-invisibility-spec nil) ts)
5135 (org-back-to-heading t)
5136 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5137 (goto-char (match-end 1))
5138 (setq col (current-column))
5139 (goto-char (1+ (match-end 0)))
5140 (if (and (not (looking-at outline-regexp))
5141 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5142 "[^\r\n]*"))
5143 (not (equal (match-string 1) org-clock-string)))
5144 (narrow-to-region (match-beginning 0) (match-end 0))
5145 (insert "\n")
5146 (backward-char 1)
5147 (narrow-to-region (point) (point))
5148 (indent-to-column col))
5149 ;; Check if we have to remove something.
5150 (setq list (cons what remove))
5151 (while list
5152 (setq elt (pop list))
5153 (goto-char (point-min))
5154 (when (or (and (eq elt 'scheduled)
5155 (re-search-forward org-scheduled-time-regexp nil t))
5156 (and (eq elt 'deadline)
5157 (re-search-forward org-deadline-time-regexp nil t))
5158 (and (eq elt 'closed)
5159 (re-search-forward org-closed-time-regexp nil t)))
5160 (replace-match "")
5161 (if (looking-at " +") (replace-match ""))))
5162 (goto-char (point-max))
5163 (when what
5164 (insert
5165 (if (not (equal (char-before) ?\ )) " " "")
5166 (cond ((eq what 'scheduled) org-scheduled-string)
5167 ((eq what 'deadline) org-deadline-string)
5168 ((eq what 'closed) org-closed-string))
5169 " ")
5170 (insert
5171 (setq ts
5172 (format-time-string
5173 (if (eq what 'closed)
5174 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5175 (car org-time-stamp-formats))
5176 time))))
5177 (goto-char (point-min))
5178 (widen)
5179 (if (looking-at "[ \t]+\r?\n")
5180 (replace-match ""))
5181 ts)))
5182
5183 (defun org-occur (regexp &optional callback)
5184 "Make a compact tree which shows all matches of REGEXP.
5185 The tree will show the lines where the regexp matches, and all higher
5186 headlines above the match. It will also show the heading after the match,
5187 to make sure editing the matching entry is easy.
5188 If CALLBACK is non-nil, it is a function which is called to confirm
5189 that the match should indeed be shown."
5190 (interactive "sRegexp: ")
5191 (org-remove-occur-highlights nil nil t)
5192 (setq regexp (org-check-occur-regexp regexp))
5193 (let ((cnt 0))
5194 (save-excursion
5195 (goto-char (point-min))
5196 (org-overview)
5197 (while (re-search-forward regexp nil t)
5198 (when (or (not callback)
5199 (save-match-data (funcall callback)))
5200 (setq cnt (1+ cnt))
5201 (org-highlight-new-match (match-beginning 0) (match-end 0))
5202 (org-show-hierarchy-above))))
5203 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5204 nil 'local)
5205 (unless org-sparse-tree-open-archived-trees
5206 (org-hide-archived-subtrees (point-min) (point-max)))
5207 (run-hooks 'org-occur-hook)
5208 (if (interactive-p)
5209 (message "%d match(es) for regexp %s" cnt regexp))
5210 cnt))
5211
5212 (defun org-show-hierarchy-above ()
5213 "Make sure point and the headings hierarchy above is visible."
5214 (catch 'exit
5215 (if (org-on-heading-p t)
5216 (org-flag-heading nil) ; only show the heading
5217 (and (or (org-invisible-p) (org-invisible-p2))
5218 (org-show-hidden-entry))) ; show entire entry
5219 (save-excursion
5220 (and org-show-following-heading
5221 (outline-next-heading)
5222 (org-flag-heading nil))) ; show the next heading
5223 (when org-show-hierarchy-above
5224 (save-excursion ; show all higher headings
5225 (while (and (condition-case nil
5226 (progn (org-up-heading-all 1) t)
5227 (error nil))
5228 (not (bobp)))
5229 (org-flag-heading nil))))))
5230
5231 ;; Overlay compatibility functions
5232 (defun org-make-overlay (beg end &optional buffer)
5233 (if (featurep 'xemacs)
5234 (make-extent beg end buffer)
5235 (make-overlay beg end buffer)))
5236 (defun org-delete-overlay (ovl)
5237 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5238 (defun org-detatch-overlay (ovl)
5239 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5240 (defun org-move-overlay (ovl beg end &optional buffer)
5241 (if (featurep 'xemacs)
5242 (set-extent-endpoints ovl beg end buffer)
5243 (move-overlay ovl beg end buffer)))
5244 (defun org-overlay-put (ovl prop value)
5245 (if (featurep 'xemacs)
5246 (set-extent-property ovl prop value)
5247 (overlay-put ovl prop value)))
5248 (defun org-overlays-at (pos)
5249 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5250 (defun org-overlay-start (o)
5251 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5252 (defun org-overlay-end (o)
5253 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5254
5255 (defvar org-occur-highlights nil)
5256 (make-variable-buffer-local 'org-occur-highlights)
5257 (defun org-highlight-new-match (beg end)
5258 "Highlight from BEG to END and mark the highlight is an occur headline."
5259 (let ((ov (org-make-overlay beg end)))
5260 (org-overlay-put ov 'face 'secondary-selection)
5261 (push ov org-occur-highlights)))
5262
5263 (defvar org-inhibit-highlight-removal nil)
5264 (defun org-remove-occur-highlights (&optional beg end noremove)
5265 "Remove the occur highlights from the buffer.
5266 BEG and END are ignored. If NOREMOVE is nil, remove this function
5267 from the `before-change-functions' in the current buffer."
5268 (interactive)
5269 (unless org-inhibit-highlight-removal
5270 (mapc 'org-delete-overlay org-occur-highlights)
5271 (setq org-occur-highlights nil)
5272 (unless noremove
5273 (remove-hook 'before-change-functions
5274 'org-remove-occur-highlights 'local))))
5275
5276 ;;; Priorities
5277
5278 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5279 "Regular expression matching the priority indicator.")
5280
5281 (defvar org-remove-priority-next-time nil)
5282
5283 (defun org-priority-up ()
5284 "Increase the priority of the current item."
5285 (interactive)
5286 (org-priority 'up))
5287
5288 (defun org-priority-down ()
5289 "Decrease the priority of the current item."
5290 (interactive)
5291 (org-priority 'down))
5292
5293 (defun org-priority (&optional action)
5294 "Change the priority of an item by ARG.
5295 ACTION can be set, up, or down."
5296 (interactive)
5297 (setq action (or action 'set))
5298 (let (current new news have remove)
5299 (save-excursion
5300 (org-back-to-heading)
5301 (if (looking-at org-priority-regexp)
5302 (setq current (string-to-char (match-string 2))
5303 have t)
5304 (setq current org-default-priority))
5305 (cond
5306 ((eq action 'set)
5307 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5308 (setq new (read-char-exclusive))
5309 (cond ((equal new ?\ ) (setq remove t))
5310 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5311 (error "Priority must be between `%c' and `%c'"
5312 ?A org-lowest-priority))))
5313 ((eq action 'up)
5314 (setq new (1- current)))
5315 ((eq action 'down)
5316 (setq new (1+ current)))
5317 (t (error "Invalid action")))
5318 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5319 (setq news (format "%c" new))
5320 (if have
5321 (if remove
5322 (replace-match "" t t nil 1)
5323 (replace-match news t t nil 2))
5324 (if remove
5325 (error "No priority cookie found in line")
5326 (looking-at org-todo-line-regexp)
5327 (if (match-end 2)
5328 (progn
5329 (goto-char (match-end 2))
5330 (insert " [#" news "]"))
5331 (goto-char (match-beginning 3))
5332 (insert "[#" news "] ")))))
5333 (if remove
5334 (message "Priority removed")
5335 (message "Priority of current item set to %s" news))))
5336
5337
5338 (defun org-get-priority (s)
5339 "Find priority cookie and return priority."
5340 (save-match-data
5341 (if (not (string-match org-priority-regexp s))
5342 (* 1000 (- org-lowest-priority org-default-priority))
5343 (* 1000 (- org-lowest-priority
5344 (string-to-char (match-string 2 s)))))))
5345
5346 ;;; Timestamps
5347
5348 (defvar org-last-changed-timestamp nil)
5349
5350 (defun org-time-stamp (arg)
5351 "Prompt for a date/time and insert a time stamp.
5352 If the user specifies a time like HH:MM, or if this command is called
5353 with a prefix argument, the time stamp will contain date and time.
5354 Otherwise, only the date will be included. All parts of a date not
5355 specified by the user will be filled in from the current date/time.
5356 So if you press just return without typing anything, the time stamp
5357 will represent the current date/time. If there is already a timestamp
5358 at the cursor, it will be modified."
5359 (interactive "P")
5360 (let ((fmt (if arg (cdr org-time-stamp-formats)
5361 (car org-time-stamp-formats)))
5362 (org-time-was-given nil)
5363 time)
5364 (cond
5365 ((and (org-at-timestamp-p)
5366 (eq last-command 'org-time-stamp)
5367 (eq this-command 'org-time-stamp))
5368 (insert "--")
5369 (setq time (let ((this-command this-command))
5370 (org-read-date arg 'totime)))
5371 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5372 (insert (format-time-string fmt time)))
5373 ((org-at-timestamp-p)
5374 (setq time (let ((this-command this-command))
5375 (org-read-date arg 'totime)))
5376 (and (org-at-timestamp-p) (replace-match
5377 (setq org-last-changed-timestamp
5378 (format-time-string fmt time))
5379 t t))
5380 (message "Timestamp updated"))
5381 (t
5382 (setq time (let ((this-command this-command))
5383 (org-read-date arg 'totime)))
5384 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5385 (insert (format-time-string fmt time))))))
5386
5387 (defun org-time-stamp-inactive (&optional arg)
5388 "Insert an inactive time stamp.
5389 An inactive time stamp is enclosed in square brackets instead of angle
5390 brackets. It is inactive in the sense that it does not trigger agenda entries,
5391 does not link to the calendar and cannot be changed with the S-cursor keys.
5392 So these are more for recording a certain time/date."
5393 (interactive "P")
5394 (let ((fmt (if arg (cdr org-time-stamp-formats)
5395 (car org-time-stamp-formats)))
5396 (org-time-was-given nil)
5397 time)
5398 (setq time (org-read-date arg 'totime))
5399 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5400 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
5401 (insert (format-time-string fmt time))))
5402
5403 (defvar org-date-ovl (org-make-overlay 1 1))
5404 (org-overlay-put org-date-ovl 'face 'org-warning)
5405 (org-detatch-overlay org-date-ovl)
5406
5407 (defun org-read-date (&optional with-time to-time)
5408 "Read a date and make things smooth for the user.
5409 The prompt will suggest to enter an ISO date, but you can also enter anything
5410 which will at least partially be understood by `parse-time-string'.
5411 Unrecognized parts of the date will default to the current day, month, year,
5412 hour and minute. For example,
5413 3-2-5 --> 2003-02-05
5414 feb 15 --> currentyear-02-15
5415 sep 12 9 --> 2009-09-12
5416 12:45 --> today 12:45
5417 22 sept 0:34 --> currentyear-09-22 0:34
5418 12 --> currentyear-currentmonth-12
5419 Fri --> nearest Friday (today or later)
5420 etc.
5421 The function understands only English month and weekday abbreviations,
5422 but this can be configured with the variables `parse-time-months' and
5423 `parse-time-weekdays'.
5424
5425 While prompting, a calendar is popped up - you can also select the
5426 date with the mouse (button 1). The calendar shows a period of three
5427 months. To scroll it to other months, use the keys `>' and `<'.
5428 If you don't like the calendar, turn it off with
5429 \(setq org-popup-calendar-for-date-prompt nil)
5430
5431 With optional argument TO-TIME, the date will immediately be converted
5432 to an internal time.
5433 With an optional argument WITH-TIME, the prompt will suggest to also
5434 insert a time. Note that when WITH-TIME is not set, you can still
5435 enter a time, and this function will inform the calling routine about
5436 this change. The calling routine may then choose to change the format
5437 used to insert the time stamp into the buffer to include the time."
5438 (require 'parse-time)
5439 (let* ((org-time-stamp-rounding-minutes
5440 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5441 (ct (org-current-time))
5442 (default-time
5443 ;; Default time is either today, or, when entering a range,
5444 ;; the range start.
5445 (if (save-excursion
5446 (re-search-backward
5447 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5448 (- (point) 20) t))
5449 (apply
5450 'encode-time
5451 (mapcar (lambda(x) (or x 0))
5452 (parse-time-string (match-string 1))))
5453 ct))
5454 (calendar-move-hook nil)
5455 (view-diary-entries-initially nil)
5456 (view-calendar-holidays-initially nil)
5457 (timestr (format-time-string
5458 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5459 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5460 ans ans1 ans2
5461 second minute hour day month year tl wday wday1)
5462
5463 (if org-popup-calendar-for-date-prompt
5464 (save-excursion
5465 (save-window-excursion
5466 (calendar)
5467 (calendar-forward-day (- (time-to-days default-time)
5468 (calendar-absolute-from-gregorian
5469 (calendar-current-date))))
5470 (org-eval-in-calendar nil)
5471 (let* ((old-map (current-local-map))
5472 (map (copy-keymap calendar-mode-map))
5473 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5474 (define-key map (kbd "RET") 'org-calendar-select)
5475 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5476 'org-calendar-select-mouse)
5477 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5478 'org-calendar-select-mouse)
5479 (define-key minibuffer-local-map [(meta shift left)]
5480 (lambda () (interactive)
5481 (org-eval-in-calendar '(calendar-backward-month 1))))
5482 (define-key minibuffer-local-map [(meta shift right)]
5483 (lambda () (interactive)
5484 (org-eval-in-calendar '(calendar-forward-month 1))))
5485 (define-key minibuffer-local-map [(shift up)]
5486 (lambda () (interactive)
5487 (org-eval-in-calendar '(calendar-backward-week 1))))
5488 (define-key minibuffer-local-map [(shift down)]
5489 (lambda () (interactive)
5490 (org-eval-in-calendar '(calendar-forward-week 1))))
5491 (define-key minibuffer-local-map [(shift left)]
5492 (lambda () (interactive)
5493 (org-eval-in-calendar '(calendar-backward-day 1))))
5494 (define-key minibuffer-local-map [(shift right)]
5495 (lambda () (interactive)
5496 (org-eval-in-calendar '(calendar-forward-day 1))))
5497 (define-key minibuffer-local-map ">"
5498 (lambda () (interactive)
5499 (org-eval-in-calendar '(scroll-calendar-left 1))))
5500 (define-key minibuffer-local-map "<"
5501 (lambda () (interactive)
5502 (org-eval-in-calendar '(scroll-calendar-right 1))))
5503 (unwind-protect
5504 (progn
5505 (use-local-map map)
5506 (setq ans (read-string prompt "" nil nil))
5507 (if (not (string-match "\\S-" ans)) (setq ans nil))
5508 (setq ans (or ans1 ans ans2)))
5509 (use-local-map old-map)))))
5510 ;; Naked prompt only
5511 (setq ans (read-string prompt "" nil timestr)))
5512 (org-detatch-overlay org-date-ovl)
5513
5514 (if (string-match
5515 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5516 (progn
5517 (setq year (if (match-end 2)
5518 (string-to-number (match-string 2 ans))
5519 (string-to-number (format-time-string "%Y")))
5520 month (string-to-number (match-string 3 ans))
5521 day (string-to-number (match-string 4 ans)))
5522 (if (< year 100) (setq year (+ 2000 year)))
5523 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
5524 t nil ans))))
5525 (setq tl (parse-time-string ans)
5526 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
5527 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
5528 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
5529 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
5530 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
5531 second (or (nth 0 tl) 0)
5532 wday (nth 6 tl))
5533 (when (and wday (not (nth 3 tl)))
5534 ;; Weekday was given, but no day, so pick that day in the week
5535 ;; on or after the derived date.
5536 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
5537 (unless (equal wday wday1)
5538 (setq day (+ day (% (- wday wday1 -7) 7)))))
5539 (if (and (boundp 'org-time-was-given)
5540 (nth 2 tl))
5541 (setq org-time-was-given t))
5542 (if (< year 100) (setq year (+ 2000 year)))
5543 (if to-time
5544 (encode-time second minute hour day month year)
5545 (if (or (nth 1 tl) (nth 2 tl))
5546 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
5547 (format "%04d-%02d-%02d" year month day)))))
5548
5549 (defun org-eval-in-calendar (form)
5550 "Eval FORM in the calendar window and return to current window.
5551 Also, store the cursor date in variable ans2."
5552 (let ((sw (selected-window)))
5553 (select-window (get-buffer-window "*Calendar*"))
5554 (eval form)
5555 (when (calendar-cursor-to-date)
5556 (let* ((date (calendar-cursor-to-date))
5557 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5558 (setq ans2 (format-time-string "%Y-%m-%d" time))))
5559 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
5560 (select-window sw)))
5561
5562 (defun org-calendar-select ()
5563 "Return to `org-read-date' with the date currently selected.
5564 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5565 (interactive)
5566 (when (calendar-cursor-to-date)
5567 (let* ((date (calendar-cursor-to-date))
5568 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5569 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5570 (if (active-minibuffer-window) (exit-minibuffer))))
5571
5572 (defun org-calendar-select-mouse (ev)
5573 "Return to `org-read-date' with the date currently selected.
5574 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5575 (interactive "e")
5576 (mouse-set-point ev)
5577 (when (calendar-cursor-to-date)
5578 (let* ((date (calendar-cursor-to-date))
5579 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5580 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5581 (if (active-minibuffer-window) (exit-minibuffer))))
5582
5583 (defun org-check-deadlines (ndays)
5584 "Check if there are any deadlines due or past due.
5585 A deadline is considered due if it happens within `org-deadline-warning-days'
5586 days from today's date. If the deadline appears in an entry marked DONE,
5587 it is not shown. The prefix arg NDAYS can be used to test that many
5588 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
5589 (interactive "P")
5590 (let* ((org-warn-days
5591 (cond
5592 ((equal ndays '(4)) 100000)
5593 (ndays (prefix-numeric-value ndays))
5594 (t org-deadline-warning-days)))
5595 (case-fold-search nil)
5596 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
5597 (callback
5598 (lambda ()
5599 (and (let ((d1 (time-to-days (current-time)))
5600 (d2 (time-to-days
5601 (org-time-string-to-time (match-string 1)))))
5602 (< (- d2 d1) org-warn-days))
5603 (not (org-entry-is-done-p))))))
5604 (message "%d deadlines past-due or due within %d days"
5605 (org-occur regexp callback)
5606 org-warn-days)))
5607
5608 (defun org-evaluate-time-range (&optional to-buffer)
5609 "Evaluate a time range by computing the difference between start and end.
5610 Normally the result is just printed in the echo area, but with prefix arg
5611 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
5612 If the time range is actually in a table, the result is inserted into the
5613 next column.
5614 For time difference computation, a year is assumed to be exactly 365
5615 days in order to avoid rounding problems."
5616 (interactive "P")
5617 (save-excursion
5618 (unless (org-at-date-range-p)
5619 (goto-char (point-at-bol))
5620 (re-search-forward org-tr-regexp (point-at-eol) t))
5621 (if (not (org-at-date-range-p))
5622 (error "Not at a time-stamp range, and none found in current line")))
5623 (let* ((ts1 (match-string 1))
5624 (ts2 (match-string 2))
5625 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
5626 (match-end (match-end 0))
5627 (time1 (org-time-string-to-time ts1))
5628 (time2 (org-time-string-to-time ts2))
5629 (t1 (time-to-seconds time1))
5630 (t2 (time-to-seconds time2))
5631 (diff (abs (- t2 t1)))
5632 (negative (< (- t2 t1) 0))
5633 ;; (ys (floor (* 365 24 60 60)))
5634 (ds (* 24 60 60))
5635 (hs (* 60 60))
5636 (fy "%dy %dd %02d:%02d")
5637 (fy1 "%dy %dd")
5638 (fd "%dd %02d:%02d")
5639 (fd1 "%dd")
5640 (fh "%02d:%02d")
5641 y d h m align)
5642 (if havetime
5643 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5644 y 0
5645 d (floor (/ diff ds)) diff (mod diff ds)
5646 h (floor (/ diff hs)) diff (mod diff hs)
5647 m (floor (/ diff 60)))
5648 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5649 y 0
5650 d (floor (+ (/ diff ds) 0.5))
5651 h 0 m 0))
5652 (if (not to-buffer)
5653 (message (org-make-tdiff-string y d h m))
5654 (when (org-at-table-p)
5655 (goto-char match-end)
5656 (setq align t)
5657 (and (looking-at " *|") (goto-char (match-end 0))))
5658 (if (looking-at
5659 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
5660 (replace-match ""))
5661 (if negative (insert " -"))
5662 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
5663 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
5664 (insert " " (format fh h m))))
5665 (if align (org-table-align))
5666 (message "Time difference inserted"))))
5667
5668 (defun org-make-tdiff-string (y d h m)
5669 (let ((fmt "")
5670 (l nil))
5671 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5672 l (push y l)))
5673 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5674 l (push d l)))
5675 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5676 l (push h l)))
5677 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5678 l (push m l)))
5679 (apply 'format fmt (nreverse l))))
5680
5681 (defun org-time-string-to-time (s)
5682 (apply 'encode-time (org-parse-time-string s)))
5683
5684 (defun org-parse-time-string (s &optional nodefault)
5685 "Parse the standard Org-mode time string.
5686 This should be a lot faster than the normal `parse-time-string'.
5687 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5688 hour and minute fields will be nil if not given."
5689 (if (string-match org-ts-regexp1 s)
5690 (list 0
5691 (if (or (match-beginning 8) (not nodefault))
5692 (string-to-number (or (match-string 8 s) "0")))
5693 (if (or (match-beginning 7) (not nodefault))
5694 (string-to-number (or (match-string 7 s) "0")))
5695 (string-to-number (match-string 4 s))
5696 (string-to-number (match-string 3 s))
5697 (string-to-number (match-string 2 s))
5698 nil nil nil)
5699 (make-list 9 0)))
5700
5701 (defun org-timestamp-up (&optional arg)
5702 "Increase the date item at the cursor by one.
5703 If the cursor is on the year, change the year. If it is on the month or
5704 the day, change that.
5705 With prefix ARG, change by that many units."
5706 (interactive "p")
5707 (org-timestamp-change (prefix-numeric-value arg)))
5708
5709 (defun org-timestamp-down (&optional arg)
5710 "Decrease the date item at the cursor by one.
5711 If the cursor is on the year, change the year. If it is on the month or
5712 the day, change that.
5713 With prefix ARG, change by that many units."
5714 (interactive "p")
5715 (org-timestamp-change (- (prefix-numeric-value arg))))
5716
5717 (defun org-timestamp-up-day (&optional arg)
5718 "Increase the date in the time stamp by one day.
5719 With prefix ARG, change that many days."
5720 (interactive "p")
5721 (if (and (not (org-at-timestamp-p t))
5722 (org-on-heading-p))
5723 (org-todo 'up)
5724 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5725
5726 (defun org-timestamp-down-day (&optional arg)
5727 "Decrease the date in the time stamp by one day.
5728 With prefix ARG, change that many days."
5729 (interactive "p")
5730 (if (and (not (org-at-timestamp-p t))
5731 (org-on-heading-p))
5732 (org-todo 'down)
5733 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5734
5735 (defsubst org-pos-in-match-range (pos n)
5736 (and (match-beginning n)
5737 (<= (match-beginning n) pos)
5738 (>= (match-end n) pos)))
5739
5740 (defun org-at-timestamp-p (&optional also-inactive)
5741 "Determine if the cursor is in or at a timestamp."
5742 (interactive)
5743 (let* ((tsr (if also-inactive org-ts-regexp3 org-ts-regexp2))
5744 (pos (point))
5745 (ans (or (looking-at tsr)
5746 (save-excursion
5747 (skip-chars-backward "^[<\n\r\t")
5748 (if (> (point) 1) (backward-char 1))
5749 (and (looking-at tsr)
5750 (> (- (match-end 0) pos) -1))))))
5751 (and (boundp 'org-ts-what)
5752 (setq org-ts-what
5753 (cond
5754 ((org-pos-in-match-range pos 2) 'year)
5755 ((org-pos-in-match-range pos 3) 'month)
5756 ((org-pos-in-match-range pos 7) 'hour)
5757 ((org-pos-in-match-range pos 8) 'minute)
5758 ((or (org-pos-in-match-range pos 4)
5759 (org-pos-in-match-range pos 5)) 'day)
5760 (t 'day))))
5761 ans))
5762
5763 (defun org-timestamp-change (n &optional what)
5764 "Change the date in the time stamp at point.
5765 The date will be changed by N times WHAT. WHAT can be `day', `month',
5766 `year', `minute', `second'. If WHAT is not given, the cursor position
5767 in the timestamp determines what will be changed."
5768 (let ((fmt (car org-time-stamp-formats))
5769 org-ts-what
5770 (pos (point))
5771 ts time time0)
5772 (if (not (org-at-timestamp-p t))
5773 (error "Not at a timestamp"))
5774 (setq org-ts-what (or what org-ts-what))
5775 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5776 (- (match-end 0) (match-beginning 0))))
5777 1)
5778 (cdr org-time-stamp-formats)
5779 (car org-time-stamp-formats)))
5780 (if (= (char-after (match-beginning 0)) ?\[)
5781 (setq fmt (concat "[" (substring fmt 1 -1) "]")))
5782 (setq ts (match-string 0))
5783 (replace-match "")
5784 (setq time0 (org-parse-time-string ts))
5785 (setq time
5786 (apply 'encode-time
5787 (append
5788 (list (or (car time0) 0))
5789 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5790 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5791 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5792 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5793 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5794 (nthcdr 6 time0))))
5795 (if (eq what 'calendar)
5796 (let ((cal-date
5797 (save-excursion
5798 (save-match-data
5799 (set-buffer "*Calendar*")
5800 (calendar-cursor-to-date)))))
5801 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5802 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5803 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5804 (setcar time0 (or (car time0) 0))
5805 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5806 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5807 (setq time (apply 'encode-time time0))))
5808 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5809 (goto-char pos)
5810 ;; Try to recenter the calendar window, if any
5811 (if (and org-calendar-follow-timestamp-change
5812 (get-buffer-window "*Calendar*" t)
5813 (memq org-ts-what '(day month year)))
5814 (org-recenter-calendar (time-to-days time)))))
5815
5816 (defun org-recenter-calendar (date)
5817 "If the calendar is visible, recenter it to DATE."
5818 (let* ((win (selected-window))
5819 (cwin (get-buffer-window "*Calendar*" t))
5820 (calendar-move-hook nil))
5821 (when cwin
5822 (select-window cwin)
5823 (calendar-goto-date (if (listp date) date
5824 (calendar-gregorian-from-absolute date)))
5825 (select-window win))))
5826
5827 (defun org-goto-calendar (&optional arg)
5828 "Go to the Emacs calendar at the current date.
5829 If there is a time stamp in the current line, go to that date.
5830 A prefix ARG can be used to force the current date."
5831 (interactive "P")
5832 (let ((tsr org-ts-regexp) diff
5833 (calendar-move-hook nil)
5834 (view-calendar-holidays-initially nil)
5835 (view-diary-entries-initially nil))
5836 (if (or (org-at-timestamp-p)
5837 (save-excursion
5838 (beginning-of-line 1)
5839 (looking-at (concat ".*" tsr))))
5840 (let ((d1 (time-to-days (current-time)))
5841 (d2 (time-to-days
5842 (org-time-string-to-time (match-string 1)))))
5843 (setq diff (- d2 d1))))
5844 (calendar)
5845 (calendar-goto-today)
5846 (if (and diff (not arg)) (calendar-forward-day diff))))
5847
5848 (defun org-date-from-calendar ()
5849 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
5850 If there is already a time stamp at the cursor position, update it."
5851 (interactive)
5852 (org-timestamp-change 0 'calendar))
5853
5854 ;;; The clock for measuring work time.
5855
5856 (defvar org-clock-marker (make-marker)
5857 "Marker recording the last clock-in.")
5858
5859 (defun org-clock-in ()
5860 "Start the clock on the current item.
5861 If necessary, clock-out of the currently active clock."
5862 (interactive)
5863 (org-clock-out t)
5864 (let (ts)
5865 (save-excursion
5866 (org-back-to-heading t)
5867 (beginning-of-line 2)
5868 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5869 (not (equal (match-string 1) org-clock-string)))
5870 (beginning-of-line 1))
5871 (insert "\n") (backward-char 1)
5872 (indent-relative)
5873 (insert org-clock-string " "
5874 (setq ts (concat "[" (format-time-string
5875 (substring
5876 (cdr org-time-stamp-formats) 1 -1)
5877 (current-time))
5878 "]")))
5879 (move-marker org-clock-marker (point))
5880 (message "Clock started at %s" ts))))
5881
5882 (defun org-clock-out (&optional fail-quietly)
5883 "Stop the currently running clock.
5884 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
5885 (interactive)
5886 (catch 'exit
5887 (if (not (marker-buffer org-clock-marker))
5888 (if fail-quietly (throw 'exit t) (error "No active clock")))
5889 (let (ts te s h m)
5890 (save-excursion
5891 (set-buffer (marker-buffer org-clock-marker))
5892 (goto-char org-clock-marker)
5893 (beginning-of-line 1)
5894 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5895 (equal (match-string 1) org-clock-string))
5896 (setq ts (match-string 2))
5897 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
5898 (goto-char org-clock-marker)
5899 (setq te (concat "[" (format-time-string
5900 (substring
5901 (cdr org-time-stamp-formats) 1 -1)
5902 (current-time))
5903 "]"))
5904 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
5905 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
5906 h (floor (/ s 3600))
5907 s (- s (* 3600 h))
5908 m (floor (/ s 60))
5909 s (- s (* 60 s)))
5910 (insert "--" te " => " (format "%2d:%02d" h m))
5911 (move-marker org-clock-marker nil)
5912 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
5913
5914 (defun org-clock-cancel ()
5915 "Cancel the running clock be removing the start timestamp."
5916 (interactive)
5917 (if (not (marker-buffer org-clock-marker))
5918 (error "No active clock"))
5919 (save-excursion
5920 (set-buffer (marker-buffer org-clock-marker))
5921 (goto-char org-clock-marker)
5922 (delete-region (1- (point-at-bol)) (point-at-eol)))
5923 (message "Clock canceled"))
5924
5925 (defvar org-clock-file-total-minutes nil
5926 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
5927 (make-variable-buffer-local 'org-clock-file-total-minutes)
5928
5929 (defun org-clock-sum ()
5930 "Sum the times for each subtree.
5931 Puts the resulting times in minutes as a text property on each headline."
5932 (interactive)
5933 (let* ((bmp (buffer-modified-p))
5934 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
5935 org-clock-string
5936 ".*=>[ \t]*\\([0-9]+\\):\\([0-9]+\\)[ \t]*$"))
5937 (lmax 30)
5938 (ltimes (make-vector lmax 0))
5939 (t1 0)
5940 (level 0)
5941 time)
5942 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
5943 (save-excursion
5944 (goto-char (point-max))
5945 (while (re-search-backward re nil t)
5946 (if (match-end 2)
5947 ;; A time
5948 (setq t1 (+ t1 (* 60 (string-to-number (match-string 2)))
5949 (string-to-number (match-string 3))))
5950 ;; A headline
5951 (setq level (- (match-end 1) (match-beginning 1)))
5952 (when (or (> t1 0) (> (aref ltimes level) 0))
5953 (loop for l from 0 to level do
5954 (aset ltimes l (+ (aref ltimes l) t1)))
5955 (setq t1 0 time (aref ltimes level))
5956 (loop for l from level to (1- lmax) do
5957 (aset ltimes l 0))
5958 (goto-char (match-beginning 0))
5959 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
5960 (setq org-clock-file-total-minutes (aref ltimes 0)))
5961 (set-buffer-modified-p bmp)))
5962
5963 (defun org-clock-display (&optional total-only)
5964 "Show subtree times in the entire buffer.
5965 If TOTAL-ONLY is non-nil, only show the total time for the entire file
5966 in the echo area."
5967 (interactive)
5968 (org-remove-clock-overlays)
5969 (let (time h m p)
5970 (org-clock-sum)
5971 (unless total-only
5972 (save-excursion
5973 (goto-char (point-min))
5974 (while (setq p (next-single-property-change (point) :org-clock-minutes))
5975 (goto-char p)
5976 (when (setq time (get-text-property p :org-clock-minutes))
5977 (org-put-clock-overlay time (funcall outline-level))))
5978 (setq h (/ org-clock-file-total-minutes 60)
5979 m (- org-clock-file-total-minutes (* 60 h)))
5980 ;; Arrange to remove the overlays upon next change.
5981 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
5982 nil 'local)))
5983 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
5984
5985 (defvar org-clock-overlays nil)
5986 (make-variable-buffer-local 'org-clock-overlays)
5987
5988 (defun org-put-clock-overlay (time &optional level)
5989 "Put an overlays on the current line, displaying TIME.
5990 If LEVEL is given, prefix time with a corresponding number of stars.
5991 This creates a new overlay and stores it in `org-clock-overlays', so that it
5992 will be easy to remove."
5993 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
5994 (l (if level (org-get-legal-level level 0) 0))
5995 (off 0)
5996 ov tx)
5997 (move-to-column c)
5998 (unless (eolp) (skip-chars-backward "^ \t"))
5999 (skip-chars-backward " \t")
6000 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6001 tx (concat (buffer-substring (1- (point)) (point))
6002 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6003 (org-add-props (format "%s %2d:%02d%s"
6004 (make-string l ?*) h m
6005 (make-string (- 10 l) ?\ ))
6006 '(face secondary-selection))
6007 ""))
6008 (org-overlay-put ov 'display tx)
6009 (push ov org-clock-overlays)))
6010
6011 (defun org-remove-clock-overlays (&optional beg end noremove)
6012 "Remove the occur highlights from the buffer.
6013 BEG and END are ignored. If NOREMOVE is nil, remove this function
6014 from the `before-change-functions' in the current buffer."
6015 (interactive)
6016 (unless org-inhibit-highlight-removal
6017 (mapc 'org-delete-overlay org-clock-overlays)
6018 (setq org-clock-overlays nil)
6019 (unless noremove
6020 (remove-hook 'before-change-functions
6021 'org-remove-clock-overlays 'local))))
6022
6023 (defun org-clock-out-if-current ()
6024 "Clock out if the current entry contains the running clock.
6025 This is used to stop the clock after a TODO entry is marked DONE."
6026 (when (and (equal state org-done-string)
6027 (equal (marker-buffer org-clock-marker) (current-buffer))
6028 (< (point) org-clock-marker)
6029 (> (save-excursion (outline-next-heading) (point))
6030 org-clock-marker))
6031 (org-clock-out)))
6032
6033 (add-hook 'org-after-todo-state-change-hook
6034 'org-clock-out-if-current)
6035
6036 (defun org-check-running-clock ()
6037 "Check if the current buffer contains the running clock.
6038 If yes, offer to stop it and to save the buffer with the changes."
6039 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6040 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6041 (buffer-name))))
6042 (org-clock-out)
6043 (when (y-or-n-p "Save changed buffer?")
6044 (save-buffer))))
6045
6046 (defun org-clock-report ()
6047 "Create a table containing a report about clocked time.
6048 If the buffer contains lines
6049 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6050
6051 #+END: clocktable
6052 then the table will be inserted between these lines, replacing whatever
6053 is was there before. If these lines are not in the buffer, the table
6054 is inserted at point, surrounded by the special lines.
6055 The BEGIN line can contain parameters. Allowed are:
6056 :maxlevel The maximum level to be included in the table. Default is 3.
6057 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6058 (interactive)
6059 (org-remove-clock-overlays)
6060 (unless (org-find-dblock "clocktable")
6061 (org-create-dblock (list :name "clocktable"
6062 :maxlevel 2 :emphasize nil)))
6063 (org-update-dblock))
6064
6065 (defun org-dblock-write:clocktable (params)
6066 "Write the standard clocktable."
6067 (let ((hlchars '((1 . "*") (2 . ?/)))
6068 (emph nil)
6069 (ins (make-marker))
6070 ipos time h m p level hlc hdl maxlevel)
6071 (setq maxlevel (or (plist-get params :maxlevel) 3)
6072 emph (plist-get params :emphasize))
6073 (move-marker ins (point))
6074 (setq ipos (point))
6075 (insert-before-markers "Clock summary at ["
6076 (substring
6077 (format-time-string (cdr org-time-stamp-formats))
6078 1 -1)
6079 "]\n|L|Headline|Time|\n")
6080 (org-clock-sum)
6081 (setq h (/ org-clock-file-total-minutes 60)
6082 m (- org-clock-file-total-minutes (* 60 h)))
6083 (insert-before-markers "|-\n|0|" "*Total file time*| "
6084 (format "*%d:%02d*" h m)
6085 "|\n")
6086 (goto-char (point-min))
6087 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6088 (goto-char p)
6089 (when (setq time (get-text-property p :org-clock-minutes))
6090 (beginning-of-line 1)
6091 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6092 (setq level (- (match-end 1) (match-beginning 1)))
6093 (<= level maxlevel))
6094 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6095 hdl (match-string 2)
6096 h (/ time 60)
6097 m (- time (* 60 h)))
6098 (save-excursion
6099 (goto-char ins)
6100 (if (= level 1) (insert-before-markers "|-\n"))
6101 (insert-before-markers
6102 "| " (int-to-string level) "|" hlc hdl hlc " |"
6103 (make-string (1- level) ?|)
6104 hlc
6105 (format "%d:%02d" h m)
6106 hlc
6107 " |\n")))))
6108 (goto-char ins)
6109 (backward-delete-char 1)
6110 (goto-char ipos)
6111 (skip-chars-forward "^|")
6112 (org-table-align)))
6113
6114 (defun org-collect-clock-time-entries ()
6115 "Return an internal list with clocking information.
6116 This list has one entry for each CLOCK interval.
6117 FIXME: describe the elements."
6118 (interactive)
6119 (let ((re (concat "^[ \t]*" org-clock-string
6120 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
6121 rtn beg end next cont level title total closedp leafp
6122 clockpos titlepos h m donep)
6123 (save-excursion
6124 (org-clock-sum)
6125 (goto-char (point-min))
6126 (while (re-search-forward re nil t)
6127 (setq clockpos (match-beginning 0)
6128 beg (match-string 1) end (match-string 2)
6129 cont (match-end 0))
6130 (setq beg (apply 'encode-time (org-parse-time-string beg))
6131 end (apply 'encode-time (org-parse-time-string end)))
6132 (org-back-to-heading t)
6133 (setq donep (org-entry-is-done-p))
6134 (setq titlepos (point)
6135 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
6136 h (/ total 60) m (- total (* 60 h))
6137 total (cons h m))
6138 (looking-at "\\(\\*+\\) +\\(.*\\)")
6139 (setq level (- (match-end 1) (match-beginning 1))
6140 title (org-match-string-no-properties 2))
6141 (save-excursion (outline-next-heading) (setq next (point)))
6142 (setq closedp (re-search-forward org-closed-time-regexp next t))
6143 (goto-char next)
6144 (setq leafp (and (looking-at "^\\*+ ")
6145 (<= (- (match-end 0) (point)) level)))
6146 (push (list beg end clockpos closedp donep
6147 total title titlepos level leafp)
6148 rtn)
6149 (goto-char cont)))
6150 (nreverse rtn)))
6151
6152 ;;; Agenda, and Diary Integration
6153
6154 ;;; Define the mode
6155
6156 (defvar org-agenda-mode-map (make-sparse-keymap)
6157 "Keymap for `org-agenda-mode'.")
6158
6159 (defvar org-agenda-menu) ; defined later in this file.
6160 (defvar org-agenda-follow-mode nil)
6161 (defvar org-agenda-show-log nil)
6162 (defvar org-agenda-buffer-name "*Org Agenda*")
6163 (defvar org-agenda-redo-command nil)
6164 (defvar org-agenda-mode-hook nil)
6165 (defvar org-agenda-type nil)
6166 (defvar org-agenda-force-single-file nil)
6167
6168 (defun org-agenda-mode ()
6169 "Mode for time-sorted view on action items in Org-mode files.
6170
6171 The following commands are available:
6172
6173 \\{org-agenda-mode-map}"
6174 (interactive)
6175 (kill-all-local-variables)
6176 (setq major-mode 'org-agenda-mode)
6177 (setq mode-name "Org-Agenda")
6178 (use-local-map org-agenda-mode-map)
6179 (easy-menu-add org-agenda-menu)
6180 (if org-startup-truncated (setq truncate-lines t))
6181 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
6182 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
6183 (unless org-agenda-keep-modes
6184 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
6185 org-agenda-show-log nil))
6186 (easy-menu-change
6187 '("Agenda") "Agenda Files"
6188 (append
6189 (list
6190 (vector
6191 (if (get 'org-agenda-files 'org-restrict)
6192 "Restricted to single file"
6193 "Edit File List")
6194 '(org-edit-agenda-file-list)
6195 (not (get 'org-agenda-files 'org-restrict)))
6196 "--")
6197 (mapcar 'org-file-menu-entry (org-agenda-files))))
6198 (org-agenda-set-mode-name)
6199 (apply
6200 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
6201 (list 'org-agenda-mode-hook)))
6202
6203 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
6204 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
6205 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
6206 (define-key org-agenda-mode-map " " 'org-agenda-show)
6207 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
6208 (define-key org-agenda-mode-map "o" 'delete-other-windows)
6209 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
6210 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
6211 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
6212 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
6213 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
6214 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
6215 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
6216 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
6217 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
6218 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
6219 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
6220
6221 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
6222 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
6223 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
6224 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
6225 (while l (define-key org-agenda-mode-map
6226 (int-to-string (pop l)) 'digit-argument)))
6227
6228 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
6229 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
6230 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
6231 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
6232 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
6233 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
6234 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
6235 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
6236 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
6237 (define-key org-agenda-mode-map "n" 'next-line)
6238 (define-key org-agenda-mode-map "p" 'previous-line)
6239 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
6240 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
6241 (define-key org-agenda-mode-map "," 'org-agenda-priority)
6242 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
6243 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
6244 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
6245 (eval-after-load "calendar"
6246 '(define-key calendar-mode-map org-calendar-to-agenda-key
6247 'org-calendar-goto-agenda))
6248 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
6249 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
6250 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
6251 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
6252 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
6253 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
6254 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
6255 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
6256 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
6257 (define-key org-agenda-mode-map "O" 'org-clock-out)
6258 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
6259 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
6260 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
6261 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
6262 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
6263 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
6264 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
6265 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
6266 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
6267 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
6268 "Local keymap for agenda entries from Org-mode.")
6269
6270 (define-key org-agenda-keymap
6271 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
6272 (define-key org-agenda-keymap
6273 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
6274 (when org-agenda-mouse-1-follows-link
6275 (define-key org-agenda-keymap [follow-link] 'mouse-face))
6276 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
6277 '("Agenda"
6278 ("Agenda Files")
6279 "--"
6280 ["Show" org-agenda-show t]
6281 ["Go To (other window)" org-agenda-goto t]
6282 ["Go To (one window)" org-agenda-switch-to t]
6283 ["Follow Mode" org-agenda-follow-mode
6284 :style toggle :selected org-agenda-follow-mode :active t]
6285 "--"
6286 ["Cycle TODO" org-agenda-todo t]
6287 ("Tags"
6288 ["Show all Tags" org-agenda-show-tags t]
6289 ["Set Tags" org-agenda-set-tags t])
6290 ("Schedule"
6291 ["Schedule" org-agenda-schedule t]
6292 ["Set Deadline" org-agenda-deadline t]
6293 "--"
6294 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
6295 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
6296 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6297 ("Priority"
6298 ["Set Priority" org-agenda-priority t]
6299 ["Increase Priority" org-agenda-priority-up t]
6300 ["Decrease Priority" org-agenda-priority-down t]
6301 ["Show Priority" org-agenda-show-priority t])
6302 "--"
6303 ;; ["New agenda command" org-agenda t]
6304 ["Rebuild buffer" org-agenda-redo t]
6305 "--"
6306 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6307 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6308 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6309 "--"
6310 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6311 :style radio :selected (equal org-agenda-ndays 1)]
6312 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6313 :style radio :selected (equal org-agenda-ndays 7)]
6314 "--"
6315 ["Show Logbook entries" org-agenda-log-mode
6316 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6317 ["Include Diary" org-agenda-toggle-diary
6318 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6319 ["Use Time Grid" org-agenda-toggle-time-grid
6320 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6321 "--"
6322 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6323 ("Calendar Commands"
6324 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6325 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6326 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6327 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6328 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
6329 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
6330 "--"
6331 ["Quit" org-agenda-quit t]
6332 ["Exit and Release Buffers" org-agenda-exit t]
6333 ))
6334
6335 ;;;###autoload
6336 (defun org-agenda (arg)
6337 "Dispatch agenda commands to collect entries to the agenda buffer.
6338 Prompts for a character to select a command. Any prefix arg will be passed
6339 on to the selected command. The default selections are:
6340
6341 a Call `org-agenda' to display the agenda for the current day or week.
6342 t Call `org-todo-list' to display the global todo list.
6343 T Call `org-todo-list' to display the global todo list, select only
6344 entries with a specific TODO keyword (the user gets a prompt).
6345 m Call `org-tags-view' to display headlines with tags matching
6346 a condition (the user is prompted for the condition).
6347 M Like `m', but select only TODO entries, no ordinary headlines.
6348
6349 More commands can be added by configuring the variable
6350 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
6351 searches can be pre-defined in this way.
6352
6353 If the current buffer is in Org-mode and visiting a file, you can also
6354 first press `1' to indicate that the agenda should be temporarily (until the
6355 next use of \\[org-agenda]) restricted to the current file."
6356 (interactive "P")
6357 (catch 'exit
6358 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
6359 (bfn buffer-file-name)
6360 (custom org-agenda-custom-commands)
6361 c entry key type string)
6362 (put 'org-agenda-files 'org-restrict nil)
6363 (save-window-excursion
6364 (delete-other-windows)
6365 (switch-to-buffer-other-window " *Agenda Commands*")
6366 (erase-buffer)
6367 (insert
6368 "Press key for an agenda command:
6369 --------------------------------
6370 a Agenda for current week or day
6371 t List of all TODO entries T Entries with special TODO kwd
6372 m Match a TAGS query M Like m, but only TODO entries
6373 C Configure your own agenda commands")
6374 (while (setq entry (pop custom))
6375 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
6376 (insert (format "\n%-4s%-14s: %s"
6377 key
6378 (cond
6379 ((eq type 'tags) "Tags query")
6380 ((eq type 'todo) "TODO keyword")
6381 ((eq type 'tags-tree) "Tags tree")
6382 ((eq type 'todo-tree) "TODO kwd tree")
6383 ((eq type 'occur-tree) "Occur tree")
6384 (t "???"))
6385 (org-add-props string nil 'face 'org-warning))))
6386 (goto-char (point-min))
6387 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
6388 (message "Press key for agenda command%s"
6389 (if restrict-ok ", or [1] to restrict to current file" ""))
6390 (setq c (read-char-exclusive))
6391 (message "")
6392 (when (equal c ?1)
6393 (if restrict-ok
6394 (put 'org-agenda-files 'org-restrict (list bfn))
6395 (error "Cannot restrict agenda to current buffer"))
6396 (message "Press key for agenda command%s"
6397 (if restrict-ok " (restricted to current file)" ""))
6398 (setq c (read-char-exclusive))
6399 (message "")))
6400 (require 'calendar) ; FIXME: can we avoid this for some commands?
6401 ;; For example the todo list should not need it (but does...)
6402 (cond
6403 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
6404 ((equal c ?a) (call-interactively 'org-agenda-list))
6405 ((equal c ?t) (call-interactively 'org-todo-list))
6406 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
6407 ((equal c ?m) (call-interactively 'org-tags-view))
6408 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
6409 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
6410 (setq type (nth 1 entry) string (nth 2 entry))
6411 (cond
6412 ((eq type 'tags)
6413 (org-tags-view current-prefix-arg string))
6414 ((eq type 'tags-todo)
6415 (org-tags-view '(4) string))
6416 ((eq type 'todo)
6417 (org-todo-list string))
6418 ((eq type 'tags-tree)
6419 (org-check-for-org-mode)
6420 (org-tags-sparse-tree current-prefix-arg string))
6421 ((eq type 'todo-tree)
6422 (org-check-for-org-mode)
6423 (org-occur (concat "^" outline-regexp "[ \t]*"
6424 (regexp-quote string) "\\>")))
6425 ((eq type 'occur-tree)
6426 (org-check-for-org-mode)
6427 (org-occur string))
6428 (t (error "Invalid custom agenda command type %s" type))))
6429 (t (error "Invalid key"))))))
6430
6431 (defun org-check-for-org-mode ()
6432 "Make sure current buffer is in org-mode. Error if not."
6433 (or (eq major-mode 'org-mode)
6434 (error "Cannot execute org-mode agenda command on buffer in %s."
6435 major-mode)))
6436
6437 (defun org-fit-agenda-window ()
6438 "Fit the window to the buffer size."
6439 (and org-fit-agenda-window
6440 (fboundp 'fit-window-to-buffer)
6441 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
6442 (/ (frame-height) 2))))
6443
6444 (defun org-agenda-files (&optional unrestricted)
6445 "Get the list of agenda files.
6446 Optional UNRESTRICTED means return the full list even if a restriction
6447 is currently in place."
6448 (cond
6449 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
6450 ((stringp org-agenda-files) (org-read-agenda-file-list))
6451 ((listp org-agenda-files) org-agenda-files)
6452 (t (error "Invalid value of `org-agenda-files'"))))
6453
6454 (defvar org-window-configuration)
6455
6456 (defun org-edit-agenda-file-list ()
6457 "Edit the list of agenda files.
6458 Depending on setup, this either uses customize to edit the variable
6459 `org-agenda-files', or it visits the file that is holding the list. In the
6460 latter case, the buffer is set up in a way that saving it automatically kills
6461 the buffer and restores the previous window configuration."
6462 (interactive)
6463 (if (stringp org-agenda-files)
6464 (let ((cw (current-window-configuration)))
6465 (find-file org-agenda-files)
6466 (set (make-local-variable 'org-window-configuration) cw)
6467 (org-add-hook 'after-save-hook
6468 (lambda ()
6469 (set-window-configuration
6470 (prog1 org-window-configuration
6471 (kill-buffer (current-buffer))))
6472 (org-install-agenda-files-menu)
6473 (message "New agenda file list installed"))
6474 nil 'local)
6475 (message (substitute-command-keys
6476 "Edit list and finish with \\[save-buffer]")))
6477 (customize-variable 'org-agenda-files)))
6478
6479 (defun org-store-new-agenda-file-list (list)
6480 "Set new value for the agenda file list and save it correcly."
6481 (if (stringp org-agenda-files)
6482 (let ((f org-agenda-files) b)
6483 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
6484 (with-temp-file f
6485 (insert (mapconcat 'identity list "\n") "\n")))
6486 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
6487 (setq org-agenda-files list)
6488 (customize-save-variable 'org-agenda-files org-agenda-files))))
6489
6490 (defun org-read-agenda-file-list ()
6491 "Read the list of agenda files from a file."
6492 (when (stringp org-agenda-files)
6493 (with-temp-buffer
6494 (insert-file-contents org-agenda-files)
6495 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
6496
6497 (defvar org-agenda-markers nil
6498 "List of all currently active markers created by `org-agenda'.")
6499 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
6500 "Creation time of the last agenda marker.")
6501
6502 (defun org-agenda-new-marker (&optional pos)
6503 "Return a new agenda marker.
6504 Org-mode keeps a list of these markers and resets them when they are
6505 no longer in use."
6506 (let ((m (copy-marker (or pos (point)))))
6507 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
6508 (push m org-agenda-markers)
6509 m))
6510
6511 (defun org-agenda-maybe-reset-markers (&optional force)
6512 "Reset markers created by `org-agenda'. But only if they are old enough."
6513 (if (or force
6514 (> (- (time-to-seconds (current-time))
6515 org-agenda-last-marker-time)
6516 5))
6517 (while org-agenda-markers
6518 (move-marker (pop org-agenda-markers) nil))))
6519
6520 (defvar org-agenda-new-buffers nil
6521 "Buffers created to visit agenda files.")
6522
6523 (defun org-get-agenda-file-buffer (file)
6524 "Get a buffer visiting FILE. If the buffer needs to be created, add
6525 it to the list of buffers which might be released later."
6526 (let ((buf (find-buffer-visiting file)))
6527 (if buf
6528 buf ; just return it
6529 ;; Make a new buffer and remember it
6530 (setq buf (find-file-noselect file))
6531 (if buf (push buf org-agenda-new-buffers))
6532 buf)))
6533
6534 (defun org-release-buffers (blist)
6535 "Release all buffers in list, asking the user for confirmation when needed.
6536 When a buffer is unmodified, it is just killed. When modified, it is saved
6537 \(if the user agrees) and then killed."
6538 (let (buf file)
6539 (while (setq buf (pop blist))
6540 (setq file (buffer-file-name buf))
6541 (when (and (buffer-modified-p buf)
6542 file
6543 (y-or-n-p (format "Save file %s? " file)))
6544 (with-current-buffer buf (save-buffer)))
6545 (kill-buffer buf))))
6546
6547 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
6548
6549 (defun org-timeline (&optional include-all keep-modes)
6550 "Show a time-sorted view of the entries in the current org file.
6551 Only entries with a time stamp of today or later will be listed. With
6552 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
6553 under the current date.
6554 If the buffer contains an active region, only check the region for
6555 dates."
6556 (interactive "P")
6557 (require 'calendar)
6558 (org-agenda-maybe-reset-markers 'force)
6559 (org-compile-prefix-format org-timeline-prefix-format)
6560 (let* ((dopast t)
6561 (dotodo include-all)
6562 (doclosed org-agenda-show-log)
6563 (org-agenda-keep-modes keep-modes)
6564 (entry buffer-file-name)
6565 (org-agenda-files (list buffer-file-name))
6566 (date (calendar-current-date))
6567 (win (selected-window))
6568 (pos1 (point))
6569 (beg (if (org-region-active-p) (region-beginning) (point-min)))
6570 (end (if (org-region-active-p) (region-end) (point-max)))
6571 (day-numbers (org-get-all-dates beg end 'no-ranges
6572 t doclosed ; always include today
6573 org-timeline-show-empty-dates))
6574 (today (time-to-days (current-time)))
6575 (org-respect-restriction t)
6576 (past t)
6577 args
6578 s e rtn d emptyp)
6579 (org-prepare-agenda-buffers org-agenda-files)
6580 (setq org-agenda-redo-command
6581 (list 'progn
6582 (list 'switch-to-buffer-other-window (current-buffer))
6583 (list 'org-timeline (list 'quote include-all) t)))
6584 (if (not dopast)
6585 ;; Remove past dates from the list of dates.
6586 (setq day-numbers (delq nil (mapcar (lambda(x)
6587 (if (>= x today) x nil))
6588 day-numbers))))
6589 (switch-to-buffer-other-window
6590 (get-buffer-create org-agenda-buffer-name))
6591 (setq buffer-read-only nil)
6592 (erase-buffer)
6593 (org-agenda-mode) (setq buffer-read-only nil)
6594 (set (make-local-variable 'org-agenda-type) 'timeline)
6595 (if doclosed (push :closed args))
6596 (push :timestamp args)
6597 (if dotodo (push :todo args))
6598 (while (setq d (pop day-numbers))
6599 (if (and (listp d) (eq (car d) :omitted))
6600 (progn
6601 (setq s (point))
6602 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
6603 (put-text-property s (1- (point)) 'face 'org-level-3))
6604 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
6605 (if (and (>= d today)
6606 dopast
6607 past)
6608 (progn
6609 (setq past nil)
6610 (insert (make-string 79 ?-) "\n")))
6611 (setq date (calendar-gregorian-from-absolute d))
6612 (setq s (point))
6613 (setq rtn (and (not emptyp)
6614 (apply 'org-agenda-get-day-entries
6615 entry date args)))
6616 (if (or rtn (equal d today) org-timeline-show-empty-dates)
6617 (progn
6618 (insert (calendar-day-name date) " "
6619 (number-to-string (extract-calendar-day date)) " "
6620 (calendar-month-name (extract-calendar-month date)) " "
6621 (number-to-string (extract-calendar-year date)) "\n")
6622 (put-text-property s (1- (point)) 'face
6623 'org-level-3)
6624 (if (equal d today)
6625 (put-text-property s (1- (point)) 'org-today t))
6626 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
6627 (put-text-property s (1- (point)) 'day d)))))
6628 (goto-char (point-min))
6629 (setq buffer-read-only t)
6630 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6631 (point-min)))
6632 (when (not org-select-timeline-window)
6633 (select-window win)
6634 (goto-char pos1))))
6635
6636 ;;;###autoload
6637 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
6638 "Produce a weekly view from all files in variable `org-agenda-files'.
6639 The view will be for the current week, but from the overview buffer you
6640 will be able to go to other weeks.
6641 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
6642 also be shown, under the current date.
6643 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
6644 on the days are also shown. See the variable `org-log-done' for how
6645 to turn on logging.
6646 START-DAY defaults to TODAY, or to the most recent match for the weekday
6647 given in `org-agenda-start-on-weekday'.
6648 NDAYS defaults to `org-agenda-ndays'."
6649 (interactive "P")
6650 (org-agenda-maybe-reset-markers 'force)
6651 (org-compile-prefix-format org-agenda-prefix-format)
6652 (require 'calendar)
6653 (let* ((org-agenda-start-on-weekday
6654 (if (or (equal ndays 1)
6655 (and (null ndays) (equal 1 org-agenda-ndays)))
6656 nil org-agenda-start-on-weekday))
6657 (org-agenda-keep-modes keep-modes)
6658 (thefiles (org-agenda-files))
6659 (files thefiles)
6660 (win (selected-window))
6661 (today (time-to-days (current-time)))
6662 (sd (or start-day today))
6663 (start (if (or (null org-agenda-start-on-weekday)
6664 (< org-agenda-ndays 7))
6665 sd
6666 (let* ((nt (calendar-day-of-week
6667 (calendar-gregorian-from-absolute sd)))
6668 (n1 org-agenda-start-on-weekday)
6669 (d (- nt n1)))
6670 (- sd (+ (if (< d 0) 7 0) d)))))
6671 (day-numbers (list start))
6672 (inhibit-redisplay t)
6673 s e rtn rtnall file date d start-pos end-pos todayp nd)
6674 (org-prepare-agenda-buffers files)
6675 (setq org-agenda-redo-command
6676 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
6677 ;; Make the list of days
6678 (setq ndays (or ndays org-agenda-ndays)
6679 nd ndays)
6680 (while (> ndays 1)
6681 (push (1+ (car day-numbers)) day-numbers)
6682 (setq ndays (1- ndays)))
6683 (setq day-numbers (nreverse day-numbers))
6684 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6685 (progn
6686 (delete-other-windows)
6687 (switch-to-buffer-other-window
6688 (get-buffer-create org-agenda-buffer-name))))
6689 (setq buffer-read-only nil)
6690 (erase-buffer)
6691 (org-agenda-mode) (setq buffer-read-only nil)
6692 (set (make-local-variable 'org-agenda-type) 'agenda)
6693 (set (make-local-variable 'starting-day) (car day-numbers))
6694 (set (make-local-variable 'include-all-loc) include-all)
6695 (when (and (or include-all org-agenda-include-all-todo)
6696 (member today day-numbers))
6697 (setq files thefiles
6698 rtnall nil)
6699 (while (setq file (pop files))
6700 (catch 'nextfile
6701 (org-check-agenda-file file)
6702 (setq date (calendar-gregorian-from-absolute today)
6703 rtn (org-agenda-get-day-entries
6704 file date :todo))
6705 (setq rtnall (append rtnall rtn))))
6706 (when rtnall
6707 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
6708 (add-text-properties (point-min) (1- (point))
6709 (list 'face 'org-level-3))
6710 (insert (org-finalize-agenda-entries rtnall) "\n")))
6711 (while (setq d (pop day-numbers))
6712 (setq date (calendar-gregorian-from-absolute d)
6713 s (point))
6714 (if (or (setq todayp (= d today))
6715 (and (not start-pos) (= d sd)))
6716 (setq start-pos (point))
6717 (if (and start-pos (not end-pos))
6718 (setq end-pos (point))))
6719 (setq files thefiles
6720 rtnall nil)
6721 (while (setq file (pop files))
6722 (catch 'nextfile
6723 (org-check-agenda-file file)
6724 (if org-agenda-show-log
6725 (setq rtn (org-agenda-get-day-entries
6726 file date
6727 :deadline :scheduled :timestamp :closed))
6728 (setq rtn (org-agenda-get-day-entries
6729 file date
6730 :deadline :scheduled :timestamp)))
6731 (setq rtnall (append rtnall rtn))))
6732 (if org-agenda-include-diary
6733 (progn
6734 (require 'diary-lib)
6735 (setq rtn (org-get-entries-from-diary date))
6736 (setq rtnall (append rtnall rtn))))
6737 (if (or rtnall org-agenda-show-all-dates)
6738 (progn
6739 (insert (format "%-9s %2d %s %4d\n"
6740 (calendar-day-name date)
6741 (extract-calendar-day date)
6742 (calendar-month-name (extract-calendar-month date))
6743 (extract-calendar-year date)))
6744 (put-text-property s (1- (point)) 'face
6745 'org-level-3)
6746 (if rtnall (insert
6747 (org-finalize-agenda-entries
6748 (org-agenda-add-time-grid-maybe
6749 rtnall nd todayp))
6750 "\n"))
6751 (put-text-property s (1- (point)) 'day d))))
6752 (goto-char (point-min))
6753 (setq buffer-read-only t)
6754 (org-fit-agenda-window)
6755 (unless (and (pos-visible-in-window-p (point-min))
6756 (pos-visible-in-window-p (point-max)))
6757 (goto-char (1- (point-max)))
6758 (recenter -1)
6759 (if (not (pos-visible-in-window-p (or start-pos 1)))
6760 (progn
6761 (goto-char (or start-pos 1))
6762 (recenter 1))))
6763 (goto-char (or start-pos 1))
6764 (if (not org-select-agenda-window) (select-window win))
6765 (message "")))
6766
6767 (defvar org-select-this-todo-keyword nil)
6768
6769 ;;;###autoload
6770 (defun org-todo-list (arg &optional keep-modes)
6771 "Show all TODO entries from all agenda file in a single list.
6772 The prefix arg can be used to select a specific TODO keyword and limit
6773 the list to these. When using \\[universal-argument], you will be prompted
6774 for a keyword. A numeric prefix directly selects the Nth keyword in
6775 `org-todo-keywords'."
6776 (interactive "P")
6777 (org-agenda-maybe-reset-markers 'force)
6778 (org-compile-prefix-format org-agenda-prefix-format)
6779 (let* ((org-agenda-keep-modes keep-modes)
6780 (today (time-to-days (current-time)))
6781 (date (calendar-gregorian-from-absolute today))
6782 (win (selected-window))
6783 (kwds org-todo-keywords)
6784 (completion-ignore-case t)
6785 (org-select-this-todo-keyword
6786 (if (stringp arg) arg
6787 (and arg (integerp arg) (> arg 0)
6788 (nth (1- arg) org-todo-keywords))))
6789 rtn rtnall files file pos)
6790 (when (equal arg '(4))
6791 (setq org-select-this-todo-keyword
6792 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
6793 nil t)))
6794 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
6795 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6796 (progn
6797 (delete-other-windows)
6798 (switch-to-buffer-other-window
6799 (get-buffer-create org-agenda-buffer-name))))
6800 (setq buffer-read-only nil)
6801 (erase-buffer)
6802 (org-agenda-mode) (setq buffer-read-only nil)
6803 (set (make-local-variable 'org-agenda-type) 'todo)
6804 (set (make-local-variable 'last-arg) arg)
6805 (set (make-local-variable 'org-todo-keywords) kwds)
6806 (set (make-local-variable 'org-agenda-redo-command)
6807 '(org-todo-list (or current-prefix-arg last-arg) t))
6808 (setq files (org-agenda-files)
6809 rtnall nil)
6810 (org-prepare-agenda-buffers files)
6811 (while (setq file (pop files))
6812 (catch 'nextfile
6813 (org-check-agenda-file file)
6814 (setq rtn (org-agenda-get-day-entries file date :todo))
6815 (setq rtnall (append rtnall rtn))))
6816 (insert "Global list of TODO items of type: ")
6817 (add-text-properties (point-min) (1- (point))
6818 (list 'face 'org-level-3))
6819 (setq pos (point))
6820 (insert (or org-select-this-todo-keyword "ALL") "\n")
6821 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6822 (setq pos (point))
6823 (insert
6824 "Available with `N r': (0)ALL "
6825 (let ((n 0))
6826 (mapconcat (lambda (x)
6827 (format "(%d)%s" (setq n (1+ n)) x))
6828 org-todo-keywords " "))
6829 "\n")
6830 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
6831 (when rtnall
6832 (insert (org-finalize-agenda-entries rtnall) "\n"))
6833 (goto-char (point-min))
6834 (setq buffer-read-only t)
6835 (org-fit-agenda-window)
6836 (if (not org-select-agenda-window) (select-window win))))
6837
6838 (defun org-check-agenda-file (file)
6839 "Make sure FILE exists. If not, ask user what to do."
6840 (when (not (file-exists-p file))
6841 (message "non-existent file %s. [R]emove from list or [A]bort?"
6842 (abbreviate-file-name file))
6843 (let ((r (downcase (read-char-exclusive))))
6844 (cond
6845 ((equal r ?r)
6846 (org-remove-file file)
6847 (throw 'nextfile t))
6848 (t (error "Abort"))))))
6849
6850 (defun org-agenda-check-type (error &rest types)
6851 "Check if agenda buffer is of allowed type.
6852 If ERROR is non-nil, throw an error, otherwise just return nil."
6853 (if (memq org-agenda-type types)
6854 t
6855 (if error
6856 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
6857 nil)))
6858
6859 (defun org-agenda-quit ()
6860 "Exit agenda by removing the window or the buffer."
6861 (interactive)
6862 (let ((buf (current-buffer)))
6863 (if (not (one-window-p)) (delete-window))
6864 (kill-buffer buf)
6865 (org-agenda-maybe-reset-markers 'force)))
6866
6867 (defun org-agenda-exit ()
6868 "Exit agenda by removing the window or the buffer.
6869 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
6870 Org-mode buffers visited directly by the user will not be touched."
6871 (interactive)
6872 (org-release-buffers org-agenda-new-buffers)
6873 (setq org-agenda-new-buffers nil)
6874 (org-agenda-quit))
6875
6876 (defun org-agenda-redo ()
6877 "Rebuild Agenda.
6878 When this is the global TODO list, a prefix argument will be interpreted."
6879 (interactive)
6880 (message "Rebuilding agenda buffer...")
6881 (eval org-agenda-redo-command)
6882 (message "Rebuilding agenda buffer...done"))
6883
6884 (defun org-agenda-goto-today ()
6885 "Go to today."
6886 (interactive)
6887 (org-agenda-check-type t 'timeline 'agenda)
6888 (if (boundp 'starting-day)
6889 (let ((cmd (car org-agenda-redo-command))
6890 (iall (nth 1 org-agenda-redo-command))
6891 (nday (nth 3 org-agenda-redo-command))
6892 (keep (nth 4 org-agenda-redo-command)))
6893 (eval (list cmd iall nil nday keep)))
6894 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6895 (point-min)))))
6896
6897 (defun org-agenda-later (arg)
6898 "Go forward in time by `org-agenda-ndays' days.
6899 With prefix ARG, go forward that many times `org-agenda-ndays'."
6900 (interactive "p")
6901 (org-agenda-check-type t 'agenda)
6902 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6903 (+ starting-day (* arg org-agenda-ndays)) nil t))
6904
6905 (defun org-agenda-earlier (arg)
6906 "Go back in time by `org-agenda-ndays' days.
6907 With prefix ARG, go back that many times `org-agenda-ndays'."
6908 (interactive "p")
6909 (org-agenda-check-type t 'agenda)
6910 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6911 (- starting-day (* arg org-agenda-ndays)) nil t))
6912
6913 (defun org-agenda-week-view ()
6914 "Switch to weekly view for agenda."
6915 (interactive)
6916 (org-agenda-check-type t 'agenda)
6917 (setq org-agenda-ndays 7)
6918 (org-agenda-list include-all-loc
6919 (or (get-text-property (point) 'day)
6920 starting-day)
6921 nil t)
6922 (org-agenda-set-mode-name)
6923 (message "Switched to week view"))
6924
6925 (defun org-agenda-day-view ()
6926 "Switch to daily view for agenda."
6927 (interactive)
6928 (org-agenda-check-type t 'agenda)
6929 (setq org-agenda-ndays 1)
6930 (org-agenda-list include-all-loc
6931 (or (get-text-property (point) 'day)
6932 starting-day)
6933 nil t)
6934 (org-agenda-set-mode-name)
6935 (message "Switched to day view"))
6936
6937 (defun org-agenda-next-date-line (&optional arg)
6938 "Jump to the next line indicating a date in agenda buffer."
6939 (interactive "p")
6940 (org-agenda-check-type t 'agenda 'timeline)
6941 (beginning-of-line 1)
6942 (if (looking-at "^\\S-") (forward-char 1))
6943 (if (not (re-search-forward "^\\S-" nil t arg))
6944 (progn
6945 (backward-char 1)
6946 (error "No next date after this line in this buffer")))
6947 (goto-char (match-beginning 0)))
6948
6949 (defun org-agenda-previous-date-line (&optional arg)
6950 "Jump to the previous line indicating a date in agenda buffer."
6951 (interactive "p")
6952 (org-agenda-check-type t 'agenda 'timeline)
6953 (beginning-of-line 1)
6954 (if (not (re-search-backward "^\\S-" nil t arg))
6955 (error "No previous date before this line in this buffer")))
6956
6957 ;; Initialize the highlight
6958 (defvar org-hl (org-make-overlay 1 1))
6959 (org-overlay-put org-hl 'face 'highlight)
6960
6961 (defun org-highlight (begin end &optional buffer)
6962 "Highlight a region with overlay."
6963 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
6964 org-hl begin end (or buffer (current-buffer))))
6965
6966 (defun org-unhighlight ()
6967 "Detach overlay INDEX."
6968 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
6969
6970
6971 (defun org-agenda-follow-mode ()
6972 "Toggle follow mode in an agenda buffer."
6973 (interactive)
6974 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
6975 (org-agenda-set-mode-name)
6976 (message "Follow mode is %s"
6977 (if org-agenda-follow-mode "on" "off")))
6978
6979 (defun org-agenda-log-mode ()
6980 "Toggle log mode in an agenda buffer."
6981 (interactive)
6982 (org-agenda-check-type t 'agenda 'timeline)
6983 (setq org-agenda-show-log (not org-agenda-show-log))
6984 (org-agenda-set-mode-name)
6985 (org-agenda-redo)
6986 (message "Log mode is %s"
6987 (if org-agenda-show-log "on" "off")))
6988
6989 (defun org-agenda-toggle-diary ()
6990 "Toggle diary inclusion in an agenda buffer."
6991 (interactive)
6992 (org-agenda-check-type t 'agenda)
6993 (setq org-agenda-include-diary (not org-agenda-include-diary))
6994 (org-agenda-redo)
6995 (org-agenda-set-mode-name)
6996 (message "Diary inclusion turned %s"
6997 (if org-agenda-include-diary "on" "off")))
6998
6999 (defun org-agenda-toggle-time-grid ()
7000 "Toggle time grid in an agenda buffer."
7001 (interactive)
7002 (org-agenda-check-type t 'agenda)
7003 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
7004 (org-agenda-redo)
7005 (org-agenda-set-mode-name)
7006 (message "Time-grid turned %s"
7007 (if org-agenda-use-time-grid "on" "off")))
7008
7009 (defun org-agenda-set-mode-name ()
7010 "Set the mode name to indicate all the small mode settings."
7011 (setq mode-name
7012 (concat "Org-Agenda"
7013 (if (equal org-agenda-ndays 1) " Day" "")
7014 (if (equal org-agenda-ndays 7) " Week" "")
7015 (if org-agenda-follow-mode " Follow" "")
7016 (if org-agenda-include-diary " Diary" "")
7017 (if org-agenda-use-time-grid " Grid" "")
7018 (if org-agenda-show-log " Log" "")))
7019 (force-mode-line-update))
7020
7021 (defun org-agenda-post-command-hook ()
7022 (and (eolp) (not (bolp)) (backward-char 1))
7023 (if (and org-agenda-follow-mode
7024 (get-text-property (point) 'org-marker))
7025 (org-agenda-show)))
7026
7027 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
7028
7029 (defun org-get-entries-from-diary (date)
7030 "Get the (Emacs Calendar) diary entries for DATE."
7031 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
7032 (diary-display-hook '(fancy-diary-display))
7033 (list-diary-entries-hook
7034 (cons 'org-diary-default-entry list-diary-entries-hook))
7035 (diary-file-name-prefix-function nil) ; turn this feature off
7036 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
7037 entries
7038 (org-disable-agenda-to-diary t))
7039 (save-excursion
7040 (save-window-excursion
7041 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
7042 (if (not (get-buffer fancy-diary-buffer))
7043 (setq entries nil)
7044 (with-current-buffer fancy-diary-buffer
7045 (setq buffer-read-only nil)
7046 (if (= (point-max) 1)
7047 ;; No entries
7048 (setq entries nil)
7049 ;; Omit the date and other unnecessary stuff
7050 (org-agenda-cleanup-fancy-diary)
7051 ;; Add prefix to each line and extend the text properties
7052 (if (= (point-max) 1)
7053 (setq entries nil)
7054 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
7055 (set-buffer-modified-p nil)
7056 (kill-buffer fancy-diary-buffer)))
7057 (when entries
7058 (setq entries (org-split-string entries "\n"))
7059 (setq entries
7060 (mapcar
7061 (lambda (x)
7062 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
7063 ;; Extend the text properties to the beginning of the line
7064 (org-add-props x (text-properties-at (1- (length x)) x)))
7065 entries)))))
7066
7067 (defun org-agenda-cleanup-fancy-diary ()
7068 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
7069 This gets rid of the date, the underline under the date, and
7070 the dummy entry installed by `org-mode' to ensure non-empty diary for each
7071 date. It also removes lines that contain only whitespace."
7072 (goto-char (point-min))
7073 (if (looking-at ".*?:[ \t]*")
7074 (progn
7075 (replace-match "")
7076 (re-search-forward "\n=+$" nil t)
7077 (replace-match "")
7078 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
7079 (re-search-forward "\n=+$" nil t)
7080 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
7081 (goto-char (point-min))
7082 (while (re-search-forward "^ +\n" nil t)
7083 (replace-match ""))
7084 (goto-char (point-min))
7085 (if (re-search-forward "^Org-mode dummy\n?" nil t)
7086 (replace-match "")))
7087
7088 ;; Make sure entries from the diary have the right text properties.
7089 (eval-after-load "diary-lib"
7090 '(if (boundp 'diary-modify-entry-list-string-function)
7091 ;; We can rely on the hook, nothing to do
7092 nil
7093 ;; Hook not avaiable, must use advice to make this work
7094 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
7095 "Make the position visible."
7096 (if (and org-disable-agenda-to-diary ;; called from org-agenda
7097 (stringp string)
7098 buffer-file-name)
7099 (setq string (org-modify-diary-entry-string string))))))
7100
7101 (defun org-modify-diary-entry-string (string)
7102 "Add text properties to string, allowing org-mode to act on it."
7103 (org-add-props string nil
7104 'mouse-face 'highlight
7105 'keymap org-agenda-keymap
7106 'help-echo (format "mouse-2 or RET jump to diary file %s"
7107 (abbreviate-file-name buffer-file-name))
7108 'org-agenda-diary-link t
7109 'org-marker (org-agenda-new-marker (point-at-bol))))
7110
7111 (defun org-diary-default-entry ()
7112 "Add a dummy entry to the diary.
7113 Needed to avoid empty dates which mess up holiday display."
7114 ;; Catch the error if dealing with the new add-to-diary-alist
7115 (when org-disable-agenda-to-diary
7116 (condition-case nil
7117 (add-to-diary-list original-date "Org-mode dummy" "")
7118 (error
7119 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
7120
7121 (defun org-cycle-agenda-files ()
7122 "Cycle through the files in `org-agenda-files'.
7123 If the current buffer visits an agenda file, find the next one in the list.
7124 If the current buffer does not, find the first agenda file."
7125 (interactive)
7126 (let* ((fs (org-agenda-files t))
7127 (files (append fs (list (car fs))))
7128 (tcf (if buffer-file-name (file-truename buffer-file-name)))
7129 file)
7130 (unless files (error "No agenda files"))
7131 (catch 'exit
7132 (while (setq file (pop files))
7133 (if (equal (file-truename file) tcf)
7134 (when (car files)
7135 (find-file (car files))
7136 (throw 'exit t))))
7137 (find-file (car fs)))))
7138
7139 (defun org-agenda-file-to-end ()
7140 "Move/add the current file to the end of the agenda file list.
7141 If the file is not present in the list, it is appended to the list. If it is
7142 present, it is moved there."
7143 (interactive)
7144 (org-agenda-file-to-front 'to-end))
7145
7146 (defun org-agenda-file-to-front (&optional to-end)
7147 "Move/add the current file to the top of the agenda file list.
7148 If the file is not present in the list, it is added to the front. If it is
7149 present, it is moved there. With optional argument TO-END, add/move to the
7150 end of the list."
7151 (interactive "P")
7152 (let ((file-alist (mapcar (lambda (x)
7153 (cons (file-truename x) x))
7154 (org-agenda-files t)))
7155 (ctf (file-truename buffer-file-name))
7156 x had)
7157 (setq x (assoc ctf file-alist) had x)
7158
7159 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
7160 (if to-end
7161 (setq file-alist (append (delq x file-alist) (list x)))
7162 (setq file-alist (cons x (delq x file-alist))))
7163 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
7164 (org-install-agenda-files-menu)
7165 (message "File %s to %s of agenda file list"
7166 (if had "moved" "added") (if to-end "end" "front"))))
7167
7168 (defun org-remove-file (&optional file)
7169 "Remove current file from the list of files in variable `org-agenda-files'.
7170 These are the files which are being checked for agenda entries.
7171 Optional argument FILE means, use this file instead of the current."
7172 (interactive)
7173 (let* ((file (or file buffer-file-name))
7174 (true-file (file-truename file))
7175 (afile (abbreviate-file-name file))
7176 (files (delq nil (mapcar
7177 (lambda (x)
7178 (if (equal true-file
7179 (file-truename x))
7180 nil x))
7181 (org-agenda-files t)))))
7182 (if (not (= (length files) (length (org-agenda-files t))))
7183 (progn
7184 (org-store-new-agenda-file-list files)
7185 (org-install-agenda-files-menu)
7186 (message "Removed file: %s" afile))
7187 (message "File was not in list: %s" afile))))
7188
7189 (defun org-file-menu-entry (file)
7190 (vector file (list 'find-file file) t))
7191
7192 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
7193 "Return a list of all relevant day numbers from BEG to END buffer positions.
7194 If NO-RANGES is non-nil, include only the start and end dates of a range,
7195 not every single day in the range. If FORCE-TODAY is non-nil, make
7196 sure that TODAY is included in the list. If INACTIVE is non-nil, also
7197 inactive time stamps (those in square brackets) are included.
7198 When EMPTY is non-nil, also include days without any entries."
7199 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
7200 dates dates1 date day day1 day2 ts1 ts2)
7201 (if force-today
7202 (setq dates (list (time-to-days (current-time)))))
7203 (save-excursion
7204 (goto-char beg)
7205 (while (re-search-forward re end t)
7206 (setq day (time-to-days (org-time-string-to-time
7207 (substring (match-string 1) 0 10))))
7208 (or (memq day dates) (push day dates)))
7209 (unless no-ranges
7210 (goto-char beg)
7211 (while (re-search-forward org-tr-regexp end t)
7212 (setq ts1 (substring (match-string 1) 0 10)
7213 ts2 (substring (match-string 2) 0 10)
7214 day1 (time-to-days (org-time-string-to-time ts1))
7215 day2 (time-to-days (org-time-string-to-time ts2)))
7216 (while (< (setq day1 (1+ day1)) day2)
7217 (or (memq day1 dates) (push day1 dates)))))
7218 (setq dates (sort dates '<))
7219 (when empty
7220 (while (setq day (pop dates))
7221 (setq day2 (car dates))
7222 (push day dates1)
7223 (when (and day2 empty)
7224 (if (or (eq empty t)
7225 (and (numberp empty) (<= (- day2 day) empty)))
7226 (while (< (setq day (1+ day)) day2)
7227 (push (list day) dates1))
7228 (push (cons :omitted (- day2 day)) dates1))))
7229 (setq dates (nreverse dates1)))
7230 dates)))
7231
7232 ;;;###autoload
7233 (defun org-diary (&rest args)
7234 "Return diary information from org-files.
7235 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
7236 It accesses org files and extracts information from those files to be
7237 listed in the diary. The function accepts arguments specifying what
7238 items should be listed. The following arguments are allowed:
7239
7240 :timestamp List the headlines of items containing a date stamp or
7241 date range matching the selected date. Deadlines will
7242 also be listed, on the expiration day.
7243
7244 :deadline List any deadlines past due, or due within
7245 `org-deadline-warning-days'. The listing occurs only
7246 in the diary for *today*, not at any other date. If
7247 an entry is marked DONE, it is no longer listed.
7248
7249 :scheduled List all items which are scheduled for the given date.
7250 The diary for *today* also contains items which were
7251 scheduled earlier and are not yet marked DONE.
7252
7253 :todo List all TODO items from the org-file. This may be a
7254 long list - so this is not turned on by default.
7255 Like deadlines, these entries only show up in the
7256 diary for *today*, not at any other date.
7257
7258 The call in the diary file should look like this:
7259
7260 &%%(org-diary) ~/path/to/some/orgfile.org
7261
7262 Use a separate line for each org file to check. Or, if you omit the file name,
7263 all files listed in `org-agenda-files' will be checked automatically:
7264
7265 &%%(org-diary)
7266
7267 If you don't give any arguments (as in the example above), the default
7268 arguments (:deadline :scheduled :timestamp) are used. So the example above may
7269 also be written as
7270
7271 &%%(org-diary :deadline :timestamp :scheduled)
7272
7273 The function expects the lisp variables `entry' and `date' to be provided
7274 by the caller, because this is how the calendar works. Don't use this
7275 function from a program - use `org-agenda-get-day-entries' instead."
7276 (org-agenda-maybe-reset-markers)
7277 (org-compile-prefix-format org-agenda-prefix-format)
7278 (setq args (or args '(:deadline :scheduled :timestamp)))
7279 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
7280 (list entry)
7281 (org-agenda-files t)))
7282 file rtn results)
7283 ;; If this is called during org-agenda, don't return any entries to
7284 ;; the calendar. Org Agenda will list these entries itself.
7285 (if org-disable-agenda-to-diary (setq files nil))
7286 (while (setq file (pop files))
7287 (setq rtn (apply 'org-agenda-get-day-entries file date args))
7288 (setq results (append results rtn)))
7289 (if results
7290 (concat (org-finalize-agenda-entries results) "\n"))))
7291 (defvar org-category-table nil)
7292 (defun org-get-category-table ()
7293 "Get the table of categories and positions in current buffer."
7294 (let (tbl)
7295 (save-excursion
7296 (goto-char (point-min))
7297 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
7298 (push (cons (point) (org-trim (match-string 2))) tbl)))
7299 tbl))
7300 (defun org-get-category (&optional pos)
7301 "Get the category applying to position POS."
7302 (if (not org-category-table)
7303 (cond
7304 ((null org-category)
7305 (setq org-category
7306 (if buffer-file-name
7307 (file-name-sans-extension
7308 (file-name-nondirectory buffer-file-name))
7309 "???")))
7310 ((symbolp org-category) (symbol-name org-category))
7311 (t org-category))
7312 (let ((tbl org-category-table)
7313 (pos (or pos (point))))
7314 (while (and tbl (> (caar tbl) pos))
7315 (pop tbl))
7316 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
7317 org-category-table))))))
7318
7319 (defun org-agenda-get-day-entries (file date &rest args)
7320 "Does the work for `org-diary' and `org-agenda'.
7321 FILE is the path to a file to be checked for entries. DATE is date like
7322 the one returned by `calendar-current-date'. ARGS are symbols indicating
7323 which kind of entries should be extracted. For details about these, see
7324 the documentation of `org-diary'."
7325 (setq args (or args '(:deadline :scheduled :timestamp)))
7326 (let* ((org-startup-with-deadline-check nil)
7327 (org-startup-folded nil)
7328 (org-startup-align-all-tables nil)
7329 (buffer (if (file-exists-p file)
7330 (org-get-agenda-file-buffer file)
7331 (error "No such file %s" file)))
7332 arg results rtn)
7333 (if (not buffer)
7334 ;; If file does not exist, make sure an error message ends up in diary
7335 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7336 (with-current-buffer buffer
7337 (unless (eq major-mode 'org-mode)
7338 (error "Agenda file %s is not in `org-mode'" file))
7339 (setq org-category-table (org-get-category-table))
7340 (let ((case-fold-search nil))
7341 (save-excursion
7342 (save-restriction
7343 (if org-respect-restriction
7344 (if (org-region-active-p)
7345 ;; Respect a region to restrict search
7346 (narrow-to-region (region-beginning) (region-end)))
7347 ;; If we work for the calendar or many files,
7348 ;; get rid of any restriction
7349 (widen))
7350 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
7351 (while (setq arg (pop args))
7352 (cond
7353 ((and (eq arg :todo)
7354 (equal date (calendar-current-date)))
7355 (setq rtn (org-agenda-get-todos))
7356 (setq results (append results rtn)))
7357 ((eq arg :timestamp)
7358 (setq rtn (org-agenda-get-blocks))
7359 (setq results (append results rtn))
7360 (setq rtn (org-agenda-get-timestamps))
7361 (setq results (append results rtn)))
7362 ((eq arg :scheduled)
7363 (setq rtn (org-agenda-get-scheduled))
7364 (setq results (append results rtn)))
7365 ((eq arg :closed)
7366 (setq rtn (org-agenda-get-closed))
7367 (setq results (append results rtn)))
7368 ((and (eq arg :deadline)
7369 (equal date (calendar-current-date)))
7370 (setq rtn (org-agenda-get-deadlines))
7371 (setq results (append results rtn))))))))
7372 results))))
7373
7374 (defun org-entry-is-done-p ()
7375 "Is the current entry marked DONE?"
7376 (save-excursion
7377 (and (re-search-backward "[\r\n]\\*" nil t)
7378 (looking-at org-nl-done-regexp))))
7379
7380 (defun org-at-date-range-p ()
7381 "Is the cursor inside a date range?"
7382 (interactive)
7383 (save-excursion
7384 (catch 'exit
7385 (let ((pos (point)))
7386 (skip-chars-backward "^<\r\n")
7387 (skip-chars-backward "<")
7388 (and (looking-at org-tr-regexp)
7389 (>= (match-end 0) pos)
7390 (throw 'exit t))
7391 (skip-chars-backward "^<\r\n")
7392 (skip-chars-backward "<")
7393 (and (looking-at org-tr-regexp)
7394 (>= (match-end 0) pos)
7395 (throw 'exit t)))
7396 nil)))
7397
7398 (defun org-agenda-get-todos ()
7399 "Return the TODO information for agenda display."
7400 (let* ((props (list 'face nil
7401 'done-face 'org-done
7402 'org-not-done-regexp org-not-done-regexp
7403 'mouse-face 'highlight
7404 'keymap org-agenda-keymap
7405 'help-echo
7406 (format "mouse-2 or RET jump to org file %s"
7407 (abbreviate-file-name buffer-file-name))))
7408 (regexp (concat "[\n\r]\\*+ *\\("
7409 (if org-select-this-todo-keyword
7410 (concat "\\<\\(" org-select-this-todo-keyword
7411 "\\)\\>")
7412 org-not-done-regexp)
7413 "[^\n\r]*\\)"))
7414 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
7415 marker priority category tags
7416 ee txt)
7417 (goto-char (point-min))
7418 (while (re-search-forward regexp nil t)
7419 (catch :skip
7420 (and org-agenda-todo-ignore-scheduled
7421 (looking-at sched-re)
7422 (throw :skip nil))
7423 (org-agenda-skip)
7424 (goto-char (match-beginning 1))
7425 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
7426 category (org-get-category)
7427 tags (org-get-tags-at (point))
7428 txt (org-format-agenda-item "" (match-string 1) category tags)
7429 priority
7430 (+ (org-get-priority txt)
7431 (if org-todo-kwd-priority-p
7432 (- org-todo-kwd-max-priority -2
7433 (length
7434 (member (match-string 2) org-todo-keywords)))
7435 1)))
7436 (org-add-props txt props
7437 'org-marker marker 'org-hd-marker marker
7438 'priority priority 'category category)
7439 (push txt ee)
7440 (if org-agenda-todo-list-sublevels
7441 (goto-char (match-end 1))
7442 (org-end-of-subtree 'invisible))))
7443 (nreverse ee)))
7444
7445 (defconst org-agenda-no-heading-message
7446 "No heading for this item in buffer or region.")
7447
7448 (defun org-agenda-get-timestamps ()
7449 "Return the date stamp information for agenda display."
7450 (let* ((props (list 'face nil
7451 'org-not-done-regexp org-not-done-regexp
7452 'mouse-face 'highlight
7453 'keymap org-agenda-keymap
7454 'help-echo
7455 (format "mouse-2 or RET jump to org file %s"
7456 (abbreviate-file-name buffer-file-name))))
7457 (regexp (regexp-quote
7458 (substring
7459 (format-time-string
7460 (car org-time-stamp-formats)
7461 (apply 'encode-time ; DATE bound by calendar
7462 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7463 0 11)))
7464 marker hdmarker deadlinep scheduledp donep tmp priority category
7465 ee txt timestr tags)
7466 (goto-char (point-min))
7467 (while (re-search-forward regexp nil t)
7468 (catch :skip
7469 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
7470 (org-agenda-skip)
7471 (setq marker (org-agenda-new-marker (match-beginning 0))
7472 category (org-get-category (match-beginning 0))
7473 tmp (buffer-substring (max (point-min)
7474 (- (match-beginning 0)
7475 org-ds-keyword-length))
7476 (match-beginning 0))
7477 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7478 deadlinep (string-match org-deadline-regexp tmp)
7479 scheduledp (string-match org-scheduled-regexp tmp)
7480 donep (org-entry-is-done-p))
7481 (if (string-match ">" timestr)
7482 ;; substring should only run to end of time stamp
7483 (setq timestr (substring timestr 0 (match-end 0))))
7484 (save-excursion
7485 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7486 (progn
7487 (goto-char (match-end 1))
7488 (setq hdmarker (org-agenda-new-marker)
7489 tags (org-get-tags-at))
7490 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7491 (setq txt (org-format-agenda-item
7492 (format "%s%s"
7493 (if deadlinep "Deadline: " "")
7494 (if scheduledp "Scheduled: " ""))
7495 (match-string 1) category tags timestr)))
7496 (setq txt org-agenda-no-heading-message))
7497 (setq priority (org-get-priority txt))
7498 (org-add-props txt props
7499 'org-marker marker 'org-hd-marker hdmarker)
7500 (if deadlinep
7501 (org-add-props txt nil
7502 'face (if donep 'org-done 'org-warning)
7503 'undone-face 'org-warning 'done-face 'org-done
7504 'category category 'priority (+ 100 priority))
7505 (if scheduledp
7506 (org-add-props txt nil
7507 'face 'org-scheduled-today
7508 'undone-face 'org-scheduled-today 'done-face 'org-done
7509 'category category 'priority (+ 99 priority))
7510 (org-add-props txt nil 'priority priority 'category category)))
7511 (push txt ee))
7512 (outline-next-heading)))
7513 (nreverse ee)))
7514
7515 (defun org-agenda-get-closed ()
7516 "Return the logged TODO entries for agenda display."
7517 (let* ((props (list 'mouse-face 'highlight
7518 'org-not-done-regexp org-not-done-regexp
7519 'keymap org-agenda-keymap
7520 'help-echo
7521 (format "mouse-2 or RET jump to org file %s"
7522 (abbreviate-file-name buffer-file-name))))
7523 (regexp (concat
7524 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
7525 (regexp-quote
7526 (substring
7527 (format-time-string
7528 (car org-time-stamp-formats)
7529 (apply 'encode-time ; DATE bound by calendar
7530 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7531 1 11))))
7532 marker hdmarker priority category tags closedp
7533 ee txt timestr)
7534 (goto-char (point-min))
7535 (while (re-search-forward regexp nil t)
7536 (catch :skip
7537 (org-agenda-skip)
7538 (setq marker (org-agenda-new-marker (match-beginning 0))
7539 closedp (equal (match-string 1) org-closed-string)
7540 category (org-get-category (match-beginning 0))
7541 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7542 ;; donep (org-entry-is-done-p)
7543 )
7544 (if (string-match "\\]" timestr)
7545 ;; substring should only run to end of time stamp
7546 (setq timestr (substring timestr 0 (match-end 0))))
7547 (save-excursion
7548 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7549 (progn
7550 (goto-char (match-end 1))
7551 (setq hdmarker (org-agenda-new-marker)
7552 tags (org-get-tags-at))
7553 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7554 (setq txt (org-format-agenda-item
7555 (if closedp "Closed: " "Clocked: ")
7556 (match-string 1) category tags timestr)))
7557 (setq txt org-agenda-no-heading-message))
7558 (setq priority 100000)
7559 (org-add-props txt props
7560 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
7561 'priority priority 'category category
7562 'undone-face 'org-warning 'done-face 'org-done)
7563 (push txt ee))
7564 (outline-next-heading)))
7565 (nreverse ee)))
7566
7567 (defun org-agenda-get-deadlines ()
7568 "Return the deadline information for agenda display."
7569 (let* ((wdays org-deadline-warning-days)
7570 (props (list 'mouse-face 'highlight
7571 'org-not-done-regexp org-not-done-regexp
7572 'keymap org-agenda-keymap
7573 'help-echo
7574 (format "mouse-2 or RET jump to org file %s"
7575 (abbreviate-file-name buffer-file-name))))
7576 (regexp org-deadline-time-regexp)
7577 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7578 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7579 d2 diff pos pos1 category tags
7580 ee txt head face)
7581 (goto-char (point-min))
7582 (while (re-search-forward regexp nil t)
7583 (catch :skip
7584 (org-agenda-skip)
7585 (setq pos (1- (match-beginning 1))
7586 d2 (time-to-days
7587 (org-time-string-to-time (match-string 1)))
7588 diff (- d2 d1))
7589 ;; When to show a deadline in the calendar:
7590 ;; If the expiration is within wdays warning time.
7591 ;; Past-due deadlines are only shown on the current date
7592 (if (and (< diff wdays) todayp (not (= diff 0)))
7593 (save-excursion
7594 (setq category (org-get-category))
7595 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7596 (progn
7597 (goto-char (match-end 0))
7598 (setq pos1 (match-end 1))
7599 (setq tags (org-get-tags-at pos1))
7600 (setq head (buffer-substring-no-properties
7601 (point)
7602 (progn (skip-chars-forward "^\r\n")
7603 (point))))
7604 (if (string-match org-looking-at-done-regexp head)
7605 (setq txt nil)
7606 (setq txt (org-format-agenda-item
7607 (format "In %3d d.: " diff) head category tags))))
7608 (setq txt org-agenda-no-heading-message))
7609 (when txt
7610 (setq face (cond ((<= diff 0) 'org-warning)
7611 ((<= diff 5) 'org-upcoming-deadline)
7612 (t nil)))
7613 (org-add-props txt props
7614 'org-marker (org-agenda-new-marker pos)
7615 'org-hd-marker (org-agenda-new-marker pos1)
7616 'priority (+ (- 10 diff) (org-get-priority txt))
7617 'category category
7618 'face face 'undone-face face 'done-face 'org-done)
7619 (push txt ee))))))
7620 ee))
7621
7622 (defun org-agenda-get-scheduled ()
7623 "Return the scheduled information for agenda display."
7624 (let* ((props (list 'face 'org-scheduled-previously
7625 'org-not-done-regexp org-not-done-regexp
7626 'undone-face 'org-scheduled-previously
7627 'done-face 'org-done
7628 'mouse-face 'highlight
7629 'keymap org-agenda-keymap
7630 'help-echo
7631 (format "mouse-2 or RET jump to org file %s"
7632 (abbreviate-file-name buffer-file-name))))
7633 (regexp org-scheduled-time-regexp)
7634 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7635 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7636 d2 diff pos pos1 category tags
7637 ee txt head)
7638 (goto-char (point-min))
7639 (while (re-search-forward regexp nil t)
7640 (catch :skip
7641 (org-agenda-skip)
7642 (setq pos (1- (match-beginning 1))
7643 d2 (time-to-days
7644 (org-time-string-to-time (match-string 1)))
7645 diff (- d2 d1))
7646 ;; When to show a scheduled item in the calendar:
7647 ;; If it is on or past the date.
7648 (if (and (< diff 0) todayp)
7649 (save-excursion
7650 (setq category (org-get-category))
7651 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7652 (progn
7653 (goto-char (match-end 0))
7654 (setq pos1 (match-end 1))
7655 (setq tags (org-get-tags-at))
7656 (setq head (buffer-substring-no-properties
7657 (point)
7658 (progn (skip-chars-forward "^\r\n") (point))))
7659 (if (string-match org-looking-at-done-regexp head)
7660 (setq txt nil)
7661 (setq txt (org-format-agenda-item
7662 (format "Sched.%2dx: " (- 1 diff)) head
7663 category tags))))
7664 (setq txt org-agenda-no-heading-message))
7665 (when txt
7666 (org-add-props txt props
7667 'org-marker (org-agenda-new-marker pos)
7668 'org-hd-marker (org-agenda-new-marker pos1)
7669 'priority (+ (- 5 diff) (org-get-priority txt))
7670 'category category)
7671 (push txt ee))))))
7672 ee))
7673
7674 (defun org-agenda-get-blocks ()
7675 "Return the date-range information for agenda display."
7676 (let* ((props (list 'face nil
7677 'org-not-done-regexp org-not-done-regexp
7678 'mouse-face 'highlight
7679 'keymap org-agenda-keymap
7680 'help-echo
7681 (format "mouse-2 or RET jump to org file %s"
7682 (abbreviate-file-name buffer-file-name))))
7683 (regexp org-tr-regexp)
7684 (d0 (calendar-absolute-from-gregorian date))
7685 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
7686 (goto-char (point-min))
7687 (while (re-search-forward regexp nil t)
7688 (catch :skip
7689 (org-agenda-skip)
7690 (setq timestr (match-string 0)
7691 s1 (match-string 1)
7692 s2 (match-string 2)
7693 d1 (time-to-days (org-time-string-to-time s1))
7694 d2 (time-to-days (org-time-string-to-time s2)))
7695 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
7696 ;; Only allow days between the limits, because the normal
7697 ;; date stamps will catch the limits.
7698 (save-excursion
7699 (setq marker (org-agenda-new-marker (point)))
7700 (setq category (org-get-category))
7701 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7702 (progn
7703 (setq hdmarker (org-agenda-new-marker (match-end 1)))
7704 (goto-char (match-end 1))
7705 (setq tags (org-get-tags-at))
7706 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7707 (setq txt (org-format-agenda-item
7708 (format (if (= d1 d2) "" "(%d/%d): ")
7709 (1+ (- d0 d1)) (1+ (- d2 d1)))
7710 (match-string 1) category tags
7711 (if (= d0 d1) timestr))))
7712 (setq txt org-agenda-no-heading-message))
7713 (org-add-props txt props
7714 'org-marker marker 'org-hd-marker hdmarker
7715 'priority (org-get-priority txt) 'category category)
7716 (push txt ee)))
7717 (outline-next-heading)))
7718 ;; Sort the entries by expiration date.
7719 (nreverse ee)))
7720
7721 (defconst org-plain-time-of-day-regexp
7722 (concat
7723 "\\(\\<[012]?[0-9]"
7724 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7725 "\\(--?"
7726 "\\(\\<[012]?[0-9]"
7727 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7728 "\\)?")
7729 "Regular expression to match a plain time or time range.
7730 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
7731 groups carry important information:
7732 0 the full match
7733 1 the first time, range or not
7734 8 the second time, if it is a range.")
7735
7736 (defconst org-stamp-time-of-day-regexp
7737 (concat
7738 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
7739 "\\([012][0-9]:[0-5][0-9]\\)>"
7740 "\\(--?"
7741 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
7742 "Regular expression to match a timestamp time or time range.
7743 After a match, the following groups carry important information:
7744 0 the full match
7745 1 date plus weekday, for backreferencing to make sure both times on same day
7746 2 the first time, range or not
7747 4 the second time, if it is a range.")
7748
7749 (defvar org-prefix-has-time nil
7750 "A flag, set by `org-compile-prefix-format'.
7751 The flag is set if the currently compiled format contains a `%t'.")
7752 (defvar org-prefix-has-tag nil
7753 "A flag, set by `org-compile-prefix-format'.
7754 The flag is set if the currently compiled format contains a `%T'.")
7755
7756 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
7757 "Format TXT to be inserted into the agenda buffer.
7758 In particular, it adds the prefix and corresponding text properties. EXTRA
7759 must be a string and replaces the `%s' specifier in the prefix format.
7760 CATEGORY (string, symbol or nil) may be used to overrule the default
7761 category taken from local variable or file name. It will replace the `%c'
7762 specifier in the format. DOTIME, when non-nil, indicates that a
7763 time-of-day should be extracted from TXT for sorting of this entry, and for
7764 the `%t' specifier in the format. When DOTIME is a string, this string is
7765 searched for a time before TXT is. NOPREFIX is a flag and indicates that
7766 only the correctly processes TXT should be returned - this is used by
7767 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
7768 (save-match-data
7769 ;; Diary entries sometimes have extra whitespace at the beginning
7770 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
7771 (let* ((category (or category
7772 org-category
7773 (if buffer-file-name
7774 (file-name-sans-extension
7775 (file-name-nondirectory buffer-file-name))
7776 "")))
7777 (tag (if tags (nth (1- (length tags)) tags) ""))
7778 time ;; needed for the eval of the prefix format
7779 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
7780 (time-of-day (and dotime (org-get-time-of-day ts)))
7781 stamp plain s0 s1 s2 rtn)
7782 (when (and dotime time-of-day org-prefix-has-time)
7783 ;; Extract starting and ending time and move them to prefix
7784 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
7785 (setq plain (string-match org-plain-time-of-day-regexp ts)))
7786 (setq s0 (match-string 0 ts)
7787 s1 (match-string (if plain 1 2) ts)
7788 s2 (match-string (if plain 8 4) ts))
7789
7790 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
7791 ;; them, we might want to remove them there to avoid duplication.
7792 ;; The user can turn this off with a variable.
7793 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
7794 (string-match (concat (regexp-quote s0) " *") txt)
7795 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
7796 (= (match-beginning 0) 0)
7797 t))
7798 (setq txt (replace-match "" nil nil txt))))
7799 ;; Normalize the time(s) to 24 hour
7800 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
7801 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
7802
7803 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
7804 ;; Tags are in the string
7805 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
7806 (and org-agenda-remove-tags-when-in-prefix
7807 org-prefix-has-tag))
7808 (setq txt (replace-match "" t t txt))
7809 (setq txt (replace-match
7810 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
7811 (match-string 2 txt))
7812 t t txt))))
7813
7814 ;; Create the final string
7815 (if noprefix
7816 (setq rtn txt)
7817 ;; Prepare the variables needed in the eval of the compiled format
7818 (setq time (cond (s2 (concat s1 "-" s2))
7819 (s1 (concat s1 "......"))
7820 (t ""))
7821 extra (or extra "")
7822 category (if (symbolp category) (symbol-name category) category))
7823 ;; Evaluate the compiled format
7824 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
7825
7826 ;; And finally add the text properties
7827 (org-add-props rtn nil
7828 'category (downcase category) 'tags tags
7829 'prefix-length (- (length rtn) (length txt))
7830 'time-of-day time-of-day
7831 'dotime dotime))))
7832
7833 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
7834 (catch 'exit
7835 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
7836 ((and todayp (member 'today (car org-agenda-time-grid))))
7837 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
7838 ((member 'weekly (car org-agenda-time-grid)))
7839 (t (throw 'exit list)))
7840 (let* ((have (delq nil (mapcar
7841 (lambda (x) (get-text-property 1 'time-of-day x))
7842 list)))
7843 (string (nth 1 org-agenda-time-grid))
7844 (gridtimes (nth 2 org-agenda-time-grid))
7845 (req (car org-agenda-time-grid))
7846 (remove (member 'remove-match req))
7847 new time)
7848 (if (and (member 'require-timed req) (not have))
7849 ;; don't show empty grid
7850 (throw 'exit list))
7851 (while (setq time (pop gridtimes))
7852 (unless (and remove (member time have))
7853 (setq time (int-to-string time))
7854 (push (org-format-agenda-item
7855 nil string "" nil
7856 (concat (substring time 0 -2) ":" (substring time -2)))
7857 new)
7858 (put-text-property
7859 1 (length (car new)) 'face 'org-time-grid (car new))))
7860 (if (member 'time-up org-agenda-sorting-strategy)
7861 (append new list)
7862 (append list new)))))
7863
7864 (defun org-compile-prefix-format (format)
7865 "Compile the prefix format into a Lisp form that can be evaluated.
7866 The resulting form is returned and stored in the variable
7867 `org-prefix-format-compiled'."
7868 (setq org-prefix-has-time nil org-prefix-has-tag nil)
7869 (let ((start 0) varform vars var (s format)e c f opt)
7870 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
7871 s start)
7872 (setq var (cdr (assoc (match-string 4 s)
7873 '(("c" . category) ("t" . time) ("s" . extra)
7874 ("T" . tag))))
7875 c (or (match-string 3 s) "")
7876 opt (match-beginning 1)
7877 start (1+ (match-beginning 0)))
7878 (if (equal var 'time) (setq org-prefix-has-time t))
7879 (if (equal var 'tag) (setq org-prefix-has-tag t))
7880 (setq f (concat "%" (match-string 2 s) "s"))
7881 (if opt
7882 (setq varform
7883 `(if (equal "" ,var)
7884 ""
7885 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
7886 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
7887 (setq s (replace-match "%s" t nil s))
7888 (push varform vars))
7889 (setq vars (nreverse vars))
7890 (setq org-prefix-format-compiled `(format ,s ,@vars))))
7891
7892 (defun org-get-time-of-day (s &optional string mod24)
7893 "Check string S for a time of day.
7894 If found, return it as a military time number between 0 and 2400.
7895 If not found, return nil.
7896 The optional STRING argument forces conversion into a 5 character wide string
7897 HH:MM."
7898 (save-match-data
7899 (when
7900 (or
7901 (string-match
7902 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
7903 (string-match
7904 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
7905 (let* ((h (string-to-number (match-string 1 s)))
7906 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
7907 (ampm (if (match-end 4) (downcase (match-string 4 s))))
7908 (am-p (equal ampm "am"))
7909 (h1 (cond ((not ampm) h)
7910 ((= h 12) (if am-p 0 12))
7911 (t (+ h (if am-p 0 12)))))
7912 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
7913 (mod h1 24) h1))
7914 (t0 (+ (* 100 h2) m))
7915 (t1 (concat (if (>= h1 24) "+" " ")
7916 (if (< t0 100) "0" "")
7917 (if (< t0 10) "0" "")
7918 (int-to-string t0))))
7919 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
7920
7921 (defun org-finalize-agenda-entries (list)
7922 "Sort and concatenate the agenda items."
7923 (setq list (mapcar 'org-agenda-highlight-todo list))
7924 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
7925
7926 (defun org-agenda-highlight-todo (x)
7927 (let (re pl)
7928 (if (eq x 'line)
7929 (save-excursion
7930 (beginning-of-line 1)
7931 (setq re (get-text-property (point) 'org-not-done-regexp))
7932 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
7933 (and (looking-at (concat "[ \t]*" re))
7934 (add-text-properties (match-beginning 0) (match-end 0)
7935 '(face org-todo))))
7936 (setq re (get-text-property 0 'org-not-done-regexp x)
7937 pl (get-text-property 0 'prefix-length x))
7938 (and re (equal (string-match re x pl) pl)
7939 (add-text-properties (match-beginning 0) (match-end 0)
7940 '(face org-todo) x))
7941 x)))
7942
7943 (defsubst org-cmp-priority (a b)
7944 "Compare the priorities of string A and B."
7945 (let ((pa (or (get-text-property 1 'priority a) 0))
7946 (pb (or (get-text-property 1 'priority b) 0)))
7947 (cond ((> pa pb) +1)
7948 ((< pa pb) -1)
7949 (t nil))))
7950
7951 (defsubst org-cmp-category (a b)
7952 "Compare the string values of categories of strings A and B."
7953 (let ((ca (or (get-text-property 1 'category a) ""))
7954 (cb (or (get-text-property 1 'category b) "")))
7955 (cond ((string-lessp ca cb) -1)
7956 ((string-lessp cb ca) +1)
7957 (t nil))))
7958
7959 (defsubst org-cmp-time (a b)
7960 "Compare the time-of-day values of strings A and B."
7961 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
7962 (ta (or (get-text-property 1 'time-of-day a) def))
7963 (tb (or (get-text-property 1 'time-of-day b) def)))
7964 (cond ((< ta tb) -1)
7965 ((< tb ta) +1)
7966 (t nil))))
7967
7968 (defun org-entries-lessp (a b)
7969 "Predicate for sorting agenda entries."
7970 ;; The following variables will be used when the form is evaluated.
7971 (let* ((time-up (org-cmp-time a b))
7972 (time-down (if time-up (- time-up) nil))
7973 (priority-up (org-cmp-priority a b))
7974 (priority-down (if priority-up (- priority-up) nil))
7975 (category-up (org-cmp-category a b))
7976 (category-down (if category-up (- category-up) nil))
7977 (category-keep (if category-up +1 nil)))
7978 (cdr (assoc
7979 (eval (cons 'or org-agenda-sorting-strategy))
7980 '((-1 . t) (1 . nil) (nil . nil))))))
7981
7982 (defun org-agenda-show-priority ()
7983 "Show the priority of the current item.
7984 This priority is composed of the main priority given with the [#A] cookies,
7985 and by additional input from the age of a schedules or deadline entry."
7986 (interactive)
7987 (let* ((pri (get-text-property (point-at-bol) 'priority)))
7988 (message "Priority is %d" (if pri pri -1000))))
7989
7990 (defun org-agenda-show-tags ()
7991 "Show the tags applicable to the current item."
7992 (interactive)
7993 (let* ((tags (get-text-property (point-at-bol) 'tags)))
7994 (if tags
7995 (message "Tags are :%s:"
7996 (org-no-properties (mapconcat 'identity tags ":")))
7997 (message "No tags associated with this line"))))
7998
7999 (defun org-agenda-goto (&optional highlight)
8000 "Go to the Org-mode file which contains the item at point."
8001 (interactive)
8002 (let* ((marker (or (get-text-property (point) 'org-marker)
8003 (org-agenda-error)))
8004 (buffer (marker-buffer marker))
8005 (pos (marker-position marker)))
8006 (switch-to-buffer-other-window buffer)
8007 (widen)
8008 (goto-char pos)
8009 (when (eq major-mode 'org-mode)
8010 (org-show-hidden-entry)
8011 (save-excursion
8012 (and (outline-next-heading)
8013 (org-flag-heading nil)))) ; show the next heading
8014 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
8015
8016 (defun org-agenda-switch-to ()
8017 "Go to the Org-mode file which contains the item at point."
8018 (interactive)
8019 (let* ((marker (or (get-text-property (point) 'org-marker)
8020 (org-agenda-error)))
8021 (buffer (marker-buffer marker))
8022 (pos (marker-position marker)))
8023 (switch-to-buffer buffer)
8024 (delete-other-windows)
8025 (widen)
8026 (goto-char pos)
8027 (when (eq major-mode 'org-mode)
8028 (org-show-hidden-entry)
8029 (save-excursion
8030 (and (outline-next-heading)
8031 (org-flag-heading nil)))))) ; show the next heading
8032
8033 (defun org-agenda-goto-mouse (ev)
8034 "Go to the Org-mode file which contains the item at the mouse click."
8035 (interactive "e")
8036 (mouse-set-point ev)
8037 (org-agenda-goto))
8038
8039 (defun org-agenda-show ()
8040 "Display the Org-mode file which contains the item at point."
8041 (interactive)
8042 (let ((win (selected-window)))
8043 (org-agenda-goto t)
8044 (select-window win)))
8045
8046 (defun org-agenda-recenter (arg)
8047 "Display the Org-mode file which contains the item at point and recenter."
8048 (interactive "P")
8049 (let ((win (selected-window)))
8050 (org-agenda-goto t)
8051 (recenter arg)
8052 (select-window win)))
8053
8054 (defun org-agenda-show-mouse (ev)
8055 "Display the Org-mode file which contains the item at the mouse click."
8056 (interactive "e")
8057 (mouse-set-point ev)
8058 (org-agenda-show))
8059
8060 (defun org-agenda-check-no-diary ()
8061 "Check if the entry is a diary link and abort if yes."
8062 (if (get-text-property (point) 'org-agenda-diary-link)
8063 (org-agenda-error)))
8064
8065 (defun org-agenda-error ()
8066 (error "Command not allowed in this line"))
8067
8068 (defvar org-last-heading-marker (make-marker)
8069 "Marker pointing to the headline that last changed its TODO state
8070 by a remote command from the agenda.")
8071
8072 (defun org-agenda-todo (&optional arg)
8073 "Cycle TODO state of line at point, also in Org-mode file.
8074 This changes the line at point, all other lines in the agenda referring to
8075 the same tree node, and the headline of the tree node in the Org-mode file."
8076 (interactive "P")
8077 (org-agenda-check-no-diary)
8078 (let* ((col (current-column))
8079 (marker (or (get-text-property (point) 'org-marker)
8080 (org-agenda-error)))
8081 (buffer (marker-buffer marker))
8082 (pos (marker-position marker))
8083 (hdmarker (get-text-property (point) 'org-hd-marker))
8084 (buffer-read-only nil)
8085 newhead)
8086 (with-current-buffer buffer
8087 (widen)
8088 (goto-char pos)
8089 (org-show-hidden-entry)
8090 (save-excursion
8091 (and (outline-next-heading)
8092 (org-flag-heading nil))) ; show the next heading
8093 (org-todo arg)
8094 (and (bolp) (forward-char 1))
8095 (setq newhead (org-get-heading))
8096 (save-excursion
8097 (org-back-to-heading)
8098 (move-marker org-last-heading-marker (point))))
8099 (beginning-of-line 1)
8100 (save-excursion
8101 (org-agenda-change-all-lines newhead hdmarker 'fixface))
8102 (move-to-column col)))
8103
8104 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
8105 "Change all lines in the agenda buffer which match HDMARKER.
8106 The new content of the line will be NEWHEAD (as modified by
8107 `org-format-agenda-item'). HDMARKER is checked with
8108 `equal' against all `org-hd-marker' text properties in the file.
8109 If FIXFACE is non-nil, the face of each item is modified acording to
8110 the new TODO state."
8111 (let* (props m pl undone-face done-face finish new dotime cat tags)
8112 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
8113 (save-excursion
8114 (goto-char (point-max))
8115 (beginning-of-line 1)
8116 (while (not finish)
8117 (setq finish (bobp))
8118 (when (and (setq m (get-text-property (point) 'org-hd-marker))
8119 (equal m hdmarker))
8120 (setq props (text-properties-at (point))
8121 dotime (get-text-property (point) 'dotime)
8122 cat (get-text-property (point) 'category)
8123 tags (get-text-property (point) 'tags)
8124 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
8125 pl (get-text-property (point) 'prefix-length)
8126 undone-face (get-text-property (point) 'undone-face)
8127 done-face (get-text-property (point) 'done-face))
8128 (move-to-column pl)
8129 (if (looking-at ".*")
8130 (progn
8131 (replace-match new t t)
8132 (beginning-of-line 1)
8133 (add-text-properties (point-at-bol) (point-at-eol) props)
8134 (when fixface
8135 (add-text-properties
8136 (point-at-bol) (point-at-eol)
8137 (list 'face
8138 (if org-last-todo-state-is-todo
8139 undone-face done-face)))
8140 (org-agenda-highlight-todo 'line))
8141 (beginning-of-line 1))
8142 (error "Line update did not work")))
8143 (beginning-of-line 0)))))
8144
8145 (defun org-agenda-priority-up ()
8146 "Increase the priority of line at point, also in Org-mode file."
8147 (interactive)
8148 (org-agenda-priority 'up))
8149
8150 (defun org-agenda-priority-down ()
8151 "Decrease the priority of line at point, also in Org-mode file."
8152 (interactive)
8153 (org-agenda-priority 'down))
8154
8155 (defun org-agenda-priority (&optional force-direction)
8156 "Set the priority of line at point, also in Org-mode file.
8157 This changes the line at point, all other lines in the agenda referring to
8158 the same tree node, and the headline of the tree node in the Org-mode file."
8159 (interactive)
8160 (org-agenda-check-no-diary)
8161 (let* ((marker (or (get-text-property (point) 'org-marker)
8162 (org-agenda-error)))
8163 (buffer (marker-buffer marker))
8164 (pos (marker-position marker))
8165 (hdmarker (get-text-property (point) 'org-hd-marker))
8166 (buffer-read-only nil)
8167 newhead)
8168 (with-current-buffer buffer
8169 (widen)
8170 (goto-char pos)
8171 (org-show-hidden-entry)
8172 (save-excursion
8173 (and (outline-next-heading)
8174 (org-flag-heading nil))) ; show the next heading
8175 (funcall 'org-priority force-direction)
8176 (end-of-line 1)
8177 (setq newhead (org-get-heading)))
8178 (org-agenda-change-all-lines newhead hdmarker)
8179 (beginning-of-line 1)))
8180
8181 (defun org-get-tags-at (&optional pos)
8182 "Get a list of all headline tags applicable at POS.
8183 POS defaults to point. If tags are inherited, the list contains
8184 the targets in the same sequence as the headlines appear, i.e.
8185 the tags of the current headline come last."
8186 (interactive)
8187 (let (tags)
8188 (save-excursion
8189 (goto-char (or pos (point)))
8190 (save-match-data
8191 (org-back-to-heading t)
8192 (condition-case nil
8193 (while t
8194 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
8195 (setq tags (append (org-split-string
8196 (org-match-string-no-properties 1) ":")
8197 tags)))
8198 (or org-use-tag-inheritance (error ""))
8199 (org-up-heading-all 1))
8200 (error nil))))
8201 (message "%s" tags)
8202 tags))
8203
8204 (defun org-agenda-set-tags ()
8205 "Set tags for the current headline."
8206 (interactive)
8207 (org-agenda-check-no-diary)
8208 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
8209 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
8210 (org-agenda-error)))
8211 (buffer (marker-buffer hdmarker))
8212 (pos (marker-position hdmarker))
8213 (buffer-read-only nil)
8214 newhead)
8215 (with-current-buffer buffer
8216 (widen)
8217 (goto-char pos)
8218 (org-show-hidden-entry)
8219 (save-excursion
8220 (and (outline-next-heading)
8221 (org-flag-heading nil))) ; show the next heading
8222 (call-interactively 'org-set-tags)
8223 (end-of-line 1)
8224 (setq newhead (org-get-heading)))
8225 (org-agenda-change-all-lines newhead hdmarker)
8226 (beginning-of-line 1)))
8227
8228 (defun org-agenda-date-later (arg &optional what)
8229 "Change the date of this item to one day later."
8230 (interactive "p")
8231 (org-agenda-check-type t 'agenda 'timeline)
8232 (org-agenda-check-no-diary)
8233 (let* ((marker (or (get-text-property (point) 'org-marker)
8234 (org-agenda-error)))
8235 (buffer (marker-buffer marker))
8236 (pos (marker-position marker)))
8237 (with-current-buffer buffer
8238 (widen)
8239 (goto-char pos)
8240 (if (not (org-at-timestamp-p))
8241 (error "Cannot find time stamp"))
8242 (org-timestamp-change arg (or what 'day))
8243 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8244
8245 (defun org-agenda-date-earlier (arg &optional what)
8246 "Change the date of this item to one day earlier."
8247 (interactive "p")
8248 (org-agenda-date-later (- arg) what))
8249
8250 (defun org-agenda-date-prompt (arg)
8251 "Change the date of this item. Date is prompted for, with default today.
8252 The prefix ARG is passed to the `org-time-stamp' command and can therefore
8253 be used to request time specification in the time stamp."
8254 (interactive "P")
8255 (org-agenda-check-type t 'agenda 'timeline)
8256 (org-agenda-check-no-diary)
8257 (let* ((marker (or (get-text-property (point) 'org-marker)
8258 (org-agenda-error)))
8259 (buffer (marker-buffer marker))
8260 (pos (marker-position marker)))
8261 (with-current-buffer buffer
8262 (widen)
8263 (goto-char pos)
8264 (if (not (org-at-timestamp-p))
8265 (error "Cannot find time stamp"))
8266 (org-time-stamp arg)
8267 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8268
8269 (defun org-agenda-schedule (arg)
8270 "Schedule the item at point."
8271 (interactive "P")
8272 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8273 (org-agenda-check-no-diary)
8274 (let* ((marker (or (get-text-property (point) 'org-marker)
8275 (org-agenda-error)))
8276 (buffer (marker-buffer marker))
8277 (pos (marker-position marker))
8278 (org-insert-labeled-timestamps-at-point nil)
8279 ts)
8280 (with-current-buffer buffer
8281 (widen)
8282 (goto-char pos)
8283 (setq ts (org-schedule))
8284 (message "Item scheduled for %s" ts))))
8285
8286 (defun org-agenda-deadline (arg)
8287 "Schedule the item at point."
8288 (interactive "P")
8289 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8290 (org-agenda-check-no-diary)
8291 (let* ((marker (or (get-text-property (point) 'org-marker)
8292 (org-agenda-error)))
8293 (buffer (marker-buffer marker))
8294 (pos (marker-position marker))
8295 (org-insert-labeled-timestamps-at-point nil)
8296 ts)
8297 (with-current-buffer buffer
8298 (widen)
8299 (goto-char pos)
8300 (setq ts (org-deadline))
8301 (message "Deadline for this item set to %s" ts))))
8302
8303 (defun org-get-heading ()
8304 "Return the heading of the current entry, without the stars."
8305 (save-excursion
8306 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
8307 (if (and (re-search-backward "[\r\n]\\*" nil t)
8308 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
8309 (match-string 1)
8310 "")))
8311
8312 (defun org-agenda-clock-in (&optional arg)
8313 "Start the clock on the currently selected item."
8314 (interactive "P")
8315 (org-agenda-check-no-diary)
8316 (let* ((marker (or (get-text-property (point) 'org-marker)
8317 (org-agenda-error)))
8318 (pos (marker-position marker)))
8319 (with-current-buffer (marker-buffer marker)
8320 (widen)
8321 (goto-char pos)
8322 (org-clock-in))))
8323
8324 (defun org-agenda-diary-entry ()
8325 "Make a diary entry, like the `i' command from the calendar.
8326 All the standard commands work: block, weekly etc."
8327 (interactive)
8328 (org-agenda-check-type t 'agenda 'timeline)
8329 (require 'diary-lib)
8330 (let* ((char (progn
8331 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
8332 (read-char-exclusive)))
8333 (cmd (cdr (assoc char
8334 '((?d . insert-diary-entry)
8335 (?w . insert-weekly-diary-entry)
8336 (?m . insert-monthly-diary-entry)
8337 (?y . insert-yearly-diary-entry)
8338 (?a . insert-anniversary-diary-entry)
8339 (?b . insert-block-diary-entry)
8340 (?c . insert-cyclic-diary-entry)))))
8341 (oldf (symbol-function 'calendar-cursor-to-date))
8342 (point (point))
8343 (mark (or (mark t) (point))))
8344 (unless cmd
8345 (error "No command associated with <%c>" char))
8346 (unless (and (get-text-property point 'day)
8347 (or (not (equal ?b char))
8348 (get-text-property mark 'day)))
8349 (error "Don't know which date to use for diary entry"))
8350 ;; We implement this by hacking the `calendar-cursor-to-date' function
8351 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
8352 (let ((calendar-mark-ring
8353 (list (calendar-gregorian-from-absolute
8354 (or (get-text-property mark 'day)
8355 (get-text-property point 'day))))))
8356 (unwind-protect
8357 (progn
8358 (fset 'calendar-cursor-to-date
8359 (lambda (&optional error)
8360 (calendar-gregorian-from-absolute
8361 (get-text-property point 'day))))
8362 (call-interactively cmd))
8363 (fset 'calendar-cursor-to-date oldf)))))
8364
8365
8366 (defun org-agenda-execute-calendar-command (cmd)
8367 "Execute a calendar command from the agenda, with the date associated to
8368 the cursor position."
8369 (org-agenda-check-type t 'agenda 'timeline)
8370 (require 'diary-lib)
8371 (unless (get-text-property (point) 'day)
8372 (error "Don't know which date to use for calendar command"))
8373 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
8374 (point (point))
8375 (date (calendar-gregorian-from-absolute
8376 (get-text-property point 'day)))
8377 (displayed-day (extract-calendar-day date))
8378 (displayed-month (extract-calendar-month date))
8379 (displayed-year (extract-calendar-year date)))
8380 (unwind-protect
8381 (progn
8382 (fset 'calendar-cursor-to-date
8383 (lambda (&optional error)
8384 (calendar-gregorian-from-absolute
8385 (get-text-property point 'day))))
8386 (call-interactively cmd))
8387 (fset 'calendar-cursor-to-date oldf))))
8388
8389 (defun org-agenda-phases-of-moon ()
8390 "Display the phases of the moon for the 3 months around the cursor date."
8391 (interactive)
8392 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
8393
8394 (defun org-agenda-holidays ()
8395 "Display the holidays for the 3 months around the cursor date."
8396 (interactive)
8397 (org-agenda-execute-calendar-command 'list-calendar-holidays))
8398
8399 (defun org-agenda-sunrise-sunset (arg)
8400 "Display sunrise and sunset for the cursor date.
8401 Latitude and longitude can be specified with the variables
8402 `calendar-latitude' and `calendar-longitude'. When called with prefix
8403 argument, latitude and longitude will be prompted for."
8404 (interactive "P")
8405 (let ((calendar-longitude (if arg nil calendar-longitude))
8406 (calendar-latitude (if arg nil calendar-latitude))
8407 (calendar-location-name
8408 (if arg "the given coordinates" calendar-location-name)))
8409 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
8410
8411 (defun org-agenda-goto-calendar ()
8412 "Open the Emacs calendar with the date at the cursor."
8413 (interactive)
8414 (org-agenda-check-type t 'agenda 'timeline)
8415 (let* ((day (or (get-text-property (point) 'day)
8416 (error "Don't know which date to open in calendar")))
8417 (date (calendar-gregorian-from-absolute day))
8418 (calendar-move-hook nil)
8419 (view-calendar-holidays-initially nil)
8420 (view-diary-entries-initially nil))
8421 (calendar)
8422 (calendar-goto-date date)))
8423
8424 (defun org-calendar-goto-agenda ()
8425 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
8426 This is a command that has to be installed in `calendar-mode-map'."
8427 (interactive)
8428 (org-agenda-list nil (calendar-absolute-from-gregorian
8429 (calendar-cursor-to-date))
8430 nil t))
8431
8432 (defun org-agenda-convert-date ()
8433 (interactive)
8434 (org-agenda-check-type t 'agenda 'timeline)
8435 (let ((day (get-text-property (point) 'day))
8436 date s)
8437 (unless day
8438 (error "Don't know which date to convert"))
8439 (setq date (calendar-gregorian-from-absolute day))
8440 (setq s (concat
8441 "Gregorian: " (calendar-date-string date) "\n"
8442 "ISO: " (calendar-iso-date-string date) "\n"
8443 "Day of Yr: " (calendar-day-of-year-string date) "\n"
8444 "Julian: " (calendar-julian-date-string date) "\n"
8445 "Astron. JD: " (calendar-astro-date-string date)
8446 " (Julian date number at noon UTC)\n"
8447 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
8448 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
8449 "French: " (calendar-french-date-string date) "\n"
8450 "Mayan: " (calendar-mayan-date-string date) "\n"
8451 "Coptic: " (calendar-coptic-date-string date) "\n"
8452 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
8453 "Persian: " (calendar-persian-date-string date) "\n"
8454 "Chinese: " (calendar-chinese-date-string date) "\n"))
8455 (with-output-to-temp-buffer "*Dates*"
8456 (princ s))
8457 (if (fboundp 'fit-window-to-buffer)
8458 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
8459
8460 ;;; Tags
8461
8462 (defun org-scan-tags (action matcher &optional todo-only)
8463 "Scan headline tags with inheritance and produce output ACTION.
8464 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8465 evaluated, testing if a given set of tags qualifies a headline for
8466 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8467 are included in the output."
8468 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8469 (mapconcat 'regexp-quote
8470 (nreverse (cdr (reverse org-todo-keywords)))
8471 "\\|")
8472 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
8473 (props (list 'face nil
8474 'done-face 'org-done
8475 'undone-face nil
8476 'mouse-face 'highlight
8477 'keymap org-agenda-keymap
8478 'help-echo
8479 (format "mouse-2 or RET jump to org file %s"
8480 (abbreviate-file-name buffer-file-name))))
8481 lspos
8482 tags tags-list tags-alist (llast 0) rtn level category i txt
8483 todo marker)
8484 (save-excursion
8485 (goto-char (point-min))
8486 (when (eq action 'sparse-tree) (org-overview))
8487 (while (re-search-forward re nil t)
8488 (catch :skip
8489 (and (eq action 'agenda) (org-agenda-skip))
8490 (setq todo (if (match-end 1) (match-string 2))
8491 tags (if (match-end 4) (match-string 4)))
8492 (goto-char (setq lspos (1+ (match-beginning 0))))
8493 (setq level (funcall outline-level)
8494 category (org-get-category))
8495 (setq i llast llast level)
8496 ;; remove tag lists from same and sublevels
8497 (while (>= i level)
8498 (when (setq entry (assoc i tags-alist))
8499 (setq tags-alist (delete entry tags-alist)))
8500 (setq i (1- i)))
8501 ;; add the nex tags
8502 (when tags
8503 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8504 tags-alist
8505 (cons (cons level tags) tags-alist)))
8506 ;; compile tags for current headline
8507 (setq tags-list
8508 (if org-use-tag-inheritance
8509 (apply 'append (mapcar 'cdr tags-alist))
8510 tags))
8511 (when (and (or (not todo-only) todo)
8512 (eval matcher)
8513 (or (not org-agenda-skip-archived-trees)
8514 (not (member org-archive-tag tags-list))))
8515 ;; list this headline
8516 (if (eq action 'sparse-tree)
8517 (progn
8518 (org-show-hierarchy-above))
8519 (setq txt (org-format-agenda-item
8520 ""
8521 (concat
8522 (if org-tags-match-list-sublevels
8523 (make-string (1- level) ?.) "")
8524 (org-get-heading))
8525 category tags-list))
8526 (goto-char lspos)
8527 (setq marker (org-agenda-new-marker))
8528 (org-add-props txt props
8529 'org-marker marker 'org-hd-marker marker 'category category)
8530 (push txt rtn))
8531 ;; if we are to skip sublevels, jump to end of subtree
8532 (point)
8533 (or org-tags-match-list-sublevels (org-end-of-subtree))))))
8534 (when (and (eq action 'sparse-tree)
8535 (not org-sparse-tree-open-archived-trees))
8536 (org-hide-archived-subtrees (point-min) (point-max)))
8537 (nreverse rtn)))
8538
8539 (defun org-tags-sparse-tree (&optional arg match)
8540 "Create a sparse tree according to tags search string MATCH.
8541 MATCH can contain positive and negative selection of tags, like
8542 \"+WORK+URGENT-WITHBOSS\"."
8543 (interactive "P")
8544 (let ((org-show-following-heading nil)
8545 (org-show-hierarchy-above nil))
8546 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
8547
8548 (defun org-make-tags-matcher (match)
8549 "Create the TAGS matcher form for the tags-selecting string MATCH."
8550 (unless match
8551 ;; Get a new match request, with completion
8552 (setq org-last-tags-completion-table
8553 (or (org-get-buffer-tags)
8554 org-last-tags-completion-table))
8555 (setq match (completing-read
8556 "Tags: " 'org-tags-completion-function nil nil nil
8557 'org-tags-history)))
8558 ;; parse the string and create a lisp form
8559 (let ((match0 match) minus tag mm matcher orterms term orlist)
8560 (setq orterms (org-split-string match "|"))
8561 (while (setq term (pop orterms))
8562 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
8563 (setq minus (and (match-end 1)
8564 (equal (match-string 1 term) "-"))
8565 tag (match-string 2 term)
8566 term (substring term (match-end 0))
8567 mm (list 'member (downcase tag) 'tags-list)
8568 mm (if minus (list 'not mm) mm))
8569 (push mm matcher))
8570 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
8571 orlist)
8572 (setq matcher nil))
8573 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8574 ;; Return the string and lisp forms of the matcher
8575 (cons match0 matcher)))
8576
8577 ;;;###autoload
8578 (defun org-tags-view (&optional todo-only match keep-modes)
8579 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
8580 The prefix arg TODO-ONLY limits the search to TODO entries."
8581 (interactive "P")
8582 (org-agenda-maybe-reset-markers 'force)
8583 (org-compile-prefix-format org-agenda-prefix-format)
8584 (let* ((org-agenda-keep-modes keep-modes)
8585 (org-tags-match-list-sublevels
8586 (if todo-only t org-tags-match-list-sublevels))
8587 (win (selected-window))
8588 (completion-ignore-case t)
8589 rtn rtnall files file pos matcher
8590 buffer)
8591 (setq matcher (org-make-tags-matcher match)
8592 match (car matcher) matcher (cdr matcher))
8593 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
8594 (progn
8595 (delete-other-windows)
8596 (switch-to-buffer-other-window
8597 (get-buffer-create org-agenda-buffer-name))))
8598 (setq buffer-read-only nil)
8599 (erase-buffer)
8600 (org-agenda-mode) (setq buffer-read-only nil)
8601 (set (make-local-variable 'org-agenda-type) 'tags)
8602 (set (make-local-variable 'org-agenda-redo-command)
8603 (list 'org-tags-view (list 'quote todo-only)
8604 (list 'if 'current-prefix-arg nil match) t))
8605 (setq files (org-agenda-files)
8606 rtnall nil)
8607 (org-prepare-agenda-buffers files)
8608 (while (setq file (pop files))
8609 (catch 'nextfile
8610 (org-check-agenda-file file)
8611 (setq buffer (if (file-exists-p file)
8612 (org-get-agenda-file-buffer file)
8613 (error "No such file %s" file)))
8614 (if (not buffer)
8615 ;; If file does not exist, merror message to agenda
8616 (setq rtn (list
8617 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8618 rtnall (append rtnall rtn))
8619 (with-current-buffer buffer
8620 (unless (eq major-mode 'org-mode)
8621 (error "Agenda file %s is not in `org-mode'" file))
8622 (setq org-category-table (org-get-category-table))
8623 (save-excursion
8624 (save-restriction
8625 (if org-respect-restriction
8626 (if (org-region-active-p)
8627 ;; Respect a region to restrict search
8628 (narrow-to-region (region-beginning) (region-end)))
8629 ;; If we work for the calendar or many files,
8630 ;; get rid of any restriction
8631 (widen))
8632 (setq rtn (org-scan-tags 'agenda matcher todo-only))
8633 (setq rtnall (append rtnall rtn))))))))
8634 (insert "Headlines with TAGS match: ")
8635 (add-text-properties (point-min) (1- (point))
8636 (list 'face 'org-level-3))
8637 (setq pos (point))
8638 (insert match "\n")
8639 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
8640 (setq pos (point))
8641 (insert "Press `C-u r' to search again with new search string\n")
8642 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
8643 (when rtnall
8644 (insert (mapconcat 'identity rtnall "\n")))
8645 (goto-char (point-min))
8646 (setq buffer-read-only t)
8647 (org-fit-agenda-window)
8648 (if (not org-select-agenda-window) (select-window win))))
8649
8650 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8651 (defun org-set-tags (&optional arg just-align)
8652 "Set the tags for the current headline.
8653 With prefix ARG, realign all tags in headings in the current buffer."
8654 (interactive "P")
8655 (let* ((re (concat "^" outline-regexp))
8656 (col (current-column))
8657 (current (org-get-tags))
8658 table current-tags inherited-tags ; computed below when needed
8659 tags hd empty invis)
8660 (if arg
8661 (save-excursion
8662 (goto-char (point-min))
8663 (while (re-search-forward re nil t)
8664 (org-set-tags nil t))
8665 (message "All tags realigned to column %d" org-tags-column))
8666 (if just-align
8667 (setq tags current)
8668 (setq table (or org-tag-alist (org-get-buffer-tags))
8669 org-last-tags-completion-table table
8670 current-tags (org-split-string current ":")
8671 inherited-tags (nreverse
8672 (nthcdr (length current-tags)
8673 (nreverse (org-get-tags-at))))
8674 tags
8675 (if (or (eq t org-use-fast-tag-selection)
8676 (and org-use-fast-tag-selection
8677 (delq nil (mapcar 'cdr table))))
8678 (org-fast-tag-selection current-tags inherited-tags table)
8679 (let ((org-add-colon-after-tag-completion t))
8680 (completing-read "Tags: " 'org-tags-completion-function
8681 nil nil current 'org-tags-history))))
8682 (while (string-match "[-+&]+" tags)
8683 (setq tags (replace-match ":" t t tags))))
8684
8685 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
8686 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8687 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8688 (if (equal current "")
8689 (progn
8690 (end-of-line 1)
8691 (or empty (insert-before-markers " ")))
8692 (beginning-of-line 1)
8693 (setq invis (org-invisible-p))
8694 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
8695 (setq hd (match-string 1))
8696 (delete-region (match-beginning 0) (match-end 0))
8697 (insert-before-markers (org-trim hd) (if empty "" " ")))
8698 (if (equal tags "")
8699 (save-excursion
8700 (beginning-of-line 1)
8701 (and (re-search-forward "[ \t]+$" (point-at-eol) t)
8702 (replace-match "")))
8703 (move-to-column (max (current-column)
8704 (if (> org-tags-column 0)
8705 org-tags-column
8706 (- (- org-tags-column) (length tags))))
8707 t)
8708 (insert-before-markers tags)
8709 (if (and (not invis) (org-invisible-p))
8710 (outline-flag-region (point-at-bol) (point) nil)))
8711 (move-to-column col))))
8712
8713 (defun org-tags-completion-function (string predicate &optional flag)
8714 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8715 (confirm (lambda (x) (stringp (car x)))))
8716 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8717 (setq s1 (match-string 1 string)
8718 s2 (match-string 2 string))
8719 (setq s1 "" s2 string))
8720 (cond
8721 ((eq flag nil)
8722 ;; try completion
8723 (setq rtn (try-completion s2 ctable confirm))
8724 (if (stringp rtn)
8725 (concat s1 s2 (substring rtn (length s2))
8726 (if (and org-add-colon-after-tag-completion
8727 (assoc rtn ctable))
8728 ":" "")))
8729 )
8730 ((eq flag t)
8731 ;; all-completions
8732 (all-completions s2 ctable confirm)
8733 )
8734 ((eq flag 'lambda)
8735 ;; exact match?
8736 (assoc s2 ctable)))
8737 ))
8738
8739 (defun org-fast-tag-insert (kwd tags face &optional end)
8740 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
8741 (insert (format "%-12s" (concat kwd ":"))
8742 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
8743 (or end "")))
8744
8745 (defun org-fast-tag-selection (current inherited table)
8746 "Fast tag selection with single keys.
8747 CURRENT is the current list of tags in the headline, INHERITED is the
8748 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
8749 possibly with grouping information.
8750 If the keys are nil, a-z are automatically assigned.
8751 Returns the new tags string, or nil to not change the current settings."
8752 (let* ((maxlen (apply 'max (mapcar
8753 (lambda (x)
8754 (if (stringp (car x)) (string-width (car x)) 0))
8755 table)))
8756 (fwidth (+ maxlen 3 1 3))
8757 (ncol (/ (- (window-width) 4) fwidth))
8758 (i-face 'org-done)
8759 (c-face 'org-tag)
8760 tg cnt e c char c1 c2 ntable tbl rtn
8761 groups ingroup)
8762 (save-window-excursion
8763 (delete-other-windows)
8764 (split-window-vertically)
8765 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
8766 (erase-buffer)
8767 (org-fast-tag-insert "Inherited" inherited i-face "\n")
8768 (org-fast-tag-insert "Current" current c-face "\n\n")
8769 (setq tbl table char ?a cnt 0)
8770 (while (setq e (pop tbl))
8771 (cond
8772 ((equal e '(:startgroup))
8773 (push '() groups) (setq ingroup t)
8774 (when (not (= cnt 0))
8775 (setq cnt 0)
8776 (insert "\n"))
8777 (insert "{ "))
8778 ((equal e '(:endgroup))
8779 (setq ingroup nil cnt 0)
8780 (insert "}\n"))
8781 (t
8782 (setq tg (car e) c2 nil)
8783 (if (cdr e)
8784 (setq c (cdr e))
8785 ;; automatically assign a character.
8786 (setq c1 (string-to-char
8787 (downcase (substring
8788 tg (if (= (string-to-char tg) ?@) 1 0)))))
8789 (if (or (rassoc c1 ntable) (rassoc c1 table))
8790 (while (or (rassoc char ntable) (rassoc char table))
8791 (setq char (1+ char)))
8792 (setq c2 c1))
8793 (setq c (or c2 char)))
8794 (if ingroup (push tg (car groups)))
8795 (setq tg (org-add-props tg nil 'face
8796 (cond
8797 ((member tg current) c-face)
8798 ((member tg inherited) i-face)
8799 (t nil))))
8800 (if (and (= cnt 0) (not ingroup)) (insert " "))
8801 (insert "[" c "] " tg (make-string
8802 (- fwidth 4 (length tg)) ?\ ))
8803 (push (cons tg c) ntable)
8804 (when (= (setq cnt (1+ cnt)) ncol)
8805 (insert "\n")
8806 (if ingroup (insert " "))
8807 (setq cnt 0)))))
8808 (setq ntable (nreverse ntable))
8809 (insert "\n")
8810 (goto-char (point-min))
8811 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
8812 (setq rtn
8813 (catch 'exit
8814 (while t
8815 (message "[key]:Toggle SPC: clear current RET accept%s"
8816 (if groups " [!] ignore goups" ""))
8817 (setq c (read-char-exclusive))
8818 (cond
8819 ((= c ?\r) (throw 'exit t))
8820 ((= c ?!)
8821 (setq groups nil)
8822 (goto-char (point-min))
8823 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
8824 ((or (= c ?\C-g)
8825 (and (= c ?q) (not (rassoc c ntable))))
8826 (setq quit-flag t))
8827 ((= c ?\ ) (setq current nil))
8828 ((setq e (rassoc c ntable) tg (car e))
8829 (if (member tg current)
8830 (setq current (delete tg current))
8831 (loop for g in groups do
8832 (if (member tg g)
8833 (mapcar (lambda (x)
8834 (setq current (delete x current)))
8835 g)))
8836 (setq current (cons tg current)))))
8837 ;; Create a sorted list
8838 (setq current
8839 (sort current
8840 (lambda (a b)
8841 (assoc b (cdr (memq (assoc a ntable) ntable))))))
8842 (goto-char (point-min))
8843 (beginning-of-line 2)
8844 (delete-region (point) (point-at-eol))
8845 (org-fast-tag-insert "Current" current c-face)
8846 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
8847 (setq tg (match-string 1))
8848 (add-text-properties (match-beginning 1) (match-end 1)
8849 (list 'face
8850 (cond
8851 ((member tg current) c-face)
8852 ((member tg inherited) i-face)
8853 (t nil)))))
8854 (goto-char (point-min)))))
8855 (if rtn
8856 (mapconcat 'identity current ":")
8857 nil))))
8858
8859 (defun org-get-tags ()
8860 "Get the TAGS string in the current headline."
8861 (unless (org-on-heading-p)
8862 (error "Not on a heading"))
8863 (save-excursion
8864 (beginning-of-line 1)
8865 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
8866 (org-match-string-no-properties 1)
8867 "")))
8868
8869 (defun org-get-buffer-tags ()
8870 "Get a table of all tags used in the buffer, for completion."
8871 (let (tags)
8872 (save-excursion
8873 (goto-char (point-min))
8874 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
8875 (mapc (lambda (x) (add-to-list 'tags x))
8876 (org-split-string (org-match-string-no-properties 1) ":"))))
8877 (mapcar 'list tags)))
8878
8879 ;;; Link Stuff
8880
8881 (defvar org-create-file-search-functions nil
8882 "List of functions to construct the right search string for a file link.
8883 These functions are called in turn with point at the location to
8884 which the link should point.
8885
8886 A function in the hook should first test if it would like to
8887 handle this file type, for example by checking the major-mode or
8888 the file extension. If it decides not to handle this file, it
8889 should just return nil to give other functions a chance. If it
8890 does handle the file, it must return the search string to be used
8891 when following the link. The search string will be part of the
8892 file link, given after a double colon, and `org-open-at-point'
8893 will automatically search for it. If special measures must be
8894 taken to make the search successful, another function should be
8895 added to the companion hook `org-execute-file-search-functions',
8896 which see.
8897
8898 A function in this hook may also use `setq' to set the variable
8899 `description' to provide a suggestion for the descriptive text to
8900 be used for this link when it gets inserted into an Org-mode
8901 buffer with \\[org-insert-link].")
8902
8903 (defvar org-execute-file-search-functions nil
8904 "List of functions to execute a file search triggered by a link.
8905
8906 Functions added to this hook must accept a single argument, the
8907 search string that was part of the file link, the part after the
8908 double colon. The function must first check if it would like to
8909 handle this search, for example by checking the major-mode or the
8910 file extension. If it decides not to handle this search, it
8911 should just return nil to give other functions a chance. If it
8912 does handle the search, it must return a non-nil value to keep
8913 other functions from trying.
8914
8915 Each function can access the current prefix argument through the
8916 variable `current-prefix-argument'. Note that a single prefix is
8917 used to force opening a link in Emacs, so it may be good to only
8918 use a numeric or double prefix to guide the search function.
8919
8920 In case this is needed, a function in this hook can also restore
8921 the window configuration before `org-open-at-point' was called using:
8922
8923 (set-window-configuration org-window-config-before-follow-link)")
8924
8925 (defun org-find-file-at-mouse (ev)
8926 "Open file link or URL at mouse."
8927 (interactive "e")
8928 (mouse-set-point ev)
8929 (org-open-at-point 'in-emacs))
8930
8931 (defun org-open-at-mouse (ev)
8932 "Open file link or URL at mouse."
8933 (interactive "e")
8934 (mouse-set-point ev)
8935 (org-open-at-point))
8936
8937 (defvar org-window-config-before-follow-link nil
8938 "The window configuration before following a link.
8939 This is saved in case the need arises to restore it.")
8940
8941 (defun org-open-at-point (&optional in-emacs)
8942 "Open link at or after point.
8943 If there is no link at point, this function will search forward up to
8944 the end of the current subtree.
8945 Normally, files will be opened by an appropriate application. If the
8946 optional argument IN-EMACS is non-nil, Emacs will visit the file."
8947 (interactive "P")
8948 (setq org-window-config-before-follow-link (current-window-configuration))
8949 (org-remove-occur-highlights nil nil t)
8950 (if (org-at-timestamp-p)
8951 (org-agenda-list nil (time-to-days (org-time-string-to-time
8952 (substring (match-string 1) 0 10)))
8953 1)
8954 (let (type path link line search (pos (point)))
8955 (catch 'match
8956 (save-excursion
8957 (skip-chars-forward "^]\n\r")
8958 (when (and (re-search-backward "\\[\\[" nil t)
8959 (looking-at org-bracket-link-regexp)
8960 (<= (match-beginning 0) pos)
8961 (>= (match-end 0) pos))
8962 (setq link (org-link-unescape (org-match-string-no-properties 1)))
8963 (while (string-match " *\n *" link)
8964 (setq link (replace-match " " t t link)))
8965 (if (string-match org-link-re-with-space2 link)
8966 (setq type (match-string 1 link)
8967 path (match-string 2 link))
8968 (setq type "thisfile"
8969 path link))
8970 (throw 'match t)))
8971
8972 (when (get-text-property (point) 'org-linked-text)
8973 (setq type "thisfile"
8974 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8975 (1+ (point)) (point))
8976 path (buffer-substring
8977 (previous-single-property-change pos 'org-linked-text)
8978 (next-single-property-change pos 'org-linked-text)))
8979 (throw 'match t))
8980
8981 (save-excursion
8982 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
8983 (if (equal (char-before) ?<) (backward-char 1))
8984 (when (or (looking-at org-angle-link-re)
8985 (looking-at org-plain-link-re)
8986 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
8987 (re-search-forward org-plain-link-re (point-at-eol) t))
8988 (<= (match-beginning 0) pos)
8989 (>= (match-end 0) pos)))
8990 (setq type (match-string 1)
8991 path (match-string 2))
8992 (throw 'match t)))
8993 (save-excursion
8994 (skip-chars-backward "^ \t\n\r")
8995 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
8996 (setq type "tags"
8997 path (match-string 1))
8998 (while (string-match ":" path)
8999 (setq path (replace-match "+" t t path)))
9000 (throw 'match t)))
9001 (save-excursion
9002 (skip-chars-backward "a-zA-Z_")
9003 (when (and (memq 'camel org-activate-links)
9004 (looking-at org-camel-regexp))
9005 (setq type "camel" path (match-string 0))
9006 (if (equal (char-before) ?*)
9007 (setq path (concat "*" path))))
9008 (throw 'match t)))
9009 (unless path
9010 (error "No link found"))
9011 ;; Remove any trailing spaces in path
9012 (if (string-match " +\\'" path)
9013 (setq path (replace-match "" t t path)))
9014
9015 (cond
9016
9017 ((member type '("http" "https" "ftp" "mailto" "news"))
9018 (browse-url (concat type ":" path)))
9019
9020 ((string= type "tags")
9021 (org-tags-view in-emacs path))
9022 ((or (string= type "camel")
9023 (string= type "thisfile"))
9024 (org-mark-ring-push)
9025 (org-link-search
9026 path
9027 (cond ((equal in-emacs '(4)) 'occur)
9028 ((equal in-emacs '(16)) 'org-occur)
9029 (t nil))))
9030
9031 ((string= type "file")
9032 (if (string-match "::\\([0-9]+\\)\\'" path)
9033 (setq line (string-to-number (match-string 1 path))
9034 path (substring path 0 (match-beginning 0)))
9035 (if (string-match "::\\(.+\\)\\'" path)
9036 (setq search (match-string 1 path)
9037 path (substring path 0 (match-beginning 0)))))
9038 (org-open-file path in-emacs line search))
9039
9040 ((string= type "news")
9041 (org-follow-gnus-link path))
9042
9043 ((string= type "bbdb")
9044 (org-follow-bbdb-link path))
9045
9046 ((string= type "info")
9047 (org-follow-info-link path))
9048
9049 ((string= type "gnus")
9050 (let (group article)
9051 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9052 (error "Error in Gnus link"))
9053 (setq group (match-string 1 path)
9054 article (match-string 3 path))
9055 (org-follow-gnus-link group article)))
9056
9057 ((string= type "vm")
9058 (let (folder article)
9059 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9060 (error "Error in VM link"))
9061 (setq folder (match-string 1 path)
9062 article (match-string 3 path))
9063 ;; in-emacs is the prefix arg, will be interpreted as read-only
9064 (org-follow-vm-link folder article in-emacs)))
9065
9066 ((string= type "wl")
9067 (let (folder article)
9068 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9069 (error "Error in Wanderlust link"))
9070 (setq folder (match-string 1 path)
9071 article (match-string 3 path))
9072 (org-follow-wl-link folder article)))
9073
9074 ((string= type "mhe")
9075 (let (folder article)
9076 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9077 (error "Error in MHE link"))
9078 (setq folder (match-string 1 path)
9079 article (match-string 3 path))
9080 (org-follow-mhe-link folder article)))
9081
9082 ((string= type "rmail")
9083 (let (folder article)
9084 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9085 (error "Error in RMAIL link"))
9086 (setq folder (match-string 1 path)
9087 article (match-string 3 path))
9088 (org-follow-rmail-link folder article)))
9089
9090 ((string= type "shell")
9091 (let ((cmd path))
9092 (while (string-match "@{" cmd)
9093 (setq cmd (replace-match "<" t t cmd)))
9094 (while (string-match "@}" cmd)
9095 (setq cmd (replace-match ">" t t cmd)))
9096 (if (or (not org-confirm-shell-link-function)
9097 (funcall org-confirm-shell-link-function
9098 (format "Execute \"%s\" in shell? "
9099 (org-add-props cmd nil
9100 'face 'org-warning))))
9101 (progn
9102 (message "Executing %s" cmd)
9103 (shell-command cmd))
9104 (error "Abort"))))
9105
9106 ((string= type "elisp")
9107 (let ((cmd path))
9108 (if (or (not org-confirm-elisp-link-function)
9109 (funcall org-confirm-elisp-link-function
9110 (format "Execute \"%s\" as elisp? "
9111 (org-add-props cmd nil
9112 'face 'org-warning))))
9113 (message "%s => %s" cmd (eval (read cmd)))
9114 (error "Abort"))))
9115
9116 (t
9117 (browse-url-at-point))))))
9118
9119 (defun org-link-search (s &optional type)
9120 "Search for a link search option.
9121 When S is a CamelCaseWord, search for a target, or for a sentence containing
9122 the words. If S is surrounded by forward slashes, it is interpreted as a
9123 regular expression. In org-mode files, this will create an `org-occur'
9124 sparse tree. In ordinary files, `occur' will be used to list matches.
9125 If the current buffer is in `dired-mode', grep will be used to search
9126 in all files."
9127 (let ((case-fold-search t)
9128 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9129 (pos (point))
9130 (pre "") (post "")
9131 words re0 re1 re2 re3 re4 re5 re2a reall camel)
9132 (cond
9133 ;; First check if there are any special
9134 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9135 ;; Now try the builtin stuff
9136 ((save-excursion
9137 (goto-char (point-min))
9138 (and
9139 (re-search-forward
9140 (concat "<<" (regexp-quote s0) ">>") nil t)
9141 (setq pos (match-beginning 0))))
9142 ;; There is an exact target for this
9143 (goto-char pos))
9144 ((string-match "^/\\(.*\\)/$" s)
9145 ;; A regular expression
9146 (cond
9147 ((eq major-mode 'org-mode)
9148 (org-occur (match-string 1 s)))
9149 ;;((eq major-mode 'dired-mode)
9150 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9151 (t (org-do-occur (match-string 1 s)))))
9152 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
9153 t)
9154 ;; A camel or a normal search string
9155 (when (equal (string-to-char s) ?*)
9156 ;; Anchor on headlines, post may include tags.
9157 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9158 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9159 s (substring s 1)))
9160 (remove-text-properties
9161 0 (length s)
9162 '(face nil mouse-face nil keymap nil fontified nil) s)
9163 ;; Make a series of regular expressions to find a match
9164 (setq words
9165 (if camel
9166 (org-camel-to-words s)
9167 (org-split-string s "[ \n\r\t]+"))
9168 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9169 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9170 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9171 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9172 re1 (concat pre re2 post)
9173 re3 (concat pre re4 post)
9174 re5 (concat pre ".*" re4)
9175 re2 (concat pre re2)
9176 re2a (concat pre re2a)
9177 re4 (concat pre re4)
9178 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9179 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9180 re5 "\\)"
9181 ))
9182 (cond
9183 ((eq type 'org-occur) (org-occur reall))
9184 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9185 (t (goto-char (point-min))
9186 (if (or (org-search-not-link re0 nil t)
9187 (org-search-not-link re1 nil t)
9188 (org-search-not-link re2 nil t)
9189 (org-search-not-link re2a nil t)
9190 (org-search-not-link re3 nil t)
9191 (org-search-not-link re4 nil t)
9192 (org-search-not-link re5 nil t)
9193 )
9194 (goto-char (match-beginning 1))
9195 (goto-char pos)
9196 (error "No match")))))
9197 (t
9198 ;; Normal string-search
9199 (goto-char (point-min))
9200 (if (search-forward s nil t)
9201 (goto-char (match-beginning 0))
9202 (error "No match"))))
9203 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
9204
9205 (defun org-search-not-link (&rest args)
9206 "Execute `re-search-forward', but only accept matches that are not a link."
9207 (catch 'exit
9208 (let (p1)
9209 (while (apply 're-search-forward args)
9210 (setq p1 (point))
9211 (if (not (save-match-data
9212 (and (re-search-backward "\\[\\[" nil t)
9213 (looking-at org-bracket-link-regexp)
9214 (<= (match-beginning 0) p1)
9215 (>= (match-end 0) p1))))
9216 (progn (goto-char (match-end 0))
9217 (throw 'exit (point)))
9218 (goto-char (match-end 0)))))))
9219
9220 (defun org-do-occur (regexp &optional cleanup)
9221 "Call the Emacs command `occur'.
9222 If CLEANUP is non-nil, remove the printout of the regular expression
9223 in the *Occur* buffer. This is useful if the regex is long and not useful
9224 to read."
9225 (occur regexp)
9226 (when cleanup
9227 (let ((cwin (selected-window)) win beg end)
9228 (when (setq win (get-buffer-window "*Occur*"))
9229 (select-window win))
9230 (goto-char (point-min))
9231 (when (re-search-forward "match[a-z]+" nil t)
9232 (setq beg (match-end 0))
9233 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9234 (setq end (1- (match-beginning 0)))))
9235 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9236 (goto-char (point-min))
9237 (select-window cwin))))
9238
9239 (defvar org-mark-ring nil
9240 "Mark ring for positions before jumps in Org-mode.")
9241 (defvar org-mark-ring-last-goto nil
9242 "Last position in the mark ring used to go back.")
9243 ;; Fill and close the ring
9244 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9245 (loop for i from 1 to org-mark-ring-length do
9246 (push (make-marker) org-mark-ring))
9247 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9248 org-mark-ring)
9249
9250 (defun org-mark-ring-push (&optional pos buffer)
9251 "Put the current position or POS into the mark ring and rotate it."
9252 (interactive)
9253 (setq pos (or pos (point)))
9254 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9255 (move-marker (car org-mark-ring)
9256 (or pos (point))
9257 (or buffer (current-buffer)))
9258 (message
9259 (substitute-command-keys
9260 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9261
9262 (defun org-mark-ring-goto (&optional n)
9263 "Jump to the previous position in the mark ring.
9264 With prefix arg N, jump back that many stored positions. When
9265 called several times in succession, walk through the entire ring.
9266 Org-mode commands jumping to a different position in the current file,
9267 or to another Org-mode file, automatically push the old position
9268 onto the ring."
9269 (interactive "p")
9270 (let (p m)
9271 (if (eq last-command this-command)
9272 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9273 (setq p org-mark-ring))
9274 (setq org-mark-ring-last-goto p)
9275 (setq m (car p))
9276 (switch-to-buffer (marker-buffer m))
9277 (goto-char m)
9278 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
9279
9280 (defun org-camel-to-words (s)
9281 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
9282 (let ((case-fold-search nil)
9283 words)
9284 (while (string-match "[a-z][A-Z]" s)
9285 (push (substring s 0 (1+ (match-beginning 0))) words)
9286 (setq s (substring s (1+ (match-beginning 0)))))
9287 (nreverse (cons s words))))
9288
9289 (defun org-remove-angle-brackets (s)
9290 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9291 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9292 s)
9293 (defun org-add-angle-brackets (s)
9294 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9295 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9296 s)
9297
9298 (defun org-follow-bbdb-link (name)
9299 "Follow a BBDB link to NAME."
9300 (require 'bbdb)
9301 (let ((inhibit-redisplay t)
9302 (bbdb-electric-p nil))
9303 (catch 'exit
9304 ;; Exact match on name
9305 (bbdb-name (concat "\\`" name "\\'") nil)
9306 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9307 ;; Exact match on name
9308 (bbdb-company (concat "\\`" name "\\'") nil)
9309 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9310 ;; Partial match on name
9311 (bbdb-name name nil)
9312 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9313 ;; Partial match on company
9314 (bbdb-company name nil)
9315 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9316 ;; General match including network address and notes
9317 (bbdb name nil)
9318 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
9319 (delete-window (get-buffer-window "*BBDB*"))
9320 (error "No matching BBDB record")))))
9321
9322
9323 (defun org-follow-info-link (name)
9324 "Follow an info file & node link to NAME."
9325 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
9326 (string-match "\\(.*\\)" name))
9327 (progn
9328 (require 'info)
9329 (if (match-string 2 name) ; If there isn't a node, choose "Top"
9330 (Info-find-node (match-string 1 name) (match-string 2 name))
9331 (Info-find-node (match-string 1 name) "Top")))
9332 (message (concat "Could not open: " name))))
9333
9334 (defun org-follow-gnus-link (&optional group article)
9335 "Follow a Gnus link to GROUP and ARTICLE."
9336 (require 'gnus)
9337 (funcall (cdr (assq 'gnus org-link-frame-setup)))
9338 (if group (gnus-fetch-group group))
9339 (if article
9340 (or (gnus-summary-goto-article article nil 'force)
9341 (if (fboundp 'gnus-summary-insert-cached-articles)
9342 (progn
9343 (gnus-summary-insert-cached-articles)
9344 (gnus-summary-goto-article article nil 'force))
9345 (message "Message could not be found.")))))
9346
9347 (defun org-follow-vm-link (&optional folder article readonly)
9348 "Follow a VM link to FOLDER and ARTICLE."
9349 (require 'vm)
9350 (setq article (org-add-angle-brackets article))
9351 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
9352 ;; ange-ftp or efs or tramp access
9353 (let ((user (or (match-string 1 folder) (user-login-name)))
9354 (host (match-string 2 folder))
9355 (file (match-string 3 folder)))
9356 (cond
9357 ((featurep 'tramp)
9358 ;; use tramp to access the file
9359 (if (featurep 'xemacs)
9360 (setq folder (format "[%s@%s]%s" user host file))
9361 (setq folder (format "/%s@%s:%s" user host file))))
9362 (t
9363 ;; use ange-ftp or efs
9364 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
9365 (setq folder (format "/%s@%s:%s" user host file))))))
9366 (when folder
9367 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
9368 (sit-for 0.1)
9369 (when article
9370 (vm-select-folder-buffer)
9371 (widen)
9372 (let ((case-fold-search t))
9373 (goto-char (point-min))
9374 (if (not (re-search-forward
9375 (concat "^" "message-id: *" (regexp-quote article))))
9376 (error "Could not find the specified message in this folder"))
9377 (vm-isearch-update)
9378 (vm-isearch-narrow)
9379 (vm-beginning-of-message)
9380 (vm-summarize)))))
9381
9382 (defun org-follow-wl-link (folder article)
9383 "Follow a Wanderlust link to FOLDER and ARTICLE."
9384 (setq article (org-add-angle-brackets article))
9385 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
9386 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
9387 (wl-summary-redisplay))
9388
9389 (defun org-follow-rmail-link (folder article)
9390 "Follow an RMAIL link to FOLDER and ARTICLE."
9391 (setq article (org-add-angle-brackets article))
9392 (let (message-number)
9393 (save-excursion
9394 (save-window-excursion
9395 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9396 (setq message-number
9397 (save-restriction
9398 (widen)
9399 (goto-char (point-max))
9400 (if (re-search-backward
9401 (concat "^Message-ID:\\s-+" (regexp-quote
9402 (or article "")))
9403 nil t)
9404 (rmail-what-message))))))
9405 (if message-number
9406 (progn
9407 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9408 (rmail-show-message message-number)
9409 message-number)
9410 (error "Message not found"))))
9411
9412 ;; mh-e integration based on planner-mode
9413 (defun org-mhe-get-message-real-folder ()
9414 "Return the name of the current message real folder, so if you use
9415 sequences, it will now work."
9416 (save-excursion
9417 (let* ((folder
9418 (if (equal major-mode 'mh-folder-mode)
9419 mh-current-folder
9420 ;; Refer to the show buffer
9421 mh-show-folder-buffer))
9422 (end-index
9423 (if (boundp 'mh-index-folder)
9424 (min (length mh-index-folder) (length folder))))
9425 )
9426 ;; a simple test on mh-index-data does not work, because
9427 ;; mh-index-data is always nil in a show buffer.
9428 (if (and (boundp 'mh-index-folder)
9429 (string= mh-index-folder (substring folder 0 end-index)))
9430 (if (equal major-mode 'mh-show-mode)
9431 (save-window-excursion
9432 (when (buffer-live-p (get-buffer folder))
9433 (progn
9434 (pop-to-buffer folder)
9435 (org-mhe-get-message-folder-from-index)
9436 )
9437 ))
9438 (org-mhe-get-message-folder-from-index)
9439 )
9440 folder
9441 )
9442 )))
9443
9444 (defun org-mhe-get-message-folder-from-index ()
9445 "Returns the name of the message folder in a index folder buffer."
9446 (save-excursion
9447 (mh-index-previous-folder)
9448 (re-search-forward "^\\(+.*\\)$" nil t)
9449 (message (match-string 1))))
9450
9451 (defun org-mhe-get-message-folder ()
9452 "Return the name of the current message folder. Be careful if you
9453 use sequences."
9454 (save-excursion
9455 (if (equal major-mode 'mh-folder-mode)
9456 mh-current-folder
9457 ;; Refer to the show buffer
9458 mh-show-folder-buffer)))
9459
9460 (defun org-mhe-get-message-num ()
9461 "Return the number of the current message. Be careful if you
9462 use sequences."
9463 (save-excursion
9464 (if (equal major-mode 'mh-folder-mode)
9465 (mh-get-msg-num nil)
9466 ;; Refer to the show buffer
9467 (mh-show-buffer-message-number))))
9468
9469 (defun org-mhe-get-header (header)
9470 "Return a header of the message in folder mode. This will create a
9471 show buffer for the corresponding message. If you have a more clever
9472 idea..."
9473 (let* ((folder (org-mhe-get-message-folder))
9474 (num (org-mhe-get-message-num))
9475 (buffer (get-buffer-create (concat "show-" folder)))
9476 (header-field))
9477 (with-current-buffer buffer
9478 (mh-display-msg num folder)
9479 (if (equal major-mode 'mh-folder-mode)
9480 (mh-header-display)
9481 (mh-show-header-display))
9482 (set-buffer buffer)
9483 (setq header-field (mh-get-header-field header))
9484 (if (equal major-mode 'mh-folder-mode)
9485 (mh-show)
9486 (mh-show-show))
9487 header-field)))
9488
9489 (defun org-follow-mhe-link (folder article)
9490 "Follow an MHE link to FOLDER and ARTICLE.
9491 If ARTICLE is nil FOLDER is shown. If the configuration variable
9492 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9493 ARTICLE is searched in all folders. Indexed searches (swish++,
9494 namazu, and others supported by MH-E) will always search in all
9495 folders."
9496 (require 'mh-e)
9497 (require 'mh-search)
9498 (require 'mh-utils)
9499 (mh-find-path)
9500 (if (not article)
9501 (mh-visit-folder (mh-normalize-folder-name folder))
9502 (setq article (org-add-angle-brackets article))
9503 (mh-search-choose)
9504 (if (equal mh-searcher 'pick)
9505 (progn
9506 (mh-search folder (list "--message-id" article))
9507 (when (and org-mhe-search-all-folders
9508 (not (org-mhe-get-message-real-folder)))
9509 (kill-this-buffer)
9510 (mh-search "+" (list "--message-id" article))))
9511 (mh-search "+" article))
9512 (if (org-mhe-get-message-real-folder)
9513 (mh-show-msg 1)
9514 (kill-this-buffer)
9515 (error "Message not found"))))
9516
9517 ;; BibTeX links
9518
9519 ;; Use the custom search meachnism to construct and use search strings for
9520 ;; file links to BibTeX database entries.
9521
9522 (defun org-create-file-search-in-bibtex ()
9523 "Create the search string and description for a BibTeX database entry."
9524 (when (eq major-mode 'bibtex-mode)
9525 ;; yes, we want to construct this search string.
9526 ;; Make a good description for this entry, using names, year and the title
9527 ;; Put it into the `description' variable which is dynamically scoped.
9528 (let ((bibtex-autokey-names 1)
9529 (bibtex-autokey-names-stretch 1)
9530 (bibtex-autokey-name-case-convert-function 'identity)
9531 (bibtex-autokey-name-separator " & ")
9532 (bibtex-autokey-additional-names " et al.")
9533 (bibtex-autokey-year-length 4)
9534 (bibtex-autokey-name-year-separator " ")
9535 (bibtex-autokey-titlewords 3)
9536 (bibtex-autokey-titleword-separator " ")
9537 (bibtex-autokey-titleword-case-convert-function 'identity)
9538 (bibtex-autokey-titleword-length 'infty)
9539 (bibtex-autokey-year-title-separator ": "))
9540 (setq description (bibtex-generate-autokey)))
9541 ;; Now parse the entry, get the key and return it.
9542 (save-excursion
9543 (bibtex-beginning-of-entry)
9544 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9545
9546 (defun org-execute-file-search-in-bibtex (s)
9547 "Find the link search string S as a key for a database entry."
9548 (when (eq major-mode 'bibtex-mode)
9549 ;; Yes, we want to do the search in this file.
9550 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9551 (goto-char (point-min))
9552 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9553 (regexp-quote s) "[ \t\n]*,") nil t)
9554 (goto-char (match-beginning 0)))
9555 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9556 ;; Use double prefix to indicate that any web link should be browsed
9557 (let ((b (current-buffer)) (p (point)))
9558 ;; Restore the window configuration because we just use the web link
9559 (set-window-configuration org-window-config-before-follow-link)
9560 (save-excursion (set-buffer b) (goto-char p)
9561 (bibtex-url)))
9562 (recenter 0)) ; Move entry start to beginning of window
9563 ;; return t to indicate that the search is done.
9564 t))
9565
9566 ;; Finally add the functions to the right hooks.
9567 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
9568 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
9569
9570 ;; end of Bibtex link setup
9571
9572 (defun org-upgrade-old-links (&optional query-description)
9573 "Transfer old <...> style links to new [[...]] style links.
9574 With arg query-description, ask at each match for a description text to use
9575 for this link."
9576 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
9577 (save-excursion
9578 (goto-char (point-min))
9579 (let ((re (concat "\\([^[]\\)<\\("
9580 "\\(" (mapconcat 'identity org-link-types "\\|")
9581 "\\):"
9582 "[^" org-non-link-chars "]+\\)>"))
9583 l1 l2 (cnt 0))
9584 (while (re-search-forward re nil t)
9585 (setq cnt (1+ cnt)
9586 l1 (org-match-string-no-properties 2)
9587 l2 (save-match-data (org-link-escape l1)))
9588 (when query-description (setq l1 (read-string "Desc: " l1)))
9589 (if (equal l1 l2)
9590 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
9591 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
9592 (message "%d matches have beed treated" cnt))))
9593
9594 (defun org-open-file (path &optional in-emacs line search)
9595 "Open the file at PATH.
9596 First, this expands any special file name abbreviations. Then the
9597 configuration variable `org-file-apps' is checked if it contains an
9598 entry for this file type, and if yes, the corresponding command is launched.
9599 If no application is found, Emacs simply visits the file.
9600 With optional argument IN-EMACS, Emacs will visit the file.
9601 Optional LINE specifies a line to go to, optional SEARCH a string to
9602 search for. If LINE or SEARCH is given, the file will always be
9603 opened in Emacs.
9604 If the file does not exist, an error is thrown."
9605 (setq in-emacs (or in-emacs line search))
9606 (let* ((file (if (equal path "")
9607 buffer-file-name
9608 path))
9609 (apps (append org-file-apps (org-default-apps)))
9610 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9611 (dirp (if remp nil (file-directory-p file)))
9612 (dfile (downcase file))
9613 (old-buffer (current-buffer))
9614 (old-pos (point))
9615 (old-mode major-mode)
9616 ext cmd)
9617 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9618 (setq ext (match-string 1 dfile))
9619 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9620 (setq ext (match-string 1 dfile))))
9621 (if in-emacs
9622 (setq cmd 'emacs)
9623 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9624 (and dirp (cdr (assoc 'directory apps)))
9625 (cdr (assoc ext apps))
9626 (cdr (assoc t apps)))))
9627 (when (eq cmd 'mailcap)
9628 (require 'mailcap)
9629 (mailcap-parse-mailcaps)
9630 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9631 (command (mailcap-mime-info mime-type)))
9632 (if (stringp command)
9633 (setq cmd command)
9634 (setq cmd 'emacs))))
9635 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
9636 (not (file-exists-p file))
9637 (not org-open-non-existing-files))
9638 (error "No such file: %s" file))
9639 (cond
9640 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9641 ;; Normalize use of quote, this can vary.
9642 (if (string-match "['\"]%s['\"]" cmd)
9643 (setq cmd (replace-match "'%s'" t t cmd)))
9644 (setq cmd (format cmd file))
9645 (save-window-excursion
9646 (shell-command (concat cmd " &"))))
9647 ((or (stringp cmd)
9648 (eq cmd 'emacs))
9649 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
9650 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
9651 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9652 (if line (goto-line line)
9653 (if search (org-link-search search))))
9654 ((consp cmd)
9655 (eval cmd))
9656 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9657 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
9658 (or (not (equal old-buffer (current-buffer)))
9659 (not (equal old-pos (point))))
9660 (org-mark-ring-push old-pos old-buffer))))
9661
9662 (defun org-default-apps ()
9663 "Return the default applications for this operating system."
9664 (cond
9665 ((eq system-type 'darwin)
9666 org-file-apps-defaults-macosx)
9667 ((eq system-type 'windows-nt)
9668 org-file-apps-defaults-windowsnt)
9669 (t org-file-apps-defaults-gnu)))
9670
9671 (defun org-expand-file-name (path)
9672 "Replace special path abbreviations and expand the file name."
9673 (expand-file-name path))
9674
9675 (defun org-file-remote-p (file)
9676 "Test whether FILE specifies a location on a remote system.
9677 Return non-nil if the location is indeed remote.
9678
9679 For example, the filename \"/user@host:/foo\" specifies a location
9680 on the system \"/user@host:\"."
9681 (cond ((fboundp 'file-remote-p)
9682 (file-remote-p file))
9683 ((fboundp 'tramp-handle-file-remote-p)
9684 (tramp-handle-file-remote-p file))
9685 ((and (boundp 'ange-ftp-name-format)
9686 (string-match ange-ftp-name-format file))
9687 t)
9688 (t nil)))
9689
9690 (defvar org-insert-link-history nil
9691 "Minibuffer history for links inserted with `org-insert-link'.")
9692
9693 (defvar org-stored-links nil
9694 "Contains the links stored with `org-store-link'.")
9695
9696 ;;;###autoload
9697 (defun org-store-link (arg)
9698 "\\<org-mode-map>Store an org-link to the current location.
9699 This link can later be inserted into an org-buffer with
9700 \\[org-insert-link].
9701 For some link types, a prefix arg is interpreted:
9702 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9703 For file links, arg negates `org-context-in-file-links'."
9704 (interactive "P")
9705 (let (link cpltxt desc description search txt (pos (point)))
9706 (cond
9707
9708 ((eq major-mode 'bbdb-mode)
9709 (setq cpltxt (concat
9710 "bbdb:"
9711 (or (bbdb-record-name (bbdb-current-record))
9712 (bbdb-record-company (bbdb-current-record))))
9713 link (org-make-link cpltxt)))
9714
9715 ((eq major-mode 'Info-mode)
9716 (setq link (org-make-link "info:"
9717 (file-name-nondirectory Info-current-file)
9718 ":" Info-current-node))
9719 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9720 ":" Info-current-node)))
9721
9722 ((eq major-mode 'calendar-mode)
9723 (let ((cd (calendar-cursor-to-date)))
9724 (setq link
9725 (format-time-string
9726 (car org-time-stamp-formats)
9727 (apply 'encode-time
9728 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9729 nil nil nil))))))
9730
9731 ((or (eq major-mode 'vm-summary-mode)
9732 (eq major-mode 'vm-presentation-mode))
9733 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9734 (vm-follow-summary-cursor)
9735 (save-excursion
9736 (vm-select-folder-buffer)
9737 (let* ((message (car vm-message-pointer))
9738 (folder buffer-file-name)
9739 (subject (vm-su-subject message))
9740 (author (vm-su-full-name message))
9741 (message-id (vm-su-message-id message)))
9742 (setq message-id (org-remove-angle-brackets message-id))
9743 (setq folder (abbreviate-file-name folder))
9744 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9745 folder)
9746 (setq folder (replace-match "" t t folder)))
9747 (setq cpltxt (concat author " on: " subject))
9748 (setq link (org-make-link "vm:" folder "#" message-id)))))
9749
9750 ((eq major-mode 'wl-summary-mode)
9751 (let* ((msgnum (wl-summary-message-number))
9752 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9753 msgnum 'message-id))
9754 (wl-message-entity (elmo-msgdb-overview-get-entity
9755 msgnum (wl-summary-buffer-msgdb)))
9756 (author (wl-summary-line-from)) ; FIXME: correct?
9757 (subject "???")) ; FIXME:
9758 (setq message-id (org-remove-angle-brackets message-id))
9759 (setq cpltxt (concat author " on: " subject))
9760 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9761 "#" message-id))))
9762
9763 ((or (equal major-mode 'mh-folder-mode)
9764 (equal major-mode 'mh-show-mode))
9765 (let ((from-header (org-mhe-get-header "From:"))
9766 (to-header (org-mhe-get-header "To:"))
9767 (subject (org-mhe-get-header "Subject:")))
9768 (setq cpltxt (concat from-header " on: " subject))
9769 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9770 (org-remove-angle-brackets
9771 (org-mhe-get-header "Message-Id:"))))))
9772
9773 ((eq major-mode 'rmail-mode)
9774 (save-excursion
9775 (save-restriction
9776 (rmail-narrow-to-non-pruned-header)
9777 (let ((folder buffer-file-name)
9778 (message-id (mail-fetch-field "message-id"))
9779 (author (mail-fetch-field "from"))
9780 (subject (mail-fetch-field "subject")))
9781 (setq message-id (org-remove-angle-brackets message-id))
9782 (setq cpltxt (concat author " on: " subject))
9783 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9784
9785 ((eq major-mode 'gnus-group-mode)
9786 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9787 (gnus-group-group-name)) ; version
9788 ((fboundp 'gnus-group-name)
9789 (gnus-group-name))
9790 (t "???"))))
9791 (setq cpltxt (concat
9792 (if (org-xor arg org-usenet-links-prefer-google)
9793 "http://groups.google.com/groups?group="
9794 "gnus:")
9795 group)
9796 link (org-make-link cpltxt))))
9797
9798 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9799 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9800 (gnus-summary-beginning-of-article)
9801 (let* ((group (car gnus-article-current))
9802 (article (cdr gnus-article-current))
9803 (header (gnus-summary-article-header article))
9804 (author (mail-header-from header))
9805 (message-id (mail-header-id header))
9806 (date (mail-header-date header))
9807 (subject (gnus-summary-subject-string)))
9808 (setq cpltxt (concat author " on: " subject))
9809 (if (org-xor arg org-usenet-links-prefer-google)
9810 (setq link
9811 (concat
9812 cpltxt "\n "
9813 (format "http://groups.google.com/groups?as_umsgid=%s"
9814 (org-fixup-message-id-for-http message-id))))
9815 (setq link (org-make-link "gnus:" group
9816 "#" (number-to-string article))))))
9817
9818 ((eq major-mode 'w3-mode)
9819 (setq cpltxt (url-view-url t)
9820 link (org-make-link cpltxt)))
9821 ((eq major-mode 'w3m-mode)
9822 (setq cpltxt (or w3m-current-title w3m-current-url)
9823 link (org-make-link w3m-current-url)))
9824
9825 ((setq search (run-hook-with-args-until-success
9826 'org-create-file-search-functions))
9827 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9828 "::" search))
9829 (setq cpltxt (or description link)))
9830
9831 ((eq major-mode 'image-mode)
9832 (setq cpltxt (concat "file:"
9833 (abbreviate-file-name buffer-file-name))
9834 link (org-make-link cpltxt)))
9835
9836 ((eq major-mode 'org-mode)
9837 ;; Just link to current headline
9838 (setq cpltxt (concat "file:"
9839 (abbreviate-file-name buffer-file-name)))
9840 ;; Add a context search string
9841 (when (org-xor org-context-in-file-links arg)
9842 ;; Check if we are on a target
9843 (if (save-excursion
9844 (skip-chars-forward "^>\n\r")
9845 (and (re-search-backward "<<" nil t)
9846 (looking-at "<<\\(.*?\\)>>")
9847 (<= (match-beginning 0) pos)
9848 (>= (match-end 0) pos)))
9849 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9850 (setq txt (cond
9851 ((org-on-heading-p) nil)
9852 ((org-region-active-p)
9853 (buffer-substring (region-beginning) (region-end)))
9854 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9855 (when (or (null txt) (string-match "\\S-" txt))
9856 (setq cpltxt
9857 (concat cpltxt "::"
9858 (if org-file-link-context-use-camel-case
9859 (org-make-org-heading-camel txt)
9860 (org-make-org-heading-search-string txt)))
9861 desc "NONE"))))
9862 (if (string-match "::\\'" cpltxt)
9863 (setq cpltxt (substring cpltxt 0 -2)))
9864 (setq link (org-make-link cpltxt)))
9865
9866 (buffer-file-name
9867 ;; Just link to this file here.
9868 (setq cpltxt (concat "file:"
9869 (abbreviate-file-name buffer-file-name)))
9870 ;; Add a context string
9871 (when (org-xor org-context-in-file-links arg)
9872 (setq txt (if (org-region-active-p)
9873 (buffer-substring (region-beginning) (region-end))
9874 (buffer-substring (point-at-bol) (point-at-eol))))
9875 ;; Only use search option if there is some text.
9876 (when (string-match "\\S-" txt)
9877 (setq cpltxt
9878 (concat cpltxt "::"
9879 (if org-file-link-context-use-camel-case
9880 (org-make-org-heading-camel txt)
9881 (org-make-org-heading-search-string txt)))
9882 desc "NONE")))
9883 (setq link (org-make-link cpltxt)))
9884
9885 ((interactive-p)
9886 (error "Cannot link to a buffer which is not visiting a file"))
9887
9888 (t (setq link nil)))
9889
9890 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9891 (setq link (or link cpltxt)
9892 desc (or desc cpltxt))
9893 (if (equal desc "NONE") (setq desc nil))
9894
9895 (if (and (interactive-p) link)
9896 (progn
9897 (setq org-stored-links
9898 (cons (list cpltxt link desc) org-stored-links))
9899 (message "Stored: %s" (or cpltxt link)))
9900 (org-make-link-string link desc))))
9901
9902 (defun org-make-org-heading-search-string (&optional string heading)
9903 "Make search string for STRING or current headline."
9904 (interactive)
9905 (let ((s (or string (org-get-heading))))
9906 (unless (and string (not heading))
9907 ;; We are using a headline, clean up garbage in there.
9908 (if (string-match org-todo-regexp s)
9909 (setq s (replace-match "" t t s)))
9910 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9911 (setq s (replace-match "" t t s)))
9912 (setq s (org-trim s))
9913 (if (string-match (concat "^\\(" org-quote-string "\\|"
9914 org-comment-string "\\)") s)
9915 (setq s (replace-match "" t t s)))
9916 (while (string-match org-ts-regexp s)
9917 (setq s (replace-match "" t t s))))
9918 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
9919 (setq s (replace-match " " t t s)))
9920 (or string (setq s (concat "*" s))) ; Add * for headlines
9921 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9922
9923 (defun org-make-org-heading-camel (&optional string heading)
9924 "Make a CamelCase string for STRING or the current headline."
9925 (interactive)
9926 (let ((s (or string (org-get-heading))))
9927 (unless (and string (not heading))
9928 ;; We are using a headline, clean up garbage in there.
9929 (if (string-match org-todo-regexp s)
9930 (setq s (replace-match "" t t s)))
9931 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9932 (setq s (replace-match "" t t s)))
9933 (setq s (org-trim s))
9934 (if (string-match (concat "^\\(" org-quote-string "\\|"
9935 org-comment-string "\\)") s)
9936 (setq s (replace-match "" t t s)))
9937 (while (string-match org-ts-regexp s)
9938 (setq s (replace-match "" t t s))))
9939 (while (string-match "[^a-zA-Z_ \t]+" s)
9940 (setq s (replace-match " " t t s)))
9941 (or string (setq s (concat "*" s))) ; Add * for headlines
9942 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
9943
9944 (defun org-make-link (&rest strings)
9945 "Concatenate STRINGS, format resulting string with `org-link-format'."
9946 (format org-link-format (apply 'concat strings)))
9947
9948 (defun org-make-link-string (link &optional description)
9949 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9950 (if (eq org-link-style 'plain)
9951 (if (equal description link)
9952 link
9953 (concat description "\n" link))
9954 (when (stringp description)
9955 ;; Remove brackets from the description, they are fatal.
9956 (while (string-match "\\[\\|\\]" description)
9957 (setq description (replace-match "" t t description))))
9958 (when (equal (org-link-escape link) description)
9959 ;; No description needed, it is identical
9960 (setq description nil))
9961 (when (and (not description)
9962 (not (equal link (org-link-escape link))))
9963 (setq description link))
9964 (concat "[[" (org-link-escape link) "]"
9965 (if description (concat "[" description "]") "")
9966 "]")))
9967
9968 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
9969 "Association list of escapes for some characters problematic in links.")
9970
9971 (defun org-link-escape (text)
9972 "Escape charaters in TEXT that are problematic for links."
9973 (when text
9974 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
9975 org-link-escape-chars "\\|")))
9976 (while (string-match re text)
9977 (setq text
9978 (replace-match
9979 (cdr (assoc (match-string 0 text) org-link-escape-chars))
9980 t t text)))
9981 text)))
9982
9983 (defun org-link-unescape (text)
9984 "Reverse the action of `org-link-escape'."
9985 (when text
9986 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
9987 org-link-escape-chars "\\|")))
9988 (while (string-match re text)
9989 (setq text
9990 (replace-match
9991 (car (rassoc (match-string 0 text) org-link-escape-chars))
9992 t t text)))
9993 text)))
9994
9995 (defun org-xor (a b)
9996 "Exclusive or."
9997 (if a (not b) b))
9998
9999 (defun org-get-header (header)
10000 "Find a header field in the current buffer."
10001 (save-excursion
10002 (goto-char (point-min))
10003 (let ((case-fold-search t) s)
10004 (cond
10005 ((eq header 'from)
10006 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10007 (setq s (match-string 1)))
10008 (while (string-match "\"" s)
10009 (setq s (replace-match "" t t s)))
10010 (if (string-match "[<(].*" s)
10011 (setq s (replace-match "" t t s))))
10012 ((eq header 'message-id)
10013 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10014 (setq s (match-string 1))))
10015 ((eq header 'subject)
10016 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10017 (setq s (match-string 1)))))
10018 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10019 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10020 s)))
10021
10022
10023 (defun org-fixup-message-id-for-http (s)
10024 "Replace special characters in a message id, so it can be used in an http query."
10025 (while (string-match "<" s)
10026 (setq s (replace-match "%3C" t t s)))
10027 (while (string-match ">" s)
10028 (setq s (replace-match "%3E" t t s)))
10029 (while (string-match "@" s)
10030 (setq s (replace-match "%40" t t s)))
10031 s)
10032
10033 (defun org-insert-link (&optional complete-file)
10034 "Insert a link. At the prompt, enter the link.
10035
10036 Completion can be used to select a link previously stored with
10037 `org-store-link'. When the empty string is entered (i.e. if you just
10038 press RET at the prompt), the link defaults to the most recently
10039 stored link. As SPC triggers completion in the minibuffer, you need to
10040 use M-SPC or C-q SPC to force the insertion of a space character.
10041
10042 You will also be prompted for a description, and if one is given, it will
10043 be displayed in the buffer instead of the link.
10044
10045 If there is already a link at point, this command will allow you to edit link
10046 and description parts.
10047
10048 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10049 selected using completion. The path to the file will be relative to
10050 the current directory if the file is in the current directory or a
10051 subdirectory. Otherwise, the link will be the absolute path as
10052 completed in the minibuffer (i.e. normally ~/path/to/file).
10053
10054 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10055 is in the current directory or below.
10056 With three \\[universal-argument] prefixes, negate the meaning of
10057 `org-keep-stored-link-after-insertion'."
10058 (interactive "P")
10059 (let (link desc entry remove file (pos (point)))
10060 (cond
10061 ((save-excursion
10062 (skip-chars-forward "^]\n\r")
10063 (and (re-search-backward "\\[\\[" nil t)
10064 (looking-at org-bracket-link-regexp)
10065 (<= (match-beginning 0) pos)
10066 (>= (match-end 0) pos)))
10067 ;; We do have a link at point, and we are going to edit it.
10068 (setq remove (list (match-beginning 0) (match-end 0)))
10069 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10070 (setq link (read-string "Link: "
10071 (org-link-unescape
10072 (org-match-string-no-properties 1)))))
10073 ((equal complete-file '(4))
10074 ;; Completing read for file names.
10075 (setq file (read-file-name "File: "))
10076 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10077 (pwd1 (file-name-as-directory (abbreviate-file-name
10078 (expand-file-name ".")))))
10079 (cond
10080 ((equal complete-file '(16))
10081 (setq link (org-make-link
10082 "file:"
10083 (abbreviate-file-name (expand-file-name file)))))
10084 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10085 (setq link (org-make-link "file:" (match-string 1 file))))
10086 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10087 (expand-file-name file))
10088 (setq link (org-make-link
10089 "file:" (match-string 1 (expand-file-name file)))))
10090 (t (setq link (org-make-link "file:" file))))))
10091 (t
10092 ;; Read link, with completion for stored links.
10093 (setq link (org-completing-read
10094 "Link: " org-stored-links nil nil nil
10095 org-insert-link-history
10096 (or (car (car org-stored-links)))))
10097 (setq entry (assoc link org-stored-links))
10098 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10099 (not org-keep-stored-link-after-insertion))
10100 (setq org-stored-links (delq (assoc link org-stored-links)
10101 org-stored-links)))
10102 (setq link (if entry (nth 1 entry) link)
10103 desc (or desc (nth 2 entry)))))
10104
10105 (if (string-match org-plain-link-re link)
10106 ;; URL-like link, normalize the use of angular brackets.
10107 (setq link (org-make-link (org-remove-angle-brackets link))))
10108
10109 ;; Check if we are linking to the current file with a search option
10110 ;; If yes, simplify the link by using only the search option.
10111 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
10112 (let* ((path (match-string 1 link))
10113 (case-fold-search nil)
10114 (search (match-string 2 link)))
10115 (save-match-data
10116 (if (equal (file-truename buffer-file-name) (file-truename path))
10117 ;; We are linking to this same file, with a search option
10118 (setq link search)))))
10119
10120 ;; Check if we can/should use a relative path. If yes, simplify the link
10121 (when (string-match "\\<file:\\(.*\\)" link)
10122 (let* ((path (match-string 1 link))
10123 (case-fold-search nil))
10124 (cond
10125 ((eq org-link-file-path-type 'absolute)
10126 (setq path (abbreviate-file-name (expand-file-name path))))
10127 ((eq org-link-file-path-type 'noabbrev)
10128 (setq path (expand-file-name path)))
10129 ((eq org-link-file-path-type 'relative)
10130 (setq path (file-relative-name path)))
10131 (t
10132 (save-match-data
10133 (if (string-match (concat "^" (regexp-quote
10134 (file-name-as-directory
10135 (expand-file-name "."))))
10136 (expand-file-name path))
10137 ;; We are linking a file with relative path name.
10138 (setq path (substring (expand-file-name path)
10139 (match-end 0)))))))
10140 (setq link (concat "file:" path))))
10141
10142 (setq desc (read-string "Description: " desc))
10143 (unless (string-match "\\S-" desc) (setq desc nil))
10144 (if remove (apply 'delete-region remove))
10145 (insert (org-make-link-string link desc))))
10146
10147 (defun org-completing-read (&rest args)
10148 (let ((minibuffer-local-completion-map
10149 (copy-keymap minibuffer-local-completion-map)))
10150 (define-key minibuffer-local-completion-map " " 'self-insert-command)
10151 (apply 'completing-read args)))
10152
10153 ;;; Hooks for remember.el
10154
10155 (defvar org-finish-function nil)
10156
10157 ;;;###autoload
10158 (defun org-remember-annotation ()
10159 "Return a link to the current location as an annotation for remember.el.
10160 If you are using Org-mode files as target for data storage with
10161 remember.el, then the annotations should include a link compatible with the
10162 conventions in Org-mode. This function returns such a link."
10163 (org-store-link nil))
10164
10165 (defconst org-remember-help
10166 "Select a destination location for the note.
10167 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10168 RET at beg-of-buf -> Append to file as level 2 headline
10169 RET on headline -> Store as sublevel entry to current headline
10170 <left>/<right> -> before/after current headline, same headings level")
10171
10172 ;;;###autoload
10173 (defun org-remember-apply-template ()
10174 "Initialize *remember* buffer with template, invoke `org-mode'.
10175 This function should be placed into `remember-mode-hook' and in fact requires
10176 to be run from that hook to fucntion properly."
10177 (if org-remember-templates
10178
10179 (let* ((entry (if (= (length org-remember-templates) 1)
10180 (cdar org-remember-templates)
10181 (message "Select template: %s"
10182 (mapconcat
10183 (lambda (x) (char-to-string (car x)))
10184 org-remember-templates " "))
10185 (cdr (assoc (read-char-exclusive) org-remember-templates))))
10186 (tpl (car entry))
10187 (file (if (consp (cdr entry)) (nth 1 entry)))
10188 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10189 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10190 (v-u (concat "[" (substring v-t 1 -1) "]"))
10191 (v-U (concat "[" (substring v-T 1 -1) "]"))
10192 (v-a annotation) ; defined in `remember-mode'
10193 (v-i initial) ; defined in `remember-mode'
10194 (v-n user-full-name)
10195 )
10196 (unless tpl (setq tpl "") (message "No template") (ding))
10197 (insert tpl) (goto-char (point-min))
10198 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
10199 (when (and initial (equal (match-string 0) "%i"))
10200 (save-match-data
10201 (let* ((lead (buffer-substring
10202 (point-at-bol) (match-beginning 0))))
10203 (setq v-i (mapconcat 'identity
10204 (org-split-string initial "\n")
10205 (concat "\n" lead))))))
10206 (replace-match
10207 (or (eval (intern (concat "v-" (match-string 1)))) "")
10208 t t))
10209 (let ((org-startup-folded nil)
10210 (org-startup-with-deadline-check nil))
10211 (org-mode))
10212 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10213 (set (make-local-variable 'org-default-notes-file) file))
10214 (goto-char (point-min))
10215 (if (re-search-forward "%\\?" nil t) (replace-match "")))
10216 (let ((org-startup-folded nil)
10217 (org-startup-with-deadline-check nil))
10218 (org-mode)))
10219 (set (make-local-variable 'org-finish-function) 'remember-buffer))
10220
10221 ;;;###autoload
10222 (defun org-remember-handler ()
10223 "Store stuff from remember.el into an org file.
10224 First prompts for an org file. If the user just presses return, the value
10225 of `org-default-notes-file' is used.
10226 Then the command offers the headings tree of the selected file in order to
10227 file the text at a specific location.
10228 You can either immediately press RET to get the note appended to the
10229 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10230 find a better place. Then press RET or <left> or <right> in insert the note.
10231
10232 Key Cursor position Note gets inserted
10233 -----------------------------------------------------------------------------
10234 RET buffer-start as level 2 heading at end of file
10235 RET on headline as sublevel of the heading at cursor
10236 RET no heading at cursor position, level taken from context.
10237 Or use prefix arg to specify level manually.
10238 <left> on headline as same level, before current heading
10239 <right> on headline as same level, after current heading
10240
10241 So the fastest way to store the note is to press RET RET to append it to
10242 the default file. This way your current train of thought is not
10243 interrupted, in accordance with the principles of remember.el. But with
10244 little extra effort, you can push it directly to the correct location.
10245
10246 Before being stored away, the function ensures that the text has a
10247 headline, i.e. a first line that starts with a \"*\". If not, a headline
10248 is constructed from the current date and some additional data.
10249
10250 If the variable `org-adapt-indentation' is non-nil, the entire text is
10251 also indented so that it starts in the same column as the headline
10252 \(i.e. after the stars).
10253
10254 See also the variable `org-reverse-note-order'."
10255 (catch 'quit
10256 (let* ((txt (buffer-substring (point-min) (point-max)))
10257 (fastp current-prefix-arg)
10258 (file (if fastp org-default-notes-file (org-get-org-file)))
10259 (visiting (find-buffer-visiting file))
10260 (org-startup-with-deadline-check nil)
10261 (org-startup-folded nil)
10262 (org-startup-align-all-tables nil)
10263 spos level indent reversed)
10264 ;; Modify text so that it becomes a nice subtree which can be inserted
10265 ;; into an org tree.
10266 (let* ((lines (split-string txt "\n"))
10267 first)
10268 ;; remove empty lines at the beginning
10269 (while (and lines (string-match "^[ \t]*\n" (car lines)))
10270 (setq lines (cdr lines)))
10271 (setq first (car lines) lines (cdr lines))
10272 (if (string-match "^\\*+" first)
10273 ;; Is already a headline
10274 (setq indent nil)
10275 ;; We need to add a headline: Use time and first buffer line
10276 (setq lines (cons first lines)
10277 first (concat "* " (current-time-string)
10278 " (" (remember-buffer-desc) ")")
10279 indent " "))
10280 (if (and org-adapt-indentation indent)
10281 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10282 (setq txt (concat first "\n"
10283 (mapconcat 'identity lines "\n"))))
10284 ;; Find the file
10285 (if (not visiting)
10286 (find-file-noselect file))
10287 (with-current-buffer (get-file-buffer file)
10288 (save-excursion (and (goto-char (point-min))
10289 (not (re-search-forward "^\\* " nil t))
10290 (insert "\n* Notes\n")))
10291 (setq reversed (org-notes-order-reversed-p))
10292 (save-excursion
10293 (save-restriction
10294 (widen)
10295 ;; Ask the User for a location
10296 (setq spos (if fastp 1 (org-get-location
10297 (current-buffer)
10298 org-remember-help)))
10299 (if (not spos) (throw 'quit nil)) ; return nil to show we did
10300 ; not handle this note
10301 (goto-char spos)
10302 (cond ((bobp)
10303 ;; Put it at the start or end, as level 2
10304 (save-restriction
10305 (widen)
10306 (goto-char (if reversed (point-min) (point-max)))
10307 (if (not (bolp)) (newline))
10308 (org-paste-subtree 2 txt)))
10309 ((and (org-on-heading-p nil) (not current-prefix-arg))
10310 ;; Put it below this entry, at the beg/end of the subtree
10311 (org-back-to-heading)
10312 (setq level (funcall outline-level))
10313 (if reversed
10314 (outline-end-of-heading)
10315 (outline-end-of-subtree))
10316 (if (not (bolp)) (newline))
10317 (beginning-of-line 1)
10318 (org-paste-subtree (1+ level) txt))
10319 (t
10320 ;; Put it right there, with automatic level determined by
10321 ;; org-paste-subtree or from prefix arg
10322 (org-paste-subtree current-prefix-arg txt)))
10323 (when remember-save-after-remembering
10324 (save-buffer)
10325 (if (not visiting) (kill-buffer (current-buffer)))))))))
10326 t) ;; return t to indicate that we took care of this note.
10327
10328 (defun org-get-org-file ()
10329 "Read a filename, with default directory `org-directory'."
10330 (let ((default (or org-default-notes-file remember-data-file)))
10331 (read-file-name (format "File name [%s]: " default)
10332 (file-name-as-directory org-directory)
10333 default)))
10334
10335 (defun org-notes-order-reversed-p ()
10336 "Check if the current file should receive notes in reversed order."
10337 (cond
10338 ((not org-reverse-note-order) nil)
10339 ((eq t org-reverse-note-order) t)
10340 ((not (listp org-reverse-note-order)) nil)
10341 (t (catch 'exit
10342 (let ((all org-reverse-note-order)
10343 entry)
10344 (while (setq entry (pop all))
10345 (if (string-match (car entry) buffer-file-name)
10346 (throw 'exit (cdr entry))))
10347 nil)))))
10348
10349 ;;; Tables
10350
10351 ;; Watch out: Here we are talking about two different kind of tables.
10352 ;; Most of the code is for the tables created with the Org-mode table editor.
10353 ;; Sometimes, we talk about tables created and edited with the table.el
10354 ;; Emacs package. We call the former org-type tables, and the latter
10355 ;; table.el-type tables.
10356
10357
10358 (defun org-before-change-function (beg end)
10359 "Every change indicates that a table might need an update."
10360 (setq org-table-may-need-update t))
10361
10362 (defconst org-table-line-regexp "^[ \t]*|"
10363 "Detects an org-type table line.")
10364 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
10365 "Detects an org-type table line.")
10366 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
10367 "Detects a table line marked for automatic recalculation.")
10368 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
10369 "Detects a table line marked for automatic recalculation.")
10370 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
10371 "Detects a table line marked for automatic recalculation.")
10372 (defconst org-table-hline-regexp "^[ \t]*|-"
10373 "Detects an org-type table hline.")
10374 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
10375 "Detects a table-type table hline.")
10376 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
10377 "Detects an org-type or table-type table.")
10378 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
10379 "Searching from within a table (any type) this finds the first line
10380 outside the table.")
10381 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
10382 "Searching from within a table (any type) this finds the first line
10383 outside the table.")
10384
10385 (defun org-table-create-with-table.el ()
10386 "Use the table.el package to insert a new table.
10387 If there is already a table at point, convert between Org-mode tables
10388 and table.el tables."
10389 (interactive)
10390 (require 'table)
10391 (cond
10392 ((org-at-table.el-p)
10393 (if (y-or-n-p "Convert table to Org-mode table? ")
10394 (org-table-convert)))
10395 ((org-at-table-p)
10396 (if (y-or-n-p "Convert table to table.el table? ")
10397 (org-table-convert)))
10398 (t (call-interactively 'table-insert))))
10399
10400 (defun org-table-create-or-convert-from-region (arg)
10401 "Convert region to table, or create an empty table.
10402 If there is an active region, convert it to a table. If there is no such
10403 region, create an empty table."
10404 (interactive "P")
10405 (if (org-region-active-p)
10406 (org-table-convert-region (region-beginning) (region-end) arg)
10407 (org-table-create arg)))
10408
10409 (defun org-table-create (&optional size)
10410 "Query for a size and insert a table skeleton.
10411 SIZE is a string Columns x Rows like for example \"3x2\"."
10412 (interactive "P")
10413 (unless size
10414 (setq size (read-string
10415 (concat "Table size Columns x Rows [e.g. "
10416 org-table-default-size "]: ")
10417 "" nil org-table-default-size)))
10418
10419 (let* ((pos (point))
10420 (indent (make-string (current-column) ?\ ))
10421 (split (org-split-string size " *x *"))
10422 (rows (string-to-number (nth 1 split)))
10423 (columns (string-to-number (car split)))
10424 (line (concat (apply 'concat indent "|" (make-list columns " |"))
10425 "\n")))
10426 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
10427 (point-at-bol) (point)))
10428 (beginning-of-line 1)
10429 (newline))
10430 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
10431 (dotimes (i rows) (insert line))
10432 (goto-char pos)
10433 (if (> rows 1)
10434 ;; Insert a hline after the first row.
10435 (progn
10436 (end-of-line 1)
10437 (insert "\n|-")
10438 (goto-char pos)))
10439 (org-table-align)))
10440
10441 (defun org-table-convert-region (beg0 end0 &optional nspace)
10442 "Convert region to a table.
10443 The region goes from BEG0 to END0, but these borders will be moved
10444 slightly, to make sure a beginning of line in the first line is included.
10445 When NSPACE is non-nil, it indicates the minimum number of spaces that
10446 separate columns (default: just one space)."
10447 (interactive "rP")
10448 (let* ((beg (min beg0 end0))
10449 (end (max beg0 end0))
10450 (tabsep t)
10451 re)
10452 (goto-char beg)
10453 (beginning-of-line 1)
10454 (setq beg (move-marker (make-marker) (point)))
10455 (goto-char end)
10456 (if (bolp) (backward-char 1) (end-of-line 1))
10457 (setq end (move-marker (make-marker) (point)))
10458 ;; Lets see if this is tab-separated material. If every nonempty line
10459 ;; contains a tab, we will assume that it is tab-separated material
10460 (if nspace
10461 (setq tabsep nil)
10462 (goto-char beg)
10463 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
10464 (if nspace (setq tabsep nil))
10465 (if tabsep
10466 (setq re "^\\|\t")
10467 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
10468 (max 1 (prefix-numeric-value nspace)))))
10469 (goto-char beg)
10470 (while (re-search-forward re end t)
10471 (replace-match "|" t t))
10472 (goto-char beg)
10473 (insert " ")
10474 (org-table-align)))
10475
10476 (defun org-table-import (file arg)
10477 "Import FILE as a table.
10478 The file is assumed to be tab-separated. Such files can be produced by most
10479 spreadsheet and database applications. If no tabs (at least one per line)
10480 are found, lines will be split on whitespace into fields."
10481 (interactive "f\nP")
10482 (or (bolp) (newline))
10483 (let ((beg (point))
10484 (pm (point-max)))
10485 (insert-file-contents file)
10486 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
10487
10488 (defun org-table-export ()
10489 "Export table as a tab-separated file.
10490 Such a file can be imported into a spreadsheet program like Excel."
10491 (interactive)
10492 (let* ((beg (org-table-begin))
10493 (end (org-table-end))
10494 (table (buffer-substring beg end))
10495 (file (read-file-name "Export table to: "))
10496 buf)
10497 (unless (or (not (file-exists-p file))
10498 (y-or-n-p (format "Overwrite file %s? " file)))
10499 (error "Abort"))
10500 (with-current-buffer (find-file-noselect file)
10501 (setq buf (current-buffer))
10502 (erase-buffer)
10503 (fundamental-mode)
10504 (insert table)
10505 (goto-char (point-min))
10506 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
10507 (replace-match "" t t)
10508 (end-of-line 1))
10509 (goto-char (point-min))
10510 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
10511 (replace-match "" t t)
10512 (goto-char (min (1+ (point)) (point-max))))
10513 (goto-char (point-min))
10514 (while (re-search-forward "^-[-+]*$" nil t)
10515 (replace-match "")
10516 (if (looking-at "\n")
10517 (delete-char 1)))
10518 (goto-char (point-min))
10519 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
10520 (replace-match "\t" t t))
10521 (save-buffer))
10522 (kill-buffer buf)))
10523
10524 (defvar org-table-aligned-begin-marker (make-marker)
10525 "Marker at the beginning of the table last aligned.
10526 Used to check if cursor still is in that table, to minimize realignment.")
10527 (defvar org-table-aligned-end-marker (make-marker)
10528 "Marker at the end of the table last aligned.
10529 Used to check if cursor still is in that table, to minimize realignment.")
10530 (defvar org-table-last-alignment nil
10531 "List of flags for flushright alignment, from the last re-alignment.
10532 This is being used to correctly align a single field after TAB or RET.")
10533 (defvar org-table-last-column-widths nil
10534 "List of max width of fields in each column.
10535 This is being used to correctly align a single field after TAB or RET.")
10536
10537 (defvar org-last-recalc-line nil)
10538 (defconst org-narrow-column-arrow "=>"
10539 "Used as display property in narrowed table columns.")
10540
10541 (defun org-table-align ()
10542 "Align the table at point by aligning all vertical bars."
10543 (interactive)
10544 (let* (
10545 ;; Limits of table
10546 (beg (org-table-begin))
10547 (end (org-table-end))
10548 ;; Current cursor position
10549 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10550 (colpos (org-table-current-column))
10551 (winstart (window-start))
10552 lines (new "") lengths l typenums ty fields maxfields i
10553 column
10554 (indent "") cnt frac
10555 rfmt hfmt
10556 (spaces '(1 . 1))
10557 (sp1 (car spaces))
10558 (sp2 (cdr spaces))
10559 (rfmt1 (concat
10560 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
10561 (hfmt1 (concat
10562 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
10563 emptystrings links narrow fmax f1 len c e)
10564 (untabify beg end)
10565 (remove-text-properties beg end '(org-cwidth t display t))
10566 ;; Check if we have links
10567 (goto-char beg)
10568 (setq links (re-search-forward org-bracket-link-regexp end t))
10569 ;; Make sure the link properties are right
10570 (when links (goto-char beg) (while (org-activate-bracket-links end)))
10571 ;; Check if we are narrowing any columns
10572 (goto-char beg)
10573 (setq narrow (and org-format-transports-properties-p
10574 (re-search-forward "<[0-9]+>" end t)))
10575 ;; Get the rows
10576 (setq lines (org-split-string
10577 (buffer-substring beg end) "\n"))
10578 ;; Store the indentation of the first line
10579 (if (string-match "^ *" (car lines))
10580 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
10581 ;; Mark the hlines by setting the corresponding element to nil
10582 ;; At the same time, we remove trailing space.
10583 (setq lines (mapcar (lambda (l)
10584 (if (string-match "^ *|-" l)
10585 nil
10586 (if (string-match "[ \t]+$" l)
10587 (substring l 0 (match-beginning 0))
10588 l)))
10589 lines))
10590 ;; Get the data fields by splitting the lines.
10591 (setq fields (mapcar
10592 (lambda (l)
10593 (org-split-string l " *| *"))
10594 (delq nil (copy-sequence lines))))
10595 ;; How many fields in the longest line?
10596 (condition-case nil
10597 (setq maxfields (apply 'max (mapcar 'length fields)))
10598 (error
10599 (kill-region beg end)
10600 (org-table-create org-table-default-size)
10601 (error "Empty table - created default table")))
10602 ;; A list of empty string to fill any short rows on output
10603 (setq emptystrings (make-list maxfields ""))
10604 ;; Check for special formatting.
10605 (setq i -1)
10606 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
10607 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
10608 ;; Check if there is an explicit width specified
10609 (when (and org-table-limit-column-width narrow)
10610 (setq c column fmax nil)
10611 (while c
10612 (setq e (pop c))
10613 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
10614 (setq fmax (string-to-number (match-string 1 e)) c nil)))
10615 ;; Find fields that are wider than fmax, and shorten them
10616 (when fmax
10617 (loop for xx in column do
10618 (when (and (stringp xx)
10619 (> (org-string-width xx) fmax))
10620 (org-add-props xx nil
10621 'help-echo
10622 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
10623 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
10624 (unless (> f1 1)
10625 (error "Cannot narrow field starting with wide link \"%s\""
10626 (match-string 0 xx)))
10627 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
10628 (add-text-properties (- f1 2) f1
10629 (list 'display org-narrow-column-arrow)
10630 xx)))))
10631 ;; Get the maximum width for each column
10632 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
10633 ;; Get the fraction of numbers, to decide about alignment of the column
10634 (setq cnt 0 frac 0.0)
10635 (loop for x in column do
10636 (if (equal x "")
10637 nil
10638 (setq frac ( / (+ (* frac cnt)
10639 (if (string-match org-table-number-regexp x) 1 0))
10640 (setq cnt (1+ cnt))))))
10641 (push (>= frac org-table-number-fraction) typenums))
10642 (setq lengths (nreverse lengths) typenums (nreverse typenums))
10643
10644 ;; Store the alignment of this table, for later editing of single fields
10645 (setq org-table-last-alignment typenums
10646 org-table-last-column-widths lengths)
10647
10648 ;; With invisible characters, `format' does not get the field width right
10649 ;; So we need to make these fields wide by hand.
10650 (when links
10651 (loop for i from 0 upto (1- maxfields) do
10652 (setq len (nth i lengths))
10653 (loop for j from 0 upto (1- (length fields)) do
10654 (setq c (nthcdr i (car (nthcdr j fields))))
10655 (if (and (stringp (car c))
10656 (string-match org-bracket-link-regexp (car c))
10657 (< (org-string-width (car c)) len))
10658 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
10659
10660 ;; Compute the formats needed for output of the table
10661 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
10662 (while (setq l (pop lengths))
10663 (setq ty (if (pop typenums) "" "-")) ; number types flushright
10664 (setq rfmt (concat rfmt (format rfmt1 ty l))
10665 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
10666 (setq rfmt (concat rfmt "\n")
10667 hfmt (concat (substring hfmt 0 -1) "|\n"))
10668
10669 (setq new (mapconcat
10670 (lambda (l)
10671 (if l (apply 'format rfmt
10672 (append (pop fields) emptystrings))
10673 hfmt))
10674 lines ""))
10675 ;; Replace the old one
10676 (delete-region beg end)
10677 (move-marker end nil)
10678 (move-marker org-table-aligned-begin-marker (point))
10679 (insert new)
10680 (move-marker org-table-aligned-end-marker (point))
10681 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
10682 (goto-char org-table-aligned-begin-marker)
10683 (while (org-hide-wide-columns org-table-aligned-end-marker)))
10684 ;; Try to move to the old location (approximately)
10685 (goto-line linepos)
10686 (set-window-start (selected-window) winstart 'noforce)
10687 (org-table-goto-column colpos)
10688 (setq org-table-may-need-update nil)
10689 ))
10690
10691 (defun org-string-width (s)
10692 "Compute width of string, ignoring invisible characters.
10693 This ignores character with invisibility property `org-link', and also
10694 characters with property `org-cwidth', because these will become invisible
10695 upon the next fontification round."
10696 (let (b)
10697 (when (or (eq t buffer-invisibility-spec)
10698 (assq 'org-link buffer-invisibility-spec))
10699 (while (setq b (text-property-any 0 (length s)
10700 'invisible 'org-link s))
10701 (setq s (concat (substring s 0 b)
10702 (substring s (or (next-single-property-change
10703 b 'invisible s) (length s)))))))
10704 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
10705 (setq s (concat (substring s 0 b)
10706 (substring s (or (next-single-property-change
10707 b 'org-cwidth s) (length s))))))
10708 (string-width s)))
10709
10710 (defun org-table-begin (&optional table-type)
10711 "Find the beginning of the table and return its position.
10712 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
10713 (save-excursion
10714 (if (not (re-search-backward
10715 (if table-type org-table-any-border-regexp
10716 org-table-border-regexp)
10717 nil t))
10718 (progn (goto-char (point-min)) (point))
10719 (goto-char (match-beginning 0))
10720 (beginning-of-line 2)
10721 (point))))
10722
10723 (defun org-table-end (&optional table-type)
10724 "Find the end of the table and return its position.
10725 With argument TABLE-TYPE, go to the end of a table.el-type table."
10726 (save-excursion
10727 (if (not (re-search-forward
10728 (if table-type org-table-any-border-regexp
10729 org-table-border-regexp)
10730 nil t))
10731 (goto-char (point-max))
10732 (goto-char (match-beginning 0)))
10733 (point-marker)))
10734
10735 (defun org-table-justify-field-maybe (&optional new)
10736 "Justify the current field, text to left, number to right.
10737 Optional argument NEW may specify text to replace the current field content."
10738 (cond
10739 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
10740 ((org-at-table-hline-p))
10741 ((and (not new)
10742 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
10743 (current-buffer)))
10744 (< (point) org-table-aligned-begin-marker)
10745 (>= (point) org-table-aligned-end-marker)))
10746 ;; This is not the same table, force a full re-align
10747 (setq org-table-may-need-update t))
10748 (t ;; realign the current field, based on previous full realign
10749 (let* ((pos (point)) s
10750 (col (org-table-current-column))
10751 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
10752 l f n o e)
10753 (when (> col 0)
10754 (skip-chars-backward "^|\n")
10755 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
10756 (progn
10757 (setq s (match-string 1)
10758 o (match-string 0)
10759 l (max 1 (- (match-end 0) (match-beginning 0) 3))
10760 e (not (= (match-beginning 2) (match-end 2))))
10761 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
10762 l (if e "|" (setq org-table-may-need-update t) ""))
10763 n (format f s))
10764 (if new
10765 (if (<= (length new) l) ;; FIXME: length -> str-width?
10766 (setq n (format f new))
10767 (setq n (concat new "|") org-table-may-need-update t)))
10768 (or (equal n o)
10769 (let (org-table-may-need-update)
10770 (replace-match n))))
10771 (setq org-table-may-need-update t))
10772 (goto-char pos))))))
10773
10774 (defun org-table-next-field ()
10775 "Go to the next field in the current table, creating new lines as needed.
10776 Before doing so, re-align the table if necessary."
10777 (interactive)
10778 (org-table-maybe-eval-formula)
10779 (org-table-maybe-recalculate-line)
10780 (if (and org-table-automatic-realign
10781 org-table-may-need-update)
10782 (org-table-align))
10783 (let ((end (org-table-end)))
10784 (if (org-at-table-hline-p)
10785 (end-of-line 1))
10786 (condition-case nil
10787 (progn
10788 (re-search-forward "|" end)
10789 (if (looking-at "[ \t]*$")
10790 (re-search-forward "|" end))
10791 (if (and (looking-at "-")
10792 org-table-tab-jumps-over-hlines
10793 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
10794 (goto-char (match-beginning 1)))
10795 (if (looking-at "-")
10796 (progn
10797 (beginning-of-line 0)
10798 (org-table-insert-row 'below))
10799 (if (looking-at " ") (forward-char 1))))
10800 (error
10801 (org-table-insert-row 'below)))))
10802
10803 (defun org-table-previous-field ()
10804 "Go to the previous field in the table.
10805 Before doing so, re-align the table if necessary."
10806 (interactive)
10807 (org-table-justify-field-maybe)
10808 (org-table-maybe-recalculate-line)
10809 (if (and org-table-automatic-realign
10810 org-table-may-need-update)
10811 (org-table-align))
10812 (if (org-at-table-hline-p)
10813 (end-of-line 1))
10814 (re-search-backward "|" (org-table-begin))
10815 (re-search-backward "|" (org-table-begin))
10816 (while (looking-at "|\\(-\\|[ \t]*$\\)")
10817 (re-search-backward "|" (org-table-begin)))
10818 (if (looking-at "| ?")
10819 (goto-char (match-end 0))))
10820
10821 (defun org-table-next-row ()
10822 "Go to the next row (same column) in the current table.
10823 Before doing so, re-align the table if necessary."
10824 (interactive)
10825 (org-table-maybe-eval-formula)
10826 (org-table-maybe-recalculate-line)
10827 (if (or (looking-at "[ \t]*$")
10828 (save-excursion (skip-chars-backward " \t") (bolp)))
10829 (newline)
10830 (if (and org-table-automatic-realign
10831 org-table-may-need-update)
10832 (org-table-align))
10833 (let ((col (org-table-current-column)))
10834 (beginning-of-line 2)
10835 (if (or (not (org-at-table-p))
10836 (org-at-table-hline-p))
10837 (progn
10838 (beginning-of-line 0)
10839 (org-table-insert-row 'below)))
10840 (org-table-goto-column col)
10841 (skip-chars-backward "^|\n\r")
10842 (if (looking-at " ") (forward-char 1)))))
10843
10844 (defun org-table-copy-down (n)
10845 "Copy a field down in the current column.
10846 If the field at the cursor is empty, copy into it the content of the nearest
10847 non-empty field above. With argument N, use the Nth non-empty field.
10848 If the current field is not empty, it is copied down to the next row, and
10849 the cursor is moved with it. Therefore, repeating this command causes the
10850 column to be filled row-by-row.
10851 If the variable `org-table-copy-increment' is non-nil and the field is an
10852 integer, it will be incremented while copying."
10853 (interactive "p")
10854 (let* ((colpos (org-table-current-column))
10855 (field (org-table-get-field))
10856 (non-empty (string-match "[^ \t]" field))
10857 (beg (org-table-begin))
10858 txt)
10859 (org-table-check-inside-data-field)
10860 (if non-empty
10861 (progn
10862 (setq txt (org-trim field))
10863 (org-table-next-row)
10864 (org-table-blank-field))
10865 (save-excursion
10866 (setq txt
10867 (catch 'exit
10868 (while (progn (beginning-of-line 1)
10869 (re-search-backward org-table-dataline-regexp
10870 beg t))
10871 (org-table-goto-column colpos t)
10872 (if (and (looking-at
10873 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
10874 (= (setq n (1- n)) 0))
10875 (throw 'exit (match-string 1))))))))
10876 (if txt
10877 (progn
10878 (if (and org-table-copy-increment
10879 (string-match "^[0-9]+$" txt))
10880 (setq txt (format "%d" (+ (string-to-number txt) 1))))
10881 (insert txt)
10882 (org-table-maybe-recalculate-line)
10883 (org-table-align))
10884 (error "No non-empty field found"))))
10885
10886 (defun org-table-check-inside-data-field ()
10887 "Is point inside a table data field?
10888 I.e. not on a hline or before the first or after the last column?
10889 This actually throws an error, so it aborts the current command."
10890 (if (or (not (org-at-table-p))
10891 (= (org-table-current-column) 0)
10892 (org-at-table-hline-p)
10893 (looking-at "[ \t]*$"))
10894 (error "Not in table data field")))
10895
10896 (defvar org-table-clip nil
10897 "Clipboard for table regions.")
10898
10899 (defun org-table-blank-field ()
10900 "Blank the current table field or active region."
10901 (interactive)
10902 (org-table-check-inside-data-field)
10903 (if (and (interactive-p) (org-region-active-p))
10904 (let (org-table-clip)
10905 (org-table-cut-region (region-beginning) (region-end)))
10906 (skip-chars-backward "^|")
10907 (backward-char 1)
10908 (if (looking-at "|[^|\n]+")
10909 (let* ((pos (match-beginning 0))
10910 (match (match-string 0))
10911 (len (org-string-width match)))
10912 (replace-match (concat "|" (make-string (1- len) ?\ )))
10913 (goto-char (+ 2 pos))
10914 (substring match 1)))))
10915
10916 (defun org-table-get-field (&optional n replace)
10917 "Return the value of the field in column N of current row.
10918 N defaults to current field.
10919 If REPLACE is a string, replace field with this value. The return value
10920 is always the old value."
10921 (and n (org-table-goto-column n))
10922 (skip-chars-backward "^|\n")
10923 (backward-char 1)
10924 (if (looking-at "|[^|\r\n]*")
10925 (let* ((pos (match-beginning 0))
10926 (val (buffer-substring (1+ pos) (match-end 0))))
10927 (if replace
10928 (replace-match (concat "|" replace)))
10929 (goto-char (min (point-at-eol) (+ 2 pos)))
10930 val)
10931 (forward-char 1) ""))
10932
10933 (defun org-table-current-column ()
10934 "Find out which column we are in.
10935 When called interactively, column is also displayed in echo area."
10936 (interactive)
10937 (if (interactive-p) (org-table-check-inside-data-field))
10938 (save-excursion
10939 (let ((cnt 0) (pos (point)))
10940 (beginning-of-line 1)
10941 (while (search-forward "|" pos t)
10942 (setq cnt (1+ cnt)))
10943 (if (interactive-p) (message "This is table column %d" cnt))
10944 cnt)))
10945
10946 (defun org-table-goto-column (n &optional on-delim force)
10947 "Move the cursor to the Nth column in the current table line.
10948 With optional argument ON-DELIM, stop with point before the left delimiter
10949 of the field.
10950 If there are less than N fields, just go to after the last delimiter.
10951 However, when FORCE is non-nil, create new columns if necessary."
10952 (interactive "p")
10953 (let ((pos (point-at-eol)))
10954 (beginning-of-line 1)
10955 (when (> n 0)
10956 (while (and (> (setq n (1- n)) -1)
10957 (or (search-forward "|" pos t)
10958 (and force
10959 (progn (end-of-line 1)
10960 (skip-chars-backward "^|")
10961 (insert " | "))))))
10962 ; (backward-char 2) t)))))
10963 (when (and force (not (looking-at ".*|")))
10964 (save-excursion (end-of-line 1) (insert " | ")))
10965 (if on-delim
10966 (backward-char 1)
10967 (if (looking-at " ") (forward-char 1))))))
10968
10969 (defun org-at-table-p (&optional table-type)
10970 "Return t if the cursor is inside an org-type table.
10971 If TABLE-TYPE is non-nil, also check for table.el-type tables."
10972 (if org-enable-table-editor
10973 (save-excursion
10974 (beginning-of-line 1)
10975 (looking-at (if table-type org-table-any-line-regexp
10976 org-table-line-regexp)))
10977 nil))
10978
10979 (defun org-at-table.el-p ()
10980 "Return t if and only if we are at a table.el table."
10981 (and (org-at-table-p 'any)
10982 (save-excursion
10983 (goto-char (org-table-begin 'any))
10984 (looking-at org-table1-hline-regexp))))
10985
10986 (defun org-table-recognize-table.el ()
10987 "If there is a table.el table nearby, recognize it and move into it."
10988 (if org-table-tab-recognizes-table.el
10989 (if (org-at-table.el-p)
10990 (progn
10991 (beginning-of-line 1)
10992 (if (looking-at org-table-dataline-regexp)
10993 nil
10994 (if (looking-at org-table1-hline-regexp)
10995 (progn
10996 (beginning-of-line 2)
10997 (if (looking-at org-table-any-border-regexp)
10998 (beginning-of-line -1)))))
10999 (if (re-search-forward "|" (org-table-end t) t)
11000 (progn
11001 (require 'table)
11002 (if (table--at-cell-p (point))
11003 t
11004 (message "recognizing table.el table...")
11005 (table-recognize-table)
11006 (message "recognizing table.el table...done")))
11007 (error "This should not happen..."))
11008 t)
11009 nil)
11010 nil))
11011
11012 (defun org-at-table-hline-p ()
11013 "Return t if the cursor is inside a hline in a table."
11014 (if org-enable-table-editor
11015 (save-excursion
11016 (beginning-of-line 1)
11017 (looking-at org-table-hline-regexp))
11018 nil))
11019
11020 (defun org-table-insert-column ()
11021 "Insert a new column into the table."
11022 (interactive)
11023 (if (not (org-at-table-p))
11024 (error "Not at a table"))
11025 (org-table-find-dataline)
11026 (let* ((col (max 1 (org-table-current-column)))
11027 (beg (org-table-begin))
11028 (end (org-table-end))
11029 ;; Current cursor position
11030 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11031 (colpos col))
11032 (goto-char beg)
11033 (while (< (point) end)
11034 (if (org-at-table-hline-p)
11035 nil
11036 (org-table-goto-column col t)
11037 (insert "| "))
11038 (beginning-of-line 2))
11039 (move-marker end nil)
11040 (goto-line linepos)
11041 (org-table-goto-column colpos)
11042 (org-table-align)
11043 (org-table-modify-formulas 'insert col)))
11044
11045 (defun org-table-find-dataline ()
11046 "Find a dataline in the current table, which is needed for column commands."
11047 (if (and (org-at-table-p)
11048 (not (org-at-table-hline-p)))
11049 t
11050 (let ((col (current-column))
11051 (end (org-table-end)))
11052 (move-to-column col)
11053 (while (and (< (point) end)
11054 (or (not (= (current-column) col))
11055 (org-at-table-hline-p)))
11056 (beginning-of-line 2)
11057 (move-to-column col))
11058 (if (and (org-at-table-p)
11059 (not (org-at-table-hline-p)))
11060 t
11061 (error
11062 "Please position cursor in a data line for column operations")))))
11063
11064 (defun org-table-delete-column ()
11065 "Delete a column from the table."
11066 (interactive)
11067 (if (not (org-at-table-p))
11068 (error "Not at a table"))
11069 (org-table-find-dataline)
11070 (org-table-check-inside-data-field)
11071 (let* ((col (org-table-current-column))
11072 (beg (org-table-begin))
11073 (end (org-table-end))
11074 ;; Current cursor position
11075 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11076 (colpos col))
11077 (goto-char beg)
11078 (while (< (point) end)
11079 (if (org-at-table-hline-p)
11080 nil
11081 (org-table-goto-column col t)
11082 (and (looking-at "|[^|\n]+|")
11083 (replace-match "|")))
11084 (beginning-of-line 2))
11085 (move-marker end nil)
11086 (goto-line linepos)
11087 (org-table-goto-column colpos)
11088 (org-table-align)
11089 (org-table-modify-formulas 'remove col)))
11090
11091 (defun org-table-move-column-right ()
11092 "Move column to the right."
11093 (interactive)
11094 (org-table-move-column nil))
11095 (defun org-table-move-column-left ()
11096 "Move column to the left."
11097 (interactive)
11098 (org-table-move-column 'left))
11099
11100 (defun org-table-move-column (&optional left)
11101 "Move the current column to the right. With arg LEFT, move to the left."
11102 (interactive "P")
11103 (if (not (org-at-table-p))
11104 (error "Not at a table"))
11105 (org-table-find-dataline)
11106 (org-table-check-inside-data-field)
11107 (let* ((col (org-table-current-column))
11108 (col1 (if left (1- col) col))
11109 (beg (org-table-begin))
11110 (end (org-table-end))
11111 ;; Current cursor position
11112 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11113 (colpos (if left (1- col) (1+ col))))
11114 (if (and left (= col 1))
11115 (error "Cannot move column further left"))
11116 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
11117 (error "Cannot move column further right"))
11118 (goto-char beg)
11119 (while (< (point) end)
11120 (if (org-at-table-hline-p)
11121 nil
11122 (org-table-goto-column col1 t)
11123 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
11124 (replace-match "|\\2|\\1|")))
11125 (beginning-of-line 2))
11126 (move-marker end nil)
11127 (goto-line linepos)
11128 (org-table-goto-column colpos)
11129 (org-table-align)
11130 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
11131
11132 (defun org-table-move-row-down ()
11133 "Move table row down."
11134 (interactive)
11135 (org-table-move-row nil))
11136 (defun org-table-move-row-up ()
11137 "Move table row up."
11138 (interactive)
11139 (org-table-move-row 'up))
11140
11141 (defun org-table-move-row (&optional up)
11142 "Move the current table line down. With arg UP, move it up."
11143 (interactive "P")
11144 (let ((col (current-column))
11145 (pos (point))
11146 (tonew (if up 0 2))
11147 txt)
11148 (beginning-of-line tonew)
11149 (if (not (org-at-table-p))
11150 (progn
11151 (goto-char pos)
11152 (error "Cannot move row further")))
11153 (goto-char pos)
11154 (beginning-of-line 1)
11155 (setq pos (point))
11156 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
11157 (delete-region (point) (1+ (point-at-eol)))
11158 (beginning-of-line tonew)
11159 (insert txt)
11160 (beginning-of-line 0)
11161 (move-to-column col)))
11162
11163 (defun org-table-insert-row (&optional arg)
11164 "Insert a new row above the current line into the table.
11165 With prefix ARG, insert below the current line."
11166 (interactive "P")
11167 (if (not (org-at-table-p))
11168 (error "Not at a table"))
11169 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
11170 (new (org-table-clean-line line)))
11171 ;; Fix the first field if necessary
11172 (if (string-match "^[ \t]*| *[#$] *|" line)
11173 (setq new (replace-match (match-string 0 line) t t new)))
11174 (beginning-of-line (if arg 2 1))
11175 (let (org-table-may-need-update) (insert-before-markers new "\n"))
11176 (beginning-of-line 0)
11177 (re-search-forward "| ?" (point-at-eol) t)
11178 (and org-table-may-need-update (org-table-align))))
11179
11180 (defun org-table-insert-hline (&optional arg)
11181 "Insert a horizontal-line below the current line into the table.
11182 With prefix ARG, insert above the current line."
11183 (interactive "P")
11184 (if (not (org-at-table-p))
11185 (error "Not at a table"))
11186 (let ((line (org-table-clean-line
11187 (buffer-substring (point-at-bol) (point-at-eol))))
11188 (col (current-column)))
11189 (while (string-match "|\\( +\\)|" line)
11190 (setq line (replace-match
11191 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
11192 ?-) "|") t t line)))
11193 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
11194 (beginning-of-line (if arg 1 2))
11195 (insert line "\n")
11196 (beginning-of-line (if arg 1 -1))
11197 (move-to-column col)))
11198
11199 (defun org-table-clean-line (s)
11200 "Convert a table line S into a string with only \"|\" and space.
11201 In particular, this does handle wide and invisible characters."
11202 (if (string-match "^[ \t]*|-" s)
11203 ;; It's a hline, just map the characters
11204 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
11205 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
11206 (setq s (replace-match
11207 (concat "|" (make-string (org-string-width (match-string 1 s))
11208 ?\ ) "|")
11209 t t s)))
11210 s))
11211
11212 (defun org-table-kill-row ()
11213 "Delete the current row or horizontal line from the table."
11214 (interactive)
11215 (if (not (org-at-table-p))
11216 (error "Not at a table"))
11217 (let ((col (current-column)))
11218 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
11219 (if (not (org-at-table-p)) (beginning-of-line 0))
11220 (move-to-column col)))
11221
11222 (defun org-table-sort-lines (beg end numericp)
11223 "Sort table lines in region.
11224 Point and mark define the first and last line to include. Both point and
11225 mark should be in the column that is used for sorting. For example, to
11226 sort according to column 3, put the mark in the first line to sort, in
11227 table column 3. Put point into the last line to be included in the sorting,
11228 also in table column 3. The command will prompt for the sorting method
11229 \(n for numerical, a for alphanumeric)."
11230 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
11231 (setq numericp (string-match "[nN]" numericp))
11232 (org-table-align) ;; Just to be safe
11233 (let* (bcol ecol cmp column lns)
11234 (goto-char beg)
11235 (org-table-check-inside-data-field)
11236 (setq column (org-table-current-column)
11237 beg (move-marker (make-marker) (point-at-bol)))
11238 (goto-char end)
11239 (org-table-check-inside-data-field)
11240 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
11241 (untabify beg end)
11242 (goto-char beg)
11243 (org-table-goto-column column)
11244 (skip-chars-backward "^|")
11245 (setq bcol (current-column))
11246 (org-table-goto-column (1+ column))
11247 (skip-chars-backward "^|")
11248 (setq ecol (1- (current-column)))
11249 (setq cmp (if numericp
11250 (lambda (a b) (< (car a) (car b)))
11251 (lambda (a b) (string< (car a) (car b)))))
11252 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
11253 (org-split-string (buffer-substring beg end) "\n")))
11254 (if numericp
11255 (setq lns (mapcar (lambda(x)
11256 (cons (string-to-number (car x)) (cdr x)))
11257 lns)))
11258 (delete-region beg end)
11259 (move-marker beg nil)
11260 (move-marker end nil)
11261 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
11262 (message "%d lines sorted %s based on column %d"
11263 (length lns)
11264 (if numericp "numerically" "alphabetically") column)))
11265
11266 (defun org-table-cut-region (beg end)
11267 "Copy region in table to the clipboard and blank all relevant fields."
11268 (interactive "r")
11269 (org-table-copy-region beg end 'cut))
11270
11271 (defun org-table-copy-region (beg end &optional cut)
11272 "Copy rectangular region in table to clipboard.
11273 A special clipboard is used which can only be accessed
11274 with `org-table-paste-rectangle'."
11275 (interactive "rP")
11276 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
11277 region cols
11278 (rpl (if cut " " nil)))
11279 (goto-char beg)
11280 (org-table-check-inside-data-field)
11281 (setq l01 (count-lines (point-min) (point))
11282 c01 (org-table-current-column))
11283 (goto-char end)
11284 (org-table-check-inside-data-field)
11285 (setq l02 (count-lines (point-min) (point))
11286 c02 (org-table-current-column))
11287 (setq l1 (min l01 l02) l2 (max l01 l02)
11288 c1 (min c01 c02) c2 (max c01 c02))
11289 (catch 'exit
11290 (while t
11291 (catch 'nextline
11292 (if (> l1 l2) (throw 'exit t))
11293 (goto-line l1)
11294 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
11295 (setq cols nil ic1 c1 ic2 c2)
11296 (while (< ic1 (1+ ic2))
11297 (push (org-table-get-field ic1 rpl) cols)
11298 (setq ic1 (1+ ic1)))
11299 (push (nreverse cols) region)
11300 (setq l1 (1+ l1)))))
11301 (setq org-table-clip (nreverse region))
11302 (if cut (org-table-align))
11303 org-table-clip))
11304
11305 (defun org-table-paste-rectangle ()
11306 "Paste a rectangular region into a table.
11307 The upper right corner ends up in the current field. All involved fields
11308 will be overwritten. If the rectangle does not fit into the present table,
11309 the table is enlarged as needed. The process ignores horizontal separator
11310 lines."
11311 (interactive)
11312 (unless (and org-table-clip (listp org-table-clip))
11313 (error "First cut/copy a region to paste!"))
11314 (org-table-check-inside-data-field)
11315 (let* ((clip org-table-clip)
11316 (line (count-lines (point-min) (point)))
11317 (col (org-table-current-column))
11318 (org-enable-table-editor t)
11319 (org-table-automatic-realign nil)
11320 c cols field)
11321 (while (setq cols (pop clip))
11322 (while (org-at-table-hline-p) (beginning-of-line 2))
11323 (if (not (org-at-table-p))
11324 (progn (end-of-line 0) (org-table-next-field)))
11325 (setq c col)
11326 (while (setq field (pop cols))
11327 (org-table-goto-column c nil 'force)
11328 (org-table-get-field nil field)
11329 (setq c (1+ c)))
11330 (beginning-of-line 2))
11331 (goto-line line)
11332 (org-table-goto-column col)
11333 (org-table-align)))
11334
11335 (defun org-table-convert ()
11336 "Convert from `org-mode' table to table.el and back.
11337 Obviously, this only works within limits. When an Org-mode table is
11338 converted to table.el, all horizontal separator lines get lost, because
11339 table.el uses these as cell boundaries and has no notion of horizontal lines.
11340 A table.el table can be converted to an Org-mode table only if it does not
11341 do row or column spanning. Multiline cells will become multiple cells.
11342 Beware, Org-mode does not test if the table can be successfully converted - it
11343 blindly applies a recipe that works for simple tables."
11344 (interactive)
11345 (require 'table)
11346 (if (org-at-table.el-p)
11347 ;; convert to Org-mode table
11348 (let ((beg (move-marker (make-marker) (org-table-begin t)))
11349 (end (move-marker (make-marker) (org-table-end t))))
11350 (table-unrecognize-region beg end)
11351 (goto-char beg)
11352 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
11353 (replace-match ""))
11354 (goto-char beg))
11355 (if (org-at-table-p)
11356 ;; convert to table.el table
11357 (let ((beg (move-marker (make-marker) (org-table-begin)))
11358 (end (move-marker (make-marker) (org-table-end))))
11359 ;; first, get rid of all horizontal lines
11360 (goto-char beg)
11361 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
11362 (replace-match ""))
11363 ;; insert a hline before first
11364 (goto-char beg)
11365 (org-table-insert-hline 'above)
11366 (beginning-of-line -1)
11367 ;; insert a hline after each line
11368 (while (progn (beginning-of-line 3) (< (point) end))
11369 (org-table-insert-hline))
11370 (goto-char beg)
11371 (setq end (move-marker end (org-table-end)))
11372 ;; replace "+" at beginning and ending of hlines
11373 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
11374 (replace-match "\\1+-"))
11375 (goto-char beg)
11376 (while (re-search-forward "-|[ \t]*$" end t)
11377 (replace-match "-+"))
11378 (goto-char beg)))))
11379
11380 (defun org-table-wrap-region (arg)
11381 "Wrap several fields in a column like a paragraph.
11382 This is useful if you'd like to spread the contents of a field over several
11383 lines, in order to keep the table compact.
11384
11385 If there is an active region, and both point and mark are in the same column,
11386 the text in the column is wrapped to minimum width for the given number of
11387 lines. Generally, this makes the table more compact. A prefix ARG may be
11388 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
11389 formats the selected text to two lines. If the region was longer than two
11390 lines, the remaining lines remain empty. A negative prefix argument reduces
11391 the current number of lines by that amount. The wrapped text is pasted back
11392 into the table. If you formatted it to more lines than it was before, fields
11393 further down in the table get overwritten - so you might need to make space in
11394 the table first.
11395
11396 If there is no region, the current field is split at the cursor position and
11397 the text fragment to the right of the cursor is prepended to the field one
11398 line down.
11399
11400 If there is no region, but you specify a prefix ARG, the current field gets
11401 blank, and the content is appended to the field above."
11402 (interactive "P")
11403 (org-table-check-inside-data-field)
11404 (if (org-region-active-p)
11405 ;; There is a region: fill as a paragraph
11406 (let ((beg (region-beginning))
11407 nlines)
11408 (org-table-cut-region (region-beginning) (region-end))
11409 (if (> (length (car org-table-clip)) 1)
11410 (error "Region must be limited to single column"))
11411 (setq nlines (if arg
11412 (if (< arg 1)
11413 (+ (length org-table-clip) arg)
11414 arg)
11415 (length org-table-clip)))
11416 (setq org-table-clip
11417 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
11418 nil nlines)))
11419 (goto-char beg)
11420 (org-table-paste-rectangle))
11421 ;; No region, split the current field at point
11422 (if arg
11423 ;; combine with field above
11424 (let ((s (org-table-blank-field))
11425 (col (org-table-current-column)))
11426 (beginning-of-line 0)
11427 (while (org-at-table-hline-p) (beginning-of-line 0))
11428 (org-table-goto-column col)
11429 (skip-chars-forward "^|")
11430 (skip-chars-backward " ")
11431 (insert " " (org-trim s))
11432 (org-table-align))
11433 ;; split field
11434 (when (looking-at "\\([^|]+\\)+|")
11435 (let ((s (match-string 1)))
11436 (replace-match " |")
11437 (goto-char (match-beginning 0))
11438 (org-table-next-row)
11439 (insert (org-trim s) " ")
11440 (org-table-align))))))
11441
11442 (defvar org-field-marker nil)
11443
11444 (defun org-table-edit-field (arg)
11445 "Edit table field in a different window.
11446 This is mainly useful for fields that contain hidden parts.
11447 When called with a \\[universal-argument] prefix, just make the full field visible so that
11448 it can be edited in place."
11449 (interactive "P")
11450 (if arg
11451 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
11452 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
11453 (remove-text-properties b e '(org-cwidth t invisible t
11454 display t intangible t))
11455 (if (and (boundp 'font-lock-mode) font-lock-mode)
11456 (font-lock-fontify-block)))
11457 (let ((pos (move-marker (make-marker) (point)))
11458 (field (org-table-get-field))
11459 (cw (current-window-configuration))
11460 p)
11461 (switch-to-buffer-other-window "*Org tmp*")
11462 (erase-buffer)
11463 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
11464 (org-mode)
11465 (goto-char (setq p (point-max)))
11466 (insert (org-trim field))
11467 (remove-text-properties p (point-max)
11468 '(invisible t org-cwidth t display t
11469 intangible t))
11470 (goto-char p)
11471 (set (make-local-variable 'org-finish-function)
11472 'org-table-finish-edit-field)
11473 (set (make-local-variable 'org-window-configuration) cw)
11474 (set (make-local-variable 'org-field-marker) pos)
11475 (message "Edit and finish with C-c C-c"))))
11476
11477 (defun org-table-finish-edit-field ()
11478 "Finish editing a table data field.
11479 Remove all newline characters, insert the result into the table, realign
11480 the table and kill the editing buffer."
11481 (let ((pos org-field-marker)
11482 (cw org-window-configuration)
11483 (cb (current-buffer))
11484 text)
11485 (goto-char (point-min))
11486 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
11487 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
11488 (replace-match " "))
11489 (setq text (org-trim (buffer-string)))
11490 (set-window-configuration cw)
11491 (kill-buffer cb)
11492 (select-window (get-buffer-window (marker-buffer pos)))
11493 (goto-char pos)
11494 (move-marker pos nil)
11495 (org-table-check-inside-data-field)
11496 (org-table-get-field nil text)
11497 (org-table-align)
11498 (message "New field value inserted")))
11499
11500 (defun org-trim (s)
11501 "Remove whitespace at beginning and end of string."
11502 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
11503 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
11504 s)
11505
11506 (defun org-wrap (string &optional width lines)
11507 "Wrap string to either a number of lines, or a width in characters.
11508 If WIDTH is non-nil, the string is wrapped to that width, however many lines
11509 that costs. If there is a word longer than WIDTH, the text is actually
11510 wrapped to the length of that word.
11511 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
11512 many lines, whatever width that takes.
11513 The return value is a list of lines, without newlines at the end."
11514 (let* ((words (org-split-string string "[ \t\n]+"))
11515 (maxword (apply 'max (mapcar 'org-string-width words)))
11516 w ll)
11517 (cond (width
11518 (org-do-wrap words (max maxword width)))
11519 (lines
11520 (setq w maxword)
11521 (setq ll (org-do-wrap words maxword))
11522 (if (<= (length ll) lines)
11523 ll
11524 (setq ll words)
11525 (while (> (length ll) lines)
11526 (setq w (1+ w))
11527 (setq ll (org-do-wrap words w)))
11528 ll))
11529 (t (error "Cannot wrap this")))))
11530
11531
11532 (defun org-do-wrap (words width)
11533 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
11534 (let (lines line)
11535 (while words
11536 (setq line (pop words))
11537 (while (and words (< (+ (length line) (length (car words))) width))
11538 (setq line (concat line " " (pop words))))
11539 (setq lines (push line lines)))
11540 (nreverse lines)))
11541
11542 (defun org-split-string (string &optional separators)
11543 "Splits STRING into substrings at SEPARATORS.
11544 No empty strings are returned if there are matches at the beginning
11545 and end of string."
11546 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
11547 (start 0)
11548 notfirst
11549 (list nil))
11550 (while (and (string-match rexp string
11551 (if (and notfirst
11552 (= start (match-beginning 0))
11553 (< start (length string)))
11554 (1+ start) start))
11555 (< (match-beginning 0) (length string)))
11556 (setq notfirst t)
11557 (or (eq (match-beginning 0) 0)
11558 (and (eq (match-beginning 0) (match-end 0))
11559 (eq (match-beginning 0) start))
11560 (setq list
11561 (cons (substring string start (match-beginning 0))
11562 list)))
11563 (setq start (match-end 0)))
11564 (or (eq start (length string))
11565 (setq list
11566 (cons (substring string start)
11567 list)))
11568 (nreverse list)))
11569
11570 (defun org-table-map-tables (function)
11571 "Apply FUNCTION to the start of all tables in the buffer."
11572 (save-excursion
11573 (save-restriction
11574 (widen)
11575 (goto-char (point-min))
11576 (while (re-search-forward org-table-any-line-regexp nil t)
11577 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
11578 (beginning-of-line 1)
11579 (if (looking-at org-table-line-regexp)
11580 (save-excursion (funcall function)))
11581 (re-search-forward org-table-any-border-regexp nil 1))))
11582 (message "Mapping tables: done"))
11583
11584 (defun org-table-sum (&optional beg end nlast)
11585 "Sum numbers in region of current table column.
11586 The result will be displayed in the echo area, and will be available
11587 as kill to be inserted with \\[yank].
11588
11589 If there is an active region, it is interpreted as a rectangle and all
11590 numbers in that rectangle will be summed. If there is no active
11591 region and point is located in a table column, sum all numbers in that
11592 column.
11593
11594 If at least one number looks like a time HH:MM or HH:MM:SS, all other
11595 numbers are assumed to be times as well (in decimal hours) and the
11596 numbers are added as such.
11597
11598 If NLAST is a number, only the NLAST fields will actually be summed."
11599 (interactive)
11600 (save-excursion
11601 (let (col (timecnt 0) diff h m s org-table-clip)
11602 (cond
11603 ((and beg end)) ; beg and end given explicitly
11604 ((org-region-active-p)
11605 (setq beg (region-beginning) end (region-end)))
11606 (t
11607 (setq col (org-table-current-column))
11608 (goto-char (org-table-begin))
11609 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
11610 (error "No table data"))
11611 (org-table-goto-column col)
11612 ;not needed? (skip-chars-backward "^|")
11613 (setq beg (point))
11614 (goto-char (org-table-end))
11615 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
11616 (error "No table data"))
11617 (org-table-goto-column col)
11618 ;not needed? (skip-chars-forward "^|")
11619 (setq end (point))))
11620 (let* ((items (apply 'append (org-table-copy-region beg end)))
11621 (items1 (cond ((not nlast) items)
11622 ((>= nlast (length items)) items)
11623 (t (setq items (reverse items))
11624 (setcdr (nthcdr (1- nlast) items) nil)
11625 (nreverse items))))
11626 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
11627 items1)))
11628 (res (apply '+ numbers))
11629 (sres (if (= timecnt 0)
11630 (format "%g" res)
11631 (setq diff (* 3600 res)
11632 h (floor (/ diff 3600)) diff (mod diff 3600)
11633 m (floor (/ diff 60)) diff (mod diff 60)
11634 s diff)
11635 (format "%d:%02d:%02d" h m s))))
11636 (kill-new sres)
11637 (if (interactive-p)
11638 (message "%s"
11639 (substitute-command-keys
11640 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
11641 (length numbers) sres))))
11642 sres))))
11643
11644 (defun org-table-get-number-for-summing (s)
11645 (let (n)
11646 (if (string-match "^ *|? *" s)
11647 (setq s (replace-match "" nil nil s)))
11648 (if (string-match " *|? *$" s)
11649 (setq s (replace-match "" nil nil s)))
11650 (setq n (string-to-number s))
11651 (cond
11652 ((and (string-match "0" s)
11653 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
11654 ((string-match "\\`[ \t]+\\'" s) nil)
11655 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
11656 (let ((h (string-to-number (or (match-string 1 s) "0")))
11657 (m (string-to-number (or (match-string 2 s) "0")))
11658 (s (string-to-number (or (match-string 4 s) "0"))))
11659 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
11660 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
11661 ((equal n 0) nil)
11662 (t n))))
11663
11664 (defun org-table-get-vertical-vector (desc &optional tbeg col)
11665 "Get a calc vector from a column, accorting to descriptor DESC.
11666 Optional arguments TBEG and COL can give the beginning of the table and
11667 the current column, to avoid unnecessary parsing."
11668 (save-excursion
11669 (or tbeg (setq tbeg (org-table-begin)))
11670 (or col (setq col (org-table-current-column)))
11671 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
11672 (cond
11673 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
11674 (setq n1 (- (match-end 1) (match-beginning 1)))
11675 (if (match-beginning 3)
11676 (setq n2 (- (match-end 2) (match-beginning 3))))
11677 (setq n (if n2 (max n1 n2) n1))
11678 (setq n1 (if n2 (min n1 n2)))
11679 (setq nn n)
11680 (while (and (> nn 0)
11681 (re-search-backward org-table-hline-regexp tbeg t))
11682 (push (org-current-line) hline-list)
11683 (setq nn (1- nn)))
11684 (setq hline-list (nreverse hline-list))
11685 (goto-line (nth (1- n) hline-list))
11686 (when (re-search-forward org-table-dataline-regexp)
11687 (org-table-goto-column col)
11688 (setq beg (point)))
11689 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
11690 (when (re-search-backward org-table-dataline-regexp)
11691 (org-table-goto-column col)
11692 (setq end (point)))
11693 (setq l (apply 'append (org-table-copy-region beg end)))
11694 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
11695 (if (equal x "") "0" x))
11696 l ",") "]"))
11697 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
11698 (setq n1 (string-to-number (match-string 1 desc))
11699 n2 (string-to-number (match-string 2 desc)))
11700 (beginning-of-line 1)
11701 (save-excursion
11702 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
11703 (org-table-goto-column col)
11704 (setq beg (point))))
11705 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
11706 (org-table-goto-column col)
11707 (setq end (point)))
11708 (setq l (apply 'append (org-table-copy-region beg end)))
11709 (concat "[" (mapconcat
11710 (lambda (x) (setq x (org-trim x))
11711 (if (equal x "") "0" x))
11712 l ",") "]"))
11713 ((string-match "\\([0-9]+\\)" desc)
11714 (beginning-of-line 1)
11715 (when (re-search-backward org-table-dataline-regexp tbeg t
11716 (string-to-number (match-string 0 desc)))
11717 (org-table-goto-column col)
11718 (org-trim (org-table-get-field))))))))
11719
11720 (defvar org-table-formula-history nil)
11721
11722 (defvar org-table-column-names nil
11723 "Alist with column names, derived from the `!' line.")
11724 (defvar org-table-column-name-regexp nil
11725 "Regular expression matching the current column names.")
11726 (defvar org-table-local-parameters nil
11727 "Alist with parameter names, derived from the `$' line.")
11728 (defvar org-table-named-field-locations nil
11729 "Alist with locations of named fields.")
11730
11731 (defun org-table-get-formula (&optional equation named)
11732 "Read a formula from the minibuffer, offer stored formula as default."
11733 (let* ((name (car (rassoc (list (org-current-line)
11734 (org-table-current-column))
11735 org-table-named-field-locations)))
11736 (scol (if named
11737 (if name name
11738 (error "Not in a named field"))
11739 (int-to-string (org-table-current-column))))
11740 (dummy (and name (not named)
11741 (not (y-or-n-p "Replace named-field formula with column equation? " ))
11742 (error "Abort")))
11743 (org-table-may-need-update nil)
11744 (stored-list (org-table-get-stored-formulas))
11745 (stored (cdr (assoc scol stored-list)))
11746 (eq (cond
11747 ((and stored equation (string-match "^ *=? *$" equation))
11748 stored)
11749 ((stringp equation)
11750 equation)
11751 (t (read-string
11752 (format "%s formula $%s=" (if named "Field" "Column") scol)
11753 (or stored "") 'org-table-formula-history
11754 ;stored
11755 ))))
11756 mustsave)
11757 (when (not (string-match "\\S-" eq))
11758 ;; remove formula
11759 (setq stored-list (delq (assoc scol stored-list) stored-list))
11760 (org-table-store-formulas stored-list)
11761 (error "Formula removed"))
11762 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
11763 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
11764 (if (and name (not named))
11765 ;; We set the column equation, delete the named one.
11766 (setq stored-list (delq (assoc name stored-list) stored-list)
11767 mustsave t))
11768 (if stored
11769 (setcdr (assoc scol stored-list) eq)
11770 (setq stored-list (cons (cons scol eq) stored-list)))
11771 (if (or mustsave (not (equal stored eq)))
11772 (org-table-store-formulas stored-list))
11773 eq))
11774
11775 (defun org-table-store-formulas (alist)
11776 "Store the list of formulas below the current table."
11777 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
11778 (save-excursion
11779 (goto-char (org-table-end))
11780 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
11781 (delete-region (point) (match-end 0)))
11782 (insert "#+TBLFM: "
11783 (mapconcat (lambda (x)
11784 (concat "$" (car x) "=" (cdr x)))
11785 alist "::")
11786 "\n")))
11787
11788 (defun org-table-get-stored-formulas ()
11789 "Return an alist with the stored formulas directly after current table."
11790 (interactive)
11791 (let (scol eq eq-alist strings string seen)
11792 (save-excursion
11793 (goto-char (org-table-end))
11794 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
11795 (setq strings (org-split-string (match-string 2) " *:: *"))
11796 (while (setq string (pop strings))
11797 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
11798 (setq scol (match-string 1 string)
11799 eq (match-string 2 string)
11800 eq-alist (cons (cons scol eq) eq-alist))
11801 (if (member scol seen)
11802 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
11803 (push scol seen))))))
11804 (nreverse eq-alist)))
11805
11806 (defun org-table-modify-formulas (action &rest columns)
11807 "Modify the formulas stored below the current table.
11808 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
11809 expected, for the other actions only a single column number is needed."
11810 (let ((list (org-table-get-stored-formulas))
11811 (nmax (length (org-split-string
11812 (buffer-substring (point-at-bol) (point-at-eol))
11813 "|")))
11814 col col1 col2 scol si sc1 sc2)
11815 (cond
11816 ((null list)) ; No action needed if there are no stored formulas
11817 ((eq action 'remove)
11818 (setq col (car columns)
11819 scol (int-to-string col))
11820 (org-table-replace-in-formulas list scol "INVALID")
11821 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
11822 (loop for i from (1+ col) upto nmax by 1 do
11823 (setq si (int-to-string i))
11824 (org-table-replace-in-formulas list si (int-to-string (1- i)))
11825 (if (assoc si list) (setcar (assoc si list)
11826 (int-to-string (1- i))))))
11827 ((eq action 'insert)
11828 (setq col (car columns))
11829 (loop for i from nmax downto col by 1 do
11830 (setq si (int-to-string i))
11831 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
11832 (if (assoc si list) (setcar (assoc si list)
11833 (int-to-string (1+ i))))))
11834 ((eq action 'swap)
11835 (setq col1 (car columns) col2 (nth 1 columns)
11836 sc1 (int-to-string col1) sc2 (int-to-string col2))
11837 ;; Hopefully, ZqZtZ will never be a name in a table
11838 (org-table-replace-in-formulas list sc1 "ZqZtZ")
11839 (org-table-replace-in-formulas list sc2 sc1)
11840 (org-table-replace-in-formulas list "ZqZtZ" sc2)
11841 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
11842 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
11843 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
11844 (t (error "Invalid action in `org-table-modify-formulas'")))
11845 (if list (org-table-store-formulas list))))
11846
11847 (defun org-table-replace-in-formulas (list s1 s2)
11848 (let (elt re s)
11849 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
11850 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
11851 re (concat (regexp-quote s1) "\\>"))
11852 (while (setq elt (pop list))
11853 (setq s (cdr elt))
11854 (while (string-match re s)
11855 (setq s (replace-match s2 t t s)))
11856 (setcdr elt s))))
11857
11858 (defun org-table-get-specials ()
11859 "Get the column names and local parameters for this table."
11860 (save-excursion
11861 (let ((beg (org-table-begin)) (end (org-table-end))
11862 names name fields fields1 field cnt c v line col)
11863 (setq org-table-column-names nil
11864 org-table-local-parameters nil
11865 org-table-named-field-locations nil)
11866 (goto-char beg)
11867 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
11868 (setq names (org-split-string (match-string 1) " *| *")
11869 cnt 1)
11870 (while (setq name (pop names))
11871 (setq cnt (1+ cnt))
11872 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
11873 (push (cons name (int-to-string cnt)) org-table-column-names))))
11874 (setq org-table-column-names (nreverse org-table-column-names))
11875 (setq org-table-column-name-regexp
11876 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
11877 (goto-char beg)
11878 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
11879 (setq fields (org-split-string (match-string 1) " *| *"))
11880 (while (setq field (pop fields))
11881 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
11882 (push (cons (match-string 1 field) (match-string 2 field))
11883 org-table-local-parameters))))
11884 (goto-char beg)
11885 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
11886 (setq c (match-string 1)
11887 fields (org-split-string (match-string 2) " *| *"))
11888 (save-excursion
11889 (beginning-of-line (if (equal c "_") 2 0))
11890 (setq line (org-current-line) col 1)
11891 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
11892 (setq fields1 (org-split-string (match-string 1) " *| *"))))
11893 (while (and fields1 (setq field (pop fields)))
11894 (setq v (pop fields1) col (1+ col))
11895 (when (and (stringp field) (stringp v)
11896 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
11897 (push (cons field v) org-table-local-parameters)
11898 (push (list field line col) org-table-named-field-locations)))))))
11899
11900 (defun org-this-word ()
11901 ;; Get the current word
11902 (save-excursion
11903 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
11904 (end (progn (skip-chars-forward "^ \t\n") (point))))
11905 (buffer-substring-no-properties beg end))))
11906
11907 (defun org-table-maybe-eval-formula ()
11908 "Check if the current field starts with \"=\" or \":=\".
11909 If yes, store the formula and apply it."
11910 ;; We already know we are in a table. Get field will only return a formula
11911 ;; when appropriate. It might return a separator line, but no problem.
11912 (when org-table-formula-evaluate-inline
11913 (let* ((field (org-trim (or (org-table-get-field) "")))
11914 named eq)
11915 (when (string-match "^:?=\\(.*\\)" field)
11916 (setq named (equal (string-to-char field) ?:)
11917 eq (match-string 1 field))
11918 (if (fboundp 'calc-eval)
11919 (org-table-eval-formula (if named '(4) nil) eq))))))
11920
11921 (defvar org-recalc-commands nil
11922 "List of commands triggering the recalculation of a line.
11923 Will be filled automatically during use.")
11924
11925 (defvar org-recalc-marks
11926 '((" " . "Unmarked: no special line, no automatic recalculation")
11927 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
11928 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
11929 ("!" . "Column name definition line. Reference in formula as $name.")
11930 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
11931 ("_" . "Names for values in row below this one.")
11932 ("^" . "Names for values in row above this one.")))
11933
11934 (defun org-table-rotate-recalc-marks (&optional newchar)
11935 "Rotate the recalculation mark in the first column.
11936 If in any row, the first field is not consistent with a mark,
11937 insert a new column for the markers.
11938 When there is an active region, change all the lines in the region,
11939 after prompting for the marking character.
11940 After each change, a message will be displayed indicating the meaning
11941 of the new mark."
11942 (interactive)
11943 (unless (org-at-table-p) (error "Not at a table"))
11944 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
11945 (beg (org-table-begin))
11946 (end (org-table-end))
11947 (l (org-current-line))
11948 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
11949 (l2 (if (org-region-active-p) (org-current-line (region-end))))
11950 (have-col
11951 (save-excursion
11952 (goto-char beg)
11953 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
11954 (col (org-table-current-column))
11955 (forcenew (car (assoc newchar org-recalc-marks)))
11956 epos new)
11957 (when l1
11958 (message "Change region to what mark? Type # * ! $ or SPC: ")
11959 (setq newchar (char-to-string (read-char-exclusive))
11960 forcenew (car (assoc newchar org-recalc-marks))))
11961 (if (and newchar (not forcenew))
11962 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
11963 newchar))
11964 (if l1 (goto-line l1))
11965 (save-excursion
11966 (beginning-of-line 1)
11967 (unless (looking-at org-table-dataline-regexp)
11968 (error "Not at a table data line")))
11969 (unless have-col
11970 (org-table-goto-column 1)
11971 (org-table-insert-column)
11972 (org-table-goto-column (1+ col)))
11973 (setq epos (point-at-eol))
11974 (save-excursion
11975 (beginning-of-line 1)
11976 (org-table-get-field
11977 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
11978 (concat " "
11979 (setq new (or forcenew
11980 (cadr (member (match-string 1) marks))))
11981 " ")
11982 " # ")))
11983 (if (and l1 l2)
11984 (progn
11985 (goto-line l1)
11986 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
11987 (and (looking-at org-table-dataline-regexp)
11988 (org-table-get-field 1 (concat " " new " "))))
11989 (goto-line l1)))
11990 (if (not (= epos (point-at-eol))) (org-table-align))
11991 (goto-line l)
11992 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
11993
11994 (defun org-table-maybe-recalculate-line ()
11995 "Recompute the current line if marked for it, and if we haven't just done it."
11996 (interactive)
11997 (and org-table-allow-automatic-line-recalculation
11998 (not (and (memq last-command org-recalc-commands)
11999 (equal org-last-recalc-line (org-current-line))))
12000 (save-excursion (beginning-of-line 1)
12001 (looking-at org-table-auto-recalculate-regexp))
12002 (fboundp 'calc-eval)
12003 (org-table-recalculate) t))
12004
12005 (defvar org-table-formula-debug nil
12006 "Non-nil means, debug table formulas.
12007 When nil, simply write \"#ERROR\" in corrupted fields.")
12008
12009 (defvar modes)
12010 (defsubst org-set-calc-mode (var &optional value)
12011 (if (stringp var)
12012 (setq var (assoc var '(("D" calc-angle-mode deg)
12013 ("R" calc-angle-mode rad)
12014 ("F" calc-prefer-frac t)
12015 ("S" calc-symbolic-mode t)))
12016 value (nth 2 var) var (nth 1 var)))
12017 (if (memq var modes)
12018 (setcar (cdr (memq var modes)) value)
12019 (cons var (cons value modes)))
12020 modes)
12021
12022 (defun org-table-eval-formula (&optional arg equation
12023 suppress-align suppress-const
12024 suppress-store)
12025 "Replace the table field value at the cursor by the result of a calculation.
12026
12027 This function makes use of Dave Gillespie's Calc package, in my view the
12028 most exciting program ever written for GNU Emacs. So you need to have Calc
12029 installed in order to use this function.
12030
12031 In a table, this command replaces the value in the current field with the
12032 result of a formula. It also installs the formula as the \"current\" column
12033 formula, by storing it in a special line below the table. When called
12034 with a `C-u' prefix, the current field must ba a named field, and the
12035 formula is installed as valid in only this specific field.
12036
12037 When called, the command first prompts for a formula, which is read in
12038 the minibuffer. Previously entered formulas are available through the
12039 history list, and the last used formula is offered as a default.
12040 These stored formulas are adapted correctly when moving, inserting, or
12041 deleting columns with the corresponding commands.
12042
12043 The formula can be any algebraic expression understood by the Calc package.
12044 For details, see the Org-mode manual.
12045
12046 This function can also be called from Lisp programs and offers
12047 additional arguments: EQUATION can be the formula to apply. If this
12048 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
12049 used to speed-up recursive calls by by-passing unnecessary aligns.
12050 SUPPRESS-CONST suppresses the interpretation of constants in the
12051 formula, assuming that this has been done already outside the function.
12052 SUPPRESS-STORE means the formula should not be stored, either because
12053 it is already stored, or because it is a modified equation that should
12054 not overwrite the stored one."
12055 (interactive "P")
12056 (require 'calc)
12057 (org-table-check-inside-data-field)
12058 (org-table-get-specials)
12059 (let* (fields
12060 (ndown (if (integerp arg) arg 1))
12061 (org-table-automatic-realign nil)
12062 (case-fold-search nil)
12063 (down (> ndown 1))
12064 (formula (if (and equation suppress-store)
12065 equation
12066 (org-table-get-formula equation (equal arg '(4)))))
12067 (n0 (org-table-current-column))
12068 (modes (copy-sequence org-calc-default-modes))
12069 n form fmt x ev orig c lispp)
12070 ;; Parse the format string. Since we have a lot of modes, this is
12071 ;; a lot of work. However, I think calc still uses most of the time.
12072 (if (string-match ";" formula)
12073 (let ((tmp (org-split-string formula ";")))
12074 (setq formula (car tmp)
12075 fmt (concat (cdr (assoc "%" org-table-local-parameters))
12076 (nth 1 tmp)))
12077 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
12078 (setq c (string-to-char (match-string 1 fmt))
12079 n (string-to-number (or (match-string 1 fmt) "")))
12080 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
12081 (setq modes (org-set-calc-mode
12082 'calc-float-format
12083 (list (cdr (assoc c '((?n . float) (?f . fix)
12084 (?s . sci) (?e . eng))))
12085 n))))
12086 (setq fmt (replace-match "" t t fmt)))
12087 (while (string-match "[DRFS]" fmt)
12088 (setq modes (org-set-calc-mode (match-string 0 fmt)))
12089 (setq fmt (replace-match "" t t fmt)))
12090 (unless (string-match "\\S-" fmt)
12091 (setq fmt nil))))
12092 (if (and (not suppress-const) org-table-formula-use-constants)
12093 (setq formula (org-table-formula-substitute-names formula)))
12094 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
12095 (while (> ndown 0)
12096 (setq fields (org-split-string
12097 (buffer-substring
12098 (point-at-bol) (point-at-eol)) " *| *"))
12099 (if org-table-formula-numbers-only
12100 (setq fields (mapcar
12101 (lambda (x) (number-to-string (string-to-number x)))
12102 fields)))
12103 (setq ndown (1- ndown))
12104 (setq form (copy-sequence formula)
12105 lispp (equal (substring form 0 2) "'("))
12106 ;; Insert the references to fields in same row
12107 (while (string-match "\\$\\([0-9]+\\)?" form)
12108 (setq n (if (match-beginning 1)
12109 (string-to-number (match-string 1 form))
12110 n0)
12111 x (nth (1- n) fields))
12112 (unless x (error "Invalid field specifier \"%s\""
12113 (match-string 0 form)))
12114 (if (equal x "") (setq x "0"))
12115 (setq form (replace-match
12116 (if lispp x (concat "(" x ")"))
12117 t t form)))
12118 ;; Insert ranges in current column
12119 (while (string-match "\\&[-I0-9]+" form)
12120 (setq form (replace-match
12121 (save-match-data
12122 (org-table-get-vertical-vector (match-string 0 form)
12123 nil n0))
12124 t t form)))
12125 (if lispp
12126 (setq ev (eval (eval (read form)))
12127 ev (if (numberp ev) (number-to-string ev) ev))
12128 (setq ev (calc-eval (cons form modes)
12129 (if org-table-formula-numbers-only 'num))))
12130
12131 (when org-table-formula-debug
12132 (with-output-to-temp-buffer "*Help*"
12133 (princ (format "Substitution history of formula
12134 Orig: %s
12135 $xyz-> %s
12136 $1-> %s\n" orig formula form))
12137 (if (listp ev)
12138 (princ (format " %s^\nError: %s"
12139 (make-string (car ev) ?\-) (nth 1 ev)))
12140 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
12141 ev (or fmt "NONE")
12142 (if fmt (format fmt (string-to-number ev)) ev)))))
12143 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
12144 (unless (and (interactive-p) (not ndown))
12145 (unless (let (inhibit-redisplay)
12146 (y-or-n-p "Debugging Formula. Continue to next? "))
12147 (org-table-align)
12148 (error "Abort"))
12149 (delete-window (get-buffer-window "*Help*"))
12150 (message "")))
12151 (if (listp ev) (setq fmt nil ev "#ERROR"))
12152 (org-table-justify-field-maybe
12153 (if fmt (format fmt (string-to-number ev)) ev))
12154 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
12155 (call-interactively 'org-return)
12156 (setq ndown 0)))
12157 (and down (org-table-maybe-recalculate-line))
12158 (or suppress-align (and org-table-may-need-update
12159 (org-table-align)))))
12160
12161 (defun org-table-recalculate (&optional all noalign)
12162 "Recalculate the current table line by applying all stored formulas.
12163 With prefix arg ALL, do this for all lines in the table."
12164 (interactive "P")
12165 (or (memq this-command org-recalc-commands)
12166 (setq org-recalc-commands (cons this-command org-recalc-commands)))
12167 (unless (org-at-table-p) (error "Not at a table"))
12168 (org-table-get-specials)
12169 (let* ((eqlist (sort (org-table-get-stored-formulas)
12170 (lambda (a b) (string< (car a) (car b)))))
12171 (inhibit-redisplay t)
12172 (line-re org-table-dataline-regexp)
12173 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
12174 (thiscol (org-table-current-column))
12175 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
12176 ;; Insert constants in all formulas
12177 (setq eqlist
12178 (mapcar (lambda (x)
12179 (setcdr x (org-table-formula-substitute-names (cdr x)))
12180 x)
12181 eqlist))
12182 ;; Split the equation list
12183 (while (setq eq (pop eqlist))
12184 (if (<= (string-to-char (car eq)) ?9)
12185 (push eq eqlnum)
12186 (push eq eqlname)))
12187 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
12188 (if all
12189 (progn
12190 (setq end (move-marker (make-marker) (1+ (org-table-end))))
12191 (goto-char (setq beg (org-table-begin)))
12192 (if (re-search-forward org-table-calculate-mark-regexp end t)
12193 ;; This is a table with marked lines, only compute selected lines
12194 (setq line-re org-table-recalculate-regexp)
12195 ;; Move forward to the first non-header line
12196 (if (and (re-search-forward org-table-dataline-regexp end t)
12197 (re-search-forward org-table-hline-regexp end t)
12198 (re-search-forward org-table-dataline-regexp end t))
12199 (setq beg (match-beginning 0))
12200 nil))) ;; just leave beg where it is
12201 (setq beg (point-at-bol)
12202 end (move-marker (make-marker) (1+ (point-at-eol)))))
12203 (goto-char beg)
12204 (and all (message "Re-applying formulas to full table..."))
12205 (while (re-search-forward line-re end t)
12206 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
12207 ;; Unprotected line, recalculate
12208 (and all (message "Re-applying formulas to full table...(line %d)"
12209 (setq cnt (1+ cnt))))
12210 (setq org-last-recalc-line (org-current-line))
12211 (setq eql eqlnum)
12212 (while (setq entry (pop eql))
12213 (goto-line org-last-recalc-line)
12214 (org-table-goto-column (string-to-number (car entry)) nil 'force)
12215 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
12216 (goto-line thisline)
12217 (org-table-goto-column thiscol)
12218 (or noalign (and org-table-may-need-update (org-table-align))
12219 (and all (message "Re-applying formulas to %d lines...done" cnt)))
12220 ;; Now do the names fields
12221 (while (setq eq (pop eqlname))
12222 (setq name (car eq)
12223 a (assoc name org-table-named-field-locations))
12224 (when a
12225 (message "Re-applying formula to named field: %s" name)
12226 (goto-line (nth 1 a))
12227 (org-table-goto-column (nth 2 a))
12228 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
12229 ;; back to initial position
12230 (goto-line thisline)
12231 (org-table-goto-column thiscol)
12232 (or noalign (and org-table-may-need-update (org-table-align))
12233 (and all (message "Re-applying formulas...done")))))
12234
12235 (defun org-table-formula-substitute-names (f)
12236 "Replace $const with values in string F."
12237 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
12238 ;; First, check for column names
12239 (while (setq start (string-match org-table-column-name-regexp f start))
12240 (setq start (1+ start))
12241 (setq a (assoc (match-string 1 f) org-table-column-names))
12242 (setq f (replace-match (concat "$" (cdr a)) t t f)))
12243 ;; Expand ranges to vectors
12244 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
12245 (setq n1 (string-to-number (match-string 1 f))
12246 n2 (string-to-number (match-string 2 f))
12247 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
12248 s (concat "[($" (number-to-string (1- nn1)) ")"))
12249 (loop for i from nn1 upto nn2 do
12250 (setq s (concat s ",($" (int-to-string i) ")")))
12251 (setq s (concat s "]"))
12252 (if (< n2 n1) (setq s (concat "rev(" s ")")))
12253 (setq f (replace-match s t t f)))
12254 ;; Parameters and constants
12255 (setq start 0)
12256 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
12257 (setq start (1+ start))
12258 (if (setq a (save-match-data
12259 (org-table-get-constant (match-string 1 f))))
12260 (setq f (replace-match (concat "(" a ")") t t f))))
12261 (if org-table-formula-debug
12262 (put-text-property 0 (length f) :orig-formula f1 f))
12263 f))
12264
12265 (defun org-table-get-constant (const)
12266 "Find the value for a parameter or constant in a formula.
12267 Parameters get priority."
12268 (or (cdr (assoc const org-table-local-parameters))
12269 (cdr (assoc const org-table-formula-constants))
12270 (and (fboundp 'constants-get) (constants-get const))
12271 "#UNDEFINED_NAME"))
12272
12273 (defvar org-edit-formulas-map (make-sparse-keymap))
12274 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
12275 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
12276 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
12277
12278 (defvar org-pos)
12279
12280 (defun org-table-edit-formulas ()
12281 "Edit the formulas of the current table in a separate buffer."
12282 (interactive)
12283 (unless (org-at-table-p)
12284 (error "Not at a table"))
12285 (org-table-get-specials)
12286 (let ((eql (org-table-get-stored-formulas))
12287 (pos (move-marker (make-marker) (point)))
12288 (wc (current-window-configuration))
12289 entry loc s)
12290 (switch-to-buffer-other-window "*Edit Formulas*")
12291 (erase-buffer)
12292 (fundamental-mode)
12293 (set (make-local-variable 'org-pos) pos)
12294 (set (make-local-variable 'org-window-configuration) wc)
12295 (use-local-map org-edit-formulas-map)
12296 (setq s "# Edit formulas and finish with `C-c C-c'.
12297 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
12298 # Use `C-c ?' to get information about $name at point.
12299 # To cancel editing, press `C-c C-q'.\n")
12300 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12301 (insert s)
12302 (while (setq entry (pop eql))
12303 (when (setq loc (assoc (car entry) org-table-named-field-locations))
12304 (setq s (format "# Named formula, referring to column %d in line %d\n"
12305 (nth 2 loc) (nth 1 loc)))
12306 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12307 (insert s))
12308 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
12309 (remove-text-properties 0 (length s) '(face nil) s)
12310 (insert s))
12311 (goto-char (point-min))
12312 (message "Edit formulas and finish with `C-c C-c'.")))
12313
12314 (defun org-show-variable ()
12315 "Show the location/value of the $ expression at point."
12316 (interactive)
12317 (let (var (pos org-pos) (win (selected-window)) e)
12318 (save-excursion
12319 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
12320 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
12321 (setq var (match-string 1))
12322 (error "No variable at point")))
12323 (cond
12324 ((setq e (assoc var org-table-named-field-locations))
12325 (switch-to-buffer-other-window (marker-buffer pos))
12326 (goto-line (nth 1 e))
12327 (org-table-goto-column (nth 2 e))
12328 (select-window win)
12329 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
12330 ((setq e (assoc var org-table-column-names))
12331 (switch-to-buffer-other-window (marker-buffer pos))
12332 (goto-char pos)
12333 (goto-char (org-table-begin))
12334 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
12335 (org-table-end) t)
12336 (progn
12337 (goto-char (match-beginning 1))
12338 (message "Named column (column %s)" (cdr e)))
12339 (error "Column name not found"))
12340 (select-window win))
12341 ((string-match "^[0-9]$" var)
12342 ;; column number
12343 (switch-to-buffer-other-window (marker-buffer pos))
12344 (goto-char pos)
12345 (goto-char (org-table-begin))
12346 (recenter 1)
12347 (if (re-search-forward org-table-dataline-regexp
12348 (org-table-end) t)
12349 (progn
12350 (goto-char (match-beginning 0))
12351 (org-table-goto-column (string-to-number var))
12352 (message "Column %s" var))
12353 (error "Column name not found"))
12354 (select-window win))
12355 ((setq e (assoc var org-table-local-parameters))
12356 (switch-to-buffer-other-window (marker-buffer pos))
12357 (goto-char pos)
12358 (goto-char (org-table-begin))
12359 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
12360 (progn
12361 (goto-char (match-beginning 1))
12362 (message "Local parameter."))
12363 (error "Parameter not found"))
12364 (select-window win))
12365 (t
12366 (cond
12367 ((setq e (assoc var org-table-formula-constants))
12368 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
12369 ((setq e (and (fboundp 'constants-get) (constants-get var)))
12370 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
12371 (t (error "Undefined name $%s" var)))))))
12372
12373 (defun org-finish-edit-formulas (&optional arg)
12374 "Parse the buffer for formula definitions and install them.
12375 With prefix ARG, apply the new formulas to the table."
12376 (interactive "P")
12377 (let ((pos org-pos) eql)
12378 (goto-char (point-min))
12379 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
12380 (push (cons (match-string 1) (match-string 2)) eql))
12381 (set-window-configuration org-window-configuration)
12382 (select-window (get-buffer-window (marker-buffer pos)))
12383 (goto-char pos)
12384 (unless (org-at-table-p)
12385 (error "Lost table position - cannot install formulae"))
12386 (org-table-store-formulas eql)
12387 (move-marker pos nil)
12388 (kill-buffer "*Edit Formulas*")
12389 (if arg
12390 (org-table-recalculate 'all)
12391 (message "New formulas installed - press C-u C-c C-c to apply."))))
12392
12393 (defun org-abort-edit-formulas ()
12394 "Abort editing formulas, without installing the changes."
12395 (interactive)
12396 (let ((pos org-pos))
12397 (set-window-configuration org-window-configuration)
12398 (select-window (get-buffer-window (marker-buffer pos)))
12399 (goto-char pos)
12400 (message "Formula editing aborted without installing changes")))
12401
12402 ;;; The orgtbl minor mode
12403
12404 ;; Define a minor mode which can be used in other modes in order to
12405 ;; integrate the org-mode table editor.
12406
12407 ;; This is really a hack, because the org-mode table editor uses several
12408 ;; keys which normally belong to the major mode, for example the TAB and
12409 ;; RET keys. Here is how it works: The minor mode defines all the keys
12410 ;; necessary to operate the table editor, but wraps the commands into a
12411 ;; function which tests if the cursor is currently inside a table. If that
12412 ;; is the case, the table editor command is executed. However, when any of
12413 ;; those keys is used outside a table, the function uses `key-binding' to
12414 ;; look up if the key has an associated command in another currently active
12415 ;; keymap (minor modes, major mode, global), and executes that command.
12416 ;; There might be problems if any of the keys used by the table editor is
12417 ;; otherwise used as a prefix key.
12418
12419 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
12420 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
12421 ;; addresses this by checking explicitly for both bindings.
12422
12423 ;; The optimized version (see variable `orgtbl-optimized') takes over
12424 ;; all keys which are bound to `self-insert-command' in the *global map*.
12425 ;; Some modes bind other commands to simple characters, for example
12426 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
12427 ;; active, this binding is ignored inside tables and replaced with a
12428 ;; modified self-insert.
12429
12430 (defvar orgtbl-mode nil
12431 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
12432 table editor in arbitrary modes.")
12433 (make-variable-buffer-local 'orgtbl-mode)
12434
12435 (defvar orgtbl-mode-map (make-keymap)
12436 "Keymap for `orgtbl-mode'.")
12437
12438 ;;;###autoload
12439 (defun turn-on-orgtbl ()
12440 "Unconditionally turn on `orgtbl-mode'."
12441 (orgtbl-mode 1))
12442
12443 ;;;###autoload
12444 (defun orgtbl-mode (&optional arg)
12445 "The `org-mode' table editor as a minor mode for use in other modes."
12446 (interactive)
12447 (if (eq major-mode 'org-mode)
12448 ;; Exit without error, in case some hook functions calls this
12449 ;; by accident in org-mode.
12450 (message "Orgtbl-mode is not useful in org-mode, command ignored")
12451 (setq orgtbl-mode
12452 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
12453 (if orgtbl-mode
12454 (progn
12455 (and (orgtbl-setup) (defun orgtbl-setup () nil))
12456 ;; Make sure we are first in minor-mode-map-alist
12457 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
12458 (and c (setq minor-mode-map-alist
12459 (cons c (delq c minor-mode-map-alist)))))
12460 (set (make-local-variable (quote org-table-may-need-update)) t)
12461 (org-add-hook 'before-change-functions 'org-before-change-function
12462 nil 'local)
12463 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
12464 auto-fill-inhibit-regexp)
12465 (set (make-local-variable 'auto-fill-inhibit-regexp)
12466 (if auto-fill-inhibit-regexp
12467 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
12468 "[ \t]*|"))
12469 (org-add-to-invisibility-spec '(org-cwidth))
12470 (easy-menu-add orgtbl-mode-menu)
12471 (run-hooks 'orgtbl-mode-hook))
12472 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
12473 (org-cleanup-narrow-column-properties)
12474 (org-remove-from-invisibility-spec '(org-cwidth))
12475 (remove-hook 'before-change-functions 'org-before-change-function t)
12476 (easy-menu-remove orgtbl-mode-menu)
12477 (force-mode-line-update 'all))))
12478
12479 (defun org-cleanup-narrow-column-properties ()
12480 "Remove all properties related to narrow-column invisibility."
12481 (let ((s 1))
12482 (while (setq s (text-property-any s (point-max)
12483 'display org-narrow-column-arrow))
12484 (remove-text-properties s (1+ s) '(display t)))
12485 (setq s 1)
12486 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
12487 (remove-text-properties s (1+ s) '(org-cwidth t)))
12488 (setq s 1)
12489 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
12490 (remove-text-properties s (1+ s) '(invisible t)))))
12491
12492 ;; Install it as a minor mode.
12493 (put 'orgtbl-mode :included t)
12494 (put 'orgtbl-mode :menu-tag "Org Table Mode")
12495 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
12496
12497 (defun orgtbl-make-binding (fun n &rest keys)
12498 "Create a function for binding in the table minor mode.
12499 FUN is the command to call inside a table. N is used to create a unique
12500 command name. KEYS are keys that should be checked in for a command
12501 to execute outside of tables."
12502 (eval
12503 (list 'defun
12504 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
12505 '(arg)
12506 (concat "In tables, run `" (symbol-name fun) "'.\n"
12507 "Outside of tables, run the binding of `"
12508 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
12509 "'.")
12510 '(interactive "p")
12511 (list 'if
12512 '(org-at-table-p)
12513 (list 'call-interactively (list 'quote fun))
12514 (list 'let '(orgtbl-mode)
12515 (list 'call-interactively
12516 (append '(or)
12517 (mapcar (lambda (k)
12518 (list 'key-binding k))
12519 keys)
12520 '('orgtbl-error))))))))
12521
12522 (defun orgtbl-error ()
12523 "Error when there is no default binding for a table key."
12524 (interactive)
12525 (error "This key is has no function outside tables"))
12526
12527 (defun orgtbl-setup ()
12528 "Setup orgtbl keymaps."
12529 (let ((nfunc 0)
12530 (bindings
12531 (list
12532 '([(meta shift left)] org-table-delete-column)
12533 '([(meta left)] org-table-move-column-left)
12534 '([(meta right)] org-table-move-column-right)
12535 '([(meta shift right)] org-table-insert-column)
12536 '([(meta shift up)] org-table-kill-row)
12537 '([(meta shift down)] org-table-insert-row)
12538 '([(meta up)] org-table-move-row-up)
12539 '([(meta down)] org-table-move-row-down)
12540 '("\C-c\C-w" org-table-cut-region)
12541 '("\C-c\M-w" org-table-copy-region)
12542 '("\C-c\C-y" org-table-paste-rectangle)
12543 '("\C-c-" org-table-insert-hline)
12544 ; '([(shift tab)] org-table-previous-field)
12545 '("\C-m" org-table-next-row)
12546 (list (org-key 'S-return) 'org-table-copy-down)
12547 '([(meta return)] org-table-wrap-region)
12548 '("\C-c\C-q" org-table-wrap-region)
12549 '("\C-c?" org-table-current-column)
12550 '("\C-c " org-table-blank-field)
12551 '("\C-c+" org-table-sum)
12552 '("\C-c=" org-table-eval-formula)
12553 '("\C-c'" org-table-edit-formulas)
12554 '("\C-c`" org-table-edit-field)
12555 '("\C-c*" org-table-recalculate)
12556 '("\C-c|" org-table-create-or-convert-from-region)
12557 '("\C-c^" org-table-sort-lines)
12558 '([(control ?#)] org-table-rotate-recalc-marks)))
12559 elt key fun cmd)
12560 (while (setq elt (pop bindings))
12561 (setq nfunc (1+ nfunc))
12562 (setq key (car elt)
12563 fun (nth 1 elt)
12564 cmd (orgtbl-make-binding fun nfunc key))
12565 (define-key orgtbl-mode-map key cmd))
12566 ;; Special treatment needed for TAB and RET
12567 (define-key orgtbl-mode-map [(return)]
12568 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
12569 (define-key orgtbl-mode-map "\C-m"
12570 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
12571 (define-key orgtbl-mode-map [(tab)]
12572 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
12573 (define-key orgtbl-mode-map "\C-i"
12574 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
12575 (define-key orgtbl-mode-map "\C-i"
12576 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
12577 (define-key orgtbl-mode-map "\C-c\C-c"
12578 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
12579 (when orgtbl-optimized
12580 ;; If the user wants maximum table support, we need to hijack
12581 ;; some standard editing functions
12582 (org-remap orgtbl-mode-map
12583 'self-insert-command 'orgtbl-self-insert-command
12584 'delete-char 'org-delete-char
12585 'delete-backward-char 'org-delete-backward-char)
12586 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
12587 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
12588 '("OrgTbl"
12589 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
12590 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
12591 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
12592 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
12593 "--"
12594 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
12595 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
12596 ["Copy Field from Above"
12597 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
12598 "--"
12599 ("Column"
12600 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
12601 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
12602 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
12603 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
12604 "--"
12605 ["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])
12606 ("Row"
12607 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
12608 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
12609 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
12610 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
12611 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
12612 "--"
12613 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
12614 ("Rectangle"
12615 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
12616 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
12617 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
12618 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
12619 "--"
12620 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
12621 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12622 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
12623 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
12624 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
12625 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
12626 ["Sum Column/Rectangle" org-table-sum
12627 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
12628 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
12629 ["Debug Formulas"
12630 (setq org-table-formula-debug (not org-table-formula-debug))
12631 :style toggle :selected org-table-formula-debug]
12632 ))
12633 t)
12634
12635 (defun orgtbl-tab (arg)
12636 "Justification and field motion for `orgtbl-mode'."
12637 (interactive "P")
12638 (if arg (org-table-edit-field t)
12639 (org-table-justify-field-maybe)
12640 (org-table-next-field)))
12641
12642 (defun orgtbl-ret ()
12643 "Justification and field motion for `orgtbl-mode'."
12644 (interactive)
12645 (org-table-justify-field-maybe)
12646 (org-table-next-row))
12647
12648 (defun orgtbl-self-insert-command (N)
12649 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12650 If the cursor is in a table looking at whitespace, the whitespace is
12651 overwritten, and the table is not marked as requiring realignment."
12652 (interactive "p")
12653 (if (and (org-at-table-p)
12654 (or
12655 (and org-table-auto-blank-field
12656 (member last-command
12657 '(orgtbl-hijacker-command-100
12658 orgtbl-hijacker-command-101
12659 orgtbl-hijacker-command-102
12660 orgtbl-hijacker-command-103
12661 orgtbl-hijacker-command-104
12662 orgtbl-hijacker-command-105))
12663 (org-table-blank-field))
12664 t)
12665 (eq N 1)
12666 (looking-at "[^|\n]* +|"))
12667 (let (org-table-may-need-update)
12668 (goto-char (1- (match-end 0)))
12669 (delete-backward-char 1)
12670 (goto-char (match-beginning 0))
12671 (self-insert-command N))
12672 (setq org-table-may-need-update t)
12673 (let (orgtbl-mode)
12674 (call-interactively (key-binding (vector last-input-event))))))
12675
12676 (defun org-force-self-insert (N)
12677 "Needed to enforce self-insert under remapping."
12678 (interactive "p")
12679 (self-insert-command N))
12680
12681 ;;; Exporting
12682
12683 (defconst org-level-max 20)
12684
12685 (defvar org-export-html-preamble nil
12686 "Preamble, to be inserted just after <body>. Set by publishing functions.")
12687 (defvar org-export-html-postamble nil
12688 "Preamble, to be inserted just before </body>. Set by publishing functions.")
12689 (defvar org-export-html-auto-preamble t
12690 "Should default preamble be inserted? Set by publishing functions.")
12691 (defvar org-export-html-auto-postamble t
12692 "Should default postamble be inserted? Set by publishing functions.")
12693
12694 (defconst org-export-plist-vars
12695 '((:language . org-export-default-language)
12696 (:headline-levels . org-export-headline-levels)
12697 (:section-numbers . org-export-with-section-numbers)
12698 (:table-of-contents . org-export-with-toc)
12699 (:archived-trees . org-export-with-archived-trees)
12700 (:emphasize . org-export-with-emphasize)
12701 (:sub-superscript . org-export-with-sub-superscripts)
12702 (:TeX-macros . org-export-with-TeX-macros)
12703 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
12704 (:fixed-width . org-export-with-fixed-width)
12705 (:timestamps . org-export-with-timestamps)
12706 (:tables . org-export-with-tables)
12707 (:table-auto-headline . org-export-highlight-first-table-line)
12708 (:style . org-export-html-style)
12709 (:convert-org-links . org-export-html-link-org-files-as-html)
12710 (:inline-images . org-export-html-inline-images)
12711 (:expand-quoted-html . org-export-html-expand)
12712 (:timestamp . org-export-html-with-timestamp)
12713 (:publishing-directory . org-export-publishing-directory)
12714 (:preamble . org-export-html-preamble)
12715 (:postamble . org-export-html-postamble)
12716 (:auto-preamble . org-export-html-auto-preamble)
12717 (:auto-postamble . org-export-html-auto-postamble)
12718 (:author . user-full-name)
12719 (:email . user-mail-address)))
12720
12721 (defun org-default-export-plist ()
12722 "Return the property list with default settings for the export variables."
12723 (let ((l org-export-plist-vars) rtn e)
12724 (while (setq e (pop l))
12725 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
12726 rtn))
12727
12728 (defun org-infile-export-plist ()
12729 "Return the property list with file-local settings for export."
12730 (save-excursion
12731 (goto-char 0)
12732 (let ((re (org-make-options-regexp
12733 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12734 p key val text options)
12735 (while (re-search-forward re nil t)
12736 (setq key (org-match-string-no-properties 1)
12737 val (org-match-string-no-properties 2))
12738 (cond
12739 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
12740 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
12741 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
12742 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
12743 ((string-equal key "TEXT")
12744 (setq text (if text (concat text "\n" val) val)))
12745 ((string-equal key "OPTIONS") (setq options val))))
12746 (setq p (plist-put p :text text))
12747 (when options
12748 (let ((op '(("H" . :headline-levels)
12749 ("num" . :section-numbers)
12750 ("toc" . :table-of-contents)
12751 ("\\n" . :preserve-breaks)
12752 ("@" . :expand-quoted-html)
12753 (":" . :fixed-width)
12754 ("|" . :tables)
12755 ("^" . :sub-superscript)
12756 ("*" . :emphasize)
12757 ("TeX" . :TeX-macros)
12758 ("LaTeX" . :LaTeX-fragments)))
12759 o)
12760 (while (setq o (pop op))
12761 (if (string-match (concat (regexp-quote (car o))
12762 ":\\([^ \t\n\r;,.]*\\)")
12763 options)
12764 (setq p (plist-put p (cdr o)
12765 (car (read-from-string
12766 (match-string 1 options)))))))))
12767 p)))
12768
12769 (defun org-combine-plists (&rest plists)
12770 "Create a single property list from all plists in PLISTS.
12771 The process starts by copying the last list, and then setting properties
12772 from the other lists. Settings in the first list are the most significant
12773 ones and overrule settings in the other lists."
12774 (let ((rtn (copy-sequence (pop plists)))
12775 p v ls)
12776 (while plists
12777 (setq ls (pop plists))
12778 (while ls
12779 (setq p (pop ls) v (pop ls))
12780 (setq rtn (plist-put rtn p v))))
12781 rtn))
12782
12783 (defun org-export-directory (type plist)
12784 (let* ((val (plist-get plist :publishing-directory))
12785 (dir (if (listp val)
12786 (or (cdr (assoc type val)) ".")
12787 val)))
12788 dir))
12789
12790 (defun org-export-find-first-heading-line (list)
12791 "Remove all lines from LIST which are before the first headline."
12792 (let ((orig-list list)
12793 (re (concat "^" outline-regexp)))
12794 (while (and list
12795 (not (string-match re (car list))))
12796 (pop list))
12797 (or list orig-list)))
12798
12799 (defun org-skip-comments (lines)
12800 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
12801 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
12802 (re2 "^\\(\\*+\\)[ \t\n\r]")
12803 rtn line level)
12804 (while (setq line (pop lines))
12805 (cond
12806 ((and (string-match re1 line)
12807 (setq level (- (match-end 1) (match-beginning 1))))
12808 ;; Beginning of a COMMENT subtree. Skip it.
12809 (while (and (setq line (pop lines))
12810 (or (not (string-match re2 line))
12811 (> (- (match-end 1) (match-beginning 1)) level))))
12812 (setq lines (cons line lines)))
12813 ((string-match "^#" line)
12814 ;; an ordinary comment line
12815 )
12816 ((and org-export-table-remove-special-lines
12817 (string-match "^[ \t]*|" line)
12818 (or (string-match "^[ \t]*| *[!_^] *|" line)
12819 (and (string-match "| *<[0-9]+> *|" line)
12820 (not (string-match "| *[^ <|]" line)))))
12821 ;; a special table line that should be removed
12822 )
12823 (t (setq rtn (cons line rtn)))))
12824 (nreverse rtn)))
12825
12826 (defun org-export (&optional arg)
12827 (interactive)
12828 (let ((help "[t] insert the export option template
12829 \[v] limit export to visible part of outline tree
12830
12831 \[a] export as ASCII
12832 \[h] export as HTML
12833 \[b] export as HTML and browse immediately
12834 \[x] export as XOXO
12835
12836 \[i] export current file as iCalendar file
12837 \[I] export all agenda files as iCalendar files
12838 \[c] export agenda files into combined iCalendar file
12839
12840 \[F] publish current file
12841 \[P] publish current project
12842 \[X] publish... (project will be prompted for)
12843 \[A] publish all projects")
12844 (cmds
12845 '((?t . org-insert-export-options-template)
12846 (?v . org-export-visible)
12847 (?a . org-export-as-ascii)
12848 (?h . org-export-as-html)
12849 (?b . org-export-as-html-and-open)
12850 (?x . org-export-as-xoxo)
12851 (?i . org-export-icalendar-this-file)
12852 (?I . org-export-icalendar-all-agenda-files)
12853 (?c . org-export-icalendar-combine-agenda-files)
12854 (?F . org-publish-current-file)
12855 (?P . org-publish-current-project)
12856 (?X . org-publish)
12857 (?A . org-publish-all)))
12858 r1 r2 ass)
12859 (save-window-excursion
12860 (delete-other-windows)
12861 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
12862 (princ help))
12863 (message "Select command: ")
12864 (setq r1 (read-char-exclusive)))
12865 (setq r2 (if (< r1 27) (+ r1 96) r1))
12866 (if (setq ass (assq r2 cmds))
12867 (call-interactively (cdr ass))
12868 (error "No command associated with key %c" r1))))
12869
12870 ;; ASCII
12871
12872 (defconst org-html-entities
12873 '(("nbsp")
12874 ("iexcl")
12875 ("cent")
12876 ("pound")
12877 ("curren")
12878 ("yen")
12879 ("brvbar")
12880 ("sect")
12881 ("uml")
12882 ("copy")
12883 ("ordf")
12884 ("laquo")
12885 ("not")
12886 ("shy")
12887 ("reg")
12888 ("macr")
12889 ("deg")
12890 ("plusmn")
12891 ("sup2")
12892 ("sup3")
12893 ("acute")
12894 ("micro")
12895 ("para")
12896 ("middot")
12897 ("odot"."o")
12898 ("star"."*")
12899 ("cedil")
12900 ("sup1")
12901 ("ordm")
12902 ("raquo")
12903 ("frac14")
12904 ("frac12")
12905 ("frac34")
12906 ("iquest")
12907 ("Agrave")
12908 ("Aacute")
12909 ("Acirc")
12910 ("Atilde")
12911 ("Auml")
12912 ("Aring") ("AA"."&Aring;")
12913 ("AElig")
12914 ("Ccedil")
12915 ("Egrave")
12916 ("Eacute")
12917 ("Ecirc")
12918 ("Euml")
12919 ("Igrave")
12920 ("Iacute")
12921 ("Icirc")
12922 ("Iuml")
12923 ("ETH")
12924 ("Ntilde")
12925 ("Ograve")
12926 ("Oacute")
12927 ("Ocirc")
12928 ("Otilde")
12929 ("Ouml")
12930 ("times")
12931 ("Oslash")
12932 ("Ugrave")
12933 ("Uacute")
12934 ("Ucirc")
12935 ("Uuml")
12936 ("Yacute")
12937 ("THORN")
12938 ("szlig")
12939 ("agrave")
12940 ("aacute")
12941 ("acirc")
12942 ("atilde")
12943 ("auml")
12944 ("aring")
12945 ("aelig")
12946 ("ccedil")
12947 ("egrave")
12948 ("eacute")
12949 ("ecirc")
12950 ("euml")
12951 ("igrave")
12952 ("iacute")
12953 ("icirc")
12954 ("iuml")
12955 ("eth")
12956 ("ntilde")
12957 ("ograve")
12958 ("oacute")
12959 ("ocirc")
12960 ("otilde")
12961 ("ouml")
12962 ("divide")
12963 ("oslash")
12964 ("ugrave")
12965 ("uacute")
12966 ("ucirc")
12967 ("uuml")
12968 ("yacute")
12969 ("thorn")
12970 ("yuml")
12971 ("fnof")
12972 ("Alpha")
12973 ("Beta")
12974 ("Gamma")
12975 ("Delta")
12976 ("Epsilon")
12977 ("Zeta")
12978 ("Eta")
12979 ("Theta")
12980 ("Iota")
12981 ("Kappa")
12982 ("Lambda")
12983 ("Mu")
12984 ("Nu")
12985 ("Xi")
12986 ("Omicron")
12987 ("Pi")
12988 ("Rho")
12989 ("Sigma")
12990 ("Tau")
12991 ("Upsilon")
12992 ("Phi")
12993 ("Chi")
12994 ("Psi")
12995 ("Omega")
12996 ("alpha")
12997 ("beta")
12998 ("gamma")
12999 ("delta")
13000 ("epsilon")
13001 ("varepsilon"."&epsilon;")
13002 ("zeta")
13003 ("eta")
13004 ("theta")
13005 ("iota")
13006 ("kappa")
13007 ("lambda")
13008 ("mu")
13009 ("nu")
13010 ("xi")
13011 ("omicron")
13012 ("pi")
13013 ("rho")
13014 ("sigmaf") ("varsigma"."&sigmaf;")
13015 ("sigma")
13016 ("tau")
13017 ("upsilon")
13018 ("phi")
13019 ("chi")
13020 ("psi")
13021 ("omega")
13022 ("thetasym") ("vartheta"."&thetasym;")
13023 ("upsih")
13024 ("piv")
13025 ("bull") ("bullet"."&bull;")
13026 ("hellip") ("dots"."&hellip;")
13027 ("prime")
13028 ("Prime")
13029 ("oline")
13030 ("frasl")
13031 ("weierp")
13032 ("image")
13033 ("real")
13034 ("trade")
13035 ("alefsym")
13036 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
13037 ("uarr") ("uparrow"."&uarr;")
13038 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
13039 ("darr")("downarrow"."&darr;")
13040 ("harr") ("leftrightarrow"."&harr;")
13041 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
13042 ("lArr") ("Leftarrow"."&lArr;")
13043 ("uArr") ("Uparrow"."&uArr;")
13044 ("rArr") ("Rightarrow"."&rArr;")
13045 ("dArr") ("Downarrow"."&dArr;")
13046 ("hArr") ("Leftrightarrow"."&hArr;")
13047 ("forall")
13048 ("part") ("partial"."&part;")
13049 ("exist") ("exists"."&exist;")
13050 ("empty") ("emptyset"."&empty;")
13051 ("nabla")
13052 ("isin") ("in"."&isin;")
13053 ("notin")
13054 ("ni")
13055 ("prod")
13056 ("sum")
13057 ("minus")
13058 ("lowast") ("ast"."&lowast;")
13059 ("radic")
13060 ("prop") ("proptp"."&prop;")
13061 ("infin") ("infty"."&infin;")
13062 ("ang") ("angle"."&ang;")
13063 ("and") ("vee"."&and;")
13064 ("or") ("wedge"."&or;")
13065 ("cap")
13066 ("cup")
13067 ("int")
13068 ("there4")
13069 ("sim")
13070 ("cong") ("simeq"."&cong;")
13071 ("asymp")("approx"."&asymp;")
13072 ("ne") ("neq"."&ne;")
13073 ("equiv")
13074 ("le")
13075 ("ge")
13076 ("sub") ("subset"."&sub;")
13077 ("sup") ("supset"."&sup;")
13078 ("nsub")
13079 ("sube")
13080 ("supe")
13081 ("oplus")
13082 ("otimes")
13083 ("perp")
13084 ("sdot") ("cdot"."&sdot;")
13085 ("lceil")
13086 ("rceil")
13087 ("lfloor")
13088 ("rfloor")
13089 ("lang")
13090 ("rang")
13091 ("loz") ("Diamond"."&loz;")
13092 ("spades") ("spadesuit"."&spades;")
13093 ("clubs") ("clubsuit"."&clubs;")
13094 ("hearts") ("diamondsuit"."&hearts;")
13095 ("diams") ("diamondsuit"."&diams;")
13096 ("quot")
13097 ("amp")
13098 ("lt")
13099 ("gt")
13100 ("OElig")
13101 ("oelig")
13102 ("Scaron")
13103 ("scaron")
13104 ("Yuml")
13105 ("circ")
13106 ("tilde")
13107 ("ensp")
13108 ("emsp")
13109 ("thinsp")
13110 ("zwnj")
13111 ("zwj")
13112 ("lrm")
13113 ("rlm")
13114 ("ndash")
13115 ("mdash")
13116 ("lsquo")
13117 ("rsquo")
13118 ("sbquo")
13119 ("ldquo")
13120 ("rdquo")
13121 ("bdquo")
13122 ("dagger")
13123 ("Dagger")
13124 ("permil")
13125 ("lsaquo")
13126 ("rsaquo")
13127 ("euro")
13128
13129 ("arccos"."arccos")
13130 ("arcsin"."arcsin")
13131 ("arctan"."arctan")
13132 ("arg"."arg")
13133 ("cos"."cos")
13134 ("cosh"."cosh")
13135 ("cot"."cot")
13136 ("coth"."coth")
13137 ("csc"."csc")
13138 ("deg"."deg")
13139 ("det"."det")
13140 ("dim"."dim")
13141 ("exp"."exp")
13142 ("gcd"."gcd")
13143 ("hom"."hom")
13144 ("inf"."inf")
13145 ("ker"."ker")
13146 ("lg"."lg")
13147 ("lim"."lim")
13148 ("liminf"."liminf")
13149 ("limsup"."limsup")
13150 ("ln"."ln")
13151 ("log"."log")
13152 ("max"."max")
13153 ("min"."min")
13154 ("Pr"."Pr")
13155 ("sec"."sec")
13156 ("sin"."sin")
13157 ("sinh"."sinh")
13158 ("sup"."sup")
13159 ("tan"."tan")
13160 ("tanh"."tanh")
13161 )
13162 "Entities for TeX->HTML translation.
13163 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
13164 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
13165 In that case, \"\\ent\" will be translated to \"&other;\".
13166 The list contains HTML entities for Latin-1, Greek and other symbols.
13167 It is supplemented by a number of commonly used TeX macros with appropriate
13168 translations. There is currently no way for users to extend this.")
13169
13170 (defun org-cleaned-string-for-export (string &rest parameters)
13171 "Cleanup a buffer substring so that links can be created safely."
13172 (interactive)
13173 (let* ((re-radio (and org-target-link-regexp
13174 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
13175 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
13176 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
13177 (re-archive (concat ":" org-archive-tag ":"))
13178 rtn)
13179 (save-excursion
13180 (set-buffer (get-buffer-create " org-mode-tmp"))
13181 (erase-buffer)
13182 (insert string)
13183 (let ((org-inhibit-startup t)) (org-mode))
13184
13185 ;; Get rid of archived trees
13186 (when (not (eq org-export-with-archived-trees t))
13187 (goto-char (point-min))
13188 (while (re-search-forward re-archive nil t)
13189 (if (not (org-on-heading-p))
13190 (org-end-of-subtree t)
13191 (beginning-of-line 1)
13192 (delete-region
13193 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
13194 (org-end-of-subtree)))))
13195
13196 ;; Find targets in comments and move them out of comments,
13197 ;; but mark them as targets that should be invisible
13198 (goto-char (point-min))
13199 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
13200 (replace-match "\\1(INVISIBLE)"))
13201
13202 ;; Find matches for radio targets and turn them into internal links
13203 (goto-char (point-min))
13204 (when re-radio
13205 (while (re-search-forward re-radio nil t)
13206 (replace-match "\\1[[\\2]]")))
13207
13208 ;; Find all links that contain a newline and put them into a single line
13209 (goto-char (point-min))
13210 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
13211 (replace-match "\\1 \\3")
13212 (goto-char (match-beginning 0)))
13213
13214 ;; Convert LaTeX fragments to images
13215 (when (memq :LaTeX-fragments parameters)
13216 (org-format-latex
13217 (concat "ltxpng/" (file-name-sans-extension
13218 (file-name-nondirectory
13219 org-current-export-file)))
13220 org-current-export-dir nil "Creating LaTeX image %s"))
13221 (message "Exporting...")
13222
13223 ;; Normalize links: Convert angle and plain links into bracket links
13224 (goto-char (point-min))
13225 (while (re-search-forward re-plain-link nil t)
13226 (replace-match
13227 (concat
13228 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13229 t t))
13230 (goto-char (point-min))
13231 (while (re-search-forward re-angle-link nil t)
13232 (replace-match
13233 (concat
13234 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13235 t t))
13236
13237 ;; Find multiline emphasis and put them into single line
13238 (when (memq :emph-multiline parameters)
13239 (goto-char (point-min))
13240 (while (re-search-forward org-emph-re nil t)
13241 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
13242 (goto-char (1- (match-end 0)))))
13243
13244 ;; Remove comments
13245 (goto-char (point-min))
13246 (while (re-search-forward "^#.*\n?" nil t)
13247 (replace-match ""))
13248 (setq rtn (buffer-string)))
13249 (kill-buffer " org-mode-tmp")
13250 rtn))
13251
13252 (defun org-solidify-link-text (s &optional alist)
13253 "Take link text and make a safe target out of it."
13254 (save-match-data
13255 (let* ((rtn
13256 (mapconcat
13257 'identity
13258 (org-split-string s "[ \t\r\n]+") "--"))
13259 (a (assoc rtn alist)))
13260 (or (cdr a) rtn))))
13261
13262 (defun org-convert-to-odd-levels ()
13263 "Convert an org-mode file with all levels allowed to one with odd levels.
13264 This will leave level 1 alone, convert level 2 to level 3, level 3 to
13265 level 5 etc."
13266 (interactive)
13267 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
13268 (let ((org-odd-levels-only nil) n)
13269 (save-excursion
13270 (goto-char (point-min))
13271 (while (re-search-forward "^\\*\\*+" nil t)
13272 (setq n (1- (length (match-string 0))))
13273 (while (>= (setq n (1- n)) 0)
13274 (org-demote))
13275 (end-of-line 1))))))
13276
13277
13278 (defun org-convert-to-oddeven-levels ()
13279 "Convert an org-mode file with only odd levels to one with odd and even levels.
13280 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
13281 section with an even level, conversion would destroy the structure of the file. An error
13282 is signaled in this case."
13283 (interactive)
13284 (goto-char (point-min))
13285 ;; First check if there are no even levels
13286 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
13287 (org-show-hierarchy-above)
13288 (error "Not all levels are odd in this file. Conversion not possible."))
13289 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
13290 (let ((org-odd-levels-only nil) n)
13291 (save-excursion
13292 (goto-char (point-min))
13293 (while (re-search-forward "^\\*\\*+" nil t)
13294 (setq n (/ (length (match-string 0)) 2))
13295 (while (>= (setq n (1- n)) 0)
13296 (org-promote))
13297 (end-of-line 1))))))
13298
13299 (defun org-tr-level (n)
13300 "Make N odd if required."
13301 (if org-odd-levels-only (1+ (/ n 2)) n))
13302
13303 (defvar org-last-level nil) ; dynamically scoped variable
13304 (defvar org-ascii-current-indentation nil) ; For communication
13305
13306 (defun org-export-as-ascii (arg)
13307 "Export the outline as a pretty ASCII file.
13308 If there is an active region, export only the region.
13309 The prefix ARG specifies how many levels of the outline should become
13310 underlined headlines. The default is 3."
13311 (interactive "P")
13312 (setq-default org-todo-line-regexp org-todo-line-regexp)
13313 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13314 (org-infile-export-plist)))
13315 (region
13316 (buffer-substring
13317 (if (org-region-active-p) (region-beginning) (point-min))
13318 (if (org-region-active-p) (region-end) (point-max))))
13319 (lines (org-export-find-first-heading-line
13320 (org-skip-comments
13321 (org-split-string
13322 (org-cleaned-string-for-export region)
13323 "[\r\n]"))))
13324 (org-ascii-current-indentation '(0 . 0))
13325 (org-startup-with-deadline-check nil)
13326 (level 0) line txt
13327 (umax nil)
13328 (case-fold-search nil)
13329 (filename (concat (file-name-as-directory
13330 (org-export-directory :ascii opt-plist))
13331 (file-name-sans-extension
13332 (file-name-nondirectory buffer-file-name))
13333 ".txt"))
13334 (buffer (find-file-noselect filename))
13335 (levels-open (make-vector org-level-max nil))
13336 (odd org-odd-levels-only)
13337 (date (format-time-string "%Y/%m/%d" (current-time)))
13338 (time (format-time-string "%X" (org-current-time)))
13339 (author (plist-get opt-plist :author))
13340 (title (or (plist-get opt-plist :title)
13341 (file-name-sans-extension
13342 (file-name-nondirectory buffer-file-name))))
13343 (email (plist-get opt-plist :email))
13344 (language (plist-get opt-plist :language))
13345 (text nil)
13346 (todo nil)
13347 (lang-words nil))
13348
13349 (setq org-last-level 1)
13350 (org-init-section-numbers)
13351
13352 (find-file-noselect filename)
13353
13354 (setq lang-words (or (assoc language org-export-language-setup)
13355 (assoc "en" org-export-language-setup)))
13356 (if org-export-ascii-show-new-buffer
13357 (switch-to-buffer-other-window buffer)
13358 (set-buffer buffer))
13359 (erase-buffer)
13360 (fundamental-mode)
13361 ;; create local variables for all options, to make sure all called
13362 ;; functions get the correct information
13363 (mapcar (lambda (x)
13364 (set (make-local-variable (cdr x))
13365 (plist-get opt-plist (car x))))
13366 org-export-plist-vars)
13367 (set (make-local-variable 'org-odd-levels-only) odd)
13368 (setq umax (if arg (prefix-numeric-value arg)
13369 org-export-headline-levels))
13370
13371 ;; File header
13372 (if title (org-insert-centered title ?=))
13373 (insert "\n")
13374 (if (or author email)
13375 (insert (concat (nth 1 lang-words) ": " (or author "")
13376 (if email (concat " <" email ">") "")
13377 "\n")))
13378 (if (and date time)
13379 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
13380 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
13381
13382 (insert "\n\n")
13383
13384 (if org-export-with-toc
13385 (progn
13386 (insert (nth 3 lang-words) "\n"
13387 (make-string (length (nth 3 lang-words)) ?=) "\n")
13388 (mapcar '(lambda (line)
13389 (if (string-match org-todo-line-regexp
13390 line)
13391 ;; This is a headline
13392 (progn
13393 (setq level (- (match-end 1) (match-beginning 1))
13394 level (org-tr-level level)
13395 txt (match-string 3 line)
13396 todo
13397 (or (and org-export-mark-todo-in-toc
13398 (match-beginning 2)
13399 (not (equal (match-string 2 line)
13400 org-done-string)))
13401 ; TODO, not DONE
13402 (and org-export-mark-todo-in-toc
13403 (= level umax)
13404 (org-search-todo-below
13405 line lines level))))
13406 (setq txt (org-html-expand-for-ascii txt))
13407
13408 (if org-export-with-section-numbers
13409 (setq txt (concat (org-section-number level)
13410 " " txt)))
13411 (if (<= level umax)
13412 (progn
13413 (insert
13414 (make-string (* (1- level) 4) ?\ )
13415 (format (if todo "%s (*)\n" "%s\n") txt))
13416 (setq org-last-level level))
13417 ))))
13418 lines)))
13419
13420 (org-init-section-numbers)
13421 (while (setq line (pop lines))
13422 ;; Remove the quoted HTML tags.
13423 (setq line (org-html-expand-for-ascii line))
13424 ;; Remove targets
13425 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
13426 (setq line (replace-match "" t t line)))
13427 ;; Replace internal links
13428 (while (string-match org-bracket-link-regexp line)
13429 (setq line (replace-match
13430 (if (match-end 3) "[\\3]" "[\\1]")
13431 t nil line)))
13432 (cond
13433 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
13434 ;; a Headline
13435 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
13436 txt (match-string 2 line))
13437 (org-ascii-level-start level txt umax lines))
13438 (t
13439 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
13440 (normal-mode)
13441 (save-buffer)
13442 ;; remove display and invisible chars
13443 (let (beg end)
13444 (goto-char (point-min))
13445 (while (setq beg (next-single-property-change (point) 'display))
13446 (setq end (next-single-property-change beg 'display))
13447 (delete-region beg end)
13448 (goto-char beg)
13449 (insert "=>"))
13450 (goto-char (point-min))
13451 (while (setq beg (next-single-property-change (point) 'org-cwidth))
13452 (setq end (next-single-property-change beg 'org-cwidth))
13453 (delete-region beg end)
13454 (goto-char beg)))
13455 (goto-char (point-min))))
13456
13457 (defun org-search-todo-below (line lines level)
13458 "Search the subtree below LINE for any TODO entries."
13459 (let ((rest (cdr (memq line lines)))
13460 (re org-todo-line-regexp)
13461 line lv todo)
13462 (catch 'exit
13463 (while (setq line (pop rest))
13464 (if (string-match re line)
13465 (progn
13466 (setq lv (- (match-end 1) (match-beginning 1))
13467 todo (and (match-beginning 2)
13468 (not (equal (match-string 2 line)
13469 org-done-string))))
13470 ; TODO, not DONE
13471 (if (<= lv level) (throw 'exit nil))
13472 (if todo (throw 'exit t))))))))
13473
13474 (defun org-html-expand-for-ascii (line)
13475 "Handle quoted HTML for ASCII export."
13476 (if org-export-html-expand
13477 (while (string-match "@<[^<>\n]*>" line)
13478 ;; We just remove the tags for now.
13479 (setq line (replace-match "" nil nil line))))
13480 line)
13481
13482 (defun org-insert-centered (s &optional underline)
13483 "Insert the string S centered and underline it with character UNDERLINE."
13484 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
13485 (insert (make-string ind ?\ ) s "\n")
13486 (if underline
13487 (insert (make-string ind ?\ )
13488 (make-string (string-width s) underline)
13489 "\n"))))
13490
13491 (defun org-ascii-level-start (level title umax &optional lines)
13492 "Insert a new level in ASCII export."
13493 (let (char (n (- level umax 1)) (ind 0))
13494 (if (> level umax)
13495 (progn
13496 (insert (make-string (* 2 n) ?\ )
13497 (char-to-string (nth (% n (length org-export-ascii-bullets))
13498 org-export-ascii-bullets))
13499 " " title "\n")
13500 ;; find the indentation of the next non-empty line
13501 (catch 'stop
13502 (while lines
13503 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
13504 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
13505 (throw 'stop (setq ind (org-get-indentation (car lines)))))
13506 (pop lines)))
13507 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
13508 (if (or (not (equal (char-before) ?\n))
13509 (not (equal (char-before (1- (point))) ?\n)))
13510 (insert "\n"))
13511 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
13512 (if org-export-with-section-numbers
13513 (setq title (concat (org-section-number level) " " title)))
13514 (insert title "\n" (make-string (string-width title) char) "\n")
13515 (setq org-ascii-current-indentation '(0 . 0)))))
13516
13517 (defun org-export-visible (type arg)
13518 "Create a copy of the visible part of the current buffer, and export it.
13519 The copy is created in a temporary buffer and removed after use.
13520 TYPE is the final key (as a string) that also select the export command in
13521 the `C-c C-e' export dispatcher.
13522 As a special case, if the you type SPC at the prompt, the temporary
13523 org-mode file will not be removed but presented to you so that you can
13524 continue to use it. The prefix arg ARG is passed through to the exporting
13525 command."
13526 (interactive
13527 (list (progn
13528 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
13529 (read-char-exclusive))
13530 current-prefix-arg))
13531 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
13532 (error "Invalid export key"))
13533 (let* ((binding (cdr (assoc type
13534 '((?a . org-export-as-ascii)
13535 (?\C-a . org-export-as-ascii)
13536 (?b . org-export-as-html-and-open)
13537 (?\C-b . org-export-as-html-and-open)
13538 (?h . org-export-as-html)
13539 (?x . org-export-as-xoxo)))))
13540 (keepp (equal type ?\ ))
13541 (file buffer-file-name)
13542 (buffer (get-buffer-create "*Org Export Visible*"))
13543 s e)
13544 (with-current-buffer buffer (erase-buffer))
13545 (save-excursion
13546 (setq s (goto-char (point-min)))
13547 (while (not (= (point) (point-max)))
13548 (goto-char (org-find-invisible))
13549 (append-to-buffer buffer s (point))
13550 (setq s (goto-char (org-find-visible))))
13551 (goto-char (point-min))
13552 (unless keepp
13553 ;; Copy all comment lines to the end, to make sure #+ settings are
13554 ;; still available for the second export step. Kind of a hack, but
13555 ;; does do the trick.
13556 (if (looking-at "#[^\r\n]*")
13557 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
13558 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
13559 (append-to-buffer buffer (1+ (match-beginning 0))
13560 (min (point-max) (1+ (match-end 0))))))
13561 (set-buffer buffer)
13562 (let ((buffer-file-name file)
13563 (org-inhibit-startup t))
13564 (org-mode)
13565 (show-all)
13566 (unless keepp (funcall binding arg))))
13567 (if (not keepp)
13568 (kill-buffer buffer)
13569 (switch-to-buffer-other-window buffer)
13570 (goto-char (point-min)))))
13571
13572 (defun org-find-visible ()
13573 (if (featurep 'noutline)
13574 (let ((s (point)))
13575 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13576 (get-char-property s 'invisible)))
13577 s)
13578 (skip-chars-forward "^\n")
13579 (point)))
13580 (defun org-find-invisible ()
13581 (if (featurep 'noutline)
13582 (let ((s (point)))
13583 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13584 (not (get-char-property s 'invisible))))
13585 s)
13586 (skip-chars-forward "^\r")
13587 (point)))
13588
13589
13590 ;; HTML
13591
13592 (defun org-get-current-options ()
13593 "Return a string with current options as keyword options.
13594 Does include HTML export options as well as TODO and CATEGORY stuff."
13595 (format
13596 "#+TITLE: %s
13597 #+AUTHOR: %s
13598 #+EMAIL: %s
13599 #+LANGUAGE: %s
13600 #+TEXT: Some descriptive text to be emitted. Several lines OK.
13601 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
13602 #+CATEGORY: %s
13603 #+SEQ_TODO: %s
13604 #+TYP_TODO: %s
13605 #+STARTUP: %s %s %s %s %s %s
13606 #+TAGS: %s
13607 #+ARCHIVE: %s
13608 "
13609 (buffer-name) (user-full-name) user-mail-address org-export-default-language
13610 org-export-headline-levels
13611 org-export-with-section-numbers
13612 org-export-with-toc
13613 org-export-preserve-breaks
13614 org-export-html-expand
13615 org-export-with-fixed-width
13616 org-export-with-tables
13617 org-export-with-sub-superscripts
13618 org-export-with-emphasize
13619 org-export-with-TeX-macros
13620 org-export-with-LaTeX-fragments
13621 (file-name-nondirectory buffer-file-name)
13622 (if (equal org-todo-interpretation 'sequence)
13623 (mapconcat 'identity org-todo-keywords " ")
13624 "TODO FEEDBACK VERIFY DONE")
13625 (if (equal org-todo-interpretation 'type)
13626 (mapconcat 'identity org-todo-keywords " ")
13627 "Me Jason Marie DONE")
13628 (cdr (assoc org-startup-folded
13629 '((nil . "showall") (t . "overview") (content . "content"))))
13630 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
13631 (if org-odd-levels-only "odd" "oddeven")
13632 (if org-hide-leading-stars "hidestars" "showstars")
13633 (if org-startup-align-all-tables "align" "noalign")
13634 (if org-log-done "logging" "nologging")
13635 (if org-tag-alist (mapconcat 'car org-tag-alist " ") "")
13636 org-archive-location
13637 ))
13638
13639 (defun org-insert-export-options-template ()
13640 "Insert into the buffer a template with information for exporting."
13641 (interactive)
13642 (if (not (bolp)) (newline))
13643 (let ((s (org-get-current-options)))
13644 (and (string-match "#\\+CATEGORY" s)
13645 (setq s (substring s 0 (match-beginning 0))))
13646 (insert s)))
13647
13648 (defun org-toggle-fixed-width-section (arg)
13649 "Toggle the fixed-width export.
13650 If there is no active region, the QUOTE keyword at the current headline is
13651 inserted or removed. When present, it causes the text between this headline
13652 and the next to be exported as fixed-width text, and unmodified.
13653 If there is an active region, this command adds or removes a colon as the
13654 first character of this line. If the first character of a line is a colon,
13655 this line is also exported in fixed-width font."
13656 (interactive "P")
13657 (let* ((cc 0)
13658 (regionp (org-region-active-p))
13659 (beg (if regionp (region-beginning) (point)))
13660 (end (if regionp (region-end)))
13661 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13662 (re "[ \t]*\\(:\\)")
13663 off)
13664 (if regionp
13665 (save-excursion
13666 (goto-char beg)
13667 (setq cc (current-column))
13668 (beginning-of-line 1)
13669 (setq off (looking-at re))
13670 (while (> nlines 0)
13671 (setq nlines (1- nlines))
13672 (beginning-of-line 1)
13673 (cond
13674 (arg
13675 (move-to-column cc t)
13676 (insert ":\n")
13677 (forward-line -1))
13678 ((and off (looking-at re))
13679 (replace-match "" t t nil 1))
13680 ((not off) (move-to-column cc t) (insert ":")))
13681 (forward-line 1)))
13682 (save-excursion
13683 (org-back-to-heading)
13684 (if (looking-at (concat outline-regexp
13685 "\\( +\\<" org-quote-string "\\>\\)"))
13686 (replace-match "" t t nil 1)
13687 (if (looking-at outline-regexp)
13688 (progn
13689 (goto-char (match-end 0))
13690 (insert " " org-quote-string))))))))
13691
13692 (defun org-export-as-html-and-open (arg)
13693 "Export the outline as HTML and immediately open it with a browser.
13694 If there is an active region, export only the region.
13695 The prefix ARG specifies how many levels of the outline should become
13696 headlines. The default is 3. Lower levels will become bulleted lists."
13697 (interactive "P")
13698 (org-export-as-html arg 'hidden)
13699 (org-open-file buffer-file-name))
13700
13701 (defun org-export-as-html-batch ()
13702 "Call `org-export-as-html', may be used in batch processing as
13703 emacs --batch
13704 --load=$HOME/lib/emacs/org.el
13705 --eval \"(setq org-export-headline-levels 2)\"
13706 --visit=MyFile --funcall org-export-as-html-batch"
13707 (org-export-as-html org-export-headline-levels 'hidden))
13708
13709 (defun org-export-as-html (arg &optional hidden ext-plist)
13710 "Export the outline as a pretty HTML file.
13711 If there is an active region, export only the region.
13712 The prefix ARG specifies how many levels of the outline should become
13713 headlines. The default is 3. Lower levels will become bulleted lists.
13714 When HIDDEN is non-nil, don't display the HTML buffer.
13715 EXT-PLIST is a property list with external parameters overriding
13716 org-mode's default settings, but still inferior to file-local settings."
13717 (interactive "P")
13718 (message "Exporting...")
13719 (setq-default org-todo-line-regexp org-todo-line-regexp)
13720 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
13721 (setq-default org-done-string org-done-string)
13722 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13723 ext-plist
13724 (org-infile-export-plist)))
13725
13726 (style (plist-get opt-plist :style))
13727 (link-validate (plist-get opt-plist :link-validation-function))
13728 valid
13729 (odd org-odd-levels-only)
13730 (region-p (org-region-active-p))
13731 (region
13732 (buffer-substring
13733 (if region-p (region-beginning) (point-min))
13734 (if region-p (region-end) (point-max))))
13735 ;; The following two are dynamically scoped into other
13736 ;; routines below.
13737 (org-current-export-dir (org-export-directory :html opt-plist))
13738 (org-current-export-file buffer-file-name)
13739 (all_lines
13740 (org-skip-comments (org-split-string
13741 (org-cleaned-string-for-export
13742 region :emph-multiline
13743 (if (plist-get opt-plist :LaTeX-fragments)
13744 :LaTeX-fragments))
13745 "[\r\n]")))
13746 (lines (org-export-find-first-heading-line all_lines))
13747 (level 0) (line "") (origline "") txt todo
13748 (umax nil)
13749 (filename (concat (file-name-as-directory
13750 (org-export-directory :html opt-plist))
13751 (file-name-sans-extension
13752 (file-name-nondirectory buffer-file-name))
13753 ".html"))
13754 (current-dir (file-name-directory buffer-file-name))
13755 (buffer (find-file-noselect filename))
13756 (levels-open (make-vector org-level-max nil))
13757 (date (format-time-string "%Y/%m/%d" (current-time)))
13758 (time (format-time-string "%X" (org-current-time)))
13759 (author (plist-get opt-plist :author))
13760 (title (or (plist-get opt-plist :title)
13761 (file-name-sans-extension
13762 (file-name-nondirectory buffer-file-name))))
13763 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
13764 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
13765 (inquote nil)
13766 (infixed nil)
13767 (in-local-list nil)
13768 (local-list-num nil)
13769 (local-list-indent nil)
13770 (llt org-plain-list-ordered-item-terminator)
13771 (email (plist-get opt-plist :email))
13772 (language (plist-get opt-plist :language))
13773 (text (plist-get opt-plist :text))
13774 (lang-words nil)
13775 (target-alist nil) tg
13776 (head-count 0) cnt
13777 (start 0)
13778 (coding-system (and (fboundp 'coding-system-get)
13779 (boundp 'buffer-file-coding-system)
13780 buffer-file-coding-system))
13781 (coding-system-for-write (or coding-system coding-system-for-write))
13782 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
13783 (charset (and coding-system
13784 (coding-system-get coding-system 'mime-charset)))
13785 table-open type
13786 table-buffer table-orig-buffer
13787 ind start-is-num starter
13788 rpl path desc descp desc1 desc2 link
13789 )
13790 (message "Exporting...")
13791
13792 (setq org-last-level 1)
13793 (org-init-section-numbers)
13794
13795 ;; Get the language-dependent settings
13796 (setq lang-words (or (assoc language org-export-language-setup)
13797 (assoc "en" org-export-language-setup)))
13798
13799 ;; Switch to the output buffer
13800 (if (or hidden (not org-export-html-show-new-buffer))
13801 (set-buffer buffer)
13802 (switch-to-buffer-other-window buffer))
13803 (erase-buffer)
13804 (fundamental-mode)
13805 (let ((case-fold-search nil)
13806 (org-odd-levels-only odd))
13807 ;; create local variables for all options, to make sure all called
13808 ;; functions get the correct information
13809 (mapcar (lambda (x)
13810 (set (make-local-variable (cdr x))
13811 (plist-get opt-plist (car x))))
13812 org-export-plist-vars)
13813 (setq umax (if arg (prefix-numeric-value arg)
13814 org-export-headline-levels))
13815
13816 ;; File header
13817 (insert (format
13818 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
13819 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
13820 <html xmlns=\"http://www.w3.org/1999/xhtml\"
13821 lang=\"%s\" xml:lang=\"%s\">
13822 <head>
13823 <title>%s</title>
13824 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
13825 <meta name=\"generator\" content=\"Org-mode\"/>
13826 <meta name=\"generated\" content=\"%s %s\"/>
13827 <meta name=\"author\" content=\"%s\"/>
13828 %s
13829 </head><body>
13830 "
13831 language language (org-html-expand title) (or charset "iso-8859-1")
13832 date time author style))
13833
13834
13835 (insert (or (plist-get opt-plist :preamble) ""))
13836
13837 (when (plist-get opt-plist :auto-preamble)
13838 (if title (insert (concat "<h1 class=\"title\">"
13839 (org-html-expand title) "</h1>\n")))
13840
13841 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
13842
13843 (if org-export-with-toc
13844 (progn
13845 (insert (format "<h2>%s</h2>\n" (nth 3 lang-words)))
13846 (insert "<ul>\n<li>")
13847 (setq lines
13848 (mapcar '(lambda (line)
13849 (if (string-match org-todo-line-regexp line)
13850 ;; This is a headline
13851 (progn
13852 (setq level (- (match-end 1) (match-beginning 1))
13853 level (org-tr-level level)
13854 txt (save-match-data
13855 (org-html-expand
13856 (org-export-cleanup-toc-line
13857 (match-string 3 line))))
13858 todo
13859 (or (and org-export-mark-todo-in-toc
13860 (match-beginning 2)
13861 (not (equal (match-string 2 line)
13862 org-done-string)))
13863 ; TODO, not DONE
13864 (and org-export-mark-todo-in-toc
13865 (= level umax)
13866 (org-search-todo-below
13867 line lines level))))
13868 (if org-export-with-section-numbers
13869 (setq txt (concat (org-section-number level)
13870 " " txt)))
13871 (if (<= level umax)
13872 (progn
13873 (setq head-count (+ head-count 1))
13874 (if (> level org-last-level)
13875 (progn
13876 (setq cnt (- level org-last-level))
13877 (while (>= (setq cnt (1- cnt)) 0)
13878 (insert "\n<ul>\n<li>"))
13879 (insert "\n")))
13880 (if (< level org-last-level)
13881 (progn
13882 (setq cnt (- org-last-level level))
13883 (while (>= (setq cnt (1- cnt)) 0)
13884 (insert "</li>\n</ul>"))
13885 (insert "\n")))
13886 ;; Check for targets
13887 (while (string-match org-target-regexp line)
13888 (setq tg (match-string 1 line)
13889 line (replace-match
13890 (concat "@<span class=\"target\">" tg "@</span> ")
13891 t t line))
13892 (push (cons (org-solidify-link-text tg)
13893 (format "sec-%d" head-count))
13894 target-alist))
13895 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
13896 (setq txt (replace-match "" t t txt)))
13897 (insert
13898 (format
13899 (if todo
13900 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
13901 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
13902 head-count txt))
13903
13904 (setq org-last-level level))
13905 )))
13906 line)
13907 lines))
13908 (while (> org-last-level 0)
13909 (setq org-last-level (1- org-last-level))
13910 (insert "</li>\n</ul>\n"))
13911 ))
13912 (setq head-count 0)
13913 (org-init-section-numbers)
13914
13915 (while (setq line (pop lines) origline line)
13916 (catch 'nextline
13917
13918 ;; end of quote section?
13919 (when (and inquote (string-match "^\\*+" line))
13920 (insert "</pre>\n")
13921 (setq inquote nil))
13922 ;; inside a quote section?
13923 (when inquote
13924 (insert (org-html-protect line) "\n")
13925 (throw 'nextline nil))
13926
13927 ;; verbatim lines
13928 (when (and org-export-with-fixed-width
13929 (string-match "^[ \t]*:\\(.*\\)" line))
13930 (when (not infixed)
13931 (setq infixed t)
13932 (insert "<pre>\n"))
13933 (insert (org-html-protect (match-string 1 line)) "\n")
13934 (when (and lines
13935 (not (string-match "^[ \t]*\\(:.*\\)"
13936 (car lines))))
13937 (setq infixed nil)
13938 (insert "</pre>\n"))
13939 (throw 'nextline nil))
13940
13941
13942 ;; make targets to anchors
13943 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
13944 (cond
13945 ((match-end 2)
13946 (setq line (replace-match
13947 (concat "@<a name=\""
13948 (org-solidify-link-text (match-string 1 line))
13949 "\">\\nbsp@</a>")
13950 t t line)))
13951 ((and org-export-with-toc (equal (string-to-char line) ?*))
13952 (setq line (replace-match
13953 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
13954 ; (concat "@<i>" (match-string 1 line) "@</i> ")
13955 t t line)))
13956 (t
13957 (setq line (replace-match
13958 (concat "@<a name=\""
13959 (org-solidify-link-text (match-string 1 line))
13960 "\" class=\"target\">" (match-string 1 line) "@</a> ")
13961 t t line)))))
13962
13963 (setq line (org-html-handle-time-stamps line))
13964
13965 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
13966 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
13967 ;; Also handle sub_superscripts and checkboxes
13968 (setq line (org-html-expand line))
13969
13970 ;; Format the links
13971 (setq start 0)
13972 (while (string-match org-bracket-link-analytic-regexp line start)
13973 (setq start (match-beginning 0))
13974 (setq type (if (match-end 2) (match-string 2 line) "internal"))
13975 (setq path (match-string 3 line))
13976 (setq desc1 (if (match-end 5) (match-string 5 line))
13977 desc2 (if (match-end 2) (concat type ":" path) path)
13978 descp (and desc1 (not (equal desc1 desc2)))
13979 desc (or desc1 desc2))
13980 ;; FIXME: do we need to unescape here somewhere?
13981 (cond
13982 ((equal type "internal")
13983 (setq rpl
13984 (concat
13985 "<a href=\"#"
13986 (org-solidify-link-text path target-alist)
13987 "\">" desc "</a>")))
13988 ((member type '("http" "https" "ftp" "mailto" "news"))
13989 ;; standard URL
13990 (setq link (concat type ":" path))
13991 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
13992 ((string= type "file")
13993 ;; FILE link
13994 (let* ((filename path)
13995 (abs-p (file-name-absolute-p filename))
13996 thefile file-is-image-p search)
13997 (save-match-data
13998 (if (string-match "::\\(.*\\)" filename)
13999 (setq search (match-string 1 filename)
14000 filename (replace-match "" t nil filename)))
14001 (setq valid
14002 (if (functionp link-validate)
14003 (funcall link-validate filename current-dir)
14004 t))
14005 (setq file-is-image-p
14006 (string-match (org-image-file-name-regexp) filename))
14007 (setq thefile (if abs-p (expand-file-name filename) filename))
14008 (when (and org-export-html-link-org-files-as-html
14009 (string-match "\\.org$" thefile))
14010 (setq thefile (concat (substring thefile 0
14011 (match-beginning 0))
14012 ".html"))
14013 (if (and search
14014 ;; make sure this is can be used as target search
14015 (not (string-match "^[0-9]*$" search))
14016 (not (string-match "^\\*" search))
14017 (not (string-match "^/.*/$" search)))
14018 (setq thefile (concat thefile "#"
14019 (org-solidify-link-text
14020 (org-link-unescape search)))))
14021 (when (string-match "^file:" desc)
14022 (setq desc (replace-match "" t t desc))
14023 (if (string-match "\\.org$" desc)
14024 (setq desc (replace-match "" t t desc))))))
14025 (setq rpl (if (and file-is-image-p
14026 (or (eq t org-export-html-inline-images)
14027 (and org-export-html-inline-images
14028 (not descp))))
14029 (concat "<img src=\"" thefile "\"/>")
14030 (concat "<a href=\"" thefile "\">" desc "</a>")))
14031 (if (not valid) (setq rpl desc))))
14032 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
14033 (setq rpl (concat "<i>&lt;" type ":"
14034 (save-match-data (org-link-unescape path))
14035 "&gt;</i>"))))
14036 (setq line (replace-match rpl t t line)
14037 start (+ start (length rpl))))
14038 ;; TODO items
14039 (if (and (string-match org-todo-line-regexp line)
14040 (match-beginning 2))
14041 (if (equal (match-string 2 line) org-done-string)
14042 (setq line (replace-match
14043 "<span class=\"done\">\\2</span>"
14044 t nil line 2))
14045 (setq line (replace-match "<span class=\"todo\">\\2</span>"
14046 t nil line 2))))
14047
14048 (cond
14049 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14050 ;; This is a headline
14051 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14052 txt (match-string 2 line))
14053 (if (string-match quote-re0 txt)
14054 (setq txt (replace-match "" t t txt)))
14055 (if (<= level umax) (setq head-count (+ head-count 1)))
14056 (when in-local-list
14057 ;; Close any local lists before inserting a new header line
14058 (while local-list-num
14059 (org-close-li)
14060 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14061 (pop local-list-num))
14062 (setq local-list-indent nil
14063 in-local-list nil))
14064 (org-html-level-start level txt umax
14065 (and org-export-with-toc (<= level umax))
14066 head-count)
14067 ;; QUOTES
14068 (when (string-match quote-re line)
14069 (insert "<pre>")
14070 (setq inquote t)))
14071
14072 ((and org-export-with-tables
14073 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
14074 (if (not table-open)
14075 ;; New table starts
14076 (setq table-open t table-buffer nil table-orig-buffer nil))
14077 ;; Accumulate lines
14078 (setq table-buffer (cons line table-buffer)
14079 table-orig-buffer (cons origline table-orig-buffer))
14080 (when (or (not lines)
14081 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
14082 (car lines))))
14083 (setq table-open nil
14084 table-buffer (nreverse table-buffer)
14085 table-orig-buffer (nreverse table-orig-buffer))
14086 (org-close-par-maybe)
14087 (insert (org-format-table-html table-buffer table-orig-buffer))))
14088 (t
14089 ;; Normal lines
14090 (when (string-match
14091 (cond
14092 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14093 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14094 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14095 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
14096 line)
14097 (setq ind (org-get-string-indentation line)
14098 start-is-num (match-beginning 4)
14099 starter (if (match-beginning 2)
14100 (substring (match-string 2 line) 0 -1))
14101 line (substring line (match-beginning 5)))
14102 (unless (string-match "[^ \t]" line)
14103 ;; empty line. Pretend indentation is large.
14104 (setq ind (1+ (or (car local-list-indent) 1))))
14105 (while (and in-local-list
14106 (or (and (= ind (car local-list-indent))
14107 (not starter))
14108 (< ind (car local-list-indent))))
14109 (org-close-li)
14110 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14111 (pop local-list-num) (pop local-list-indent)
14112 (setq in-local-list local-list-indent))
14113 (cond
14114 ((and starter
14115 (or (not in-local-list)
14116 (> ind (car local-list-indent))))
14117 ;; Start new (level of ) list
14118 (org-close-par-maybe)
14119 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
14120 (push start-is-num local-list-num)
14121 (push ind local-list-indent)
14122 (setq in-local-list t))
14123 (starter
14124 ;; continue current list
14125 (org-close-li)
14126 (insert "<li>\n")))
14127 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
14128 (setq line
14129 (replace-match
14130 (if (equal (match-string 1 line) "X")
14131 "<b>[X]</b>"
14132 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
14133 t t line))))
14134
14135 ;; Empty lines start a new paragraph. If hand-formatted lists
14136 ;; are not fully interpreted, lines starting with "-", "+", "*"
14137 ;; also start a new paragraph.
14138 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
14139
14140 ;; Check if the line break needs to be conserved
14141 (cond
14142 ((string-match "\\\\\\\\[ \t]*$" line)
14143 (setq line (replace-match "<br/>" t t line)))
14144 (org-export-preserve-breaks
14145 (setq line (concat line "<br/>"))))
14146
14147 (insert line "\n")))))
14148
14149 ;; Properly close all local lists and other lists
14150 (when inquote (insert "</pre>\n"))
14151 (when in-local-list
14152 ;; Close any local lists before inserting a new header line
14153 (while local-list-num
14154 (org-close-li)
14155 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
14156 (pop local-list-num))
14157 (setq local-list-indent nil
14158 in-local-list nil))
14159 (org-html-level-start 1 nil umax
14160 (and org-export-with-toc (<= level umax))
14161 head-count)
14162
14163 (when (plist-get opt-plist :auto-postamble)
14164 (when author
14165 (insert "<p class=\"author\"> "
14166 (nth 1 lang-words) ": " author "\n")
14167 (when email
14168 (insert "<a href=\"mailto:" email "\">&lt;"
14169 email "&gt;</a>\n"))
14170 (insert "</p>\n"))
14171 (when (and date time)
14172 (insert "<p class=\"date\"> "
14173 (nth 2 lang-words) ": "
14174 date " " time "</p>\n")))
14175
14176 (if org-export-html-with-timestamp
14177 (insert org-export-html-html-helper-timestamp))
14178 (insert (or (plist-get opt-plist :postamble) ""))
14179 (insert "</body>\n</html>\n")
14180 (normal-mode)
14181 ;; remove empty paragraphs and lists
14182 (goto-char (point-min))
14183 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
14184 (replace-match ""))
14185 (goto-char (point-min))
14186 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
14187 (replace-match ""))
14188 (save-buffer)
14189 (goto-char (point-min))
14190 (message "Exporting... done"))))
14191
14192
14193 (defun org-format-table-html (lines olines)
14194 "Find out which HTML converter to use and return the HTML code."
14195 (if (string-match "^[ \t]*|" (car lines))
14196 ;; A normal org table
14197 (org-format-org-table-html lines)
14198 ;; Table made by table.el - test for spanning
14199 (let* ((hlines (delq nil (mapcar
14200 (lambda (x)
14201 (if (string-match "^[ \t]*\\+-" x) x
14202 nil))
14203 lines)))
14204 (first (car hlines))
14205 (ll (and (string-match "\\S-+" first)
14206 (match-string 0 first)))
14207 (re (concat "^[ \t]*" (regexp-quote ll)))
14208 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
14209 hlines))))
14210 (if (and (not spanning)
14211 (not org-export-prefer-native-exporter-for-tables))
14212 ;; We can use my own converter with HTML conversions
14213 (org-format-table-table-html lines)
14214 ;; Need to use the code generator in table.el, with the original text.
14215 (org-format-table-table-html-using-table-generate-source olines)))))
14216
14217 (defun org-format-org-table-html (lines)
14218 "Format a table into HTML."
14219 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14220 (setq lines (nreverse lines))
14221 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14222 (setq lines (nreverse lines))
14223 (when org-export-table-remove-special-lines
14224 ;; Check if the table has a marking column. If yes remove the
14225 ;; column and the special lines
14226 (let* ((special
14227 (not
14228 (memq nil
14229 (mapcar
14230 (lambda (x)
14231 (or (string-match "^[ \t]*|-" x)
14232 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
14233 lines)))))
14234 (if special
14235 (setq lines
14236 (delq nil
14237 (mapcar
14238 (lambda (x)
14239 (if (string-match "^[ \t]*| *[!_^] *|" x)
14240 nil ; ignore this line
14241 (and (or (string-match "^[ \t]*|-+\\+" x)
14242 (string-match "^[ \t]*|[^|]*|" x))
14243 (replace-match "|" t t x))))
14244 lines))))))
14245
14246 (let ((head (and org-export-highlight-first-table-line
14247 (delq nil (mapcar
14248 (lambda (x) (string-match "^[ \t]*|-" x))
14249 (cdr lines)))))
14250 line fields html)
14251 (setq html (concat org-export-html-table-tag "\n"))
14252 (while (setq line (pop lines))
14253 (catch 'next-line
14254 (if (string-match "^[ \t]*|-" line)
14255 (progn
14256 (setq head nil) ;; head ends here, first time around
14257 ;; ignore this line
14258 (throw 'next-line t)))
14259 ;; Break the line into fields
14260 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14261 (setq html (concat
14262 html
14263 "<tr>"
14264 (mapconcat (lambda (x)
14265 (if head
14266 (concat "<th>" x "</th>")
14267 (concat "<td>" x "</td>")))
14268 fields "")
14269 "</tr>\n"))))
14270 (setq html (concat html "</table>\n"))
14271 html))
14272
14273 (defun org-fake-empty-table-line (line)
14274 "Replace everything except \"|\" with spaces."
14275 (let ((i (length line))
14276 (newstr (copy-sequence line)))
14277 (while (> i 0)
14278 (setq i (1- i))
14279 (if (not (eq (aref newstr i) ?|))
14280 (aset newstr i ?\ )))
14281 newstr))
14282
14283 (defun org-format-table-table-html (lines)
14284 "Format a table generated by table.el into HTML.
14285 This conversion does *not* use `table-generate-source' from table.el.
14286 This has the advantage that Org-mode's HTML conversions can be used.
14287 But it has the disadvantage, that no cell- or row-spanning is allowed."
14288 (let (line field-buffer
14289 (head org-export-highlight-first-table-line)
14290 fields html empty)
14291 (setq html (concat org-export-html-table-tag "\n"))
14292 (while (setq line (pop lines))
14293 (setq empty "&nbsp;")
14294 (catch 'next-line
14295 (if (string-match "^[ \t]*\\+-" line)
14296 (progn
14297 (if field-buffer
14298 (progn
14299 (setq html (concat
14300 html
14301 "<tr>"
14302 (mapconcat
14303 (lambda (x)
14304 (if (equal x "") (setq x empty))
14305 (if head
14306 (concat "<th>" x "</th>\n")
14307 (concat "<td>" x "</td>\n")))
14308 field-buffer "\n")
14309 "</tr>\n"))
14310 (setq head nil)
14311 (setq field-buffer nil)))
14312 ;; Ignore this line
14313 (throw 'next-line t)))
14314 ;; Break the line into fields and store the fields
14315 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14316 (if field-buffer
14317 (setq field-buffer (mapcar
14318 (lambda (x)
14319 (concat x "<br/>" (pop fields)))
14320 field-buffer))
14321 (setq field-buffer fields))))
14322 (setq html (concat html "</table>\n"))
14323 html))
14324
14325 (defun org-format-table-table-html-using-table-generate-source (lines)
14326 "Format a table into html, using `table-generate-source' from table.el.
14327 This has the advantage that cell- or row-spanning is allowed.
14328 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
14329 (require 'table)
14330 (with-current-buffer (get-buffer-create " org-tmp1 ")
14331 (erase-buffer)
14332 (insert (mapconcat 'identity lines "\n"))
14333 (goto-char (point-min))
14334 (if (not (re-search-forward "|[^+]" nil t))
14335 (error "Error processing table"))
14336 (table-recognize-table)
14337 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
14338 (table-generate-source 'html " org-tmp2 ")
14339 (set-buffer " org-tmp2 ")
14340 (buffer-substring (point-min) (point-max))))
14341
14342 (defun org-html-handle-time-stamps (s)
14343 "Format time stamps in string S, or remove them."
14344 (catch 'exit
14345 (let (r b)
14346 (while (string-match org-maybe-keyword-time-regexp s)
14347 ;; FIXME: is it good to never export CLOCK, or do we need control?
14348 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
14349 (throw 'exit ""))
14350 (or b (setq b (substring s 0 (match-beginning 0))))
14351 (if (not org-export-with-timestamps)
14352 (setq r (concat r (substring s 0 (match-beginning 0)))
14353 s (substring s (match-end 0)))
14354 (setq r (concat
14355 r (substring s 0 (match-beginning 0))
14356 (if (match-end 1)
14357 (format "@<span class=\"timestamp-kwd\">%s @</span>"
14358 (match-string 1 s)))
14359 (format " @<span class=\"timestamp\">%s@</span>"
14360 (substring (match-string 3 s) 1 -1)))
14361 s (substring s (match-end 0)))))
14362 ;; Line break if line started and ended with time stamp stuff
14363 (if (not r)
14364 s
14365 (setq r (concat r s))
14366 (unless (string-match "\\S-" (concat b s))
14367 (setq r (concat r "@<br/>")))
14368 r))))
14369
14370 (defun org-html-protect (s)
14371 ;; convert & to &amp;, < to &lt; and > to &gt;
14372 (let ((start 0))
14373 (while (string-match "&" s start)
14374 (setq s (replace-match "&amp;" t t s)
14375 start (1+ (match-beginning 0))))
14376 (while (string-match "<" s)
14377 (setq s (replace-match "&lt;" t t s)))
14378 (while (string-match ">" s)
14379 (setq s (replace-match "&gt;" t t s))))
14380 s)
14381
14382 (defun org-export-cleanup-toc-line (s)
14383 "Remove tags and time staps from lines going into the toc."
14384 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
14385 (setq s (replace-match "" t t s)))
14386 (when org-export-remove-timestamps-from-toc
14387 (while (string-match org-maybe-keyword-time-regexp s)
14388 (setq s (replace-match "" t t s))))
14389 s)
14390
14391 (defun org-html-expand (string)
14392 "Prepare STRING for HTML export. Applies all active conversions.
14393 If there are links in the string, don't modify these."
14394 (let* (m s l res)
14395 (while (setq m (string-match org-bracket-link-regexp string))
14396 (setq s (substring string 0 m)
14397 l (match-string 0 string)
14398 string (substring string (match-end 0)))
14399 (push (org-html-do-expand s) res)
14400 (push l res))
14401 (push (org-html-do-expand string) res)
14402 (apply 'concat (nreverse res))))
14403
14404 (defun org-html-do-expand (s)
14405 "Apply all active conversions to translate special ASCII to HTML."
14406 (setq s (org-html-protect s))
14407 (if org-export-html-expand
14408 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
14409 (setq s (replace-match "<\\1>" t nil s))))
14410 (if org-export-with-emphasize
14411 (setq s (org-export-html-convert-emphasize s)))
14412 (if org-export-with-sub-superscripts
14413 (setq s (org-export-html-convert-sub-super s)))
14414 (if org-export-with-TeX-macros
14415 (let ((start 0) wd ass)
14416 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
14417 (setq wd (match-string 1 s))
14418 (if (setq ass (assoc wd org-html-entities))
14419 (setq s (replace-match (or (cdr ass)
14420 (concat "&" (car ass) ";"))
14421 t t s))
14422 (setq start (+ start (length wd)))))))
14423 s)
14424
14425 (defun org-create-multibrace-regexp (left right n)
14426 "Create a regular expression which will match a balanced sexp.
14427 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
14428 as single character strings.
14429 The regexp returned will match the entire expression including the
14430 delimiters. It will also define a single group which contains the
14431 match except for the outermost delimiters. The maximum depth of
14432 stacked delimiters is N. Escaping delimiters is not possible."
14433 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
14434 (or "\\|")
14435 (re nothing)
14436 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
14437 (while (> n 1)
14438 (setq n (1- n)
14439 re (concat re or next)
14440 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
14441 (concat left "\\(" re "\\)" right)))
14442
14443 (defvar org-match-substring-regexp
14444 (concat
14445 "\\([^\\]\\)\\([_^]\\)\\("
14446 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
14447 "\\|"
14448 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
14449 "\\|"
14450 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
14451 "The regular expression matching a sub- or superscript.")
14452
14453 (defun org-export-html-convert-sub-super (string)
14454 "Convert sub- and superscripts in STRING to HTML."
14455 (let (key c)
14456 (while (string-match org-match-substring-regexp string)
14457 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
14458 (setq c (or (match-string 8 string)
14459 (match-string 6 string)
14460 (match-string 5 string)))
14461 (setq string (replace-match
14462 (concat (match-string 1 string)
14463 "<" key ">" c "</" key ">")
14464 t t string)))
14465 (while (string-match "\\\\\\([_^]\\)" string)
14466 (setq string (replace-match (match-string 1 string) t t string))))
14467 string)
14468
14469 (defun org-export-html-convert-emphasize (string)
14470 "Apply emphasis."
14471 (while (string-match org-emph-re string)
14472 (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)))
14473 string)
14474
14475 (defvar org-par-open nil)
14476 (defun org-open-par ()
14477 "Insert <p>, but first close previous paragraph if any."
14478 (org-close-par-maybe)
14479 (insert "\n<p>")
14480 (setq org-par-open t))
14481 (defun org-close-par-maybe ()
14482 "Close paragraph if there is one open."
14483 (when org-par-open
14484 (insert "</p>")
14485 (setq org-par-open nil)))
14486 (defun org-close-li ()
14487 "Close <li> if necessary."
14488 (org-close-par-maybe)
14489 (insert "</li>\n"))
14490 ; (when (save-excursion
14491 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
14492 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
14493 ; (insert "</li>"))))
14494
14495 (defun org-html-level-start (level title umax with-toc head-count)
14496 "Insert a new level in HTML export.
14497 When TITLE is nil, just close all open levels."
14498 (org-close-par-maybe)
14499 (let ((l (1+ (max level umax))))
14500 (while (<= l org-level-max)
14501 (if (aref levels-open (1- l))
14502 (progn
14503 (org-html-level-close l)
14504 (aset levels-open (1- l) nil)))
14505 (setq l (1+ l)))
14506 (when title
14507 ;; If title is nil, this means this function is called to close
14508 ;; all levels, so the rest is done only if title is given
14509 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14510 (setq title (replace-match
14511 (if org-export-with-tags
14512 (save-match-data
14513 (concat
14514 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
14515 (mapconcat 'identity (org-split-string
14516 (match-string 1 title) ":")
14517 "&nbsp;")
14518 "</span>"))
14519 "")
14520 t t title)))
14521 (if (> level umax)
14522 (progn
14523 (if (aref levels-open (1- level))
14524 (progn
14525 (org-close-li)
14526 (insert "<li>" title "<br/>\n"))
14527 (aset levels-open (1- level) t)
14528 (org-close-par-maybe)
14529 (insert "<ul>\n<li>" title "<br/>\n")))
14530 (if org-export-with-section-numbers
14531 (setq title (concat (org-section-number level) " " title)))
14532 (setq level (+ level 1))
14533 (if with-toc
14534 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
14535 level head-count title level))
14536 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
14537 (org-open-par)))))
14538
14539 (defun org-html-level-close (&rest args)
14540 "Terminate one level in HTML export."
14541 (org-close-li)
14542 (insert "</ul>"))
14543
14544 ;; Variable holding the vector with section numbers
14545 (defvar org-section-numbers (make-vector org-level-max 0))
14546
14547 (defun org-init-section-numbers ()
14548 "Initialize the vector for the section numbers."
14549 (let* ((level -1)
14550 (numbers (nreverse (org-split-string "" "\\.")))
14551 (depth (1- (length org-section-numbers)))
14552 (i depth) number-string)
14553 (while (>= i 0)
14554 (if (> i level)
14555 (aset org-section-numbers i 0)
14556 (setq number-string (or (car numbers) "0"))
14557 (if (string-match "\\`[A-Z]\\'" number-string)
14558 (aset org-section-numbers i
14559 (- (string-to-char number-string) ?A -1))
14560 (aset org-section-numbers i (string-to-number number-string)))
14561 (pop numbers))
14562 (setq i (1- i)))))
14563
14564 (defun org-section-number (&optional level)
14565 "Return a string with the current section number.
14566 When LEVEL is non-nil, increase section numbers on that level."
14567 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
14568 (when level
14569 (when (> level -1)
14570 (aset org-section-numbers
14571 level (1+ (aref org-section-numbers level))))
14572 (setq idx (1+ level))
14573 (while (<= idx depth)
14574 (if (not (= idx 1))
14575 (aset org-section-numbers idx 0))
14576 (setq idx (1+ idx))))
14577 (setq idx 0)
14578 (while (<= idx depth)
14579 (setq n (aref org-section-numbers idx))
14580 (setq string (concat string (if (not (string= string "")) "." "")
14581 (int-to-string n)))
14582 (setq idx (1+ idx)))
14583 (save-match-data
14584 (if (string-match "\\`\\([@0]\\.\\)+" string)
14585 (setq string (replace-match "" t nil string)))
14586 (if (string-match "\\(\\.0\\)+\\'" string)
14587 (setq string (replace-match "" t nil string))))
14588 string))
14589
14590
14591 ;;;###autoload
14592 (defun org-export-icalendar-this-file ()
14593 "Export current file as an iCalendar file.
14594 The iCalendar file will be located in the same directory as the Org-mode
14595 file, but with extension `.ics'."
14596 (interactive)
14597 (org-export-icalendar nil buffer-file-name))
14598
14599 (defun org-export-as-xoxo-insert-into (buffer &rest output)
14600 (with-current-buffer buffer
14601 (apply 'insert output)))
14602
14603 (defun org-export-as-xoxo (&optional buffer)
14604 "Export the org buffer as XOXO.
14605 The XOXO buffer is named *xoxo-<source buffer name>*"
14606 (interactive (list (current-buffer)))
14607 ;; A quickie abstraction
14608
14609 ;; Output everything as XOXO
14610 (with-current-buffer (get-buffer buffer)
14611 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
14612 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14613 (org-infile-export-plist)))
14614 (filename (concat (file-name-as-directory
14615 (org-export-directory :xoxo opt-plist))
14616 (file-name-sans-extension
14617 (file-name-nondirectory buffer-file-name))
14618 ".html"))
14619 (out (find-file-noselect filename))
14620 (last-level 1)
14621 (hanging-li nil))
14622 ;; Check the output buffer is empty.
14623 (with-current-buffer out (erase-buffer))
14624 ;; Kick off the output
14625 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
14626 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
14627 (let* ((hd (match-string-no-properties 1))
14628 (level (length hd))
14629 (text (concat
14630 (match-string-no-properties 2)
14631 (save-excursion
14632 (goto-char (match-end 0))
14633 (let ((str ""))
14634 (catch 'loop
14635 (while 't
14636 (forward-line)
14637 (if (looking-at "^[ \t]\\(.*\\)")
14638 (setq str (concat str (match-string-no-properties 1)))
14639 (throw 'loop str)))))))))
14640
14641 ;; Handle level rendering
14642 (cond
14643 ((> level last-level)
14644 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
14645
14646 ((< level last-level)
14647 (dotimes (- (- last-level level) 1)
14648 (if hanging-li
14649 (org-export-as-xoxo-insert-into out "</li>\n"))
14650 (org-export-as-xoxo-insert-into out "</ol>\n"))
14651 (when hanging-li
14652 (org-export-as-xoxo-insert-into out "</li>\n")
14653 (setq hanging-li nil)))
14654
14655 ((equal level last-level)
14656 (if hanging-li
14657 (org-export-as-xoxo-insert-into out "</li>\n")))
14658 )
14659
14660 (setq last-level level)
14661
14662 ;; And output the new li
14663 (setq hanging-li 't)
14664 (if (equal ?+ (elt text 0))
14665 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
14666 (org-export-as-xoxo-insert-into out "<li>" text))))
14667
14668 ;; Finally finish off the ol
14669 (dotimes (- last-level 1)
14670 (if hanging-li
14671 (org-export-as-xoxo-insert-into out "</li>\n"))
14672 (org-export-as-xoxo-insert-into out "</ol>\n"))
14673
14674 ;; Finish the buffer off and clean it up.
14675 (switch-to-buffer-other-window out)
14676 (indent-region (point-min) (point-max) nil)
14677 (save-buffer)
14678 (goto-char (point-min))
14679 )))
14680
14681 ;;;###autoload
14682 (defun org-export-icalendar-all-agenda-files ()
14683 "Export all files in `org-agenda-files' to iCalendar .ics files.
14684 Each iCalendar file will be located in the same directory as the Org-mode
14685 file, but with extension `.ics'."
14686 (interactive)
14687 (apply 'org-export-icalendar nil (org-agenda-files t)))
14688
14689 ;;;###autoload
14690 (defun org-export-icalendar-combine-agenda-files ()
14691 "Export all files in `org-agenda-files' to a single combined iCalendar file.
14692 The file is stored under the name `org-combined-agenda-icalendar-file'."
14693 (interactive)
14694 (apply 'org-export-icalendar t (org-agenda-files t)))
14695
14696 (defun org-export-icalendar (combine &rest files)
14697 "Create iCalendar files for all elements of FILES.
14698 If COMBINE is non-nil, combine all calendar entries into a single large
14699 file and store it under the name `org-combined-agenda-icalendar-file'."
14700 (save-excursion
14701 (let* ((dir (org-export-directory
14702 :ical (list :publishing-directory
14703 org-export-publishing-directory)))
14704 file ical-file ical-buffer category started org-agenda-new-buffers)
14705
14706 (when combine
14707 (setq ical-file
14708 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
14709 org-combined-agenda-icalendar-file
14710 (expand-file-name org-combined-agenda-icalendar-file dir))
14711 ical-buffer (org-get-agenda-file-buffer ical-file))
14712 (set-buffer ical-buffer) (erase-buffer))
14713 (while (setq file (pop files))
14714 (catch 'nextfile
14715 (org-check-agenda-file file)
14716 (set-buffer (org-get-agenda-file-buffer file))
14717 (unless combine
14718 (setq ical-file (concat (file-name-as-directory dir)
14719 (file-name-sans-extension
14720 (file-name-nondirectory buffer-file-name))
14721 ".ics"))
14722 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
14723 (with-current-buffer ical-buffer (erase-buffer)))
14724 (setq category (or org-category
14725 (file-name-sans-extension
14726 (file-name-nondirectory buffer-file-name))))
14727 (if (symbolp category) (setq category (symbol-name category)))
14728 (let ((standard-output ical-buffer))
14729 (if combine
14730 (and (not started) (setq started t)
14731 (org-start-icalendar-file org-icalendar-combined-name))
14732 (org-start-icalendar-file category))
14733 (org-print-icalendar-entries combine category)
14734 (when (or (and combine (not files)) (not combine))
14735 (org-finish-icalendar-file)
14736 (set-buffer ical-buffer)
14737 (save-buffer)
14738 (run-hooks 'org-after-save-iCalendar-file-hook)))))
14739 (org-release-buffers org-agenda-new-buffers))))
14740
14741 (defvar org-after-save-iCalendar-file-hook nil
14742 "Hook run after an iCalendar file has been saved.
14743 The iCalendar buffer is still current when this hook is run.
14744 A good way to use this is to tell a desktop calenndar application to re-read
14745 the iCalendar file.")
14746
14747 (defun org-print-icalendar-entries (&optional combine category)
14748 "Print iCalendar entries for the current Org-mode file to `standard-output'.
14749 When COMBINE is non nil, add the category to each line."
14750 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
14751 (dts (org-ical-ts-to-string
14752 (format-time-string (cdr org-time-stamp-formats) (current-time))
14753 "DTSTART"))
14754 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
14755 (save-excursion
14756 (goto-char (point-min))
14757 (while (re-search-forward org-ts-regexp nil t)
14758 (setq pos (match-beginning 0)
14759 ts (match-string 0)
14760 inc t
14761 hd (org-get-heading))
14762 (if (looking-at re2)
14763 (progn
14764 (goto-char (match-end 0))
14765 (setq ts2 (match-string 1) inc nil))
14766 (setq ts2 ts
14767 tmp (buffer-substring (max (point-min)
14768 (- pos org-ds-keyword-length))
14769 pos)
14770 deadlinep (string-match org-deadline-regexp tmp)
14771 scheduledp (string-match org-scheduled-regexp tmp)
14772 ;; donep (org-entry-is-done-p)
14773 ))
14774 (if (or (string-match org-tr-regexp hd)
14775 (string-match org-ts-regexp hd))
14776 (setq hd (replace-match "" t t hd)))
14777 (if combine
14778 (setq hd (concat hd " (category " category ")")))
14779 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
14780 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
14781 (princ (format "BEGIN:VEVENT
14782 %s
14783 %s
14784 SUMMARY:%s
14785 END:VEVENT\n"
14786 (org-ical-ts-to-string ts "DTSTART")
14787 (org-ical-ts-to-string ts2 "DTEND" inc)
14788 hd)))
14789 (when org-icalendar-include-todo
14790 (goto-char (point-min))
14791 (while (re-search-forward org-todo-line-regexp nil t)
14792 (setq state (match-string 1))
14793 (unless (equal state org-done-string)
14794 (setq hd (match-string 3))
14795 (if (string-match org-priority-regexp hd)
14796 (setq pri (string-to-char (match-string 2 hd))
14797 hd (concat (substring hd 0 (match-beginning 1))
14798 (substring hd (- (match-end 1)))))
14799 (setq pri org-default-priority))
14800 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
14801 (- org-lowest-priority ?A))))))
14802
14803 (princ (format "BEGIN:VTODO
14804 %s
14805 SUMMARY:%s
14806 SEQUENCE:1
14807 PRIORITY:%d
14808 END:VTODO\n"
14809 dts hd pri))))))))
14810
14811 (defun org-start-icalendar-file (name)
14812 "Start an iCalendar file by inserting the header."
14813 (let ((user user-full-name)
14814 (name (or name "unknown"))
14815 (timezone (cadr (current-time-zone))))
14816 (princ
14817 (format "BEGIN:VCALENDAR
14818 VERSION:2.0
14819 X-WR-CALNAME:%s
14820 PRODID:-//%s//Emacs with Org-mode//EN
14821 X-WR-TIMEZONE:%s
14822 CALSCALE:GREGORIAN\n" name user timezone))))
14823
14824 (defun org-finish-icalendar-file ()
14825 "Finish an iCalendar file by inserting the END statement."
14826 (princ "END:VCALENDAR\n"))
14827
14828 (defun org-ical-ts-to-string (s keyword &optional inc)
14829 "Take a time string S and convert it to iCalendar format.
14830 KEYWORD is added in front, to make a complete line like DTSTART....
14831 When INC is non-nil, increase the hour by two (if time string contains
14832 a time), or the day by one (if it does not contain a time)."
14833 (let ((t1 (org-parse-time-string s 'nodefault))
14834 t2 fmt have-time time)
14835 (if (and (car t1) (nth 1 t1) (nth 2 t1))
14836 (setq t2 t1 have-time t)
14837 (setq t2 (org-parse-time-string s)))
14838 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
14839 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
14840 (when inc
14841 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
14842 (setq time (encode-time s mi h d m y)))
14843 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
14844 (concat keyword (format-time-string fmt time))))
14845
14846 ;;; LaTeX stuff
14847
14848 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14849 "Keymap for the minor `org-cdlatex-mode'.")
14850
14851 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14852 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14853 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14854 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14855 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14856
14857 (defvar org-cdlatex-texmathp-advice-is-done nil
14858 "Flag remembering if we have applied the advice to texmathp already.")
14859
14860 (define-minor-mode org-cdlatex-mode
14861 "Toggle the minor `org-cdlatex-mode'.
14862 This mode supports entering LaTeX environment and math in LaTeX fragments
14863 in Org-mode.
14864 \\{org-cdlatex-mode-map}"
14865 nil " OCDL" nil
14866 (when org-cdlatex-mode (require 'cdlatex))
14867 (unless org-cdlatex-texmathp-advice-is-done
14868 (setq org-cdlatex-texmathp-advice-is-done t)
14869 (defadvice texmathp (around org-math-always-on activate)
14870 "Always return t in org-mode buffers.
14871 This is because we want to insert math symbols without dollars even outside
14872 the LaTeX math segments. If Orgmode thinks that point is actually inside
14873 en embedded LaTeX fragement, let texmathp do its job.
14874 \\[org-cdlatex-mode-map]"
14875 (interactive)
14876 (let (p)
14877 (cond
14878 ((not (eq major-mode 'org-mode)) ad-do-it)
14879 ((eq this-command 'cdlatex-math-symbol)
14880 (setq ad-return-value t
14881 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14882 (t
14883 (let ((p (org-inside-LaTeX-fragment-p)))
14884 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14885 (setq ad-return-value t
14886 texmathp-why '("Org-mode embedded math" . 0))
14887 (if p ad-do-it)))))))))
14888
14889 (defun turn-on-org-cdlatex ()
14890 "Unconditionally turn on `org-cdlatex-mode'."
14891 (org-cdlatex-mode 1))
14892
14893 (defun org-inside-LaTeX-fragment-p ()
14894 "Test if point is inside a LaTeX fragment.
14895 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14896 sequence appearing also before point.
14897 Even though the matchers for math are configurable, this function assumes
14898 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14899 delimiters are skipped when they have been removed by customization.
14900 The return value is nil, or a cons cell with the delimiter and
14901 and the position of this delimiter.
14902
14903 This function does a reasonably good job, but can locally be fooled by
14904 for example currency specifications. For example it will assume being in
14905 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14906 fragments that are properly closed, but during editing, we have to live
14907 with the uncertainty caused by missing closing delimiters. This function
14908 looks only before point, not after."
14909 (catch 'exit
14910 (let ((pos (point))
14911 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14912 (lim (progn
14913 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14914 (point)))
14915 dd-on str (start 0) m re)
14916 (goto-char pos)
14917 (when dodollar
14918 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14919 re (nth 1 (assoc "$" org-latex-regexps)))
14920 (while (string-match re str start)
14921 (cond
14922 ((= (match-end 0) (length str))
14923 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
14924 ((= (match-end 0) (- (length str) 5))
14925 (throw 'exit nil))
14926 (t (setq start (match-end 0))))))
14927 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14928 (goto-char pos)
14929 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14930 (and (match-beginning 2) (throw 'exit nil))
14931 ;; count $$
14932 (while (re-search-backward "\\$\\$" lim t)
14933 (setq dd-on (not dd-on)))
14934 (goto-char pos)
14935 (if dd-on (cons "$$" m))))))
14936
14937
14938 (defun org-try-cdlatex-tab ()
14939 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14940 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14941 - inside a LaTeX fragment, or
14942 - after the first word in a line, where an abbreviation expansion could
14943 insert a LaTeX environment."
14944 ;; FIXME: This may still need refinement.
14945 (when org-cdlatex-mode
14946 (cond
14947 ((save-excursion
14948 (skip-chars-backward "a-zA-Z0-9*")
14949 (skip-chars-backward " \t")
14950 (bolp))
14951 (cdlatex-tab) t)
14952 ((org-inside-LaTeX-fragment-p)
14953 (cdlatex-tab) t)
14954 (t nil))))
14955
14956 (defun org-cdlatex-underscore-caret (&optional arg)
14957 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14958 Revert to the normal definition outside of these fragments."
14959 (interactive "P")
14960 (if (org-inside-LaTeX-fragment-p)
14961 (call-interactively 'cdlatex-sub-superscript)
14962 (let (org-cdlatex-mode)
14963 (call-interactively (key-binding (vector last-input-event))))))
14964
14965 (defun org-cdlatex-math-modify (&optional arg)
14966 "Execute `cdlatex-math-modify' in LaTeX fragments.
14967 Revert to the normal definition outside of these fragments."
14968 (interactive "P")
14969 (if (org-inside-LaTeX-fragment-p)
14970 (call-interactively 'cdlatex-math-modify)
14971 (let (org-cdlatex-mode)
14972 (call-interactively (key-binding (vector last-input-event))))))
14973
14974 (defvar org-latex-fragment-image-overlays nil
14975 "List of overlays carrying the images of latex fragments.")
14976 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14977
14978 (defun org-remove-latex-fragment-image-overlays ()
14979 "Remove all overlays with LaTeX fragment images in current buffer."
14980 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14981 (setq org-latex-fragment-image-overlays nil))
14982
14983 (defun org-preview-latex-fragment (&optional subtree)
14984 "Preview the LaTeX fragment at point, or all locally or globally.
14985 If the cursor is in a LaTeX fragment, create the image and overlay
14986 it over the source code. If there is no fragment at point, display
14987 all fragments in the current text, from one headline to the next. With
14988 prefix SUBTREE, display all fragments in the current subtree. With a
14989 double prefix `C-u C-u', or when the cursor is before the first headline,
14990 display all fragments in the buffer.
14991 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14992 (interactive "P")
14993 (org-remove-latex-fragment-image-overlays)
14994 (save-excursion
14995 (save-restriction
14996 (let (beg end at msg)
14997 (cond
14998 ((or (equal subtree '(16))
14999 (not (save-excursion
15000 (re-search-backward (concat "^" outline-regexp) nil t))))
15001 (setq beg (point-min) end (point-max)
15002 msg "Creating images for buffer...%s"))
15003 ((equal subtree '(4))
15004 (org-back-to-heading)
15005 (setq beg (point) end (org-end-of-subtree)
15006 msg "Creating images for subtree...%s"))
15007 (t
15008 (if (setq at (org-inside-LaTeX-fragment-p))
15009 (goto-char (max (point-min) (- (cdr at) 2)))
15010 (org-back-to-heading))
15011 (setq beg (point) end (progn (outline-next-heading) (point))
15012 msg (if at "Creating image...%s"
15013 "Creating images for entry...%s"))))
15014 (message msg "")
15015 (narrow-to-region beg end)
15016 (org-format-latex
15017 (concat "ltxpng/" (file-name-sans-extension
15018 (file-name-nondirectory
15019 buffer-file-name)))
15020 default-directory 'overlays msg at)
15021 (message msg "done. Use `C-c C-c' to remove images.")))))
15022
15023 (defvar org-latex-regexps
15024 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15025 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15026 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15027 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
15028 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15029 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
15030 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
15031 "Regular expressions for matching embedded LaTeX.")
15032
15033 (defun org-format-latex (prefix &optional dir overlays msg at)
15034 "Replace LaTeX fragments with links to an image, and produce images."
15035 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15036 (let* ((prefixnodir (file-name-nondirectory prefix))
15037 (absprefix (expand-file-name prefix dir))
15038 (todir (file-name-directory absprefix))
15039 (opt org-format-latex-options)
15040 (matchers (plist-get opt :matchers))
15041 (re-list org-latex-regexps)
15042 (cnt 0) txt link beg end re e oldfiles
15043 m n block linkfile movefile ov)
15044 ;; Make sure the directory exists
15045 (or (file-directory-p todir) (make-directory todir))
15046 ;; Check if there are old images files with this prefix, and remove them
15047 (setq oldfiles (directory-files
15048 todir 'full
15049 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
15050 (while oldfiles (delete-file (pop oldfiles)))
15051 ;; Check the different regular expressions
15052 (while (setq e (pop re-list))
15053 (setq m (car e) re (nth 1 e) n (nth 2 e)
15054 block (if (nth 3 e) "\n\n" ""))
15055 (when (member m matchers)
15056 (goto-char (point-min))
15057 (while (re-search-forward re nil t)
15058 (when (or (not at) (equal (cdr at) (match-beginning n)))
15059 (setq txt (match-string n)
15060 beg (match-beginning n) end (match-end n)
15061 cnt (1+ cnt)
15062 linkfile (format "%s_%04d.png" prefix cnt)
15063 movefile (format "%s_%04d.png" absprefix cnt)
15064 link (concat block "[[file:" linkfile "]]" block))
15065 (if msg (message msg cnt))
15066 (goto-char beg)
15067 (org-create-formula-image
15068 txt movefile opt)
15069 (if overlays
15070 (progn
15071 (setq ov (org-make-overlay beg end))
15072 (if (featurep 'xemacs)
15073 (progn
15074 (org-overlay-put ov 'invisible t)
15075 (org-overlay-put
15076 ov 'end-glyph
15077 (make-glyph (vector 'png :file movefile))))
15078 (org-overlay-put
15079 ov 'display
15080 (list 'image :type 'png :file movefile :ascent 'center)))
15081 (push ov org-latex-fragment-image-overlays)
15082 (goto-char end))
15083 (delete-region beg end)
15084 (insert link))))))))
15085
15086 ;; This function borrows from Ganesh Swami's latex2png.el
15087 (defun org-create-formula-image (string tofile options)
15088 (let* ((tmpdir (if (featurep 'xemacs)
15089 (temp-directory)
15090 temporary-file-directory))
15091 (texfilebase (make-temp-name
15092 (expand-file-name "orgtex" tmpdir)))
15093
15094 ;(texfilebase (make-temp-file "orgtex"))
15095 ; (dummy (delete-file texfilebase))
15096 (texfile (concat texfilebase ".tex"))
15097 (dvifile (concat texfilebase ".dvi"))
15098 (pngfile (concat texfilebase ".png"))
15099 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
15100 (fg (or (plist-get options :foreground) "Black"))
15101 (bg (or (plist-get options :background) "Transparent")))
15102 (with-temp-file texfile
15103 (insert "\\documentclass{article}
15104 \\usepackage{fullpage}
15105 \\usepackage{amssymb}
15106 \\usepackage[usenames]{color}
15107 \\usepackage{amsmath}
15108 \\usepackage{latexsym}
15109 \\usepackage[mathscr]{eucal}
15110 \\pagestyle{empty}
15111 \\begin{document}\n" string "\n\\end{document}\n"))
15112 (let ((dir default-directory))
15113 (condition-case nil
15114 (progn
15115 (cd tmpdir)
15116 (call-process "latex" nil nil nil texfile))
15117 (error nil))
15118 (cd dir))
15119 (if (not (file-exists-p dvifile))
15120 (progn (message "Failed to create dvi file from %s" texfile) nil)
15121 (call-process "dvipng" nil nil nil
15122 "-E" "-fg" fg "-bg" bg
15123 "-x" scale "-y" scale "-T" "tight"
15124 "-o" pngfile
15125 dvifile)
15126 (if (not (file-exists-p pngfile))
15127 (progn (message "Failed to create png file from %s" texfile) nil)
15128 ;; Use the requested file name and clean up
15129 (copy-file pngfile tofile 'replace)
15130 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15131 (delete-file (concat texfilebase e)))
15132 pngfile))))
15133
15134 ;;; Key bindings
15135
15136 ;; - Bindings in Org-mode map are currently
15137 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
15138 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
15139 ;; e (?) useful from outline-mode
15140 ;; i k @ expendable from outline-mode
15141 ;; 0123456789 % & ()_{} " ` free
15142
15143 ;; Make `C-c C-x' a prefix key
15144 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
15145
15146 ;; TAB key with modifiers
15147 (define-key org-mode-map "\C-i" 'org-cycle)
15148 (define-key org-mode-map [(tab)] 'org-cycle)
15149 (define-key org-mode-map [(meta tab)] 'org-complete)
15150 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
15151 ;; The following line is necessary under Suse GNU/Linux
15152 (unless (featurep 'xemacs)
15153 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
15154 (define-key org-mode-map [(shift tab)] 'org-shifttab)
15155
15156 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
15157 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
15158 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15159 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
15160 (define-key org-mode-map [(meta return)] 'org-meta-return)
15161 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
15162 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
15163
15164 ;; Cursor keys with modifiers
15165 (define-key org-mode-map [(meta left)] 'org-metaleft)
15166 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
15167 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
15168 (define-key org-mode-map [(meta right)] 'org-metaright)
15169 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
15170 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
15171 (define-key org-mode-map [(meta up)] 'org-metaup)
15172 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
15173 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
15174 (define-key org-mode-map [(meta down)] 'org-metadown)
15175 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
15176 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
15177
15178 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15179 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
15180 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
15181 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
15182 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
15183 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
15184 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
15185 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
15186 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
15187 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
15188 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
15189 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
15190 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
15191 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
15192 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
15193 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
15194
15195 ;; All the other keys
15196
15197 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15198 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
15199 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
15200 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
15201 (define-key org-mode-map "\C-c\C-j" 'org-goto)
15202 (define-key org-mode-map "\C-c\C-t" 'org-todo)
15203 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
15204 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
15205 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
15206 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15207 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
15208 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
15209 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
15210 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
15211 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
15212 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
15213 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
15214 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
15215 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
15216 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
15217 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15218 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15219 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15220 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15221 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
15222 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
15223 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15224 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
15225 (define-key org-mode-map "\C-c]" 'org-remove-file)
15226 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
15227 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
15228 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
15229 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15230 (define-key org-mode-map "\C-m" 'org-return)
15231 (define-key org-mode-map "\C-c?" 'org-table-current-column)
15232 (define-key org-mode-map "\C-c " 'org-table-blank-field)
15233 (define-key org-mode-map "\C-c+" 'org-table-sum)
15234 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
15235 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
15236 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
15237 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15238 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
15239 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15240 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
15241 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
15242 (define-key org-mode-map "\C-c\C-e" 'org-export)
15243 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15244
15245 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
15246 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15247 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15248 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15249
15250 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15251 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15252 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15253 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15254 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15255 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15256 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15257 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15258
15259 (when (featurep 'xemacs)
15260 (define-key org-mode-map 'button3 'popup-mode-menu))
15261
15262 (defsubst org-table-p () (org-at-table-p))
15263
15264 (defun org-self-insert-command (N)
15265 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15266 If the cursor is in a table looking at whitespace, the whitespace is
15267 overwritten, and the table is not marked as requiring realignment."
15268 (interactive "p")
15269 (if (and (org-table-p)
15270 (progn
15271 ;; check if we blank the field, and if that triggers align
15272 (and org-table-auto-blank-field
15273 (member last-command
15274 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
15275 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15276 ;; got extra space, this field does not determine column width
15277 (let (org-table-may-need-update) (org-table-blank-field))
15278 ;; no extra space, this field may determine column width
15279 (org-table-blank-field)))
15280 t)
15281 (eq N 1)
15282 (looking-at "[^|\n]* |"))
15283 (let (org-table-may-need-update)
15284 (goto-char (1- (match-end 0)))
15285 (delete-backward-char 1)
15286 (goto-char (match-beginning 0))
15287 (self-insert-command N))
15288 (setq org-table-may-need-update t)
15289 (self-insert-command N)))
15290
15291 (defun org-delete-backward-char (N)
15292 "Like `delete-backward-char', insert whitespace at field end in tables.
15293 When deleting backwards, in tables this function will insert whitespace in
15294 front of the next \"|\" separator, to keep the table aligned. The table will
15295 still be marked for re-alignment if the field did fill the entire column,
15296 because, in this case the deletion might narrow the column."
15297 (interactive "p")
15298 (if (and (org-table-p)
15299 (eq N 1)
15300 (string-match "|" (buffer-substring (point-at-bol) (point)))
15301 (looking-at ".*?|"))
15302 (let ((pos (point))
15303 (noalign (looking-at "[^|\n\r]* |"))
15304 (c org-table-may-need-update))
15305 (backward-delete-char N)
15306 (skip-chars-forward "^|")
15307 (insert " ")
15308 (goto-char (1- pos))
15309 ;; noalign: if there were two spaces at the end, this field
15310 ;; does not determine the width of the column.
15311 (if noalign (setq org-table-may-need-update c)))
15312 (backward-delete-char N)))
15313
15314 (defun org-delete-char (N)
15315 "Like `delete-char', but insert whitespace at field end in tables.
15316 When deleting characters, in tables this function will insert whitespace in
15317 front of the next \"|\" separator, to keep the table aligned. The table will
15318 still be marked for re-alignment if the field did fill the entire column,
15319 because, in this case the deletion might narrow the column."
15320 (interactive "p")
15321 (if (and (org-table-p)
15322 (not (bolp))
15323 (not (= (char-after) ?|))
15324 (eq N 1))
15325 (if (looking-at ".*?|")
15326 (let ((pos (point))
15327 (noalign (looking-at "[^|\n\r]* |"))
15328 (c org-table-may-need-update))
15329 (replace-match (concat
15330 (substring (match-string 0) 1 -1)
15331 " |"))
15332 (goto-char pos)
15333 ;; noalign: if there were two spaces at the end, this field
15334 ;; does not determine the width of the column.
15335 (if noalign (setq org-table-may-need-update c)))
15336 (delete-char N))
15337 (delete-char N)))
15338
15339 ;; How to do this: Measure non-white length of current string
15340 ;; If equal to column width, we should realign.
15341
15342 (defun org-remap (map &rest commands)
15343 "In MAP, remap the functions given in COMMANDS.
15344 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15345 (let (new old)
15346 (while commands
15347 (setq old (pop commands) new (pop commands))
15348 (if (fboundp 'command-remapping)
15349 (define-key map (vector 'remap old) new)
15350 (substitute-key-definition old new map global-map)))))
15351
15352 (when (eq org-enable-table-editor 'optimized)
15353 ;; If the user wants maximum table support, we need to hijack
15354 ;; some standard editing functions
15355 (org-remap org-mode-map
15356 'self-insert-command 'org-self-insert-command
15357 'delete-char 'org-delete-char
15358 'delete-backward-char 'org-delete-backward-char)
15359 (define-key org-mode-map "|" 'org-force-self-insert))
15360
15361 (defun org-shiftcursor-error ()
15362 "Throw an error because Shift-Cursor command was applied in wrong context."
15363 (error "This command is active in special context like tables, headlines or timestamps"))
15364
15365 (defun org-shifttab (&optional arg)
15366 "Global visibility cycling or move to previous table field.
15367 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15368 on context.
15369 See the individual commands for more information."
15370 (interactive "P")
15371 (cond
15372 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15373 (t (call-interactively 'org-global-cycle))))
15374
15375 (defun org-shiftmetaleft ()
15376 "Promote subtree or delete table column.
15377 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
15378 See the individual commands for more information."
15379 (interactive)
15380 (cond
15381 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15382 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15383 ((org-at-item-p) (call-interactively 'org-outdent-item))
15384 (t (org-shiftcursor-error))))
15385
15386 (defun org-shiftmetaright ()
15387 "Demote subtree or insert table column.
15388 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
15389 See the individual commands for more information."
15390 (interactive)
15391 (cond
15392 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15393 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15394 ((org-at-item-p) (call-interactively 'org-indent-item))
15395 (t (org-shiftcursor-error))))
15396
15397 (defun org-shiftmetaup (&optional arg)
15398 "Move subtree up or kill table row.
15399 Calls `org-move-subtree-up' or `org-table-kill-row' or
15400 `org-move-item-up' depending on context. See the individual commands
15401 for more information."
15402 (interactive "P")
15403 (cond
15404 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15405 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15406 ((org-at-item-p) (call-interactively 'org-move-item-up))
15407 (t (org-shiftcursor-error))))
15408 (defun org-shiftmetadown (&optional arg)
15409 "Move subtree down or insert table row.
15410 Calls `org-move-subtree-down' or `org-table-insert-row' or
15411 `org-move-item-down', depending on context. See the individual
15412 commands for more information."
15413 (interactive "P")
15414 (cond
15415 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15416 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15417 ((org-at-item-p) (call-interactively 'org-move-item-down))
15418 (t (org-shiftcursor-error))))
15419
15420 (defun org-metaleft (&optional arg)
15421 "Promote heading or move table column to left.
15422 Calls `org-do-promote' or `org-table-move-column', depending on context.
15423 With no specific context, calls the Emacs default `backward-word'.
15424 See the individual commands for more information."
15425 (interactive "P")
15426 (cond
15427 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15428 ((or (org-on-heading-p) (org-region-active-p))
15429 (call-interactively 'org-do-promote))
15430 (t (call-interactively 'backward-word))))
15431
15432 (defun org-metaright (&optional arg)
15433 "Demote subtree or move table column to right.
15434 Calls `org-do-demote' or `org-table-move-column', depending on context.
15435 With no specific context, calls the Emacs default `forward-word'.
15436 See the individual commands for more information."
15437 (interactive "P")
15438 (cond
15439 ((org-at-table-p) (call-interactively 'org-table-move-column))
15440 ((or (org-on-heading-p) (org-region-active-p))
15441 (call-interactively 'org-do-demote))
15442 (t (call-interactively 'forward-word))))
15443
15444 (defun org-metaup (&optional arg)
15445 "Move subtree up or move table row up.
15446 Calls `org-move-subtree-up' or `org-table-move-row' or
15447 `org-move-item-up', depending on context. See the individual commands
15448 for more information."
15449 (interactive "P")
15450 (cond
15451 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15452 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15453 ((org-at-item-p) (call-interactively 'org-move-item-up))
15454 (t (org-shiftcursor-error))))
15455
15456 (defun org-metadown (&optional arg)
15457 "Move subtree down or move table row down.
15458 Calls `org-move-subtree-down' or `org-table-move-row' or
15459 `org-move-item-down', depending on context. See the individual
15460 commands for more information."
15461 (interactive "P")
15462 (cond
15463 ((org-at-table-p) (call-interactively 'org-table-move-row))
15464 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15465 ((org-at-item-p) (call-interactively 'org-move-item-down))
15466 (t (org-shiftcursor-error))))
15467
15468 (defun org-shiftup (&optional arg)
15469 "Increase item in timestamp or increase priority of current headline.
15470 Calls `org-timestamp-up' or `org-priority-up', depending on context.
15471 See the individual commands for more information."
15472 (interactive "P")
15473 (cond
15474 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
15475 ((org-on-heading-p) (call-interactively 'org-priority-up))
15476 ((org-at-item-p) (call-interactively 'org-previous-item))
15477 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
15478
15479 (defun org-shiftdown (&optional arg)
15480 "Decrease item in timestamp or decrease priority of current headline.
15481 Calls `org-timestamp-down' or `org-priority-down', depending on context.
15482 See the individual commands for more information."
15483 (interactive "P")
15484 (cond
15485 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
15486 ((org-on-heading-p) (call-interactively 'org-priority-down))
15487 (t (call-interactively 'org-next-item))))
15488
15489 (defun org-shiftright ()
15490 "Next TODO keyword or timestamp one day later, depending on context."
15491 (interactive)
15492 (cond
15493 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15494 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
15495 (t (org-shiftcursor-error))))
15496
15497 (defun org-shiftleft ()
15498 "Previous TODO keyword or timestamp one day earlier, depending on context."
15499 (interactive)
15500 (cond
15501 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15502 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
15503 (t (org-shiftcursor-error))))
15504
15505 (defun org-copy-special ()
15506 "Copy region in table or copy current subtree.
15507 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15508 See the individual commands for more information."
15509 (interactive)
15510 (call-interactively
15511 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15512
15513 (defun org-cut-special ()
15514 "Cut region in table or cut current subtree.
15515 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15516 See the individual commands for more information."
15517 (interactive)
15518 (call-interactively
15519 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15520
15521 (defun org-paste-special (arg)
15522 "Paste rectangular region into table, or past subtree relative to level.
15523 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15524 See the individual commands for more information."
15525 (interactive "P")
15526 (if (org-at-table-p)
15527 (org-table-paste-rectangle)
15528 (org-paste-subtree arg)))
15529
15530 (defun org-ctrl-c-ctrl-c (&optional arg)
15531 "Set tags in headline, or update according to changed information at point.
15532
15533 This command does many different things, depending on context:
15534
15535 - If the cursor is in a headline, prompt for tags and insert them
15536 into the current line, aligned to `org-tags-column'. When called
15537 with prefix arg, realign all tags in the current buffer.
15538
15539 - If the cursor is in one of the special #+KEYWORD lines, this
15540 triggers scanning the buffer for these lines and updating the
15541 information.
15542
15543 - If the cursor is inside a table, realign the table. This command
15544 works even if the automatic table editor has been turned off.
15545
15546 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15547 the entire table.
15548
15549 - If the cursor is inside a table created by the table.el package,
15550 activate that table.
15551
15552 - If the current buffer is a remember buffer, close note and file it.
15553 with a prefix argument, file it without further interaction to the default
15554 location.
15555
15556 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15557 links in this buffer.
15558
15559 - If the cursor is on a numbered item in a plain list, renumber the
15560 ordered list."
15561 (interactive "P")
15562 (let ((org-enable-table-editor t))
15563 (cond
15564 ((or org-clock-overlays org-occur-highlights
15565 org-latex-fragment-image-overlays)
15566 (org-remove-clock-overlays)
15567 (org-remove-occur-highlights)
15568 (org-remove-latex-fragment-image-overlays)
15569 (message "Temporary highlights/overlays removed from current buffer"))
15570 ((and (local-variable-p 'org-finish-function (current-buffer))
15571 (fboundp org-finish-function))
15572 (funcall org-finish-function))
15573 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15574 ((org-on-heading-p) (call-interactively 'org-set-tags))
15575 ((org-at-table.el-p)
15576 (require 'table)
15577 (beginning-of-line 1)
15578 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15579 (call-interactively 'table-recognize-table))
15580 ((org-at-table-p)
15581 (org-table-maybe-eval-formula)
15582 (if arg
15583 (call-interactively 'org-table-recalculate)
15584 (org-table-maybe-recalculate-line))
15585 (call-interactively 'org-table-align))
15586 ((org-at-item-checkbox-p)
15587 (call-interactively 'org-toggle-checkbox))
15588 ((org-at-item-p)
15589 (call-interactively 'org-renumber-ordered-list))
15590 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
15591 (cond
15592 ((equal (match-string 1) "TBLFM")
15593 ;; Recalculate the table before this line
15594 (save-excursion
15595 (beginning-of-line 1)
15596 (skip-chars-backward " \r\n\t")
15597 (if (org-at-table-p)
15598 (org-call-with-arg 'org-table-recalculate t))))
15599 (t
15600 (call-interactively 'org-mode-restart))))
15601 (t (error "C-c C-c can do nothing useful at this location.")))))
15602
15603 (defun org-mode-restart ()
15604 "Restart Org-mode, to scan again for special lines.
15605 Also updates the keyword regular expressions."
15606 (interactive)
15607 (let ((org-inhibit-startup t)) (org-mode))
15608 (message "Org-mode restarted to refresh keyword and special line setup"))
15609
15610 (defun org-return ()
15611 "Goto next table row or insert a newline.
15612 Calls `org-table-next-row' or `newline', depending on context.
15613 See the individual commands for more information."
15614 (interactive)
15615 (cond
15616 ((org-at-table-p)
15617 (org-table-justify-field-maybe)
15618 (call-interactively 'org-table-next-row))
15619 (t (newline))))
15620
15621 (defun org-meta-return (&optional arg)
15622 "Insert a new heading or wrap a region in a table.
15623 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15624 See the individual commands for more information."
15625 (interactive "P")
15626 (cond
15627 ((org-at-table-p)
15628 (call-interactively 'org-table-wrap-region))
15629 (t (call-interactively 'org-insert-heading))))
15630
15631 ;;; Menu entries
15632
15633 ;; Define the Org-mode menus
15634 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15635 '("Tbl"
15636 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
15637 ["Next Field" org-cycle (org-at-table-p)]
15638 ["Previous Field" org-shifttab (org-at-table-p)]
15639 ["Next Row" org-return (org-at-table-p)]
15640 "--"
15641 ["Blank Field" org-table-blank-field (org-at-table-p)]
15642 ["Edit Field" org-table-edit-field (org-at-table-p)]
15643 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15644 "--"
15645 ("Column"
15646 ["Move Column Left" org-metaleft (org-at-table-p)]
15647 ["Move Column Right" org-metaright (org-at-table-p)]
15648 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15649 ["Insert Column" org-shiftmetaright (org-at-table-p)]
15650 "--"
15651 ["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])
15652 ("Row"
15653 ["Move Row Up" org-metaup (org-at-table-p)]
15654 ["Move Row Down" org-metadown (org-at-table-p)]
15655 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15656 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15657 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15658 "--"
15659 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
15660 ("Rectangle"
15661 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15662 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15663 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15664 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15665 "--"
15666 ("Calculate"
15667 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15668 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15669 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
15670 "--"
15671 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15672 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15673 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15674 "--"
15675 ["Sum Column/Rectangle" org-table-sum
15676 (or (org-at-table-p) (org-region-active-p))]
15677 ["Which Column?" org-table-current-column (org-at-table-p)])
15678 ["Debug Formulas"
15679 (setq org-table-formula-debug (not org-table-formula-debug))
15680 :style toggle :selected org-table-formula-debug]
15681 "--"
15682 ["Create" org-table-create (and (not (org-at-table-p))
15683 org-enable-table-editor)]
15684 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15685 ["Import from File" org-table-import (not (org-at-table-p))]
15686 ["Export to File" org-table-export (org-at-table-p)]
15687 "--"
15688 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15689
15690 (easy-menu-define org-org-menu org-mode-map "Org menu"
15691 '("Org"
15692 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
15693 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
15694 ["Sparse Tree" org-occur t]
15695 ["Show All" show-all t]
15696 "--"
15697 ["New Heading" org-insert-heading t]
15698 ("Navigate Headings"
15699 ["Up" outline-up-heading t]
15700 ["Next" outline-next-visible-heading t]
15701 ["Previous" outline-previous-visible-heading t]
15702 ["Next Same Level" outline-forward-same-level t]
15703 ["Previous Same Level" outline-backward-same-level t]
15704 "--"
15705 ["Jump" org-goto t])
15706 ("Edit Structure"
15707 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15708 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15709 "--"
15710 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15711 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15712 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15713 "--"
15714 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15715 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15716 ["Demote Heading" org-metaright (not (org-at-table-p))]
15717 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15718 "--"
15719 ["Convert to odd levels" org-convert-to-odd-levels t]
15720 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15721 ("Archive"
15722 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15723 ["Check and Tag Children" (org-toggle-archive-tag (4))
15724 :active t :keys "C-u C-c C-x C-a"]
15725 ["Sparse trees open ARCHIVE trees"
15726 (setq org-sparse-tree-open-archived-trees
15727 (not org-sparse-tree-open-archived-trees))
15728 :style toggle :selected org-sparse-tree-open-archived-trees]
15729 ["Cycling opens ARCHIVE trees"
15730 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15731 :style toggle :selected org-cycle-open-archived-trees]
15732 ["Agenda includes ARCHIVE trees"
15733 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
15734 :style toggle :selected (not org-agenda-skip-archived-trees)]
15735 "--"
15736 ["Move Subtree to Archive" org-archive-subtree t]
15737 ["Check and Move Children" (org-archive-subtree '(4))
15738 :active t :keys "C-u C-c $"])
15739 "--"
15740 ("TODO Lists"
15741 ["TODO/DONE/-" org-todo t]
15742 ["Show TODO Tree" org-show-todo-tree t]
15743 ["Global TODO list" org-todo-list t]
15744 "--"
15745 ["Set Priority" org-priority t]
15746 ["Priority Up" org-shiftup t]
15747 ["Priority Down" org-shiftdown t])
15748 ("Dates and Scheduling"
15749 ["Timestamp" org-time-stamp t]
15750 ["Timestamp (inactive)" org-time-stamp-inactive t]
15751 ("Change Date"
15752 ["1 Day Later" org-timestamp-up-day t]
15753 ["1 Day Earlier" org-timestamp-down-day t]
15754 ["1 ... Later" org-shiftup t]
15755 ["1 ... Earlier" org-shiftdown t])
15756 ["Compute Time Range" org-evaluate-time-range t]
15757 ["Schedule Item" org-schedule t]
15758 ["Deadline" org-deadline t]
15759 "--"
15760 ["Goto Calendar" org-goto-calendar t]
15761 ["Date from Calendar" org-date-from-calendar t])
15762 ("Logging work"
15763 ["Clock in" org-clock-in t]
15764 ["Clock out" org-clock-out t]
15765 ["Clock cancel" org-clock-cancel t]
15766 ["Display times" org-clock-display t]
15767 ["Create clock table" org-clock-report t]
15768 "--"
15769 ["Record DONE time"
15770 (progn (setq org-log-done (not org-log-done))
15771 (message "Switching to %s will %s record a timestamp"
15772 org-done-string
15773 (if org-log-done "automatically" "not")))
15774 :style toggle :selected org-log-done])
15775 "--"
15776 ["Agenda Command" org-agenda t]
15777 ("File List for Agenda")
15778 ("Special views current file"
15779 ["TODO Tree" org-show-todo-tree t]
15780 ["Check Deadlines" org-check-deadlines t]
15781 ["Timeline" org-timeline t]
15782 ["Tags Tree" org-tags-sparse-tree t])
15783 "--"
15784 ("Hyperlinks"
15785 ["Store Link (Global)" org-store-link t]
15786 ["Insert Link" org-insert-link t]
15787 ["Follow Link" org-open-at-point t]
15788 "--"
15789 ["Descriptive Links"
15790 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15791 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
15792 ["Literal Links"
15793 (progn
15794 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15795 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
15796 "--"
15797 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
15798 (save-excursion (goto-char (point-min))
15799 (re-search-forward "<[a-z]+:" nil t))])
15800 "--"
15801 ["Export/Publish" org-export t]
15802 ("LaTeX"
15803 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15804 :selected org-cdlatex-mode]
15805 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15806 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15807 ["Modify math symbol" org-cdlatex-math-modify
15808 (org-inside-LaTeX-fragment-p)]
15809 ["Export LaTeX fragments as images"
15810 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
15811 :style toggle :selected org-export-with-LaTeX-fragments])
15812 "--"
15813 ("Documentation"
15814 ["Show Version" org-version t]
15815 ["Info Documentation" org-info t])
15816 ("Customize"
15817 ["Browse Org Group" org-customize t]
15818 "--"
15819 ["Expand This Menu" org-create-customize-menu
15820 (fboundp 'customize-menu-create)])
15821 "--"
15822 ["Refresh setup" org-mode-restart t]
15823 ))
15824
15825 (defun org-info (&optional node)
15826 "Read documentation for Org-mode in the info system.
15827 With optional NODE, go directly to that node."
15828 (interactive)
15829 (require 'info)
15830 (Info-goto-node (format "(org)%s" (or node ""))))
15831
15832 (defun org-install-agenda-files-menu ()
15833 (let ((bl (buffer-list)))
15834 (save-excursion
15835 (while bl
15836 (set-buffer (pop bl))
15837 (if (eq major-mode 'org-mode) (setq bl nil)))
15838 (when (eq major-mode 'org-mode)
15839 (easy-menu-change
15840 '("Org") "File List for Agenda"
15841 (append
15842 (list
15843 ["Edit File List" (org-edit-agenda-file-list) t]
15844 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15845 ["Remove Current File from List" org-remove-file t]
15846 ["Cycle through agenda files" org-cycle-agenda-files t]
15847 "--")
15848 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15849
15850 ;;; Documentation
15851
15852 (defun org-customize ()
15853 "Call the customize function with org as argument."
15854 (interactive)
15855 (customize-browse 'org))
15856
15857 (defun org-create-customize-menu ()
15858 "Create a full customization menu for Org-mode, insert it into the menu."
15859 (interactive)
15860 (if (fboundp 'customize-menu-create)
15861 (progn
15862 (easy-menu-change
15863 '("Org") "Customize"
15864 `(["Browse Org group" org-customize t]
15865 "--"
15866 ,(customize-menu-create 'org)
15867 ["Set" Custom-set t]
15868 ["Save" Custom-save t]
15869 ["Reset to Current" Custom-reset-current t]
15870 ["Reset to Saved" Custom-reset-saved t]
15871 ["Reset to Standard Settings" Custom-reset-standard t]))
15872 (message "\"Org\"-menu now contains full customization menu"))
15873 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15874
15875 ;;; Miscellaneous stuff
15876
15877 (defun org-context ()
15878 "Return a list of contexts of the current cursor position.
15879 If several contexts apply, all are returned.
15880 Each context entry is a list with a symbol naming the context, and
15881 two positions indicating start and end of the context. Possible
15882 contexts are:
15883
15884 :headline anywhere in a headline
15885 :headline-stars on the leading stars in a headline
15886 :todo-keyword on a TODO keyword (including DONE) in a headline
15887 :tags on the TAGS in a headline
15888 :priority on the priority cookie in a headline
15889 :item on the first line of a plain list item
15890 :item-bullet on the bullet/number of a plain list item
15891 :checkbox on the checkbox in a plain list item
15892 :table in an org-mode table
15893 :table-special on a special filed in a table
15894 :table-table in a table.el table
15895 :link on a hyperline
15896 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15897 :target on a <<target>>
15898 :radio-target on a <<<radio-target>>>
15899 :latex-fragment on a LaTeX fragment
15900 :latex-preview on a LaTeX fragment with overlayed preview image
15901
15902 This function expects the position to be visible because it uses font-lock
15903 faces as a help to recognize the following contexts: :table-special, :link,
15904 and :keyword."
15905 (let* ((f (get-text-property (point) 'face))
15906 (faces (if (listp f) f (list f)))
15907 (p (point)) clist o)
15908 ;; First the large context
15909 (cond
15910 ((org-on-heading-p)
15911 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15912 (when (progn
15913 (beginning-of-line 1)
15914 (looking-at org-todo-line-tags-regexp))
15915 (push (org-point-in-group p 1 :headline-stars) clist)
15916 (push (org-point-in-group p 2 :todo-keyword) clist)
15917 (push (org-point-in-group p 4 :tags) clist))
15918 (goto-char p)
15919 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15920 (if (looking-at "\\[#[A-Z]\\]")
15921 (push (org-point-in-group p 0 :priority) clist)))
15922
15923 ((org-at-item-p)
15924 (push (org-point-in-group p 2 :item-bullet) clist)
15925 (push (list :item (point-at-bol)
15926 (save-excursion (org-end-of-item) (point)))
15927 clist)
15928 (and (org-at-item-checkbox-p)
15929 (push (org-point-in-group p 0 :checkbox) clist)))
15930
15931 ((org-at-table-p)
15932 (push (list :table (org-table-begin) (org-table-end)) clist)
15933 (if (memq 'org-formula faces)
15934 (push (list :table-special
15935 (previous-single-property-change p 'face)
15936 (next-single-property-change p 'face)) clist)))
15937 ((org-at-table-p 'any)
15938 (push (list :table-table) clist)))
15939 (goto-char p)
15940
15941 ;; Now the small context
15942 (cond
15943 ((org-at-timestamp-p)
15944 (push (org-point-in-group p 0 :timestamp) clist))
15945 ((memq 'org-link faces)
15946 (push (list :link
15947 (previous-single-property-change p 'face)
15948 (next-single-property-change p 'face)) clist))
15949 ((memq 'org-special-keyword faces)
15950 (push (list :keyword
15951 (previous-single-property-change p 'face)
15952 (next-single-property-change p 'face)) clist))
15953 ((org-on-target-p)
15954 (push (org-point-in-group p 0 :target) clist)
15955 (goto-char (1- (match-beginning 0)))
15956 (if (looking-at org-radio-target-regexp)
15957 (push (org-point-in-group p 0 :radio-target) clist))
15958 (goto-char p))
15959 ((setq o (car (delq nil
15960 (mapcar
15961 (lambda (x)
15962 (if (memq x org-latex-fragment-image-overlays) x))
15963 (org-overlays-at (point))))))
15964 (push (list :latex-fragment
15965 (org-overlay-start o) (org-overlay-end o)) clist)
15966 (push (list :latex-preview
15967 (org-overlay-start o) (org-overlay-end o)) clist))
15968 ((org-inside-LaTeX-fragment-p)
15969 ;; FIXME: positions wring.
15970 (push (list :latex-fragment (point) (point)) clist)))
15971
15972 (setq clist (nreverse (delq nil clist)))
15973 clist))
15974
15975 (defun org-point-in-group (point group &optional context)
15976 "Check if POINT is in match-group GROUP.
15977 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15978 match. If the match group does ot exist or point is not inside it,
15979 return nil."
15980 (and (match-beginning group)
15981 (>= point (match-beginning group))
15982 (<= point (match-end group))
15983 (if context
15984 (list context (match-beginning group) (match-end group))
15985 t)))
15986
15987 (defun org-move-line-down (arg)
15988 "Move the current line down. With prefix argument, move it past ARG lines."
15989 (interactive "p")
15990 (let ((col (current-column))
15991 beg end pos)
15992 (beginning-of-line 1) (setq beg (point))
15993 (beginning-of-line 2) (setq end (point))
15994 (beginning-of-line (+ 1 arg))
15995 (setq pos (move-marker (make-marker) (point)))
15996 (insert (delete-and-extract-region beg end))
15997 (goto-char pos)
15998 (move-to-column col)))
15999
16000 (defun org-move-line-up (arg)
16001 "Move the current line up. With prefix argument, move it past ARG lines."
16002 (interactive "p")
16003 (let ((col (current-column))
16004 beg end pos)
16005 (beginning-of-line 1) (setq beg (point))
16006 (beginning-of-line 2) (setq end (point))
16007 (beginning-of-line (- arg))
16008 (setq pos (move-marker (make-marker) (point)))
16009 (insert (delete-and-extract-region beg end))
16010 (goto-char pos)
16011 (move-to-column col)))
16012
16013 ;; Paragraph filling stuff.
16014 ;; We want this to be just right, so use the full arsenal.
16015
16016 (defun org-set-autofill-regexps ()
16017 (interactive)
16018 ;; In the paragraph separator we include headlines, because filling
16019 ;; text in a line directly attached to a headline would otherwise
16020 ;; fill the headline as well.
16021 (set (make-local-variable 'comment-start-skip) "^#+[ \t]*")
16022 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
16023 ;; The paragraph starter includes hand-formatted lists.
16024 (set (make-local-variable 'paragraph-start)
16025 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
16026 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16027 ;; But only if the user has not turned off tables or fixed-width regions
16028 (set (make-local-variable 'auto-fill-inhibit-regexp)
16029 (concat "\\*\\|#"
16030 "\\|[ \t]*" org-keyword-time-regexp
16031 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16032 (concat
16033 "\\|[ \t]*["
16034 (if org-enable-table-editor "|" "")
16035 (if org-enable-fixed-width-editor ":" "")
16036 "]"))))
16037 ;; We use our own fill-paragraph function, to make sure that tables
16038 ;; and fixed-width regions are not wrapped. That function will pass
16039 ;; through to `fill-paragraph' when appropriate.
16040 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
16041 ;; Adaptive filling: To get full control, first make sure that
16042 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16043 (set (make-local-variable 'adaptive-fill-regexp) "\000")
16044 (set (make-local-variable 'adaptive-fill-function)
16045 'org-adaptive-fill-function))
16046
16047 (defun org-fill-paragraph (&optional justify)
16048 "Re-align a table, pass through to fill-paragraph if no table."
16049 (let ((table-p (org-at-table-p))
16050 (table.el-p (org-at-table.el-p)))
16051 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
16052 (table.el-p t) ; skip table.el tables
16053 (table-p (org-table-align) t) ; align org-mode tables
16054 (t nil)))) ; call paragraph-fill
16055
16056 ;; For reference, this is the default value of adaptive-fill-regexp
16057 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16058
16059 (defun org-adaptive-fill-function ()
16060 "Return a fill prefix for org-mode files.
16061 In particular, this makes sure hanging paragraphs for hand-formatted lists
16062 work correctly."
16063 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
16064 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
16065
16066 ;; Functions needed for Emacs/XEmacs region compatibility
16067
16068 (defun org-add-hook (hook function &optional append local)
16069 "Add-hook, compatible with both Emacsen."
16070 (if (and local (featurep 'xemacs))
16071 (add-local-hook hook function append)
16072 (add-hook hook function append local)))
16073
16074 (defun org-region-active-p ()
16075 "Is `transient-mark-mode' on and the region active?
16076 Works on both Emacs and XEmacs."
16077 (if org-ignore-region
16078 nil
16079 (if (featurep 'xemacs)
16080 (and zmacs-regions (region-active-p))
16081 (and transient-mark-mode mark-active))))
16082
16083 (defun org-add-to-invisibility-spec (arg)
16084 "Add elements to `buffer-invisibility-spec'.
16085 See documentation for `buffer-invisibility-spec' for the kind of elements
16086 that can be added."
16087 (cond
16088 ((fboundp 'add-to-invisibility-spec)
16089 (add-to-invisibility-spec arg))
16090 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
16091 (setq buffer-invisibility-spec (list arg)))
16092 (t
16093 (setq buffer-invisibility-spec
16094 (cons arg buffer-invisibility-spec)))))
16095
16096 (defun org-remove-from-invisibility-spec (arg)
16097 "Remove elements from `buffer-invisibility-spec'."
16098 (if (fboundp 'remove-from-invisibility-spec)
16099 (remove-from-invisibility-spec arg)
16100 (if (consp buffer-invisibility-spec)
16101 (setq buffer-invisibility-spec
16102 (delete arg buffer-invisibility-spec)))))
16103
16104 (defun org-in-invisibility-spec-p (arg)
16105 "Is ARG a member of `buffer-invisibility-spec'?"
16106 (if (consp buffer-invisibility-spec)
16107 (member arg buffer-invisibility-spec)
16108 nil))
16109
16110 (defun org-image-file-name-regexp ()
16111 "Return regexp matching the file names of images."
16112 (if (fboundp 'image-file-name-regexp)
16113 (image-file-name-regexp)
16114 (let ((image-file-name-extensions
16115 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16116 "xbm" "xpm" "pbm" "pgm" "ppm")))
16117 (concat "\\."
16118 (regexp-opt (nconc (mapcar 'upcase
16119 image-file-name-extensions)
16120 image-file-name-extensions)
16121 t)
16122 "\\'"))))
16123
16124 ;; Functions needed for compatibility with old outline.el.
16125
16126 ;; Programming for the old outline.el (that uses selective display
16127 ;; instead of `invisible' text properties) is a nightmare, mostly
16128 ;; because regular expressions can no longer be anchored at
16129 ;; beginning/end of line. Therefore a number of function need special
16130 ;; treatment when the old outline.el is being used.
16131
16132 ;; The following functions capture almost the entire compatibility code
16133 ;; between the different versions of outline-mode. The only other
16134 ;; places where this is important are the font-lock-keywords, and in
16135 ;; `org-export-visible'. Search for `org-noutline-p' to find them.
16136
16137 ;; C-a should go to the beginning of a *visible* line, also in the
16138 ;; new outline.el. I guess this should be patched into Emacs?
16139 (defun org-beginning-of-line ()
16140 "Go to the beginning of the current line. If that is invisible, continue
16141 to a visible line beginning. This makes the function of C-a more intuitive."
16142 (interactive)
16143 (beginning-of-line 1)
16144 (if (bobp)
16145 nil
16146 (backward-char 1)
16147 (if (org-invisible-p)
16148 (while (and (not (bobp)) (org-invisible-p))
16149 (backward-char 1)
16150 (beginning-of-line 1))
16151 (forward-char 1))))
16152
16153 (when org-noutline-p
16154 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
16155
16156 (defun org-invisible-p ()
16157 "Check if point is at a character currently not visible."
16158 (if org-noutline-p
16159 ;; Early versions of noutline don't have `outline-invisible-p'.
16160 (if (fboundp 'outline-invisible-p)
16161 (outline-invisible-p)
16162 (get-char-property (point) 'invisible))
16163 (save-excursion
16164 (skip-chars-backward "^\r\n")
16165 (equal (char-before) ?\r))))
16166
16167 (defun org-invisible-p2 ()
16168 "Check if point is at a character currently not visible."
16169 (save-excursion
16170 (if org-noutline-p
16171 (progn
16172 (if (and (eolp) (not (bobp))) (backward-char 1))
16173 ;; Early versions of noutline don't have `outline-invisible-p'.
16174 (if (fboundp 'outline-invisible-p)
16175 (outline-invisible-p)
16176 (get-char-property (point) 'invisible)))
16177 (skip-chars-backward "^\r\n")
16178 (equal (char-before) ?\r))))
16179
16180 (defun org-back-to-heading (&optional invisible-ok)
16181 "Move to previous heading line, or beg of this line if it's a heading.
16182 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
16183 (if org-noutline-p
16184 (outline-back-to-heading invisible-ok)
16185 (if (and (or (bobp) (memq (char-before) '(?\n ?\r)))
16186 (looking-at outline-regexp))
16187 t
16188 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
16189 outline-regexp)
16190 nil t)
16191 (if invisible-ok
16192 (progn (goto-char (or (match-end 1) (match-beginning 0)))
16193 (looking-at outline-regexp)))
16194 (error "Before first heading")))))
16195
16196 (defun org-on-heading-p (&optional invisible-ok)
16197 "Return t if point is on a (visible) heading line.
16198 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
16199 (if org-noutline-p
16200 (outline-on-heading-p 'invisible-ok)
16201 (save-excursion
16202 (skip-chars-backward "^\n\r")
16203 (and (looking-at outline-regexp)
16204 (or invisible-ok
16205 (bobp)
16206 (equal (char-before) ?\n))))))
16207
16208 (defun org-on-target-p ()
16209 (let ((pos (point)))
16210 (save-excursion
16211 (skip-chars-forward "<")
16212 (and (re-search-backward "<<" nil t)
16213 (or (looking-at org-radio-target-regexp)
16214 (looking-at org-target-regexp))
16215 (<= (match-beginning 0) pos)
16216 (>= (1+ (match-end 0)) pos)))))
16217
16218 (defun org-up-heading-all (arg)
16219 "Move to the heading line of which the present line is a subheading.
16220 This function considers both visible and invisible heading lines.
16221 With argument, move up ARG levels."
16222 (if org-noutline-p
16223 (if (fboundp 'outline-up-heading-all)
16224 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16225 (outline-up-heading arg t)) ; emacs 22 version of outline.el
16226 (org-back-to-heading t)
16227 (looking-at outline-regexp)
16228 (if (<= (- (match-end 0) (match-beginning 0)) arg)
16229 (error "Cannot move up %d levels" arg)
16230 (re-search-backward
16231 (concat "[\n\r]" (regexp-quote
16232 (make-string (- (match-end 0) (match-beginning 0) arg)
16233 ?*))
16234 "[^*]"))
16235 (forward-char 1))))
16236
16237 (defun org-show-hidden-entry ()
16238 "Show an entry where even the heading is hidden."
16239 (save-excursion
16240 (if (not org-noutline-p)
16241 (progn
16242 (org-back-to-heading t)
16243 (org-flag-heading nil)))
16244 (org-show-entry)))
16245
16246 (defun org-check-occur-regexp (regexp)
16247 "If REGEXP starts with \"^\", modify it to check for \\r as well.
16248 Of course, only for the old outline mode."
16249 (if org-noutline-p
16250 regexp
16251 (if (string-match "^\\^" regexp)
16252 (concat "[\n\r]" (substring regexp 1))
16253 regexp)))
16254
16255 (defun org-flag-heading (flag &optional entry)
16256 "Flag the current heading. FLAG non-nil means make invisible.
16257 When ENTRY is non-nil, show the entire entry."
16258 (save-excursion
16259 (org-back-to-heading t)
16260 (if (not org-noutline-p)
16261 ;; Make the current headline visible
16262 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
16263 ;; Check if we should show the entire entry
16264 (if entry
16265 (progn
16266 (org-show-entry)
16267 (save-excursion
16268 (and (outline-next-heading)
16269 (org-flag-heading nil))))
16270 (outline-flag-region (max 1 (1- (point)))
16271 (save-excursion (outline-end-of-heading) (point))
16272 (if org-noutline-p
16273 flag
16274 (if flag ?\r ?\n))))))
16275
16276 (defun org-end-of-subtree (&optional invisible-OK)
16277 ;; This is an exact copy of the original function, but it uses
16278 ;; `org-back-to-heading', to make it work also in invisible
16279 ;; trees. And is uses an invisible-OK argument.
16280 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16281 (org-back-to-heading invisible-OK)
16282 (let ((first t)
16283 (level (funcall outline-level)))
16284 (while (and (not (eobp))
16285 (or first (> (funcall outline-level) level)))
16286 (setq first nil)
16287 (outline-next-heading))
16288 (if (memq (preceding-char) '(?\n ?\^M))
16289 (progn
16290 ;; Go to end of line before heading
16291 (forward-char -1)
16292 (if (memq (preceding-char) '(?\n ?\^M))
16293 ;; leave blank line before heading
16294 (forward-char -1)))))
16295 (point))
16296
16297 (defun org-show-subtree ()
16298 "Show everything after this heading at deeper levels."
16299 (outline-flag-region
16300 (point)
16301 (save-excursion
16302 (outline-end-of-subtree) (outline-next-heading) (point))
16303 (if org-noutline-p nil ?\n)))
16304
16305 (defun org-show-entry ()
16306 "Show the body directly following this heading.
16307 Show the heading too, if it is currently invisible."
16308 (interactive)
16309 (save-excursion
16310 (org-back-to-heading t)
16311 (outline-flag-region
16312 (max 1 (1- (point)))
16313 (save-excursion
16314 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
16315 (or (match-beginning 1) (point-max)))
16316 (if org-noutline-p nil ?\n))))
16317
16318 (defun org-make-options-regexp (kwds)
16319 "Make a regular expression for keyword lines."
16320 (concat
16321 (if org-noutline-p "^" "[\n\r]")
16322 "#?[ \t]*\\+\\("
16323 (mapconcat 'regexp-quote kwds "\\|")
16324 "\\):[ \t]*"
16325 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
16326
16327 ;; Make `bookmark-jump' show the jump location if it was hidden.
16328 (eval-after-load "bookmark"
16329 '(if (boundp 'bookmark-after-jump-hook)
16330 ;; We can use the hook
16331 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16332 ;; Hook not available, use advice
16333 (defadvice bookmark-jump (after org-make-visible activate)
16334 "Make the position visible."
16335 (org-bookmark-jump-unhide))))
16336
16337 (defun org-bookmark-jump-unhide ()
16338 "Unhide the current position, to show the bookmark location."
16339 (and (eq major-mode 'org-mode)
16340 (or (org-invisible-p)
16341 (save-excursion (goto-char (max (point-min) (1- (point))))
16342 (org-invisible-p)))
16343 (org-show-hierarchy-above)))
16344
16345 ;;; Experimental code
16346
16347 ;;; Finish up
16348
16349 (provide 'org)
16350
16351 (run-hooks 'org-load-hook)
16352
16353 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16354 ;;; org.el ends here