]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-agenda-mode-map): Add bindings for clocking
[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.36b
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.37
94 ;; - Clock-feature for measuring time spent on specific items.
95 ;; - Improved emphasizing allows configuration and stacking.
96 ;;
97 ;; Version 4.36
98 ;; - Improved indentation of ASCII export, when headlines become items.
99 ;; - Handling of 12am and 12pm fixed. Times beyond 24:00 can be used
100 ;; and will not lead to conflicts.
101 ;; - Support for mutually exclusive TAGS with the fast tags interface.
102 ;; - Bug fixes.
103 ;;
104 ;; Version 4.35
105 ;; - HTML export is now valid XHTML.
106 ;; - Timeline can also show dates without entries. See new option
107 ;; `org-timeline-show-empty-dates'.
108 ;; - The bullets created by the ASCII exporter can now be configured.
109 ;; See the new option `org-export-ascii-bullets'.
110 ;; - New face `org-upcoming-deadline' (was `org-scheduled-previously').
111 ;; - New function `org-context' to allow testing for local context.
112 ;;
113 ;; Version 4.34
114 ;; - Bug fixes.
115 ;;
116 ;; Version 4.33
117 ;; - New commands to move through plain lists: S-up and S-down.
118 ;; - Bug fixes and documentation update.
119 ;;
120 ;; Version 4.32
121 ;; - Fast (single-key-per-tag) interface for setting TAGS.
122 ;; - The list of legal tags can be configured globally and locally.
123 ;; - Elisp and Info links (thanks to Todd Neal).
124 ;; - `org-export-publishing-directory' can be an alist, with different
125 ;; directories for different export types.
126 ;; - All context-sensitive commands use `call-interactively' to dispatch.
127 ;; - `org-confirm-shell-links' renamed to `org-confirm-shell-link-function'.
128 ;; - Bug fixes.
129 ;;
130 ;; Version 4.31
131 ;; - Bug fixes.
132 ;;
133 ;; Version 4.30
134 ;; - Modified installation: Autoloads have been collected in org-install.el.
135 ;; - Logging (org-log-done) is now a #+STARTUP option.
136 ;; - Checkboxes in plain list items, following up on Frank Ruell's idea.
137 ;; - File links inserted with C-c C-l will use relative paths if the linked
138 ;; file is in the current directory or a subdirectory of it.
139 ;; - New variable `org-link-file-path-type' to specify preference for
140 ;; relative and absolute paths.
141 ;; - New CSS classes for tags, timestamps, timestamp keywords.
142 ;; - Bug and typo fixes.
143 ;;
144 ;; Version 4.29
145 ;; - Inlining images in HTML export now depends on wheather the link
146 ;; contains a description or not.
147 ;; - TODO items can be scheduled from the global TODO list using C-c C-s.
148 ;; - TODO items already scheduled can be made to disappear from the global
149 ;; todo list, see `org-agenda-todo-ignore-scheduled'.
150 ;; - In Tables, formulas may also be Lisp forms.
151 ;; - Exporting the visible part of an outline with `C-c C-x v' works now
152 ;; for all available exporters.
153 ;; - Bug fixes, lots of them :-(
154 ;;
155 ;; Version 4.28
156 ;; - Bug fixes.
157 ;;
158 ;; Version 4.27
159 ;; - HTML exporter generalized to receive external options.
160 ;; As part of the process, author, email and date have been moved to the
161 ;; end of the HTML file.
162 ;; - Support for customizable file search in file links.
163 ;; - BibTeX database links as first application of the above.
164 ;; - New option `org-agenda-todo-list-sublevels' to turn off listing TODO
165 ;; entries that are sublevels of another TODO entry.
166 ;;
167 ;;
168 ;;; Code:
169
170 (eval-when-compile
171 (require 'cl)
172 (require 'calendar))
173 (require 'outline)
174 (require 'time-date)
175 (require 'easymenu)
176
177 ;;; Customization variables
178
179 (defvar org-version "4.36b"
180 "The version number of the file org.el.")
181 (defun org-version ()
182 (interactive)
183 (message "Org-mode version %s" org-version))
184
185 ;; The following constant is for compatibility with different versions
186 ;; of outline.el.
187 (defconst org-noutline-p (featurep 'noutline)
188 "Are we using the new outline mode?")
189 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
190 (defconst org-format-transports-properties-p
191 (let ((x "a"))
192 (add-text-properties 0 1 '(test t) x)
193 (get-text-property 0 'test (format "%s" x)))
194 "Does format transport text properties?")
195
196 (defgroup org nil
197 "Outline-based notes management and organizer."
198 :tag "Org"
199 :group 'outlines
200 :group 'hypermedia
201 :group 'calendar)
202
203 (defgroup org-startup nil
204 "Options concerning startup of Org-mode."
205 :tag "Org Startup"
206 :group 'org)
207
208 (defcustom org-startup-folded t
209 "Non-nil means, entering Org-mode will switch to OVERVIEW.
210 This can also be configured on a per-file basis by adding one of
211 the following lines anywhere in the buffer:
212
213 #+STARTUP: fold
214 #+STARTUP: nofold
215 #+STARTUP: content"
216 :group 'org-startup
217 :type '(choice
218 (const :tag "nofold: show all" nil)
219 (const :tag "fold: overview" t)
220 (const :tag "content: all headlines" content)))
221
222 (defcustom org-startup-truncated t
223 "Non-nil means, entering Org-mode will set `truncate-lines'.
224 This is useful since some lines containing links can be very long and
225 uninteresting. Also tables look terrible when wrapped."
226 :group 'org-startup
227 :type 'boolean)
228
229 (defcustom org-startup-align-all-tables nil
230 "Non-nil means, align all tables when visiting a file.
231 This is useful when the column width in tables is forced with <N> cookies
232 in table fields. Such tables will look correct only after the first re-align.
233 This can also be configured on a per-file basis by adding one of
234 the following lines anywhere in the buffer:
235 #+STARTUP: align
236 #+STARTUP: noalign"
237 :group 'org-startup
238 :type 'boolean)
239
240 (defcustom org-startup-with-deadline-check nil
241 "Non-nil means, entering Org-mode will run the deadline check.
242 This means, if you start editing an org file, you will get an
243 immediate reminder of any due deadlines.
244 This can also be configured on a per-file basis by adding one of
245 the following lines anywhere in the buffer:
246 #+STARTUP: dlcheck
247 #+STARTUP: nodlcheck"
248 :group 'org-startup
249 :type 'boolean)
250
251 (defcustom org-insert-mode-line-in-empty-file nil
252 "Non-nil means insert the first line setting Org-mode in empty files.
253 When the function `org-mode' is called interactively in an empty file, this
254 normally means that the file name does not automatically trigger Org-mode.
255 To ensure that the file will always be in Org-mode in the future, a
256 line enforcing Org-mode will be inserted into the buffer, if this option
257 has been set."
258 :group 'org-startup
259 :type 'boolean)
260
261 (defcustom org-CUA-compatible nil
262 "Non-nil means use alternative key bindings for S-<cursor movement>.
263 Org-mode used S-<cursor movement> for changing timestamps and priorities.
264 S-<cursor movement> is also used for example by `CUA-mode' to select text.
265 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
266 alternative bindings. Setting this variable to t will replace the following
267 keys both in Org-mode and in the Org-agenda buffer.
268
269 S-RET -> C-S-RET
270 S-up -> M-p
271 S-down -> M-n
272 S-left -> M--
273 S-right -> M-+
274
275 If you do not like the alternative keys, take a look at the variable
276 `org-disputed-keys'.
277
278 This option is only relevant at load-time of Org-mode. Changing it requires
279 a restart of Emacs to become effective."
280 :group 'org-startup
281 :type 'boolean)
282
283 (defvar org-disputed-keys
284 '((S-up [(shift up)] [(meta ?p)])
285 (S-down [(shift down)] [(meta ?n)])
286 (S-left [(shift left)] [(meta ?-)])
287 (S-right [(shift right)] [(meta ?+)])
288 (S-return [(shift return)] [(control shift return)]))
289 "Keys for which Org-mode and other modes compete.
290 This is an alist, cars are symbols for lookup, 1st element is the default key,
291 second element will be used when `org-CUA-compatible' is t.")
292
293 (defun org-key (key)
294 "Select a key according to `org-CUA-compatible'."
295 (nth (if org-CUA-compatible 2 1)
296 (or (assq key org-disputed-keys)
297 (error "Invalid Key %s in `org-key'" key))))
298
299 (defcustom org-ellipsis nil
300 "The ellipsis to use in the Org-mode outline.
301 When nil, just use the standard three dots. When a string, use that instead,
302 and just in Org-mode (which will then use its own display table).
303 Changing this requires executing `M-x org-mode' in a buffer to become
304 effective."
305 :group 'org-startup
306 :type '(choice (const :tag "Default" nil)
307 (string :tag "String" :value "...#")))
308
309 (defvar org-display-table nil
310 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
311
312 (defgroup org-keywords nil
313 "Keywords in Org-mode."
314 :tag "Org Keywords"
315 :group 'org)
316
317 (defcustom org-deadline-string "DEADLINE:"
318 "String to mark deadline entries.
319 A deadline is this string, followed by a time stamp. Should be a word,
320 terminated by a colon. You can insert a schedule keyword and
321 a timestamp with \\[org-deadline].
322 Changes become only effective after restarting Emacs."
323 :group 'org-keywords
324 :type 'string)
325
326 (defcustom org-scheduled-string "SCHEDULED:"
327 "String to mark scheduled TODO entries.
328 A schedule is this string, followed by a time stamp. Should be a word,
329 terminated by a colon. You can insert a schedule keyword and
330 a timestamp with \\[org-schedule].
331 Changes become only effective after restarting Emacs."
332 :group 'org-keywords
333 :type 'string)
334
335 (defcustom org-closed-string "CLOSED:"
336 "String used as the prefix for timestamps logging closing a TODO entry."
337 :group 'org-keywords
338 :type 'string)
339
340 (defcustom org-clock-string "CLOCK:"
341 "String used as prefix for timestamps clocking work hours on an item."
342 :group 'org-keywords
343 :type 'string)
344
345 (defcustom org-comment-string "COMMENT"
346 "Entries starting with this keyword will never be exported.
347 An entry can be toggled between COMMENT and normal with
348 \\[org-toggle-comment].
349 Changes become only effective after restarting Emacs."
350 :group 'org-keywords
351 :type 'string)
352
353 (defcustom org-quote-string "QUOTE"
354 "Entries starting with this keyword will be exported in fixed-width font.
355 Quoting applies only to the text in the entry following the headline, and does
356 not extend beyond the next headline, even if that is lower level.
357 An entry can be toggled between QUOTE and normal with
358 \\[org-toggle-fixed-width-section]."
359 :group 'org-keywords
360 :type 'string)
361
362 (defgroup org-structure nil
363 "Options concerning the general structure of Org-mode files."
364 :tag "Org Structure"
365 :group 'org)
366
367 (defgroup org-cycle nil
368 "Options concerning visibility cycling in Org-mode."
369 :tag "Org Cycle"
370 :group 'org-structure)
371
372 (defcustom org-cycle-global-at-bob t
373 "Cycle globally if cursor is at beginning of buffer and not at a headline.
374 This makes it possible to do global cycling without having to use S-TAB or
375 C-u TAB. For this special case to work, the first line of the buffer
376 must not be a headline - it may be empty ot some other text. When used in
377 this way, `org-cycle-hook' is disables temporarily, to make sure the
378 cursor stays at the beginning of the buffer.
379 When this option is nil, don't do anything special at the beginning
380 of the buffer."
381 :group 'org-cycle
382 :type 'boolean)
383
384 (defcustom org-cycle-emulate-tab t
385 "Where should `org-cycle' emulate TAB.
386 nil Never
387 white Only in completely white lines
388 whitestart Only at the beginning of lines, before the first non-white char.
389 t Everywhere except in headlines
390 If TAB is used in a place where it does not emulate TAB, the current subtree
391 visibility is cycled."
392 :group 'org-cycle
393 :type '(choice (const :tag "Never" nil)
394 (const :tag "Only in completely white lines" white)
395 (const :tag "Before first char in a line" whitestart)
396 (const :tag "Everywhere except in headlines" t)
397 ))
398
399 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
400 "Hook that is run after `org-cycle' has changed the buffer visibility.
401 The function(s) in this hook must accept a single argument which indicates
402 the new state that was set by the most recent `org-cycle' command. The
403 argument is a symbol. After a global state change, it can have the values
404 `overview', `content', or `all'. After a local state change, it can have
405 the values `folded', `children', or `subtree'."
406 :group 'org-cycle
407 :type 'hook)
408
409 (defgroup org-edit-structure nil
410 "Options concerning structure editing in Org-mode."
411 :tag "Org Edit Structure"
412 :group 'org-structure)
413
414 (defcustom org-odd-levels-only nil
415 "Non-nil means, skip even levels and only use odd levels for the outline.
416 This has the effect that two stars are being added/taken away in
417 promotion/demotion commands. It also influences how levels are
418 handled by the exporters.
419 Changing it requires restart of `font-lock-mode' to become effective
420 for fontification also in regions already fontified.
421 You may also set this on a per-file basis by adding one of the following
422 lines to the buffer:
423
424 #+STARTUP: odd
425 #+STARTUP: oddeven"
426 :group 'org-edit-structure
427 :group 'org-font-lock
428 :type 'boolean)
429
430 (defcustom org-adapt-indentation t
431 "Non-nil means, adapt indentation when promoting and demoting.
432 When this is set and the *entire* text in an entry is indented, the
433 indentation is increased by one space in a demotion command, and
434 decreased by one in a promotion command. If any line in the entry
435 body starts at column 0, indentation is not changed at all."
436 :group 'org-edit-structure
437 :type 'boolean)
438
439 (defcustom org-insert-heading-hook nil
440 "Hook being run after inserting a new heading."
441 :group 'org-edit-structure
442 :type 'boolean)
443
444 (defcustom org-enable-fixed-width-editor t
445 "Non-nil means, lines starting with \":\" are treated as fixed-width.
446 This currently only means, they are never auto-wrapped.
447 When nil, such lines will be treated like ordinary lines.
448 See also the QUOTE keyword."
449 :group 'org-edit-structure
450 :type 'boolean)
451
452 (defgroup org-sparse-trees nil
453 "Options concerning sparse trees in Org-mode."
454 :tag "Org Sparse Trees"
455 :group 'org-structure)
456
457 (defcustom org-highlight-sparse-tree-matches t
458 "Non-nil means, highlight all matches that define a sparse tree.
459 The highlights will automatically disappear the next time the buffer is
460 changed by an edit command."
461 :group 'org-sparse-trees
462 :type 'boolean)
463
464 (defcustom org-show-hierarchy-above t
465 "Non-nil means, show full hierarchy when showing a spot in the tree.
466 Turning this off makes sparse trees more compact, but also less clear."
467 :group 'org-sparse-trees
468 :type 'boolean)
469
470 (defcustom org-show-following-heading t
471 "Non-nil means, show heading following match in `org-occur'.
472 When doing an `org-occur' it is useful to show the headline which
473 follows the match, even if they do not match the regexp. This makes it
474 easier to edit directly inside the sparse tree. However, if you use
475 `org-occur' mainly as an overview, the following headlines are
476 unnecessary clutter."
477 :group 'org-sparse-trees
478 :type 'boolean)
479
480 (defcustom org-occur-hook '(org-first-headline-recenter)
481 "Hook that is run after `org-occur' has constructed a sparse tree.
482 This can be used to recenter the window to show as much of the structure
483 as possible."
484 :group 'org-sparse-trees
485 :type 'hook)
486
487 (defgroup org-plain-lists nil
488 "Options concerning plain lists in Org-mode."
489 :tag "Org Plain lists"
490 :group 'org-structure)
491
492 (defcustom org-cycle-include-plain-lists nil
493 "Non-nil means, include plain lists into visibility cycling.
494 This means that during cycling, plain list items will *temporarily* be
495 interpreted as outline headlines with a level given by 1000+i where i is the
496 indentation of the bullet. In all other operations, plain list items are
497 not seen as headlines. For example, you cannot assign a TODO keyword to
498 such an item."
499 :group 'org-plain-lists
500 :type 'boolean)
501
502
503 (defcustom org-plain-list-ordered-item-terminator t
504 "The character that makes a line with leading number an ordered list item.
505 Valid values are ?. and ?\). To get both terminators, use t. While
506 ?. may look nicer, it creates the danger that a line with leading
507 number may be incorrectly interpreted as an item. ?\) therefore is
508 the safe choice."
509 :group 'org-plain-lists
510 :type '(choice (const :tag "dot like in \"2.\"" ?.)
511 (const :tag "paren like in \"2)\"" ?\))
512 (const :tab "both" t)))
513
514 (defcustom org-auto-renumber-ordered-lists t
515 "Non-nil means, automatically renumber ordered plain lists.
516 Renumbering happens when the sequence have been changed with
517 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
518 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
519 :group 'org-plain-lists
520 :type 'boolean)
521
522 (defgroup org-archive nil
523 "Options concerning archiving in Org-mode."
524 :tag "Org Archive"
525 :group 'org-structure)
526
527 (defcustom org-archive-location "%s_archive::"
528 "The location where subtrees should be archived.
529 This string consists of two parts, separated by a double-colon.
530
531 The first part is a file name - when omitted, archiving happens in the same
532 file. %s will be replaced by the current file name (without directory part).
533 Archiving to a different file is useful to keep archived entries from
534 contributing to the Org-mode Agenda.
535
536 The part after the double colon is a headline. The archived entries will be
537 filed under that headline. When omitted, the subtrees are simply filed away
538 at the end of the file, as top-level entries.
539
540 Here are a few examples:
541 \"%s_archive::\"
542 If the current file is Projects.org, archive in file
543 Projects.org_archive, as top-level trees. This is the default.
544
545 \"::* Archived Tasks\"
546 Archive in the current file, under the top-level headline
547 \"* Archived Tasks\".
548
549 \"~/org/archive.org::\"
550 Archive in file ~/org/archive.org (absolute path), as top-level trees.
551
552 \"basement::** Finished Tasks\"
553 Archive in file ./basement (relative path), as level 3 trees
554 below the level 2 heading \"** Finished Tasks\".
555
556 You may set this option on a per-file basis by adding to the buffer a
557 line like
558
559 #+ARCHIVE: basement::** Finished Tasks"
560 :group 'org-archive
561 :type 'string)
562
563 (defcustom org-archive-mark-done t
564 "Non-nil means, mark archived entries as DONE."
565 :group 'org-archive
566 :type 'boolean)
567
568 (defcustom org-archive-stamp-time t
569 "Non-nil means, add a time stamp to archived entries.
570 The time stamp will be added directly after the TODO state keyword in the
571 first line, so it is probably best to use this in combinations with
572 `org-archive-mark-done'."
573 :group 'org-archive
574 :type 'boolean)
575
576 (defgroup org-table nil
577 "Options concerning tables in Org-mode."
578 :tag "Org Table"
579 :group 'org)
580
581 (defcustom org-enable-table-editor 'optimized
582 "Non-nil means, lines starting with \"|\" are handled by the table editor.
583 When nil, such lines will be treated like ordinary lines.
584
585 When equal to the symbol `optimized', the table editor will be optimized to
586 do the following:
587 - Use automatic overwrite mode in front of whitespace in table fields.
588 This make the structure of the table stay in tact as long as the edited
589 field does not exceed the column width.
590 - Minimize the number of realigns. Normally, the table is aligned each time
591 TAB or RET are pressed to move to another field. With optimization this
592 happens only if changes to a field might have changed the column width.
593 Optimization requires replacing the functions `self-insert-command',
594 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
595 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
596 very good at guessing when a re-align will be necessary, but you can always
597 force one with \\[org-ctrl-c-ctrl-c].
598
599 If you would like to use the optimized version in Org-mode, but the
600 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
601
602 This variable can be used to turn on and off the table editor during a session,
603 but in order to toggle optimization, a restart is required.
604
605 See also the variable `org-table-auto-blank-field'."
606 :group 'org-table
607 :type '(choice
608 (const :tag "off" nil)
609 (const :tag "on" t)
610 (const :tag "on, optimized" optimized)))
611
612 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
613 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
614 In the optimized version, the table editor takes over all simple keys that
615 normally just insert a character. In tables, the characters are inserted
616 in a way to minimize disturbing the table structure (i.e. in overwrite mode
617 for empty fields). Outside tables, the correct binding of the keys is
618 restored.
619
620 The default for this option is t if the optimized version is also used in
621 Org-mode. See the variable `org-enable-table-editor' for details. Changing
622 this variable requires a restart of Emacs to become effective."
623 :group 'org-table
624 :type 'boolean)
625
626 (defgroup org-table-settings nil
627 "Settings for tables in Org-mode."
628 :tag "Org Table Settings"
629 :group 'org-table)
630
631 (defcustom org-table-default-size "5x2"
632 "The default size for newly created tables, Columns x Rows."
633 :group 'org-table-settings
634 :type 'string)
635
636 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
637 "Regular expression for recognizing numbers in table columns.
638 If a table column contains mostly numbers, it will be aligned to the
639 right. If not, it will be aligned to the left.
640
641 The default value of this option is a regular expression which allows
642 anything which looks remotely like a number as used in scientific
643 context. For example, all of the following will be considered a
644 number:
645 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
646
647 Other options offered by the customize interface are more restrictive."
648 :group 'org-table-settings
649 :type '(choice
650 (const :tag "Positive Integers"
651 "^[0-9]+$")
652 (const :tag "Integers"
653 "^[-+]?[0-9]+$")
654 (const :tag "Floating Point Numbers"
655 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
656 (const :tag "Floating Point Number or Integer"
657 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
658 (const :tag "Exponential, Floating point, Integer"
659 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
660 (const :tag "Very General Number-Like"
661 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
662 (string :tag "Regexp:")))
663
664 (defcustom org-table-number-fraction 0.5
665 "Fraction of numbers in a column required to make the column align right.
666 In a column all non-white fields are considered. If at least this
667 fraction of fields is matched by `org-table-number-fraction',
668 alignment to the right border applies."
669 :group 'org-table-settings
670 :type 'number)
671
672 (defgroup org-table-editing nil
673 "Bahavior of tables during editing in Org-mode."
674 :tag "Org Table Editing"
675 :group 'org-table)
676
677 (defcustom org-table-automatic-realign t
678 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
679 When nil, aligning is only done with \\[org-table-align], or after column
680 removal/insertion."
681 :group 'org-table-editing
682 :type 'boolean)
683
684 (defcustom org-table-limit-column-width t ;kw
685 "Non-nil means, allow to limit the width of table columns with <N> fields."
686 :group 'org-table-editing
687 :type 'boolean)
688
689 (defcustom org-table-auto-blank-field t
690 "Non-nil means, automatically blank table field when starting to type into it.
691 This only happens when typing immediately after a field motion
692 command (TAB, S-TAB or RET).
693 Only relevant when `org-enable-table-editor' is equal to `optimized'."
694 :group 'org-table-editing
695 :type 'boolean)
696
697 (defcustom org-table-tab-jumps-over-hlines t
698 "Non-nil means, tab in the last column of a table with jump over a hline.
699 If a horizontal separator line is following the current line,
700 `org-table-next-field' can either create a new row before that line, or jump
701 over the line. When this option is nil, a new line will be created before
702 this line."
703 :group 'org-table-editing
704 :type 'boolean)
705
706 (defcustom org-table-tab-recognizes-table.el t
707 "Non-nil means, TAB will automatically notice a table.el table.
708 When it sees such a table, it moves point into it and - if necessary -
709 calls `table-recognize-table'."
710 :group 'org-table-editing
711 :type 'boolean)
712
713 (defgroup org-table-calculation nil
714 "Options concerning tables in Org-mode."
715 :tag "Org Table Calculation"
716 :group 'org-table)
717
718 (defcustom org-table-copy-increment t
719 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
720 :group 'org-table-calculation
721 :type 'boolean)
722
723 (defcustom org-calc-default-modes
724 '(calc-internal-prec 12
725 calc-float-format (float 5)
726 calc-angle-mode deg
727 calc-prefer-frac nil
728 calc-symbolic-mode nil
729 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
730 calc-display-working-message t
731 )
732 "List with Calc mode settings for use in calc-eval for table formulas.
733 The list must contain alternating symbols (Calc modes variables and values).
734 Don't remove any of the default settings, just change the values. Org-mode
735 relies on the variables to be present in the list."
736 :group 'org-table-calculation
737 :type 'plist)
738
739 (defcustom org-table-formula-evaluate-inline t
740 "Non-nil means, TAB and RET evaluate a formula in current table field.
741 If the current field starts with an equal sign, it is assumed to be a formula
742 which should be evaluated as described in the manual and in the documentation
743 string of the command `org-table-eval-formula'. This feature requires the
744 Emacs calc package.
745 When this variable is nil, formula calculation is only available through
746 the command \\[org-table-eval-formula]."
747 :group 'org-table-calculation
748 :type 'boolean)
749
750
751 (defcustom org-table-formula-use-constants t
752 "Non-nil means, interpret constants in formulas in tables.
753 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
754 by the value given in `org-table-formula-constants', or by a value obtained
755 from the `constants.el' package."
756 :group 'org-table-calculation
757 :type 'boolean)
758
759 (defcustom org-table-formula-constants nil
760 "Alist with constant names and values, for use in table formulas.
761 The car of each element is a name of a constant, without the `$' before it.
762 The cdr is the value as a string. For example, if you'd like to use the
763 speed of light in a formula, you would configure
764
765 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
766
767 and then use it in an equation like `$1*$c'."
768 :group 'org-table-calculation
769 :type '(repeat
770 (cons (string :tag "name")
771 (string :tag "value"))))
772
773 (defcustom org-table-formula-numbers-only nil
774 "Non-nil means, calculate only with numbers in table formulas.
775 Then all input fields will be converted to a number, and the result
776 must also be a number. When nil, calc's full potential is available
777 in table calculations, including symbolics etc."
778 :group 'org-table-calculation
779 :type 'boolean)
780
781 (defcustom org-table-allow-automatic-line-recalculation t
782 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
783 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
784 :group 'org-table-calculation
785 :type 'boolean)
786
787 (defgroup org-link nil
788 "Options concerning links in Org-mode."
789 :tag "Org Link"
790 :group 'org)
791
792 (defcustom org-descriptive-links t
793 "Non-nil means, hide link part and only show description of bracket links.
794 Bracket links are like [[link][descritpion]]. This variable sets the initial
795 state in new org-mode buffers. The setting can then be toggled on a
796 per-buffer basis from the Org->Hyperlinks menu."
797 :group 'org-link
798 :type 'boolean)
799
800 (defcustom org-link-style 'bracket
801 "The style of links to be inserted with \\[org-insert-link].
802 Possible values are:
803 bracket [[link][description]]. This is recommended
804 plain Description \\n link. The old way, no longer recommended."
805 :group 'org-link
806 :type '(choice
807 (const :tag "Bracket (recommended)" bracket)
808 (const :tag "Plain (no longer recommended)" plain)))
809
810 (defcustom org-link-format "%s"
811 "Default format for external, URL-like linkes in the buffer.
812 This is a format string for printf, %s will be replaced by the link text.
813 The recommended value is just \"%s\", since links will be protected by
814 enclosing them in double brackets. If you prefer plain links (see variable
815 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
816 additional URL: prefix, so the format would be \"<URL:%s>\"."
817 :group 'org-link
818 :type '(choice
819 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
820 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
821 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
822 (string :tag "Other" :value "<%s>")))
823
824 (defcustom org-link-file-path-type 'adaptive
825 "How the path name in file links should be stored.
826 Valid values are:
827
828 relative relative to the current directory, i.e. the directory of the file
829 into which the link is being inserted.
830 absolute absolute path, if possible with ~ for home directory.
831 noabbrev absolute path, no abbreviation of home directory.
832 adaptive Use relative path for files in the current directory and sub-
833 directories of it. For other files, use an absolute path."
834 :group 'org-link
835 :type '(choice
836 (const relative)
837 (const absolute)
838 (const noabbrev)
839 (const adaptive)))
840
841 (defcustom org-activate-links '(bracket angle plain radio tag date)
842 "Types of links that should be activated in Org-mode files.
843 This is a list of symbols, each leading to the activation of a certain link
844 type. In principle, it does not hurt to turn on most link types - there may
845 be a small gain when turning off unused link types. The types are:
846
847 bracket The recommended [[link][description]] or [[link]] links with hiding.
848 angular Links in angular brackes that may contain whitespace like
849 <bbdb:Carsten Dominik>.
850 plain Plain links in normal text, no whitespace, like http://google.com.
851 radio Text that is matched by a radio target, see manual for details.
852 tag Tag settings in a headline (link to tag search).
853 date Time stamps (link to calendar).
854 camel CamelCase words defining text searches.
855
856 Changing this variable requires a restart of Emacs to become effective."
857 :group 'org-link
858 :type '(set (const :tag "Double bracket links (new style)" bracket)
859 (const :tag "Angular bracket links (old style)" angular)
860 (const :tag "plain text links" plain)
861 (const :tag "Radio target matches" radio)
862 (const :tag "Tags" tag)
863 (const :tag "Timestamps" date)
864 (const :tag "CamelCase words" camel)))
865
866 (defgroup org-link-store nil
867 "Options concerning storing links in Org-mode"
868 :tag "Org Store Link"
869 :group 'org-link)
870
871 (defcustom org-context-in-file-links t
872 "Non-nil means, file links from `org-store-link' contain context.
873 A search string will be added to the file name with :: as separator and
874 used to find the context when the link is activated by the command
875 `org-open-at-point'.
876 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
877 negates this setting for the duration of the command."
878 :group 'org-link-store
879 :type 'boolean)
880
881 (defcustom org-file-link-context-use-camel-case nil
882 "Non-nil means, use CamelCase to store a search context in a file link.
883 When nil, the search string simply consists of the words of the string.
884 CamelCase is deprecated, and support for it may be dropped in the future."
885 :group 'org-link-store
886 :type 'boolean)
887
888 (defcustom org-keep-stored-link-after-insertion nil
889 "Non-nil means, keep link in list for entire session.
890
891 The command `org-store-link' adds a link pointing to the current
892 location to an internal list. These links accumulate during a session.
893 The command `org-insert-link' can be used to insert links into any
894 Org-mode file (offering completion for all stored links). When this
895 option is nil, every link which has been inserted once using \\[org-insert-link]
896 will be removed from the list, to make completing the unused links
897 more efficient."
898 :group 'org-link-store
899 :type 'boolean)
900
901 (defcustom org-usenet-links-prefer-google nil
902 "Non-nil means, `org-store-link' will create web links to Google groups.
903 When nil, Gnus will be used for such links.
904 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
905 negates this setting for the duration of the command."
906 :group 'org-link-store
907 :type 'boolean)
908
909 (defgroup org-link-follow nil
910 "Options concerning following links in Org-mode"
911 :tag "Org Follow Link"
912 :group 'org-link)
913
914 (defcustom org-tab-follows-link nil
915 "Non-nil means, on links TAB will follow the link.
916 Needs to be set before org.el is loaded."
917 :group 'org-link-follow
918 :type 'boolean)
919
920 (defcustom org-return-follows-link nil
921 "Non-nil means, on links RET will follow the link.
922 Needs to be set before org.el is loaded."
923 :group 'org-link-follow
924 :type 'boolean)
925
926 (defcustom org-mouse-1-follows-link t
927 "Non-nil means, mouse-1 on a link will follow the link.
928 A longer mouse click will still set point. Does not wortk on XEmacs.
929 Needs to be set before org.el is loaded."
930 :group 'org-link-follow
931 :type 'boolean)
932
933 (defcustom org-mark-ring-length 4
934 "Number of different positions to be recorded in the ring
935 Changing this requires a restart of Emacs to work correctly."
936 :group 'org-link-follow
937 :type 'interger)
938
939 (defcustom org-link-frame-setup
940 '((vm . vm-visit-folder-other-frame)
941 (gnus . gnus-other-frame)
942 (file . find-file-other-window))
943 "Setup the frame configuration for following links.
944 When following a link with Emacs, it may often be useful to display
945 this link in another window or frame. This variable can be used to
946 set this up for the different types of links.
947 For VM, use any of
948 `vm-visit-folder'
949 `vm-visit-folder-other-frame'
950 For Gnus, use any of
951 `gnus'
952 `gnus-other-frame'
953 For FILE, use any of
954 `find-file'
955 `find-file-other-window'
956 `find-file-other-frame'
957 For the calendar, use the variable `calendar-setup'.
958 For BBDB, it is currently only possible to display the matches in
959 another window."
960 :group 'org-link-follow
961 :type '(list
962 (cons (const vm)
963 (choice
964 (const vm-visit-folder)
965 (const vm-visit-folder-other-window)
966 (const vm-visit-folder-other-frame)))
967 (cons (const gnus)
968 (choice
969 (const gnus)
970 (const gnus-other-frame)))
971 (cons (const file)
972 (choice
973 (const find-file)
974 (const find-file-other-window)
975 (const find-file-other-frame)))))
976
977 (defcustom org-open-non-existing-files nil
978 "Non-nil means, `org-open-file' will open non-existing file.
979 When nil, an error will be generated."
980 :group 'org-link-follow
981 :type 'boolean)
982
983 (defcustom org-confirm-shell-link-function 'yes-or-no-p
984 "Non-nil means, ask for confirmation before executing shell links.
985 Shell links can be dangerous, just thing about a link
986
987 [[shell:rm -rf ~/*][Google Search]]
988
989 This link would show up in your Org-mode document as \"Google Search\"
990 but really it would remove your entire home directory.
991 Therefore I *definitely* advise against setting this variable to nil.
992 Just change it to `y-or-n-p' of you want to confirm with a single key press
993 rather than having to type \"yes\"."
994 :group 'org-link-follow
995 :type '(choice
996 (const :tag "with yes-or-no (safer)" yes-or-no-p)
997 (const :tag "with y-or-n (faster)" y-or-n-p)
998 (const :tag "no confirmation (dangerous)" nil)))
999
1000 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1001 "Non-nil means, ask for confirmation before executing elisp links.
1002 Elisp links can be dangerous, just thing about a link
1003
1004 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1005
1006 This link would show up in your Org-mode document as \"Google Search\"
1007 but really it would remove your entire home directory.
1008 Therefore I *definitely* advise against setting this variable to nil.
1009 Just change it to `y-or-n-p' of you want to confirm with a single key press
1010 rather than having to type \"yes\"."
1011 :group 'org-link-follow
1012 :type '(choice
1013 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1014 (const :tag "with y-or-n (faster)" y-or-n-p)
1015 (const :tag "no confirmation (dangerous)" nil)))
1016
1017 (defconst org-file-apps-defaults-gnu
1018 '((t . mailcap))
1019 "Default file applications on a UNIX or GNU/Linux system.
1020 See `org-file-apps'.")
1021
1022 (defconst org-file-apps-defaults-macosx
1023 '((t . "open %s")
1024 ("ps" . "gv %s")
1025 ("ps.gz" . "gv %s")
1026 ("eps" . "gv %s")
1027 ("eps.gz" . "gv %s")
1028 ("dvi" . "xdvi %s")
1029 ("fig" . "xfig %s"))
1030 "Default file applications on a MacOS X system.
1031 The system \"open\" is known as a default, but we use X11 applications
1032 for some files for which the OS does not have a good default.
1033 See `org-file-apps'.")
1034
1035 (defconst org-file-apps-defaults-windowsnt
1036 (list (cons t
1037 (list (if (featurep 'xemacs)
1038 'mswindows-shell-execute
1039 'w32-shell-execute)
1040 "open" 'file)))
1041 "Default file applications on a Windows NT system.
1042 The system \"open\" is used for most files.
1043 See `org-file-apps'.")
1044
1045 (defcustom org-file-apps
1046 '(
1047 ("txt" . emacs)
1048 ("tex" . emacs)
1049 ("ltx" . emacs)
1050 ("org" . emacs)
1051 ("el" . emacs)
1052 ("bib" . emacs)
1053 )
1054 "External applications for opening `file:path' items in a document.
1055 Org-mode uses system defaults for different file types, but
1056 you can use this variable to set the application for a given file
1057 extension. The entries in this list are cons cells where the car identifies
1058 files and the cdr the corresponding command. Possible values for the
1059 file identifier are
1060 \"ext\" A string identifying an extension
1061 `directory' Matches a directory
1062 t Default for all remaining files
1063
1064 Possible values for the command are:
1065 `emacs' The file will be visited by the current Emacs process.
1066 `default' Use the default application for this file type.
1067 string A command to be executed by a shell; %s will be replaced
1068 by the path to the file.
1069 sexp A Lisp form which will be evaluated. The file path will
1070 be available in the Lisp variable `file'.
1071 For more examples, see the system specific constants
1072 `org-file-apps-defaults-macosx'
1073 `org-file-apps-defaults-windowsnt'
1074 `org-file-apps-defaults-gnu'."
1075 :group 'org-link-follow
1076 :type '(repeat
1077 (cons (choice :value ""
1078 (string :tag "Extension")
1079 (const :tag "Default for unrecognized files" t)
1080 (const :tag "Links to a directory" directory))
1081 (choice :value ""
1082 (const :tag "Visit with Emacs" emacs)
1083 (const :tag "Use system default" default)
1084 (string :tag "Command")
1085 (sexp :tag "Lisp form")))))
1086
1087 (defcustom org-mhe-search-all-folders nil
1088 "Non-nil means, that the search for the mh-message will be extended to
1089 all folders if the message cannot be found in the folder given in the link.
1090 Searching all folders is very effective with one of the search engines
1091 supported by MH-E, but will be slow with pick."
1092 :group 'org-link-follow
1093 :type 'boolean)
1094
1095 (defgroup org-remember nil
1096 "Options concerning interaction with remember.el."
1097 :tag "Org Remember"
1098 :group 'org)
1099
1100 (defcustom org-directory "~/org"
1101 "Directory with org files.
1102 This directory will be used as default to prompt for org files.
1103 Used by the hooks for remember.el."
1104 :group 'org-remember
1105 :type 'directory)
1106
1107 (defcustom org-default-notes-file "~/.notes"
1108 "Default target for storing notes.
1109 Used by the hooks for remember.el. This can be a string, or nil to mean
1110 the value of `remember-data-file'."
1111 :group 'org-remember
1112 :type '(choice
1113 (const :tag "Default from remember-data-file" nil)
1114 file))
1115
1116 (defcustom org-remember-templates nil
1117 "Templates for the creation of remember buffers.
1118 When nil, just let remember make the buffer.
1119 When not nil, this is a list of 3-element lists. In each entry, the first
1120 element is a character, a unique key to select this template.
1121 The second element is the template. The third element is optional and can
1122 specify a destination file for remember items created with this template.
1123 The default file is given by `org-default-notes-file'.
1124
1125 The template specifies the structure of the remember buffer. It should have
1126 a first line starting with a star, to act as the org-mode headline.
1127 Furthermore, the following %-escapes will be replaced with content:
1128 %t time stamp, date only
1129 %T time stamp with date and time
1130 %u inactive time stamp, date only
1131 %U inactive time stamp with date and time
1132 %n user name
1133 %a annotation, normally the link created with org-store-link
1134 %i initial content, the region when remember is called with C-u.
1135 If %i is indented, the entire inserted text will be indented as well.
1136 %? This will be removed, and the cursor placed at this position."
1137 :group 'org-remember
1138 :type '(repeat :tag "enabled"
1139 (list :value (?a "\n" nil)
1140 (character :tag "Selection Key")
1141 (string :tag "Template")
1142 (file :tag "Destination file (optional)"))))
1143
1144 (defcustom org-reverse-note-order nil
1145 "Non-nil means, store new notes at the beginning of a file or entry.
1146 When nil, new notes will be filed to the end of a file or entry."
1147 :group 'org-remember
1148 :type '(choice
1149 (const :tag "Reverse always" t)
1150 (const :tag "Reverse never" nil)
1151 (repeat :tag "By file name regexp"
1152 (cons regexp boolean))))
1153
1154 (defgroup org-todo nil
1155 "Options concerning TODO items in Org-mode."
1156 :tag "Org TODO"
1157 :group 'org)
1158
1159 (defcustom org-todo-keywords '("TODO" "DONE")
1160 "List of TODO entry keywords.
1161 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1162 considered to mean that the entry is \"done\". All the other mean that
1163 action is required, and will make the entry show up in todo lists, diaries
1164 etc.
1165 The command \\[org-todo] cycles an entry through these states, and an
1166 additional state where no keyword is present. For details about this
1167 cycling, see also the variable `org-todo-interpretation'
1168 Changes become only effective after restarting Emacs."
1169 :group 'org-todo
1170 :group 'org-keywords
1171 :type '(repeat (string :tag "Keyword")))
1172
1173 (defcustom org-todo-interpretation 'sequence
1174 "Controls how TODO keywords are interpreted.
1175 This variable is only relevant if `org-todo-keywords' contains more than two
1176 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1177
1178 When `sequence', \\[org-todo] will always switch to the next state in the
1179 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1180 to state when executed several times in direct succession. Otherwise, it
1181 switches directly to DONE from any state.
1182 See the manual for more information."
1183 :group 'org-todo
1184 :group 'org-keywords
1185 :type '(choice (const sequence)
1186 (const type)))
1187
1188 (defcustom org-after-todo-state-change-hook nil
1189 "Hook which is run after the state of a TODO item was changed.
1190 The new state (a string with a TODO keyword, or nil) is available in the
1191 Lisp variable `state'."
1192 :group 'org-todo
1193 :type 'hook)
1194
1195 (defcustom org-log-done nil
1196 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1197 When the state of an entry is changed from nothing to TODO, remove a previous
1198 closing date.
1199 This can also be configured on a per-file basis by adding one of
1200 the following lines anywhere in the buffer:
1201
1202 #+STARTUP: logging
1203 #+STARTUP: nologging"
1204 :group 'org-todo
1205 :type 'boolean)
1206
1207 (defgroup org-priorities nil
1208 "Priorities in Org-mode."
1209 :tag "Org Priorities"
1210 :group 'org-todo)
1211
1212 (defcustom org-default-priority ?B
1213 "The default priority of TODO items.
1214 This is the priority an item get if no explicit priority is given."
1215 :group 'org-priorities
1216 :type 'character)
1217
1218 (defcustom org-lowest-priority ?C
1219 "The lowest priority of TODO items. A character like ?A, ?B etc."
1220 :group 'org-priorities
1221 :type 'character)
1222
1223 (defgroup org-time nil
1224 "Options concerning time stamps and deadlines in Org-mode."
1225 :tag "Org Time"
1226 :group 'org)
1227
1228 (defcustom org-insert-labeled-timestamps-at-point nil
1229 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1230 When nil, these labeled time stamps are forces into the second line of an
1231 entry, just after the headline. When scheduling from the global TODO list,
1232 the time stamp will always be forced into the second line."
1233 :group 'org-time
1234 :type 'boolean)
1235
1236 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1237 "Formats for `format-time-string' which are used for time stamps.
1238 It is not recommended to change this constant.")
1239
1240 (defcustom org-time-stamp-rounding-minutes 0
1241 "Number of minutes to round time stamps to upon insertion.
1242 When zero, insert the time unmodified. Useful rounding numbers
1243 should be factors of 60, so for example 5, 10, 15.
1244 When this is not zero, you can still force an exact time-stamp by using
1245 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1246 :group 'org-time
1247 :type 'integer)
1248
1249 (defcustom org-deadline-warning-days 30
1250 "No. of days before expiration during which a deadline becomes active.
1251 This variable governs the display in the org file."
1252 :group 'org-time
1253 :type 'number)
1254
1255 (defcustom org-popup-calendar-for-date-prompt t
1256 "Non-nil means, pop up a calendar when prompting for a date.
1257 In the calendar, the date can be selected with mouse-1. However, the
1258 minibuffer will also be active, and you can simply enter the date as well.
1259 When nil, only the minibuffer will be available."
1260 :group 'org-time
1261 :type 'boolean)
1262
1263 (defcustom org-calendar-follow-timestamp-change t
1264 "Non-nil means, make the calendar window follow timestamp changes.
1265 When a timestamp is modified and the calendar window is visible, it will be
1266 moved to the new date."
1267 :group 'org-time
1268 :type 'boolean)
1269
1270 (defgroup org-tags nil
1271 "Options concerning tags in Org-mode."
1272 :tag "Org Tags"
1273 :group 'org)
1274
1275 (defcustom org-tag-alist nil
1276 "List of tags allowed in Org-mode files.
1277 When this list is nil, Org-mode will base TAG input on what is already in the
1278 buffer.
1279 The value of this variable is an alist, the car may be (and should) be a
1280 character that is used to select that tag through the fast-tag-selection
1281 interface. See the manual for details."
1282 :group 'org-tags
1283 :type '(repeat
1284 (choice
1285 (cons (string :tag "Tag name")
1286 (character :tag "Access char"))
1287 (const :tag "Start radio group" (:startgroup))
1288 (const :tag "End radio group" (:endgroup)))))
1289
1290 (defcustom org-use-fast-tag-selection 'auto
1291 "Non-nil means, use fast tag selection scheme.
1292 This is a special interface to select and deselect tags with single keys.
1293 When nil, fast selection is never used.
1294 When the symbol `auto', fast selection is used if and only if selection
1295 characters for tags have been configured, either through the variable
1296 `org-tag-alist' or through a #+TAGS line in the buffer.
1297 When t, fast selection is always used and selection keys are assigned
1298 automatically if necessary."
1299 :group 'org-tags
1300 :type '(choice
1301 (const :tag "Always" t)
1302 (const :tag "Never" nil)
1303 (const :tag "When selection characters are configured" 'auto)))
1304
1305 (defcustom org-tags-column 48
1306 "The column to which tags should be indented in a headline.
1307 If this number is positive, it specifies the column. If it is negative,
1308 it means that the tags should be flushright to that column. For example,
1309 -79 works well for a normal 80 character screen."
1310 :group 'org-tags
1311 :type 'integer)
1312
1313 (defcustom org-auto-align-tags t
1314 "Non-nil means, realign tags after pro/demotion of TODO state change.
1315 These operations change the length of a headline and therefore shift
1316 the tags around. With this options turned on, after each such operation
1317 the tags are again aligned to `org-tags-column'."
1318 :group 'org-tags
1319 :type 'boolean)
1320
1321 (defcustom org-use-tag-inheritance t
1322 "Non-nil means, tags in levels apply also for sublevels.
1323 When nil, only the tags directly given in a specific line apply there.
1324 If you turn off this option, you very likely want to turn on the
1325 companion option `org-tags-match-list-sublevels'."
1326 :group 'org-tags
1327 :type 'boolean)
1328
1329 (defcustom org-tags-match-list-sublevels nil
1330 "Non-nil means list also sublevels of headlines matching tag search.
1331 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1332 the sublevels of a headline matching a tag search often also match
1333 the same search. Listing all of them can create very long lists.
1334 Setting this variable to nil causes subtrees of a match to be skipped.
1335 This option is off by default, because inheritance in on. If you turn
1336 inheritance off, you very likely want to turn this option on.
1337
1338 As a special case, if the tag search is restricted to TODO items, the
1339 value of this variable is ignored and sublevels are always checked, to
1340 make sure all corresponding TODO items find their way into the list."
1341 :group 'org-tags
1342 :type 'boolean)
1343
1344 (defvar org-tags-history nil
1345 "History of minibuffer reads for tags.")
1346 (defvar org-last-tags-completion-table nil
1347 "The last used completion table for tags.")
1348
1349 (defgroup org-agenda nil
1350 "Options concerning agenda display Org-mode."
1351 :tag "Org Agenda"
1352 :group 'org)
1353
1354 (defvar org-category nil
1355 "Variable used by org files to set a category for agenda display.
1356 Such files should use a file variable to set it, for example
1357
1358 -*- mode: org; org-category: \"ELisp\"
1359
1360 or contain a special line
1361
1362 #+CATEGORY: ELisp
1363
1364 If the file does not specify a category, then file's base name
1365 is used instead.")
1366 (make-variable-buffer-local 'org-category)
1367
1368 (defcustom org-agenda-files nil
1369 "The files to be used for agenda display.
1370 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1371 \\[org-remove-file]. You can also use customize to edit the list.
1372
1373 If the value of the variable is not a list but a single file name, then
1374 the list of agenda files is actually stored and maintained in that file, one
1375 agenda file per line."
1376 :group 'org-agenda
1377 :type '(choice
1378 (repeat :tag "List of files" file)
1379 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1380
1381 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1382 "Custom commands for the agenda.
1383 These commands will be offered on the splash screen displayed by the
1384 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1385
1386 key The key (a single char as a string) to be associated with the command.
1387 type The command type, any of the following symbols:
1388 todo Entries with a specific TODO keyword, in all agenda files.
1389 tags Tags match in all agenda files.
1390 tags-todo Tags match in all agenda files, TODO entries only.
1391 todo-tree Sparse tree of specific TODO keyword in *current* file.
1392 tags-tree Sparse tree with all tags matches in *current* file.
1393 occur-tree Occur sparse tree for current file.
1394 match What to search for:
1395 - a single keyword for TODO keyword searches
1396 - a tags match expression for tags searches
1397 - a regular expression for occur searches"
1398 :group 'org-agenda
1399 :type '(repeat
1400 (list (string :tag "Key")
1401 (choice :tag "Type"
1402 (const :tag "Tags search in all agenda files" tags)
1403 (const :tag "Tags search of TODO entries, all agenda files" tags-todo)
1404 (const :tag "TODO keyword search in all agenda files" todo)
1405 (const :tag "Tags sparse tree in current buffer" tags-tree)
1406 (const :tag "TODO keyword tree in current buffer" todo-tree)
1407 (const :tag "Occur tree in current buffer" occur-tree))
1408 (string :tag "Match"))))
1409
1410 (defcustom org-agenda-todo-list-sublevels t
1411 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1412 When nil, the sublevels of a TODO entry are not checked, resulting in
1413 potentially much shorter TODO lists."
1414 :group 'org-agenda
1415 :group 'org-todo
1416 :type 'boolean)
1417
1418 (defcustom org-agenda-todo-ignore-scheduled nil
1419 "Non-nil means, don't show scheduled entries in the global todo list.
1420 The idea behind this is that by scheduling it, you have already taken care
1421 of this item."
1422 :group 'org-agenda
1423 :group 'org-todo
1424 :type 'boolean)
1425
1426 (defcustom org-agenda-include-all-todo nil
1427 "Non-nil means, the agenda will always contain all TODO entries.
1428 When nil, date-less entries will only be shown if `org-agenda' is called
1429 with a prefix argument.
1430 When non-nil, the TODO entries will be listed at the top of the agenda, before
1431 the entries for specific days."
1432 :group 'org-agenda
1433 :type 'boolean)
1434
1435 (defcustom org-agenda-include-diary nil
1436 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1437 :group 'org-agenda
1438 :type 'boolean)
1439
1440 (defcustom org-calendar-to-agenda-key [?c]
1441 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1442 The command `org-calendar-goto-agenda' will be bound to this key. The
1443 default is the character `c' because then `c' can be used to switch back and
1444 forth between agenda and calendar."
1445 :group 'org-agenda
1446 :type 'sexp)
1447
1448 (defgroup org-agenda-setup nil
1449 "Options concerning setting up the Agenda window in Org Mode."
1450 :tag "Org Agenda Window Setup"
1451 :group 'org-agenda)
1452
1453 (defcustom org-agenda-mouse-1-follows-link nil
1454 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1455 A longer mouse click will still set point. Does not wortk on XEmacs.
1456 Needs to be set before org.el is loaded."
1457 :group 'org-agenda-setup
1458 :type 'boolean)
1459
1460 (defcustom org-agenda-start-with-follow-mode nil
1461 "The initial value of follwo-mode in a newly created agenda window."
1462 :group 'org-agenda-setup
1463 :type 'boolean)
1464
1465 (defcustom org-select-agenda-window t
1466 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1467 When nil, cursor will remain in the current window."
1468 :group 'org-agenda-setup
1469 :type 'boolean)
1470
1471 (defcustom org-fit-agenda-window t
1472 "Non-nil means, change window size of agenda to fit content."
1473 :group 'org-agenda-setup
1474 :type 'boolean)
1475
1476 (defgroup org-agenda-display nil
1477 "Options concerning what to display initially in Agenda."
1478 :tag "Org Agenda Display"
1479 :group 'org-agenda)
1480
1481 (defcustom org-agenda-show-all-dates t
1482 "Non-nil means, `org-agenda' shows every day in the selected range.
1483 When nil, only the days which actually have entries are shown."
1484 :group 'org-agenda-display
1485 :type 'boolean)
1486
1487 (defcustom org-agenda-start-on-weekday 1
1488 "Non-nil means, start the overview always on the specified weekday.
1489 0 denotes Sunday, 1 denotes Monday etc.
1490 When nil, always start on the current day."
1491 :group 'org-agenda-display
1492 :type '(choice (const :tag "Today" nil)
1493 (number :tag "Weekday No.")))
1494
1495 (defcustom org-agenda-ndays 7
1496 "Number of days to include in overview display.
1497 Should be 1 or 7."
1498 :group 'org-agenda-display
1499 :type 'number)
1500
1501 (defcustom org-agenda-use-time-grid t
1502 "Non-nil means, show a time grid in the agenda schedule.
1503 A time grid is a set of lines for specific times (like every two hours between
1504 8:00 and 20:00). The items scheduled for a day at specific times are
1505 sorted in between these lines.
1506 For details about when the grid will be shown, and what it will look like, see
1507 the variable `org-agenda-time-grid'."
1508 :group 'org-agenda-display
1509 :type 'boolean)
1510
1511 (defcustom org-agenda-time-grid
1512 '((daily today require-timed)
1513 "----------------"
1514 (800 1000 1200 1400 1600 1800 2000))
1515
1516 "The settings for time grid for agenda display.
1517 This is a list of three items. The first item is again a list. It contains
1518 symbols specifying conditions when the grid should be displayed:
1519
1520 daily if the agenda shows a single day
1521 weekly if the agenda shows an entire week
1522 today show grid on current date, independent of daily/weekly display
1523 require-timed show grid only if at least on item has a time specification
1524
1525 The second item is a string which will be places behing the grid time.
1526
1527 The third item is a list of integers, indicating the times that should have
1528 a grid line."
1529 :group 'org-agenda-display
1530 :type
1531 '(list
1532 (set :greedy t :tag "Grid Display Options"
1533 (const :tag "Show grid in single day agenda display" daily)
1534 (const :tag "Show grid in weekly agenda display" weekly)
1535 (const :tag "Always show grid for today" today)
1536 (const :tag "Show grid only if any timed entries are present"
1537 require-timed)
1538 (const :tag "Skip grid times already present in an entry"
1539 remove-match))
1540 (string :tag "Grid String")
1541 (repeat :tag "Grid Times" (integer :tag "Time"))))
1542
1543 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1544 "Sorting structure for the agenda items of a single day.
1545 This is a list of symbols which will be used in sequence to determine
1546 if an entry should be listed before another entry. The following
1547 symbols are recognized:
1548
1549 time-up Put entries with time-of-day indications first, early first
1550 time-down Put entries with time-of-day indications first, late first
1551 category-keep Keep the default order of categories, corresponding to the
1552 sequence in `org-agenda-files'.
1553 category-up Sort alphabetically by category, A-Z.
1554 category-down Sort alphabetically by category, Z-A.
1555 priority-up Sort numerically by priority, high priority last.
1556 priority-down Sort numerically by priority, high priority first.
1557
1558 The different possibilities will be tried in sequence, and testing stops
1559 if one comparison returns a \"not-equal\". For example, the default
1560 '(time-up category-keep priority-down)
1561 means: Pull out all entries having a specified time of day and sort them,
1562 in order to make a time schedule for the current day the first thing in the
1563 agenda listing for the day. Of the entries without a time indication, keep
1564 the grouped in categories, don't sort the categories, but keep them in
1565 the sequence given in `org-agenda-files'. Within each category sort by
1566 priority.
1567
1568 Leaving out `category-keep' would mean that items will be sorted across
1569 categories by priority."
1570 :group 'org-agenda-display
1571 :type '(repeat
1572 (choice
1573 (const time-up)
1574 (const time-down)
1575 (const category-keep)
1576 (const category-up)
1577 (const category-down)
1578 (const priority-up)
1579 (const priority-down))))
1580
1581 (defcustom org-sort-agenda-notime-is-late t
1582 "Non-nil means, items without time are considered late.
1583 This is only relevant for sorting. When t, items which have no explicit
1584 time like 15:30 will be considered as 99:01, i.e. later than any items which
1585 do have a time. When nil, the default time is before 0:00. You can use this
1586 option to decide if the schedule for today should come before or after timeless
1587 agenda entries."
1588 :group 'org-agenda-display
1589 :type 'boolean)
1590
1591
1592 (defgroup org-agenda-prefix nil
1593 "Options concerning the entry prefix in the Org-mode agenda display."
1594 :tag "Org Agenda Prefix"
1595 :group 'org-agenda)
1596
1597 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1598 "Format specification for the prefix of items in the agenda buffer.
1599 This format works similar to a printf format, with the following meaning:
1600
1601 %c the category of the item, \"Diary\" for entries from the diary, or
1602 as given by the CATEGORY keyword or derived from the file name.
1603 %T the first tag of the item.
1604 %t the time-of-day specification if one applies to the entry, in the
1605 format HH:MM
1606 %s Scheduling/Deadline information, a short string
1607
1608 All specifiers work basically like the standard `%s' of printf, but may
1609 contain two additional characters: A question mark just after the `%' and
1610 a whitespace/punctuation character just before the final letter.
1611
1612 If the first character after `%' is a question mark, the entire field
1613 will only be included if the corresponding value applies to the
1614 current entry. This is useful for fields which should have fixed
1615 width when present, but zero width when absent. For example,
1616 \"%?-12t\" will result in a 12 character time field if a time of the
1617 day is specified, but will completely disappear in entries which do
1618 not contain a time.
1619
1620 If there is punctuation or whitespace character just before the final
1621 format letter, this character will be appended to the field value if
1622 the value is not empty. For example, the format \"%-12:c\" leads to
1623 \"Diary: \" if the category is \"Diary\". If the category were be
1624 empty, no additional colon would be interted.
1625
1626 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1627 - Indent the line with two space characters
1628 - Give the category in a 12 chars wide field, padded with whitespace on
1629 the right (because of `-'). Append a colon if there is a category
1630 (because of `:').
1631 - If there is a time-of-day, put it into a 12 chars wide field. If no
1632 time, don't put in an empty field, just skip it (because of '?').
1633 - Finally, put the scheduling information and append a whitespace.
1634
1635 As another example, if you don't want the time-of-day of entries in
1636 the prefix, you could use:
1637
1638 (setq org-agenda-prefix-format \" %-11:c% s\")
1639
1640 See also the variables `org-agenda-remove-times-when-in-prefix' and
1641 `org-agenda-remove-tags-when-in-prefix'."
1642 :type 'string
1643 :group 'org-agenda-prefix)
1644
1645 (defvar org-prefix-format-compiled nil
1646 "The compiled version of the most recently used prefix format.
1647 Depending on which command was used last, this may be the compiled version
1648 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1649
1650 (defcustom org-agenda-remove-times-when-in-prefix t
1651 "Non-nil means, remove duplicate time specifications in agenda items.
1652 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1653 time-of-day specification in a headline or diary entry is extracted and
1654 placed into the prefix. If this option is non-nil, the original specification
1655 \(a timestamp or -range, or just a plain time(range) specification like
1656 11:30-4pm) will be removed for agenda display. This makes the agenda less
1657 cluttered.
1658 The option can be t or nil. It may also be the symbol `beg', indicating
1659 that the time should only be removed what it is located at the beginning of
1660 the headline/diary entry."
1661 :group 'org-agenda-prefix
1662 :type '(choice
1663 (const :tag "Always" t)
1664 (const :tag "Never" nil)
1665 (const :tag "When at beginning of entry" beg)))
1666
1667 (defcustom org-agenda-remove-tags-when-in-prefix nil
1668 "Non-nil means, remove the tags from the headline copy in the agenda.
1669 When this is the symbol `prefix', only remove tags when
1670 `org-agenda-prefix-format' contains a `%T' specifier."
1671 :group 'org-agenda-prefix
1672 :type '(choice
1673 (const :tag "Always" t)
1674 (const :tag "Never" nil)
1675 (const :tag "When prefix format contains %T" prefix)))
1676
1677 (defgroup org-agenda-timeline nil
1678 "Options concerning the timeline buffer in Org Mode."
1679 :tag "Org Agenda Timeline"
1680 :group 'org-agenda)
1681
1682 (defcustom org-timeline-prefix-format " % s"
1683 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1684 :type 'string
1685 :group 'org-agenda-timeline)
1686
1687 (defcustom org-select-timeline-window t
1688 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1689 When nil, cursor will remain in the current window."
1690 :group 'org-agenda-timeline
1691 :type 'boolean)
1692
1693 (defcustom org-timeline-show-empty-dates 3
1694 "Non-nil means, `org-timeline' also shows dates without an entry.
1695 When nil, only the days which actually have entries are shown.
1696 When t, all days between the first and the last date are shown.
1697 When an integer, show also empty dates, but if there is a gap of more than
1698 N days, just insert a special line indicating the size of the gap."
1699 :group 'org-agenda-timeline
1700 :type '(choice
1701 (const :tag "None" nil)
1702 (const :tag "All" t)
1703 (number :tag "at most")))
1704
1705 (defgroup org-export nil
1706 "Options for exporting org-listings."
1707 :tag "Org Export"
1708 :group 'org)
1709
1710 (defgroup org-export-general nil
1711 "General options for exporting Org-mode files."
1712 :tag "Org Export General"
1713 :group 'org-export)
1714
1715 (defcustom org-export-publishing-directory "."
1716 "Path to the location where exported files should be located.
1717 This path may be relative to the directory where the Org-mode file lives.
1718 The default is to put them into the same directory as the Org-mode file.
1719 The variable may also be an alist with export types `:html', `:ascii',
1720 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1721 is relative, it is interpreted relative to the directory where the exported
1722 Org-mode files lives."
1723 :group 'org-export-general
1724 :type '(choice
1725 (directory)
1726 (repeat
1727 (cons
1728 (choice :tag "Type"
1729 (const :html) (const :ascii) (const :ical) (const :xoxo))
1730 (directory)))))
1731
1732 (defcustom org-export-language-setup
1733 '(("en" "Author" "Date" "Table of Contents")
1734 ("da" "Ophavsmand" "Dato" "Indhold")
1735 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1736 ("es" "Autor" "Fecha" "\xccndice")
1737 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1738 ("it" "Autore" "Data" "Indice")
1739 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1740 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1741 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1742 "Terms used in export text, translated to different languages.
1743 Use the variable `org-export-default-language' to set the language,
1744 or use the +OPTION lines for a per-file setting."
1745 :group 'org-export-general
1746 :type '(repeat
1747 (list
1748 (string :tag "HTML language tag")
1749 (string :tag "Author")
1750 (string :tag "Date")
1751 (string :tag "Table of Contents"))))
1752
1753 (defcustom org-export-default-language "en"
1754 "The default language of HTML export, as a string.
1755 This should have an association in `org-export-language-setup'."
1756 :group 'org-export-general
1757 :type 'string)
1758
1759 (defcustom org-export-headline-levels 3
1760 "The last level which is still exported as a headline.
1761 Inferior levels will produce itemize lists when exported.
1762 Note that a numeric prefix argument to an exporter function overrides
1763 this setting.
1764
1765 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1766 :group 'org-export-general
1767 :type 'number)
1768
1769 (defcustom org-export-with-section-numbers t
1770 "Non-nil means, add section numbers to headlines when exporting.
1771
1772 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1773 :group 'org-export-general
1774 :type 'boolean)
1775
1776 (defcustom org-export-with-toc t
1777 "Non-nil means, create a table of contents in exported files.
1778 The TOC contains headlines with levels up to`org-export-headline-levels'.
1779
1780 Headlines which contain any TODO items will be marked with \"(*)\" in
1781 ASCII export, and with red color in HTML output.
1782
1783 In HTML output, the TOC will be clickable.
1784
1785 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1786 :group 'org-export-general
1787 :type 'boolean)
1788
1789 (defcustom org-export-mark-todo-in-toc nil
1790 "Non-nil means, mark TOC lines that contain any open TODO items."
1791 :group 'org-export-general
1792 :type 'boolean)
1793
1794 (defcustom org-export-preserve-breaks nil
1795 "Non-nil means, preserve all line breaks when exporting.
1796 Normally, in HTML output paragraphs will be reformatted. In ASCII
1797 export, line breaks will always be preserved, regardless of this variable.
1798
1799 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1800 :group 'org-export-general
1801 :type 'boolean)
1802
1803 (defcustom org-export-with-timestamps t
1804 "Nil means, do not export time stamps and associated keywords."
1805 :group 'org-export
1806 :type 'boolean)
1807
1808 (defcustom org-export-with-tags t
1809 "Nil means, do not export tags, just remove them from headlines."
1810 :group 'org-export-general
1811 :type 'boolean)
1812
1813 (defcustom org-export-with-timestamps t
1814 "Nil means, do not export timestamps and associated keywords."
1815 :group 'org-export-general
1816 :type 'boolean)
1817
1818 (defgroup org-export-translation nil
1819 "Options for translating special ascii sequences for the export backends."
1820 :tag "Org Export Translation"
1821 :group 'org-export)
1822
1823 (defcustom org-export-with-emphasize t
1824 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1825 If the export target supports emphasizing text, the word will be
1826 typeset in bold, italic, or underlined, respectively. Works only for
1827 single words, but you can say: I *really* *mean* *this*.
1828 Not all export backends support this.
1829
1830 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1831 :group 'org-export-translation
1832 :type 'boolean)
1833
1834 (defcustom org-export-with-sub-superscripts t
1835 "Non-nil means, interpret \"_\" and \"^\" for export.
1836 When this option is turned on, you can use TeX-like syntax for sub- and
1837 superscripts. Several characters after \"_\" or \"^\" will be
1838 considered as a single item - so grouping with {} is normally not
1839 needed. For example, the following things will be parsed as single
1840 sub- or superscripts.
1841
1842 10^24 or 10^tau several digits will be considered 1 item.
1843 10^-12 or 10^-tau a leading sign with digits or a word
1844 x^2-y^3 will be read as x^2 - y^3, because items are
1845 terminated by almost any nonword/nondigit char.
1846 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1847
1848 Still, ambiguity is possible - so when in doubt use {} to enclose the
1849 sub/superscript.
1850 Not all export backends support this, but HTML does.
1851
1852 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1853 :group 'org-export-translation
1854 :type 'boolean)
1855
1856 (defcustom org-export-with-TeX-macros t
1857 "Non-nil means, interpret simple TeX-like macros when exporting.
1858 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1859 No only real TeX macros will work here, but the standard HTML entities
1860 for math can be used as macro names as well. For a list of supported
1861 names in HTML export, see the constant `org-html-entities'.
1862 Not all export backends support this.
1863
1864 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1865 :group 'org-export-translation
1866 :type 'boolean)
1867
1868 (defcustom org-export-with-fixed-width t
1869 "Non-nil means, lines starting with \":\" will be in fixed width font.
1870 This can be used to have pre-formatted text, fragments of code etc. For
1871 example:
1872 : ;; Some Lisp examples
1873 : (while (defc cnt)
1874 : (ding))
1875 will be looking just like this in also HTML. See also the QUOTE keyword.
1876 Not all export backends support this.
1877
1878 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1879 :group 'org-export-translation
1880 :type 'boolean)
1881
1882 (defcustom org-match-sexp-depth 3
1883 "Number of stacked braces for sub/superscript matching.
1884 This has to be set before loading org.el to be effective."
1885 :group 'org-export-translation
1886 :type 'integer)
1887
1888 (defgroup org-export-tables nil
1889 "Options for exporting tables in Org-mode."
1890 :tag "Org Export Tables"
1891 :group 'org-export)
1892
1893 (defcustom org-export-with-tables t
1894 "If non-nil, lines starting with \"|\" define a table.
1895 For example:
1896
1897 | Name | Address | Birthday |
1898 |-------------+----------+-----------|
1899 | Arthur Dent | England | 29.2.2100 |
1900
1901 Not all export backends support this.
1902
1903 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1904 :group 'org-export-tables
1905 :type 'boolean)
1906
1907 (defcustom org-export-highlight-first-table-line t
1908 "Non-nil means, highlight the first table line.
1909 In HTML export, this means use <th> instead of <td>.
1910 In tables created with table.el, this applies to the first table line.
1911 In Org-mode tables, all lines before the first horizontal separator
1912 line will be formatted with <th> tags."
1913 :group 'org-export-tables
1914 :type 'boolean)
1915
1916 (defcustom org-export-table-remove-special-lines t
1917 "Remove special lines and marking characters in calculating tables.
1918 This removes the special marking character column from tables that are set
1919 up for spreadsheet calculations. It also removes the entire lines
1920 marked with `!', `_', or `^'. The lines with `$' are kept, because
1921 the values of constants may be useful to have."
1922 :group 'org-export-tables
1923 :type 'boolean)
1924
1925 (defcustom org-export-prefer-native-exporter-for-tables nil
1926 "Non-nil means, always export tables created with table.el natively.
1927 Natively means, use the HTML code generator in table.el.
1928 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1929 the table does not use row- or column-spanning). This has the
1930 advantage, that the automatic HTML conversions for math symbols and
1931 sub/superscripts can be applied. Org-mode's HTML generator is also
1932 much faster."
1933 :group 'org-export-tables
1934 :type 'boolean)
1935
1936 (defgroup org-export-ascii nil
1937 "Options specific for ASCII export of Org-mode files."
1938 :tag "Org Export ASCII"
1939 :group 'org-export)
1940
1941 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
1942 "Characters for underlining headings in ASCII export.
1943 In the given sequence, these characters will be used for level 1, 2, ..."
1944 :group 'org-export-ascii
1945 :type '(repeat character))
1946
1947 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
1948 "Bullet characters for headlines converted to lists in ASCII export.
1949 The first character is is used for the first lest level generated in this
1950 way, and so on. If there are more levels than characters given here,
1951 the list will be repeated.
1952 Note that plain lists will keep the same bullets as the have in the
1953 Org-mode file."
1954 :group 'org-export-ascii
1955 :type '(repeat character))
1956
1957 (defcustom org-export-ascii-show-new-buffer t
1958 "Non-nil means, popup buffer containing the exported ASCII text.
1959 Otherwise the buffer will just be saved to a file and stay hidden."
1960 :group 'org-export-ascii
1961 :type 'boolean)
1962
1963 (defgroup org-export-xml nil
1964 "Options specific for XML export of Org-mode files."
1965 :tag "Org Export XML"
1966 :group 'org-export)
1967
1968 (defgroup org-export-html nil
1969 "Options specific for HTML export of Org-mode files."
1970 :tag "Org Export HTML"
1971 :group 'org-export)
1972
1973 (defcustom org-export-html-style
1974 "<style type=\"text/css\">
1975 html {
1976 font-family: Times, serif;
1977 font-size: 12pt;
1978 }
1979 .title { text-align: center; }
1980 .todo { color: red; }
1981 .done { color: green; }
1982 .timestamp { color: grey }
1983 .timestamp-kwd { color: CadetBlue }
1984 .tag { background-color:lightblue; font-weight:normal }
1985 .target { background-color: lavender; }
1986 pre {
1987 border: 1pt solid #AEBDCC;
1988 background-color: #F3F5F7;
1989 padding: 5pt;
1990 font-family: courier, monospace;
1991 }
1992 table { border-collapse: collapse; }
1993 td, th {
1994 vertical-align: top;
1995 border: 1pt solid #ADB9CC;
1996 }
1997 </style>"
1998 "The default style specification for exported HTML files.
1999 Since there are different ways of setting style information, this variable
2000 needs to contain the full HTML structure to provide a style, including the
2001 surrounding HTML tags. The style specifications should include definitions
2002 for new classes todo, done, title, and deadline. For example, legal values
2003 would be:
2004
2005 <style type=\"text/css\">
2006 p { font-weight: normal; color: gray; }
2007 h1 { color: black; }
2008 .title { text-align: center; }
2009 .todo, .deadline { color: red; }
2010 .done { color: green; }
2011 </style>
2012
2013 or, if you want to keep the style in a file,
2014
2015 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2016
2017 As the value of this option simply gets inserted into the HTML <head> header,
2018 you can \"misuse\" it to add arbitrary text to the header."
2019 :group 'org-export-html
2020 :type 'string)
2021
2022 (defcustom org-export-html-link-org-files-as-html t
2023 "Non-nil means, make file links to `file.org' point to `file.html'.
2024 When org-mode is exporting an org-mode file to HTML, links to
2025 non-html files are directly put into a href tag in HTML.
2026 However, links to other Org-mode files (recognized by the
2027 extension `.org.) should become links to the corresponding html
2028 file, assuming that the linked org-mode file will also be
2029 converted to HTML.
2030 When nil, the links still point to the plain `.org' file."
2031 :group 'org-export-html
2032 :type 'boolean)
2033
2034 (defcustom org-export-html-inline-images 'maybe
2035 "Non-nil means, inline images into exported HTML pages.
2036 This is done using an <img> tag. When nil, an anchor with href is used to
2037 link to the image. If this option is `maybe', then images in links with
2038 an empty description will be inlined, while images with a description will
2039 be linked only."
2040 :group 'org-export-html
2041 :type '(choice (const :tag "Never" nil)
2042 (const :tag "Always" t)
2043 (const :tag "When there is no description" maybe)))
2044
2045 (defcustom org-export-html-expand t
2046 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2047 When nil, these tags will be exported as plain text and therefore
2048 not be interpreted by a browser.
2049
2050 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2051 :group 'org-export-html
2052 :type 'boolean)
2053
2054 (defcustom org-export-html-table-tag
2055 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2056 "The HTML tag used to start a table.
2057 This must be a <table> tag, but you may change the options like
2058 borders and spacing."
2059 :group 'org-export-html
2060 :type 'string)
2061
2062 (defcustom org-export-html-with-timestamp nil
2063 "If non-nil, write `org-export-html-html-helper-timestamp'
2064 into the exported HTML text. Otherwise, the buffer will just be saved
2065 to a file."
2066 :group 'org-export-html
2067 :type 'boolean)
2068
2069 (defcustom org-export-html-html-helper-timestamp
2070 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2071 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2072 :group 'org-export-html
2073 :type 'string)
2074
2075 (defcustom org-export-html-show-new-buffer nil
2076 "Non-nil means, popup buffer containing the exported html text.
2077 Otherwise, the buffer will just be saved to a file and stay hidden."
2078 :group 'org-export-html
2079 :type 'boolean)
2080
2081 (defgroup org-export-icalendar nil
2082 "Options specific for iCalendar export of Org-mode files."
2083 :tag "Org Export iCalendar"
2084 :group 'org-export)
2085
2086 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2087 "The file name for the iCalendar file covering all agenda files.
2088 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2089 The file name should be absolute."
2090 :group 'org-export-icalendar
2091 :type 'file)
2092
2093 (defcustom org-icalendar-include-todo nil
2094 "Non-nil means, export to iCalendar files should also cover TODO items."
2095 :group 'org-export-icalendar
2096 :type 'boolean)
2097
2098 (defcustom org-icalendar-combined-name "OrgMode"
2099 "Calendar name for the combined iCalendar representing all agenda files."
2100 :group 'org-export-icalendar
2101 :type 'string)
2102
2103 (defgroup org-font-lock nil
2104 "Font-lock settings for highlighting in Org-mode."
2105 :tag "Org Font Lock"
2106 :group 'org)
2107
2108 (defcustom org-level-color-stars-only nil
2109 "Non-nil means fontify only the stars in each headline.
2110 When nil, the entire headline is fontified.
2111 Changing it requires restart of `font-lock-mode' to become effective
2112 also in regions already fontified."
2113 :group 'org-font-lock
2114 :type 'boolean)
2115
2116 (defcustom org-hide-leading-stars nil
2117 "Non-nil means, hide the first N-1 stars in a headline.
2118 This works by using the face `org-hide' for these stars. This
2119 face is white for a light background, and black for a dark
2120 background. You may have to customize the face `org-hide' to
2121 make this work.
2122 Changing it requires restart of `font-lock-mode' to become effective
2123 also in regions already fontified.
2124 You may also set this on a per-file basis by adding one of the following
2125 lines to the buffer:
2126
2127 #+STARTUP: hidestars
2128 #+STARTUP: showstars"
2129 :group 'org-font-lock
2130 :type 'boolean)
2131
2132 (defcustom org-fontify-done-headline nil
2133 "Non-nil means, change the face of a headline if it is marked DONE.
2134 Normally, only the TODO/DONE keyword indicates the state of a headline.
2135 When this is non-nil, the headline after the keyword is set to the
2136 `org-headline-done' as an additional indication."
2137 :group 'org-font-lock
2138 :type 'boolean)
2139
2140 (defcustom org-fontify-emphasized-text t
2141 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2142 Changing this variable requires a restart of Emacs to take effect."
2143 :group 'org-font-lock
2144 :type 'boolean)
2145
2146 (defvar org-emph-re nil
2147 "Regular expression for matching emphasis.")
2148 (defvar org-emphasis-regexp-components) ; defined just below
2149 (defvar org-emphasis-alist) ; defined just below
2150 (defun org-set-emph-re (var val)
2151 "Set variable and compute the emphasis regular expression."
2152 (set var val)
2153 (when (and (boundp 'org-emphasis-alist)
2154 (boundp 'org-emphasis-regexp-components)
2155 org-emphasis-alist org-emphasis-regexp-components)
2156 (let* ((e org-emphasis-regexp-components)
2157 (pre (car e))
2158 (post (nth 1 e))
2159 (border (nth 2 e))
2160 (body (nth 3 e))
2161 (nl (nth 4 e))
2162 (stacked (nth 5 e))
2163 (body1 (concat body "*?"))
2164 (markers (mapconcat 'car org-emphasis-alist "")))
2165 ;; make sure special characters appear at the right position in the class
2166 (if (string-match "\\^" markers)
2167 (setq markers (concat (replace-match "" t t markers) "^")))
2168 (if (string-match "-" markers)
2169 (setq markers (concat (replace-match "" t t markers) "-")))
2170 (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2171 ;; Make the regexp
2172 (setq org-emph-re
2173 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2174 "\\("
2175 "\\([" markers "]\\)"
2176 "\\("
2177 "[^" border markers "]"
2178 body1
2179 "[^" border markers "]"
2180 "\\)"
2181 "\\3\\)"
2182 "\\([" post (if stacked markers) "]\\|$\\)")))))
2183
2184 (defcustom org-emphasis-regexp-components
2185 '(" \t(" " \t.,?;:'\")" " \t\r\n,." "." 1 nil)
2186 "Components used to build the reqular expression for emphasis.
2187 This is a list with 6 entries. Terminology: In an emphasis string
2188 like \" *strong word* \", we call the initial space PREMATCH, the final
2189 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2190 and \"trong wor\" is the body. The different components in this variable
2191 specify what is allowed/forbidden in each part:
2192
2193 pre Chars allowed as prematch. Beginning of line will be allowed too.
2194 post Chars allowed as postmatch. End of line will be allowed too.
2195 border The chars *forbidden* as border characters. In addition to the
2196 characters given here, all marker characters are forbidden too.
2197 body-regexp A regexp like \".\" to match a body character. Don't use
2198 non-shy groups here, and don't allow newline here.
2199 newline The maximum number of newlines allowed in an emphasis exp.
2200 stacked Non-nil means, allow stacked styles. This works only in HTML
2201 export. When this is set, all marker characters (as given in
2202 `org-emphasis-alist') will be allowed as pre/post, aiding
2203 inside-out matching.
2204 Use customize to modify this, or restart emacs after changing it."
2205 :group 'org-fixme
2206 :set 'org-set-emph-re
2207 :type '(list
2208 (sexp :tag "Allowed chars in pre ")
2209 (sexp :tag "Allowed chars in post ")
2210 (sexp :tag "Forbidden chars in border ")
2211 (sexp :tag "Regexp for body ")
2212 (integer :tag "number of newlines allowed")
2213 (boolean :tag "Stacking allowed ")))
2214
2215 (defcustom org-emphasis-alist
2216 '(("*" bold "<b>" "</b>")
2217 ("/" italic "<i>" "</i>")
2218 ("_" underline "<u>" "</u>")
2219 ("=" shadow "<code>" "</code>"))
2220 "Special syntax for emphasised text.
2221 Text starting and ending with a special character will be emphasized, for
2222 example *bold*, _underlined_ and /italic/. This variable sets the marker
2223 characters, the face to bbe used by font-lock for highlighting in Org-mode
2224 emacs buffers, and the HTML tags to be used for this.
2225 Use customize to modify this, or restart emacs after changing it."
2226 :group 'org-fixme
2227 :set 'org-set-emph-re
2228 :type '(repeat
2229 (list
2230 (string :tag "Marker character")
2231 (face :tag "Font-lock-face")
2232 (string :tag "HTML start tag")
2233 (string :tag "HTML end tag"))))
2234
2235 (defgroup org-faces nil
2236 "Faces in Org-mode."
2237 :tag "Org Faces"
2238 :group 'org-font-lock)
2239
2240 (defun org-compatible-face (specs)
2241 "Make a compatible face specification.
2242 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2243 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2244 to the top of the list. The `min-colors' attribute will be removed from
2245 any other entries, and any resulting duplicates will be removed entirely."
2246 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2247 (let (r e a)
2248 (while (setq e (pop specs))
2249 (cond
2250 ((memq (car e) '(t default)) (push e r))
2251 ((setq a (member '(min-colors 8) (car e)))
2252 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2253 (cdr e)))))
2254 ((setq a (assq 'min-colors (car e)))
2255 (setq e (cons (delq a (car e)) (cdr e)))
2256 (or (assoc (car e) r) (push e r)))
2257 (t (or (assoc (car e) r) (push e r)))))
2258 (nreverse r))
2259 specs))
2260
2261 (defface org-hide
2262 '((((background light)) (:foreground "white"))
2263 (((background dark)) (:foreground "black")))
2264 "Face used to hide leading stars in headlines.
2265 The forground color of this face should be equal to the background
2266 color of the frame."
2267 :group 'org-faces)
2268
2269 (defface org-level-1 ;; font-lock-function-name-face
2270 (org-compatible-face
2271 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2272 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2273 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2274 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2275 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2276 (t (:bold t))))
2277 "Face used for level 1 headlines."
2278 :group 'org-faces)
2279
2280 (defface org-level-2 ;; font-lock-variable-name-face
2281 (org-compatible-face
2282 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2283 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2284 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2285 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2286 (t (:bold t))))
2287 "Face used for level 2 headlines."
2288 :group 'org-faces)
2289
2290 (defface org-level-3 ;; font-lock-keyword-face
2291 (org-compatible-face
2292 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2293 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2294 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2295 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2296 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2297 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2298 (t (:bold t))))
2299 "Face used for level 3 headlines."
2300 :group 'org-faces)
2301
2302 (defface org-level-4 ;; font-lock-comment-face
2303 (org-compatible-face
2304 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2305 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2306 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2307 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2308 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2309 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2310 (t (:bold t))))
2311 "Face used for level 4 headlines."
2312 :group 'org-faces)
2313
2314 (defface org-level-5 ;; font-lock-type-face
2315 (org-compatible-face
2316 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2317 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2318 (((class color) (min-colors 8)) (:foreground "green"))))
2319 "Face used for level 5 headlines."
2320 :group 'org-faces)
2321
2322 (defface org-level-6 ;; font-lock-constant-face
2323 (org-compatible-face
2324 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2325 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2326 (((class color) (min-colors 8)) (:foreground "magenta"))))
2327 "Face used for level 6 headlines."
2328 :group 'org-faces)
2329
2330 (defface org-level-7 ;; font-lock-builtin-face
2331 (org-compatible-face
2332 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2333 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2334 (((class color) (min-colors 8)) (:foreground "blue"))))
2335 "Face used for level 7 headlines."
2336 :group 'org-faces)
2337
2338 (defface org-level-8 ;; font-lock-string-face
2339 (org-compatible-face
2340 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2341 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2342 (((class color) (min-colors 8)) (:foreground "green"))))
2343 "Face used for level 8 headlines."
2344 :group 'org-faces)
2345
2346 (defface org-special-keyword ;; font-lock-string-face
2347 (org-compatible-face
2348 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2349 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2350 (t (:italic t))))
2351 "Face used for special keywords."
2352 :group 'org-faces)
2353
2354 (defface org-warning ;; font-lock-warning-face
2355 (org-compatible-face
2356 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2357 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2358 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2359 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2360 (t (:bold t))))
2361 "Face for deadlines and TODO keywords."
2362 :group 'org-faces)
2363
2364 (defface org-headline-done ;; font-lock-string-face
2365 (org-compatible-face
2366 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2367 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2368 (((class color) (min-colors 8) (background light)) (:bold nil))))
2369 "Face used to indicate that a headline is DONE.
2370 This face is only used if `org-fontify-done-headline' is set."
2371 :group 'org-faces)
2372
2373 (defface org-link
2374 '((((class color) (background light)) (:foreground "Purple" :underline t))
2375 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2376 (t (:underline t)))
2377 "Face for links."
2378 :group 'org-faces)
2379
2380 (defface org-date
2381 '((((class color) (background light)) (:foreground "Purple" :underline t))
2382 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2383 (t (:underline t)))
2384 "Face for links."
2385 :group 'org-faces)
2386
2387 (defface org-tag
2388 '((t (:bold t)))
2389 "Face for tags."
2390 :group 'org-faces)
2391
2392 (defface org-todo ;; font-lock-warning-face
2393 (org-compatible-face
2394 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2395 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2396 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2397 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2398 (t (:inverse-video t :bold t))))
2399 "Face for TODO keywords."
2400 :group 'org-faces)
2401
2402 (defface org-done ;; font-lock-type-face
2403 (org-compatible-face
2404 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2405 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2406 (((class color) (min-colors 8)) (:foreground "green"))
2407 (t (:bold t))))
2408 "Face used for DONE."
2409 :group 'org-faces)
2410
2411 (defface org-table ;; font-lock-function-name-face
2412 (org-compatible-face
2413 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2414 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2415 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2416 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2417 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2418 (((class color) (min-colors 8) (background dark)))))
2419 "Face used for tables."
2420 :group 'org-faces)
2421
2422 (defface org-formula
2423 (org-compatible-face
2424 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2425 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2426 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2427 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2428 (t (:bold t :italic t))))
2429 "Face for formulas."
2430 :group 'org-faces)
2431
2432 (defface org-scheduled-today
2433 (org-compatible-face
2434 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2435 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2436 (((class color) (min-colors 8)) (:foreground "green"))
2437 (t (:bold t :italic t))))
2438 "Face for items scheduled for a certain day."
2439 :group 'org-faces)
2440
2441 (defface org-scheduled-previously
2442 (org-compatible-face
2443 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2444 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2445 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2446 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2447 (t (:bold t))))
2448 "Face for items scheduled previously, and not yet done."
2449 :group 'org-faces)
2450
2451 (defface org-upcoming-deadline
2452 (org-compatible-face
2453 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2454 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2455 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2456 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2457 (t (:bold t))))
2458 "Face for items scheduled previously, and not yet done."
2459 :group 'org-faces)
2460
2461 (defface org-time-grid ;; font-lock-variable-name-face
2462 (org-compatible-face
2463 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2464 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2465 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2466 "Face used for time grids."
2467 :group 'org-faces)
2468
2469 (defconst org-level-faces
2470 '(org-level-1 org-level-2 org-level-3 org-level-4
2471 org-level-5 org-level-6 org-level-7 org-level-8
2472 ))
2473 (defconst org-n-levels (length org-level-faces))
2474
2475
2476 ;; Variables for pre-computed regular expressions, all buffer local
2477 (defvar org-done-string nil
2478 "The last string in `org-todo-keywords', indicating an item is DONE.")
2479 (make-variable-buffer-local 'org-done-string)
2480 (defvar org-todo-regexp nil
2481 "Matches any of the TODO state keywords.")
2482 (make-variable-buffer-local 'org-todo-regexp)
2483 (defvar org-not-done-regexp nil
2484 "Matches any of the TODO state keywords except the last one.")
2485 (make-variable-buffer-local 'org-not-done-regexp)
2486 (defvar org-todo-line-regexp nil
2487 "Matches a headline and puts TODO state into group 2 if present.")
2488 (make-variable-buffer-local 'org-todo-line-regexp)
2489 (defvar org-todo-line-tags-regexp nil
2490 "Matches a headline and puts TODO state into group 2 if present.
2491 Also put tags into group 4 if tags are present.")
2492 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2493 (defvar org-nl-done-regexp nil
2494 "Matches newline followed by a headline with the DONE keyword.")
2495 (make-variable-buffer-local 'org-nl-done-regexp)
2496 (defvar org-looking-at-done-regexp nil
2497 "Matches the DONE keyword a point.")
2498 (make-variable-buffer-local 'org-looking-at-done-regexp)
2499 (defvar org-todo-kwd-priority-p nil
2500 "Do TODO items have priorities?")
2501 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2502 (defvar org-todo-kwd-max-priority nil
2503 "Maximum priority of TODO items.")
2504 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2505 (defvar org-ds-keyword-length 12
2506 "Maximum length of the Deadline and SCHEDULED keywords.")
2507 (make-variable-buffer-local 'org-ds-keyword-length)
2508 (defvar org-deadline-regexp nil
2509 "Matches the DEADLINE keyword.")
2510 (make-variable-buffer-local 'org-deadline-regexp)
2511 (defvar org-deadline-time-regexp nil
2512 "Matches the DEADLINE keyword together with a time stamp.")
2513 (make-variable-buffer-local 'org-deadline-time-regexp)
2514 (defvar org-deadline-line-regexp nil
2515 "Matches the DEADLINE keyword and the rest of the line.")
2516 (make-variable-buffer-local 'org-deadline-line-regexp)
2517 (defvar org-scheduled-regexp nil
2518 "Matches the SCHEDULED keyword.")
2519 (make-variable-buffer-local 'org-scheduled-regexp)
2520 (defvar org-scheduled-time-regexp nil
2521 "Matches the SCHEDULED keyword together with a time stamp.")
2522 (make-variable-buffer-local 'org-scheduled-time-regexp)
2523 (defvar org-closed-time-regexp nil
2524 "Matches the CLOSED keyword together with a time stamp.")
2525 (make-variable-buffer-local 'org-closed-time-regexp)
2526
2527 (defvar org-keyword-time-regexp nil
2528 "Matches any of the 3 keywords, together with the time stamp.")
2529 (make-variable-buffer-local 'org-keyword-time-regexp)
2530 (defvar org-maybe-keyword-time-regexp nil
2531 "Matches a timestamp, possibly preceeded by a keyword.")
2532 (make-variable-buffer-local 'org-keyword-time-regexp)
2533
2534 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2535 mouse-map t)
2536 "Properties to remove when a string without properties is wanted.")
2537
2538 (defsubst org-match-string-no-properties (num &optional string)
2539 (if (featurep 'xemacs)
2540 (let ((s (match-string num string)))
2541 (remove-text-properties 0 (length s) org-rm-props s)
2542 s)
2543 (match-string-no-properties num string)))
2544
2545 (defsubst org-no-properties (s)
2546 (remove-text-properties 0 (length s) org-rm-props s)
2547 s)
2548
2549 (defun org-set-regexps-and-options ()
2550 "Precompute regular expressions for current buffer."
2551 (when (eq major-mode 'org-mode)
2552 (let ((re (org-make-options-regexp
2553 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2554 "STARTUP" "ARCHIVE" "TAGS")))
2555 (splitre "[ \t]+")
2556 kwds int key value cat arch tags)
2557 (save-excursion
2558 (save-restriction
2559 (widen)
2560 (goto-char (point-min))
2561 (while (re-search-forward re nil t)
2562 (setq key (match-string 1) value (org-match-string-no-properties 2))
2563 (cond
2564 ((equal key "CATEGORY")
2565 (if (string-match "[ \t]+$" value)
2566 (setq value (replace-match "" t t value)))
2567 (setq cat (intern value)))
2568 ((equal key "SEQ_TODO")
2569 (setq int 'sequence
2570 kwds (append kwds (org-split-string value splitre))))
2571 ((equal key "PRI_TODO")
2572 (setq int 'priority
2573 kwds (append kwds (org-split-string value splitre))))
2574 ((equal key "TYP_TODO")
2575 (setq int 'type
2576 kwds (append kwds (org-split-string value splitre))))
2577 ((equal key "TAGS")
2578 (setq tags (append tags (org-split-string value splitre))))
2579 ((equal key "STARTUP")
2580 (let ((opts (org-split-string value splitre))
2581 (set '(("fold" org-startup-folded t)
2582 ("overview" org-startup-folded t)
2583 ("nofold" org-startup-folded nil)
2584 ("showall" org-startup-folded nil)
2585 ("content" org-startup-folded content)
2586 ("hidestars" org-hide-leading-stars t)
2587 ("showstars" org-hide-leading-stars nil)
2588 ("odd" org-odd-levels-only t)
2589 ("oddeven" org-odd-levels-only nil)
2590 ("align" org-startup-align-all-tables t)
2591 ("noalign" org-startup-align-all-tables nil)
2592 ("logging" org-log-done t)
2593 ("nologging" org-log-done nil)
2594 ("dlcheck" org-startup-with-deadline-check t)
2595 ("nodlcheck" org-startup-with-deadline-check nil)))
2596 l var val)
2597 (while (setq l (assoc (pop opts) set))
2598 (setq var (nth 1 l) val (nth 2 l))
2599 (set (make-local-variable var) val))))
2600 ((equal key "ARCHIVE")
2601 (string-match " *$" value)
2602 (setq arch (replace-match "" t t value))
2603 (remove-text-properties 0 (length arch)
2604 '(face t fontified t) arch)))
2605 )))
2606 (and cat (set (make-local-variable 'org-category) cat))
2607 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2608 (and arch (set (make-local-variable 'org-archive-location) arch))
2609 (and int (set (make-local-variable 'org-todo-interpretation) int))
2610 (when tags
2611 (let (e tg c tgs)
2612 (while (setq e (pop tags))
2613 (cond
2614 ((equal e "{") (push '(:startgroup) tgs))
2615 ((equal e "}") (push '(:endgroup) tgs))
2616 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2617 (push (cons (match-string 1 e)
2618 (string-to-char (match-string 2 e)))
2619 tgs))
2620 (t (push (list e) tgs))))
2621 (set (make-local-variable 'org-tag-alist) nil)
2622 (while (setq e (pop tgs))
2623 (or (and (stringp (car e))
2624 (assoc (car e) org-tag-alist))
2625 (push e org-tag-alist))))))
2626
2627 ;; Compute the regular expressions and other local variables
2628 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2629 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2630 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2631 (length org-scheduled-string)))
2632 org-done-string
2633 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2634 org-todo-regexp
2635 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2636 "\\|") "\\)\\>")
2637 org-not-done-regexp
2638 (concat "\\<\\("
2639 (mapconcat 'regexp-quote
2640 (nreverse (cdr (reverse org-todo-keywords)))
2641 "\\|")
2642 "\\)\\>")
2643 org-todo-line-regexp
2644 (concat "^\\(\\*+\\)[ \t]*\\("
2645 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2646 "\\)? *\\(.*\\)")
2647 org-nl-done-regexp
2648 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2649 org-todo-line-tags-regexp
2650 (concat "^\\(\\*+\\)[ \t]*\\("
2651 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2652 "\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
2653 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2654 org-deadline-regexp (concat "\\<" org-deadline-string)
2655 org-deadline-time-regexp
2656 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2657 org-deadline-line-regexp
2658 (concat "\\<\\(" org-deadline-string "\\).*")
2659 org-scheduled-regexp
2660 (concat "\\<" org-scheduled-string)
2661 org-scheduled-time-regexp
2662 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2663 org-closed-time-regexp
2664 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2665 org-keyword-time-regexp
2666 (concat "\\<\\(" org-scheduled-string
2667 "\\|" org-deadline-string
2668 "\\|" org-closed-string
2669 "\\|" org-clock-string "\\)"
2670 " *[[<]\\([^]>]+\\)[]>]")
2671 org-maybe-keyword-time-regexp
2672 (concat "\\(\\<\\(" org-scheduled-string
2673 "\\|" org-deadline-string
2674 "\\|" org-closed-string
2675 "\\|" org-clock-string "\\)\\)?"
2676 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
2677
2678 (org-set-font-lock-defaults)))
2679
2680 ;; Tell the compiler about dynamically scoped variables,
2681 ;; and variables from other packages
2682 (defvar calc-embedded-close-formula) ; defined by the calc package
2683 (defvar calc-embedded-open-formula) ; defined by the calc package
2684 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
2685 (defvar zmacs-regions) ; XEmacs regions
2686 (defvar original-date) ; dynamically scoped in calendar
2687 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2688 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2689 (defvar org-html-entities) ; defined later in this file
2690 (defvar org-goto-start-pos) ; dynamically scoped parameter
2691 (defvar org-time-was-given) ; dynamically scoped parameter
2692 (defvar org-ts-what) ; dynamically scoped parameter
2693 (defvar mark-active) ; Emacs only, not available in XEmacs.
2694 (defvar timecnt) ; dynamically scoped parameter
2695 (defvar levels-open) ; dynamically scoped parameter
2696 (defvar entry) ; dynamically scoped parameter
2697 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
2698 (defvar date) ; dynamically scoped parameter
2699 (defvar description) ; dynamically scoped parameter
2700 (defvar ans1) ; dynamically scoped parameter
2701 (defvar ans2) ; dynamically scoped parameter
2702 (defvar starting-day) ; local variable
2703 (defvar include-all-loc) ; local variable
2704 (defvar vm-message-pointer) ; from vm
2705 (defvar vm-folder-directory) ; from vm
2706 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2707 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2708 (defvar gnus-group-name) ; from gnus
2709 (defvar gnus-article-current) ; from gnus
2710 (defvar w3m-current-url) ; from w3m
2711 (defvar mh-progs) ; from MH-E
2712 (defvar mh-current-folder) ; from MH-E
2713 (defvar mh-show-folder-buffer) ; from MH-E
2714 (defvar mh-index-folder) ; from MH-E
2715 (defvar mh-searcher) ; from MH-E
2716 (defvar org-selected-point) ; dynamically scoped parameter
2717 (defvar calendar-mode-map) ; from calendar.el
2718 (defvar last-arg) ; local variable
2719 (defvar remember-save-after-remembering) ; from remember.el
2720 (defvar remember-data-file) ; from remember.el
2721 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2722 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2723 (defvar orgtbl-mode) ; defined later in this file
2724 (defvar Info-current-file) ; from info.el
2725 (defvar Info-current-node) ; from info.el
2726
2727 ;;; Define the mode
2728
2729 (defvar org-mode-map
2730 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2731 (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.")
2732 (copy-keymap outline-mode-map))
2733 "Keymap for Org-mode.")
2734
2735 (defvar org-struct-menu) ; defined later in this file
2736 (defvar org-org-menu) ; defined later in this file
2737 (defvar org-tbl-menu) ; defined later in this file
2738
2739 ;; We use a before-change function to check if a table might need
2740 ;; an update.
2741 (defvar org-table-may-need-update t
2742 "Indicates that a table might need an update.
2743 This variable is set by `org-before-change-function'.
2744 `org-table-align' sets it back to nil.")
2745 (defvar org-mode-hook nil)
2746 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2747 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2748
2749
2750 ;;;###autoload
2751 (define-derived-mode org-mode outline-mode "Org"
2752 "Outline-based notes management and organizer, alias
2753 \"Carsten's outline-mode for keeping track of everything.\"
2754
2755 Org-mode develops organizational tasks around a NOTES file which
2756 contains information about projects as plain text. Org-mode is
2757 implemented on top of outline-mode, which is ideal to keep the content
2758 of large files well structured. It supports ToDo items, deadlines and
2759 time stamps, which magically appear in the diary listing of the Emacs
2760 calendar. Tables are easily created with a built-in table editor.
2761 Plain text URL-like links connect to websites, emails (VM), Usenet
2762 messages (Gnus), BBDB entries, and any files related to the project.
2763 For printing and sharing of notes, an Org-mode file (or a part of it)
2764 can be exported as a structured ASCII or HTML file.
2765
2766 The following commands are available:
2767
2768 \\{org-mode-map}"
2769
2770 ;; Get rid of Outline menus, they are not needed
2771 ;; Need to do this here because define-derived-mode sets up
2772 ;; the keymap so late.
2773 (if (featurep 'xemacs)
2774 (if org-noutline-p
2775 (progn
2776 (easy-menu-remove outline-mode-menu-heading)
2777 (easy-menu-remove outline-mode-menu-show)
2778 (easy-menu-remove outline-mode-menu-hide))
2779 (delete-menu-item '("Headings"))
2780 (delete-menu-item '("Show"))
2781 (delete-menu-item '("Hide"))
2782 (set-menubar-dirty-flag))
2783 (define-key org-mode-map [menu-bar headings] 'undefined)
2784 (define-key org-mode-map [menu-bar hide] 'undefined)
2785 (define-key org-mode-map [menu-bar show] 'undefined))
2786
2787 (easy-menu-add org-org-menu)
2788 (easy-menu-add org-tbl-menu)
2789 (org-install-agenda-files-menu)
2790 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2791 (org-add-to-invisibility-spec '(org-cwidth))
2792 (when (featurep 'xemacs)
2793 (set (make-local-variable 'line-move-ignore-invisible) t))
2794 (setq outline-regexp "\\*+")
2795 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2796 (setq outline-level 'org-outline-level)
2797 (when (and org-ellipsis (stringp org-ellipsis))
2798 (unless org-display-table
2799 (setq org-display-table (make-display-table)))
2800 (set-display-table-slot org-display-table
2801 4 (string-to-vector org-ellipsis))
2802 (setq buffer-display-table org-display-table))
2803 (org-set-regexps-and-options)
2804 (modify-syntax-entry ?# "<")
2805 (if org-startup-truncated (setq truncate-lines t))
2806 (set (make-local-variable 'font-lock-unfontify-region-function)
2807 'org-unfontify-region)
2808 ;; Activate before-change-function
2809 (set (make-local-variable 'org-table-may-need-update) t)
2810 (org-add-hook 'before-change-functions 'org-before-change-function nil
2811 'local)
2812 ;; Check for running clock before killing a buffer
2813 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
2814 ;; Paragraphs and auto-filling
2815 (org-set-autofill-regexps)
2816 (org-update-radio-target-regexp)
2817 ;; Settings for Calc embedded mode
2818 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2819 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2820 (if (and org-insert-mode-line-in-empty-file
2821 (interactive-p)
2822 (= (point-min) (point-max)))
2823 (insert " -*- mode: org -*-\n\n"))
2824
2825 (unless org-inhibit-startup
2826 (if org-startup-align-all-tables
2827 (org-table-map-tables 'org-table-align))
2828 (if org-startup-with-deadline-check
2829 (call-interactively 'org-check-deadlines)
2830 (cond
2831 ((eq org-startup-folded t)
2832 (org-cycle '(4)))
2833 ((eq org-startup-folded 'content)
2834 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2835 (org-cycle '(4)) (org-cycle '(4))))))))
2836
2837 (defsubst org-call-with-arg (command arg)
2838 "Call COMMAND interactively, but pretend prefix are was ARG."
2839 (let ((current-prefix-arg arg)) (call-interactively command)))
2840
2841 (defsubst org-current-line (&optional pos)
2842 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2843
2844 (defun org-current-time ()
2845 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2846 (if (> org-time-stamp-rounding-minutes 0)
2847 (let ((r org-time-stamp-rounding-minutes)
2848 (time (decode-time)))
2849 (apply 'encode-time
2850 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2851 (nthcdr 2 time))))
2852 (current-time)))
2853
2854 (defun org-add-props (string plist &rest props)
2855 "Add text properties to entire string, from beginning to end.
2856 PLIST may be a list of properties, PROPS are individual properties and values
2857 that will be added to PLIST. Returns the string that was modified."
2858 (add-text-properties
2859 0 (length string) (if props (append plist props) plist) string)
2860 string)
2861 (put 'org-add-props 'lisp-indent-function 2)
2862
2863
2864 ;;; Font-Lock stuff
2865
2866 (defvar org-mouse-map (make-sparse-keymap))
2867 (define-key org-mouse-map
2868 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2869 (define-key org-mouse-map
2870 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2871 (when org-mouse-1-follows-link
2872 (define-key org-mouse-map [follow-link] 'mouse-face))
2873 (when org-tab-follows-link
2874 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2875 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2876 (when org-return-follows-link
2877 (define-key org-mouse-map [(return)] 'org-open-at-point)
2878 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2879
2880 (require 'font-lock)
2881
2882 (defconst org-non-link-chars "]\t\n\r<>")
2883 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
2884 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
2885 (defconst org-link-re-with-space
2886 (concat
2887 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2888 "\\([^" org-non-link-chars " ]"
2889 "[^" org-non-link-chars "]*"
2890 "[^" org-non-link-chars " ]\\)>?")
2891 "Matches a link with spaces, optional angular brackets around it.")
2892
2893 (defconst org-link-re-with-space2
2894 (concat
2895 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2896 "\\([^" org-non-link-chars " ]"
2897 "[^]\t\n\r]*"
2898 "[^" org-non-link-chars " ]\\)>?")
2899 "Matches a link with spaces, optional angular brackets around it.")
2900
2901 (defconst org-angle-link-re
2902 (concat
2903 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2904 "\\([^" org-non-link-chars " ]"
2905 "[^" org-non-link-chars "]*"
2906 "\\)>")
2907 "Matches link with angular brackets, spaces are allowed.")
2908 (defconst org-plain-link-re
2909 (concat
2910 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2911 "\\([^]\t\n\r<>,;() ]+\\)")
2912 "Matches plain link, without spaces.")
2913
2914 (defconst org-bracket-link-regexp
2915 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2916 "Matches a link in double brackets.")
2917
2918 (defconst org-bracket-link-analytic-regexp
2919 (concat
2920 "\\[\\["
2921 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
2922 "\\([^]]+\\)"
2923 "\\]"
2924 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
2925 "\\]"))
2926 ; 1: http:
2927 ; 2: http
2928 ; 3: path
2929 ; 4: [desc]
2930 ; 5: desc
2931
2932
2933 (defconst org-ts-lengths
2934 (cons (length (format-time-string (car org-time-stamp-formats)))
2935 (length (format-time-string (cdr org-time-stamp-formats))))
2936 "This holds the lengths of the two different time formats.")
2937 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2938 "Regular expression for fast time stamp matching.")
2939 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2940 "Regular expression for fast time stamp matching.")
2941 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2942 "Regular expression matching time strings for analysis.")
2943 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2944 "Regular expression matching time stamps, with groups.")
2945 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2946 "Regular expression matching a time stamp range.")
2947 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2948 org-ts-regexp "\\)?")
2949 "Regular expression matching a time stamp or time stamp range.")
2950
2951 (defvar org-§emph-face nil)
2952
2953 (defun org-do-emphasis-faces (limit)
2954 "Run through the buffer and add overlays to links."
2955 (if (re-search-forward org-emph-re limit t)
2956 (progn
2957 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
2958 'face
2959 (nth 1 (assoc (match-string 3)
2960 org-emphasis-alist)))
2961 (add-text-properties (match-beginning 2) (match-end 2)
2962 '(font-lock-multiline t))
2963 (backward-char 1)
2964 t)))
2965
2966 (defun org-activate-plain-links (limit)
2967 "Run through the buffer and add overlays to links."
2968 (if (re-search-forward org-plain-link-re limit t)
2969 (progn
2970 (add-text-properties (match-beginning 0) (match-end 0)
2971 (list 'mouse-face 'highlight
2972 'keymap org-mouse-map
2973 ))
2974 t)))
2975
2976 (defun org-activate-angle-links (limit)
2977 "Run through the buffer and add overlays to links."
2978 (if (re-search-forward org-angle-link-re limit t)
2979 (progn
2980 (add-text-properties (match-beginning 0) (match-end 0)
2981 (list 'mouse-face 'highlight
2982 'keymap org-mouse-map
2983 ))
2984 t)))
2985
2986 (defun org-activate-bracket-links (limit)
2987 "Run through the buffer and add overlays to bracketed links."
2988 (if (re-search-forward org-bracket-link-regexp limit t)
2989 (let* ((help (concat "LINK: "
2990 (org-match-string-no-properties 1)))
2991 ;; FIXME: above we should remove the escapes.
2992 ;; but that requires another match, protecting match data,
2993 ;; a lot of overhead for font-lock.
2994 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
2995 'keymap org-mouse-map 'mouse-face 'highlight
2996 'help-echo help))
2997 (vp (list 'rear-nonsticky t
2998 'keymap org-mouse-map 'mouse-face 'highlight
2999 'help-echo help)))
3000 ;; We need to remove the invisible property here. Table narrowing
3001 ;; may have made some of this invisible.
3002 (remove-text-properties (match-beginning 0) (match-end 0)
3003 '(invisible nil))
3004 (if (match-end 3)
3005 (progn
3006 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3007 (add-text-properties (match-beginning 3) (match-end 3) vp)
3008 (add-text-properties (match-end 3) (match-end 0) ip))
3009 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3010 (add-text-properties (match-beginning 1) (match-end 1) vp)
3011 (add-text-properties (match-end 1) (match-end 0) ip))
3012 t)))
3013
3014 (defun org-activate-dates (limit)
3015 "Run through the buffer and add overlays to dates."
3016 (if (re-search-forward org-tsr-regexp limit t)
3017 (progn
3018 (add-text-properties (match-beginning 0) (match-end 0)
3019 (list 'mouse-face 'highlight
3020 'keymap org-mouse-map))
3021 t)))
3022
3023 (defvar org-target-link-regexp nil
3024 "Regular expression matching radio targets in plain text.")
3025 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3026 "Regular expression matching a link target.")
3027 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3028 "Regular expression matching a link target.")
3029
3030 (defun org-activate-target-links (limit)
3031 "Run through the buffer and add overlays to target matches."
3032 (when org-target-link-regexp
3033 (let ((case-fold-search t))
3034 (if (re-search-forward org-target-link-regexp limit t)
3035 (progn
3036 (add-text-properties (match-beginning 0) (match-end 0)
3037 (list 'mouse-face 'highlight
3038 'keymap org-mouse-map
3039 'help-echo "Radio target link"
3040 'org-linked-text t))
3041 t)))))
3042
3043 (defun org-update-radio-target-regexp ()
3044 "Find all radio targets in this file and update the regular expression."
3045 (interactive)
3046 (when (memq 'radio org-activate-links)
3047 (setq org-target-link-regexp
3048 (org-make-target-link-regexp (org-all-targets 'radio)))
3049 (org-restart-font-lock)))
3050
3051 (defun org-hide-wide-columns (limit)
3052 (let (s e)
3053 (setq s (text-property-any (point) (or limit (point-max))
3054 'org-cwidth t))
3055 (when s
3056 (setq e (next-single-property-change s 'org-cwidth))
3057 (add-text-properties s e '(invisible org-cwidth intangible t))
3058 (goto-char e)
3059 t)))
3060
3061 (defun org-restart-font-lock ()
3062 "Restart font-lock-mode, to force refontification."
3063 (when (and (boundp 'font-lock-mode) font-lock-mode)
3064 (font-lock-mode -1)
3065 (font-lock-mode 1)))
3066
3067 (defun org-all-targets (&optional radio)
3068 "Return a list of all targets in this file.
3069 With optional argument RADIO, only find radio targets."
3070 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3071 rtn)
3072 (save-excursion
3073 (goto-char (point-min))
3074 (while (re-search-forward re nil t)
3075 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3076 rtn)))
3077
3078 (defun org-make-target-link-regexp (targets)
3079 "Make regular expression matching all strings in TARGETS.
3080 The regular expression finds the targets also if there is a line break
3081 between words."
3082 (and targets
3083 (concat
3084 "\\<\\("
3085 (mapconcat
3086 (lambda (x)
3087 (while (string-match " +" x)
3088 (setq x (replace-match "\\s-+" t t x)))
3089 x)
3090 targets
3091 "\\|")
3092 "\\)\\>")))
3093
3094 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3095 "Matches CamelCase words, possibly with a star before it.")
3096
3097 (defun org-activate-camels (limit)
3098 "Run through the buffer and add overlays to dates."
3099 (if (re-search-forward org-camel-regexp limit t)
3100 (progn
3101 (add-text-properties (match-beginning 0) (match-end 0)
3102 (list 'mouse-face 'highlight
3103 'keymap org-mouse-map))
3104 t)))
3105
3106 (defun org-activate-tags (limit)
3107 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3108 (progn
3109 (add-text-properties (match-beginning 1) (match-end 1)
3110 (list 'mouse-face 'highlight
3111 'keymap org-mouse-map))
3112 t)))
3113
3114 (defun org-font-lock-level ()
3115 (save-excursion
3116 (org-back-to-heading t)
3117 (- (match-end 0) (match-beginning 0))))
3118
3119 (defun org-outline-level ()
3120 (save-excursion
3121 (looking-at outline-regexp)
3122 (if (match-beginning 1)
3123 (+ (org-get-string-indentation (match-string 1)) 1000)
3124 (- (match-end 0) (match-beginning 0)))))
3125
3126 (defvar org-font-lock-keywords nil)
3127
3128 (defun org-set-font-lock-defaults ()
3129 (let* ((em org-fontify-emphasized-text)
3130 (lk org-activate-links)
3131 (org-font-lock-extra-keywords
3132 ;; Headlines
3133 (list
3134 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3135 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3136 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3137 (1 'org-table))
3138 ;; Links
3139 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3140 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3141 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3142 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3143 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3144 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3145 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3146 (if org-table-limit-column-width
3147 '(org-hide-wide-columns (0 nil append)))
3148 ;; TODO lines
3149 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3150 '(1 'org-todo t))
3151 ;; Priorities
3152 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3153 ;; Special keywords
3154 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3155 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3156 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3157 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3158 ;; Emphasis
3159 (if em '(org-do-emphasis-faces))
3160 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3161 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3162 2 'bold prepend)
3163 ;; COMMENT
3164 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3165 "\\|" org-quote-string "\\)\\>")
3166 '(1 'org-special-keyword t))
3167 '("^#.*" (0 'font-lock-comment-face t))
3168 ;; DONE
3169 (if org-fontify-done-headline
3170 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3171 '(1 'org-done t) '(2 'org-headline-done t))
3172 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3173 '(1 'org-done t)))
3174 ;; Table stuff
3175 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3176 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3177 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3178 (if org-format-transports-properties-p
3179 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3180 )))
3181 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3182 ;; Now set the full font-lock-keywords
3183 (set (make-local-variable 'org-font-lock-keywords)
3184 org-font-lock-extra-keywords)
3185 (set (make-local-variable 'font-lock-defaults)
3186 '(org-font-lock-keywords t nil nil backward-paragraph))
3187 (kill-local-variable 'font-lock-keywords) nil))
3188
3189 (defvar org-m nil)
3190 (defvar org-l nil)
3191 (defvar org-f nil)
3192 (defun org-get-level-face (n)
3193 "Get the right face for match N in font-lock matching of healdines."
3194 (setq org-l (- (match-end 2) (match-beginning 1)))
3195 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3196 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3197 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3198 (cond
3199 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3200 ((eq n 2) org-f)
3201 (t (if org-level-color-stars-only nil org-f))))
3202
3203 (defun org-unfontify-region (beg end &optional maybe_loudly)
3204 "Remove fontification and activation overlays from links."
3205 (font-lock-default-unfontify-region beg end)
3206 (let* ((buffer-undo-list t)
3207 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3208 (inhibit-modification-hooks t)
3209 deactivate-mark buffer-file-name buffer-file-truename)
3210 (remove-text-properties beg end
3211 '(mouse-face nil keymap nil org-linked-text nil
3212 invisible nil intangible nil))))
3213 ;;; Visibility cycling
3214
3215 (defvar org-cycle-global-status nil)
3216 (make-variable-buffer-local 'org-cycle-global-status)
3217 (defvar org-cycle-subtree-status nil)
3218 (make-variable-buffer-local 'org-cycle-subtree-status)
3219
3220 ;;;###autoload
3221 (defun org-cycle (&optional arg)
3222 "Visibility cycling for Org-mode.
3223
3224 - When this function is called with a prefix argument, rotate the entire
3225 buffer through 3 states (global cycling)
3226 1. OVERVIEW: Show only top-level headlines.
3227 2. CONTENTS: Show all headlines of all levels, but no body text.
3228 3. SHOW ALL: Show everything.
3229
3230 - When point is at the beginning of a headline, rotate the subtree started
3231 by this line through 3 different states (local cycling)
3232 1. FOLDED: Only the main headline is shown.
3233 2. CHILDREN: The main headline and the direct children are shown.
3234 From this state, you can move to one of the children
3235 and zoom in further.
3236 3. SUBTREE: Show the entire subtree, including body text.
3237
3238 - When there is a numeric prefix, go up to a heading with level ARG, do
3239 a `show-subtree' and return to the previous cursor position. If ARG
3240 is negative, go up that many levels.
3241
3242 - When point is not at the beginning of a headline, execute
3243 `indent-relative', like TAB normally does. See the option
3244 `org-cycle-emulate-tab' for details.
3245
3246 - Special case: if point is the the beginning of the buffer and there is
3247 no headline in line 1, this function will act as if called with prefix arg."
3248 (interactive "P")
3249
3250 (let* ((outline-regexp
3251 (if org-cycle-include-plain-lists
3252 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
3253 outline-regexp))
3254 (bob-special (and org-cycle-global-at-bob (bobp)
3255 (not (looking-at outline-regexp))))
3256 (org-cycle-hook (if bob-special nil org-cycle-hook))
3257 (pos (point)))
3258
3259 (if (or bob-special (equal arg '(4)))
3260 ;; special case: use global cycling
3261 (setq arg t))
3262
3263 (cond
3264
3265 ((org-at-table-p 'any)
3266 ;; Enter the table or move to the next field in the table
3267 (or (org-table-recognize-table.el)
3268 (progn
3269 (if arg (org-table-edit-field t)
3270 (org-table-justify-field-maybe)
3271 (call-interactively 'org-table-next-field)))))
3272
3273 ((eq arg t) ;; Global cycling
3274
3275 (cond
3276 ((and (eq last-command this-command)
3277 (eq org-cycle-global-status 'overview))
3278 ;; We just created the overview - now do table of contents
3279 ;; This can be slow in very large buffers, so indicate action
3280 (message "CONTENTS...")
3281 (org-content)
3282 (message "CONTENTS...done")
3283 (setq org-cycle-global-status 'contents)
3284 (run-hook-with-args 'org-cycle-hook 'contents))
3285
3286 ((and (eq last-command this-command)
3287 (eq org-cycle-global-status 'contents))
3288 ;; We just showed the table of contents - now show everything
3289 (show-all)
3290 (message "SHOW ALL")
3291 (setq org-cycle-global-status 'all)
3292 (run-hook-with-args 'org-cycle-hook 'all))
3293
3294 (t
3295 ;; Default action: go to overview
3296 (org-overview)
3297 (message "OVERVIEW")
3298 (setq org-cycle-global-status 'overview)
3299 (run-hook-with-args 'org-cycle-hook 'overview))))
3300
3301 ((integerp arg)
3302 ;; Show-subtree, ARG levels up from here.
3303 (save-excursion
3304 (org-back-to-heading)
3305 (outline-up-heading (if (< arg 0) (- arg)
3306 (- (funcall outline-level) arg)))
3307 (org-show-subtree)))
3308
3309 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3310 ;; At a heading: rotate between three different views
3311 (org-back-to-heading)
3312 (let ((goal-column 0) eoh eol eos)
3313 ;; First, some boundaries
3314 (save-excursion
3315 (org-back-to-heading)
3316 (save-excursion
3317 (beginning-of-line 2)
3318 (while (and (not (eobp)) ;; this is like `next-line'
3319 (get-char-property (1- (point)) 'invisible))
3320 (beginning-of-line 2)) (setq eol (point)))
3321 (outline-end-of-heading) (setq eoh (point))
3322 (org-end-of-subtree t) (setq eos (point))
3323 (outline-next-heading))
3324 ;; Find out what to do next and set `this-command'
3325 (cond
3326 ((and (= eos eoh)
3327 ;; Nothing is hidden behind this heading
3328 (message "EMPTY ENTRY")
3329 (setq org-cycle-subtree-status nil)))
3330 ((>= eol eos)
3331 ;; Entire subtree is hidden in one line: open it
3332 (org-show-entry)
3333 (show-children)
3334 (message "CHILDREN")
3335 (setq org-cycle-subtree-status 'children)
3336 (run-hook-with-args 'org-cycle-hook 'children))
3337 ((and (eq last-command this-command)
3338 (eq org-cycle-subtree-status 'children))
3339 ;; We just showed the children, now show everything.
3340 (org-show-subtree)
3341 (message "SUBTREE")
3342 (setq org-cycle-subtree-status 'subtree)
3343 (run-hook-with-args 'org-cycle-hook 'subtree))
3344 (t
3345 ;; Default action: hide the subtree.
3346 (hide-subtree)
3347 (message "FOLDED")
3348 (setq org-cycle-subtree-status 'folded)
3349 (run-hook-with-args 'org-cycle-hook 'folded)))))
3350
3351 ;; TAB emulation
3352 (buffer-read-only (org-back-to-heading))
3353 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3354 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3355 (or (and (eq org-cycle-emulate-tab 'white)
3356 (= (match-end 0) (point-at-eol)))
3357 (and (eq org-cycle-emulate-tab 'whitestart)
3358 (>= (match-end 0) pos))))
3359 t
3360 (eq org-cycle-emulate-tab t))
3361 (if (and (looking-at "[ \n\r\t]")
3362 (string-match "^[ \t]*$" (buffer-substring
3363 (point-at-bol) (point))))
3364 (progn
3365 (beginning-of-line 1)
3366 (and (looking-at "[ \t]+") (replace-match ""))))
3367 (indent-relative))
3368
3369 (t (save-excursion
3370 (org-back-to-heading)
3371 (org-cycle))))))
3372
3373 ;;;###autoload
3374 (defun org-global-cycle (&optional arg)
3375 "Cycle the global visibility. For details see `org-cycle'."
3376 (interactive "P")
3377 (if (integerp arg)
3378 (progn
3379 (show-all)
3380 (hide-sublevels arg)
3381 (setq org-cycle-global-status 'contents))
3382 (org-cycle '(4))))
3383
3384 (defun org-overview ()
3385 "Switch to overview mode, shoing only top-level headlines.
3386 Really, this shows all headlines with level equal or greater than the level
3387 of the first headline in the buffer. This is important, because if the
3388 first headline is not level one, then (hide-sublevels 1) gives confusing
3389 results."
3390 (interactive)
3391 (hide-sublevels (save-excursion
3392 (goto-char (point-min))
3393 (if (re-search-forward (concat "^" outline-regexp) nil t)
3394 (progn
3395 (goto-char (match-beginning 0))
3396 (funcall outline-level))
3397 1))))
3398
3399 ;; FIXME: allow an argument to give a limiting level for this.
3400 (defun org-content ()
3401 "Show all headlines in the buffer, like a table of contents"
3402 (interactive)
3403 (save-excursion
3404 ;; Visit all headings and show their offspring
3405 (goto-char (point-max))
3406 (catch 'exit
3407 (while (and (progn (condition-case nil
3408 (outline-previous-visible-heading 1)
3409 (error (goto-char (point-min))))
3410 t)
3411 (looking-at outline-regexp))
3412 (show-branches)
3413 (if (bobp) (throw 'exit nil))))))
3414
3415
3416 (defun org-optimize-window-after-visibility-change (state)
3417 "Adjust the window after a change in outline visibility.
3418 This function is the default value of the hook `org-cycle-hook'."
3419 (when (get-buffer-window (current-buffer))
3420 (cond
3421 ((eq state 'overview) (org-first-headline-recenter 1))
3422 ((eq state 'content) nil)
3423 ((eq state 'all) nil)
3424 ((eq state 'folded) nil)
3425 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3426 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3427
3428 (defun org-subtree-end-visible-p ()
3429 "Is the end of the current subtree visible?"
3430 (pos-visible-in-window-p
3431 (save-excursion (org-end-of-subtree t) (point))))
3432
3433 (defun org-first-headline-recenter (&optional N)
3434 "Move cursor to the first headline and recenter the headline.
3435 Optional argument N means, put the headline into the Nth line of the window."
3436 (goto-char (point-min))
3437 (when (re-search-forward (concat "^" outline-regexp) nil t)
3438 (beginning-of-line)
3439 (recenter (prefix-numeric-value N))))
3440
3441 (defvar org-goto-window-configuration nil)
3442 (defvar org-goto-marker nil)
3443 (defvar org-goto-map (make-sparse-keymap))
3444 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3445 (while (setq cmd (pop cmds))
3446 (substitute-key-definition cmd cmd org-goto-map global-map)))
3447 (define-key org-goto-map "\C-m" 'org-goto-ret)
3448 (define-key org-goto-map [(left)] 'org-goto-left)
3449 (define-key org-goto-map [(right)] 'org-goto-right)
3450 (define-key org-goto-map [(?q)] 'org-goto-quit)
3451 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3452 (define-key org-goto-map "\C-i" 'org-cycle)
3453 (define-key org-goto-map [(tab)] 'org-cycle)
3454 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3455 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3456 (define-key org-goto-map "n" 'outline-next-visible-heading)
3457 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3458 (define-key org-goto-map "f" 'outline-forward-same-level)
3459 (define-key org-goto-map "b" 'outline-backward-same-level)
3460 (define-key org-goto-map "u" 'outline-up-heading)
3461 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3462 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3463 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3464 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3465 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3466 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3467 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3468
3469 (defconst org-goto-help
3470 "Select a location to jump to, press RET
3471 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3472
3473 (defun org-goto ()
3474 "Go to a different location of the document, keeping current visibility.
3475
3476 When you want to go to a different location in a document, the fastest way
3477 is often to fold the entire buffer and then dive into the tree. This
3478 method has the disadvantage, that the previous location will be folded,
3479 which may not be what you want.
3480
3481 This command works around this by showing a copy of the current buffer in
3482 overview mode. You can dive into the tree in that copy, to find the
3483 location you want to reach. When pressing RET, the command returns to the
3484 original buffer in which the visibility is still unchanged. It then jumps
3485 to the new location, making it and the headline hierarchy above it visible."
3486 (interactive)
3487 (let* ((org-goto-start-pos (point))
3488 (selected-point
3489 (org-get-location (current-buffer) org-goto-help)))
3490 (if selected-point
3491 (progn
3492 (org-mark-ring-push org-goto-start-pos)
3493 (goto-char selected-point)
3494 (if (or (org-invisible-p) (org-invisible-p2))
3495 (org-show-hierarchy-above)))
3496 (error "Quit"))))
3497
3498 (defun org-get-location (buf help)
3499 "Let the user select a location in the Org-mode buffer BUF.
3500 This function uses a recursive edit. It returns the selected position
3501 or nil."
3502 (let (org-selected-point)
3503 (save-excursion
3504 (save-window-excursion
3505 (delete-other-windows)
3506 (switch-to-buffer (get-buffer-create "*org-goto*"))
3507 (with-output-to-temp-buffer "*Help*"
3508 (princ help))
3509 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3510 (setq buffer-read-only nil)
3511 (erase-buffer)
3512 (insert-buffer-substring buf)
3513 (let ((org-startup-truncated t)
3514 (org-startup-folded t)
3515 (org-startup-align-all-tables nil)
3516 (org-startup-with-deadline-check nil))
3517 (org-mode))
3518 (setq buffer-read-only t)
3519 (if (boundp 'org-goto-start-pos)
3520 (goto-char org-goto-start-pos)
3521 (goto-char (point-min)))
3522 (org-beginning-of-line)
3523 (message "Select location and press RET")
3524 ;; now we make sure that during selection, ony very few keys work
3525 ;; and that it is impossible to switch to another window.
3526 (let ((gm (current-global-map))
3527 (overriding-local-map org-goto-map))
3528 (unwind-protect
3529 (progn
3530 (use-global-map org-goto-map)
3531 (recursive-edit))
3532 (use-global-map gm)))))
3533 (kill-buffer "*org-goto*")
3534 org-selected-point))
3535
3536 (defun org-goto-ret (&optional arg)
3537 "Finish `org-goto' by going to the new location."
3538 (interactive "P")
3539 (setq org-selected-point (point)
3540 current-prefix-arg arg)
3541 (throw 'exit nil))
3542
3543 (defun org-goto-left ()
3544 "Finish `org-goto' by going to the new location."
3545 (interactive)
3546 (if (org-on-heading-p)
3547 (progn
3548 (beginning-of-line 1)
3549 (setq org-selected-point (point)
3550 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3551 (throw 'exit nil))
3552 (error "Not on a heading")))
3553
3554 (defun org-goto-right ()
3555 "Finish `org-goto' by going to the new location."
3556 (interactive)
3557 (if (org-on-heading-p)
3558 (progn
3559 (outline-end-of-subtree)
3560 (or (eobp) (forward-char 1))
3561 (setq org-selected-point (point)
3562 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3563 (throw 'exit nil))
3564 (error "Not on a heading")))
3565
3566 (defun org-goto-quit ()
3567 "Finish `org-goto' without cursor motion."
3568 (interactive)
3569 (setq org-selected-point nil)
3570 (throw 'exit nil))
3571
3572 ;;; Promotion, Demotion, Inserting new headlines
3573
3574 (defvar org-ignore-region nil
3575 "To temporarily disable the active region.")
3576
3577 (defun org-insert-heading (&optional force-heading)
3578 "Insert a new heading or item with same depth at point.
3579 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3580 If point is at the beginning of a headline, insert a sibling before the
3581 current headline. If point is in the middle of a headline, split the headline
3582 at that position and make the rest of the headline part of the sibling below
3583 the current headline."
3584 (interactive "P")
3585 (if (= (buffer-size) 0)
3586 (insert "\n* ")
3587 (when (or force-heading (not (org-insert-item)))
3588 (let* ((head (save-excursion
3589 (condition-case nil
3590 (progn
3591 (org-back-to-heading)
3592 (match-string 0))
3593 (error "*"))))
3594 pos)
3595 (cond
3596 ((and (org-on-heading-p) (bolp)
3597 (save-excursion (backward-char 1) (not (org-invisible-p))))
3598 (open-line 1))
3599 ((and (bolp) (save-excursion
3600 (backward-char 1) (not (org-invisible-p))))
3601 nil)
3602 (t (newline)))
3603 (insert head) (just-one-space)
3604 (setq pos (point))
3605 (end-of-line 1)
3606 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3607 (run-hooks 'org-insert-heading-hook)))))
3608
3609 (defun org-insert-item (&optional checkbox)
3610 "Insert a new item at the current level.
3611 Return t when things worked, nil when we are not in an item."
3612 (when (save-excursion
3613 (condition-case nil
3614 (progn
3615 (org-beginning-of-item)
3616 (org-at-item-p)
3617 t)
3618 (error nil)))
3619 (let* ((bul (match-string 0))
3620 (end (match-end 0))
3621 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3622 (match-end 0)))
3623 (eowcol (save-excursion (goto-char eow) (current-column)))
3624 pos)
3625 (cond
3626 ((and (org-at-item-p) (<= (point) eow))
3627 ;; before the bullet
3628 (beginning-of-line 1)
3629 (open-line 1))
3630 ((<= (point) eow)
3631 (beginning-of-line 1))
3632 (t (newline)))
3633 (insert bul (if checkbox "[ ]" ""))
3634 (just-one-space)
3635 (setq pos (point))
3636 (end-of-line 1)
3637 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3638 (org-maybe-renumber-ordered-list)
3639 t))
3640
3641 (defun org-insert-todo-heading (arg)
3642 "Insert a new heading with the same level and TODO state as current heading.
3643 If the heading has no TODO state, or if the state is DONE, use the first
3644 state (TODO by default). Also with prefix arg, force first state."
3645 (interactive "P")
3646 (when (not (org-insert-item 'checkbox))
3647 (org-insert-heading)
3648 (save-excursion
3649 (org-back-to-heading)
3650 (if org-noutline-p
3651 (outline-previous-heading)
3652 (outline-previous-visible-heading t))
3653 (looking-at org-todo-line-regexp))
3654 (if (or arg
3655 (not (match-beginning 2))
3656 (equal (match-string 2) org-done-string))
3657 (insert (car org-todo-keywords) " ")
3658 (insert (match-string 2) " "))))
3659
3660 (defun org-promote-subtree ()
3661 "Promote the entire subtree.
3662 See also `org-promote'."
3663 (interactive)
3664 (save-excursion
3665 (org-map-tree 'org-promote)))
3666
3667 (defun org-demote-subtree ()
3668 "Demote the entire subtree. See `org-demote'.
3669 See also `org-promote'."
3670 (interactive)
3671 (save-excursion
3672 (org-map-tree 'org-demote)))
3673
3674 (defun org-do-promote ()
3675 "Promote the current heading higher up the tree.
3676 If the region is active in `transient-mark-mode', promote all headings
3677 in the region."
3678 (interactive)
3679 (save-excursion
3680 (if (org-region-active-p)
3681 (org-map-region 'org-promote (region-beginning) (region-end))
3682 (org-promote)))
3683 (org-fix-position-after-promote))
3684
3685 (defun org-do-demote ()
3686 "Demote the current heading lower down the tree.
3687 If the region is active in `transient-mark-mode', demote all headings
3688 in the region."
3689 (interactive)
3690 (save-excursion
3691 (if (org-region-active-p)
3692 (org-map-region 'org-demote (region-beginning) (region-end))
3693 (org-demote)))
3694 (org-fix-position-after-promote))
3695
3696 (defun org-fix-position-after-promote ()
3697 "Make sure that after pro/demotion cursor position is right."
3698 (and (equal (char-after) ?\ )
3699 (equal (char-before) ?*)
3700 (forward-char 1)))
3701
3702 (defun org-get-legal-level (level change)
3703 "Rectify a level change under the influence of `org-odd-levels-only'
3704 LEVEL is a current level, CHANGE is by how much the level should be
3705 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3706 even level numbers will become the next higher odd number."
3707 (if org-odd-levels-only
3708 (cond ((not change) (1+ (* 2 (/ level 2))))
3709 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3710 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3711 (max 1 (+ level change))))
3712
3713 (defun org-promote ()
3714 "Promote the current heading higher up the tree.
3715 If the region is active in `transient-mark-mode', promote all headings
3716 in the region."
3717 (org-back-to-heading t)
3718 (let* ((level (save-match-data (funcall outline-level)))
3719 (up-head (make-string (org-get-legal-level level -1) ?*))
3720 (diff (abs (- level (length up-head)))))
3721 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3722 (replace-match up-head nil t)
3723 ;; Fixup tag positioning
3724 (and org-auto-align-tags (org-set-tags nil t))
3725 (if org-adapt-indentation
3726 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
3727 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
3728
3729 (defun org-demote ()
3730 "Demote the current heading lower down the tree.
3731 If the region is active in `transient-mark-mode', demote all headings
3732 in the region."
3733 (org-back-to-heading t)
3734 (let* ((level (save-match-data (funcall outline-level)))
3735 (down-head (make-string (org-get-legal-level level 1) ?*))
3736 (diff (abs (- level (length down-head)))))
3737 (replace-match down-head nil t)
3738 ;; Fixup tag positioning
3739 (and org-auto-align-tags (org-set-tags nil t))
3740 (if org-adapt-indentation
3741 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
3742
3743 (defun org-map-tree (fun)
3744 "Call FUN for every heading underneath the current one."
3745 (org-back-to-heading)
3746 (let ((level (funcall outline-level)))
3747 (save-excursion
3748 (funcall fun)
3749 (while (and (progn
3750 (outline-next-heading)
3751 (> (funcall outline-level) level))
3752 (not (eobp)))
3753 (funcall fun)))))
3754
3755 (defun org-map-region (fun beg end)
3756 "Call FUN for every heading between BEG and END."
3757 (let ((org-ignore-region t))
3758 (save-excursion
3759 (setq end (copy-marker end))
3760 (goto-char beg)
3761 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3762 (< (point) end))
3763 (funcall fun))
3764 (while (and (progn
3765 (outline-next-heading)
3766 (< (point) end))
3767 (not (eobp)))
3768 (funcall fun)))))
3769
3770 ;; FIXME: this does not work well with Tabulators. This has to be re-written entirely.
3771 (defun org-fixup-indentation (from to prohibit)
3772 "Change the indentation in the current entry by re-replacing FROM with TO.
3773 However, if the regexp PROHIBIT matches at all, don't do anything.
3774 This is being used to change indentation along with the length of the
3775 heading marker. But if there are any lines which are not indented, nothing
3776 is changed at all."
3777 (save-excursion
3778 (let ((end (save-excursion (outline-next-heading)
3779 (point-marker))))
3780 (unless (save-excursion (re-search-forward prohibit end t))
3781 (while (re-search-forward from end t)
3782 (replace-match to)
3783 (beginning-of-line 2)))
3784 (move-marker end nil))))
3785
3786 ;;; Vertical tree motion, cutting and pasting of subtrees
3787
3788 (defun org-move-subtree-up (&optional arg)
3789 "Move the current subtree up past ARG headlines of the same level."
3790 (interactive "p")
3791 (org-move-subtree-down (- (prefix-numeric-value arg))))
3792
3793 (defun org-move-subtree-down (&optional arg)
3794 "Move the current subtree down past ARG headlines of the same level."
3795 (interactive "p")
3796 (setq arg (prefix-numeric-value arg))
3797 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3798 'outline-get-last-sibling))
3799 (ins-point (make-marker))
3800 (cnt (abs arg))
3801 beg end txt folded)
3802 ;; Select the tree
3803 (org-back-to-heading)
3804 (setq beg (point))
3805 (save-match-data
3806 (save-excursion (outline-end-of-heading)
3807 (setq folded (org-invisible-p)))
3808 (outline-end-of-subtree))
3809 (outline-next-heading)
3810 (setq end (point))
3811 ;; Find insertion point, with error handling
3812 (goto-char beg)
3813 (while (> cnt 0)
3814 (or (and (funcall movfunc) (looking-at outline-regexp))
3815 (progn (goto-char beg)
3816 (error "Cannot move past superior level or buffer limit")))
3817 (setq cnt (1- cnt)))
3818 (if (> arg 0)
3819 ;; Moving forward - still need to move over subtree
3820 (progn (outline-end-of-subtree)
3821 (outline-next-heading)
3822 (if (not (or (looking-at (concat "^" outline-regexp))
3823 (bolp)))
3824 (newline))))
3825 (move-marker ins-point (point))
3826 (setq txt (buffer-substring beg end))
3827 (delete-region beg end)
3828 (insert txt)
3829 (goto-char ins-point)
3830 (if folded (hide-subtree))
3831 (move-marker ins-point nil)))
3832
3833 (defvar org-subtree-clip ""
3834 "Clipboard for cut and paste of subtrees.
3835 This is actually only a copy of the kill, because we use the normal kill
3836 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3837
3838 (defvar org-subtree-clip-folded nil
3839 "Was the last copied subtree folded?
3840 This is used to fold the tree back after pasting.")
3841
3842 (defun org-cut-subtree ()
3843 "Cut the current subtree into the clipboard.
3844 This is a short-hand for marking the subtree and then cutting it."
3845 (interactive)
3846 (org-copy-subtree 'cut))
3847
3848 (defun org-copy-subtree (&optional cut)
3849 "Cut the current subtree into the clipboard.
3850 This is a short-hand for marking the subtree and then copying it.
3851 If CUT is non nil, actually cut the subtree."
3852 (interactive)
3853 (let (beg end folded)
3854 (org-back-to-heading)
3855 (setq beg (point))
3856 (save-match-data
3857 (save-excursion (outline-end-of-heading)
3858 (setq folded (org-invisible-p)))
3859 (outline-end-of-subtree))
3860 (if (equal (char-after) ?\n) (forward-char 1))
3861 (setq end (point))
3862 (goto-char beg)
3863 (when (> end beg)
3864 (setq org-subtree-clip-folded folded)
3865 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3866 (setq org-subtree-clip (current-kill 0))
3867 (message "%s: Subtree with %d characters"
3868 (if cut "Cut" "Copied")
3869 (length org-subtree-clip)))))
3870
3871 (defun org-paste-subtree (&optional level tree)
3872 "Paste the clipboard as a subtree, with modification of headline level.
3873 The entire subtree is promoted or demoted in order to match a new headline
3874 level. By default, the new level is derived from the visible headings
3875 before and after the insertion point, and taken to be the inferior headline
3876 level of the two. So if the previous visible heading is level 3 and the
3877 next is level 4 (or vice versa), level 4 will be used for insertion.
3878 This makes sure that the subtree remains an independent subtree and does
3879 not swallow low level entries.
3880
3881 You can also force a different level, either by using a numeric prefix
3882 argument, or by inserting the heading marker by hand. For example, if the
3883 cursor is after \"*****\", then the tree will be shifted to level 5.
3884
3885 If you want to insert the tree as is, just use \\[yank].
3886
3887 If optional TREE is given, use this text instead of the kill ring."
3888 (interactive "P")
3889 (unless (org-kill-is-subtree-p tree)
3890 (error
3891 (substitute-command-keys
3892 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3893 (let* ((txt (or tree (and kill-ring (current-kill 0))))
3894 (^re (concat "^\\(" outline-regexp "\\)"))
3895 (re (concat "\\(" outline-regexp "\\)"))
3896 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3897
3898 (old-level (if (string-match ^re txt)
3899 (- (match-end 0) (match-beginning 0))
3900 -1))
3901 (force-level (cond (level (prefix-numeric-value level))
3902 ((string-match
3903 ^re_ (buffer-substring (point-at-bol) (point)))
3904 (- (match-end 0) (match-beginning 0)))
3905 (t nil)))
3906 (previous-level (save-excursion
3907 (condition-case nil
3908 (progn
3909 (outline-previous-visible-heading 1)
3910 (if (looking-at re)
3911 (- (match-end 0) (match-beginning 0))
3912 1))
3913 (error 1))))
3914 (next-level (save-excursion
3915 (condition-case nil
3916 (progn
3917 (outline-next-visible-heading 1)
3918 (if (looking-at re)
3919 (- (match-end 0) (match-beginning 0))
3920 1))
3921 (error 1))))
3922 (new-level (or force-level (max previous-level next-level)))
3923 (shift (if (or (= old-level -1)
3924 (= new-level -1)
3925 (= old-level new-level))
3926 0
3927 (- new-level old-level)))
3928 (shift1 shift)
3929 (delta (if (> shift 0) -1 1))
3930 (func (if (> shift 0) 'org-demote 'org-promote))
3931 (org-odd-levels-only nil)
3932 beg end)
3933 ;; Remove the forces level indicator
3934 (if force-level
3935 (delete-region (point-at-bol) (point)))
3936 ;; Make sure we start at the beginning of an empty line
3937 (if (not (bolp)) (insert "\n"))
3938 (if (not (looking-at "[ \t]*$"))
3939 (progn (insert "\n") (backward-char 1)))
3940 ;; Paste
3941 (setq beg (point))
3942 (if (string-match "[ \t\r\n]+\\'" txt)
3943 (setq txt (replace-match "\n" t t txt)))
3944 (insert txt)
3945 (setq end (point))
3946 (if (looking-at "[ \t\r\n]+")
3947 (replace-match "\n"))
3948 (goto-char beg)
3949 ;; Shift if necessary
3950 (if (= shift 0)
3951 (message "Pasted at level %d, without shift" new-level)
3952 (save-restriction
3953 (narrow-to-region beg end)
3954 (while (not (= shift 0))
3955 (org-map-region func (point-min) (point-max))
3956 (setq shift (+ delta shift)))
3957 (goto-char (point-min))
3958 (message "Pasted at level %d, with shift by %d levels"
3959 new-level shift1)))
3960 (if (and kill-ring
3961 (eq org-subtree-clip (current-kill 0))
3962 org-subtree-clip-folded)
3963 ;; The tree was folded before it was killed/copied
3964 (hide-subtree))))
3965
3966 (defun org-kill-is-subtree-p (&optional txt)
3967 "Check if the current kill is an outline subtree, or a set of trees.
3968 Returns nil if kill does not start with a headline, or if the first
3969 headline level is not the largest headline level in the tree.
3970 So this will actually accept several entries of equal levels as well,
3971 which is OK for `org-paste-subtree'.
3972 If optional TXT is given, check this string instead of the current kill."
3973 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
3974 (start-level (and kill
3975 (string-match (concat "\\`" outline-regexp) kill)
3976 (- (match-end 0) (match-beginning 0))))
3977 (re (concat "^" outline-regexp))
3978 (start 1))
3979 (if (not start-level)
3980 nil ;; does not even start with a heading
3981 (catch 'exit
3982 (while (setq start (string-match re kill (1+ start)))
3983 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3984 (throw 'exit nil)))
3985 t))))
3986
3987 ;;; Plain list items
3988
3989 (defun org-at-item-p ()
3990 "Is point in a line starting a hand-formatted item?"
3991 (let ((llt org-plain-list-ordered-item-terminator))
3992 (save-excursion
3993 (goto-char (point-at-bol))
3994 (looking-at
3995 (cond
3996 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3997 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3998 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3999 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4000
4001 (defun org-at-item-checkbox-p ()
4002 "Is point at a line starting a plain-list item with a checklet?"
4003 (and (org-at-item-p)
4004 (save-excursion
4005 (goto-char (match-end 0))
4006 (skip-chars-forward " \t")
4007 (looking-at "\\[[ X]\\]"))))
4008
4009 (defun org-toggle-checkbox ()
4010 "Toggle the checkbox in the current line."
4011 (interactive)
4012 (save-excursion
4013 (if (org-at-item-checkbox-p)
4014 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))))
4015
4016 (defun org-get-indentation (&optional line)
4017 "Get the indentation of the current line, interpreting tabs.
4018 When LINE is given, assume it represents a line and compute its indentation."
4019 (if line
4020 (if (string-match "^ *" (org-remove-tabs line))
4021 (match-end 0))
4022 (save-excursion
4023 (beginning-of-line 1)
4024 (skip-chars-forward " \t")
4025 (current-column))))
4026
4027 (defun org-remove-tabs (s &optional width)
4028 "Replace tabulators in S with spaces.
4029 Assumes that s is a single line, starting in column 0."
4030 (setq width (or width tab-width))
4031 (while (string-match "\t" s)
4032 (setq s (replace-match
4033 (make-string
4034 (- (* width (/ (+ (match-beginning 0) width) width))
4035 (match-beginning 0)) ?\ )
4036 t t s)))
4037 s)
4038
4039 ;; FIXME: document properly.
4040 (defun org-fix-indentation (line ind)
4041 "If the current indenation is smaller than ind1, leave it alone.
4042 If it is larger than ind, reduce it by ind."
4043 (let* ((l (org-remove-tabs line))
4044 (i (org-get-indentation l))
4045 (i1 (car ind)) (i2 (cdr ind)))
4046 (if (>= i i2) (setq l (substring line i2)))
4047 (if (> i1 0)
4048 (concat (make-string i1 ?\ ) l)
4049 l)))
4050
4051 (defun org-beginning-of-item ()
4052 "Go to the beginning of the current hand-formatted item.
4053 If the cursor is not in an item, throw an error."
4054 (interactive)
4055 (let ((pos (point))
4056 (limit (save-excursion (org-back-to-heading)
4057 (beginning-of-line 2) (point)))
4058 ind ind1)
4059 (if (org-at-item-p)
4060 (beginning-of-line 1)
4061 (beginning-of-line 1)
4062 (skip-chars-forward " \t")
4063 (setq ind (current-column))
4064 (if (catch 'exit
4065 (while t
4066 (beginning-of-line 0)
4067 (if (< (point) limit) (throw 'exit nil))
4068 (unless (looking-at " \t]*$")
4069 (skip-chars-forward " \t")
4070 (setq ind1 (current-column))
4071 (if (< ind1 ind)
4072 (throw 'exit (org-at-item-p))))))
4073 nil
4074 (goto-char pos)
4075 (error "Not in an item")))))
4076
4077 (defun org-end-of-item ()
4078 "Go to the end of the current hand-formatted item.
4079 If the cursor is not in an item, throw an error."
4080 (interactive)
4081 (let ((pos (point))
4082 (limit (save-excursion (outline-next-heading) (point)))
4083 (ind (save-excursion
4084 (org-beginning-of-item)
4085 (skip-chars-forward " \t")
4086 (current-column)))
4087 ind1)
4088 (if (catch 'exit
4089 (while t
4090 (beginning-of-line 2)
4091 (if (>= (point) limit) (throw 'exit t))
4092 (unless (looking-at "[ \t]*$")
4093 (skip-chars-forward " \t")
4094 (setq ind1 (current-column))
4095 (if (<= ind1 ind) (throw 'exit t)))))
4096 (beginning-of-line 1)
4097 (goto-char pos)
4098 (error "Not in an item"))))
4099
4100 (defun org-next-item ()
4101 "Move to the beginning of the next item in the current plain list.
4102 Error if not at a plain list, or if this is the last item in the list."
4103 (interactive)
4104 (let (beg end ind ind1 (pos (point)) txt)
4105 (org-beginning-of-item)
4106 (setq beg (point))
4107 (setq ind (org-get-indentation))
4108 (org-end-of-item)
4109 (setq end (point))
4110 (setq ind1 (org-get-indentation))
4111 (unless (and (org-at-item-p) (= ind ind1))
4112 (goto-char pos)
4113 (error "On last item"))))
4114
4115 (defun org-previous-item ()
4116 "Move to the beginning of the previous item in the current plain list.
4117 Error if not at a plain list, or if this is the last item in the list."
4118 (interactive)
4119 (let (beg end ind ind1 (pos (point)) txt)
4120 (org-beginning-of-item)
4121 (setq beg (point))
4122 (setq ind (org-get-indentation))
4123 (goto-char beg)
4124 (catch 'exit
4125 (while t
4126 (beginning-of-line 0)
4127 (if (looking-at "[ \t]*$")
4128 nil
4129 (if (<= (setq ind1 (org-get-indentation)) ind)
4130 (throw 'exit t)))))
4131 (condition-case nil
4132 (org-beginning-of-item)
4133 (error (goto-char pos)
4134 (error "On first item")))))
4135
4136 (defun org-move-item-down ()
4137 "Move the plain list item at point down, i.e. swap with following item.
4138 Subitems (items with larger indentation) are considered part of the item,
4139 so this really moves item trees."
4140 (interactive)
4141 (let (beg end ind ind1 (pos (point)) txt)
4142 (org-beginning-of-item)
4143 (setq beg (point))
4144 (setq ind (org-get-indentation))
4145 (org-end-of-item)
4146 (setq end (point))
4147 (setq ind1 (org-get-indentation))
4148 (if (and (org-at-item-p) (= ind ind1))
4149 (progn
4150 (org-end-of-item)
4151 (setq txt (buffer-substring beg end))
4152 (save-excursion
4153 (delete-region beg end))
4154 (setq pos (point))
4155 (insert txt)
4156 (goto-char pos)
4157 (org-maybe-renumber-ordered-list))
4158 (goto-char pos)
4159 (error "Cannot move this item further down"))))
4160
4161 (defun org-move-item-up (arg)
4162 "Move the plain list item at point up, i.e. swap with previous item.
4163 Subitems (items with larger indentation) are considered part of the item,
4164 so this really moves item trees."
4165 (interactive "p")
4166 (let (beg end ind ind1 (pos (point)) txt)
4167 (org-beginning-of-item)
4168 (setq beg (point))
4169 (setq ind (org-get-indentation))
4170 (org-end-of-item)
4171 (setq end (point))
4172 (goto-char beg)
4173 (catch 'exit
4174 (while t
4175 (beginning-of-line 0)
4176 (if (looking-at "[ \t]*$")
4177 nil
4178 (if (<= (setq ind1 (org-get-indentation)) ind)
4179 (throw 'exit t)))))
4180 (condition-case nil
4181 (org-beginning-of-item)
4182 (error (goto-char beg)
4183 (error "Cannot move this item further up")))
4184 (setq ind1 (org-get-indentation))
4185 (if (and (org-at-item-p) (= ind ind1))
4186 (progn
4187 (setq txt (buffer-substring beg end))
4188 (save-excursion
4189 (delete-region beg end))
4190 (setq pos (point))
4191 (insert txt)
4192 (goto-char pos)
4193 (org-maybe-renumber-ordered-list))
4194 (goto-char pos)
4195 (error "Cannot move this item further up"))))
4196
4197 (defun org-maybe-renumber-ordered-list ()
4198 "Renumber the ordered list at point if setup allows it.
4199 This tests the user option `org-auto-renumber-ordered-lists' before
4200 doing the renumbering."
4201 (and org-auto-renumber-ordered-lists
4202 (org-at-item-p)
4203 (match-beginning 3)
4204 (org-renumber-ordered-list 1)))
4205
4206 (defun org-get-string-indentation (s)
4207 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4208 (let ((n -1) (i 0) (w tab-width) c)
4209 (catch 'exit
4210 (while (< (setq n (1+ n)) (length s))
4211 (setq c (aref s n))
4212 (cond ((= c ?\ ) (setq i (1+ i)))
4213 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4214 (t (throw 'exit t)))))
4215 i))
4216
4217 (defun org-renumber-ordered-list (arg)
4218 "Renumber an ordered plain list.
4219 Cursor needs to be in the first line of an item, the line that starts
4220 with something like \"1.\" or \"2)\"."
4221 (interactive "p")
4222 (unless (and (org-at-item-p)
4223 (match-beginning 3))
4224 (error "This is not an ordered list"))
4225 (let ((line (org-current-line))
4226 (col (current-column))
4227 (ind (org-get-string-indentation
4228 (buffer-substring (point-at-bol) (match-beginning 3))))
4229 ;; (term (substring (match-string 3) -1))
4230 ind1 (n (1- arg)))
4231 ;; find where this list begins
4232 (catch 'exit
4233 (while t
4234 (catch 'next
4235 (beginning-of-line 0)
4236 (if (looking-at "[ \t]*$") (throw 'next t))
4237 (skip-chars-forward " \t") (setq ind1 (current-column))
4238 (if (or (< ind1 ind)
4239 (and (= ind1 ind)
4240 (not (org-at-item-p))))
4241 (throw 'exit t)))))
4242 ;; Walk forward and replace these numbers
4243 (catch 'exit
4244 (while t
4245 (catch 'next
4246 (beginning-of-line 2)
4247 (if (eobp) (throw 'exit nil))
4248 (if (looking-at "[ \t]*$") (throw 'next nil))
4249 (skip-chars-forward " \t") (setq ind1 (current-column))
4250 (if (> ind1 ind) (throw 'next t))
4251 (if (< ind1 ind) (throw 'exit t))
4252 (if (not (org-at-item-p)) (throw 'exit nil))
4253 (if (not (match-beginning 3))
4254 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4255 (delete-region (match-beginning 3) (1- (match-end 3)))
4256 (goto-char (match-beginning 3))
4257 (insert (format "%d" (setq n (1+ n)))))))
4258 (goto-line line)
4259 (move-to-column col)))
4260
4261 (defvar org-last-indent-begin-marker (make-marker))
4262 (defvar org-last-indent-end-marker (make-marker))
4263
4264 (defun org-outdent-item (arg)
4265 "Outdent a local list item."
4266 (interactive "p")
4267 (org-indent-item (- arg)))
4268
4269 (defun org-indent-item (arg)
4270 "Indent a local list item."
4271 (interactive "p")
4272 (unless (org-at-item-p)
4273 (error "Not on an item"))
4274 (save-excursion
4275 (let (beg end ind ind1)
4276 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4277 (setq beg org-last-indent-begin-marker
4278 end org-last-indent-end-marker)
4279 (org-beginning-of-item)
4280 (setq beg (move-marker org-last-indent-begin-marker (point)))
4281 (org-end-of-item)
4282 (setq end (move-marker org-last-indent-end-marker (point))))
4283 (goto-char beg)
4284 (skip-chars-forward " \t") (setq ind (current-column))
4285 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4286 (while (< (point) end)
4287 (beginning-of-line 1)
4288 (skip-chars-forward " \t") (setq ind1 (current-column))
4289 (delete-region (point-at-bol) (point))
4290 (indent-to-column (+ ind1 arg))
4291 (beginning-of-line 2)))))
4292
4293 ;;; Archiving
4294
4295 (defun org-archive-subtree ()
4296 "Move the current subtree to the archive.
4297 The archive can be a certain top-level heading in the current file, or in
4298 a different file. The tree will be moved to that location, the subtree
4299 heading be marked DONE, and the current time will be added."
4300 (interactive)
4301 ;; Save all relevant TODO keyword-relatex variables
4302 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4303 (tr-org-todo-keywords org-todo-keywords)
4304 (tr-org-todo-interpretation org-todo-interpretation)
4305 (tr-org-done-string org-done-string)
4306 (tr-org-todo-regexp org-todo-regexp)
4307 (tr-org-todo-line-regexp org-todo-line-regexp)
4308 (this-buffer (current-buffer))
4309 file heading buffer level newfile-p)
4310 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4311 (progn
4312 (setq file (format (match-string 1 org-archive-location)
4313 (file-name-nondirectory buffer-file-name))
4314 heading (match-string 2 org-archive-location)))
4315 (error "Invalid `org-archive-location'"))
4316 (if (> (length file) 0)
4317 (setq newfile-p (not (file-exists-p file))
4318 buffer (find-file-noselect file))
4319 (setq buffer (current-buffer)))
4320 (unless buffer
4321 (error "Cannot access file \"%s\"" file))
4322 (if (and (> (length heading) 0)
4323 (string-match "^\\*+" heading))
4324 (setq level (match-end 0))
4325 (setq heading nil level 0))
4326 (save-excursion
4327 ;; We first only copy, in case something goes wrong
4328 ;; we need to protect this-command, to avoid kill-region sets it,
4329 ;; which would lead to duplication of subtrees
4330 (let (this-command) (org-copy-subtree))
4331 (set-buffer buffer)
4332 ;; Enforce org-mode for the archive buffer
4333 (if (not (eq major-mode 'org-mode))
4334 ;; Force the mode for future visits.
4335 (let ((org-insert-mode-line-in-empty-file t))
4336 (call-interactively 'org-mode)))
4337 (when newfile-p
4338 (goto-char (point-max))
4339 (insert (format "\nArchived entries from file %s\n\n"
4340 (buffer-file-name this-buffer))))
4341 ;; Force the TODO keywords of the original buffer
4342 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4343 (org-todo-keywords tr-org-todo-keywords)
4344 (org-todo-interpretation tr-org-todo-interpretation)
4345 (org-done-string tr-org-done-string)
4346 (org-todo-regexp tr-org-todo-regexp)
4347 (org-todo-line-regexp tr-org-todo-line-regexp))
4348 (goto-char (point-min))
4349 (if heading
4350 (progn
4351 (if (re-search-forward
4352 (concat "\\(^\\|\r\\)"
4353 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4354 nil t)
4355 (goto-char (match-end 0))
4356 ;; Heading not found, just insert it at the end
4357 (goto-char (point-max))
4358 (or (bolp) (insert "\n"))
4359 (insert "\n" heading "\n")
4360 (end-of-line 0))
4361 ;; Make the subtree visible
4362 (show-subtree)
4363 (org-end-of-subtree t)
4364 (skip-chars-backward " \t\r\n]")
4365 (and (looking-at "[ \t\r\n]*")
4366 (replace-match "\n\n")))
4367 ;; No specific heading, just go to end of file.
4368 (goto-char (point-max)) (insert "\n"))
4369 ;; Paste
4370 (org-paste-subtree (1+ level))
4371 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4372 (if org-archive-mark-done
4373 (org-todo (length org-todo-keywords)))
4374 ;; Move cursor to right after the TODO keyword
4375 (when org-archive-stamp-time
4376 (beginning-of-line 1)
4377 (looking-at org-todo-line-regexp)
4378 (goto-char (or (match-end 2) (match-beginning 3)))
4379 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4380 (org-current-time))
4381 ")"))
4382 ;; Save the buffer, if it is not the same buffer.
4383 (if (not (eq this-buffer buffer)) (save-buffer))))
4384 ;; Here we are back in the original buffer. Everything seems to have
4385 ;; worked. So now cut the tree and finish up.
4386 (let (this-command) (org-cut-subtree))
4387 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4388 (message "Subtree archived %s"
4389 (if (eq this-buffer buffer)
4390 (concat "under heading: " heading)
4391 (concat "in file: " (abbreviate-file-name file))))))
4392
4393 ;;; Completion
4394
4395 (defun org-complete (&optional arg)
4396 "Perform completion on word at point.
4397 At the beginning of a headline, this completes TODO keywords as given in
4398 `org-todo-keywords'.
4399 If the current word is preceded by a backslash, completes the TeX symbols
4400 that are supported for HTML support.
4401 If the current word is preceded by \"#+\", completes special words for
4402 setting file options.
4403 At all other locations, this simply calls `ispell-complete-word'."
4404 (interactive "P")
4405 (catch 'exit
4406 (let* ((end (point))
4407 (beg1 (save-excursion
4408 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4409 (skip-chars-backward "a-zA-Z_@0-9")
4410 (point)))
4411 (beg (save-excursion
4412 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4413 (skip-chars-backward "a-zA-Z0-9_:$")
4414 (point)))
4415 (confirm (lambda (x) (stringp (car x))))
4416 (camel (equal (char-before beg) ?*))
4417 (tag (equal (char-before beg1) ?:))
4418 (texp (equal (char-before beg) ?\\))
4419 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
4420 beg)
4421 "#+"))
4422 (completion-ignore-case opt)
4423 (type nil)
4424 (tbl nil)
4425 (table (cond
4426 (opt
4427 (setq type :opt)
4428 (mapcar (lambda (x)
4429 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
4430 (cons (match-string 2 x) (match-string 1 x)))
4431 (org-split-string (org-get-current-options) "\n")))
4432 (texp
4433 (setq type :tex)
4434 org-html-entities)
4435 ((string-match "\\`\\*+[ \t]*\\'"
4436 (buffer-substring (point-at-bol) beg))
4437 (setq type :todo)
4438 (mapcar 'list org-todo-keywords))
4439 (camel
4440 (setq type :camel)
4441 (save-excursion
4442 (goto-char (point-min))
4443 (while (re-search-forward org-todo-line-regexp nil t)
4444 (push (list
4445 (if org-file-link-context-use-camel-case
4446 (org-make-org-heading-camel (match-string 3) t)
4447 (org-make-org-heading-search-string
4448 (match-string 3) t)))
4449 tbl)))
4450 tbl)
4451 (tag (setq type :tag beg beg1)
4452 (or org-tag-alist (org-get-buffer-tags)))
4453 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
4454 (pattern (buffer-substring-no-properties beg end))
4455 (completion (try-completion pattern table confirm)))
4456 (cond ((eq completion t)
4457 (if (equal type :opt)
4458 (insert (substring (cdr (assoc (upcase pattern) table))
4459 (length pattern)))))
4460 ((null completion)
4461 (message "Can't find completion for \"%s\"" pattern)
4462 (ding))
4463 ((not (string= pattern completion))
4464 (delete-region beg end)
4465 (if (string-match " +$" completion)
4466 (setq completion (replace-match "" t t completion)))
4467 (insert completion)
4468 (if (get-buffer-window "*Completions*")
4469 (delete-window (get-buffer-window "*Completions*")))
4470 (if (assoc completion table)
4471 (if (eq type :todo) (insert " ")
4472 (if (eq type :tag) (insert ":"))))
4473 (if (and (equal type :opt) (assoc completion table))
4474 (message "%s" (substitute-command-keys
4475 "Press \\[org-complete] again to insert example settings"))))
4476 (t
4477 (message "Making completion list...")
4478 (let ((list (sort (all-completions pattern table confirm)
4479 'string<)))
4480 (with-output-to-temp-buffer "*Completions*"
4481 (condition-case nil
4482 ;; Protection needed for XEmacs and emacs 21
4483 (display-completion-list list pattern)
4484 (error (display-completion-list list)))))
4485 (message "Making completion list...%s" "done"))))))
4486
4487 ;;; Comments, TODO and DEADLINE
4488
4489 (defun org-toggle-comment ()
4490 "Change the COMMENT state of an entry."
4491 (interactive)
4492 (save-excursion
4493 (org-back-to-heading)
4494 (if (looking-at (concat outline-regexp
4495 "\\( +\\<" org-comment-string "\\>\\)"))
4496 (replace-match "" t t nil 1)
4497 (if (looking-at outline-regexp)
4498 (progn
4499 (goto-char (match-end 0))
4500 (insert " " org-comment-string))))))
4501
4502 (defvar org-last-todo-state-is-todo nil
4503 "This is non-nil when the last TODO state change led to a TODO state.
4504 If the last change removed the TODO tag or switched to DONE, then
4505 this is nil.")
4506
4507 (defun org-todo (&optional arg)
4508 "Change the TODO state of an item.
4509 The state of an item is given by a keyword at the start of the heading,
4510 like
4511 *** TODO Write paper
4512 *** DONE Call mom
4513
4514 The different keywords are specified in the variable `org-todo-keywords'.
4515 By default the available states are \"TODO\" and \"DONE\".
4516 So for this example: when the item starts with TODO, it is changed to DONE.
4517 When it starts with DONE, the DONE is removed. And when neither TODO nor
4518 DONE are present, add TODO at the beginning of the heading.
4519
4520 With prefix arg, use completion to determine the new state. With numeric
4521 prefix arg, switch to that state."
4522 (interactive "P")
4523 (save-excursion
4524 (org-back-to-heading)
4525 (if (looking-at outline-regexp) (goto-char (match-end 0)))
4526 (or (looking-at (concat " +" org-todo-regexp " *"))
4527 (looking-at " *"))
4528 (let* ((this (match-string 1))
4529 (completion-ignore-case t)
4530 (member (member this org-todo-keywords))
4531 (tail (cdr member))
4532 (state (cond
4533 ((equal arg '(4))
4534 ;; Read a state with completion
4535 (completing-read "State: " (mapcar (lambda(x) (list x))
4536 org-todo-keywords)
4537 nil t))
4538 ((eq arg 'right)
4539 (if this
4540 (if tail (car tail) nil)
4541 (car org-todo-keywords)))
4542 ((eq arg 'left)
4543 (if (equal member org-todo-keywords)
4544 nil
4545 (if this
4546 (nth (- (length org-todo-keywords) (length tail) 2)
4547 org-todo-keywords)
4548 org-done-string)))
4549 (arg
4550 ;; user requests a specific state
4551 (nth (1- (prefix-numeric-value arg))
4552 org-todo-keywords))
4553 ((null member) (car org-todo-keywords))
4554 ((null tail) nil) ;; -> first entry
4555 ((eq org-todo-interpretation 'sequence)
4556 (car tail))
4557 ((memq org-todo-interpretation '(type priority))
4558 (if (eq this-command last-command)
4559 (car tail)
4560 (if (> (length tail) 0) org-done-string nil)))
4561 (t nil)))
4562 (next (if state (concat " " state " ") " ")))
4563 (replace-match next t t)
4564 (setq org-last-todo-state-is-todo
4565 (not (equal state org-done-string)))
4566 (when org-log-done
4567 (if (equal state org-done-string)
4568 (org-add-planning-info 'closed (current-time) 'scheduled)
4569 (if (not this)
4570 (org-add-planning-info nil nil 'closed))))
4571 ;; Fixup tag positioning
4572 (and org-auto-align-tags (org-set-tags nil t))
4573 (run-hooks 'org-after-todo-state-change-hook)))
4574 ;; Fixup cursor location if close to the keyword
4575 (if (and (outline-on-heading-p)
4576 (not (bolp))
4577 (save-excursion (beginning-of-line 1)
4578 (looking-at org-todo-line-regexp))
4579 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
4580 (progn
4581 (goto-char (or (match-end 2) (match-end 1)))
4582 (just-one-space))))
4583
4584 (defun org-log-done (&optional undone)
4585 "Add a time stamp logging that a TODO entry has been closed.
4586 When UNDONE is non-nil, remove such a time stamp again."
4587 (interactive)
4588 (let (beg end col)
4589 (save-excursion
4590 (org-back-to-heading t)
4591 (setq beg (point))
4592 (looking-at (concat outline-regexp " *"))
4593 (goto-char (match-end 0))
4594 (setq col (current-column))
4595 (outline-next-heading)
4596 (setq end (point))
4597 (goto-char beg)
4598 (when (re-search-forward (concat
4599 "[\r\n]\\([ \t]*"
4600 (regexp-quote org-closed-string)
4601 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
4602 (delete-region (match-beginning 1) (match-end 1)))
4603 (unless undone
4604 (org-back-to-heading t)
4605 (skip-chars-forward "^\n\r")
4606 (goto-char (min (1+ (point)) (point-max)))
4607 (when (not (member (char-before) '(?\r ?\n)))
4608 (insert "\n"))
4609 (indent-to col)
4610 (insert org-closed-string " "
4611 (format-time-string
4612 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4613 (org-current-time))
4614 "\n")))))
4615
4616 (defun org-show-todo-tree (arg)
4617 "Make a compact tree which shows all headlines marked with TODO.
4618 The tree will show the lines where the regexp matches, and all higher
4619 headlines above the match.
4620 With \\[universal-argument] prefix, also show the DONE entries.
4621 With a numeric prefix N, construct a sparse tree for the Nth element
4622 of `org-todo-keywords'."
4623 (interactive "P")
4624 (let ((case-fold-search nil)
4625 (kwd-re
4626 (cond ((null arg) org-not-done-regexp)
4627 ((equal arg '(4)) org-todo-regexp)
4628 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
4629 (regexp-quote (nth (1- (prefix-numeric-value arg))
4630 org-todo-keywords)))
4631 (t (error "Invalid prefix argument: %s" arg)))))
4632 (message "%d TODO entries found"
4633 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
4634
4635 (defun org-deadline ()
4636 "Insert the DEADLINE: string to make a deadline.
4637 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4638 to modify it to the correct date."
4639 (interactive)
4640 (org-add-planning-info 'deadline nil 'closed))
4641
4642 (defun org-schedule ()
4643 "Insert the SCHEDULED: string to schedule a TODO item.
4644 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4645 to modify it to the correct date."
4646 (interactive)
4647 (org-add-planning-info 'scheduled nil 'closed))
4648
4649 (defun org-add-planning-info (what &optional time &rest remove)
4650 "Insert new timestamp with keyword in the line directly after the headline.
4651 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
4652 If non is given, the user is prompted for a date.
4653 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
4654 be removed."
4655 (interactive)
4656 (when what (setq time (or time (org-read-date nil 'to-time))))
4657 (when (and org-insert-labeled-timestamps-at-point
4658 (member what '(scheduled deadline)))
4659 (insert
4660 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
4661 " "
4662 (format-time-string (car org-time-stamp-formats) time))
4663 (setq what nil))
4664 (save-excursion
4665 (let (beg end col list elt (buffer-invisibility-spec nil) ts)
4666 (org-back-to-heading t)
4667 (setq beg (point))
4668 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
4669 (goto-char (match-end 1))
4670 (setq col (current-column))
4671 (goto-char (1+ (match-end 0)))
4672 (if (and (not (looking-at outline-regexp))
4673 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
4674 "[^\r\n]*"))
4675 (not (equal (match-string 1) org-clock-string)))
4676 (narrow-to-region (match-beginning 0) (match-end 0))
4677 (insert "\n")
4678 (backward-char 1)
4679 (narrow-to-region (point) (point))
4680 (indent-to-column col))
4681 ;; Check if we have to remove something.
4682 (setq list (cons what remove))
4683 (while list
4684 (setq elt (pop list))
4685 (goto-char (point-min))
4686 (when (or (and (eq elt 'scheduled)
4687 (re-search-forward org-scheduled-time-regexp nil t))
4688 (and (eq elt 'deadline)
4689 (re-search-forward org-deadline-time-regexp nil t))
4690 (and (eq elt 'closed)
4691 (re-search-forward org-closed-time-regexp nil t)))
4692 (replace-match "")
4693 (if (looking-at " +") (replace-match ""))))
4694 (goto-char (point-max))
4695 (when what
4696 (insert
4697 (if (not (equal (char-before) ?\ )) " " "")
4698 (cond ((eq what 'scheduled) org-scheduled-string)
4699 ((eq what 'deadline) org-deadline-string)
4700 ((eq what 'closed) org-closed-string))
4701 " ")
4702 (insert
4703 (setq ts
4704 (format-time-string
4705 (if (eq what 'closed)
4706 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4707 (car org-time-stamp-formats))
4708 time))))
4709 (goto-char (point-min))
4710 (widen)
4711 (if (looking-at "[ \t]+\r?\n")
4712 (replace-match ""))
4713 ts)))
4714
4715 (defun org-occur (regexp &optional callback)
4716 "Make a compact tree which shows all matches of REGEXP.
4717 The tree will show the lines where the regexp matches, and all higher
4718 headlines above the match. It will also show the heading after the match,
4719 to make sure editing the matching entry is easy.
4720 If CALLBACK is non-nil, it is a function which is called to confirm
4721 that the match should indeed be shown."
4722 (interactive "sRegexp: ")
4723 (org-remove-occur-highlights nil nil t)
4724 (setq regexp (org-check-occur-regexp regexp))
4725 (let ((cnt 0))
4726 (save-excursion
4727 (goto-char (point-min))
4728 (org-overview)
4729 (while (re-search-forward regexp nil t)
4730 (when (or (not callback)
4731 (save-match-data (funcall callback)))
4732 (setq cnt (1+ cnt))
4733 (org-highlight-new-match (match-beginning 0) (match-end 0))
4734 (org-show-hierarchy-above))))
4735 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
4736 nil 'local)
4737 (run-hooks 'org-occur-hook)
4738 (if (interactive-p)
4739 (message "%d match(es) for regexp %s" cnt regexp))
4740 cnt))
4741
4742 (defun org-show-hierarchy-above ()
4743 "Make sure point and the headings hierarchy above is visible."
4744 (catch 'exit
4745 (if (org-on-heading-p t)
4746 (org-flag-heading nil) ; only show the heading
4747 (and (or (org-invisible-p) (org-invisible-p2))
4748 (org-show-hidden-entry))) ; show entire entry
4749 (save-excursion
4750 (and org-show-following-heading
4751 (outline-next-heading)
4752 (org-flag-heading nil))) ; show the next heading
4753 (when org-show-hierarchy-above
4754 (save-excursion ; show all higher headings
4755 (while (and (condition-case nil
4756 (progn (org-up-heading-all 1) t)
4757 (error nil))
4758 (not (bobp)))
4759 (org-flag-heading nil))))))
4760
4761 ;; Overlay compatibility functions
4762 (defun org-make-overlay (beg end &optional buffer)
4763 (if (featurep 'xemacs)
4764 (make-extent beg end buffer)
4765 (make-overlay beg end buffer)))
4766 (defun org-delete-overlay (ovl)
4767 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4768 (defun org-detatch-overlay (ovl)
4769 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4770 (defun org-move-overlay (ovl beg end &optional buffer)
4771 (if (featurep 'xemacs)
4772 (set-extent-endpoints ovl beg end buffer)
4773 (move-overlay ovl beg end buffer)))
4774 (defun org-overlay-put (ovl prop value)
4775 (if (featurep 'xemacs)
4776 (set-extent-property ovl prop value)
4777 (overlay-put ovl prop value)))
4778
4779 (defvar org-occur-highlights nil)
4780 (defun org-highlight-new-match (beg end)
4781 "Highlight from BEG to END and mark the highlight is an occur headline."
4782 (let ((ov (org-make-overlay beg end)))
4783 (org-overlay-put ov 'face 'secondary-selection)
4784 (push ov org-occur-highlights)))
4785
4786 (defun org-remove-occur-highlights (&optional beg end noremove)
4787 "Remove the occur highlights from the buffer.
4788 BEG and END are ignored. If NOREMOVE is nil, remove this function
4789 from the `before-change-functions' in the current buffer."
4790 (interactive)
4791 (mapc 'org-delete-overlay org-occur-highlights)
4792 (setq org-occur-highlights nil)
4793 (unless noremove
4794 (remove-hook 'before-change-functions
4795 'org-remove-occur-highlights 'local)))
4796
4797 ;;; Priorities
4798
4799 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
4800 "Regular expression matching the priority indicator.")
4801
4802 (defvar org-remove-priority-next-time nil)
4803
4804 (defun org-priority-up ()
4805 "Increase the priority of the current item."
4806 (interactive)
4807 (org-priority 'up))
4808
4809 (defun org-priority-down ()
4810 "Decrease the priority of the current item."
4811 (interactive)
4812 (org-priority 'down))
4813
4814 (defun org-priority (&optional action)
4815 "Change the priority of an item by ARG.
4816 ACTION can be set, up, or down."
4817 (interactive)
4818 (setq action (or action 'set))
4819 (let (current new news have remove)
4820 (save-excursion
4821 (org-back-to-heading)
4822 (if (looking-at org-priority-regexp)
4823 (setq current (string-to-char (match-string 2))
4824 have t)
4825 (setq current org-default-priority))
4826 (cond
4827 ((eq action 'set)
4828 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
4829 (setq new (read-char-exclusive))
4830 (cond ((equal new ?\ ) (setq remove t))
4831 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
4832 (error "Priority must be between `%c' and `%c'"
4833 ?A org-lowest-priority))))
4834 ((eq action 'up)
4835 (setq new (1- current)))
4836 ((eq action 'down)
4837 (setq new (1+ current)))
4838 (t (error "Invalid action")))
4839 (setq new (min (max ?A (upcase new)) org-lowest-priority))
4840 (setq news (format "%c" new))
4841 (if have
4842 (if remove
4843 (replace-match "" t t nil 1)
4844 (replace-match news t t nil 2))
4845 (if remove
4846 (error "No priority cookie found in line")
4847 (looking-at org-todo-line-regexp)
4848 (if (match-end 2)
4849 (progn
4850 (goto-char (match-end 2))
4851 (insert " [#" news "]"))
4852 (goto-char (match-beginning 3))
4853 (insert "[#" news "] ")))))
4854 (if remove
4855 (message "Priority removed")
4856 (message "Priority of current item set to %s" news))))
4857
4858
4859 (defun org-get-priority (s)
4860 "Find priority cookie and return priority."
4861 (save-match-data
4862 (if (not (string-match org-priority-regexp s))
4863 (* 1000 (- org-lowest-priority org-default-priority))
4864 (* 1000 (- org-lowest-priority
4865 (string-to-char (match-string 2 s)))))))
4866
4867 ;;; Timestamps
4868
4869 (defvar org-last-changed-timestamp nil)
4870
4871 (defun org-time-stamp (arg)
4872 "Prompt for a date/time and insert a time stamp.
4873 If the user specifies a time like HH:MM, or if this command is called
4874 with a prefix argument, the time stamp will contain date and time.
4875 Otherwise, only the date will be included. All parts of a date not
4876 specified by the user will be filled in from the current date/time.
4877 So if you press just return without typing anything, the time stamp
4878 will represent the current date/time. If there is already a timestamp
4879 at the cursor, it will be modified."
4880 (interactive "P")
4881 (let ((fmt (if arg (cdr org-time-stamp-formats)
4882 (car org-time-stamp-formats)))
4883 (org-time-was-given nil)
4884 time)
4885 (cond
4886 ((and (org-at-timestamp-p)
4887 (eq last-command 'org-time-stamp)
4888 (eq this-command 'org-time-stamp))
4889 (insert "--")
4890 (setq time (let ((this-command this-command))
4891 (org-read-date arg 'totime)))
4892 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4893 (insert (format-time-string fmt time)))
4894 ((org-at-timestamp-p)
4895 (setq time (let ((this-command this-command))
4896 (org-read-date arg 'totime)))
4897 (and (org-at-timestamp-p) (replace-match
4898 (setq org-last-changed-timestamp
4899 (format-time-string fmt time))
4900 t t))
4901 (message "Timestamp updated"))
4902 (t
4903 (setq time (let ((this-command this-command))
4904 (org-read-date arg 'totime)))
4905 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4906 (insert (format-time-string fmt time))))))
4907
4908 (defun org-time-stamp-inactive (&optional arg)
4909 "Insert an inactive time stamp.
4910 An inactive time stamp is enclosed in square brackets instead of angle
4911 brackets. It is inactive in the sense that it does not trigger agenda entries,
4912 does not link to the calendar and cannot be changed with the S-cursor keys.
4913 So these are more for recording a certain time/date."
4914 (interactive "P")
4915 (let ((fmt (if arg (cdr org-time-stamp-formats)
4916 (car org-time-stamp-formats)))
4917 (org-time-was-given nil)
4918 time)
4919 (setq time (org-read-date arg 'totime))
4920 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4921 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
4922 (insert (format-time-string fmt time))))
4923
4924 (defvar org-date-ovl (org-make-overlay 1 1))
4925 (org-overlay-put org-date-ovl 'face 'org-warning)
4926 (org-detatch-overlay org-date-ovl)
4927
4928 (defun org-read-date (&optional with-time to-time)
4929 "Read a date and make things smooth for the user.
4930 The prompt will suggest to enter an ISO date, but you can also enter anything
4931 which will at least partially be understood by `parse-time-string'.
4932 Unrecognized parts of the date will default to the current day, month, year,
4933 hour and minute. For example,
4934 3-2-5 --> 2003-02-05
4935 feb 15 --> currentyear-02-15
4936 sep 12 9 --> 2009-09-12
4937 12:45 --> today 12:45
4938 22 sept 0:34 --> currentyear-09-22 0:34
4939 12 --> currentyear-currentmonth-12
4940 Fri --> nearest Friday (today or later)
4941 etc.
4942 The function understands only English month and weekday abbreviations,
4943 but this can be configured with the variables `parse-time-months' and
4944 `parse-time-weekdays'.
4945
4946 While prompting, a calendar is popped up - you can also select the
4947 date with the mouse (button 1). The calendar shows a period of three
4948 months. To scroll it to other months, use the keys `>' and `<'.
4949 If you don't like the calendar, turn it off with
4950 \(setq org-popup-calendar-for-date-prompt nil)
4951
4952 With optional argument TO-TIME, the date will immediately be converted
4953 to an internal time.
4954 With an optional argument WITH-TIME, the prompt will suggest to also
4955 insert a time. Note that when WITH-TIME is not set, you can still
4956 enter a time, and this function will inform the calling routine about
4957 this change. The calling routine may then choose to change the format
4958 used to insert the time stamp into the buffer to include the time."
4959 (require 'parse-time)
4960 (let* ((org-time-stamp-rounding-minutes
4961 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
4962 (ct (org-current-time))
4963 (default-time
4964 ;; Default time is either today, or, when entering a range,
4965 ;; the range start.
4966 (if (save-excursion
4967 (re-search-backward
4968 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
4969 (- (point) 20) t))
4970 (apply
4971 'encode-time
4972 (mapcar (lambda(x) (or x 0))
4973 (parse-time-string (match-string 1))))
4974 ct))
4975 (calendar-move-hook nil)
4976 (view-diary-entries-initially nil)
4977 (view-calendar-holidays-initially nil)
4978 (timestr (format-time-string
4979 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
4980 (prompt (format "YYYY-MM-DD [%s]: " timestr))
4981 ans ans1 ans2
4982 second minute hour day month year tl wday wday1)
4983
4984 (if org-popup-calendar-for-date-prompt
4985 (save-excursion
4986 (save-window-excursion
4987 (calendar)
4988 (calendar-forward-day (- (time-to-days default-time)
4989 (calendar-absolute-from-gregorian
4990 (calendar-current-date))))
4991 (org-eval-in-calendar nil)
4992 (let* ((old-map (current-local-map))
4993 (map (copy-keymap calendar-mode-map))
4994 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4995 (define-key map (kbd "RET") 'org-calendar-select)
4996 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
4997 'org-calendar-select-mouse)
4998 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
4999 'org-calendar-select-mouse)
5000 (define-key minibuffer-local-map [(meta shift left)]
5001 (lambda () (interactive)
5002 (org-eval-in-calendar '(calendar-backward-month 1))))
5003 (define-key minibuffer-local-map [(meta shift right)]
5004 (lambda () (interactive)
5005 (org-eval-in-calendar '(calendar-forward-month 1))))
5006 (define-key minibuffer-local-map [(shift up)]
5007 (lambda () (interactive)
5008 (org-eval-in-calendar '(calendar-backward-week 1))))
5009 (define-key minibuffer-local-map [(shift down)]
5010 (lambda () (interactive)
5011 (org-eval-in-calendar '(calendar-forward-week 1))))
5012 (define-key minibuffer-local-map [(shift left)]
5013 (lambda () (interactive)
5014 (org-eval-in-calendar '(calendar-backward-day 1))))
5015 (define-key minibuffer-local-map [(shift right)]
5016 (lambda () (interactive)
5017 (org-eval-in-calendar '(calendar-forward-day 1))))
5018 (define-key minibuffer-local-map ">"
5019 (lambda () (interactive)
5020 (org-eval-in-calendar '(scroll-calendar-left 1))))
5021 (define-key minibuffer-local-map "<"
5022 (lambda () (interactive)
5023 (org-eval-in-calendar '(scroll-calendar-right 1))))
5024 (unwind-protect
5025 (progn
5026 (use-local-map map)
5027 (setq ans (read-string prompt "" nil nil))
5028 (if (not (string-match "\\S-" ans)) (setq ans nil))
5029 (setq ans (or ans1 ans ans2)))
5030 (use-local-map old-map)))))
5031 ;; Naked prompt only
5032 (setq ans (read-string prompt "" nil timestr)))
5033 (org-detatch-overlay org-date-ovl)
5034
5035 (if (string-match
5036 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5037 (progn
5038 (setq year (if (match-end 2)
5039 (string-to-number (match-string 2 ans))
5040 (string-to-number (format-time-string "%Y")))
5041 month (string-to-number (match-string 3 ans))
5042 day (string-to-number (match-string 4 ans)))
5043 (if (< year 100) (setq year (+ 2000 year)))
5044 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
5045 t nil ans))))
5046 (setq tl (parse-time-string ans)
5047 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
5048 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
5049 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
5050 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
5051 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
5052 second (or (nth 0 tl) 0)
5053 wday (nth 6 tl))
5054 (when (and wday (not (nth 3 tl)))
5055 ;; Weekday was given, but no day, so pick that day in the week
5056 ;; on or after the derived date.
5057 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
5058 (unless (equal wday wday1)
5059 (setq day (+ day (% (- wday wday1 -7) 7)))))
5060 (if (and (boundp 'org-time-was-given)
5061 (nth 2 tl))
5062 (setq org-time-was-given t))
5063 (if (< year 100) (setq year (+ 2000 year)))
5064 (if to-time
5065 (encode-time second minute hour day month year)
5066 (if (or (nth 1 tl) (nth 2 tl))
5067 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
5068 (format "%04d-%02d-%02d" year month day)))))
5069
5070 (defun org-eval-in-calendar (form)
5071 "Eval FORM in the calendar window and return to current window.
5072 Also, store the cursor date in variable ans2."
5073 (let ((sw (selected-window)))
5074 (select-window (get-buffer-window "*Calendar*"))
5075 (eval form)
5076 (when (calendar-cursor-to-date)
5077 (let* ((date (calendar-cursor-to-date))
5078 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5079 (setq ans2 (format-time-string "%Y-%m-%d" time))))
5080 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
5081 (select-window sw)))
5082
5083 (defun org-calendar-select ()
5084 "Return to `org-read-date' with the date currently selected.
5085 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5086 (interactive)
5087 (when (calendar-cursor-to-date)
5088 (let* ((date (calendar-cursor-to-date))
5089 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5090 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5091 (if (active-minibuffer-window) (exit-minibuffer))))
5092
5093 (defun org-calendar-select-mouse (ev)
5094 "Return to `org-read-date' with the date currently selected.
5095 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5096 (interactive "e")
5097 (mouse-set-point ev)
5098 (when (calendar-cursor-to-date)
5099 (let* ((date (calendar-cursor-to-date))
5100 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5101 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5102 (if (active-minibuffer-window) (exit-minibuffer))))
5103
5104 (defun org-check-deadlines (ndays)
5105 "Check if there are any deadlines due or past due.
5106 A deadline is considered due if it happens within `org-deadline-warning-days'
5107 days from today's date. If the deadline appears in an entry marked DONE,
5108 it is not shown. The prefix arg NDAYS can be used to test that many
5109 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
5110 (interactive "P")
5111 (let* ((org-warn-days
5112 (cond
5113 ((equal ndays '(4)) 100000)
5114 (ndays (prefix-numeric-value ndays))
5115 (t org-deadline-warning-days)))
5116 (case-fold-search nil)
5117 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
5118 (callback
5119 (lambda ()
5120 (and (let ((d1 (time-to-days (current-time)))
5121 (d2 (time-to-days
5122 (org-time-string-to-time (match-string 1)))))
5123 (< (- d2 d1) org-warn-days))
5124 (not (org-entry-is-done-p))))))
5125 (message "%d deadlines past-due or due within %d days"
5126 (org-occur regexp callback)
5127 org-warn-days)))
5128
5129 (defun org-evaluate-time-range (&optional to-buffer)
5130 "Evaluate a time range by computing the difference between start and end.
5131 Normally the result is just printed in the echo area, but with prefix arg
5132 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
5133 If the time range is actually in a table, the result is inserted into the
5134 next column.
5135 For time difference computation, a year is assumed to be exactly 365
5136 days in order to avoid rounding problems."
5137 (interactive "P")
5138 (save-excursion
5139 (unless (org-at-date-range-p)
5140 (goto-char (point-at-bol))
5141 (re-search-forward org-tr-regexp (point-at-eol) t))
5142 (if (not (org-at-date-range-p))
5143 (error "Not at a time-stamp range, and none found in current line")))
5144 (let* ((ts1 (match-string 1))
5145 (ts2 (match-string 2))
5146 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
5147 (match-end (match-end 0))
5148 (time1 (org-time-string-to-time ts1))
5149 (time2 (org-time-string-to-time ts2))
5150 (t1 (time-to-seconds time1))
5151 (t2 (time-to-seconds time2))
5152 (diff (abs (- t2 t1)))
5153 (negative (< (- t2 t1) 0))
5154 ;; (ys (floor (* 365 24 60 60)))
5155 (ds (* 24 60 60))
5156 (hs (* 60 60))
5157 (fy "%dy %dd %02d:%02d")
5158 (fy1 "%dy %dd")
5159 (fd "%dd %02d:%02d")
5160 (fd1 "%dd")
5161 (fh "%02d:%02d")
5162 y d h m align)
5163 (if havetime
5164 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5165 y 0
5166 d (floor (/ diff ds)) diff (mod diff ds)
5167 h (floor (/ diff hs)) diff (mod diff hs)
5168 m (floor (/ diff 60)))
5169 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5170 y 0
5171 d (floor (+ (/ diff ds) 0.5))
5172 h 0 m 0))
5173 (if (not to-buffer)
5174 (message (org-make-tdiff-string y d h m))
5175 (when (org-at-table-p)
5176 (goto-char match-end)
5177 (setq align t)
5178 (and (looking-at " *|") (goto-char (match-end 0))))
5179 (if (looking-at
5180 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
5181 (replace-match ""))
5182 (if negative (insert " -"))
5183 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
5184 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
5185 (insert " " (format fh h m))))
5186 (if align (org-table-align))
5187 (message "Time difference inserted"))))
5188
5189 (defun org-make-tdiff-string (y d h m)
5190 (let ((fmt "")
5191 (l nil))
5192 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5193 l (push y l)))
5194 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5195 l (push d l)))
5196 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5197 l (push h l)))
5198 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5199 l (push m l)))
5200 (apply 'format fmt (nreverse l))))
5201
5202 (defun org-time-string-to-time (s)
5203 (apply 'encode-time (org-parse-time-string s)))
5204
5205 (defun org-parse-time-string (s &optional nodefault)
5206 "Parse the standard Org-mode time string.
5207 This should be a lot faster than the normal `parse-time-string'.
5208 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5209 hour and minute fields will be nil if not given."
5210 (if (string-match org-ts-regexp1 s)
5211 (list 0
5212 (if (or (match-beginning 8) (not nodefault))
5213 (string-to-number (or (match-string 8 s) "0")))
5214 (if (or (match-beginning 7) (not nodefault))
5215 (string-to-number (or (match-string 7 s) "0")))
5216 (string-to-number (match-string 4 s))
5217 (string-to-number (match-string 3 s))
5218 (string-to-number (match-string 2 s))
5219 nil nil nil)
5220 (make-list 9 0)))
5221
5222 (defun org-timestamp-up (&optional arg)
5223 "Increase the date item at the cursor by one.
5224 If the cursor is on the year, change the year. If it is on the month or
5225 the day, change that.
5226 With prefix ARG, change by that many units."
5227 (interactive "p")
5228 (org-timestamp-change (prefix-numeric-value arg)))
5229
5230 (defun org-timestamp-down (&optional arg)
5231 "Decrease the date item at the cursor by one.
5232 If the cursor is on the year, change the year. If it is on the month or
5233 the day, change that.
5234 With prefix ARG, change by that many units."
5235 (interactive "p")
5236 (org-timestamp-change (- (prefix-numeric-value arg))))
5237
5238 (defun org-timestamp-up-day (&optional arg)
5239 "Increase the date in the time stamp by one day.
5240 With prefix ARG, change that many days."
5241 (interactive "p")
5242 (if (and (not (org-at-timestamp-p))
5243 (org-on-heading-p))
5244 (org-todo 'up)
5245 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5246
5247 (defun org-timestamp-down-day (&optional arg)
5248 "Decrease the date in the time stamp by one day.
5249 With prefix ARG, change that many days."
5250 (interactive "p")
5251 (if (and (not (org-at-timestamp-p))
5252 (org-on-heading-p))
5253 (org-todo 'down)
5254 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5255
5256 (defsubst org-pos-in-match-range (pos n)
5257 (and (match-beginning n)
5258 (<= (match-beginning n) pos)
5259 (>= (match-end n) pos)))
5260
5261 (defun org-at-timestamp-p ()
5262 "Determine if the cursor is in or at a timestamp."
5263 (interactive)
5264 (let* ((tsr org-ts-regexp2)
5265 (pos (point))
5266 (ans (or (looking-at tsr)
5267 (save-excursion
5268 (skip-chars-backward "^<\n\r\t")
5269 (if (> (point) 1) (backward-char 1))
5270 (and (looking-at tsr)
5271 (> (- (match-end 0) pos) -1))))))
5272 (and (boundp 'org-ts-what)
5273 (setq org-ts-what
5274 (cond
5275 ((org-pos-in-match-range pos 2) 'year)
5276 ((org-pos-in-match-range pos 3) 'month)
5277 ((org-pos-in-match-range pos 7) 'hour)
5278 ((org-pos-in-match-range pos 8) 'minute)
5279 ((or (org-pos-in-match-range pos 4)
5280 (org-pos-in-match-range pos 5)) 'day)
5281 (t 'day))))
5282 ans))
5283
5284 (defun org-timestamp-change (n &optional what)
5285 "Change the date in the time stamp at point.
5286 The date will be changed by N times WHAT. WHAT can be `day', `month',
5287 `year', `minute', `second'. If WHAT is not given, the cursor position
5288 in the timestamp determines what will be changed."
5289 (let ((fmt (car org-time-stamp-formats))
5290 org-ts-what
5291 (pos (point))
5292 ts time time0)
5293 (if (not (org-at-timestamp-p))
5294 (error "Not at a timestamp"))
5295 (setq org-ts-what (or what org-ts-what))
5296 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5297 (- (match-end 0) (match-beginning 0))))
5298 1)
5299 (cdr org-time-stamp-formats)
5300 (car org-time-stamp-formats)))
5301 (setq ts (match-string 0))
5302 (replace-match "")
5303 (setq time0 (org-parse-time-string ts))
5304 (setq time
5305 (apply 'encode-time
5306 (append
5307 (list (or (car time0) 0))
5308 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5309 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5310 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5311 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5312 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5313 (nthcdr 6 time0))))
5314 (if (eq what 'calendar)
5315 (let ((cal-date
5316 (save-excursion
5317 (save-match-data
5318 (set-buffer "*Calendar*")
5319 (calendar-cursor-to-date)))))
5320 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5321 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5322 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5323 (setcar time0 (or (car time0) 0))
5324 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5325 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5326 (setq time (apply 'encode-time time0))))
5327 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5328 (goto-char pos)
5329 ;; Try to recenter the calendar window, if any
5330 (if (and org-calendar-follow-timestamp-change
5331 (get-buffer-window "*Calendar*" t)
5332 (memq org-ts-what '(day month year)))
5333 (org-recenter-calendar (time-to-days time)))))
5334
5335 (defun org-recenter-calendar (date)
5336 "If the calendar is visible, recenter it to DATE."
5337 (let* ((win (selected-window))
5338 (cwin (get-buffer-window "*Calendar*" t))
5339 (calendar-move-hook nil))
5340 (when cwin
5341 (select-window cwin)
5342 (calendar-goto-date (if (listp date) date
5343 (calendar-gregorian-from-absolute date)))
5344 (select-window win))))
5345
5346 (defun org-goto-calendar (&optional arg)
5347 "Go to the Emacs calendar at the current date.
5348 If there is a time stamp in the current line, go to that date.
5349 A prefix ARG can be used to force the current date."
5350 (interactive "P")
5351 (let ((tsr org-ts-regexp) diff
5352 (calendar-move-hook nil)
5353 (view-calendar-holidays-initially nil)
5354 (view-diary-entries-initially nil))
5355 (if (or (org-at-timestamp-p)
5356 (save-excursion
5357 (beginning-of-line 1)
5358 (looking-at (concat ".*" tsr))))
5359 (let ((d1 (time-to-days (current-time)))
5360 (d2 (time-to-days
5361 (org-time-string-to-time (match-string 1)))))
5362 (setq diff (- d2 d1))))
5363 (calendar)
5364 (calendar-goto-today)
5365 (if (and diff (not arg)) (calendar-forward-day diff))))
5366
5367 (defun org-date-from-calendar ()
5368 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
5369 If there is already a time stamp at the cursor position, update it."
5370 (interactive)
5371 (org-timestamp-change 0 'calendar))
5372
5373 ;;; The clock for measuring work time.
5374
5375 (defvar org-clock-marker (make-marker)
5376 "Marker recording the last clock-in.")
5377
5378 (defun org-clock-in ()
5379 "Start the clock on the current item.
5380 If necessary, clock-out of the currently active clock."
5381 (interactive)
5382 (org-clock-out t)
5383 (let (ts)
5384 (save-excursion
5385 (org-back-to-heading t)
5386 (beginning-of-line 2)
5387 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5388 (not (equal (match-string 1) org-clock-string)))
5389 (beginning-of-line 1))
5390 (insert "\n") (backward-char 1)
5391 (indent-relative)
5392 (insert org-clock-string " "
5393 (setq ts (concat "[" (format-time-string
5394 (substring
5395 (cdr org-time-stamp-formats) 1 -1)
5396 (current-time))
5397 "]")))
5398 (move-marker org-clock-marker (point))
5399 (message "Clock started at %s" ts))))
5400
5401 (defun org-clock-out (&optional fail-quietly)
5402 "Stop the currently running clock.
5403 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
5404 (interactive)
5405 (catch 'exit
5406 (if (not (marker-buffer org-clock-marker))
5407 (if fail-quietly (throw 'exit t) (error "No active clock")))
5408 (let (ts te s h m)
5409 (save-excursion
5410 (set-buffer (marker-buffer org-clock-marker))
5411 (goto-char org-clock-marker)
5412 (beginning-of-line 1)
5413 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5414 (equal (match-string 1) org-clock-string))
5415 (setq ts (match-string 2))
5416 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
5417 (goto-char org-clock-marker)
5418 (setq te (concat "[" (format-time-string
5419 (substring
5420 (cdr org-time-stamp-formats) 1 -1)
5421 (current-time))
5422 "]"))
5423 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
5424 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
5425 h (floor (/ s 3600))
5426 s (- s (* 3600 h))
5427 m (floor (/ s 60))
5428 s (- s (* 60 s)))
5429 (insert "--" te " => " (format "%2d:%02d" h m))
5430 (move-marker org-clock-marker nil)
5431 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
5432
5433 (defun org-clock-cancel ()
5434 "Cancel the running clock be removing the start timestamp."
5435 (interactive)
5436 (if (not (marker-buffer org-clock-marker))
5437 (error "No active clock"))
5438 (save-excursion
5439 (set-buffer (marker-buffer org-clock-marker))
5440 (goto-char org-clock-marker)
5441 (delete-region (1- (point-at-bol)) (point-at-eol)))
5442 (message "Clock canceled"))
5443
5444 (defvar org-clock-file-total-minutes nil
5445 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
5446 (make-variable-buffer-local 'org-clock-file-total-minutes)
5447
5448 (defun org-clock-sum ()
5449 "Sum the times for each subtree.
5450 Puts the resulting times in minutes as a text property on each headline."
5451 (interactive)
5452 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
5453 (let* ((re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
5454 org-clock-string
5455 ".*=>[ \t]*\\([0-9]+\\):\\([0-9]+\\)[ \t]*$"))
5456 (lmax 30)
5457 (ltimes (make-vector lmax 0))
5458 (t1 0)
5459 (level 0)
5460 (lastlevel 0) time)
5461 (save-excursion
5462 (goto-char (point-max))
5463 (while (re-search-backward re nil t)
5464 (if (match-end 2)
5465 ;; A time
5466 (setq t1 (+ t1 (* 60 (string-to-number (match-string 2)))
5467 (string-to-number (match-string 3))))
5468 ;; A headline
5469 (setq level (- (match-end 1) (match-beginning 1)))
5470 (when (or (> t1 0) (> (aref ltimes level) 0))
5471 (loop for l from 0 to level do
5472 (aset ltimes l (+ (aref ltimes l) t1)))
5473 (setq t1 0 time (aref ltimes level))
5474 (loop for l from level to (1- lmax) do
5475 (aset ltimes l 0))
5476 (goto-char (match-beginning 0))
5477 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
5478 (setq org-clock-file-total-minutes (aref ltimes 0)))))
5479
5480 (defun org-clock-display (&optional total-only)
5481 "Show subtree times in the entire buffer.
5482 If TOTAL-ONLY is non-nil, only show the total time for the entire file
5483 in the echo area."
5484 (interactive)
5485 (org-remove-clock-overlays)
5486 (let (time h m p)
5487 (org-clock-sum)
5488 (unless total-only
5489 (save-excursion
5490 (goto-char (point-min))
5491 (while (setq p (next-single-property-change (point) :org-clock-minutes))
5492 (goto-char p)
5493 (when (setq time (get-text-property p :org-clock-minutes))
5494 (org-put-clock-overlay time (funcall outline-level))))
5495 (setq h (/ org-clock-file-total-minutes 60)
5496 m (- org-clock-file-total-minutes (* 60 h)))
5497 ;; Arrange to remove the overlays upon next change.
5498 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
5499 nil 'local)))
5500 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
5501
5502 (defvar org-clock-overlays nil)
5503 (defun org-put-clock-overlay (time &optional level)
5504 "Put an overlays on the current line, displaying TIME.
5505 If LEVEL is given, prefix time with a corresponding number of stars.
5506 This creates a new overlay and stores it in `org-clock-overlays', so that it
5507 will be easy to remove."
5508 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
5509 (l (if level (org-get-legal-level level 0) 0))
5510 (off 0)
5511 ov tx)
5512 (move-to-column c)
5513 (if (eolp) (setq off 1))
5514 (unless (eolp) (skip-chars-backward "^ \t"))
5515 (skip-chars-backward " \t")
5516 (setq ov (org-make-overlay (- (point) off) (point-at-eol))
5517 tx (concat (make-string (+ off (max 0 (- c (current-column)))) ?.)
5518 (org-add-props (format "%s %2d:%02d%s"
5519 (make-string l ?*) h m
5520 (make-string (- 10 l) ?\ ))
5521 '(face secondary-selection))
5522 ""))
5523 (org-overlay-put ov 'display tx)
5524 (push ov org-clock-overlays)))
5525
5526 (defun org-remove-clock-overlays (&optional beg end noremove)
5527 "Remove the occur highlights from the buffer.
5528 BEG and END are ignored. If NOREMOVE is nil, remove this function
5529 from the `before-change-functions' in the current buffer."
5530 (interactive)
5531 (mapc 'org-delete-overlay org-clock-overlays)
5532 (setq org-clock-overlays nil)
5533 (unless noremove
5534 (remove-hook 'before-change-functions
5535 'org-remove-clock-overlays 'local)))
5536
5537 (defun org-clock-out-if-current ()
5538 "Clock out if the current entry contains the running clock.
5539 This is used to stop the clock after a TODO entry is marked DONE."
5540 (when (and (equal state org-done-string)
5541 (equal (marker-buffer org-clock-marker) (current-buffer))
5542 (< (point) org-clock-marker)
5543 (> (save-excursion (outline-next-heading) (point))
5544 org-clock-marker))
5545 (org-clock-out)))
5546
5547 (add-hook 'org-after-todo-state-change-hook
5548 'org-clock-out-if-current)
5549
5550 (defun org-check-running-clock ()
5551 "Check if the current buffer contains the running clock.
5552 If yes, offer to stop it and to save the buffer with the changes."
5553 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
5554 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
5555 (buffer-name))))
5556 (org-clock-out)
5557 (when (y-or-n-p "Save changed buffer?")
5558 (save-buffer))))
5559
5560 ;;; Agenda, and Diary Integration
5561
5562 ;;; Define the mode
5563
5564 (defvar org-agenda-mode-map (make-sparse-keymap)
5565 "Keymap for `org-agenda-mode'.")
5566
5567 (defvar org-agenda-menu) ; defined later in this file.
5568 (defvar org-agenda-follow-mode nil)
5569 (defvar org-agenda-show-log nil)
5570 (defvar org-agenda-buffer-name "*Org Agenda*")
5571 (defvar org-agenda-redo-command nil)
5572 (defvar org-agenda-mode-hook nil)
5573 (defvar org-agenda-type nil)
5574 (defvar org-agenda-force-single-file nil)
5575
5576 (defun org-agenda-mode ()
5577 "Mode for time-sorted view on action items in Org-mode files.
5578
5579 The following commands are available:
5580
5581 \\{org-agenda-mode-map}"
5582 (interactive)
5583 (kill-all-local-variables)
5584 (setq major-mode 'org-agenda-mode)
5585 (setq mode-name "Org-Agenda")
5586 (use-local-map org-agenda-mode-map)
5587 (easy-menu-add org-agenda-menu)
5588 (if org-startup-truncated (setq truncate-lines t))
5589 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
5590 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
5591 (unless org-agenda-keep-modes
5592 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
5593 org-agenda-show-log nil))
5594 (easy-menu-change
5595 '("Agenda") "Agenda Files"
5596 (append
5597 (list
5598 (vector
5599 (if (get 'org-agenda-files 'org-restrict)
5600 "Restricted to single file"
5601 "Edit File List")
5602 '(org-edit-agenda-file-list)
5603 (not (get 'org-agenda-files 'org-restrict)))
5604 "--")
5605 (mapcar 'org-file-menu-entry (org-agenda-files))))
5606 (org-agenda-set-mode-name)
5607 (apply
5608 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
5609 (list 'org-agenda-mode-hook)))
5610
5611 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
5612 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
5613 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
5614 (define-key org-agenda-mode-map " " 'org-agenda-show)
5615 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
5616 (define-key org-agenda-mode-map "o" 'delete-other-windows)
5617 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
5618 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
5619 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
5620 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
5621 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
5622 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
5623 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
5624 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
5625 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
5626 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
5627
5628 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
5629 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
5630 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
5631 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
5632 (while l (define-key org-agenda-mode-map
5633 (int-to-string (pop l)) 'digit-argument)))
5634
5635 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
5636 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
5637 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
5638 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
5639 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
5640 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
5641 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
5642 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
5643 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
5644 (define-key org-agenda-mode-map "n" 'next-line)
5645 (define-key org-agenda-mode-map "p" 'previous-line)
5646 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
5647 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
5648 (define-key org-agenda-mode-map "," 'org-agenda-priority)
5649 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
5650 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
5651 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
5652 (eval-after-load "calendar"
5653 '(define-key calendar-mode-map org-calendar-to-agenda-key
5654 'org-calendar-goto-agenda))
5655 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
5656 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
5657 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
5658 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
5659 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
5660 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
5661 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
5662 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
5663 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
5664 (define-key org-agenda-mode-map "O" 'org-clock-out)
5665 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
5666 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
5667 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
5668 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
5669 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
5670 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
5671 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
5672 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
5673 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
5674 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
5675 "Local keymap for agenda entries from Org-mode.")
5676
5677 (define-key org-agenda-keymap
5678 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
5679 (define-key org-agenda-keymap
5680 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
5681 (when org-agenda-mouse-1-follows-link
5682 (define-key org-agenda-keymap [follow-link] 'mouse-face))
5683 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
5684 '("Agenda"
5685 ("Agenda Files")
5686 "--"
5687 ["Show" org-agenda-show t]
5688 ["Go To (other window)" org-agenda-goto t]
5689 ["Go To (one window)" org-agenda-switch-to t]
5690 ["Follow Mode" org-agenda-follow-mode
5691 :style toggle :selected org-agenda-follow-mode :active t]
5692 "--"
5693 ["Cycle TODO" org-agenda-todo t]
5694 ("Tags"
5695 ["Show all Tags" org-agenda-show-tags t]
5696 ["Set Tags" org-agenda-set-tags t])
5697 ("Schedule"
5698 ["Schedule" org-agenda-schedule t]
5699 ["Set Deadline" org-agenda-deadline t]
5700 "--"
5701 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
5702 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
5703 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
5704 ("Priority"
5705 ["Set Priority" org-agenda-priority t]
5706 ["Increase Priority" org-agenda-priority-up t]
5707 ["Decrease Priority" org-agenda-priority-down t]
5708 ["Show Priority" org-agenda-show-priority t])
5709 "--"
5710 ;; ["New agenda command" org-agenda t]
5711 ["Rebuild buffer" org-agenda-redo t]
5712 "--"
5713 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
5714 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
5715 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
5716 "--"
5717 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
5718 :style radio :selected (equal org-agenda-ndays 1)]
5719 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
5720 :style radio :selected (equal org-agenda-ndays 7)]
5721 "--"
5722 ["Show Logbook entries" org-agenda-log-mode
5723 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
5724 ["Include Diary" org-agenda-toggle-diary
5725 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
5726 ["Use Time Grid" org-agenda-toggle-time-grid
5727 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
5728 "--"
5729 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
5730 ("Calendar Commands"
5731 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
5732 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
5733 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
5734 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
5735 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
5736 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
5737 "--"
5738 ["Quit" org-agenda-quit t]
5739 ["Exit and Release Buffers" org-agenda-exit t]
5740 ))
5741
5742 ;;;###autoload
5743 (defun org-agenda (arg)
5744 "Dispatch agenda commands to collect entries to the agenda buffer.
5745 Prompts for a character to select a command. Any prefix arg will be passed
5746 on to the selected command. The default selections are:
5747
5748 a Call `org-agenda' to display the agenda for the current day or week.
5749 t Call `org-todo-list' to display the global todo list.
5750 T Call `org-todo-list' to display the global todo list, select only
5751 entries with a specific TODO keyword (the user gets a prompt).
5752 m Call `org-tags-view' to display headlines with tags matching
5753 a condition (the user is prompted for the condition).
5754 M Like `m', but select only TODO entries, no ordinary headlines.
5755
5756 More commands can be added by configuring the variable
5757 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
5758 searches can be pre-defined in this way.
5759
5760 If the current buffer is in Org-mode and visiting a file, you can also
5761 first press `1' to indicate that the agenda should be temporarily (until the
5762 next use of \\[org-agenda]) restricted to the current file."
5763 (interactive "P")
5764 (catch 'exit
5765 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
5766 (bfn buffer-file-name)
5767 (custom org-agenda-custom-commands)
5768 c entry key type string)
5769 (put 'org-agenda-files 'org-restrict nil)
5770 (save-window-excursion
5771 (delete-other-windows)
5772 (switch-to-buffer-other-window " *Agenda Commands*")
5773 (erase-buffer)
5774 (insert
5775 "Press key for an agenda command:
5776 --------------------------------
5777 a Agenda for current week or day
5778 t List of all TODO entries T Entries with special TODO kwd
5779 m Match a TAGS query M Like m, but only TODO entries
5780 C Configure your own agenda commands")
5781 (while (setq entry (pop custom))
5782 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
5783 (insert (format "\n%-4s%-14s: %s"
5784 key
5785 (cond
5786 ((eq type 'tags) "Tags query")
5787 ((eq type 'todo) "TODO keyword")
5788 ((eq type 'tags-tree) "Tags tree")
5789 ((eq type 'todo-tree) "TODO kwd tree")
5790 ((eq type 'occur-tree) "Occur tree")
5791 (t "???"))
5792 (org-add-props string nil 'face 'org-warning))))
5793 (goto-char (point-min))
5794 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
5795 (message "Press key for agenda command%s"
5796 (if restrict-ok ", or [1] to restrict to current file" ""))
5797 (setq c (read-char-exclusive))
5798 (message "")
5799 (when (equal c ?1)
5800 (if restrict-ok
5801 (put 'org-agenda-files 'org-restrict (list bfn))
5802 (error "Cannot restrict agenda to current buffer"))
5803 (message "Press key for agenda command%s"
5804 (if restrict-ok " (restricted to current file)" ""))
5805 (setq c (read-char-exclusive))
5806 (message "")))
5807 (require 'calendar) ; FIXME: can we avoid this for some commands?
5808 ;; For example the todo list should not need it (but does...)
5809 (cond
5810 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
5811 ((equal c ?a) (call-interactively 'org-agenda-list))
5812 ((equal c ?t) (call-interactively 'org-todo-list))
5813 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
5814 ((equal c ?m) (call-interactively 'org-tags-view))
5815 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
5816 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
5817 (setq type (nth 1 entry) string (nth 2 entry))
5818 (cond
5819 ((eq type 'tags)
5820 (org-tags-view current-prefix-arg string))
5821 ((eq type 'tags-todo)
5822 (org-tags-view '(4) string))
5823 ((eq type 'todo)
5824 (org-todo-list string))
5825 ((eq type 'tags-tree)
5826 (org-check-for-org-mode)
5827 (org-tags-sparse-tree current-prefix-arg string))
5828 ((eq type 'todo-tree)
5829 (org-check-for-org-mode)
5830 (org-occur (concat "^" outline-regexp "[ \t]*"
5831 (regexp-quote string) "\\>")))
5832 ((eq type 'occur-tree)
5833 (org-check-for-org-mode)
5834 (org-occur string))
5835 (t (error "Invalid custom agenda command type %s" type))))
5836 (t (error "Invalid key"))))))
5837
5838 (defun org-check-for-org-mode ()
5839 "Make sure current buffer is in org-mode. Error if not."
5840 (or (eq major-mode 'org-mode)
5841 (error "Cannot execute org-mode agenda command on buffer in %s."
5842 major-mode)))
5843
5844 (defun org-fit-agenda-window ()
5845 "Fit the window to the buffer size."
5846 (and org-fit-agenda-window
5847 (fboundp 'fit-window-to-buffer)
5848 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
5849 (/ (frame-height) 2))))
5850
5851 (defun org-agenda-files (&optional unrestricted)
5852 "Get the list of agenda files.
5853 Optional UNRESTRICTED means return the full list even if a restriction
5854 is currently in place."
5855 (cond
5856 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
5857 ((stringp org-agenda-files) (org-read-agenda-file-list))
5858 ((listp org-agenda-files) org-agenda-files)
5859 (t (error "Invalid value of `org-agenda-files'"))))
5860
5861 (defvar org-window-configuration)
5862
5863 (defun org-edit-agenda-file-list ()
5864 "Edit the list of agenda files.
5865 Depending on setup, this either uses customize to edit the variable
5866 `org-agenda-files', or it visits the file that is holding the list. In the
5867 latter case, the buffer is set up in a way that saving it automatically kills
5868 the buffer and restores the previous window configuration."
5869 (interactive)
5870 (if (stringp org-agenda-files)
5871 (let ((cw (current-window-configuration)))
5872 (find-file org-agenda-files)
5873 (set (make-local-variable 'org-window-configuration) cw)
5874 (org-add-hook 'after-save-hook
5875 (lambda ()
5876 (set-window-configuration
5877 (prog1 org-window-configuration
5878 (kill-buffer (current-buffer))))
5879 (org-install-agenda-files-menu)
5880 (message "New agenda file list installed"))
5881 nil 'local)
5882 (message (substitute-command-keys
5883 "Edit list and finish with \\[save-buffer]")))
5884 (customize-variable 'org-agenda-files)))
5885
5886 (defun org-store-new-agenda-file-list (list)
5887 "Set new value for the agenda file list and save it correcly."
5888 (if (stringp org-agenda-files)
5889 (let ((f org-agenda-files) b)
5890 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
5891 (with-temp-file f
5892 (insert (mapconcat 'identity list "\n") "\n")))
5893 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5894 (setq org-agenda-files list)
5895 (customize-save-variable 'org-agenda-files org-agenda-files))))
5896
5897 (defun org-read-agenda-file-list ()
5898 "Read the list of agenda files from a file."
5899 (when (stringp org-agenda-files)
5900 (with-temp-buffer
5901 (insert-file-contents org-agenda-files)
5902 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
5903
5904 (defvar org-agenda-markers nil
5905 "List of all currently active markers created by `org-agenda'.")
5906 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
5907 "Creation time of the last agenda marker.")
5908
5909 (defun org-agenda-new-marker (&optional pos)
5910 "Return a new agenda marker.
5911 Org-mode keeps a list of these markers and resets them when they are
5912 no longer in use."
5913 (let ((m (copy-marker (or pos (point)))))
5914 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
5915 (push m org-agenda-markers)
5916 m))
5917
5918 (defun org-agenda-maybe-reset-markers (&optional force)
5919 "Reset markers created by `org-agenda'. But only if they are old enough."
5920 (if (or force
5921 (> (- (time-to-seconds (current-time))
5922 org-agenda-last-marker-time)
5923 5))
5924 (while org-agenda-markers
5925 (move-marker (pop org-agenda-markers) nil))))
5926
5927 (defvar org-agenda-new-buffers nil
5928 "Buffers created to visit agenda files.")
5929
5930 (defun org-get-agenda-file-buffer (file)
5931 "Get a buffer visiting FILE. If the buffer needs to be created, add
5932 it to the list of buffers which might be released later."
5933 (let ((buf (find-buffer-visiting file)))
5934 (if buf
5935 buf ; just return it
5936 ;; Make a new buffer and remember it
5937 (setq buf (find-file-noselect file))
5938 (if buf (push buf org-agenda-new-buffers))
5939 buf)))
5940
5941 (defun org-release-buffers (blist)
5942 "Release all buffers in list, asking the user for confirmation when needed.
5943 When a buffer is unmodified, it is just killed. When modified, it is saved
5944 \(if the user agrees) and then killed."
5945 (let (buf file)
5946 (while (setq buf (pop blist))
5947 (setq file (buffer-file-name buf))
5948 (when (and (buffer-modified-p buf)
5949 file
5950 (y-or-n-p (format "Save file %s? " file)))
5951 (with-current-buffer buf (save-buffer)))
5952 (kill-buffer buf))))
5953
5954 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
5955
5956 (defun org-timeline (&optional include-all keep-modes)
5957 "Show a time-sorted view of the entries in the current org file.
5958 Only entries with a time stamp of today or later will be listed. With
5959 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
5960 under the current date.
5961 If the buffer contains an active region, only check the region for
5962 dates."
5963 (interactive "P")
5964 (require 'calendar)
5965 (org-agenda-maybe-reset-markers 'force)
5966 (org-compile-prefix-format org-timeline-prefix-format)
5967 (let* ((dopast t)
5968 (dotodo include-all)
5969 (doclosed org-agenda-show-log)
5970 (org-agenda-keep-modes keep-modes)
5971 (entry buffer-file-name)
5972 (org-agenda-files (list buffer-file-name))
5973 (date (calendar-current-date))
5974 (win (selected-window))
5975 (pos1 (point))
5976 (beg (if (org-region-active-p) (region-beginning) (point-min)))
5977 (end (if (org-region-active-p) (region-end) (point-max)))
5978 (day-numbers (org-get-all-dates beg end 'no-ranges
5979 t doclosed ; always include today
5980 org-timeline-show-empty-dates))
5981 (today (time-to-days (current-time)))
5982 (org-respect-restriction t)
5983 (past t)
5984 args
5985 s e rtn d emptyp)
5986 (setq org-agenda-redo-command
5987 (list 'progn
5988 (list 'switch-to-buffer-other-window (current-buffer))
5989 (list 'org-timeline (list 'quote include-all) t)))
5990 (if (not dopast)
5991 ;; Remove past dates from the list of dates.
5992 (setq day-numbers (delq nil (mapcar (lambda(x)
5993 (if (>= x today) x nil))
5994 day-numbers))))
5995 (switch-to-buffer-other-window
5996 (get-buffer-create org-agenda-buffer-name))
5997 (setq buffer-read-only nil)
5998 (erase-buffer)
5999 (org-agenda-mode) (setq buffer-read-only nil)
6000 (set (make-local-variable 'org-agenda-type) 'timeline)
6001 (if doclosed (push :closed args))
6002 (push :timestamp args)
6003 (if dotodo (push :todo args))
6004 (while (setq d (pop day-numbers))
6005 (if (and (listp d) (eq (car d) :omitted))
6006 (progn
6007 (setq s (point))
6008 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
6009 (put-text-property s (1- (point)) 'face 'org-level-3))
6010 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
6011 (if (and (>= d today)
6012 dopast
6013 past)
6014 (progn
6015 (setq past nil)
6016 (insert (make-string 79 ?-) "\n")))
6017 (setq date (calendar-gregorian-from-absolute d))
6018 (setq s (point))
6019 (setq rtn (and (not emptyp)
6020 (apply 'org-agenda-get-day-entries
6021 entry date args)))
6022 (if (or rtn (equal d today) org-timeline-show-empty-dates)
6023 (progn
6024 (insert (calendar-day-name date) " "
6025 (number-to-string (extract-calendar-day date)) " "
6026 (calendar-month-name (extract-calendar-month date)) " "
6027 (number-to-string (extract-calendar-year date)) "\n")
6028 (put-text-property s (1- (point)) 'face
6029 'org-level-3)
6030 (if (equal d today)
6031 (put-text-property s (1- (point)) 'org-today t))
6032 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
6033 (put-text-property s (1- (point)) 'day d)))))
6034 (goto-char (point-min))
6035 (setq buffer-read-only t)
6036 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6037 (point-min)))
6038 (when (not org-select-timeline-window)
6039 (select-window win)
6040 (goto-char pos1))))
6041
6042 ;;;###autoload
6043 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
6044 "Produce a weekly view from all files in variable `org-agenda-files'.
6045 The view will be for the current week, but from the overview buffer you
6046 will be able to go to other weeks.
6047 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
6048 also be shown, under the current date.
6049 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
6050 on the days are also shown. See the variable `org-log-done' for how
6051 to turn on logging.
6052 START-DAY defaults to TODAY, or to the most recent match for the weekday
6053 given in `org-agenda-start-on-weekday'.
6054 NDAYS defaults to `org-agenda-ndays'."
6055 (interactive "P")
6056 (org-agenda-maybe-reset-markers 'force)
6057 (org-compile-prefix-format org-agenda-prefix-format)
6058 (require 'calendar)
6059 (let* ((org-agenda-start-on-weekday
6060 (if (or (equal ndays 1)
6061 (and (null ndays) (equal 1 org-agenda-ndays)))
6062 nil org-agenda-start-on-weekday))
6063 (org-agenda-keep-modes keep-modes)
6064 (thefiles (org-agenda-files))
6065 (files thefiles)
6066 (win (selected-window))
6067 (today (time-to-days (current-time)))
6068 (sd (or start-day today))
6069 (start (if (or (null org-agenda-start-on-weekday)
6070 (< org-agenda-ndays 7))
6071 sd
6072 (let* ((nt (calendar-day-of-week
6073 (calendar-gregorian-from-absolute sd)))
6074 (n1 org-agenda-start-on-weekday)
6075 (d (- nt n1)))
6076 (- sd (+ (if (< d 0) 7 0) d)))))
6077 (day-numbers (list start))
6078 (inhibit-redisplay t)
6079 s e rtn rtnall file date d start-pos end-pos todayp nd)
6080 (setq org-agenda-redo-command
6081 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
6082 ;; Make the list of days
6083 (setq ndays (or ndays org-agenda-ndays)
6084 nd ndays)
6085 (while (> ndays 1)
6086 (push (1+ (car day-numbers)) day-numbers)
6087 (setq ndays (1- ndays)))
6088 (setq day-numbers (nreverse day-numbers))
6089 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6090 (progn
6091 (delete-other-windows)
6092 (switch-to-buffer-other-window
6093 (get-buffer-create org-agenda-buffer-name))))
6094 (setq buffer-read-only nil)
6095 (erase-buffer)
6096 (org-agenda-mode) (setq buffer-read-only nil)
6097 (set (make-local-variable 'org-agenda-type) 'agenda)
6098 (set (make-local-variable 'starting-day) (car day-numbers))
6099 (set (make-local-variable 'include-all-loc) include-all)
6100 (when (and (or include-all org-agenda-include-all-todo)
6101 (member today day-numbers))
6102 (setq files thefiles
6103 rtnall nil)
6104 (while (setq file (pop files))
6105 (catch 'nextfile
6106 (org-check-agenda-file file)
6107 (setq date (calendar-gregorian-from-absolute today)
6108 rtn (org-agenda-get-day-entries
6109 file date :todo))
6110 (setq rtnall (append rtnall rtn))))
6111 (when rtnall
6112 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
6113 (add-text-properties (point-min) (1- (point))
6114 (list 'face 'org-level-3))
6115 (insert (org-finalize-agenda-entries rtnall) "\n")))
6116 (while (setq d (pop day-numbers))
6117 (setq date (calendar-gregorian-from-absolute d)
6118 s (point))
6119 (if (or (setq todayp (= d today))
6120 (and (not start-pos) (= d sd)))
6121 (setq start-pos (point))
6122 (if (and start-pos (not end-pos))
6123 (setq end-pos (point))))
6124 (setq files thefiles
6125 rtnall nil)
6126 (while (setq file (pop files))
6127 (catch 'nextfile
6128 (org-check-agenda-file file)
6129 (if org-agenda-show-log
6130 (setq rtn (org-agenda-get-day-entries
6131 file date
6132 :deadline :scheduled :timestamp :closed))
6133 (setq rtn (org-agenda-get-day-entries
6134 file date
6135 :deadline :scheduled :timestamp)))
6136 (setq rtnall (append rtnall rtn))))
6137 (if org-agenda-include-diary
6138 (progn
6139 (require 'diary-lib)
6140 (setq rtn (org-get-entries-from-diary date))
6141 (setq rtnall (append rtnall rtn))))
6142 (if (or rtnall org-agenda-show-all-dates)
6143 (progn
6144 (insert (format "%-9s %2d %s %4d\n"
6145 (calendar-day-name date)
6146 (extract-calendar-day date)
6147 (calendar-month-name (extract-calendar-month date))
6148 (extract-calendar-year date)))
6149 (put-text-property s (1- (point)) 'face
6150 'org-level-3)
6151 (if rtnall (insert
6152 (org-finalize-agenda-entries
6153 (org-agenda-add-time-grid-maybe
6154 rtnall nd todayp))
6155 "\n"))
6156 (put-text-property s (1- (point)) 'day d))))
6157 (goto-char (point-min))
6158 (setq buffer-read-only t)
6159 (org-fit-agenda-window)
6160 (unless (and (pos-visible-in-window-p (point-min))
6161 (pos-visible-in-window-p (point-max)))
6162 (goto-char (1- (point-max)))
6163 (recenter -1)
6164 (if (not (pos-visible-in-window-p (or start-pos 1)))
6165 (progn
6166 (goto-char (or start-pos 1))
6167 (recenter 1))))
6168 (goto-char (or start-pos 1))
6169 (if (not org-select-agenda-window) (select-window win))
6170 (message "")))
6171
6172 (defvar org-select-this-todo-keyword nil)
6173
6174 ;;;###autoload
6175 (defun org-todo-list (arg &optional keep-modes)
6176 "Show all TODO entries from all agenda file in a single list.
6177 The prefix arg can be used to select a specific TODO keyword and limit
6178 the list to these. When using \\[universal-argument], you will be prompted
6179 for a keyword. A numeric prefix directly selects the Nth keyword in
6180 `org-todo-keywords'."
6181 (interactive "P")
6182 (org-agenda-maybe-reset-markers 'force)
6183 (org-compile-prefix-format org-agenda-prefix-format)
6184 (let* ((org-agenda-keep-modes keep-modes)
6185 (today (time-to-days (current-time)))
6186 (date (calendar-gregorian-from-absolute today))
6187 (win (selected-window))
6188 (kwds org-todo-keywords)
6189 (completion-ignore-case t)
6190 (org-select-this-todo-keyword
6191 (if (stringp arg) arg
6192 (and arg (integerp arg) (> arg 0)
6193 (nth (1- arg) org-todo-keywords))))
6194 rtn rtnall files file pos)
6195 (when (equal arg '(4))
6196 (setq org-select-this-todo-keyword
6197 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
6198 nil t)))
6199 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
6200 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6201 (progn
6202 (delete-other-windows)
6203 (switch-to-buffer-other-window
6204 (get-buffer-create org-agenda-buffer-name))))
6205 (setq buffer-read-only nil)
6206 (erase-buffer)
6207 (org-agenda-mode) (setq buffer-read-only nil)
6208 (set (make-local-variable 'org-agenda-type) 'todo)
6209 (set (make-local-variable 'last-arg) arg)
6210 (set (make-local-variable 'org-todo-keywords) kwds)
6211 (set (make-local-variable 'org-agenda-redo-command)
6212 '(org-todo-list (or current-prefix-arg last-arg) t))
6213 (setq files (org-agenda-files)
6214 rtnall nil)
6215 (while (setq file (pop files))
6216 (catch 'nextfile
6217 (org-check-agenda-file file)
6218 (setq rtn (org-agenda-get-day-entries file date :todo))
6219 (setq rtnall (append rtnall rtn))))
6220 (insert "Global list of TODO items of type: ")
6221 (add-text-properties (point-min) (1- (point))
6222 (list 'face 'org-level-3))
6223 (setq pos (point))
6224 (insert (or org-select-this-todo-keyword "ALL") "\n")
6225 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6226 (setq pos (point))
6227 (insert
6228 "Available with `N r': (0)ALL "
6229 (let ((n 0))
6230 (mapconcat (lambda (x)
6231 (format "(%d)%s" (setq n (1+ n)) x))
6232 org-todo-keywords " "))
6233 "\n")
6234 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
6235 (when rtnall
6236 (insert (org-finalize-agenda-entries rtnall) "\n"))
6237 (goto-char (point-min))
6238 (setq buffer-read-only t)
6239 (org-fit-agenda-window)
6240 (if (not org-select-agenda-window) (select-window win))))
6241
6242 (defun org-check-agenda-file (file)
6243 "Make sure FILE exists. If not, ask user what to do."
6244 (when (not (file-exists-p file))
6245 (message "non-existent file %s. [R]emove from list or [A]bort?"
6246 (abbreviate-file-name file))
6247 (let ((r (downcase (read-char-exclusive))))
6248 (cond
6249 ((equal r ?r)
6250 (org-remove-file file)
6251 (throw 'nextfile t))
6252 (t (error "Abort"))))))
6253
6254 (defun org-agenda-check-type (error &rest types)
6255 "Check if agenda buffer is of allowed type.
6256 If ERROR is non-nil, throw an error, otherwise just return nil."
6257 (if (memq org-agenda-type types)
6258 t
6259 (if error
6260 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
6261 nil)))
6262
6263 (defun org-agenda-quit ()
6264 "Exit agenda by removing the window or the buffer."
6265 (interactive)
6266 (let ((buf (current-buffer)))
6267 (if (not (one-window-p)) (delete-window))
6268 (kill-buffer buf)
6269 (org-agenda-maybe-reset-markers 'force)))
6270
6271 (defun org-agenda-exit ()
6272 "Exit agenda by removing the window or the buffer.
6273 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
6274 Org-mode buffers visited directly by the user will not be touched."
6275 (interactive)
6276 (org-release-buffers org-agenda-new-buffers)
6277 (setq org-agenda-new-buffers nil)
6278 (org-agenda-quit))
6279
6280 (defun org-agenda-redo ()
6281 "Rebuild Agenda.
6282 When this is the global TODO list, a prefix argument will be interpreted."
6283 (interactive)
6284 (message "Rebuilding agenda buffer...")
6285 (eval org-agenda-redo-command)
6286 (message "Rebuilding agenda buffer...done"))
6287
6288 (defun org-agenda-goto-today ()
6289 "Go to today."
6290 (interactive)
6291 (org-agenda-check-type t 'timeline 'agenda)
6292 (if (boundp 'starting-day)
6293 (let ((cmd (car org-agenda-redo-command))
6294 (iall (nth 1 org-agenda-redo-command))
6295 (nday (nth 3 org-agenda-redo-command))
6296 (keep (nth 4 org-agenda-redo-command)))
6297 (eval (list cmd iall nil nday keep)))
6298 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6299 (point-min)))))
6300
6301 (defun org-agenda-later (arg)
6302 "Go forward in time by `org-agenda-ndays' days.
6303 With prefix ARG, go forward that many times `org-agenda-ndays'."
6304 (interactive "p")
6305 (org-agenda-check-type t 'agenda)
6306 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6307 (+ starting-day (* arg org-agenda-ndays)) nil t))
6308
6309 (defun org-agenda-earlier (arg)
6310 "Go back in time by `org-agenda-ndays' days.
6311 With prefix ARG, go back that many times `org-agenda-ndays'."
6312 (interactive "p")
6313 (org-agenda-check-type t 'agenda)
6314 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6315 (- starting-day (* arg org-agenda-ndays)) nil t))
6316
6317 (defun org-agenda-week-view ()
6318 "Switch to weekly view for agenda."
6319 (interactive)
6320 (org-agenda-check-type t 'agenda)
6321 (setq org-agenda-ndays 7)
6322 (org-agenda-list include-all-loc
6323 (or (get-text-property (point) 'day)
6324 starting-day)
6325 nil t)
6326 (org-agenda-set-mode-name)
6327 (message "Switched to week view"))
6328
6329 (defun org-agenda-day-view ()
6330 "Switch to daily view for agenda."
6331 (interactive)
6332 (org-agenda-check-type t 'agenda)
6333 (setq org-agenda-ndays 1)
6334 (org-agenda-list include-all-loc
6335 (or (get-text-property (point) 'day)
6336 starting-day)
6337 nil t)
6338 (org-agenda-set-mode-name)
6339 (message "Switched to day view"))
6340
6341 (defun org-agenda-next-date-line (&optional arg)
6342 "Jump to the next line indicating a date in agenda buffer."
6343 (interactive "p")
6344 (org-agenda-check-type t 'agenda 'timeline)
6345 (beginning-of-line 1)
6346 (if (looking-at "^\\S-") (forward-char 1))
6347 (if (not (re-search-forward "^\\S-" nil t arg))
6348 (progn
6349 (backward-char 1)
6350 (error "No next date after this line in this buffer")))
6351 (goto-char (match-beginning 0)))
6352
6353 (defun org-agenda-previous-date-line (&optional arg)
6354 "Jump to the previous line indicating a date in agenda buffer."
6355 (interactive "p")
6356 (org-agenda-check-type t 'agenda 'timeline)
6357 (beginning-of-line 1)
6358 (if (not (re-search-backward "^\\S-" nil t arg))
6359 (error "No previous date before this line in this buffer")))
6360
6361 ;; Initialize the highlight
6362 (defvar org-hl (org-make-overlay 1 1))
6363 (org-overlay-put org-hl 'face 'highlight)
6364
6365 (defun org-highlight (begin end &optional buffer)
6366 "Highlight a region with overlay."
6367 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
6368 org-hl begin end (or buffer (current-buffer))))
6369
6370 (defun org-unhighlight ()
6371 "Detach overlay INDEX."
6372 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
6373
6374
6375 (defun org-agenda-follow-mode ()
6376 "Toggle follow mode in an agenda buffer."
6377 (interactive)
6378 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
6379 (org-agenda-set-mode-name)
6380 (message "Follow mode is %s"
6381 (if org-agenda-follow-mode "on" "off")))
6382
6383 (defun org-agenda-log-mode ()
6384 "Toggle log mode in an agenda buffer."
6385 (interactive)
6386 (org-agenda-check-type t 'agenda 'timeline)
6387 (setq org-agenda-show-log (not org-agenda-show-log))
6388 (org-agenda-set-mode-name)
6389 (org-agenda-redo)
6390 (message "Log mode is %s"
6391 (if org-agenda-show-log "on" "off")))
6392
6393 (defun org-agenda-toggle-diary ()
6394 "Toggle diary inclusion in an agenda buffer."
6395 (interactive)
6396 (org-agenda-check-type t 'agenda)
6397 (setq org-agenda-include-diary (not org-agenda-include-diary))
6398 (org-agenda-redo)
6399 (org-agenda-set-mode-name)
6400 (message "Diary inclusion turned %s"
6401 (if org-agenda-include-diary "on" "off")))
6402
6403 (defun org-agenda-toggle-time-grid ()
6404 "Toggle time grid in an agenda buffer."
6405 (interactive)
6406 (org-agenda-check-type t 'agenda)
6407 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
6408 (org-agenda-redo)
6409 (org-agenda-set-mode-name)
6410 (message "Time-grid turned %s"
6411 (if org-agenda-use-time-grid "on" "off")))
6412
6413 (defun org-agenda-set-mode-name ()
6414 "Set the mode name to indicate all the small mode settings."
6415 (setq mode-name
6416 (concat "Org-Agenda"
6417 (if (equal org-agenda-ndays 1) " Day" "")
6418 (if (equal org-agenda-ndays 7) " Week" "")
6419 (if org-agenda-follow-mode " Follow" "")
6420 (if org-agenda-include-diary " Diary" "")
6421 (if org-agenda-use-time-grid " Grid" "")
6422 (if org-agenda-show-log " Log" "")))
6423 (force-mode-line-update))
6424
6425 (defun org-agenda-post-command-hook ()
6426 (and (eolp) (not (bolp)) (backward-char 1))
6427 (if (and org-agenda-follow-mode
6428 (get-text-property (point) 'org-marker))
6429 (org-agenda-show)))
6430
6431 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
6432
6433 (defun org-get-entries-from-diary (date)
6434 "Get the (Emacs Calendar) diary entries for DATE."
6435 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
6436 (diary-display-hook '(fancy-diary-display))
6437 (list-diary-entries-hook
6438 (cons 'org-diary-default-entry list-diary-entries-hook))
6439 (diary-file-name-prefix-function nil) ; turn this feature off
6440 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
6441 entries
6442 (org-disable-agenda-to-diary t))
6443 (save-excursion
6444 (save-window-excursion
6445 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
6446 (if (not (get-buffer fancy-diary-buffer))
6447 (setq entries nil)
6448 (with-current-buffer fancy-diary-buffer
6449 (setq buffer-read-only nil)
6450 (if (= (point-max) 1)
6451 ;; No entries
6452 (setq entries nil)
6453 ;; Omit the date and other unnecessary stuff
6454 (org-agenda-cleanup-fancy-diary)
6455 ;; Add prefix to each line and extend the text properties
6456 (if (= (point-max) 1)
6457 (setq entries nil)
6458 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
6459 (set-buffer-modified-p nil)
6460 (kill-buffer fancy-diary-buffer)))
6461 (when entries
6462 (setq entries (org-split-string entries "\n"))
6463 (setq entries
6464 (mapcar
6465 (lambda (x)
6466 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
6467 ;; Extend the text properties to the beginning of the line
6468 (org-add-props x (text-properties-at (1- (length x)) x)))
6469 entries)))))
6470
6471 (defun org-agenda-cleanup-fancy-diary ()
6472 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
6473 This gets rid of the date, the underline under the date, and
6474 the dummy entry installed by `org-mode' to ensure non-empty diary for each
6475 date. It also removes lines that contain only whitespace."
6476 (goto-char (point-min))
6477 (if (looking-at ".*?:[ \t]*")
6478 (progn
6479 (replace-match "")
6480 (re-search-forward "\n=+$" nil t)
6481 (replace-match "")
6482 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
6483 (re-search-forward "\n=+$" nil t)
6484 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
6485 (goto-char (point-min))
6486 (while (re-search-forward "^ +\n" nil t)
6487 (replace-match ""))
6488 (goto-char (point-min))
6489 (if (re-search-forward "^Org-mode dummy\n?" nil t)
6490 (replace-match "")))
6491
6492 ;; Make sure entries from the diary have the right text properties.
6493 (eval-after-load "diary-lib"
6494 '(if (boundp 'diary-modify-entry-list-string-function)
6495 ;; We can rely on the hook, nothing to do
6496 nil
6497 ;; Hook not avaiable, must use advice to make this work
6498 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
6499 "Make the position visible."
6500 (if (and org-disable-agenda-to-diary ;; called from org-agenda
6501 (stringp string)
6502 buffer-file-name)
6503 (setq string (org-modify-diary-entry-string string))))))
6504
6505 (defun org-modify-diary-entry-string (string)
6506 "Add text properties to string, allowing org-mode to act on it."
6507 (org-add-props string nil
6508 'mouse-face 'highlight
6509 'keymap org-agenda-keymap
6510 'help-echo (format "mouse-2 or RET jump to diary file %s"
6511 (abbreviate-file-name buffer-file-name))
6512 'org-agenda-diary-link t
6513 'org-marker (org-agenda-new-marker (point-at-bol))))
6514
6515 (defun org-diary-default-entry ()
6516 "Add a dummy entry to the diary.
6517 Needed to avoid empty dates which mess up holiday display."
6518 ;; Catch the error if dealing with the new add-to-diary-alist
6519 (when org-disable-agenda-to-diary
6520 (condition-case nil
6521 (add-to-diary-list original-date "Org-mode dummy" "")
6522 (error
6523 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
6524
6525 (defun org-cycle-agenda-files ()
6526 "Cycle through the files in `org-agenda-files'.
6527 If the current buffer visits an agenda file, find the next one in the list.
6528 If the current buffer does not, find the first agenda file."
6529 (interactive)
6530 (let* ((fs (org-agenda-files t))
6531 (files (append fs (list (car fs))))
6532 (tcf (if buffer-file-name (file-truename buffer-file-name)))
6533 file)
6534 (unless files (error "No agenda files"))
6535 (catch 'exit
6536 (while (setq file (pop files))
6537 (if (equal (file-truename file) tcf)
6538 (when (car files)
6539 (find-file (car files))
6540 (throw 'exit t))))
6541 (find-file (car fs)))))
6542
6543 (defun org-agenda-file-to-end ()
6544 "Move/add the current file to the end of the agenda file list.
6545 If the file is not present in the list, it is appended to the list. If it is
6546 present, it is moved there."
6547 (interactive)
6548 (org-agenda-file-to-front 'to-end))
6549
6550 (defun org-agenda-file-to-front (&optional to-end)
6551 "Move/add the current file to the top of the agenda file list.
6552 If the file is not present in the list, it is added to the front. If it is
6553 present, it is moved there. With optional argument TO-END, add/move to the
6554 end of the list."
6555 (interactive "P")
6556 (let ((file-alist (mapcar (lambda (x)
6557 (cons (file-truename x) x))
6558 (org-agenda-files t)))
6559 (ctf (file-truename buffer-file-name))
6560 x had)
6561 (setq x (assoc ctf file-alist) had x)
6562
6563 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
6564 (if to-end
6565 (setq file-alist (append (delq x file-alist) (list x)))
6566 (setq file-alist (cons x (delq x file-alist))))
6567 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
6568 (org-install-agenda-files-menu)
6569 (message "File %s to %s of agenda file list"
6570 (if had "moved" "added") (if to-end "end" "front"))))
6571
6572 (defun org-remove-file (&optional file)
6573 "Remove current file from the list of files in variable `org-agenda-files'.
6574 These are the files which are being checked for agenda entries.
6575 Optional argument FILE means, use this file instead of the current."
6576 (interactive)
6577 (let* ((file (or file buffer-file-name))
6578 (true-file (file-truename file))
6579 (afile (abbreviate-file-name file))
6580 (files (delq nil (mapcar
6581 (lambda (x)
6582 (if (equal true-file
6583 (file-truename x))
6584 nil x))
6585 (org-agenda-files t)))))
6586 (if (not (= (length files) (length (org-agenda-files t))))
6587 (progn
6588 (org-store-new-agenda-file-list files)
6589 (org-install-agenda-files-menu)
6590 (message "Removed file: %s" afile))
6591 (message "File was not in list: %s" afile))))
6592
6593 (defun org-file-menu-entry (file)
6594 (vector file (list 'find-file file) t))
6595
6596 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
6597 "Return a list of all relevant day numbers from BEG to END buffer positions.
6598 If NO-RANGES is non-nil, include only the start and end dates of a range,
6599 not every single day in the range. If FORCE-TODAY is non-nil, make
6600 sure that TODAY is included in the list. If INACTIVE is non-nil, also
6601 inactive time stamps (those in square brackets) are included.
6602 When EMPTY is non-nil, also include days without any entries."
6603 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
6604 dates dates1 date day day1 day2 ts1 ts2)
6605 (if force-today
6606 (setq dates (list (time-to-days (current-time)))))
6607 (save-excursion
6608 (goto-char beg)
6609 (while (re-search-forward re end t)
6610 (setq day (time-to-days (org-time-string-to-time
6611 (substring (match-string 1) 0 10))))
6612 (or (memq day dates) (push day dates)))
6613 (unless no-ranges
6614 (goto-char beg)
6615 (while (re-search-forward org-tr-regexp end t)
6616 (setq ts1 (substring (match-string 1) 0 10)
6617 ts2 (substring (match-string 2) 0 10)
6618 day1 (time-to-days (org-time-string-to-time ts1))
6619 day2 (time-to-days (org-time-string-to-time ts2)))
6620 (while (< (setq day1 (1+ day1)) day2)
6621 (or (memq day1 dates) (push day1 dates)))))
6622 (setq dates (sort dates '<))
6623 (when empty
6624 (while (setq day (pop dates))
6625 (setq day2 (car dates))
6626 (push day dates1)
6627 (when (and day2 empty)
6628 (if (or (eq empty t)
6629 (and (numberp empty) (<= (- day2 day) empty)))
6630 (while (< (setq day (1+ day)) day2)
6631 (push (list day) dates1))
6632 (push (cons :omitted (- day2 day)) dates1))))
6633 (setq dates (nreverse dates1)))
6634 dates)))
6635
6636 ;;;###autoload
6637 (defun org-diary (&rest args)
6638 "Return diary information from org-files.
6639 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
6640 It accesses org files and extracts information from those files to be
6641 listed in the diary. The function accepts arguments specifying what
6642 items should be listed. The following arguments are allowed:
6643
6644 :timestamp List the headlines of items containing a date stamp or
6645 date range matching the selected date. Deadlines will
6646 also be listed, on the expiration day.
6647
6648 :deadline List any deadlines past due, or due within
6649 `org-deadline-warning-days'. The listing occurs only
6650 in the diary for *today*, not at any other date. If
6651 an entry is marked DONE, it is no longer listed.
6652
6653 :scheduled List all items which are scheduled for the given date.
6654 The diary for *today* also contains items which were
6655 scheduled earlier and are not yet marked DONE.
6656
6657 :todo List all TODO items from the org-file. This may be a
6658 long list - so this is not turned on by default.
6659 Like deadlines, these entries only show up in the
6660 diary for *today*, not at any other date.
6661
6662 The call in the diary file should look like this:
6663
6664 &%%(org-diary) ~/path/to/some/orgfile.org
6665
6666 Use a separate line for each org file to check. Or, if you omit the file name,
6667 all files listed in `org-agenda-files' will be checked automatically:
6668
6669 &%%(org-diary)
6670
6671 If you don't give any arguments (as in the example above), the default
6672 arguments (:deadline :scheduled :timestamp) are used. So the example above may
6673 also be written as
6674
6675 &%%(org-diary :deadline :timestamp :scheduled)
6676
6677 The function expects the lisp variables `entry' and `date' to be provided
6678 by the caller, because this is how the calendar works. Don't use this
6679 function from a program - use `org-agenda-get-day-entries' instead."
6680 (org-agenda-maybe-reset-markers)
6681 (org-compile-prefix-format org-agenda-prefix-format)
6682 (setq args (or args '(:deadline :scheduled :timestamp)))
6683 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
6684 (list entry)
6685 (org-agenda-files t)))
6686 file rtn results)
6687 ;; If this is called during org-agenda, don't return any entries to
6688 ;; the calendar. Org Agenda will list these entries itself.
6689 (if org-disable-agenda-to-diary (setq files nil))
6690 (while (setq file (pop files))
6691 (setq rtn (apply 'org-agenda-get-day-entries file date args))
6692 (setq results (append results rtn)))
6693 (if results
6694 (concat (org-finalize-agenda-entries results) "\n"))))
6695 (defvar org-category-table nil)
6696 (defun org-get-category-table ()
6697 "Get the table of categories and positions in current buffer."
6698 (let (tbl)
6699 (save-excursion
6700 (goto-char (point-min))
6701 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
6702 (push (cons (point) (org-trim (match-string 2))) tbl)))
6703 tbl))
6704 (defun org-get-category (&optional pos)
6705 "Get the category applying to position POS."
6706 (if (not org-category-table)
6707 (cond
6708 ((null org-category)
6709 (setq org-category
6710 (if buffer-file-name
6711 (file-name-sans-extension
6712 (file-name-nondirectory buffer-file-name))
6713 "???")))
6714 ((symbolp org-category) (symbol-name org-category))
6715 (t org-category))
6716 (let ((tbl org-category-table)
6717 (pos (or pos (point))))
6718 (while (and tbl (> (caar tbl) pos))
6719 (pop tbl))
6720 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
6721 org-category-table))))))
6722
6723 (defun org-agenda-get-day-entries (file date &rest args)
6724 "Does the work for `org-diary' and `org-agenda'.
6725 FILE is the path to a file to be checked for entries. DATE is date like
6726 the one returned by `calendar-current-date'. ARGS are symbols indicating
6727 which kind of entries should be extracted. For details about these, see
6728 the documentation of `org-diary'."
6729 (setq args (or args '(:deadline :scheduled :timestamp)))
6730 (let* ((org-startup-with-deadline-check nil)
6731 (org-startup-folded nil)
6732 (org-startup-align-all-tables nil)
6733 (buffer (if (file-exists-p file)
6734 (org-get-agenda-file-buffer file)
6735 (error "No such file %s" file)))
6736 arg results rtn)
6737 (if (not buffer)
6738 ;; If file does not exist, make sure an error message ends up in diary
6739 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6740 (with-current-buffer buffer
6741 (unless (eq major-mode 'org-mode)
6742 (error "Agenda file %s is not in `org-mode'" file))
6743 (setq org-category-table (org-get-category-table))
6744 (let ((case-fold-search nil))
6745 (save-excursion
6746 (save-restriction
6747 (if org-respect-restriction
6748 (if (org-region-active-p)
6749 ;; Respect a region to restrict search
6750 (narrow-to-region (region-beginning) (region-end)))
6751 ;; If we work for the calendar or many files,
6752 ;; get rid of any restriction
6753 (widen))
6754 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
6755 (while (setq arg (pop args))
6756 (cond
6757 ((and (eq arg :todo)
6758 (equal date (calendar-current-date)))
6759 (setq rtn (org-agenda-get-todos))
6760 (setq results (append results rtn)))
6761 ((eq arg :timestamp)
6762 (setq rtn (org-agenda-get-blocks))
6763 (setq results (append results rtn))
6764 (setq rtn (org-agenda-get-timestamps))
6765 (setq results (append results rtn)))
6766 ((eq arg :scheduled)
6767 (setq rtn (org-agenda-get-scheduled))
6768 (setq results (append results rtn)))
6769 ((eq arg :closed)
6770 (setq rtn (org-agenda-get-closed))
6771 (setq results (append results rtn)))
6772 ((and (eq arg :deadline)
6773 (equal date (calendar-current-date)))
6774 (setq rtn (org-agenda-get-deadlines))
6775 (setq results (append results rtn))))))))
6776 results))))
6777
6778 (defun org-entry-is-done-p ()
6779 "Is the current entry marked DONE?"
6780 (save-excursion
6781 (and (re-search-backward "[\r\n]\\*" nil t)
6782 (looking-at org-nl-done-regexp))))
6783
6784 (defun org-at-date-range-p ()
6785 "Is the cursor inside a date range?"
6786 (interactive)
6787 (save-excursion
6788 (catch 'exit
6789 (let ((pos (point)))
6790 (skip-chars-backward "^<\r\n")
6791 (skip-chars-backward "<")
6792 (and (looking-at org-tr-regexp)
6793 (>= (match-end 0) pos)
6794 (throw 'exit t))
6795 (skip-chars-backward "^<\r\n")
6796 (skip-chars-backward "<")
6797 (and (looking-at org-tr-regexp)
6798 (>= (match-end 0) pos)
6799 (throw 'exit t)))
6800 nil)))
6801
6802 (defun org-agenda-get-todos ()
6803 "Return the TODO information for agenda display."
6804 (let* ((props (list 'face nil
6805 'done-face 'org-done
6806 'org-not-done-regexp org-not-done-regexp
6807 'mouse-face 'highlight
6808 'keymap org-agenda-keymap
6809 'help-echo
6810 (format "mouse-2 or RET jump to org file %s"
6811 (abbreviate-file-name buffer-file-name))))
6812 (regexp (concat "[\n\r]\\*+ *\\("
6813 (if org-select-this-todo-keyword
6814 (concat "\\<\\(" org-select-this-todo-keyword
6815 "\\)\\>")
6816 org-not-done-regexp)
6817 "[^\n\r]*\\)"))
6818 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
6819 marker priority category tags
6820 ee txt)
6821 (goto-char (point-min))
6822 (while (re-search-forward regexp nil t)
6823 (when (not (and org-agenda-todo-ignore-scheduled
6824 (save-match-data (looking-at sched-re))))
6825 (goto-char (match-beginning 1))
6826 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
6827 category (org-get-category)
6828 tags (org-get-tags-at (point))
6829 txt (org-format-agenda-item "" (match-string 1) category tags)
6830 priority
6831 (+ (org-get-priority txt)
6832 (if org-todo-kwd-priority-p
6833 (- org-todo-kwd-max-priority -2
6834 (length
6835 (member (match-string 2) org-todo-keywords)))
6836 1)))
6837 (org-add-props txt props
6838 'org-marker marker 'org-hd-marker marker
6839 'priority priority 'category category)
6840 (push txt ee))
6841 (if org-agenda-todo-list-sublevels
6842 (goto-char (match-end 1))
6843 (org-end-of-subtree 'invisible)))
6844 (nreverse ee)))
6845
6846 (defconst org-agenda-no-heading-message
6847 "No heading for this item in buffer or region.")
6848
6849 (defun org-agenda-get-timestamps ()
6850 "Return the date stamp information for agenda display."
6851 (let* ((props (list 'face nil
6852 'org-not-done-regexp org-not-done-regexp
6853 'mouse-face 'highlight
6854 'keymap org-agenda-keymap
6855 'help-echo
6856 (format "mouse-2 or RET jump to org file %s"
6857 (abbreviate-file-name buffer-file-name))))
6858 (regexp (regexp-quote
6859 (substring
6860 (format-time-string
6861 (car org-time-stamp-formats)
6862 (apply 'encode-time ; DATE bound by calendar
6863 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6864 0 11)))
6865 marker hdmarker deadlinep scheduledp donep tmp priority category
6866 ee txt timestr tags)
6867 (goto-char (point-min))
6868 (while (re-search-forward regexp nil t)
6869 (if (not (save-match-data (org-at-date-range-p)))
6870 (progn
6871 (setq marker (org-agenda-new-marker (match-beginning 0))
6872 category (org-get-category (match-beginning 0))
6873 tmp (buffer-substring (max (point-min)
6874 (- (match-beginning 0)
6875 org-ds-keyword-length))
6876 (match-beginning 0))
6877 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6878 deadlinep (string-match org-deadline-regexp tmp)
6879 scheduledp (string-match org-scheduled-regexp tmp)
6880 donep (org-entry-is-done-p))
6881 (if (string-match ">" timestr)
6882 ;; substring should only run to end of time stamp
6883 (setq timestr (substring timestr 0 (match-end 0))))
6884 (save-excursion
6885 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6886 (progn
6887 (goto-char (match-end 1))
6888 (setq hdmarker (org-agenda-new-marker)
6889 tags (org-get-tags-at))
6890 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6891 (setq txt (org-format-agenda-item
6892 (format "%s%s"
6893 (if deadlinep "Deadline: " "")
6894 (if scheduledp "Scheduled: " ""))
6895 (match-string 1) category tags timestr)))
6896 (setq txt org-agenda-no-heading-message))
6897 (setq priority (org-get-priority txt))
6898 (org-add-props txt props
6899 'org-marker marker 'org-hd-marker hdmarker)
6900 (if deadlinep
6901 (org-add-props txt nil
6902 'face (if donep 'org-done 'org-warning)
6903 'undone-face 'org-warning 'done-face 'org-done
6904 'category category 'priority (+ 100 priority))
6905 (if scheduledp
6906 (org-add-props txt nil
6907 'face 'org-scheduled-today
6908 'undone-face 'org-scheduled-today 'done-face 'org-done
6909 'category category 'priority (+ 99 priority))
6910 (org-add-props txt nil 'priority priority 'category category)))
6911 (push txt ee))
6912 (outline-next-heading))))
6913 (nreverse ee)))
6914
6915 (defun org-agenda-get-closed ()
6916 "Return the logged TODO entries for agenda display."
6917 (let* ((props (list 'mouse-face 'highlight
6918 'org-not-done-regexp org-not-done-regexp
6919 'keymap org-agenda-keymap
6920 'help-echo
6921 (format "mouse-2 or RET jump to org file %s"
6922 (abbreviate-file-name buffer-file-name))))
6923 (regexp (concat
6924 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
6925 (regexp-quote
6926 (substring
6927 (format-time-string
6928 (car org-time-stamp-formats)
6929 (apply 'encode-time ; DATE bound by calendar
6930 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6931 1 11))))
6932 marker hdmarker priority category tags closedp
6933 ee txt timestr)
6934 (goto-char (point-min))
6935 (while (re-search-forward regexp nil t)
6936 (if (not (save-match-data (org-at-date-range-p)))
6937 (progn
6938 (setq marker (org-agenda-new-marker (match-beginning 0))
6939 closedp (equal (match-string 1) org-closed-string)
6940 category (org-get-category (match-beginning 0))
6941 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6942 ;; donep (org-entry-is-done-p)
6943 )
6944 (if (string-match "\\]" timestr)
6945 ;; substring should only run to end of time stamp
6946 (setq timestr (substring timestr 0 (match-end 0))))
6947 (save-excursion
6948 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6949 (progn
6950 (goto-char (match-end 1))
6951 (setq hdmarker (org-agenda-new-marker)
6952 tags (org-get-tags-at))
6953 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6954 (setq txt (org-format-agenda-item
6955 (if closedp "Closed: " "Clocked: ")
6956 (match-string 1) category tags timestr)))
6957 (setq txt org-agenda-no-heading-message))
6958 (setq priority 100000)
6959 (org-add-props txt props
6960 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
6961 'priority priority 'category category
6962 'undone-face 'org-warning 'done-face 'org-done)
6963 (push txt ee))
6964 (outline-next-heading))))
6965 (nreverse ee)))
6966
6967 (defun org-agenda-get-deadlines ()
6968 "Return the deadline information for agenda display."
6969 (let* ((wdays org-deadline-warning-days)
6970 (props (list 'mouse-face 'highlight
6971 'org-not-done-regexp org-not-done-regexp
6972 'keymap org-agenda-keymap
6973 'help-echo
6974 (format "mouse-2 or RET jump to org file %s"
6975 (abbreviate-file-name buffer-file-name))))
6976 (regexp org-deadline-time-regexp)
6977 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6978 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6979 d2 diff pos pos1 category tags
6980 ee txt head face)
6981 (goto-char (point-min))
6982 (while (re-search-forward regexp nil t)
6983 (setq pos (1- (match-beginning 1))
6984 d2 (time-to-days
6985 (org-time-string-to-time (match-string 1)))
6986 diff (- d2 d1))
6987 ;; When to show a deadline in the calendar:
6988 ;; If the expiration is within wdays warning time.
6989 ;; Past-due deadlines are only shown on the current date
6990 (if (and (< diff wdays) todayp (not (= diff 0)))
6991 (save-excursion
6992 (setq category (org-get-category))
6993 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6994 (progn
6995 (goto-char (match-end 0))
6996 (setq pos1 (match-end 1))
6997 (setq tags (org-get-tags-at pos1))
6998 (setq head (buffer-substring-no-properties
6999 (point)
7000 (progn (skip-chars-forward "^\r\n")
7001 (point))))
7002 (if (string-match org-looking-at-done-regexp head)
7003 (setq txt nil)
7004 (setq txt (org-format-agenda-item
7005 (format "In %3d d.: " diff) head category tags))))
7006 (setq txt org-agenda-no-heading-message))
7007 (when txt
7008 (setq face (cond ((<= diff 0) 'org-warning)
7009 ((<= diff 5) 'org-upcoming-deadline)
7010 (t nil)))
7011 (org-add-props txt props
7012 'org-marker (org-agenda-new-marker pos)
7013 'org-hd-marker (org-agenda-new-marker pos1)
7014 'priority (+ (- 10 diff) (org-get-priority txt))
7015 'category category
7016 'face face 'undone-face face 'done-face 'org-done)
7017 (push txt ee)))))
7018 ee))
7019
7020 (defun org-agenda-get-scheduled ()
7021 "Return the scheduled information for agenda display."
7022 (let* ((props (list 'face 'org-scheduled-previously
7023 'org-not-done-regexp org-not-done-regexp
7024 'undone-face 'org-scheduled-previously
7025 'done-face 'org-done
7026 'mouse-face 'highlight
7027 'keymap org-agenda-keymap
7028 'help-echo
7029 (format "mouse-2 or RET jump to org file %s"
7030 (abbreviate-file-name buffer-file-name))))
7031 (regexp org-scheduled-time-regexp)
7032 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7033 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7034 d2 diff pos pos1 category tags
7035 ee txt head)
7036 (goto-char (point-min))
7037 (while (re-search-forward regexp nil t)
7038 (setq pos (1- (match-beginning 1))
7039 d2 (time-to-days
7040 (org-time-string-to-time (match-string 1)))
7041 diff (- d2 d1))
7042 ;; When to show a scheduled item in the calendar:
7043 ;; If it is on or past the date.
7044 (if (and (< diff 0) todayp)
7045 (save-excursion
7046 (setq category (org-get-category))
7047 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7048 (progn
7049 (goto-char (match-end 0))
7050 (setq pos1 (match-end 1))
7051 (setq tags (org-get-tags-at))
7052 (setq head (buffer-substring-no-properties
7053 (point)
7054 (progn (skip-chars-forward "^\r\n") (point))))
7055 (if (string-match org-looking-at-done-regexp head)
7056 (setq txt nil)
7057 (setq txt (org-format-agenda-item
7058 (format "Sched.%2dx: " (- 1 diff)) head
7059 category tags))))
7060 (setq txt org-agenda-no-heading-message))
7061 (when txt
7062 (org-add-props txt props
7063 'org-marker (org-agenda-new-marker pos)
7064 'org-hd-marker (org-agenda-new-marker pos1)
7065 'priority (+ (- 5 diff) (org-get-priority txt))
7066 'category category)
7067 (push txt ee)))))
7068 ee))
7069
7070 (defun org-agenda-get-blocks ()
7071 "Return the date-range information for agenda display."
7072 (let* ((props (list 'face nil
7073 'org-not-done-regexp org-not-done-regexp
7074 'mouse-face 'highlight
7075 'keymap org-agenda-keymap
7076 'help-echo
7077 (format "mouse-2 or RET jump to org file %s"
7078 (abbreviate-file-name buffer-file-name))))
7079 (regexp org-tr-regexp)
7080 (d0 (calendar-absolute-from-gregorian date))
7081 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
7082 (goto-char (point-min))
7083 (while (re-search-forward regexp nil t)
7084 (setq timestr (match-string 0)
7085 s1 (match-string 1)
7086 s2 (match-string 2)
7087 d1 (time-to-days (org-time-string-to-time s1))
7088 d2 (time-to-days (org-time-string-to-time s2)))
7089 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
7090 ;; Only allow days between the limits, because the normal
7091 ;; date stamps will catch the limits.
7092 (save-excursion
7093 (setq marker (org-agenda-new-marker (point)))
7094 (setq category (org-get-category))
7095 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7096 (progn
7097 (setq hdmarker (org-agenda-new-marker (match-end 1)))
7098 (goto-char (match-end 1))
7099 (setq tags (org-get-tags-at))
7100 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7101 (setq txt (org-format-agenda-item
7102 (format (if (= d1 d2) "" "(%d/%d): ")
7103 (1+ (- d0 d1)) (1+ (- d2 d1)))
7104 (match-string 1) category tags
7105 (if (= d0 d1) timestr))))
7106 (setq txt org-agenda-no-heading-message))
7107 (org-add-props txt props
7108 'org-marker marker 'org-hd-marker hdmarker
7109 'priority (org-get-priority txt) 'category category)
7110 (push txt ee)))
7111 (outline-next-heading))
7112 ;; Sort the entries by expiration date.
7113 (nreverse ee)))
7114
7115 (defconst org-plain-time-of-day-regexp
7116 (concat
7117 "\\(\\<[012]?[0-9]"
7118 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7119 "\\(--?"
7120 "\\(\\<[012]?[0-9]"
7121 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7122 "\\)?")
7123 "Regular expression to match a plain time or time range.
7124 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
7125 groups carry important information:
7126 0 the full match
7127 1 the first time, range or not
7128 8 the second time, if it is a range.")
7129
7130 (defconst org-stamp-time-of-day-regexp
7131 (concat
7132 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
7133 "\\([012][0-9]:[0-5][0-9]\\)>"
7134 "\\(--?"
7135 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
7136 "Regular expression to match a timestamp time or time range.
7137 After a match, the following groups carry important information:
7138 0 the full match
7139 1 date plus weekday, for backreferencing to make sure both times on same day
7140 2 the first time, range or not
7141 4 the second time, if it is a range.")
7142
7143 (defvar org-prefix-has-time nil
7144 "A flag, set by `org-compile-prefix-format'.
7145 The flag is set if the currently compiled format contains a `%t'.")
7146 (defvar org-prefix-has-tag nil
7147 "A flag, set by `org-compile-prefix-format'.
7148 The flag is set if the currently compiled format contains a `%T'.")
7149
7150 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
7151 "Format TXT to be inserted into the agenda buffer.
7152 In particular, it adds the prefix and corresponding text properties. EXTRA
7153 must be a string and replaces the `%s' specifier in the prefix format.
7154 CATEGORY (string, symbol or nil) may be used to overrule the default
7155 category taken from local variable or file name. It will replace the `%c'
7156 specifier in the format. DOTIME, when non-nil, indicates that a
7157 time-of-day should be extracted from TXT for sorting of this entry, and for
7158 the `%t' specifier in the format. When DOTIME is a string, this string is
7159 searched for a time before TXT is. NOPREFIX is a flag and indicates that
7160 only the correctly processes TXT should be returned - this is used by
7161 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
7162 (save-match-data
7163 ;; Diary entries sometimes have extra whitespace at the beginning
7164 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
7165 (let* ((category (or category
7166 org-category
7167 (if buffer-file-name
7168 (file-name-sans-extension
7169 (file-name-nondirectory buffer-file-name))
7170 "")))
7171 (tag (if tags (nth (1- (length tags)) tags) ""))
7172 time ;; needed for the eval of the prefix format
7173 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
7174 (time-of-day (and dotime (org-get-time-of-day ts)))
7175 stamp plain s0 s1 s2 rtn)
7176 (when (and dotime time-of-day org-prefix-has-time)
7177 ;; Extract starting and ending time and move them to prefix
7178 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
7179 (setq plain (string-match org-plain-time-of-day-regexp ts)))
7180 (setq s0 (match-string 0 ts)
7181 s1 (match-string (if plain 1 2) ts)
7182 s2 (match-string (if plain 8 4) ts))
7183
7184 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
7185 ;; them, we might want to remove them there to avoid duplication.
7186 ;; The user can turn this off with a variable.
7187 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
7188 (string-match (concat (regexp-quote s0) " *") txt)
7189 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
7190 (= (match-beginning 0) 0)
7191 t))
7192 (setq txt (replace-match "" nil nil txt))))
7193 ;; Normalize the time(s) to 24 hour
7194 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
7195 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
7196
7197 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
7198 ;; Tags are in the string
7199 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
7200 (and org-agenda-remove-tags-when-in-prefix
7201 org-prefix-has-tag))
7202 (setq txt (replace-match "" t t txt))
7203 (setq txt (replace-match
7204 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
7205 (match-string 2 txt))
7206 t t txt))))
7207
7208 ;; Create the final string
7209 (if noprefix
7210 (setq rtn txt)
7211 ;; Prepare the variables needed in the eval of the compiled format
7212 (setq time (cond (s2 (concat s1 "-" s2))
7213 (s1 (concat s1 "......"))
7214 (t ""))
7215 extra (or extra "")
7216 category (if (symbolp category) (symbol-name category) category))
7217 ;; Evaluate the compiled format
7218 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
7219
7220 ;; And finally add the text properties
7221 (org-add-props rtn nil
7222 'category (downcase category) 'tags tags
7223 'prefix-length (- (length rtn) (length txt))
7224 'time-of-day time-of-day
7225 'dotime dotime))))
7226
7227 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
7228 (catch 'exit
7229 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
7230 ((and todayp (member 'today (car org-agenda-time-grid))))
7231 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
7232 ((member 'weekly (car org-agenda-time-grid)))
7233 (t (throw 'exit list)))
7234 (let* ((have (delq nil (mapcar
7235 (lambda (x) (get-text-property 1 'time-of-day x))
7236 list)))
7237 (string (nth 1 org-agenda-time-grid))
7238 (gridtimes (nth 2 org-agenda-time-grid))
7239 (req (car org-agenda-time-grid))
7240 (remove (member 'remove-match req))
7241 new time)
7242 (if (and (member 'require-timed req) (not have))
7243 ;; don't show empty grid
7244 (throw 'exit list))
7245 (while (setq time (pop gridtimes))
7246 (unless (and remove (member time have))
7247 (setq time (int-to-string time))
7248 (push (org-format-agenda-item
7249 nil string "" nil
7250 (concat (substring time 0 -2) ":" (substring time -2)))
7251 new)
7252 (put-text-property
7253 1 (length (car new)) 'face 'org-time-grid (car new))))
7254 (if (member 'time-up org-agenda-sorting-strategy)
7255 (append new list)
7256 (append list new)))))
7257
7258 (defun org-compile-prefix-format (format)
7259 "Compile the prefix format into a Lisp form that can be evaluated.
7260 The resulting form is returned and stored in the variable
7261 `org-prefix-format-compiled'."
7262 (setq org-prefix-has-time nil org-prefix-has-tag nil)
7263 (let ((start 0) varform vars var (s format)e c f opt)
7264 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
7265 s start)
7266 (setq var (cdr (assoc (match-string 4 s)
7267 '(("c" . category) ("t" . time) ("s" . extra)
7268 ("T" . tag))))
7269 c (or (match-string 3 s) "")
7270 opt (match-beginning 1)
7271 start (1+ (match-beginning 0)))
7272 (if (equal var 'time) (setq org-prefix-has-time t))
7273 (if (equal var 'tag) (setq org-prefix-has-tag t))
7274 (setq f (concat "%" (match-string 2 s) "s"))
7275 (if opt
7276 (setq varform
7277 `(if (equal "" ,var)
7278 ""
7279 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
7280 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
7281 (setq s (replace-match "%s" t nil s))
7282 (push varform vars))
7283 (setq vars (nreverse vars))
7284 (setq org-prefix-format-compiled `(format ,s ,@vars))))
7285
7286 (defun org-get-time-of-day (s &optional string mod24)
7287 "Check string S for a time of day.
7288 If found, return it as a military time number between 0 and 2400.
7289 If not found, return nil.
7290 The optional STRING argument forces conversion into a 5 character wide string
7291 HH:MM."
7292 (save-match-data
7293 (when
7294 (or
7295 (string-match
7296 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
7297 (string-match
7298 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
7299 (let* ((h (string-to-number (match-string 1 s)))
7300 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
7301 (ampm (if (match-end 4) (downcase (match-string 4 s))))
7302 (am-p (equal ampm "am"))
7303 (h1 (cond ((not ampm) h)
7304 ((= h 12) (if am-p 0 12))
7305 (t (+ h (if am-p 0 12)))))
7306 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
7307 (mod h1 24) h1))
7308 (t0 (+ (* 100 h2) m))
7309 (t1 (concat (if (>= h1 24) "+" " ")
7310 (if (< t0 100) "0" "")
7311 (if (< t0 10) "0" "")
7312 (int-to-string t0))))
7313 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
7314
7315 (defun org-finalize-agenda-entries (list)
7316 "Sort and concatenate the agenda items."
7317 (setq list (mapcar 'org-agenda-highlight-todo list))
7318 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
7319
7320 (defun org-agenda-highlight-todo (x)
7321 (let (re pl)
7322 (if (eq x 'line)
7323 (save-excursion
7324 (beginning-of-line 1)
7325 (setq re (get-text-property (point) 'org-not-done-regexp))
7326 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
7327 (and (looking-at (concat "[ \t]*" re))
7328 (add-text-properties (match-beginning 0) (match-end 0)
7329 '(face org-todo))))
7330 (setq re (get-text-property 0 'org-not-done-regexp x)
7331 pl (get-text-property 0 'prefix-length x))
7332 (and re (equal (string-match re x pl) pl)
7333 (add-text-properties (match-beginning 0) (match-end 0)
7334 '(face org-todo) x))
7335 x)))
7336
7337 (defsubst org-cmp-priority (a b)
7338 "Compare the priorities of string A and B."
7339 (let ((pa (or (get-text-property 1 'priority a) 0))
7340 (pb (or (get-text-property 1 'priority b) 0)))
7341 (cond ((> pa pb) +1)
7342 ((< pa pb) -1)
7343 (t nil))))
7344
7345 (defsubst org-cmp-category (a b)
7346 "Compare the string values of categories of strings A and B."
7347 (let ((ca (or (get-text-property 1 'category a) ""))
7348 (cb (or (get-text-property 1 'category b) "")))
7349 (cond ((string-lessp ca cb) -1)
7350 ((string-lessp cb ca) +1)
7351 (t nil))))
7352
7353 (defsubst org-cmp-time (a b)
7354 "Compare the time-of-day values of strings A and B."
7355 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
7356 (ta (or (get-text-property 1 'time-of-day a) def))
7357 (tb (or (get-text-property 1 'time-of-day b) def)))
7358 (cond ((< ta tb) -1)
7359 ((< tb ta) +1)
7360 (t nil))))
7361
7362 (defun org-entries-lessp (a b)
7363 "Predicate for sorting agenda entries."
7364 ;; The following variables will be used when the form is evaluated.
7365 (let* ((time-up (org-cmp-time a b))
7366 (time-down (if time-up (- time-up) nil))
7367 (priority-up (org-cmp-priority a b))
7368 (priority-down (if priority-up (- priority-up) nil))
7369 (category-up (org-cmp-category a b))
7370 (category-down (if category-up (- category-up) nil))
7371 (category-keep (if category-up +1 nil)))
7372 (cdr (assoc
7373 (eval (cons 'or org-agenda-sorting-strategy))
7374 '((-1 . t) (1 . nil) (nil . nil))))))
7375
7376 (defun org-agenda-show-priority ()
7377 "Show the priority of the current item.
7378 This priority is composed of the main priority given with the [#A] cookies,
7379 and by additional input from the age of a schedules or deadline entry."
7380 (interactive)
7381 (let* ((pri (get-text-property (point-at-bol) 'priority)))
7382 (message "Priority is %d" (if pri pri -1000))))
7383
7384 (defun org-agenda-show-tags ()
7385 "Show the tags applicable to the current item."
7386 (interactive)
7387 (let* ((tags (get-text-property (point-at-bol) 'tags)))
7388 (if tags
7389 (message "Tags are :%s:"
7390 (org-no-properties (mapconcat 'identity tags ":")))
7391 (message "No tags associated with this line"))))
7392
7393 (defun org-agenda-goto (&optional highlight)
7394 "Go to the Org-mode file which contains the item at point."
7395 (interactive)
7396 (let* ((marker (or (get-text-property (point) 'org-marker)
7397 (org-agenda-error)))
7398 (buffer (marker-buffer marker))
7399 (pos (marker-position marker)))
7400 (switch-to-buffer-other-window buffer)
7401 (widen)
7402 (goto-char pos)
7403 (when (eq major-mode 'org-mode)
7404 (org-show-hidden-entry)
7405 (save-excursion
7406 (and (outline-next-heading)
7407 (org-flag-heading nil)))) ; show the next heading
7408 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
7409
7410 (defun org-agenda-switch-to ()
7411 "Go to the Org-mode file which contains the item at point."
7412 (interactive)
7413 (let* ((marker (or (get-text-property (point) 'org-marker)
7414 (org-agenda-error)))
7415 (buffer (marker-buffer marker))
7416 (pos (marker-position marker)))
7417 (switch-to-buffer buffer)
7418 (delete-other-windows)
7419 (widen)
7420 (goto-char pos)
7421 (when (eq major-mode 'org-mode)
7422 (org-show-hidden-entry)
7423 (save-excursion
7424 (and (outline-next-heading)
7425 (org-flag-heading nil)))))) ; show the next heading
7426
7427 (defun org-agenda-goto-mouse (ev)
7428 "Go to the Org-mode file which contains the item at the mouse click."
7429 (interactive "e")
7430 (mouse-set-point ev)
7431 (org-agenda-goto))
7432
7433 (defun org-agenda-show ()
7434 "Display the Org-mode file which contains the item at point."
7435 (interactive)
7436 (let ((win (selected-window)))
7437 (org-agenda-goto t)
7438 (select-window win)))
7439
7440 (defun org-agenda-recenter (arg)
7441 "Display the Org-mode file which contains the item at point and recenter."
7442 (interactive "P")
7443 (let ((win (selected-window)))
7444 (org-agenda-goto t)
7445 (recenter arg)
7446 (select-window win)))
7447
7448 (defun org-agenda-show-mouse (ev)
7449 "Display the Org-mode file which contains the item at the mouse click."
7450 (interactive "e")
7451 (mouse-set-point ev)
7452 (org-agenda-show))
7453
7454 (defun org-agenda-check-no-diary ()
7455 "Check if the entry is a diary link and abort if yes."
7456 (if (get-text-property (point) 'org-agenda-diary-link)
7457 (org-agenda-error)))
7458
7459 (defun org-agenda-error ()
7460 (error "Command not allowed in this line"))
7461
7462 (defvar org-last-heading-marker (make-marker)
7463 "Marker pointing to the headline that last changed its TODO state
7464 by a remote command from the agenda.")
7465
7466 (defun org-agenda-todo (&optional arg)
7467 "Cycle TODO state of line at point, also in Org-mode file.
7468 This changes the line at point, all other lines in the agenda referring to
7469 the same tree node, and the headline of the tree node in the Org-mode file."
7470 (interactive "P")
7471 (org-agenda-check-no-diary)
7472 (let* ((col (current-column))
7473 (marker (or (get-text-property (point) 'org-marker)
7474 (org-agenda-error)))
7475 (buffer (marker-buffer marker))
7476 (pos (marker-position marker))
7477 (hdmarker (get-text-property (point) 'org-hd-marker))
7478 (buffer-read-only nil)
7479 newhead)
7480 (with-current-buffer buffer
7481 (widen)
7482 (goto-char pos)
7483 (org-show-hidden-entry)
7484 (save-excursion
7485 (and (outline-next-heading)
7486 (org-flag-heading nil))) ; show the next heading
7487 (org-todo arg)
7488 (and (bolp) (forward-char 1))
7489 (setq newhead (org-get-heading))
7490 (save-excursion
7491 (org-back-to-heading)
7492 (move-marker org-last-heading-marker (point))))
7493 (beginning-of-line 1)
7494 (save-excursion
7495 (org-agenda-change-all-lines newhead hdmarker 'fixface))
7496 (move-to-column col)))
7497
7498 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
7499 "Change all lines in the agenda buffer which match HDMARKER.
7500 The new content of the line will be NEWHEAD (as modified by
7501 `org-format-agenda-item'). HDMARKER is checked with
7502 `equal' against all `org-hd-marker' text properties in the file.
7503 If FIXFACE is non-nil, the face of each item is modified acording to
7504 the new TODO state."
7505 (let* (props m pl undone-face done-face finish new dotime cat tags)
7506 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
7507 (save-excursion
7508 (goto-char (point-max))
7509 (beginning-of-line 1)
7510 (while (not finish)
7511 (setq finish (bobp))
7512 (when (and (setq m (get-text-property (point) 'org-hd-marker))
7513 (equal m hdmarker))
7514 (setq props (text-properties-at (point))
7515 dotime (get-text-property (point) 'dotime)
7516 cat (get-text-property (point) 'category)
7517 tags (get-text-property (point) 'tags)
7518 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
7519 pl (get-text-property (point) 'prefix-length)
7520 undone-face (get-text-property (point) 'undone-face)
7521 done-face (get-text-property (point) 'done-face))
7522 (move-to-column pl)
7523 (if (looking-at ".*")
7524 (progn
7525 (replace-match new t t)
7526 (beginning-of-line 1)
7527 (add-text-properties (point-at-bol) (point-at-eol) props)
7528 (when fixface
7529 (add-text-properties
7530 (point-at-bol) (point-at-eol)
7531 (list 'face
7532 (if org-last-todo-state-is-todo
7533 undone-face done-face)))
7534 (org-agenda-highlight-todo 'line))
7535 (beginning-of-line 1))
7536 (error "Line update did not work")))
7537 (beginning-of-line 0)))))
7538
7539 (defun org-agenda-priority-up ()
7540 "Increase the priority of line at point, also in Org-mode file."
7541 (interactive)
7542 (org-agenda-priority 'up))
7543
7544 (defun org-agenda-priority-down ()
7545 "Decrease the priority of line at point, also in Org-mode file."
7546 (interactive)
7547 (org-agenda-priority 'down))
7548
7549 (defun org-agenda-priority (&optional force-direction)
7550 "Set the priority of line at point, also in Org-mode file.
7551 This changes the line at point, all other lines in the agenda referring to
7552 the same tree node, and the headline of the tree node in the Org-mode file."
7553 (interactive)
7554 (org-agenda-check-no-diary)
7555 (let* ((marker (or (get-text-property (point) 'org-marker)
7556 (org-agenda-error)))
7557 (buffer (marker-buffer marker))
7558 (pos (marker-position marker))
7559 (hdmarker (get-text-property (point) 'org-hd-marker))
7560 (buffer-read-only nil)
7561 newhead)
7562 (with-current-buffer buffer
7563 (widen)
7564 (goto-char pos)
7565 (org-show-hidden-entry)
7566 (save-excursion
7567 (and (outline-next-heading)
7568 (org-flag-heading nil))) ; show the next heading
7569 (funcall 'org-priority force-direction)
7570 (end-of-line 1)
7571 (setq newhead (org-get-heading)))
7572 (org-agenda-change-all-lines newhead hdmarker)
7573 (beginning-of-line 1)))
7574
7575 (defun org-get-tags-at (&optional pos)
7576 "Get a list of all headline tags applicable at POS.
7577 POS defaults to point. If tags are inherited, the list contains
7578 the targets in the same sequence as the headlines appear, i.e.
7579 the tags of the current headline come last."
7580 (interactive)
7581 (let (tags)
7582 (save-excursion
7583 (goto-char (or pos (point)))
7584 (save-match-data
7585 (org-back-to-heading t)
7586 (condition-case nil
7587 (while t
7588 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
7589 (setq tags (append (org-split-string
7590 (org-match-string-no-properties 1) ":")
7591 tags)))
7592 (or org-use-tag-inheritance (error ""))
7593 (org-up-heading-all 1))
7594 (error nil))))
7595 (message "%s" tags)
7596 tags))
7597
7598 (defun org-agenda-set-tags ()
7599 "Set tags for the current headline."
7600 (interactive)
7601 (org-agenda-check-no-diary)
7602 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
7603 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
7604 (org-agenda-error)))
7605 (buffer (marker-buffer hdmarker))
7606 (pos (marker-position hdmarker))
7607 (buffer-read-only nil)
7608 newhead)
7609 (with-current-buffer buffer
7610 (widen)
7611 (goto-char pos)
7612 (org-show-hidden-entry)
7613 (save-excursion
7614 (and (outline-next-heading)
7615 (org-flag-heading nil))) ; show the next heading
7616 (call-interactively 'org-set-tags)
7617 (end-of-line 1)
7618 (setq newhead (org-get-heading)))
7619 (org-agenda-change-all-lines newhead hdmarker)
7620 (beginning-of-line 1)))
7621
7622 (defun org-agenda-date-later (arg &optional what)
7623 "Change the date of this item to one day later."
7624 (interactive "p")
7625 (org-agenda-check-type t 'agenda 'timeline)
7626 (org-agenda-check-no-diary)
7627 (let* ((marker (or (get-text-property (point) 'org-marker)
7628 (org-agenda-error)))
7629 (buffer (marker-buffer marker))
7630 (pos (marker-position marker)))
7631 (with-current-buffer buffer
7632 (widen)
7633 (goto-char pos)
7634 (if (not (org-at-timestamp-p))
7635 (error "Cannot find time stamp"))
7636 (org-timestamp-change arg (or what 'day))
7637 (message "Time stamp changed to %s" org-last-changed-timestamp))))
7638
7639 (defun org-agenda-date-earlier (arg &optional what)
7640 "Change the date of this item to one day earlier."
7641 (interactive "p")
7642 (org-agenda-date-later (- arg) what))
7643
7644 (defun org-agenda-date-prompt (arg)
7645 "Change the date of this item. Date is prompted for, with default today.
7646 The prefix ARG is passed to the `org-time-stamp' command and can therefore
7647 be used to request time specification in the time stamp."
7648 (interactive "P")
7649 (org-agenda-check-type t 'agenda 'timeline)
7650 (org-agenda-check-no-diary)
7651 (let* ((marker (or (get-text-property (point) 'org-marker)
7652 (org-agenda-error)))
7653 (buffer (marker-buffer marker))
7654 (pos (marker-position marker)))
7655 (with-current-buffer buffer
7656 (widen)
7657 (goto-char pos)
7658 (if (not (org-at-timestamp-p))
7659 (error "Cannot find time stamp"))
7660 (org-time-stamp arg)
7661 (message "Time stamp changed to %s" org-last-changed-timestamp))))
7662
7663 (defun org-agenda-schedule (arg)
7664 "Schedule the item at point."
7665 (interactive "P")
7666 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
7667 (org-agenda-check-no-diary)
7668 (let* ((marker (or (get-text-property (point) 'org-marker)
7669 (org-agenda-error)))
7670 (buffer (marker-buffer marker))
7671 (pos (marker-position marker))
7672 (org-insert-labeled-timestamps-at-point nil)
7673 ts)
7674 (with-current-buffer buffer
7675 (widen)
7676 (goto-char pos)
7677 (setq ts (org-schedule))
7678 (message "Item scheduled for %s" ts))))
7679
7680 (defun org-agenda-deadline (arg)
7681 "Schedule the item at point."
7682 (interactive "P")
7683 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
7684 (org-agenda-check-no-diary)
7685 (let* ((marker (or (get-text-property (point) 'org-marker)
7686 (org-agenda-error)))
7687 (buffer (marker-buffer marker))
7688 (pos (marker-position marker))
7689 (org-insert-labeled-timestamps-at-point nil)
7690 ts)
7691 (with-current-buffer buffer
7692 (widen)
7693 (goto-char pos)
7694 (setq ts (org-deadline))
7695 (message "Deadline for this item set to %s" ts))))
7696
7697 (defun org-get-heading ()
7698 "Return the heading of the current entry, without the stars."
7699 (save-excursion
7700 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
7701 (if (and (re-search-backward "[\r\n]\\*" nil t)
7702 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
7703 (match-string 1)
7704 "")))
7705
7706 (defun org-agenda-clock-in (&optional arg)
7707 "Start the clock on the currently selected item."
7708 (interactive "P")
7709 (org-agenda-check-no-diary)
7710 (let* ((marker (or (get-text-property (point) 'org-marker)
7711 (org-agenda-error)))
7712 (buffer (marker-buffer marker))
7713 (pos (marker-position marker))
7714 (hdmarker (get-text-property (point) 'org-hd-marker)))
7715 (with-current-buffer (marker-buffer marker)
7716 (widen)
7717 (goto-char pos)
7718 (org-clock-in))))
7719
7720 (defun org-agenda-diary-entry ()
7721 "Make a diary entry, like the `i' command from the calendar.
7722 All the standard commands work: block, weekly etc."
7723 (interactive)
7724 (org-agenda-check-type t 'agenda 'timeline)
7725 (require 'diary-lib)
7726 (let* ((char (progn
7727 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
7728 (read-char-exclusive)))
7729 (cmd (cdr (assoc char
7730 '((?d . insert-diary-entry)
7731 (?w . insert-weekly-diary-entry)
7732 (?m . insert-monthly-diary-entry)
7733 (?y . insert-yearly-diary-entry)
7734 (?a . insert-anniversary-diary-entry)
7735 (?b . insert-block-diary-entry)
7736 (?c . insert-cyclic-diary-entry)))))
7737 (oldf (symbol-function 'calendar-cursor-to-date))
7738 (point (point))
7739 (mark (or (mark t) (point))))
7740 (unless cmd
7741 (error "No command associated with <%c>" char))
7742 (unless (and (get-text-property point 'day)
7743 (or (not (equal ?b char))
7744 (get-text-property mark 'day)))
7745 (error "Don't know which date to use for diary entry"))
7746 ;; We implement this by hacking the `calendar-cursor-to-date' function
7747 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
7748 (let ((calendar-mark-ring
7749 (list (calendar-gregorian-from-absolute
7750 (or (get-text-property mark 'day)
7751 (get-text-property point 'day))))))
7752 (unwind-protect
7753 (progn
7754 (fset 'calendar-cursor-to-date
7755 (lambda (&optional error)
7756 (calendar-gregorian-from-absolute
7757 (get-text-property point 'day))))
7758 (call-interactively cmd))
7759 (fset 'calendar-cursor-to-date oldf)))))
7760
7761
7762 (defun org-agenda-execute-calendar-command (cmd)
7763 "Execute a calendar command from the agenda, with the date associated to
7764 the cursor position."
7765 (org-agenda-check-type t 'agenda 'timeline)
7766 (require 'diary-lib)
7767 (unless (get-text-property (point) 'day)
7768 (error "Don't know which date to use for calendar command"))
7769 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
7770 (point (point))
7771 (date (calendar-gregorian-from-absolute
7772 (get-text-property point 'day)))
7773 (displayed-day (extract-calendar-day date))
7774 (displayed-month (extract-calendar-month date))
7775 (displayed-year (extract-calendar-year date)))
7776 (unwind-protect
7777 (progn
7778 (fset 'calendar-cursor-to-date
7779 (lambda (&optional error)
7780 (calendar-gregorian-from-absolute
7781 (get-text-property point 'day))))
7782 (call-interactively cmd))
7783 (fset 'calendar-cursor-to-date oldf))))
7784
7785 (defun org-agenda-phases-of-moon ()
7786 "Display the phases of the moon for the 3 months around the cursor date."
7787 (interactive)
7788 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
7789
7790 (defun org-agenda-holidays ()
7791 "Display the holidays for the 3 months around the cursor date."
7792 (interactive)
7793 (org-agenda-execute-calendar-command 'list-calendar-holidays))
7794
7795 (defun org-agenda-sunrise-sunset (arg)
7796 "Display sunrise and sunset for the cursor date.
7797 Latitude and longitude can be specified with the variables
7798 `calendar-latitude' and `calendar-longitude'. When called with prefix
7799 argument, latitude and longitude will be prompted for."
7800 (interactive "P")
7801 (let ((calendar-longitude (if arg nil calendar-longitude))
7802 (calendar-latitude (if arg nil calendar-latitude))
7803 (calendar-location-name
7804 (if arg "the given coordinates" calendar-location-name)))
7805 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
7806
7807 (defun org-agenda-goto-calendar ()
7808 "Open the Emacs calendar with the date at the cursor."
7809 (interactive)
7810 (org-agenda-check-type t 'agenda 'timeline)
7811 (let* ((day (or (get-text-property (point) 'day)
7812 (error "Don't know which date to open in calendar")))
7813 (date (calendar-gregorian-from-absolute day))
7814 (calendar-move-hook nil)
7815 (view-calendar-holidays-initially nil)
7816 (view-diary-entries-initially nil))
7817 (calendar)
7818 (calendar-goto-date date)))
7819
7820 (defun org-calendar-goto-agenda ()
7821 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
7822 This is a command that has to be installed in `calendar-mode-map'."
7823 (interactive)
7824 (org-agenda-list nil (calendar-absolute-from-gregorian
7825 (calendar-cursor-to-date))
7826 nil t))
7827
7828 (defun org-agenda-convert-date ()
7829 (interactive)
7830 (org-agenda-check-type t 'agenda 'timeline)
7831 (let ((day (get-text-property (point) 'day))
7832 date s)
7833 (unless day
7834 (error "Don't know which date to convert"))
7835 (setq date (calendar-gregorian-from-absolute day))
7836 (setq s (concat
7837 "Gregorian: " (calendar-date-string date) "\n"
7838 "ISO: " (calendar-iso-date-string date) "\n"
7839 "Day of Yr: " (calendar-day-of-year-string date) "\n"
7840 "Julian: " (calendar-julian-date-string date) "\n"
7841 "Astron. JD: " (calendar-astro-date-string date)
7842 " (Julian date number at noon UTC)\n"
7843 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
7844 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
7845 "French: " (calendar-french-date-string date) "\n"
7846 "Mayan: " (calendar-mayan-date-string date) "\n"
7847 "Coptic: " (calendar-coptic-date-string date) "\n"
7848 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
7849 "Persian: " (calendar-persian-date-string date) "\n"
7850 "Chinese: " (calendar-chinese-date-string date) "\n"))
7851 (with-output-to-temp-buffer "*Dates*"
7852 (princ s))
7853 (if (fboundp 'fit-window-to-buffer)
7854 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
7855
7856 ;;; Tags
7857
7858 (defun org-scan-tags (action matcher &optional todo-only)
7859 "Scan headline tags with inheritance and produce output ACTION.
7860 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
7861 evaluated, testing if a given set of tags qualifies a headline for
7862 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
7863 are included in the output."
7864 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
7865 (mapconcat 'regexp-quote
7866 (nreverse (cdr (reverse org-todo-keywords)))
7867 "\\|")
7868 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
7869 (props (list 'face nil
7870 'done-face 'org-done
7871 'undone-face nil
7872 'mouse-face 'highlight
7873 'keymap org-agenda-keymap
7874 'help-echo
7875 (format "mouse-2 or RET jump to org file %s"
7876 (abbreviate-file-name buffer-file-name))))
7877 lspos
7878 tags tags-list tags-alist (llast 0) rtn level category i txt
7879 todo marker)
7880
7881 (save-excursion
7882 (goto-char (point-min))
7883 (when (eq action 'sparse-tree) (org-overview))
7884 (while (re-search-forward re nil t)
7885 (setq todo (if (match-end 1) (match-string 2))
7886 tags (if (match-end 4) (match-string 4)))
7887 (goto-char (setq lspos (1+ (match-beginning 0))))
7888 (setq level (funcall outline-level)
7889 category (org-get-category))
7890 (setq i llast llast level)
7891 ;; remove tag lists from same and sublevels
7892 (while (>= i level)
7893 (when (setq entry (assoc i tags-alist))
7894 (setq tags-alist (delete entry tags-alist)))
7895 (setq i (1- i)))
7896 ;; add the nex tags
7897 (when tags
7898 (setq tags (mapcar 'downcase (org-split-string tags ":"))
7899 tags-alist
7900 (cons (cons level tags) tags-alist)))
7901 ;; compile tags for current headline
7902 (setq tags-list
7903 (if org-use-tag-inheritance
7904 (apply 'append (mapcar 'cdr tags-alist))
7905 tags))
7906 (when (and (or (not todo-only) todo)
7907 (eval matcher))
7908 ;; list this headline
7909 (if (eq action 'sparse-tree)
7910 (progn
7911 (org-show-hierarchy-above))
7912 (setq txt (org-format-agenda-item
7913 ""
7914 (concat
7915 (if org-tags-match-list-sublevels
7916 (make-string (1- level) ?.) "")
7917 (org-get-heading))
7918 category tags-list))
7919 (goto-char lspos)
7920 (setq marker (org-agenda-new-marker))
7921 (org-add-props txt props
7922 'org-marker marker 'org-hd-marker marker 'category category)
7923 (push txt rtn))
7924 ;; if we are to skip sublevels, jump to end of subtree
7925 (point)
7926 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
7927 (nreverse rtn)))
7928
7929 (defun org-tags-sparse-tree (&optional arg match)
7930 "Create a sparse tree according to tags search string MATCH.
7931 MATCH can contain positive and negative selection of tags, like
7932 \"+WORK+URGENT-WITHBOSS\"."
7933 (interactive "P")
7934 (let ((org-show-following-heading nil)
7935 (org-show-hierarchy-above nil))
7936 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
7937
7938 (defun org-make-tags-matcher (match)
7939 "Create the TAGS matcher form for the tags-selecting string MATCH."
7940 (unless match
7941 ;; Get a new match request, with completion
7942 (setq org-last-tags-completion-table
7943 (or (org-get-buffer-tags)
7944 org-last-tags-completion-table))
7945 (setq match (completing-read
7946 "Tags: " 'org-tags-completion-function nil nil nil
7947 'org-tags-history)))
7948 ;; parse the string and create a lisp form
7949 (let ((match0 match) minus tag mm matcher orterms term orlist)
7950 (setq orterms (org-split-string match "|"))
7951 (while (setq term (pop orterms))
7952 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
7953 (setq minus (and (match-end 1)
7954 (equal (match-string 1 term) "-"))
7955 tag (match-string 2 term)
7956 term (substring term (match-end 0))
7957 mm (list 'member (downcase tag) 'tags-list)
7958 mm (if minus (list 'not mm) mm))
7959 (push mm matcher))
7960 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
7961 orlist)
7962 (setq matcher nil))
7963 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
7964 ;; Return the string and lisp forms of the matcher
7965 (cons match0 matcher)))
7966
7967 ;;;###autoload
7968 (defun org-tags-view (&optional todo-only match keep-modes)
7969 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
7970 The prefix arg TODO-ONLY limits the search to TODO entries."
7971 (interactive "P")
7972 (org-agenda-maybe-reset-markers 'force)
7973 (org-compile-prefix-format org-agenda-prefix-format)
7974 (let* ((org-agenda-keep-modes keep-modes)
7975 (org-tags-match-list-sublevels
7976 (if todo-only t org-tags-match-list-sublevels))
7977 (win (selected-window))
7978 (completion-ignore-case t)
7979 rtn rtnall files file pos matcher
7980 buffer)
7981 (setq matcher (org-make-tags-matcher match)
7982 match (car matcher) matcher (cdr matcher))
7983 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
7984 (progn
7985 (delete-other-windows)
7986 (switch-to-buffer-other-window
7987 (get-buffer-create org-agenda-buffer-name))))
7988 (setq buffer-read-only nil)
7989 (erase-buffer)
7990 (org-agenda-mode) (setq buffer-read-only nil)
7991 (set (make-local-variable 'org-agenda-type) 'tags)
7992 (set (make-local-variable 'org-agenda-redo-command)
7993 (list 'org-tags-view (list 'quote todo-only)
7994 (list 'if 'current-prefix-arg nil match) t))
7995 (setq files (org-agenda-files)
7996 rtnall nil)
7997 (while (setq file (pop files))
7998 (catch 'nextfile
7999 (org-check-agenda-file file)
8000 (setq buffer (if (file-exists-p file)
8001 (org-get-agenda-file-buffer file)
8002 (error "No such file %s" file)))
8003 (if (not buffer)
8004 ;; If file does not exist, merror message to agenda
8005 (setq rtn (list
8006 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8007 rtnall (append rtnall rtn))
8008 (with-current-buffer buffer
8009 (unless (eq major-mode 'org-mode)
8010 (error "Agenda file %s is not in `org-mode'" file))
8011 (setq org-category-table (org-get-category-table))
8012 (save-excursion
8013 (save-restriction
8014 (if org-respect-restriction
8015 (if (org-region-active-p)
8016 ;; Respect a region to restrict search
8017 (narrow-to-region (region-beginning) (region-end)))
8018 ;; If we work for the calendar or many files,
8019 ;; get rid of any restriction
8020 (widen))
8021 (setq rtn (org-scan-tags 'agenda matcher todo-only))
8022 (setq rtnall (append rtnall rtn))))))))
8023 (insert "Headlines with TAGS match: ")
8024 (add-text-properties (point-min) (1- (point))
8025 (list 'face 'org-level-3))
8026 (setq pos (point))
8027 (insert match "\n")
8028 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
8029 (setq pos (point))
8030 (insert "Press `C-u r' to search again with new search string\n")
8031 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
8032 (when rtnall
8033 (insert (mapconcat 'identity rtnall "\n")))
8034 (goto-char (point-min))
8035 (setq buffer-read-only t)
8036 (org-fit-agenda-window)
8037 (if (not org-select-agenda-window) (select-window win))))
8038
8039 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8040 (defun org-set-tags (&optional arg just-align)
8041 "Set the tags for the current headline.
8042 With prefix ARG, realign all tags in headings in the current buffer."
8043 (interactive "P")
8044 (let* ((re (concat "^" outline-regexp))
8045 (col (current-column))
8046 (current (org-get-tags))
8047 table current-tags inherited-tags ; computed below when needed
8048 tags hd empty invis)
8049 (if arg
8050 (save-excursion
8051 (goto-char (point-min))
8052 (while (re-search-forward re nil t)
8053 (org-set-tags nil t))
8054 (message "All tags realigned to column %d" org-tags-column))
8055 (if just-align
8056 (setq tags current)
8057 (setq table (or org-tag-alist (org-get-buffer-tags))
8058 org-last-tags-completion-table table
8059 current-tags (org-split-string current ":")
8060 inherited-tags (nreverse
8061 (nthcdr (length current-tags)
8062 (nreverse (org-get-tags-at))))
8063 tags
8064 (if (or (eq t org-use-fast-tag-selection)
8065 (and org-use-fast-tag-selection
8066 (delq nil (mapcar 'cdr table))))
8067 (org-fast-tag-selection current-tags inherited-tags table)
8068 (let ((org-add-colon-after-tag-completion t))
8069 (completing-read "Tags: " 'org-tags-completion-function
8070 nil nil current 'org-tags-history))))
8071 (while (string-match "[-+&]+" tags)
8072 (setq tags (replace-match ":" t t tags))))
8073
8074 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
8075 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8076 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8077 (if (equal current "")
8078 (progn
8079 (end-of-line 1)
8080 (or empty (insert-before-markers " ")))
8081 (beginning-of-line 1)
8082 (setq invis (org-invisible-p))
8083 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
8084 (setq hd (match-string 1))
8085 (delete-region (match-beginning 0) (match-end 0))
8086 (insert-before-markers (org-trim hd) (if empty "" " ")))
8087 (unless (equal tags "")
8088 (move-to-column (max (current-column)
8089 (if (> org-tags-column 0)
8090 org-tags-column
8091 (- (- org-tags-column) (length tags))))
8092 t)
8093 (insert-before-markers tags)
8094 (if (and (not invis) (org-invisible-p))
8095 (outline-flag-region (point-at-bol) (point) nil)))
8096 (move-to-column col))))
8097
8098 (defun org-tags-completion-function (string predicate &optional flag)
8099 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8100 (confirm (lambda (x) (stringp (car x)))))
8101 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8102 (setq s1 (match-string 1 string)
8103 s2 (match-string 2 string))
8104 (setq s1 "" s2 string))
8105 (cond
8106 ((eq flag nil)
8107 ;; try completion
8108 (setq rtn (try-completion s2 ctable confirm))
8109 (if (stringp rtn)
8110 (concat s1 s2 (substring rtn (length s2))
8111 (if (and org-add-colon-after-tag-completion
8112 (assoc rtn ctable))
8113 ":" "")))
8114 )
8115 ((eq flag t)
8116 ;; all-completions
8117 (all-completions s2 ctable confirm)
8118 )
8119 ((eq flag 'lambda)
8120 ;; exact match?
8121 (assoc s2 ctable)))
8122 ))
8123
8124 (defun org-fast-tag-insert (kwd tags face &optional end)
8125 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
8126 (insert (format "%-12s" (concat kwd ":"))
8127 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
8128 (or end "")))
8129
8130 (defun org-fast-tag-selection (current inherited table)
8131 "Fast tag selection with single keys.
8132 CURRENT is the current list of tags in the headline, INHERITED is the
8133 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
8134 possibly with grouping information.
8135 If the keys are nil, a-z are automatically assigned.
8136 Returns the new tags string, or nil to not change the current settings."
8137 (let* ((maxlen (apply 'max (mapcar
8138 (lambda (x)
8139 (if (stringp (car x)) (string-width (car x)) 0))
8140 table)))
8141 (fwidth (+ maxlen 3 1 3))
8142 (ncol (/ (- (window-width) 4) fwidth))
8143 (i-face 'org-done)
8144 (c-face 'org-tag)
8145 tg cnt e c char c1 c2 ntable tbl rtn
8146 groups ingroup)
8147 (save-window-excursion
8148 (delete-other-windows)
8149 (split-window-vertically)
8150 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
8151 (erase-buffer)
8152 (org-fast-tag-insert "Inherited" inherited i-face "\n")
8153 (org-fast-tag-insert "Current" current c-face "\n\n")
8154 (setq tbl table char ?a cnt 0)
8155 (while (setq e (pop tbl))
8156 (cond
8157 ((equal e '(:startgroup))
8158 (push '() groups) (setq ingroup t)
8159 (when (not (= cnt 0))
8160 (setq cnt 0)
8161 (insert "\n"))
8162 (insert "{ "))
8163 ((equal e '(:endgroup))
8164 (setq ingroup nil cnt 0)
8165 (insert "}\n"))
8166 (t
8167 (setq tg (car e) c2 nil)
8168 (if (cdr e)
8169 (setq c (cdr e))
8170 ;; automatically assign a character.
8171 (setq c1 (string-to-char
8172 (downcase (substring
8173 tg (if (= (string-to-char tg) ?@) 1 0)))))
8174 (if (or (rassoc c1 ntable) (rassoc c1 table))
8175 (while (or (rassoc char ntable) (rassoc char table))
8176 (setq char (1+ char)))
8177 (setq c2 c1))
8178 (setq c (or c2 char)))
8179 (if ingroup (push tg (car groups)))
8180 (setq tg (org-add-props tg nil 'face
8181 (cond
8182 ((member tg current) c-face)
8183 ((member tg inherited) i-face)
8184 (t nil))))
8185 (if (and (= cnt 0) (not ingroup)) (insert " "))
8186 (insert "[" c "] " tg (make-string
8187 (- fwidth 4 (length tg)) ?\ ))
8188 (push (cons tg c) ntable)
8189 (when (= (setq cnt (1+ cnt)) ncol)
8190 (insert "\n")
8191 (if ingroup (insert " "))
8192 (setq cnt 0)))))
8193 (setq ntable (nreverse ntable))
8194 (insert "\n")
8195 (goto-char (point-min))
8196 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
8197 (setq rtn
8198 (catch 'exit
8199 (while t
8200 (message "[key]:Toggle SPC: clear current RET accept%s"
8201 (if groups " [!] ignore goups" ""))
8202 (setq c (read-char-exclusive))
8203 (cond
8204 ((= c ?\r) (throw 'exit t))
8205 ((= c ?!)
8206 (setq groups nil)
8207 (goto-char (point-min))
8208 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
8209 ((or (= c ?\C-g)
8210 (and (= c ?q) (not (rassoc c ntable))))
8211 (setq quit-flag t))
8212 ((= c ?\ ) (setq current nil))
8213 ((setq e (rassoc c ntable) tg (car e))
8214 (if (member tg current)
8215 (setq current (delete tg current))
8216 (loop for g in groups do
8217 (if (member tg g)
8218 (mapcar (lambda (x)
8219 (setq current (delete x current)))
8220 g)))
8221 (setq current (cons tg current)))))
8222 ;; Create a sorted list
8223 (setq current
8224 (sort current
8225 (lambda (a b)
8226 (assoc b (cdr (memq (assoc a ntable) ntable))))))
8227 (goto-char (point-min))
8228 (beginning-of-line 2)
8229 (delete-region (point) (point-at-eol))
8230 (org-fast-tag-insert "Current" current c-face)
8231 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
8232 (setq tg (match-string 1))
8233 (add-text-properties (match-beginning 1) (match-end 1)
8234 (list 'face
8235 (cond
8236 ((member tg current) c-face)
8237 ((member tg inherited) i-face)
8238 (t nil)))))
8239 (goto-char (point-min)))))
8240 (if rtn
8241 (mapconcat 'identity current ":")
8242 nil))))
8243
8244 (defun org-get-tags ()
8245 "Get the TAGS string in the current headline."
8246 (unless (org-on-heading-p)
8247 (error "Not on a heading"))
8248 (save-excursion
8249 (beginning-of-line 1)
8250 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
8251 (org-match-string-no-properties 1)
8252 "")))
8253
8254 (defun org-get-buffer-tags ()
8255 "Get a table of all tags used in the buffer, for completion."
8256 (let (tags)
8257 (save-excursion
8258 (goto-char (point-min))
8259 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
8260 (mapc (lambda (x) (add-to-list 'tags x))
8261 (org-split-string (org-match-string-no-properties 1) ":"))))
8262 (mapcar 'list tags)))
8263
8264 ;;; Link Stuff
8265
8266 (defvar org-create-file-search-functions nil
8267 "List of functions to construct the right search string for a file link.
8268 These functions are called in turn with point at the location to
8269 which the link should point.
8270
8271 A function in the hook should first test if it would like to
8272 handle this file type, for example by checking the major-mode or
8273 the file extension. If it decides not to handle this file, it
8274 should just return nil to give other functions a chance. If it
8275 does handle the file, it must return the search string to be used
8276 when following the link. The search string will be part of the
8277 file link, given after a double colon, and `org-open-at-point'
8278 will automatically search for it. If special measures must be
8279 taken to make the search successful, another function should be
8280 added to the companion hook `org-execute-file-search-functions',
8281 which see.
8282
8283 A function in this hook may also use `setq' to set the variable
8284 `description' to provide a suggestion for the descriptive text to
8285 be used for this link when it gets inserted into an Org-mode
8286 buffer with \\[org-insert-link].")
8287
8288 (defvar org-execute-file-search-functions nil
8289 "List of functions to execute a file search triggered by a link.
8290
8291 Functions added to this hook must accept a single argument, the
8292 search string that was part of the file link, the part after the
8293 double colon. The function must first check if it would like to
8294 handle this search, for example by checking the major-mode or the
8295 file extension. If it decides not to handle this search, it
8296 should just return nil to give other functions a chance. If it
8297 does handle the search, it must return a non-nil value to keep
8298 other functions from trying.
8299
8300 Each function can access the current prefix argument through the
8301 variable `current-prefix-argument'. Note that a single prefix is
8302 used to force opening a link in Emacs, so it may be good to only
8303 use a numeric or double prefix to guide the search function.
8304
8305 In case this is needed, a function in this hook can also restore
8306 the window configuration before `org-open-at-point' was called using:
8307
8308 (set-window-configuration org-window-config-before-follow-link)")
8309
8310 (defun org-find-file-at-mouse (ev)
8311 "Open file link or URL at mouse."
8312 (interactive "e")
8313 (mouse-set-point ev)
8314 (org-open-at-point 'in-emacs))
8315
8316 (defun org-open-at-mouse (ev)
8317 "Open file link or URL at mouse."
8318 (interactive "e")
8319 (mouse-set-point ev)
8320 (org-open-at-point))
8321
8322 (defvar org-window-config-before-follow-link nil
8323 "The window configuration before following a link.
8324 This is saved in case the need arises to restore it.")
8325
8326 (defun org-open-at-point (&optional in-emacs)
8327 "Open link at or after point.
8328 If there is no link at point, this function will search forward up to
8329 the end of the current subtree.
8330 Normally, files will be opened by an appropriate application. If the
8331 optional argument IN-EMACS is non-nil, Emacs will visit the file."
8332 (interactive "P")
8333 (setq org-window-config-before-follow-link (current-window-configuration))
8334 (org-remove-occur-highlights nil nil t)
8335 (if (org-at-timestamp-p)
8336 (org-agenda-list nil (time-to-days (org-time-string-to-time
8337 (substring (match-string 1) 0 10)))
8338 1)
8339 (let (type path link line search (pos (point)))
8340 (catch 'match
8341 (save-excursion
8342 (skip-chars-forward "^]\n\r")
8343 (when (and (re-search-backward "\\[\\[" nil t)
8344 (looking-at org-bracket-link-regexp)
8345 (<= (match-beginning 0) pos)
8346 (>= (match-end 0) pos))
8347 (setq link (org-link-unescape (org-match-string-no-properties 1)))
8348 (while (string-match " *\n *" link)
8349 (setq link (replace-match " " t t link)))
8350 (if (string-match org-link-re-with-space2 link)
8351 (setq type (match-string 1 link)
8352 path (match-string 2 link))
8353 (setq type "thisfile"
8354 path link))
8355 (throw 'match t)))
8356
8357 (when (get-text-property (point) 'org-linked-text)
8358 (setq type "thisfile"
8359 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8360 (1+ (point)) (point))
8361 path (buffer-substring
8362 (previous-single-property-change pos 'org-linked-text)
8363 (next-single-property-change pos 'org-linked-text)))
8364 (throw 'match t))
8365
8366 (save-excursion
8367 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
8368 (if (equal (char-before) ?<) (backward-char 1))
8369 (when (or (looking-at org-angle-link-re)
8370 (looking-at org-plain-link-re)
8371 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
8372 (re-search-forward org-plain-link-re (point-at-eol) t))
8373 (<= (match-beginning 0) pos)
8374 (>= (match-end 0) pos)))
8375 (setq type (match-string 1)
8376 path (match-string 2))
8377 (throw 'match t)))
8378 (save-excursion
8379 (skip-chars-backward "^ \t\n\r")
8380 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
8381 (setq type "tags"
8382 path (match-string 1))
8383 (while (string-match ":" path)
8384 (setq path (replace-match "+" t t path)))
8385 (throw 'match t)))
8386 (save-excursion
8387 (skip-chars-backward "a-zA-Z_")
8388 (when (and (memq 'camel org-activate-links)
8389 (looking-at org-camel-regexp))
8390 (setq type "camel" path (match-string 0))
8391 (if (equal (char-before) ?*)
8392 (setq path (concat "*" path))))
8393 (throw 'match t)))
8394 (unless path
8395 (error "No link found"))
8396 ;; Remove any trailing spaces in path
8397 (if (string-match " +\\'" path)
8398 (setq path (replace-match "" t t path)))
8399
8400 (cond
8401
8402 ((member type '("http" "https" "ftp" "mailto" "news"))
8403 (browse-url (concat type ":" path)))
8404
8405 ((string= type "tags")
8406 (org-tags-view in-emacs path))
8407 ((or (string= type "camel")
8408 (string= type "thisfile"))
8409 (org-mark-ring-push)
8410 (org-link-search
8411 path
8412 (cond ((equal in-emacs '(4)) 'occur)
8413 ((equal in-emacs '(16)) 'org-occur)
8414 (t nil))))
8415
8416 ((string= type "file")
8417 (if (string-match "::\\([0-9]+\\)\\'" path)
8418 (setq line (string-to-number (match-string 1 path))
8419 path (substring path 0 (match-beginning 0)))
8420 (if (string-match "::\\(.+\\)\\'" path)
8421 (setq search (match-string 1 path)
8422 path (substring path 0 (match-beginning 0)))))
8423 (org-open-file path in-emacs line search))
8424
8425 ((string= type "news")
8426 (org-follow-gnus-link path))
8427
8428 ((string= type "bbdb")
8429 (org-follow-bbdb-link path))
8430
8431 ((string= type "info")
8432 (org-follow-info-link path))
8433
8434 ((string= type "gnus")
8435 (let (group article)
8436 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8437 (error "Error in Gnus link"))
8438 (setq group (match-string 1 path)
8439 article (match-string 3 path))
8440 (org-follow-gnus-link group article)))
8441
8442 ((string= type "vm")
8443 (let (folder article)
8444 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8445 (error "Error in VM link"))
8446 (setq folder (match-string 1 path)
8447 article (match-string 3 path))
8448 ;; in-emacs is the prefix arg, will be interpreted as read-only
8449 (org-follow-vm-link folder article in-emacs)))
8450
8451 ((string= type "wl")
8452 (let (folder article)
8453 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8454 (error "Error in Wanderlust link"))
8455 (setq folder (match-string 1 path)
8456 article (match-string 3 path))
8457 (org-follow-wl-link folder article)))
8458
8459 ((string= type "mhe")
8460 (let (folder article)
8461 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8462 (error "Error in MHE link"))
8463 (setq folder (match-string 1 path)
8464 article (match-string 3 path))
8465 (org-follow-mhe-link folder article)))
8466
8467 ((string= type "rmail")
8468 (let (folder article)
8469 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8470 (error "Error in RMAIL link"))
8471 (setq folder (match-string 1 path)
8472 article (match-string 3 path))
8473 (org-follow-rmail-link folder article)))
8474
8475 ((string= type "shell")
8476 (let ((cmd path))
8477 (while (string-match "@{" cmd)
8478 (setq cmd (replace-match "<" t t cmd)))
8479 (while (string-match "@}" cmd)
8480 (setq cmd (replace-match ">" t t cmd)))
8481 (if (or (not org-confirm-shell-link-function)
8482 (funcall org-confirm-shell-link-function
8483 (format "Execute \"%s\" in shell? "
8484 (org-add-props cmd nil
8485 'face 'org-warning))))
8486 (progn
8487 (message "Executing %s" cmd)
8488 (shell-command cmd))
8489 (error "Abort"))))
8490
8491 ((string= type "elisp")
8492 (let ((cmd path))
8493 (if (or (not org-confirm-elisp-link-function)
8494 (funcall org-confirm-elisp-link-function
8495 (format "Execute \"%s\" as elisp? "
8496 (org-add-props cmd nil
8497 'face 'org-warning))))
8498 (message "%s => %s" cmd (eval (read cmd)))
8499 (error "Abort"))))
8500
8501 (t
8502 (browse-url-at-point))))))
8503
8504 (defun org-link-search (s &optional type)
8505 "Search for a link search option.
8506 When S is a CamelCaseWord, search for a target, or for a sentence containing
8507 the words. If S is surrounded by forward slashes, it is interpreted as a
8508 regular expression. In org-mode files, this will create an `org-occur'
8509 sparse tree. In ordinary files, `occur' will be used to list matches.
8510 If the current buffer is in `dired-mode', grep will be used to search
8511 in all files."
8512 (let ((case-fold-search t)
8513 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8514 (pos (point))
8515 (pre "") (post "")
8516 words re0 re1 re2 re3 re4 re5 re2a reall camel)
8517 (cond
8518 ;; First check if there are any special
8519 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8520 ;; Now try the builtin stuff
8521 ((save-excursion
8522 (goto-char (point-min))
8523 (and
8524 (re-search-forward
8525 (concat "<<" (regexp-quote s0) ">>") nil t)
8526 (setq pos (match-beginning 0))))
8527 ;; There is an exact target for this
8528 (goto-char pos))
8529 ((string-match "^/\\(.*\\)/$" s)
8530 ;; A regular expression
8531 (cond
8532 ((eq major-mode 'org-mode)
8533 (org-occur (match-string 1 s)))
8534 ;;((eq major-mode 'dired-mode)
8535 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8536 (t (org-do-occur (match-string 1 s)))))
8537 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
8538 t)
8539 ;; A camel or a normal search string
8540 (when (equal (string-to-char s) ?*)
8541 ;; Anchor on headlines, post may include tags.
8542 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
8543 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
8544 s (substring s 1)))
8545 (remove-text-properties
8546 0 (length s)
8547 '(face nil mouse-face nil keymap nil fontified nil) s)
8548 ;; Make a series of regular expressions to find a match
8549 (setq words
8550 (if camel
8551 (org-camel-to-words s)
8552 (org-split-string s "[ \n\r\t]+"))
8553 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8554 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
8555 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8556 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8557 re1 (concat pre re2 post)
8558 re3 (concat pre re4 post)
8559 re5 (concat pre ".*" re4)
8560 re2 (concat pre re2)
8561 re2a (concat pre re2a)
8562 re4 (concat pre re4)
8563 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8564 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8565 re5 "\\)"
8566 ))
8567 (cond
8568 ((eq type 'org-occur) (org-occur reall))
8569 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8570 (t (goto-char (point-min))
8571 (if (or (org-search-not-link re0 nil t)
8572 (org-search-not-link re1 nil t)
8573 (org-search-not-link re2 nil t)
8574 (org-search-not-link re2a nil t)
8575 (org-search-not-link re3 nil t)
8576 (org-search-not-link re4 nil t)
8577 (org-search-not-link re5 nil t)
8578 )
8579 (goto-char (match-beginning 1))
8580 (goto-char pos)
8581 (error "No match")))))
8582 (t
8583 ;; Normal string-search
8584 (goto-char (point-min))
8585 (if (search-forward s nil t)
8586 (goto-char (match-beginning 0))
8587 (error "No match"))))
8588 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
8589
8590 (defun org-search-not-link (&rest args)
8591 "Execute `re-search-forward', but only accept matches that are not a link."
8592 (catch 'exit
8593 (let ((pos (point)) p1)
8594 (while (apply 're-search-forward args)
8595 (setq p1 (point))
8596 (if (not (save-match-data
8597 (and (re-search-backward "\\[\\[" nil t)
8598 (looking-at org-bracket-link-regexp)
8599 (<= (match-beginning 0) p1)
8600 (>= (match-end 0) p1))))
8601 (progn (goto-char (match-end 0))
8602 (throw 'exit (point)))
8603 (goto-char (match-end 0)))))))
8604
8605 (defun org-do-occur (regexp &optional cleanup)
8606 "Call the Emacs command `occur'.
8607 If CLEANUP is non-nil, remove the printout of the regular expression
8608 in the *Occur* buffer. This is useful if the regex is long and not useful
8609 to read."
8610 (occur regexp)
8611 (when cleanup
8612 (let ((cwin (selected-window)) win beg end)
8613 (when (setq win (get-buffer-window "*Occur*"))
8614 (select-window win))
8615 (goto-char (point-min))
8616 (when (re-search-forward "match[a-z]+" nil t)
8617 (setq beg (match-end 0))
8618 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8619 (setq end (1- (match-beginning 0)))))
8620 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
8621 (goto-char (point-min))
8622 (select-window cwin))))
8623
8624 (defvar org-mark-ring nil
8625 "Mark ring for positions before jumps in Org-mode.")
8626 (defvar org-mark-ring-last-goto nil
8627 "Last position in the mark ring used to go back.")
8628 ;; Fill and close the ring
8629 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8630 (loop for i from 1 to org-mark-ring-length do
8631 (push (make-marker) org-mark-ring))
8632 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8633 org-mark-ring)
8634
8635 (defun org-mark-ring-push (&optional pos buffer)
8636 "Put the current position or POS into the mark ring and rotate it."
8637 (interactive)
8638 (setq pos (or pos (point)))
8639 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8640 (move-marker (car org-mark-ring)
8641 (or pos (point))
8642 (or buffer (current-buffer)))
8643 (message
8644 (substitute-command-keys
8645 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8646
8647 (defun org-mark-ring-goto (&optional n)
8648 "Jump to the previous position in the mark ring.
8649 With prefix arg N, jump back that many stored positions. When
8650 called several times in succession, walk through the entire ring.
8651 Org-mode commands jumping to a different position in the current file,
8652 or to another Org-mode file, automatically push the old position
8653 onto the ring."
8654 (interactive "p")
8655 (let (p m)
8656 (if (eq last-command this-command)
8657 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8658 (setq p org-mark-ring))
8659 (setq org-mark-ring-last-goto p)
8660 (setq m (car p))
8661 (switch-to-buffer (marker-buffer m))
8662 (goto-char m)
8663 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
8664
8665 (defun org-camel-to-words (s)
8666 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
8667 (let ((case-fold-search nil)
8668 words)
8669 (while (string-match "[a-z][A-Z]" s)
8670 (push (substring s 0 (1+ (match-beginning 0))) words)
8671 (setq s (substring s (1+ (match-beginning 0)))))
8672 (nreverse (cons s words))))
8673
8674 (defun org-remove-angle-brackets (s)
8675 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8676 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8677 s)
8678 (defun org-add-angle-brackets (s)
8679 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8680 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8681 s)
8682
8683 (defun org-follow-bbdb-link (name)
8684 "Follow a BBDB link to NAME."
8685 (require 'bbdb)
8686 (let ((inhibit-redisplay t)
8687 (bbdb-electric-p nil))
8688 (catch 'exit
8689 ;; Exact match on name
8690 (bbdb-name (concat "\\`" name "\\'") nil)
8691 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8692 ;; Exact match on name
8693 (bbdb-company (concat "\\`" name "\\'") nil)
8694 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8695 ;; Partial match on name
8696 (bbdb-name name nil)
8697 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8698 ;; Partial match on company
8699 (bbdb-company name nil)
8700 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8701 ;; General match including network address and notes
8702 (bbdb name nil)
8703 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
8704 (delete-window (get-buffer-window "*BBDB*"))
8705 (error "No matching BBDB record")))))
8706
8707
8708 (defun org-follow-info-link (name)
8709 "Follow an info file & node link to NAME."
8710 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
8711 (string-match "\\(.*\\)" name))
8712 (progn
8713 (require 'info)
8714 (if (match-string 2 name) ; If there isn't a node, choose "Top"
8715 (Info-find-node (match-string 1 name) (match-string 2 name))
8716 (Info-find-node (match-string 1 name) "Top")))
8717 (message (concat "Could not open: " name))))
8718
8719 (defun org-follow-gnus-link (&optional group article)
8720 "Follow a Gnus link to GROUP and ARTICLE."
8721 (require 'gnus)
8722 (funcall (cdr (assq 'gnus org-link-frame-setup)))
8723 (if group (gnus-fetch-group group))
8724 (if article
8725 (or (gnus-summary-goto-article article nil 'force)
8726 (if (fboundp 'gnus-summary-insert-cached-articles)
8727 (progn
8728 (gnus-summary-insert-cached-articles)
8729 (gnus-summary-goto-article article nil 'force))
8730 (message "Message could not be found.")))))
8731
8732 (defun org-follow-vm-link (&optional folder article readonly)
8733 "Follow a VM link to FOLDER and ARTICLE."
8734 (require 'vm)
8735 (setq article (org-add-angle-brackets article))
8736 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
8737 ;; ange-ftp or efs or tramp access
8738 (let ((user (or (match-string 1 folder) (user-login-name)))
8739 (host (match-string 2 folder))
8740 (file (match-string 3 folder)))
8741 (cond
8742 ((featurep 'tramp)
8743 ;; use tramp to access the file
8744 (if (featurep 'xemacs)
8745 (setq folder (format "[%s@%s]%s" user host file))
8746 (setq folder (format "/%s@%s:%s" user host file))))
8747 (t
8748 ;; use ange-ftp or efs
8749 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
8750 (setq folder (format "/%s@%s:%s" user host file))))))
8751 (when folder
8752 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
8753 (sit-for 0.1)
8754 (when article
8755 (vm-select-folder-buffer)
8756 (widen)
8757 (let ((case-fold-search t))
8758 (goto-char (point-min))
8759 (if (not (re-search-forward
8760 (concat "^" "message-id: *" (regexp-quote article))))
8761 (error "Could not find the specified message in this folder"))
8762 (vm-isearch-update)
8763 (vm-isearch-narrow)
8764 (vm-beginning-of-message)
8765 (vm-summarize)))))
8766
8767 (defun org-follow-wl-link (folder article)
8768 "Follow a Wanderlust link to FOLDER and ARTICLE."
8769 (setq article (org-add-angle-brackets article))
8770 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
8771 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
8772 (wl-summary-redisplay))
8773
8774 (defun org-follow-rmail-link (folder article)
8775 "Follow an RMAIL link to FOLDER and ARTICLE."
8776 (setq article (org-add-angle-brackets article))
8777 (let (message-number)
8778 (save-excursion
8779 (save-window-excursion
8780 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
8781 (setq message-number
8782 (save-restriction
8783 (widen)
8784 (goto-char (point-max))
8785 (if (re-search-backward
8786 (concat "^Message-ID:\\s-+" (regexp-quote
8787 (or article "")))
8788 nil t)
8789 (rmail-what-message))))))
8790 (if message-number
8791 (progn
8792 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
8793 (rmail-show-message message-number)
8794 message-number)
8795 (error "Message not found"))))
8796
8797 ;; mh-e integration based on planner-mode
8798 (defun org-mhe-get-message-real-folder ()
8799 "Return the name of the current message real folder, so if you use
8800 sequences, it will now work."
8801 (save-excursion
8802 (let* ((folder
8803 (if (equal major-mode 'mh-folder-mode)
8804 mh-current-folder
8805 ;; Refer to the show buffer
8806 mh-show-folder-buffer))
8807 (end-index
8808 (if (boundp 'mh-index-folder)
8809 (min (length mh-index-folder) (length folder))))
8810 )
8811 ;; a simple test on mh-index-data does not work, because
8812 ;; mh-index-data is always nil in a show buffer.
8813 (if (and (boundp 'mh-index-folder)
8814 (string= mh-index-folder (substring folder 0 end-index)))
8815 (if (equal major-mode 'mh-show-mode)
8816 (save-window-excursion
8817 (when (buffer-live-p (get-buffer folder))
8818 (progn
8819 (pop-to-buffer folder)
8820 (org-mhe-get-message-folder-from-index)
8821 )
8822 ))
8823 (org-mhe-get-message-folder-from-index)
8824 )
8825 folder
8826 )
8827 )))
8828
8829 (defun org-mhe-get-message-folder-from-index ()
8830 "Returns the name of the message folder in a index folder buffer."
8831 (save-excursion
8832 (mh-index-previous-folder)
8833 (re-search-forward "^\\(+.*\\)$" nil t)
8834 (message (match-string 1))))
8835
8836 (defun org-mhe-get-message-folder ()
8837 "Return the name of the current message folder. Be careful if you
8838 use sequences."
8839 (save-excursion
8840 (if (equal major-mode 'mh-folder-mode)
8841 mh-current-folder
8842 ;; Refer to the show buffer
8843 mh-show-folder-buffer)))
8844
8845 (defun org-mhe-get-message-num ()
8846 "Return the number of the current message. Be careful if you
8847 use sequences."
8848 (save-excursion
8849 (if (equal major-mode 'mh-folder-mode)
8850 (mh-get-msg-num nil)
8851 ;; Refer to the show buffer
8852 (mh-show-buffer-message-number))))
8853
8854 (defun org-mhe-get-header (header)
8855 "Return a header of the message in folder mode. This will create a
8856 show buffer for the corresponding message. If you have a more clever
8857 idea..."
8858 (let* ((folder (org-mhe-get-message-folder))
8859 (num (org-mhe-get-message-num))
8860 (buffer (get-buffer-create (concat "show-" folder)))
8861 (header-field))
8862 (with-current-buffer buffer
8863 (mh-display-msg num folder)
8864 (if (equal major-mode 'mh-folder-mode)
8865 (mh-header-display)
8866 (mh-show-header-display))
8867 (set-buffer buffer)
8868 (setq header-field (mh-get-header-field header))
8869 (if (equal major-mode 'mh-folder-mode)
8870 (mh-show)
8871 (mh-show-show))
8872 header-field)))
8873
8874 (defun org-follow-mhe-link (folder article)
8875 "Follow an MHE link to FOLDER and ARTICLE.
8876 If ARTICLE is nil FOLDER is shown. If the configuration variable
8877 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
8878 ARTICLE is searched in all folders. Indexed searches (swish++,
8879 namazu, and others supported by MH-E) will always search in all
8880 folders."
8881 (require 'mh-e)
8882 (require 'mh-search)
8883 (require 'mh-utils)
8884 (mh-find-path)
8885 (if (not article)
8886 (mh-visit-folder (mh-normalize-folder-name folder))
8887 (setq article (org-add-angle-brackets article))
8888 (mh-search-choose)
8889 (if (equal mh-searcher 'pick)
8890 (progn
8891 (mh-search folder (list "--message-id" article))
8892 (when (and org-mhe-search-all-folders
8893 (not (org-mhe-get-message-real-folder)))
8894 (kill-this-buffer)
8895 (mh-search "+" (list "--message-id" article))))
8896 (mh-search "+" article))
8897 (if (org-mhe-get-message-real-folder)
8898 (mh-show-msg 1)
8899 (kill-this-buffer)
8900 (error "Message not found"))))
8901
8902 ;; BibTeX links
8903
8904 ;; Use the custom search meachnism to construct and use search strings for
8905 ;; file links to BibTeX database entries.
8906
8907 (defun org-create-file-search-in-bibtex ()
8908 "Create the search string and description for a BibTeX database entry."
8909 (when (eq major-mode 'bibtex-mode)
8910 ;; yes, we want to construct this search string.
8911 ;; Make a good description for this entry, using names, year and the title
8912 ;; Put it into the `description' variable which is dynamically scoped.
8913 (let ((bibtex-autokey-names 1)
8914 (bibtex-autokey-names-stretch 1)
8915 (bibtex-autokey-name-case-convert-function 'identity)
8916 (bibtex-autokey-name-separator " & ")
8917 (bibtex-autokey-additional-names " et al.")
8918 (bibtex-autokey-year-length 4)
8919 (bibtex-autokey-name-year-separator " ")
8920 (bibtex-autokey-titlewords 3)
8921 (bibtex-autokey-titleword-separator " ")
8922 (bibtex-autokey-titleword-case-convert-function 'identity)
8923 (bibtex-autokey-titleword-length 'infty)
8924 (bibtex-autokey-year-title-separator ": "))
8925 (setq description (bibtex-generate-autokey)))
8926 ;; Now parse the entry, get the key and return it.
8927 (save-excursion
8928 (bibtex-beginning-of-entry)
8929 (cdr (assoc "=key=" (bibtex-parse-entry))))))
8930
8931 (defun org-execute-file-search-in-bibtex (s)
8932 "Find the link search string S as a key for a database entry."
8933 (when (eq major-mode 'bibtex-mode)
8934 ;; Yes, we want to do the search in this file.
8935 ;; We construct a regexp that searches for "@entrytype{" followed by the key
8936 (goto-char (point-min))
8937 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
8938 (regexp-quote s) "[ \t\n]*,") nil t)
8939 (goto-char (match-beginning 0)))
8940 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
8941 ;; Use double prefix to indicate that any web link should be browsed
8942 (let ((b (current-buffer)) (p (point)))
8943 ;; Restore the window configuration because we just use the web link
8944 (set-window-configuration org-window-config-before-follow-link)
8945 (save-excursion (set-buffer b) (goto-char p)
8946 (bibtex-url)))
8947 (recenter 0)) ; Move entry start to beginning of window
8948 ;; return t to indicate that the search is done.
8949 t))
8950
8951 ;; Finally add the functions to the right hooks.
8952 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
8953 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
8954
8955 ;; end of Bibtex link setup
8956
8957 (defun org-upgrade-old-links (&optional query-description)
8958 "Transfer old <...> style links to new [[...]] style links.
8959 With arg query-description, ask at each match for a description text to use
8960 for this link."
8961 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
8962 (save-excursion
8963 (goto-char (point-min))
8964 (let ((re (concat "\\([^[]\\)<\\("
8965 "\\(" (mapconcat 'identity org-link-types "\\|")
8966 "\\):"
8967 "[^" org-non-link-chars "]+\\)>"))
8968 l1 l2 (cnt 0))
8969 (while (re-search-forward re nil t)
8970 (setq cnt (1+ cnt)
8971 l1 (org-match-string-no-properties 2)
8972 l2 (save-match-data (org-link-escape l1)))
8973 (when query-description (setq l1 (read-string "Desc: " l1)))
8974 (if (equal l1 l2)
8975 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
8976 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
8977 (message "%d matches have beed treated" cnt))))
8978
8979 (defun org-open-file (path &optional in-emacs line search)
8980 "Open the file at PATH.
8981 First, this expands any special file name abbreviations. Then the
8982 configuration variable `org-file-apps' is checked if it contains an
8983 entry for this file type, and if yes, the corresponding command is launched.
8984 If no application is found, Emacs simply visits the file.
8985 With optional argument IN-EMACS, Emacs will visit the file.
8986 Optional LINE specifies a line to go to, optional SEARCH a string to
8987 search for. If LINE or SEARCH is given, the file will always be
8988 opened in Emacs.
8989 If the file does not exist, an error is thrown."
8990 (setq in-emacs (or in-emacs line search))
8991 (let* ((file (if (equal path "")
8992 buffer-file-name
8993 (convert-standard-filename (org-expand-file-name path))))
8994 (dirp (file-directory-p file))
8995 (dfile (downcase file))
8996 (old-buffer (current-buffer))
8997 (old-pos (point))
8998 (old-mode major-mode)
8999 ext cmd apps)
9000 (if (and (not (file-exists-p file))
9001 (not org-open-non-existing-files))
9002 (error "No such file: %s" file))
9003 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9004 (setq ext (match-string 1 dfile))
9005 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9006 (setq ext (match-string 1 dfile))))
9007 (setq apps (append org-file-apps (org-default-apps)))
9008 (if in-emacs
9009 (setq cmd 'emacs)
9010 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
9011 (cdr (assoc ext apps))
9012 (cdr (assoc t apps)))))
9013 (when (eq cmd 'mailcap)
9014 (require 'mailcap)
9015 (mailcap-parse-mailcaps)
9016 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9017 (command (mailcap-mime-info mime-type)))
9018 (if (stringp command)
9019 (setq cmd command)
9020 (setq cmd 'emacs))))
9021 (cond
9022 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9023 ;; Normalize use of quote, this can vary.
9024 (if (string-match "['\"]%s['\"]" cmd)
9025 (setq cmd (replace-match "'%s'" t t cmd)))
9026 (setq cmd (format cmd file))
9027 (save-window-excursion
9028 (shell-command (concat cmd " &"))))
9029 ((or (stringp cmd)
9030 (eq cmd 'emacs))
9031 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
9032 (funcall (cdr (assq 'file org-link-frame-setup)) file))
9033 (if line (goto-line line)
9034 (if search (org-link-search search))))
9035 ((consp cmd)
9036 (eval cmd))
9037 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9038 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
9039 (or (not (equal old-buffer (current-buffer)))
9040 (not (equal old-pos (point))))
9041 (org-mark-ring-push old-pos old-buffer))))
9042
9043 (defun org-default-apps ()
9044 "Return the default applications for this operating system."
9045 (cond
9046 ((eq system-type 'darwin)
9047 org-file-apps-defaults-macosx)
9048 ((eq system-type 'windows-nt)
9049 org-file-apps-defaults-windowsnt)
9050 (t org-file-apps-defaults-gnu)))
9051
9052 (defun org-expand-file-name (path)
9053 "Replace special path abbreviations and expand the file name."
9054 (expand-file-name path))
9055
9056
9057 (defvar org-insert-link-history nil
9058 "Minibuffer history for links inserted with `org-insert-link'.")
9059
9060 (defvar org-stored-links nil
9061 "Contains the links stored with `org-store-link'.")
9062
9063 ;;;###autoload
9064 (defun org-store-link (arg)
9065 "\\<org-mode-map>Store an org-link to the current location.
9066 This link can later be inserted into an org-buffer with
9067 \\[org-insert-link].
9068 For some link types, a prefix arg is interpreted:
9069 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9070 For file links, arg negates `org-context-in-file-links'."
9071 (interactive "P")
9072 (let (link cpltxt desc description search txt (pos (point)))
9073 (cond
9074
9075 ((eq major-mode 'bbdb-mode)
9076 (setq cpltxt (concat
9077 "bbdb:"
9078 (or (bbdb-record-name (bbdb-current-record))
9079 (bbdb-record-company (bbdb-current-record))))
9080 link (org-make-link cpltxt)))
9081
9082 ((eq major-mode 'Info-mode)
9083 (setq link (org-make-link "info:"
9084 (file-name-nondirectory Info-current-file)
9085 ":" Info-current-node))
9086 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9087 ":" Info-current-node)))
9088
9089 ((eq major-mode 'calendar-mode)
9090 (let ((cd (calendar-cursor-to-date)))
9091 (setq link
9092 (format-time-string
9093 (car org-time-stamp-formats)
9094 (apply 'encode-time
9095 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9096 nil nil nil))))))
9097
9098 ((or (eq major-mode 'vm-summary-mode)
9099 (eq major-mode 'vm-presentation-mode))
9100 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9101 (vm-follow-summary-cursor)
9102 (save-excursion
9103 (vm-select-folder-buffer)
9104 (let* ((message (car vm-message-pointer))
9105 (folder buffer-file-name)
9106 (subject (vm-su-subject message))
9107 (author (vm-su-full-name message))
9108 (message-id (vm-su-message-id message)))
9109 (setq message-id (org-remove-angle-brackets message-id))
9110 (setq folder (abbreviate-file-name folder))
9111 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9112 folder)
9113 (setq folder (replace-match "" t t folder)))
9114 (setq cpltxt (concat author " on: " subject))
9115 (setq link (org-make-link "vm:" folder "#" message-id)))))
9116
9117 ((eq major-mode 'wl-summary-mode)
9118 (let* ((msgnum (wl-summary-message-number))
9119 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9120 msgnum 'message-id))
9121 (wl-message-entity (elmo-msgdb-overview-get-entity
9122 msgnum (wl-summary-buffer-msgdb)))
9123 (author (wl-summary-line-from)) ; FIXME: correct?
9124 (subject "???")) ; FIXME:
9125 (setq message-id (org-remove-angle-brackets message-id))
9126 (setq cpltxt (concat author " on: " subject))
9127 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9128 "#" message-id))))
9129
9130 ((or (equal major-mode 'mh-folder-mode)
9131 (equal major-mode 'mh-show-mode))
9132 (let ((from-header (org-mhe-get-header "From:"))
9133 (to-header (org-mhe-get-header "To:"))
9134 (subject (org-mhe-get-header "Subject:")))
9135 (setq cpltxt (concat from-header " on: " subject))
9136 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9137 (org-remove-angle-brackets
9138 (org-mhe-get-header "Message-Id:"))))))
9139
9140 ((eq major-mode 'rmail-mode)
9141 (save-excursion
9142 (save-restriction
9143 (rmail-narrow-to-non-pruned-header)
9144 (let ((folder buffer-file-name)
9145 (message-id (mail-fetch-field "message-id"))
9146 (author (mail-fetch-field "from"))
9147 (subject (mail-fetch-field "subject")))
9148 (setq message-id (org-remove-angle-brackets message-id))
9149 (setq cpltxt (concat author " on: " subject))
9150 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9151
9152 ((eq major-mode 'gnus-group-mode)
9153 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9154 (gnus-group-group-name)) ; version
9155 ((fboundp 'gnus-group-name)
9156 (gnus-group-name))
9157 (t "???"))))
9158 (setq cpltxt (concat
9159 (if (org-xor arg org-usenet-links-prefer-google)
9160 "http://groups.google.com/groups?group="
9161 "gnus:")
9162 group)
9163 link (org-make-link cpltxt))))
9164
9165 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9166 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9167 (gnus-summary-beginning-of-article)
9168 (let* ((group (car gnus-article-current))
9169 (article (cdr gnus-article-current))
9170 (header (gnus-summary-article-header article))
9171 (author (mail-header-from header))
9172 (message-id (mail-header-id header))
9173 (date (mail-header-date header))
9174 (subject (gnus-summary-subject-string)))
9175 (setq cpltxt (concat author " on: " subject))
9176 (if (org-xor arg org-usenet-links-prefer-google)
9177 (setq link
9178 (concat
9179 cpltxt "\n "
9180 (format "http://groups.google.com/groups?as_umsgid=%s"
9181 (org-fixup-message-id-for-http message-id))))
9182 (setq link (org-make-link "gnus:" group
9183 "#" (number-to-string article))))))
9184
9185 ((eq major-mode 'w3-mode)
9186 (setq cpltxt (url-view-url t)
9187 link (org-make-link cpltxt)))
9188 ((eq major-mode 'w3m-mode)
9189 (setq cpltxt w3m-current-url
9190 link (org-make-link cpltxt)))
9191
9192 ((setq search (run-hook-with-args-until-success
9193 'org-create-file-search-functions))
9194 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9195 "::" search))
9196 (setq cpltxt (or description link)))
9197
9198 ((eq major-mode 'org-mode)
9199 ;; Just link to current headline
9200 (setq cpltxt (concat "file:"
9201 (abbreviate-file-name buffer-file-name)))
9202 ;; Add a context search string
9203 (when (org-xor org-context-in-file-links arg)
9204 ;; Check if we are on a target
9205 (if (save-excursion
9206 (skip-chars-forward "^>\n\r")
9207 (and (re-search-backward "<<" nil t)
9208 (looking-at "<<\\(.*?\\)>>")
9209 (<= (match-beginning 0) pos)
9210 (>= (match-end 0) pos)))
9211 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9212 (setq txt (cond
9213 ((org-on-heading-p) nil)
9214 ((org-region-active-p)
9215 (buffer-substring (region-beginning) (region-end)))
9216 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9217 (when (or (null txt) (string-match "\\S-" txt))
9218 (setq cpltxt
9219 (concat cpltxt "::"
9220 (if org-file-link-context-use-camel-case
9221 (org-make-org-heading-camel txt)
9222 (org-make-org-heading-search-string txt)))
9223 desc "NONE"))))
9224 (if (string-match "::\\'" cpltxt)
9225 (setq cpltxt (substring cpltxt 0 -2)))
9226 (setq link (org-make-link cpltxt)))
9227
9228 (buffer-file-name
9229 ;; Just link to this file here.
9230 (setq cpltxt (concat "file:"
9231 (abbreviate-file-name buffer-file-name)))
9232 ;; Add a context string
9233 (when (org-xor org-context-in-file-links arg)
9234 (setq txt (if (org-region-active-p)
9235 (buffer-substring (region-beginning) (region-end))
9236 (buffer-substring (point-at-bol) (point-at-eol))))
9237 ;; Only use search option if there is some text.
9238 (when (string-match "\\S-" txt)
9239 (setq cpltxt
9240 (concat cpltxt "::"
9241 (if org-file-link-context-use-camel-case
9242 (org-make-org-heading-camel txt)
9243 (org-make-org-heading-search-string txt)))
9244 desc "NONE")))
9245 (setq link (org-make-link cpltxt)))
9246
9247 ((interactive-p)
9248 (error "Cannot link to a buffer which is not visiting a file"))
9249
9250 (t (setq link nil)))
9251
9252 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9253 (setq link (or link cpltxt)
9254 desc (or desc cpltxt))
9255 (if (equal desc "NONE") (setq desc nil))
9256
9257 (if (and (interactive-p) link)
9258 (progn
9259 (setq org-stored-links
9260 (cons (list cpltxt link desc) org-stored-links))
9261 (message "Stored: %s" (or cpltxt link)))
9262 (org-make-link-string link desc))))
9263
9264 (defun org-make-org-heading-search-string (&optional string heading)
9265 "Make search string for STRING or current headline."
9266 (interactive)
9267 (let ((s (or string (org-get-heading))))
9268 (unless (and string (not heading))
9269 ;; We are using a headline, clean up garbage in there.
9270 (if (string-match org-todo-regexp s)
9271 (setq s (replace-match "" t t s)))
9272 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9273 (setq s (replace-match "" t t s)))
9274 (setq s (org-trim s))
9275 (if (string-match (concat "^\\(" org-quote-string "\\|"
9276 org-comment-string "\\)") s)
9277 (setq s (replace-match "" t t s)))
9278 (while (string-match org-ts-regexp s)
9279 (setq s (replace-match "" t t s))))
9280 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
9281 (setq s (replace-match " " t t s)))
9282 (or string (setq s (concat "*" s))) ; Add * for headlines
9283 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9284
9285 (defun org-make-org-heading-camel (&optional string heading)
9286 "Make a CamelCase string for STRING or the current headline."
9287 (interactive)
9288 (let ((s (or string (org-get-heading))))
9289 (unless (and string (not heading))
9290 ;; We are using a headline, clean up garbage in there.
9291 (if (string-match org-todo-regexp s)
9292 (setq s (replace-match "" t t s)))
9293 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9294 (setq s (replace-match "" t t s)))
9295 (setq s (org-trim s))
9296 (if (string-match (concat "^\\(" org-quote-string "\\|"
9297 org-comment-string "\\)") s)
9298 (setq s (replace-match "" t t s)))
9299 (while (string-match org-ts-regexp s)
9300 (setq s (replace-match "" t t s))))
9301 (while (string-match "[^a-zA-Z_ \t]+" s)
9302 (setq s (replace-match " " t t s)))
9303 (or string (setq s (concat "*" s))) ; Add * for headlines
9304 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
9305
9306 (defun org-make-link (&rest strings)
9307 "Concatenate STRINGS, format resulting string with `org-link-format'."
9308 (format org-link-format (apply 'concat strings)))
9309
9310 (defun org-make-link-string (link &optional description)
9311 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9312 (if (eq org-link-style 'plain)
9313 (if (equal description link)
9314 link
9315 (concat description "\n" link))
9316 (when (stringp description)
9317 ;; Remove brackets from the description, they are fatal.
9318 (while (string-match "\\[\\|\\]" description)
9319 (setq description (replace-match "" t t description))))
9320 (when (equal (org-link-escape link) description)
9321 ;; No description needed, it is identical
9322 (setq description nil))
9323 (when (and (not description)
9324 (not (equal link (org-link-escape link))))
9325 (setq description link))
9326 (concat "[[" (org-link-escape link) "]"
9327 (if description (concat "[" description "]") "")
9328 "]")))
9329
9330 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
9331 "Association list of escapes for some characters problematic in links.")
9332
9333 (defun org-link-escape (text)
9334 "Escape charaters in TEXT that are problematic for links."
9335 (when text
9336 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
9337 org-link-escape-chars "\\|")))
9338 (while (string-match re text)
9339 (setq text
9340 (replace-match
9341 (cdr (assoc (match-string 0 text) org-link-escape-chars))
9342 t t text)))
9343 text)))
9344
9345 (defun org-link-unescape (text)
9346 "Reverse the action of `org-link-escape'."
9347 (when text
9348 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
9349 org-link-escape-chars "\\|")))
9350 (while (string-match re text)
9351 (setq text
9352 (replace-match
9353 (car (rassoc (match-string 0 text) org-link-escape-chars))
9354 t t text)))
9355 text)))
9356
9357 (defun org-xor (a b)
9358 "Exclusive or."
9359 (if a (not b) b))
9360
9361 (defun org-get-header (header)
9362 "Find a header field in the current buffer."
9363 (save-excursion
9364 (goto-char (point-min))
9365 (let ((case-fold-search t) s)
9366 (cond
9367 ((eq header 'from)
9368 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
9369 (setq s (match-string 1)))
9370 (while (string-match "\"" s)
9371 (setq s (replace-match "" t t s)))
9372 (if (string-match "[<(].*" s)
9373 (setq s (replace-match "" t t s))))
9374 ((eq header 'message-id)
9375 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
9376 (setq s (match-string 1))))
9377 ((eq header 'subject)
9378 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
9379 (setq s (match-string 1)))))
9380 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
9381 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
9382 s)))
9383
9384
9385 (defun org-fixup-message-id-for-http (s)
9386 "Replace special characters in a message id, so it can be used in an http query."
9387 (while (string-match "<" s)
9388 (setq s (replace-match "%3C" t t s)))
9389 (while (string-match ">" s)
9390 (setq s (replace-match "%3E" t t s)))
9391 (while (string-match "@" s)
9392 (setq s (replace-match "%40" t t s)))
9393 s)
9394
9395 (defun org-insert-link (&optional complete-file)
9396 "Insert a link. At the prompt, enter the link.
9397
9398 Completion can be used to select a link previously stored with
9399 `org-store-link'. When the empty string is entered (i.e. if you just
9400 press RET at the prompt), the link defaults to the most recently
9401 stored link. As SPC triggers completion in the minibuffer, you need to
9402 use M-SPC or C-q SPC to force the insertion of a space character.
9403
9404 You will also be prompted for a description, and if one is given, it will
9405 be displayed in the buffer instead of the link.
9406
9407 If there is already a link at point, this command will allow you to edit link
9408 and description parts.
9409
9410 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
9411 selected using completion. The path to the file will be relative to
9412 the current directory if the file is in the current directory or a
9413 subdirectory. Otherwise, the link will be the absolute path as
9414 completed in the minibuffer (i.e. normally ~/path/to/file).
9415
9416 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
9417 is in the current directory or below."
9418 (interactive "P")
9419 (let (link desc entry remove file (pos (point)))
9420 (cond
9421 ((save-excursion
9422 (skip-chars-forward "^]\n\r")
9423 (and (re-search-backward "\\[\\[" nil t)
9424 (looking-at org-bracket-link-regexp)
9425 (<= (match-beginning 0) pos)
9426 (>= (match-end 0) pos)))
9427 ;; We do have a link at point, and we are going to edit it.
9428 (setq remove (list (match-beginning 0) (match-end 0)))
9429 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9430 (setq link (read-string "Link: "
9431 (org-link-unescape
9432 (org-match-string-no-properties 1)))))
9433 (complete-file
9434 ;; Completing read for file names.
9435 (setq file (read-file-name "File: "))
9436 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9437 (pwd1 (file-name-as-directory (abbreviate-file-name
9438 (expand-file-name ".")))))
9439 (cond
9440 ((equal complete-file '(16))
9441 (setq link (org-make-link
9442 "file:"
9443 (abbreviate-file-name (expand-file-name file)))))
9444 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9445 (setq link (org-make-link "file:" (match-string 1 file))))
9446 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9447 (expand-file-name file))
9448 (setq link (org-make-link
9449 "file:" (match-string 1 (expand-file-name file)))))
9450 (t (setq link (org-make-link "file:" file))))))
9451 (t
9452 ;; Read link, with completion for stored links.
9453 (setq link (org-completing-read
9454 "Link: " org-stored-links nil nil nil
9455 org-insert-link-history
9456 (or (car (car org-stored-links)))))
9457 (setq entry (assoc link org-stored-links))
9458 (if (not org-keep-stored-link-after-insertion)
9459 (setq org-stored-links (delq (assoc link org-stored-links)
9460 org-stored-links)))
9461 (setq link (if entry (nth 1 entry) link)
9462 desc (or desc (nth 2 entry)))))
9463
9464 (if (string-match org-plain-link-re link)
9465 ;; URL-like link, normalize the use of angular brackets.
9466 (setq link (org-make-link (org-remove-angle-brackets link))))
9467
9468 ;; Check if we are linking to the current file with a search option
9469 ;; If yes, simplify the link by using only the search option.
9470 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
9471 (let* ((path (match-string 1 link))
9472 (case-fold-search nil)
9473 (search (match-string 2 link)))
9474 (save-match-data
9475 (if (equal (file-truename buffer-file-name) (file-truename path))
9476 ;; We are linking to this same file, with a search option
9477 (setq link search)))))
9478
9479 ;; Check if we can/should use a relative path. If yes, simplify the link
9480 (when (string-match "\\<file:\\(.*\\)" link)
9481 (let* ((path (match-string 1 link))
9482 (case-fold-search nil))
9483 (cond
9484 ((eq org-link-file-path-type 'absolute)
9485 (setq path (abbreviate-file-name (expand-file-name path))))
9486 ((eq org-link-file-path-type 'noabbrev)
9487 (setq path (expand-file-name path)))
9488 ((eq org-link-file-path-type 'relative)
9489 (setq path (file-relative-name path)))
9490 (t
9491 (save-match-data
9492 (if (string-match (concat "^" (regexp-quote
9493 (file-name-as-directory
9494 (expand-file-name "."))))
9495 (expand-file-name path))
9496 ;; We are linking a file with relative path name.
9497 (setq path (substring (expand-file-name path)
9498 (match-end 0)))))))
9499 (setq link (concat "file:" path))))
9500
9501 (setq desc (read-string "Description: " desc))
9502 (unless (string-match "\\S-" desc) (setq desc nil))
9503 (if remove (apply 'delete-region remove))
9504 (insert (org-make-link-string link desc))))
9505
9506 (defun org-completing-read (&rest args)
9507 (let ((minibuffer-local-completion-map
9508 (copy-keymap minibuffer-local-completion-map)))
9509 (define-key minibuffer-local-completion-map " " 'self-insert-command)
9510 (apply 'completing-read args)))
9511
9512 ;;; Hooks for remember.el
9513
9514 (defvar org-finish-function nil)
9515
9516 ;;;###autoload
9517 (defun org-remember-annotation ()
9518 "Return a link to the current location as an annotation for remember.el.
9519 If you are using Org-mode files as target for data storage with
9520 remember.el, then the annotations should include a link compatible with the
9521 conventions in Org-mode. This function returns such a link."
9522 (org-store-link nil))
9523
9524 (defconst org-remember-help
9525 "Select a destination location for the note.
9526 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
9527 RET at beg-of-buf -> Append to file as level 2 headline
9528 RET on headline -> Store as sublevel entry to current headline
9529 <left>/<right> -> before/after current headline, same headings level")
9530
9531 ;;;###autoload
9532 (defun org-remember-apply-template ()
9533 "Initialize *remember* buffer with template, invoke `org-mode'.
9534 This function should be placed into `remember-mode-hook' and in fact requires
9535 to be run from that hook to fucntion properly."
9536 (if org-remember-templates
9537
9538 (let* ((entry (if (= (length org-remember-templates) 1)
9539 (cdar org-remember-templates)
9540 (message "Select template: %s"
9541 (mapconcat
9542 (lambda (x) (char-to-string (car x)))
9543 org-remember-templates " "))
9544 (cdr (assoc (read-char-exclusive) org-remember-templates))))
9545 (tpl (car entry))
9546 (file (if (consp (cdr entry)) (nth 1 entry)))
9547 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
9548 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
9549 (v-u (concat "[" (substring v-t 1 -1) "]"))
9550 (v-U (concat "[" (substring v-T 1 -1) "]"))
9551 (v-a annotation) ; defined in `remember-mode'
9552 (v-i initial) ; defined in `remember-mode'
9553 (v-n user-full-name)
9554 )
9555 (unless tpl (setq tpl "") (message "No template") (ding))
9556 (insert tpl) (goto-char (point-min))
9557 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
9558 (when (and initial (equal (match-string 0) "%i"))
9559 (save-match-data
9560 (let* ((lead (buffer-substring
9561 (point-at-bol) (match-beginning 0))))
9562 (setq v-i (mapconcat 'identity
9563 (org-split-string initial "\n")
9564 (concat "\n" lead))))))
9565 (replace-match
9566 (or (eval (intern (concat "v-" (match-string 1)))) "")
9567 t t))
9568 (let ((org-startup-folded nil)
9569 (org-startup-with-deadline-check nil))
9570 (org-mode))
9571 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
9572 (set (make-local-variable 'org-default-notes-file) file))
9573 (goto-char (point-min))
9574 (if (re-search-forward "%\\?" nil t) (replace-match "")))
9575 (let ((org-startup-folded nil)
9576 (org-startup-with-deadline-check nil))
9577 (org-mode)))
9578 (set (make-local-variable 'org-finish-function) 'remember-buffer))
9579
9580 ;;;###autoload
9581 (defun org-remember-handler ()
9582 "Store stuff from remember.el into an org file.
9583 First prompts for an org file. If the user just presses return, the value
9584 of `org-default-notes-file' is used.
9585 Then the command offers the headings tree of the selected file in order to
9586 file the text at a specific location.
9587 You can either immediately press RET to get the note appended to the
9588 file, or you can use vertical cursor motion and visibility cycling (TAB) to
9589 find a better place. Then press RET or <left> or <right> in insert the note.
9590
9591 Key Cursor position Note gets inserted
9592 -----------------------------------------------------------------------------
9593 RET buffer-start as level 2 heading at end of file
9594 RET on headline as sublevel of the heading at cursor
9595 RET no heading at cursor position, level taken from context.
9596 Or use prefix arg to specify level manually.
9597 <left> on headline as same level, before current heading
9598 <right> on headline as same level, after current heading
9599
9600 So the fastest way to store the note is to press RET RET to append it to
9601 the default file. This way your current train of thought is not
9602 interrupted, in accordance with the principles of remember.el. But with
9603 little extra effort, you can push it directly to the correct location.
9604
9605 Before being stored away, the function ensures that the text has a
9606 headline, i.e. a first line that starts with a \"*\". If not, a headline
9607 is constructed from the current date and some additional data.
9608
9609 If the variable `org-adapt-indentation' is non-nil, the entire text is
9610 also indented so that it starts in the same column as the headline
9611 \(i.e. after the stars).
9612
9613 See also the variable `org-reverse-note-order'."
9614 (catch 'quit
9615 (let* ((txt (buffer-substring (point-min) (point-max)))
9616 (fastp current-prefix-arg)
9617 (file (if fastp org-default-notes-file (org-get-org-file)))
9618 (visiting (find-buffer-visiting file))
9619 (org-startup-with-deadline-check nil)
9620 (org-startup-folded nil)
9621 (org-startup-align-all-tables nil)
9622 spos level indent reversed)
9623 ;; Modify text so that it becomes a nice subtree which can be inserted
9624 ;; into an org tree.
9625 (let* ((lines (split-string txt "\n"))
9626 first)
9627 ;; remove empty lines at the beginning
9628 (while (and lines (string-match "^[ \t]*\n" (car lines)))
9629 (setq lines (cdr lines)))
9630 (setq first (car lines) lines (cdr lines))
9631 (if (string-match "^\\*+" first)
9632 ;; Is already a headline
9633 (setq indent nil)
9634 ;; We need to add a headline: Use time and first buffer line
9635 (setq lines (cons first lines)
9636 first (concat "* " (current-time-string)
9637 " (" (remember-buffer-desc) ")")
9638 indent " "))
9639 (if (and org-adapt-indentation indent)
9640 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
9641 (setq txt (concat first "\n"
9642 (mapconcat 'identity lines "\n"))))
9643 ;; Find the file
9644 (if (not visiting)
9645 (find-file-noselect file))
9646 (with-current-buffer (get-file-buffer file)
9647 (save-excursion (and (goto-char (point-min))
9648 (not (re-search-forward "^\\* " nil t))
9649 (insert "\n* Notes\n")))
9650 (setq reversed (org-notes-order-reversed-p))
9651 (save-excursion
9652 (save-restriction
9653 (widen)
9654 ;; Ask the User for a location
9655 (setq spos (if fastp 1 (org-get-location
9656 (current-buffer)
9657 org-remember-help)))
9658 (if (not spos) (throw 'quit nil)) ; return nil to show we did
9659 ; not handle this note
9660 (goto-char spos)
9661 (cond ((bobp)
9662 ;; Put it at the start or end, as level 2
9663 (save-restriction
9664 (widen)
9665 (goto-char (if reversed (point-min) (point-max)))
9666 (if (not (bolp)) (newline))
9667 (org-paste-subtree 2 txt)))
9668 ((and (org-on-heading-p nil) (not current-prefix-arg))
9669 ;; Put it below this entry, at the beg/end of the subtree
9670 (org-back-to-heading)
9671 (setq level (funcall outline-level))
9672 (if reversed
9673 (outline-end-of-heading)
9674 (outline-end-of-subtree))
9675 (if (not (bolp)) (newline))
9676 (beginning-of-line 1)
9677 (org-paste-subtree (1+ level) txt))
9678 (t
9679 ;; Put it right there, with automatic level determined by
9680 ;; org-paste-subtree or from prefix arg
9681 (org-paste-subtree current-prefix-arg txt)))
9682 (when remember-save-after-remembering
9683 (save-buffer)
9684 (if (not visiting) (kill-buffer (current-buffer)))))))))
9685 t) ;; return t to indicate that we took care of this note.
9686
9687 (defun org-get-org-file ()
9688 "Read a filename, with default directory `org-directory'."
9689 (let ((default (or org-default-notes-file remember-data-file)))
9690 (read-file-name (format "File name [%s]: " default)
9691 (file-name-as-directory org-directory)
9692 default)))
9693
9694 (defun org-notes-order-reversed-p ()
9695 "Check if the current file should receive notes in reversed order."
9696 (cond
9697 ((not org-reverse-note-order) nil)
9698 ((eq t org-reverse-note-order) t)
9699 ((not (listp org-reverse-note-order)) nil)
9700 (t (catch 'exit
9701 (let ((all org-reverse-note-order)
9702 entry)
9703 (while (setq entry (pop all))
9704 (if (string-match (car entry) buffer-file-name)
9705 (throw 'exit (cdr entry))))
9706 nil)))))
9707
9708 ;;; Tables
9709
9710 ;; Watch out: Here we are talking about two different kind of tables.
9711 ;; Most of the code is for the tables created with the Org-mode table editor.
9712 ;; Sometimes, we talk about tables created and edited with the table.el
9713 ;; Emacs package. We call the former org-type tables, and the latter
9714 ;; table.el-type tables.
9715
9716
9717 (defun org-before-change-function (beg end)
9718 "Every change indicates that a table might need an update."
9719 (setq org-table-may-need-update t))
9720
9721 (defconst org-table-line-regexp "^[ \t]*|"
9722 "Detects an org-type table line.")
9723 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
9724 "Detects an org-type table line.")
9725 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
9726 "Detects a table line marked for automatic recalculation.")
9727 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
9728 "Detects a table line marked for automatic recalculation.")
9729 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
9730 "Detects a table line marked for automatic recalculation.")
9731 (defconst org-table-hline-regexp "^[ \t]*|-"
9732 "Detects an org-type table hline.")
9733 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
9734 "Detects a table-type table hline.")
9735 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
9736 "Detects an org-type or table-type table.")
9737 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
9738 "Searching from within a table (any type) this finds the first line
9739 outside the table.")
9740 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
9741 "Searching from within a table (any type) this finds the first line
9742 outside the table.")
9743
9744 (defun org-table-create-with-table.el ()
9745 "Use the table.el package to insert a new table.
9746 If there is already a table at point, convert between Org-mode tables
9747 and table.el tables."
9748 (interactive)
9749 (require 'table)
9750 (cond
9751 ((org-at-table.el-p)
9752 (if (y-or-n-p "Convert table to Org-mode table? ")
9753 (org-table-convert)))
9754 ((org-at-table-p)
9755 (if (y-or-n-p "Convert table to table.el table? ")
9756 (org-table-convert)))
9757 (t (call-interactively 'table-insert))))
9758
9759 (defun org-table-create-or-convert-from-region (arg)
9760 "Convert region to table, or create an empty table.
9761 If there is an active region, convert it to a table. If there is no such
9762 region, create an empty table."
9763 (interactive "P")
9764 (if (org-region-active-p)
9765 (org-table-convert-region (region-beginning) (region-end) arg)
9766 (org-table-create arg)))
9767
9768 (defun org-table-create (&optional size)
9769 "Query for a size and insert a table skeleton.
9770 SIZE is a string Columns x Rows like for example \"3x2\"."
9771 (interactive "P")
9772 (unless size
9773 (setq size (read-string
9774 (concat "Table size Columns x Rows [e.g. "
9775 org-table-default-size "]: ")
9776 "" nil org-table-default-size)))
9777
9778 (let* ((pos (point))
9779 (indent (make-string (current-column) ?\ ))
9780 (split (org-split-string size " *x *"))
9781 (rows (string-to-number (nth 1 split)))
9782 (columns (string-to-number (car split)))
9783 (line (concat (apply 'concat indent "|" (make-list columns " |"))
9784 "\n")))
9785 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
9786 (point-at-bol) (point)))
9787 (beginning-of-line 1)
9788 (newline))
9789 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
9790 (dotimes (i rows) (insert line))
9791 (goto-char pos)
9792 (if (> rows 1)
9793 ;; Insert a hline after the first row.
9794 (progn
9795 (end-of-line 1)
9796 (insert "\n|-")
9797 (goto-char pos)))
9798 (org-table-align)))
9799
9800 (defun org-table-convert-region (beg0 end0 &optional nspace)
9801 "Convert region to a table.
9802 The region goes from BEG0 to END0, but these borders will be moved
9803 slightly, to make sure a beginning of line in the first line is included.
9804 When NSPACE is non-nil, it indicates the minimum number of spaces that
9805 separate columns (default: just one space)."
9806 (interactive "rP")
9807 (let* ((beg (min beg0 end0))
9808 (end (max beg0 end0))
9809 (tabsep t)
9810 re)
9811 (goto-char beg)
9812 (beginning-of-line 1)
9813 (setq beg (move-marker (make-marker) (point)))
9814 (goto-char end)
9815 (if (bolp) (backward-char 1) (end-of-line 1))
9816 (setq end (move-marker (make-marker) (point)))
9817 ;; Lets see if this is tab-separated material. If every nonempty line
9818 ;; contains a tab, we will assume that it is tab-separated material
9819 (if nspace
9820 (setq tabsep nil)
9821 (goto-char beg)
9822 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
9823 (if nspace (setq tabsep nil))
9824 (if tabsep
9825 (setq re "^\\|\t")
9826 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
9827 (max 1 (prefix-numeric-value nspace)))))
9828 (goto-char beg)
9829 (while (re-search-forward re end t)
9830 (replace-match "|" t t))
9831 (goto-char beg)
9832 (insert " ")
9833 (org-table-align)))
9834
9835 (defun org-table-import (file arg)
9836 "Import FILE as a table.
9837 The file is assumed to be tab-separated. Such files can be produced by most
9838 spreadsheet and database applications. If no tabs (at least one per line)
9839 are found, lines will be split on whitespace into fields."
9840 (interactive "f\nP")
9841 (or (bolp) (newline))
9842 (let ((beg (point))
9843 (pm (point-max)))
9844 (insert-file-contents file)
9845 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
9846
9847 (defun org-table-export ()
9848 "Export table as a tab-separated file.
9849 Such a file can be imported into a spreadsheet program like Excel."
9850 (interactive)
9851 (let* ((beg (org-table-begin))
9852 (end (org-table-end))
9853 (table (buffer-substring beg end))
9854 (file (read-file-name "Export table to: "))
9855 buf)
9856 (unless (or (not (file-exists-p file))
9857 (y-or-n-p (format "Overwrite file %s? " file)))
9858 (error "Abort"))
9859 (with-current-buffer (find-file-noselect file)
9860 (setq buf (current-buffer))
9861 (erase-buffer)
9862 (fundamental-mode)
9863 (insert table)
9864 (goto-char (point-min))
9865 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
9866 (replace-match "" t t)
9867 (end-of-line 1))
9868 (goto-char (point-min))
9869 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
9870 (replace-match "" t t)
9871 (goto-char (min (1+ (point)) (point-max))))
9872 (goto-char (point-min))
9873 (while (re-search-forward "^-[-+]*$" nil t)
9874 (replace-match "")
9875 (if (looking-at "\n")
9876 (delete-char 1)))
9877 (goto-char (point-min))
9878 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
9879 (replace-match "\t" t t))
9880 (save-buffer))
9881 (kill-buffer buf)))
9882
9883 (defvar org-table-aligned-begin-marker (make-marker)
9884 "Marker at the beginning of the table last aligned.
9885 Used to check if cursor still is in that table, to minimize realignment.")
9886 (defvar org-table-aligned-end-marker (make-marker)
9887 "Marker at the end of the table last aligned.
9888 Used to check if cursor still is in that table, to minimize realignment.")
9889 (defvar org-table-last-alignment nil
9890 "List of flags for flushright alignment, from the last re-alignment.
9891 This is being used to correctly align a single field after TAB or RET.")
9892 (defvar org-table-last-column-widths nil
9893 "List of max width of fields in each column.
9894 This is being used to correctly align a single field after TAB or RET.")
9895
9896 (defvar org-last-recalc-line nil)
9897 (defconst org-narrow-column-arrow "=>"
9898 "Used as display property in narrowed table columns.")
9899
9900 (defun org-table-align ()
9901 "Align the table at point by aligning all vertical bars."
9902 (interactive)
9903 (let* (
9904 ;; Limits of table
9905 (beg (org-table-begin))
9906 (end (org-table-end))
9907 ;; Current cursor position
9908 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9909 (colpos (org-table-current-column))
9910 (winstart (window-start))
9911 text lines (new "") lengths l typenums ty fields maxfields i
9912 column
9913 (indent "") cnt frac
9914 rfmt hfmt
9915 (spaces '(1 . 1))
9916 (sp1 (car spaces))
9917 (sp2 (cdr spaces))
9918 (rfmt1 (concat
9919 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
9920 (hfmt1 (concat
9921 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
9922 emptystrings xx links narrow fmax fmin f1 len c e)
9923 (untabify beg end)
9924 (remove-text-properties beg end '(org-cwidth t display t))
9925 ;; Check if we have links
9926 (goto-char beg)
9927 (setq links (re-search-forward org-bracket-link-regexp end t))
9928 ;; Make sure the link properties are right
9929 (when links (goto-char beg) (while (org-activate-bracket-links end)))
9930 ;; Check if we are narrowing any columns
9931 (goto-char beg)
9932 (setq narrow (and org-format-transports-properties-p
9933 (re-search-forward "<[0-9]+>" end t)))
9934 ;; Get the rows
9935 (setq lines (org-split-string
9936 (buffer-substring beg end) "\n"))
9937 ;; Store the indentation of the first line
9938 (if (string-match "^ *" (car lines))
9939 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
9940 ;; Mark the hlines by setting the corresponding element to nil
9941 ;; At the same time, we remove trailing space.
9942 (setq lines (mapcar (lambda (l)
9943 (if (string-match "^ *|-" l)
9944 nil
9945 (if (string-match "[ \t]+$" l)
9946 (substring l 0 (match-beginning 0))
9947 l)))
9948 lines))
9949 ;; Get the data fields by splitting the lines.
9950 (setq fields (mapcar
9951 (lambda (l)
9952 (org-split-string l " *| *"))
9953 (delq nil (copy-sequence lines))))
9954 ;; How many fields in the longest line?
9955 (condition-case nil
9956 (setq maxfields (apply 'max (mapcar 'length fields)))
9957 (error
9958 (kill-region beg end)
9959 (org-table-create org-table-default-size)
9960 (error "Empty table - created default table")))
9961 ;; A list of empty string to fill any short rows on output
9962 (setq emptystrings (make-list maxfields ""))
9963 ;; Check for special formatting.
9964 (setq i -1)
9965 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
9966 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
9967 ;; Check if there is an explicit width specified
9968 (when (and org-table-limit-column-width narrow)
9969 (setq c column fmax nil)
9970 (while c
9971 (setq e (pop c))
9972 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
9973 (setq fmax (string-to-number (match-string 1 e)) c nil)))
9974 ;; Find fields that are wider than fmax, and shorten them
9975 (when fmax
9976 (loop for xx in column do
9977 (when (and (stringp xx)
9978 (> (org-string-width xx) fmax))
9979 (org-add-props xx nil
9980 'help-echo
9981 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
9982 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
9983 (unless (> f1 1)
9984 (error "Cannot narrow field starting with wide link \"%s\""
9985 (match-string 0 xx)))
9986 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
9987 (add-text-properties (- f1 2) f1
9988 (list 'display org-narrow-column-arrow)
9989 xx)))))
9990 ;; Get the maximum width for each column
9991 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
9992 ;; Get the fraction of numbers, to decide about alignment of the column
9993 (setq cnt 0 frac 0.0)
9994 (loop for x in column do
9995 (if (equal x "")
9996 nil
9997 (setq frac ( / (+ (* frac cnt)
9998 (if (string-match org-table-number-regexp x) 1 0))
9999 (setq cnt (1+ cnt))))))
10000 (push (>= frac org-table-number-fraction) typenums))
10001 (setq lengths (nreverse lengths) typenums (nreverse typenums))
10002
10003 ;; Store the alignment of this table, for later editing of single fields
10004 (setq org-table-last-alignment typenums
10005 org-table-last-column-widths lengths)
10006
10007 ;; With invisible characters, `format' does not get the field width right
10008 ;; So we need to make these fields wide by hand.
10009 (when links
10010 (loop for i from 0 upto (1- maxfields) do
10011 (setq len (nth i lengths))
10012 (loop for j from 0 upto (1- (length fields)) do
10013 (setq c (nthcdr i (car (nthcdr j fields))))
10014 (if (and (stringp (car c))
10015 (string-match org-bracket-link-regexp (car c))
10016 (< (org-string-width (car c)) len))
10017 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
10018
10019 ;; Compute the formats needed for output of the table
10020 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
10021 (while (setq l (pop lengths))
10022 (setq ty (if (pop typenums) "" "-")) ; number types flushright
10023 (setq rfmt (concat rfmt (format rfmt1 ty l))
10024 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
10025 (setq rfmt (concat rfmt "\n")
10026 hfmt (concat (substring hfmt 0 -1) "|\n"))
10027
10028 (setq new (mapconcat
10029 (lambda (l)
10030 (if l (apply 'format rfmt
10031 (append (pop fields) emptystrings))
10032 hfmt))
10033 lines ""))
10034 ;; Replace the old one
10035 (delete-region beg end)
10036 (move-marker end nil)
10037 (move-marker org-table-aligned-begin-marker (point))
10038 (insert new)
10039 (move-marker org-table-aligned-end-marker (point))
10040 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
10041 (goto-char org-table-aligned-begin-marker)
10042 (while (org-hide-wide-columns org-table-aligned-end-marker)))
10043 ;; Try to move to the old location (approximately)
10044 (goto-line linepos)
10045 (set-window-start (selected-window) winstart 'noforce)
10046 (org-table-goto-column colpos)
10047 (setq org-table-may-need-update nil)
10048 ))
10049
10050 (defun org-string-width (s)
10051 "Compute width of string, ignoring invisible characters.
10052 This ignores character with invisibility property `org-link', and also
10053 characters with property `org-cwidth', because these will become invisible
10054 upon the next fontification round."
10055 (let (b)
10056 (when (or (eq t buffer-invisibility-spec)
10057 (assq 'org-link buffer-invisibility-spec))
10058 (while (setq b (text-property-any 0 (length s)
10059 'invisible 'org-link s))
10060 (setq s (concat (substring s 0 b)
10061 (substring s (or (next-single-property-change
10062 b 'invisible s) (length s)))))))
10063 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
10064 (setq s (concat (substring s 0 b)
10065 (substring s (or (next-single-property-change
10066 b 'org-cwidth s) (length s))))))
10067 (string-width s)))
10068
10069 (defun org-table-begin (&optional table-type)
10070 "Find the beginning of the table and return its position.
10071 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
10072 (save-excursion
10073 (if (not (re-search-backward
10074 (if table-type org-table-any-border-regexp
10075 org-table-border-regexp)
10076 nil t))
10077 (progn (goto-char (point-min)) (point))
10078 (goto-char (match-beginning 0))
10079 (beginning-of-line 2)
10080 (point))))
10081
10082 (defun org-table-end (&optional table-type)
10083 "Find the end of the table and return its position.
10084 With argument TABLE-TYPE, go to the end of a table.el-type table."
10085 (save-excursion
10086 (if (not (re-search-forward
10087 (if table-type org-table-any-border-regexp
10088 org-table-border-regexp)
10089 nil t))
10090 (goto-char (point-max))
10091 (goto-char (match-beginning 0)))
10092 (point-marker)))
10093
10094 (defun org-table-justify-field-maybe (&optional new)
10095 "Justify the current field, text to left, number to right.
10096 Optional argument NEW may specify text to replace the current field content."
10097 (cond
10098 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
10099 ((org-at-table-hline-p))
10100 ((and (not new)
10101 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
10102 (current-buffer)))
10103 (< (point) org-table-aligned-begin-marker)
10104 (>= (point) org-table-aligned-end-marker)))
10105 ;; This is not the same table, force a full re-align
10106 (setq org-table-may-need-update t))
10107 (t ;; realign the current field, based on previous full realign
10108 (let* ((pos (point)) s
10109 (col (org-table-current-column))
10110 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
10111 l f n o e)
10112 (when (> col 0)
10113 (skip-chars-backward "^|\n")
10114 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
10115 (progn
10116 (setq s (match-string 1)
10117 o (match-string 0)
10118 l (max 1 (- (match-end 0) (match-beginning 0) 3))
10119 e (not (= (match-beginning 2) (match-end 2))))
10120 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
10121 l (if e "|" (setq org-table-may-need-update t) ""))
10122 n (format f s))
10123 (if new
10124 (if (<= (length new) l) ;; FIXME: length -> str-width?
10125 (setq n (format f new))
10126 (setq n (concat new "|") org-table-may-need-update t)))
10127 (or (equal n o)
10128 (let (org-table-may-need-update)
10129 (replace-match n))))
10130 (setq org-table-may-need-update t))
10131 (goto-char pos))))))
10132
10133 (defun org-table-next-field ()
10134 "Go to the next field in the current table, creating new lines as needed.
10135 Before doing so, re-align the table if necessary."
10136 (interactive)
10137 (org-table-maybe-eval-formula)
10138 (org-table-maybe-recalculate-line)
10139 (if (and org-table-automatic-realign
10140 org-table-may-need-update)
10141 (org-table-align))
10142 (let ((end (org-table-end)))
10143 (if (org-at-table-hline-p)
10144 (end-of-line 1))
10145 (condition-case nil
10146 (progn
10147 (re-search-forward "|" end)
10148 (if (looking-at "[ \t]*$")
10149 (re-search-forward "|" end))
10150 (if (and (looking-at "-")
10151 org-table-tab-jumps-over-hlines
10152 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
10153 (goto-char (match-beginning 1)))
10154 (if (looking-at "-")
10155 (progn
10156 (beginning-of-line 0)
10157 (org-table-insert-row 'below))
10158 (if (looking-at " ") (forward-char 1))))
10159 (error
10160 (org-table-insert-row 'below)))))
10161
10162 (defun org-table-previous-field ()
10163 "Go to the previous field in the table.
10164 Before doing so, re-align the table if necessary."
10165 (interactive)
10166 (org-table-justify-field-maybe)
10167 (org-table-maybe-recalculate-line)
10168 (if (and org-table-automatic-realign
10169 org-table-may-need-update)
10170 (org-table-align))
10171 (if (org-at-table-hline-p)
10172 (end-of-line 1))
10173 (re-search-backward "|" (org-table-begin))
10174 (re-search-backward "|" (org-table-begin))
10175 (while (looking-at "|\\(-\\|[ \t]*$\\)")
10176 (re-search-backward "|" (org-table-begin)))
10177 (if (looking-at "| ?")
10178 (goto-char (match-end 0))))
10179
10180 (defun org-table-next-row ()
10181 "Go to the next row (same column) in the current table.
10182 Before doing so, re-align the table if necessary."
10183 (interactive)
10184 (org-table-maybe-eval-formula)
10185 (org-table-maybe-recalculate-line)
10186 (if (or (looking-at "[ \t]*$")
10187 (save-excursion (skip-chars-backward " \t") (bolp)))
10188 (newline)
10189 (if (and org-table-automatic-realign
10190 org-table-may-need-update)
10191 (org-table-align))
10192 (let ((col (org-table-current-column)))
10193 (beginning-of-line 2)
10194 (if (or (not (org-at-table-p))
10195 (org-at-table-hline-p))
10196 (progn
10197 (beginning-of-line 0)
10198 (org-table-insert-row 'below)))
10199 (org-table-goto-column col)
10200 (skip-chars-backward "^|\n\r")
10201 (if (looking-at " ") (forward-char 1)))))
10202
10203 (defun org-table-copy-down (n)
10204 "Copy a field down in the current column.
10205 If the field at the cursor is empty, copy into it the content of the nearest
10206 non-empty field above. With argument N, use the Nth non-empty field.
10207 If the current field is not empty, it is copied down to the next row, and
10208 the cursor is moved with it. Therefore, repeating this command causes the
10209 column to be filled row-by-row.
10210 If the variable `org-table-copy-increment' is non-nil and the field is an
10211 integer, it will be incremented while copying."
10212 (interactive "p")
10213 (let* ((colpos (org-table-current-column))
10214 (field (org-table-get-field))
10215 (non-empty (string-match "[^ \t]" field))
10216 (beg (org-table-begin))
10217 txt)
10218 (org-table-check-inside-data-field)
10219 (if non-empty
10220 (progn
10221 (setq txt (org-trim field))
10222 (org-table-next-row)
10223 (org-table-blank-field))
10224 (save-excursion
10225 (setq txt
10226 (catch 'exit
10227 (while (progn (beginning-of-line 1)
10228 (re-search-backward org-table-dataline-regexp
10229 beg t))
10230 (org-table-goto-column colpos t)
10231 (if (and (looking-at
10232 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
10233 (= (setq n (1- n)) 0))
10234 (throw 'exit (match-string 1))))))))
10235 (if txt
10236 (progn
10237 (if (and org-table-copy-increment
10238 (string-match "^[0-9]+$" txt))
10239 (setq txt (format "%d" (+ (string-to-number txt) 1))))
10240 (insert txt)
10241 (org-table-maybe-recalculate-line)
10242 (org-table-align))
10243 (error "No non-empty field found"))))
10244
10245 (defun org-table-check-inside-data-field ()
10246 "Is point inside a table data field?
10247 I.e. not on a hline or before the first or after the last column?
10248 This actually throws an error, so it aborts the current command."
10249 (if (or (not (org-at-table-p))
10250 (= (org-table-current-column) 0)
10251 (org-at-table-hline-p)
10252 (looking-at "[ \t]*$"))
10253 (error "Not in table data field")))
10254
10255 (defvar org-table-clip nil
10256 "Clipboard for table regions.")
10257
10258 (defun org-table-blank-field ()
10259 "Blank the current table field or active region."
10260 (interactive)
10261 (org-table-check-inside-data-field)
10262 (if (and (interactive-p) (org-region-active-p))
10263 (let (org-table-clip)
10264 (org-table-cut-region (region-beginning) (region-end)))
10265 (skip-chars-backward "^|")
10266 (backward-char 1)
10267 (if (looking-at "|[^|\n]+")
10268 (let* ((pos (match-beginning 0))
10269 (match (match-string 0))
10270 (len (org-string-width match)))
10271 (replace-match (concat "|" (make-string (1- len) ?\ )))
10272 (goto-char (+ 2 pos))
10273 (substring match 1)))))
10274
10275 (defun org-table-get-field (&optional n replace)
10276 "Return the value of the field in column N of current row.
10277 N defaults to current field.
10278 If REPLACE is a string, replace field with this value. The return value
10279 is always the old value."
10280 (and n (org-table-goto-column n))
10281 (skip-chars-backward "^|\n")
10282 (backward-char 1)
10283 (if (looking-at "|[^|\r\n]*")
10284 (let* ((pos (match-beginning 0))
10285 (val (buffer-substring (1+ pos) (match-end 0))))
10286 (if replace
10287 (replace-match (concat "|" replace)))
10288 (goto-char (min (point-at-eol) (+ 2 pos)))
10289 val)
10290 (forward-char 1) ""))
10291
10292 (defun org-table-current-column ()
10293 "Find out which column we are in.
10294 When called interactively, column is also displayed in echo area."
10295 (interactive)
10296 (if (interactive-p) (org-table-check-inside-data-field))
10297 (save-excursion
10298 (let ((cnt 0) (pos (point)))
10299 (beginning-of-line 1)
10300 (while (search-forward "|" pos t)
10301 (setq cnt (1+ cnt)))
10302 (if (interactive-p) (message "This is table column %d" cnt))
10303 cnt)))
10304
10305 (defun org-table-goto-column (n &optional on-delim force)
10306 "Move the cursor to the Nth column in the current table line.
10307 With optional argument ON-DELIM, stop with point before the left delimiter
10308 of the field.
10309 If there are less than N fields, just go to after the last delimiter.
10310 However, when FORCE is non-nil, create new columns if necessary."
10311 (interactive "p")
10312 (let ((pos (point-at-eol)))
10313 (beginning-of-line 1)
10314 (when (> n 0)
10315 (while (and (> (setq n (1- n)) -1)
10316 (or (search-forward "|" pos t)
10317 (and force
10318 (progn (end-of-line 1)
10319 (skip-chars-backward "^|")
10320 (insert " | "))))))
10321 ; (backward-char 2) t)))))
10322 (when (and force (not (looking-at ".*|")))
10323 (save-excursion (end-of-line 1) (insert " | ")))
10324 (if on-delim
10325 (backward-char 1)
10326 (if (looking-at " ") (forward-char 1))))))
10327
10328 (defun org-at-table-p (&optional table-type)
10329 "Return t if the cursor is inside an org-type table.
10330 If TABLE-TYPE is non-nil, also check for table.el-type tables."
10331 (if org-enable-table-editor
10332 (save-excursion
10333 (beginning-of-line 1)
10334 (looking-at (if table-type org-table-any-line-regexp
10335 org-table-line-regexp)))
10336 nil))
10337
10338 (defun org-at-table.el-p ()
10339 "Return t if and only if we are at a table.el table."
10340 (and (org-at-table-p 'any)
10341 (save-excursion
10342 (goto-char (org-table-begin 'any))
10343 (looking-at org-table1-hline-regexp))))
10344
10345 (defun org-table-recognize-table.el ()
10346 "If there is a table.el table nearby, recognize it and move into it."
10347 (if org-table-tab-recognizes-table.el
10348 (if (org-at-table.el-p)
10349 (progn
10350 (beginning-of-line 1)
10351 (if (looking-at org-table-dataline-regexp)
10352 nil
10353 (if (looking-at org-table1-hline-regexp)
10354 (progn
10355 (beginning-of-line 2)
10356 (if (looking-at org-table-any-border-regexp)
10357 (beginning-of-line -1)))))
10358 (if (re-search-forward "|" (org-table-end t) t)
10359 (progn
10360 (require 'table)
10361 (if (table--at-cell-p (point))
10362 t
10363 (message "recognizing table.el table...")
10364 (table-recognize-table)
10365 (message "recognizing table.el table...done")))
10366 (error "This should not happen..."))
10367 t)
10368 nil)
10369 nil))
10370
10371 (defun org-at-table-hline-p ()
10372 "Return t if the cursor is inside a hline in a table."
10373 (if org-enable-table-editor
10374 (save-excursion
10375 (beginning-of-line 1)
10376 (looking-at org-table-hline-regexp))
10377 nil))
10378
10379 (defun org-table-insert-column ()
10380 "Insert a new column into the table."
10381 (interactive)
10382 (if (not (org-at-table-p))
10383 (error "Not at a table"))
10384 (org-table-find-dataline)
10385 (let* ((col (max 1 (org-table-current-column)))
10386 (beg (org-table-begin))
10387 (end (org-table-end))
10388 ;; Current cursor position
10389 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10390 (colpos col))
10391 (goto-char beg)
10392 (while (< (point) end)
10393 (if (org-at-table-hline-p)
10394 nil
10395 (org-table-goto-column col t)
10396 (insert "| "))
10397 (beginning-of-line 2))
10398 (move-marker end nil)
10399 (goto-line linepos)
10400 (org-table-goto-column colpos)
10401 (org-table-align)
10402 (org-table-modify-formulas 'insert col)))
10403
10404 (defun org-table-find-dataline ()
10405 "Find a dataline in the current table, which is needed for column commands."
10406 (if (and (org-at-table-p)
10407 (not (org-at-table-hline-p)))
10408 t
10409 (let ((col (current-column))
10410 (end (org-table-end)))
10411 (move-to-column col)
10412 (while (and (< (point) end)
10413 (or (not (= (current-column) col))
10414 (org-at-table-hline-p)))
10415 (beginning-of-line 2)
10416 (move-to-column col))
10417 (if (and (org-at-table-p)
10418 (not (org-at-table-hline-p)))
10419 t
10420 (error
10421 "Please position cursor in a data line for column operations")))))
10422
10423 (defun org-table-delete-column ()
10424 "Delete a column from the table."
10425 (interactive)
10426 (if (not (org-at-table-p))
10427 (error "Not at a table"))
10428 (org-table-find-dataline)
10429 (org-table-check-inside-data-field)
10430 (let* ((col (org-table-current-column))
10431 (beg (org-table-begin))
10432 (end (org-table-end))
10433 ;; Current cursor position
10434 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10435 (colpos col))
10436 (goto-char beg)
10437 (while (< (point) end)
10438 (if (org-at-table-hline-p)
10439 nil
10440 (org-table-goto-column col t)
10441 (and (looking-at "|[^|\n]+|")
10442 (replace-match "|")))
10443 (beginning-of-line 2))
10444 (move-marker end nil)
10445 (goto-line linepos)
10446 (org-table-goto-column colpos)
10447 (org-table-align)
10448 (org-table-modify-formulas 'remove col)))
10449
10450 (defun org-table-move-column-right ()
10451 "Move column to the right."
10452 (interactive)
10453 (org-table-move-column nil))
10454 (defun org-table-move-column-left ()
10455 "Move column to the left."
10456 (interactive)
10457 (org-table-move-column 'left))
10458
10459 (defun org-table-move-column (&optional left)
10460 "Move the current column to the right. With arg LEFT, move to the left."
10461 (interactive "P")
10462 (if (not (org-at-table-p))
10463 (error "Not at a table"))
10464 (org-table-find-dataline)
10465 (org-table-check-inside-data-field)
10466 (let* ((col (org-table-current-column))
10467 (col1 (if left (1- col) col))
10468 (beg (org-table-begin))
10469 (end (org-table-end))
10470 ;; Current cursor position
10471 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10472 (colpos (if left (1- col) (1+ col))))
10473 (if (and left (= col 1))
10474 (error "Cannot move column further left"))
10475 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
10476 (error "Cannot move column further right"))
10477 (goto-char beg)
10478 (while (< (point) end)
10479 (if (org-at-table-hline-p)
10480 nil
10481 (org-table-goto-column col1 t)
10482 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
10483 (replace-match "|\\2|\\1|")))
10484 (beginning-of-line 2))
10485 (move-marker end nil)
10486 (goto-line linepos)
10487 (org-table-goto-column colpos)
10488 (org-table-align)
10489 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
10490
10491 (defun org-table-move-row-down ()
10492 "Move table row down."
10493 (interactive)
10494 (org-table-move-row nil))
10495 (defun org-table-move-row-up ()
10496 "Move table row up."
10497 (interactive)
10498 (org-table-move-row 'up))
10499
10500 (defun org-table-move-row (&optional up)
10501 "Move the current table line down. With arg UP, move it up."
10502 (interactive "P")
10503 (let ((col (current-column))
10504 (pos (point))
10505 (tonew (if up 0 2))
10506 txt)
10507 (beginning-of-line tonew)
10508 (if (not (org-at-table-p))
10509 (progn
10510 (goto-char pos)
10511 (error "Cannot move row further")))
10512 (goto-char pos)
10513 (beginning-of-line 1)
10514 (setq pos (point))
10515 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
10516 (delete-region (point) (1+ (point-at-eol)))
10517 (beginning-of-line tonew)
10518 (insert txt)
10519 (beginning-of-line 0)
10520 (move-to-column col)))
10521
10522 (defun org-table-insert-row (&optional arg)
10523 "Insert a new row above the current line into the table.
10524 With prefix ARG, insert below the current line."
10525 (interactive "P")
10526 (if (not (org-at-table-p))
10527 (error "Not at a table"))
10528 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
10529 (new (org-table-clean-line line)))
10530 ;; Fix the first field if necessary
10531 (if (string-match "^[ \t]*| *[#$] *|" line)
10532 (setq new (replace-match (match-string 0 line) t t new)))
10533 (beginning-of-line (if arg 2 1))
10534 (let (org-table-may-need-update) (insert-before-markers new "\n"))
10535 (beginning-of-line 0)
10536 (re-search-forward "| ?" (point-at-eol) t)
10537 (and org-table-may-need-update (org-table-align))))
10538
10539 (defun org-table-insert-hline (&optional arg)
10540 "Insert a horizontal-line below the current line into the table.
10541 With prefix ARG, insert above the current line."
10542 (interactive "P")
10543 (if (not (org-at-table-p))
10544 (error "Not at a table"))
10545 (let ((line (org-table-clean-line
10546 (buffer-substring (point-at-bol) (point-at-eol))))
10547 (col (current-column)))
10548 (while (string-match "|\\( +\\)|" line)
10549 (setq line (replace-match
10550 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
10551 ?-) "|") t t line)))
10552 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
10553 (beginning-of-line (if arg 1 2))
10554 (insert line "\n")
10555 (beginning-of-line (if arg 1 -1))
10556 (move-to-column col)))
10557
10558 (defun org-table-clean-line (s)
10559 "Convert a table line S into a string with only \"|\" and space.
10560 In particular, this does handle wide and invisible characters."
10561 (if (string-match "^[ \t]*|-" s)
10562 ;; It's a hline, just map the characters
10563 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
10564 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
10565 (setq s (replace-match
10566 (concat "|" (make-string (org-string-width (match-string 1 s))
10567 ?\ ) "|")
10568 t t s)))
10569 s))
10570
10571 (defun org-table-kill-row ()
10572 "Delete the current row or horizontal line from the table."
10573 (interactive)
10574 (if (not (org-at-table-p))
10575 (error "Not at a table"))
10576 (let ((col (current-column)))
10577 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
10578 (if (not (org-at-table-p)) (beginning-of-line 0))
10579 (move-to-column col)))
10580
10581 (defun org-table-sort-lines (beg end numericp)
10582 "Sort table lines in region.
10583 Point and mark define the first and last line to include. Both point and
10584 mark should be in the column that is used for sorting. For example, to
10585 sort according to column 3, put the mark in the first line to sort, in
10586 table column 3. Put point into the last line to be included in the sorting,
10587 also in table column 3. The command will prompt for the sorting method
10588 \(n for numerical, a for alphanumeric)."
10589 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
10590 (setq numericp (string-match "[nN]" numericp))
10591 (org-table-align) ;; Just to be safe
10592 (let* (bcol ecol cmp column lns)
10593 (goto-char beg)
10594 (org-table-check-inside-data-field)
10595 (setq column (org-table-current-column)
10596 beg (move-marker (make-marker) (point-at-bol)))
10597 (goto-char end)
10598 (org-table-check-inside-data-field)
10599 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
10600 (untabify beg end)
10601 (goto-char beg)
10602 (org-table-goto-column column)
10603 (skip-chars-backward "^|")
10604 (setq bcol (current-column))
10605 (org-table-goto-column (1+ column))
10606 (skip-chars-backward "^|")
10607 (setq ecol (1- (current-column)))
10608 (setq cmp (if numericp
10609 (lambda (a b) (< (car a) (car b)))
10610 (lambda (a b) (string< (car a) (car b)))))
10611 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
10612 (org-split-string (buffer-substring beg end) "\n")))
10613 (if numericp
10614 (setq lns (mapcar (lambda(x)
10615 (cons (string-to-number (car x)) (cdr x)))
10616 lns)))
10617 (delete-region beg end)
10618 (move-marker beg nil)
10619 (move-marker end nil)
10620 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
10621 (message "%d lines sorted %s based on column %d"
10622 (length lns)
10623 (if numericp "numerically" "alphabetically") column)))
10624
10625 (defun org-table-cut-region (beg end)
10626 "Copy region in table to the clipboard and blank all relevant fields."
10627 (interactive "r")
10628 (org-table-copy-region beg end 'cut))
10629
10630 (defun org-table-copy-region (beg end &optional cut)
10631 "Copy rectangular region in table to clipboard.
10632 A special clipboard is used which can only be accessed
10633 with `org-table-paste-rectangle'."
10634 (interactive "rP")
10635 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
10636 region cols
10637 (rpl (if cut " " nil)))
10638 (goto-char beg)
10639 (org-table-check-inside-data-field)
10640 (setq l01 (count-lines (point-min) (point))
10641 c01 (org-table-current-column))
10642 (goto-char end)
10643 (org-table-check-inside-data-field)
10644 (setq l02 (count-lines (point-min) (point))
10645 c02 (org-table-current-column))
10646 (setq l1 (min l01 l02) l2 (max l01 l02)
10647 c1 (min c01 c02) c2 (max c01 c02))
10648 (catch 'exit
10649 (while t
10650 (catch 'nextline
10651 (if (> l1 l2) (throw 'exit t))
10652 (goto-line l1)
10653 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
10654 (setq cols nil ic1 c1 ic2 c2)
10655 (while (< ic1 (1+ ic2))
10656 (push (org-table-get-field ic1 rpl) cols)
10657 (setq ic1 (1+ ic1)))
10658 (push (nreverse cols) region)
10659 (setq l1 (1+ l1)))))
10660 (setq org-table-clip (nreverse region))
10661 (if cut (org-table-align))
10662 org-table-clip))
10663
10664 (defun org-table-paste-rectangle ()
10665 "Paste a rectangular region into a table.
10666 The upper right corner ends up in the current field. All involved fields
10667 will be overwritten. If the rectangle does not fit into the present table,
10668 the table is enlarged as needed. The process ignores horizontal separator
10669 lines."
10670 (interactive)
10671 (unless (and org-table-clip (listp org-table-clip))
10672 (error "First cut/copy a region to paste!"))
10673 (org-table-check-inside-data-field)
10674 (let* ((clip org-table-clip)
10675 (line (count-lines (point-min) (point)))
10676 (col (org-table-current-column))
10677 (org-enable-table-editor t)
10678 (org-table-automatic-realign nil)
10679 c cols field)
10680 (while (setq cols (pop clip))
10681 (while (org-at-table-hline-p) (beginning-of-line 2))
10682 (if (not (org-at-table-p))
10683 (progn (end-of-line 0) (org-table-next-field)))
10684 (setq c col)
10685 (while (setq field (pop cols))
10686 (org-table-goto-column c nil 'force)
10687 (org-table-get-field nil field)
10688 (setq c (1+ c)))
10689 (beginning-of-line 2))
10690 (goto-line line)
10691 (org-table-goto-column col)
10692 (org-table-align)))
10693
10694 (defun org-table-convert ()
10695 "Convert from `org-mode' table to table.el and back.
10696 Obviously, this only works within limits. When an Org-mode table is
10697 converted to table.el, all horizontal separator lines get lost, because
10698 table.el uses these as cell boundaries and has no notion of horizontal lines.
10699 A table.el table can be converted to an Org-mode table only if it does not
10700 do row or column spanning. Multiline cells will become multiple cells.
10701 Beware, Org-mode does not test if the table can be successfully converted - it
10702 blindly applies a recipe that works for simple tables."
10703 (interactive)
10704 (require 'table)
10705 (if (org-at-table.el-p)
10706 ;; convert to Org-mode table
10707 (let ((beg (move-marker (make-marker) (org-table-begin t)))
10708 (end (move-marker (make-marker) (org-table-end t))))
10709 (table-unrecognize-region beg end)
10710 (goto-char beg)
10711 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
10712 (replace-match ""))
10713 (goto-char beg))
10714 (if (org-at-table-p)
10715 ;; convert to table.el table
10716 (let ((beg (move-marker (make-marker) (org-table-begin)))
10717 (end (move-marker (make-marker) (org-table-end))))
10718 ;; first, get rid of all horizontal lines
10719 (goto-char beg)
10720 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
10721 (replace-match ""))
10722 ;; insert a hline before first
10723 (goto-char beg)
10724 (org-table-insert-hline 'above)
10725 (beginning-of-line -1)
10726 ;; insert a hline after each line
10727 (while (progn (beginning-of-line 3) (< (point) end))
10728 (org-table-insert-hline))
10729 (goto-char beg)
10730 (setq end (move-marker end (org-table-end)))
10731 ;; replace "+" at beginning and ending of hlines
10732 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
10733 (replace-match "\\1+-"))
10734 (goto-char beg)
10735 (while (re-search-forward "-|[ \t]*$" end t)
10736 (replace-match "-+"))
10737 (goto-char beg)))))
10738
10739 (defun org-table-wrap-region (arg)
10740 "Wrap several fields in a column like a paragraph.
10741 This is useful if you'd like to spread the contents of a field over several
10742 lines, in order to keep the table compact.
10743
10744 If there is an active region, and both point and mark are in the same column,
10745 the text in the column is wrapped to minimum width for the given number of
10746 lines. Generally, this makes the table more compact. A prefix ARG may be
10747 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
10748 formats the selected text to two lines. If the region was longer than two
10749 lines, the remaining lines remain empty. A negative prefix argument reduces
10750 the current number of lines by that amount. The wrapped text is pasted back
10751 into the table. If you formatted it to more lines than it was before, fields
10752 further down in the table get overwritten - so you might need to make space in
10753 the table first.
10754
10755 If there is no region, the current field is split at the cursor position and
10756 the text fragment to the right of the cursor is prepended to the field one
10757 line down.
10758
10759 If there is no region, but you specify a prefix ARG, the current field gets
10760 blank, and the content is appended to the field above."
10761 (interactive "P")
10762 (org-table-check-inside-data-field)
10763 (if (org-region-active-p)
10764 ;; There is a region: fill as a paragraph
10765 (let ((beg (region-beginning))
10766 nlines)
10767 (org-table-cut-region (region-beginning) (region-end))
10768 (if (> (length (car org-table-clip)) 1)
10769 (error "Region must be limited to single column"))
10770 (setq nlines (if arg
10771 (if (< arg 1)
10772 (+ (length org-table-clip) arg)
10773 arg)
10774 (length org-table-clip)))
10775 (setq org-table-clip
10776 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
10777 nil nlines)))
10778 (goto-char beg)
10779 (org-table-paste-rectangle))
10780 ;; No region, split the current field at point
10781 (if arg
10782 ;; combine with field above
10783 (let ((s (org-table-blank-field))
10784 (col (org-table-current-column)))
10785 (beginning-of-line 0)
10786 (while (org-at-table-hline-p) (beginning-of-line 0))
10787 (org-table-goto-column col)
10788 (skip-chars-forward "^|")
10789 (skip-chars-backward " ")
10790 (insert " " (org-trim s))
10791 (org-table-align))
10792 ;; split field
10793 (when (looking-at "\\([^|]+\\)+|")
10794 (let ((s (match-string 1)))
10795 (replace-match " |")
10796 (goto-char (match-beginning 0))
10797 (org-table-next-row)
10798 (insert (org-trim s) " ")
10799 (org-table-align))))))
10800
10801 (defvar org-field-marker nil)
10802
10803 (defun org-table-edit-field (arg)
10804 "Edit table field in a different window.
10805 This is mainly useful for fields that contain hidden parts.
10806 When called with a \\[universal-argument] prefix, just make the full field visible so that
10807 it can be edited in place."
10808 (interactive "P")
10809 (if arg
10810 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
10811 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
10812 (remove-text-properties b e '(org-cwidth t invisible t
10813 display t intangible t))
10814 (if (and (boundp 'font-lock-mode) font-lock-mode)
10815 (font-lock-fontify-block)))
10816 (let ((pos (move-marker (make-marker) (point)))
10817 (field (org-table-get-field))
10818 (cw (current-window-configuration))
10819 p)
10820 (switch-to-buffer-other-window "*Org tmp*")
10821 (erase-buffer)
10822 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
10823 (org-mode)
10824 (goto-char (setq p (point-max)))
10825 (insert (org-trim field))
10826 (remove-text-properties p (point-max)
10827 '(invisible t org-cwidth t display t
10828 intangible t))
10829 (goto-char p)
10830 (set (make-local-variable 'org-finish-function)
10831 'org-table-finish-edit-field)
10832 (set (make-local-variable 'org-window-configuration) cw)
10833 (set (make-local-variable 'org-field-marker) pos)
10834 (message "Edit and finish with C-c C-c"))))
10835
10836 (defun org-table-finish-edit-field ()
10837 "Finish editing a table data field.
10838 Remove all newline characters, insert the result into the table, realign
10839 the table and kill the editing buffer."
10840 (let ((pos org-field-marker)
10841 (cw org-window-configuration)
10842 (cb (current-buffer))
10843 text)
10844 (goto-char (point-min))
10845 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
10846 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
10847 (replace-match " "))
10848 (setq text (org-trim (buffer-string)))
10849 (set-window-configuration cw)
10850 (kill-buffer cb)
10851 (select-window (get-buffer-window (marker-buffer pos)))
10852 (goto-char pos)
10853 (move-marker pos nil)
10854 (org-table-check-inside-data-field)
10855 (org-table-get-field nil text)
10856 (org-table-align)
10857 (message "New field value inserted")))
10858
10859 (defun org-trim (s)
10860 "Remove whitespace at beginning and end of string."
10861 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
10862 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
10863 s)
10864
10865 (defun org-wrap (string &optional width lines)
10866 "Wrap string to either a number of lines, or a width in characters.
10867 If WIDTH is non-nil, the string is wrapped to that width, however many lines
10868 that costs. If there is a word longer than WIDTH, the text is actually
10869 wrapped to the length of that word.
10870 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
10871 many lines, whatever width that takes.
10872 The return value is a list of lines, without newlines at the end."
10873 (let* ((words (org-split-string string "[ \t\n]+"))
10874 (maxword (apply 'max (mapcar 'org-string-width words)))
10875 w ll)
10876 (cond (width
10877 (org-do-wrap words (max maxword width)))
10878 (lines
10879 (setq w maxword)
10880 (setq ll (org-do-wrap words maxword))
10881 (if (<= (length ll) lines)
10882 ll
10883 (setq ll words)
10884 (while (> (length ll) lines)
10885 (setq w (1+ w))
10886 (setq ll (org-do-wrap words w)))
10887 ll))
10888 (t (error "Cannot wrap this")))))
10889
10890
10891 (defun org-do-wrap (words width)
10892 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
10893 (let (lines line)
10894 (while words
10895 (setq line (pop words))
10896 (while (and words (< (+ (length line) (length (car words))) width))
10897 (setq line (concat line " " (pop words))))
10898 (setq lines (push line lines)))
10899 (nreverse lines)))
10900
10901 (defun org-split-string (string &optional separators)
10902 "Splits STRING into substrings at SEPARATORS.
10903 No empty strings are returned if there are matches at the beginning
10904 and end of string."
10905 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
10906 (start 0)
10907 notfirst
10908 (list nil))
10909 (while (and (string-match rexp string
10910 (if (and notfirst
10911 (= start (match-beginning 0))
10912 (< start (length string)))
10913 (1+ start) start))
10914 (< (match-beginning 0) (length string)))
10915 (setq notfirst t)
10916 (or (eq (match-beginning 0) 0)
10917 (and (eq (match-beginning 0) (match-end 0))
10918 (eq (match-beginning 0) start))
10919 (setq list
10920 (cons (substring string start (match-beginning 0))
10921 list)))
10922 (setq start (match-end 0)))
10923 (or (eq start (length string))
10924 (setq list
10925 (cons (substring string start)
10926 list)))
10927 (nreverse list)))
10928
10929 (defun org-table-map-tables (function)
10930 "Apply FUNCTION to the start of all tables in the buffer."
10931 (save-excursion
10932 (save-restriction
10933 (widen)
10934 (goto-char (point-min))
10935 (while (re-search-forward org-table-any-line-regexp nil t)
10936 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
10937 (beginning-of-line 1)
10938 (if (looking-at org-table-line-regexp)
10939 (save-excursion (funcall function)))
10940 (re-search-forward org-table-any-border-regexp nil 1))))
10941 (message "Mapping tables: done"))
10942
10943 (defun org-table-sum (&optional beg end nlast)
10944 "Sum numbers in region of current table column.
10945 The result will be displayed in the echo area, and will be available
10946 as kill to be inserted with \\[yank].
10947
10948 If there is an active region, it is interpreted as a rectangle and all
10949 numbers in that rectangle will be summed. If there is no active
10950 region and point is located in a table column, sum all numbers in that
10951 column.
10952
10953 If at least one number looks like a time HH:MM or HH:MM:SS, all other
10954 numbers are assumed to be times as well (in decimal hours) and the
10955 numbers are added as such.
10956
10957 If NLAST is a number, only the NLAST fields will actually be summed."
10958 (interactive)
10959 (save-excursion
10960 (let (col (timecnt 0) diff h m s org-table-clip)
10961 (cond
10962 ((and beg end)) ; beg and end given explicitly
10963 ((org-region-active-p)
10964 (setq beg (region-beginning) end (region-end)))
10965 (t
10966 (setq col (org-table-current-column))
10967 (goto-char (org-table-begin))
10968 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
10969 (error "No table data"))
10970 (org-table-goto-column col)
10971 ;not needed? (skip-chars-backward "^|")
10972 (setq beg (point))
10973 (goto-char (org-table-end))
10974 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
10975 (error "No table data"))
10976 (org-table-goto-column col)
10977 ;not needed? (skip-chars-forward "^|")
10978 (setq end (point))))
10979 (let* ((items (apply 'append (org-table-copy-region beg end)))
10980 (items1 (cond ((not nlast) items)
10981 ((>= nlast (length items)) items)
10982 (t (setq items (reverse items))
10983 (setcdr (nthcdr (1- nlast) items) nil)
10984 (nreverse items))))
10985 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
10986 items1)))
10987 (res (apply '+ numbers))
10988 (sres (if (= timecnt 0)
10989 (format "%g" res)
10990 (setq diff (* 3600 res)
10991 h (floor (/ diff 3600)) diff (mod diff 3600)
10992 m (floor (/ diff 60)) diff (mod diff 60)
10993 s diff)
10994 (format "%d:%02d:%02d" h m s))))
10995 (kill-new sres)
10996 (if (interactive-p)
10997 (message "%s"
10998 (substitute-command-keys
10999 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
11000 (length numbers) sres))))
11001 sres))))
11002
11003 (defun org-table-get-number-for-summing (s)
11004 (let (n)
11005 (if (string-match "^ *|? *" s)
11006 (setq s (replace-match "" nil nil s)))
11007 (if (string-match " *|? *$" s)
11008 (setq s (replace-match "" nil nil s)))
11009 (setq n (string-to-number s))
11010 (cond
11011 ((and (string-match "0" s)
11012 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
11013 ((string-match "\\`[ \t]+\\'" s) nil)
11014 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
11015 (let ((h (string-to-number (or (match-string 1 s) "0")))
11016 (m (string-to-number (or (match-string 2 s) "0")))
11017 (s (string-to-number (or (match-string 4 s) "0"))))
11018 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
11019 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
11020 ((equal n 0) nil)
11021 (t n))))
11022
11023 (defun org-table-get-vertical-vector (desc &optional tbeg col)
11024 "Get a calc vector from a column, accorting to descriptor DESC.
11025 Optional arguments TBEG and COL can give the beginning of the table and
11026 the current column, to avoid unnecessary parsing."
11027 (save-excursion
11028 (or tbeg (setq tbeg (org-table-begin)))
11029 (or col (setq col (org-table-current-column)))
11030 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
11031 (cond
11032 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
11033 (setq n1 (- (match-end 1) (match-beginning 1)))
11034 (if (match-beginning 3)
11035 (setq n2 (- (match-end 2) (match-beginning 3))))
11036 (setq n (if n2 (max n1 n2) n1))
11037 (setq n1 (if n2 (min n1 n2)))
11038 (setq nn n)
11039 (while (and (> nn 0)
11040 (re-search-backward org-table-hline-regexp tbeg t))
11041 (push (org-current-line) hline-list)
11042 (setq nn (1- nn)))
11043 (setq hline-list (nreverse hline-list))
11044 (goto-line (nth (1- n) hline-list))
11045 (when (re-search-forward org-table-dataline-regexp)
11046 (org-table-goto-column col)
11047 (setq beg (point)))
11048 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
11049 (when (re-search-backward org-table-dataline-regexp)
11050 (org-table-goto-column col)
11051 (setq end (point)))
11052 (setq l (apply 'append (org-table-copy-region beg end)))
11053 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
11054 (if (equal x "") "0" x))
11055 l ",") "]"))
11056 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
11057 (setq n1 (string-to-number (match-string 1 desc))
11058 n2 (string-to-number (match-string 2 desc)))
11059 (beginning-of-line 1)
11060 (save-excursion
11061 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
11062 (org-table-goto-column col)
11063 (setq beg (point))))
11064 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
11065 (org-table-goto-column col)
11066 (setq end (point)))
11067 (setq l (apply 'append (org-table-copy-region beg end)))
11068 (concat "[" (mapconcat
11069 (lambda (x) (setq x (org-trim x))
11070 (if (equal x "") "0" x))
11071 l ",") "]"))
11072 ((string-match "\\([0-9]+\\)" desc)
11073 (beginning-of-line 1)
11074 (when (re-search-backward org-table-dataline-regexp tbeg t
11075 (string-to-number (match-string 0 desc)))
11076 (org-table-goto-column col)
11077 (org-trim (org-table-get-field))))))))
11078
11079 (defvar org-table-formula-history nil)
11080
11081 (defvar org-table-column-names nil
11082 "Alist with column names, derived from the `!' line.")
11083 (defvar org-table-column-name-regexp nil
11084 "Regular expression matching the current column names.")
11085 (defvar org-table-local-parameters nil
11086 "Alist with parameter names, derived from the `$' line.")
11087 (defvar org-table-named-field-locations nil
11088 "Alist with locations of named fields.")
11089
11090 (defun org-table-get-formula (&optional equation named)
11091 "Read a formula from the minibuffer, offer stored formula as default."
11092 (let* ((name (car (rassoc (list (org-current-line)
11093 (org-table-current-column))
11094 org-table-named-field-locations)))
11095 (scol (if named
11096 (if name name
11097 (error "Not in a named field"))
11098 (int-to-string (org-table-current-column))))
11099 (dummy (and name (not named)
11100 (not (y-or-n-p "Replace named-field formula with column equation? " ))
11101 (error "Abort")))
11102 (org-table-may-need-update nil)
11103 (stored-list (org-table-get-stored-formulas))
11104 (stored (cdr (assoc scol stored-list)))
11105 (eq (cond
11106 ((and stored equation (string-match "^ *=? *$" equation))
11107 stored)
11108 ((stringp equation)
11109 equation)
11110 (t (read-string
11111 (format "%s formula $%s=" (if named "Field" "Column") scol)
11112 (or stored "") 'org-table-formula-history
11113 ;stored
11114 ))))
11115 mustsave)
11116 (when (not (string-match "\\S-" eq))
11117 ;; remove formula
11118 (setq stored-list (delq (assoc scol stored-list) stored-list))
11119 (org-table-store-formulas stored-list)
11120 (error "Formula removed"))
11121 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
11122 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
11123 (if (and name (not named))
11124 ;; We set the column equation, delete the named one.
11125 (setq stored-list (delq (assoc name stored-list) stored-list)
11126 mustsave t))
11127 (if stored
11128 (setcdr (assoc scol stored-list) eq)
11129 (setq stored-list (cons (cons scol eq) stored-list)))
11130 (if (or mustsave (not (equal stored eq)))
11131 (org-table-store-formulas stored-list))
11132 eq))
11133
11134 (defun org-table-store-formulas (alist)
11135 "Store the list of formulas below the current table."
11136 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
11137 (save-excursion
11138 (goto-char (org-table-end))
11139 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
11140 (delete-region (point) (match-end 0)))
11141 (insert "#+TBLFM: "
11142 (mapconcat (lambda (x)
11143 (concat "$" (car x) "=" (cdr x)))
11144 alist "::")
11145 "\n")))
11146
11147 (defun org-table-get-stored-formulas ()
11148 "Return an alist with the stored formulas directly after current table."
11149 (interactive)
11150 (let (scol eq eq-alist strings string seen)
11151 (save-excursion
11152 (goto-char (org-table-end))
11153 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
11154 (setq strings (org-split-string (match-string 2) " *:: *"))
11155 (while (setq string (pop strings))
11156 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
11157 (setq scol (match-string 1 string)
11158 eq (match-string 2 string)
11159 eq-alist (cons (cons scol eq) eq-alist))
11160 (if (member scol seen)
11161 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
11162 (push scol seen))))))
11163 (nreverse eq-alist)))
11164
11165 (defun org-table-modify-formulas (action &rest columns)
11166 "Modify the formulas stored below the current table.
11167 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
11168 expected, for the other actions only a single column number is needed."
11169 (let ((list (org-table-get-stored-formulas))
11170 (nmax (length (org-split-string
11171 (buffer-substring (point-at-bol) (point-at-eol))
11172 "|")))
11173 col col1 col2 scol si sc1 sc2)
11174 (cond
11175 ((null list)) ; No action needed if there are no stored formulas
11176 ((eq action 'remove)
11177 (setq col (car columns)
11178 scol (int-to-string col))
11179 (org-table-replace-in-formulas list scol "INVALID")
11180 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
11181 (loop for i from (1+ col) upto nmax by 1 do
11182 (setq si (int-to-string i))
11183 (org-table-replace-in-formulas list si (int-to-string (1- i)))
11184 (if (assoc si list) (setcar (assoc si list)
11185 (int-to-string (1- i))))))
11186 ((eq action 'insert)
11187 (setq col (car columns))
11188 (loop for i from nmax downto col by 1 do
11189 (setq si (int-to-string i))
11190 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
11191 (if (assoc si list) (setcar (assoc si list)
11192 (int-to-string (1+ i))))))
11193 ((eq action 'swap)
11194 (setq col1 (car columns) col2 (nth 1 columns)
11195 sc1 (int-to-string col1) sc2 (int-to-string col2))
11196 ;; Hopefully, ZqZtZ will never be a name in a table
11197 (org-table-replace-in-formulas list sc1 "ZqZtZ")
11198 (org-table-replace-in-formulas list sc2 sc1)
11199 (org-table-replace-in-formulas list "ZqZtZ" sc2)
11200 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
11201 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
11202 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
11203 (t (error "Invalid action in `org-table-modify-formulas'")))
11204 (if list (org-table-store-formulas list))))
11205
11206 (defun org-table-replace-in-formulas (list s1 s2)
11207 (let (elt re s)
11208 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
11209 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
11210 re (concat (regexp-quote s1) "\\>"))
11211 (while (setq elt (pop list))
11212 (setq s (cdr elt))
11213 (while (string-match re s)
11214 (setq s (replace-match s2 t t s)))
11215 (setcdr elt s))))
11216
11217 (defun org-table-get-specials ()
11218 "Get the column names and local parameters for this table."
11219 (save-excursion
11220 (let ((beg (org-table-begin)) (end (org-table-end))
11221 names name fields fields1 field cnt c v line col)
11222 (setq org-table-column-names nil
11223 org-table-local-parameters nil
11224 org-table-named-field-locations nil)
11225 (goto-char beg)
11226 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
11227 (setq names (org-split-string (match-string 1) " *| *")
11228 cnt 1)
11229 (while (setq name (pop names))
11230 (setq cnt (1+ cnt))
11231 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
11232 (push (cons name (int-to-string cnt)) org-table-column-names))))
11233 (setq org-table-column-names (nreverse org-table-column-names))
11234 (setq org-table-column-name-regexp
11235 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
11236 (goto-char beg)
11237 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
11238 (setq fields (org-split-string (match-string 1) " *| *"))
11239 (while (setq field (pop fields))
11240 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
11241 (push (cons (match-string 1 field) (match-string 2 field))
11242 org-table-local-parameters))))
11243 (goto-char beg)
11244 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
11245 (setq c (match-string 1)
11246 fields (org-split-string (match-string 2) " *| *"))
11247 (save-excursion
11248 (beginning-of-line (if (equal c "_") 2 0))
11249 (setq line (org-current-line) col 1)
11250 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
11251 (setq fields1 (org-split-string (match-string 1) " *| *"))))
11252 (while (and fields1 (setq field (pop fields)))
11253 (setq v (pop fields1) col (1+ col))
11254 (when (and (stringp field) (stringp v)
11255 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
11256 (push (cons field v) org-table-local-parameters)
11257 (push (list field line col) org-table-named-field-locations)))))))
11258
11259 (defun org-this-word ()
11260 ;; Get the current word
11261 (save-excursion
11262 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
11263 (end (progn (skip-chars-forward "^ \t\n") (point))))
11264 (buffer-substring-no-properties beg end))))
11265
11266 (defun org-table-maybe-eval-formula ()
11267 "Check if the current field starts with \"=\" or \":=\".
11268 If yes, store the formula and apply it."
11269 ;; We already know we are in a table. Get field will only return a formula
11270 ;; when appropriate. It might return a separator line, but no problem.
11271 (when org-table-formula-evaluate-inline
11272 (let* ((field (org-trim (or (org-table-get-field) "")))
11273 named eq)
11274 (when (string-match "^:?=\\(.*\\)" field)
11275 (setq named (equal (string-to-char field) ?:)
11276 eq (match-string 1 field))
11277 (if (fboundp 'calc-eval)
11278 (org-table-eval-formula (if named '(4) nil) eq))))))
11279
11280 (defvar org-recalc-commands nil
11281 "List of commands triggering the recalculation of a line.
11282 Will be filled automatically during use.")
11283
11284 (defvar org-recalc-marks
11285 '((" " . "Unmarked: no special line, no automatic recalculation")
11286 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
11287 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
11288 ("!" . "Column name definition line. Reference in formula as $name.")
11289 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
11290 ("_" . "Names for values in row below this one.")
11291 ("^" . "Names for values in row above this one.")))
11292
11293 (defun org-table-rotate-recalc-marks (&optional newchar)
11294 "Rotate the recalculation mark in the first column.
11295 If in any row, the first field is not consistent with a mark,
11296 insert a new column for the markers.
11297 When there is an active region, change all the lines in the region,
11298 after prompting for the marking character.
11299 After each change, a message will be displayed indicating the meaning
11300 of the new mark."
11301 (interactive)
11302 (unless (org-at-table-p) (error "Not at a table"))
11303 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
11304 (beg (org-table-begin))
11305 (end (org-table-end))
11306 (l (org-current-line))
11307 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
11308 (l2 (if (org-region-active-p) (org-current-line (region-end))))
11309 (have-col
11310 (save-excursion
11311 (goto-char beg)
11312 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
11313 (col (org-table-current-column))
11314 (forcenew (car (assoc newchar org-recalc-marks)))
11315 epos new)
11316 (when l1
11317 (message "Change region to what mark? Type # * ! $ or SPC: ")
11318 (setq newchar (char-to-string (read-char-exclusive))
11319 forcenew (car (assoc newchar org-recalc-marks))))
11320 (if (and newchar (not forcenew))
11321 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
11322 newchar))
11323 (if l1 (goto-line l1))
11324 (save-excursion
11325 (beginning-of-line 1)
11326 (unless (looking-at org-table-dataline-regexp)
11327 (error "Not at a table data line")))
11328 (unless have-col
11329 (org-table-goto-column 1)
11330 (org-table-insert-column)
11331 (org-table-goto-column (1+ col)))
11332 (setq epos (point-at-eol))
11333 (save-excursion
11334 (beginning-of-line 1)
11335 (org-table-get-field
11336 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
11337 (concat " "
11338 (setq new (or forcenew
11339 (cadr (member (match-string 1) marks))))
11340 " ")
11341 " # ")))
11342 (if (and l1 l2)
11343 (progn
11344 (goto-line l1)
11345 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
11346 (and (looking-at org-table-dataline-regexp)
11347 (org-table-get-field 1 (concat " " new " "))))
11348 (goto-line l1)))
11349 (if (not (= epos (point-at-eol))) (org-table-align))
11350 (goto-line l)
11351 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
11352
11353 (defun org-table-maybe-recalculate-line ()
11354 "Recompute the current line if marked for it, and if we haven't just done it."
11355 (interactive)
11356 (and org-table-allow-automatic-line-recalculation
11357 (not (and (memq last-command org-recalc-commands)
11358 (equal org-last-recalc-line (org-current-line))))
11359 (save-excursion (beginning-of-line 1)
11360 (looking-at org-table-auto-recalculate-regexp))
11361 (fboundp 'calc-eval)
11362 (org-table-recalculate) t))
11363
11364 (defvar org-table-formula-debug nil
11365 "Non-nil means, debug table formulas.
11366 When nil, simply write \"#ERROR\" in corrupted fields.")
11367
11368 (defvar modes)
11369 (defsubst org-set-calc-mode (var &optional value)
11370 (if (stringp var)
11371 (setq var (assoc var '(("D" calc-angle-mode deg)
11372 ("R" calc-angle-mode rad)
11373 ("F" calc-prefer-frac t)
11374 ("S" calc-symbolic-mode t)))
11375 value (nth 2 var) var (nth 1 var)))
11376 (if (memq var modes)
11377 (setcar (cdr (memq var modes)) value)
11378 (cons var (cons value modes)))
11379 modes)
11380
11381 (defun org-table-eval-formula (&optional arg equation
11382 suppress-align suppress-const
11383 suppress-store)
11384 "Replace the table field value at the cursor by the result of a calculation.
11385
11386 This function makes use of Dave Gillespie's Calc package, in my view the
11387 most exciting program ever written for GNU Emacs. So you need to have Calc
11388 installed in order to use this function.
11389
11390 In a table, this command replaces the value in the current field with the
11391 result of a formula. It also installs the formula as the \"current\" column
11392 formula, by storing it in a special line below the table. When called
11393 with a `C-u' prefix, the current field must ba a named field, and the
11394 formula is installed as valid in only this specific field.
11395
11396 When called, the command first prompts for a formula, which is read in
11397 the minibuffer. Previously entered formulas are available through the
11398 history list, and the last used formula is offered as a default.
11399 These stored formulas are adapted correctly when moving, inserting, or
11400 deleting columns with the corresponding commands.
11401
11402 The formula can be any algebraic expression understood by the Calc package.
11403 For details, see the Org-mode manual.
11404
11405 This function can also be called from Lisp programs and offers
11406 additional arguments: EQUATION can be the formula to apply. If this
11407 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
11408 used to speed-up recursive calls by by-passing unnecessary aligns.
11409 SUPPRESS-CONST suppresses the interpretation of constants in the
11410 formula, assuming that this has been done already outside the function.
11411 SUPPRESS-STORE means the formula should not be stored, either because
11412 it is already stored, or because it is a modified equation that should
11413 not overwrite the stored one."
11414 (interactive "P")
11415 (require 'calc)
11416 (org-table-check-inside-data-field)
11417 (org-table-get-specials)
11418 (let* (fields
11419 (ndown (if (integerp arg) arg 1))
11420 (org-table-automatic-realign nil)
11421 (case-fold-search nil)
11422 (down (> ndown 1))
11423 (formula (if (and equation suppress-store)
11424 equation
11425 (org-table-get-formula equation (equal arg '(4)))))
11426 (n0 (org-table-current-column))
11427 (modes (copy-sequence org-calc-default-modes))
11428 n form fmt x ev orig c lispp)
11429 ;; Parse the format string. Since we have a lot of modes, this is
11430 ;; a lot of work. However, I think calc still uses most of the time.
11431 (if (string-match ";" formula)
11432 (let ((tmp (org-split-string formula ";")))
11433 (setq formula (car tmp)
11434 fmt (concat (cdr (assoc "%" org-table-local-parameters))
11435 (nth 1 tmp)))
11436 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
11437 (setq c (string-to-char (match-string 1 fmt))
11438 n (string-to-number (or (match-string 1 fmt) "")))
11439 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
11440 (setq modes (org-set-calc-mode
11441 'calc-float-format
11442 (list (cdr (assoc c '((?n . float) (?f . fix)
11443 (?s . sci) (?e . eng))))
11444 n))))
11445 (setq fmt (replace-match "" t t fmt)))
11446 (while (string-match "[DRFS]" fmt)
11447 (setq modes (org-set-calc-mode (match-string 0 fmt)))
11448 (setq fmt (replace-match "" t t fmt)))
11449 (unless (string-match "\\S-" fmt)
11450 (setq fmt nil))))
11451 (if (and (not suppress-const) org-table-formula-use-constants)
11452 (setq formula (org-table-formula-substitute-names formula)))
11453 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
11454 (while (> ndown 0)
11455 (setq fields (org-split-string
11456 (buffer-substring
11457 (point-at-bol) (point-at-eol)) " *| *"))
11458 (if org-table-formula-numbers-only
11459 (setq fields (mapcar
11460 (lambda (x) (number-to-string (string-to-number x)))
11461 fields)))
11462 (setq ndown (1- ndown))
11463 (setq form (copy-sequence formula)
11464 lispp (equal (substring form 0 2) "'("))
11465 ;; Insert the references to fields in same row
11466 (while (string-match "\\$\\([0-9]+\\)?" form)
11467 (setq n (if (match-beginning 1)
11468 (string-to-number (match-string 1 form))
11469 n0)
11470 x (nth (1- n) fields))
11471 (unless x (error "Invalid field specifier \"%s\""
11472 (match-string 0 form)))
11473 (if (equal x "") (setq x "0"))
11474 (setq form (replace-match
11475 (if lispp x (concat "(" x ")"))
11476 t t form)))
11477 ;; Insert ranges in current column
11478 (while (string-match "\\&[-I0-9]+" form)
11479 (setq form (replace-match
11480 (save-match-data
11481 (org-table-get-vertical-vector (match-string 0 form)
11482 nil n0))
11483 t t form)))
11484 (if lispp
11485 (setq ev (eval (eval (read form)))
11486 ev (if (numberp ev) (number-to-string ev) ev))
11487 (setq ev (calc-eval (cons form modes)
11488 (if org-table-formula-numbers-only 'num))))
11489
11490 (when org-table-formula-debug
11491 (with-output-to-temp-buffer "*Help*"
11492 (princ (format "Substitution history of formula
11493 Orig: %s
11494 $xyz-> %s
11495 $1-> %s\n" orig formula form))
11496 (if (listp ev)
11497 (princ (format " %s^\nError: %s"
11498 (make-string (car ev) ?\-) (nth 1 ev)))
11499 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
11500 ev (or fmt "NONE")
11501 (if fmt (format fmt (string-to-number ev)) ev)))))
11502 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
11503 (unless (and (interactive-p) (not ndown))
11504 (unless (let (inhibit-redisplay)
11505 (y-or-n-p "Debugging Formula. Continue to next? "))
11506 (org-table-align)
11507 (error "Abort"))
11508 (delete-window (get-buffer-window "*Help*"))
11509 (message "")))
11510 (if (listp ev) (setq fmt nil ev "#ERROR"))
11511 (org-table-justify-field-maybe
11512 (if fmt (format fmt (string-to-number ev)) ev))
11513 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
11514 (call-interactively 'org-return)
11515 (setq ndown 0)))
11516 (and down (org-table-maybe-recalculate-line))
11517 (or suppress-align (and org-table-may-need-update
11518 (org-table-align)))))
11519
11520 (defun org-table-recalculate (&optional all noalign)
11521 "Recalculate the current table line by applying all stored formulas.
11522 With prefix arg ALL, do this for all lines in the table."
11523 (interactive "P")
11524 (or (memq this-command org-recalc-commands)
11525 (setq org-recalc-commands (cons this-command org-recalc-commands)))
11526 (unless (org-at-table-p) (error "Not at a table"))
11527 (org-table-get-specials)
11528 (let* ((eqlist (sort (org-table-get-stored-formulas)
11529 (lambda (a b) (string< (car a) (car b)))))
11530 (inhibit-redisplay t)
11531 (line-re org-table-dataline-regexp)
11532 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11533 (thiscol (org-table-current-column))
11534 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
11535 ;; Insert constants in all formulas
11536 (setq eqlist
11537 (mapcar (lambda (x)
11538 (setcdr x (org-table-formula-substitute-names (cdr x)))
11539 x)
11540 eqlist))
11541 ;; Split the equation list
11542 (while (setq eq (pop eqlist))
11543 (if (<= (string-to-char (car eq)) ?9)
11544 (push eq eqlnum)
11545 (push eq eqlname)))
11546 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
11547 (if all
11548 (progn
11549 (setq end (move-marker (make-marker) (1+ (org-table-end))))
11550 (goto-char (setq beg (org-table-begin)))
11551 (if (re-search-forward org-table-calculate-mark-regexp end t)
11552 ;; This is a table with marked lines, only compute selected lines
11553 (setq line-re org-table-recalculate-regexp)
11554 ;; Move forward to the first non-header line
11555 (if (and (re-search-forward org-table-dataline-regexp end t)
11556 (re-search-forward org-table-hline-regexp end t)
11557 (re-search-forward org-table-dataline-regexp end t))
11558 (setq beg (match-beginning 0))
11559 nil))) ;; just leave beg where it is
11560 (setq beg (point-at-bol)
11561 end (move-marker (make-marker) (1+ (point-at-eol)))))
11562 (goto-char beg)
11563 (and all (message "Re-applying formulas to full table..."))
11564 (while (re-search-forward line-re end t)
11565 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
11566 ;; Unprotected line, recalculate
11567 (and all (message "Re-applying formulas to full table...(line %d)"
11568 (setq cnt (1+ cnt))))
11569 (setq org-last-recalc-line (org-current-line))
11570 (setq eql eqlnum)
11571 (while (setq entry (pop eql))
11572 (goto-line org-last-recalc-line)
11573 (org-table-goto-column (string-to-number (car entry)) nil 'force)
11574 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
11575 (goto-line thisline)
11576 (org-table-goto-column thiscol)
11577 (or noalign (and org-table-may-need-update (org-table-align))
11578 (and all (message "Re-applying formulas to %d lines...done" cnt)))
11579 ;; Now do the names fields
11580 (while (setq eq (pop eqlname))
11581 (setq name (car eq)
11582 a (assoc name org-table-named-field-locations))
11583 (when a
11584 (message "Re-applying formula to named field: %s" name)
11585 (goto-line (nth 1 a))
11586 (org-table-goto-column (nth 2 a))
11587 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
11588 ;; back to initial position
11589 (goto-line thisline)
11590 (org-table-goto-column thiscol)
11591 (or noalign (and org-table-may-need-update (org-table-align))
11592 (and all (message "Re-applying formulas...done")))))
11593
11594 (defun org-table-formula-substitute-names (f)
11595 "Replace $const with values in string F."
11596 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
11597 ;; First, check for column names
11598 (while (setq start (string-match org-table-column-name-regexp f start))
11599 (setq start (1+ start))
11600 (setq a (assoc (match-string 1 f) org-table-column-names))
11601 (setq f (replace-match (concat "$" (cdr a)) t t f)))
11602 ;; Expand ranges to vectors
11603 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
11604 (setq n1 (string-to-number (match-string 1 f))
11605 n2 (string-to-number (match-string 2 f))
11606 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
11607 s (concat "[($" (number-to-string (1- nn1)) ")"))
11608 (loop for i from nn1 upto nn2 do
11609 (setq s (concat s ",($" (int-to-string i) ")")))
11610 (setq s (concat s "]"))
11611 (if (< n2 n1) (setq s (concat "rev(" s ")")))
11612 (setq f (replace-match s t t f)))
11613 ;; Parameters and constants
11614 (setq start 0)
11615 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
11616 (setq start (1+ start))
11617 (if (setq a (save-match-data
11618 (org-table-get-constant (match-string 1 f))))
11619 (setq f (replace-match (concat "(" a ")") t t f))))
11620 (if org-table-formula-debug
11621 (put-text-property 0 (length f) :orig-formula f1 f))
11622 f))
11623
11624 (defun org-table-get-constant (const)
11625 "Find the value for a parameter or constant in a formula.
11626 Parameters get priority."
11627 (or (cdr (assoc const org-table-local-parameters))
11628 (cdr (assoc const org-table-formula-constants))
11629 (and (fboundp 'constants-get) (constants-get const))
11630 "#UNDEFINED_NAME"))
11631
11632 (defvar org-edit-formulas-map (make-sparse-keymap))
11633 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
11634 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
11635 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
11636
11637 (defvar org-pos)
11638
11639 (defun org-table-edit-formulas ()
11640 "Edit the formulas of the current table in a separate buffer."
11641 (interactive)
11642 (unless (org-at-table-p)
11643 (error "Not at a table"))
11644 (org-table-get-specials)
11645 (let ((eql (org-table-get-stored-formulas))
11646 (pos (move-marker (make-marker) (point)))
11647 (wc (current-window-configuration))
11648 entry loc s)
11649 (switch-to-buffer-other-window "*Edit Formulas*")
11650 (erase-buffer)
11651 (fundamental-mode)
11652 (set (make-local-variable 'org-pos) pos)
11653 (set (make-local-variable 'org-window-configuration) wc)
11654 (use-local-map org-edit-formulas-map)
11655 (setq s "# Edit formulas and finish with `C-c C-c'.
11656 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
11657 # Use `C-c ?' to get information about $name at point.
11658 # To cancel editing, press `C-c C-q'.\n")
11659 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
11660 (insert s)
11661 (while (setq entry (pop eql))
11662 (when (setq loc (assoc (car entry) org-table-named-field-locations))
11663 (setq s (format "# Named formula, referring to column %d in line %d\n"
11664 (nth 2 loc) (nth 1 loc)))
11665 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
11666 (insert s))
11667 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
11668 (remove-text-properties 0 (length s) '(face nil) s)
11669 (insert s))
11670 (goto-char (point-min))
11671 (message "Edit formulas and finish with `C-c C-c'.")))
11672
11673 (defun org-show-variable ()
11674 "Show the location/value of the $ expression at point."
11675 (interactive)
11676 (let (var (pos org-pos) (win (selected-window)) e)
11677 (save-excursion
11678 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
11679 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
11680 (setq var (match-string 1))
11681 (error "No variable at point")))
11682 (cond
11683 ((setq e (assoc var org-table-named-field-locations))
11684 (switch-to-buffer-other-window (marker-buffer pos))
11685 (goto-line (nth 1 e))
11686 (org-table-goto-column (nth 2 e))
11687 (select-window win)
11688 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11689 ((setq e (assoc var org-table-column-names))
11690 (switch-to-buffer-other-window (marker-buffer pos))
11691 (goto-char pos)
11692 (goto-char (org-table-begin))
11693 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11694 (org-table-end) t)
11695 (progn
11696 (goto-char (match-beginning 1))
11697 (message "Named column (column %s)" (cdr e)))
11698 (error "Column name not found"))
11699 (select-window win))
11700 ((string-match "^[0-9]$" var)
11701 ;; column number
11702 (switch-to-buffer-other-window (marker-buffer pos))
11703 (goto-char pos)
11704 (goto-char (org-table-begin))
11705 (recenter 1)
11706 (if (re-search-forward org-table-dataline-regexp
11707 (org-table-end) t)
11708 (progn
11709 (goto-char (match-beginning 0))
11710 (org-table-goto-column (string-to-number var))
11711 (message "Column %s" var))
11712 (error "Column name not found"))
11713 (select-window win))
11714 ((setq e (assoc var org-table-local-parameters))
11715 (switch-to-buffer-other-window (marker-buffer pos))
11716 (goto-char pos)
11717 (goto-char (org-table-begin))
11718 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11719 (progn
11720 (goto-char (match-beginning 1))
11721 (message "Local parameter."))
11722 (error "Parameter not found"))
11723 (select-window win))
11724 (t
11725 (cond
11726 ((setq e (assoc var org-table-formula-constants))
11727 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
11728 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11729 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
11730 (t (error "Undefined name $%s" var)))))))
11731
11732 (defun org-finish-edit-formulas (&optional arg)
11733 "Parse the buffer for formula definitions and install them.
11734 With prefix ARG, apply the new formulas to the table."
11735 (interactive "P")
11736 (let ((pos org-pos) eql)
11737 (goto-char (point-min))
11738 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
11739 (push (cons (match-string 1) (match-string 2)) eql))
11740 (set-window-configuration org-window-configuration)
11741 (select-window (get-buffer-window (marker-buffer pos)))
11742 (goto-char pos)
11743 (unless (org-at-table-p)
11744 (error "Lost table position - cannot install formulae"))
11745 (org-table-store-formulas eql)
11746 (move-marker pos nil)
11747 (kill-buffer "*Edit Formulas*")
11748 (if arg
11749 (org-table-recalculate 'all)
11750 (message "New formulas installed - press C-u C-c C-c to apply."))))
11751
11752 (defun org-abort-edit-formulas ()
11753 "Abort editing formulas, without installing the changes."
11754 (interactive)
11755 (let ((pos org-pos))
11756 (set-window-configuration org-window-configuration)
11757 (select-window (get-buffer-window (marker-buffer pos)))
11758 (goto-char pos)
11759 (message "Formula editing aborted without installing changes")))
11760
11761 ;;; The orgtbl minor mode
11762
11763 ;; Define a minor mode which can be used in other modes in order to
11764 ;; integrate the org-mode table editor.
11765
11766 ;; This is really a hack, because the org-mode table editor uses several
11767 ;; keys which normally belong to the major mode, for example the TAB and
11768 ;; RET keys. Here is how it works: The minor mode defines all the keys
11769 ;; necessary to operate the table editor, but wraps the commands into a
11770 ;; function which tests if the cursor is currently inside a table. If that
11771 ;; is the case, the table editor command is executed. However, when any of
11772 ;; those keys is used outside a table, the function uses `key-binding' to
11773 ;; look up if the key has an associated command in another currently active
11774 ;; keymap (minor modes, major mode, global), and executes that command.
11775 ;; There might be problems if any of the keys used by the table editor is
11776 ;; otherwise used as a prefix key.
11777
11778 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11779 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11780 ;; addresses this by checking explicitly for both bindings.
11781
11782 ;; The optimized version (see variable `orgtbl-optimized') takes over
11783 ;; all keys which are bound to `self-insert-command' in the *global map*.
11784 ;; Some modes bind other commands to simple characters, for example
11785 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11786 ;; active, this binding is ignored inside tables and replaced with a
11787 ;; modified self-insert.
11788
11789 (defvar orgtbl-mode nil
11790 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11791 table editor in arbitrary modes.")
11792 (make-variable-buffer-local 'orgtbl-mode)
11793
11794 (defvar orgtbl-mode-map (make-keymap)
11795 "Keymap for `orgtbl-mode'.")
11796
11797 ;;;###autoload
11798 (defun turn-on-orgtbl ()
11799 "Unconditionally turn on `orgtbl-mode'."
11800 (orgtbl-mode 1))
11801
11802 ;;;###autoload
11803 (defun orgtbl-mode (&optional arg)
11804 "The `org-mode' table editor as a minor mode for use in other modes."
11805 (interactive)
11806 (if (eq major-mode 'org-mode)
11807 ;; Exit without error, in case some hook functions calls this
11808 ;; by accident in org-mode.
11809 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11810 (setq orgtbl-mode
11811 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11812 (if orgtbl-mode
11813 (progn
11814 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11815 ;; Make sure we are first in minor-mode-map-alist
11816 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11817 (and c (setq minor-mode-map-alist
11818 (cons c (delq c minor-mode-map-alist)))))
11819 (set (make-local-variable (quote org-table-may-need-update)) t)
11820 (org-add-hook 'before-change-functions 'org-before-change-function
11821 nil 'local)
11822 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
11823 auto-fill-inhibit-regexp)
11824 (set (make-local-variable 'auto-fill-inhibit-regexp)
11825 (if auto-fill-inhibit-regexp
11826 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
11827 "[ \t]*|"))
11828 (org-add-to-invisibility-spec '(org-cwidth))
11829 (easy-menu-add orgtbl-mode-menu)
11830 (run-hooks 'orgtbl-mode-hook))
11831 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11832 (org-cleanup-narrow-column-properties)
11833 (org-remove-from-invisibility-spec '(org-cwidth))
11834 (remove-hook 'before-change-functions 'org-before-change-function t)
11835 (easy-menu-remove orgtbl-mode-menu)
11836 (force-mode-line-update 'all))))
11837
11838 (defun org-cleanup-narrow-column-properties ()
11839 "Remove all properties related to narrow-column invisibility."
11840 (let ((s 1))
11841 (while (setq s (text-property-any s (point-max)
11842 'display org-narrow-column-arrow))
11843 (remove-text-properties s (1+ s) '(display t)))
11844 (setq s 1)
11845 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11846 (remove-text-properties s (1+ s) '(org-cwidth t)))
11847 (setq s 1)
11848 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11849 (remove-text-properties s (1+ s) '(invisible t)))))
11850
11851 ;; Install it as a minor mode.
11852 (put 'orgtbl-mode :included t)
11853 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11854 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11855
11856 (defun orgtbl-make-binding (fun n &rest keys)
11857 "Create a function for binding in the table minor mode.
11858 FUN is the command to call inside a table. N is used to create a unique
11859 command name. KEYS are keys that should be checked in for a command
11860 to execute outside of tables."
11861 (eval
11862 (list 'defun
11863 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11864 '(arg)
11865 (concat "In tables, run `" (symbol-name fun) "'.\n"
11866 "Outside of tables, run the binding of `"
11867 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11868 "'.")
11869 '(interactive "p")
11870 (list 'if
11871 '(org-at-table-p)
11872 (list 'call-interactively (list 'quote fun))
11873 (list 'let '(orgtbl-mode)
11874 (list 'call-interactively
11875 (append '(or)
11876 (mapcar (lambda (k)
11877 (list 'key-binding k))
11878 keys)
11879 '('orgtbl-error))))))))
11880
11881 (defun orgtbl-error ()
11882 "Error when there is no default binding for a table key."
11883 (interactive)
11884 (error "This key is has no function outside tables"))
11885
11886 (defun orgtbl-setup ()
11887 "Setup orgtbl keymaps."
11888 (let ((nfunc 0)
11889 (bindings
11890 (list
11891 '([(meta shift left)] org-table-delete-column)
11892 '([(meta left)] org-table-move-column-left)
11893 '([(meta right)] org-table-move-column-right)
11894 '([(meta shift right)] org-table-insert-column)
11895 '([(meta shift up)] org-table-kill-row)
11896 '([(meta shift down)] org-table-insert-row)
11897 '([(meta up)] org-table-move-row-up)
11898 '([(meta down)] org-table-move-row-down)
11899 '("\C-c\C-w" org-table-cut-region)
11900 '("\C-c\M-w" org-table-copy-region)
11901 '("\C-c\C-y" org-table-paste-rectangle)
11902 '("\C-c-" org-table-insert-hline)
11903 ; '([(shift tab)] org-table-previous-field)
11904 '("\C-m" org-table-next-row)
11905 (list (org-key 'S-return) 'org-table-copy-down)
11906 '([(meta return)] org-table-wrap-region)
11907 '("\C-c\C-q" org-table-wrap-region)
11908 '("\C-c?" org-table-current-column)
11909 '("\C-c " org-table-blank-field)
11910 '("\C-c+" org-table-sum)
11911 '("\C-c=" org-table-eval-formula)
11912 '("\C-c'" org-table-edit-formulas)
11913 '("\C-c`" org-table-edit-field)
11914 '("\C-c*" org-table-recalculate)
11915 '("\C-c|" org-table-create-or-convert-from-region)
11916 '("\C-c^" org-table-sort-lines)
11917 '([(control ?#)] org-table-rotate-recalc-marks)))
11918 elt key fun cmd)
11919 (while (setq elt (pop bindings))
11920 (setq nfunc (1+ nfunc))
11921 (setq key (car elt)
11922 fun (nth 1 elt)
11923 cmd (orgtbl-make-binding fun nfunc key))
11924 (define-key orgtbl-mode-map key cmd))
11925 ;; Special treatment needed for TAB and RET
11926 (define-key orgtbl-mode-map [(return)]
11927 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11928 (define-key orgtbl-mode-map "\C-m"
11929 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11930 (define-key orgtbl-mode-map [(tab)]
11931 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11932 (define-key orgtbl-mode-map "\C-i"
11933 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
11934 (define-key orgtbl-mode-map "\C-i"
11935 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
11936 (define-key orgtbl-mode-map "\C-c\C-c"
11937 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
11938 (when orgtbl-optimized
11939 ;; If the user wants maximum table support, we need to hijack
11940 ;; some standard editing functions
11941 (org-remap orgtbl-mode-map
11942 'self-insert-command 'orgtbl-self-insert-command
11943 'delete-char 'org-delete-char
11944 'delete-backward-char 'org-delete-backward-char)
11945 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
11946 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11947 '("OrgTbl"
11948 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11949 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11950 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11951 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11952 "--"
11953 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11954 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11955 ["Copy Field from Above"
11956 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11957 "--"
11958 ("Column"
11959 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11960 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11961 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11962 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
11963 "--"
11964 ["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])
11965 ("Row"
11966 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11967 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11968 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11969 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11970 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11971 "--"
11972 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11973 ("Rectangle"
11974 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11975 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11976 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11977 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11978 "--"
11979 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11980 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11981 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11982 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11983 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11984 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11985 ["Sum Column/Rectangle" org-table-sum
11986 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11987 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11988 ["Debug Formulas"
11989 (setq org-table-formula-debug (not org-table-formula-debug))
11990 :style toggle :selected org-table-formula-debug]
11991 ))
11992 t)
11993
11994 (defun orgtbl-tab (arg)
11995 "Justification and field motion for `orgtbl-mode'."
11996 (interactive "P")
11997 (if arg (org-table-edit-field t)
11998 (org-table-justify-field-maybe)
11999 (org-table-next-field)))
12000
12001 (defun orgtbl-ret ()
12002 "Justification and field motion for `orgtbl-mode'."
12003 (interactive)
12004 (org-table-justify-field-maybe)
12005 (org-table-next-row))
12006
12007 (defun orgtbl-self-insert-command (N)
12008 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12009 If the cursor is in a table looking at whitespace, the whitespace is
12010 overwritten, and the table is not marked as requiring realignment."
12011 (interactive "p")
12012 (if (and (org-at-table-p)
12013 (or
12014 (and org-table-auto-blank-field
12015 (member last-command
12016 '(orgtbl-hijacker-command-100
12017 orgtbl-hijacker-command-101
12018 orgtbl-hijacker-command-102
12019 orgtbl-hijacker-command-103
12020 orgtbl-hijacker-command-104
12021 orgtbl-hijacker-command-105))
12022 (org-table-blank-field))
12023 t)
12024 (eq N 1)
12025 (looking-at "[^|\n]* +|"))
12026 (let (org-table-may-need-update)
12027 (goto-char (1- (match-end 0)))
12028 (delete-backward-char 1)
12029 (goto-char (match-beginning 0))
12030 (self-insert-command N))
12031 (setq org-table-may-need-update t)
12032 (let (orgtbl-mode)
12033 (call-interactively (key-binding (vector last-input-event))))))
12034
12035 (defun org-force-self-insert (N)
12036 "Needed to enforce self-insert under remapping."
12037 (interactive "p")
12038 (self-insert-command N))
12039
12040 ;;; Exporting
12041
12042 (defconst org-level-max 20)
12043
12044 (defvar org-export-html-preamble nil
12045 "Preamble, to be inserted just after <body>. Set by publishing functions.")
12046 (defvar org-export-html-postamble nil
12047 "Preamble, to be inserted just before </body>. Set by publishing functions.")
12048 (defvar org-export-html-auto-preamble t
12049 "Should default preamble be inserted? Set by publishing functions.")
12050 (defvar org-export-html-auto-postamble t
12051 "Should default postamble be inserted? Set by publishing functions.")
12052
12053 (defconst org-export-plist-vars
12054 '((:language . org-export-default-language)
12055 (:headline-levels . org-export-headline-levels)
12056 (:section-numbers . org-export-with-section-numbers)
12057 (:table-of-contents . org-export-with-toc)
12058 (:emphasize . org-export-with-emphasize)
12059 (:sub-superscript . org-export-with-sub-superscripts)
12060 (:TeX-macros . org-export-with-TeX-macros)
12061 (:fixed-width . org-export-with-fixed-width)
12062 (:timestamps . org-export-with-timestamps)
12063 (:tables . org-export-with-tables)
12064 (:table-auto-headline . org-export-highlight-first-table-line)
12065 (:style . org-export-html-style)
12066 (:convert-org-links . org-export-html-link-org-files-as-html)
12067 (:inline-images . org-export-html-inline-images)
12068 (:expand-quoted-html . org-export-html-expand)
12069 (:timestamp . org-export-html-with-timestamp)
12070 (:publishing-directory . org-export-publishing-directory)
12071 (:preamble . org-export-html-preamble)
12072 (:postamble . org-export-html-postamble)
12073 (:auto-preamble . org-export-html-auto-preamble)
12074 (:auto-postamble . org-export-html-auto-postamble)
12075 (:author . user-full-name)
12076 (:email . user-mail-address)))
12077
12078 (defun org-default-export-plist ()
12079 "Return the property list with default settings for the export variables."
12080 (let ((l org-export-plist-vars) rtn e)
12081 (while (setq e (pop l))
12082 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
12083 rtn))
12084
12085 (defun org-infile-export-plist ()
12086 "Return the property list with file-local settings for export."
12087 (save-excursion
12088 (goto-char 0)
12089 (let ((re (org-make-options-regexp
12090 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12091 (text nil)
12092 p key val text options)
12093 (while (re-search-forward re nil t)
12094 (setq key (org-match-string-no-properties 1)
12095 val (org-match-string-no-properties 2))
12096 (cond
12097 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
12098 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
12099 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
12100 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
12101 ((string-equal key "TEXT")
12102 (setq text (if text (concat text "\n" val) val)))
12103 ((string-equal key "OPTIONS") (setq options val))))
12104 (setq p (plist-put p :text text))
12105 (when options
12106 (let ((op '(("H" . :headline-levels)
12107 ("num" . :section-numbers)
12108 ("toc" . :table-of-contents)
12109 ("\\n" . :preserve-breaks)
12110 ("@" . :expand-quoted-html)
12111 (":" . :fixed-width)
12112 ("|" . :tables)
12113 ("^" . :sub-superscript)
12114 ("*" . :emphasize)
12115 ("TeX" . :TeX-macros)))
12116 o)
12117 (while (setq o (pop op))
12118 (if (string-match (concat (regexp-quote (car o))
12119 ":\\([^ \t\n\r;,.]*\\)")
12120 options)
12121 (setq p (plist-put p (cdr o)
12122 (car (read-from-string
12123 (match-string 1 options)))))))))
12124 p)))
12125
12126 (defun org-combine-plists (&rest plists)
12127 "Create a single property list from all plists in PLISTS.
12128 The process starts by copying the last list, and then setting properties
12129 from the other lists. Settings in the first list are the most significant
12130 ones and overrule settings in the other lists."
12131 (let ((rtn (copy-sequence (pop plists)))
12132 p v ls)
12133 (while plists
12134 (setq ls (pop plists))
12135 (while ls
12136 (setq p (pop ls) v (pop ls))
12137 (setq rtn (plist-put rtn p v))))
12138 rtn))
12139
12140 (defun org-export-directory (type plist)
12141 (let* ((val (plist-get plist :publishing-directory))
12142 (dir (if (listp val)
12143 (or (cdr (assoc type val)) ".")
12144 val)))
12145 dir))
12146
12147 (defun org-export-find-first-heading-line (list)
12148 "Remove all lines from LIST which are before the first headline."
12149 (let ((orig-list list)
12150 (re (concat "^" outline-regexp)))
12151 (while (and list
12152 (not (string-match re (car list))))
12153 (pop list))
12154 (or list orig-list)))
12155
12156 (defun org-skip-comments (lines)
12157 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
12158 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
12159 (re2 "^\\(\\*+\\)[ \t\n\r]")
12160 rtn line level)
12161 (while (setq line (pop lines))
12162 (cond
12163 ((and (string-match re1 line)
12164 (setq level (- (match-end 1) (match-beginning 1))))
12165 ;; Beginning of a COMMENT subtree. Skip it.
12166 (while (and (setq line (pop lines))
12167 (or (not (string-match re2 line))
12168 (> (- (match-end 1) (match-beginning 1)) level))))
12169 (setq lines (cons line lines)))
12170 ((string-match "^#" line)
12171 ;; an ordinary comment line
12172 )
12173 ((and org-export-table-remove-special-lines
12174 (string-match "^[ \t]*|" line)
12175 (or (string-match "^[ \t]*| *[!_^] *|" line)
12176 (and (string-match "| *<[0-9]+> *|" line)
12177 (not (string-match "| *[^ <|]" line)))))
12178 ;; a special table line that should be removed
12179 )
12180 (t (setq rtn (cons line rtn)))))
12181 (nreverse rtn)))
12182
12183 (defun org-export (&optional arg)
12184 (interactive)
12185 (let ((help "[t] insert the export option template
12186 \[v] limit export to visible part of outline tree
12187
12188 \[a] export as ASCII
12189 \[h] export as HTML
12190 \[b] export as HTML and browse immediately
12191 \[x] export as XOXO
12192
12193 \[i] export current file as iCalendar file
12194 \[I] export all agenda files as iCalendar files
12195 \[c] export agenda files into combined iCalendar file
12196
12197 \[F] publish current file
12198 \[P] publish current project
12199 \[X] publish... (project will be prompted for)
12200 \[A] publish all projects")
12201 (cmds
12202 '((?v . org-export-visible)
12203 (?a . org-export-as-ascii)
12204 (?h . org-export-as-html)
12205 (?b . org-export-as-html-and-open)
12206 (?x . org-export-as-xoxo)
12207 (?i . org-export-icalendar-this-file)
12208 (?I . org-export-icalendar-all-agenda-files)
12209 (?c . org-export-icalendar-combine-agenda-files)
12210 (?F . org-publish-current-file)
12211 (?P . org-publish-current-project)
12212 (?X . org-publish)
12213 (?A . org-publish-all)))
12214 r1 r2 ass)
12215 (save-window-excursion
12216 (delete-other-windows)
12217 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
12218 (princ help))
12219 (message "Select command: ")
12220 (setq r1 (read-char-exclusive)))
12221 (setq r2 (if (< r1 27) (+ r1 96) r1))
12222 (if (setq ass (assq r2 cmds))
12223 (call-interactively (cdr ass))
12224 (error "No command associated with key %c" r1))))
12225
12226 ;; ASCII
12227
12228 (defconst org-html-entities
12229 '(("nbsp")
12230 ("iexcl")
12231 ("cent")
12232 ("pound")
12233 ("curren")
12234 ("yen")
12235 ("brvbar")
12236 ("sect")
12237 ("uml")
12238 ("copy")
12239 ("ordf")
12240 ("laquo")
12241 ("not")
12242 ("shy")
12243 ("reg")
12244 ("macr")
12245 ("deg")
12246 ("plusmn")
12247 ("sup2")
12248 ("sup3")
12249 ("acute")
12250 ("micro")
12251 ("para")
12252 ("middot")
12253 ("odot"."o")
12254 ("star"."*")
12255 ("cedil")
12256 ("sup1")
12257 ("ordm")
12258 ("raquo")
12259 ("frac14")
12260 ("frac12")
12261 ("frac34")
12262 ("iquest")
12263 ("Agrave")
12264 ("Aacute")
12265 ("Acirc")
12266 ("Atilde")
12267 ("Auml")
12268 ("Aring") ("AA"."&Aring;")
12269 ("AElig")
12270 ("Ccedil")
12271 ("Egrave")
12272 ("Eacute")
12273 ("Ecirc")
12274 ("Euml")
12275 ("Igrave")
12276 ("Iacute")
12277 ("Icirc")
12278 ("Iuml")
12279 ("ETH")
12280 ("Ntilde")
12281 ("Ograve")
12282 ("Oacute")
12283 ("Ocirc")
12284 ("Otilde")
12285 ("Ouml")
12286 ("times")
12287 ("Oslash")
12288 ("Ugrave")
12289 ("Uacute")
12290 ("Ucirc")
12291 ("Uuml")
12292 ("Yacute")
12293 ("THORN")
12294 ("szlig")
12295 ("agrave")
12296 ("aacute")
12297 ("acirc")
12298 ("atilde")
12299 ("auml")
12300 ("aring")
12301 ("aelig")
12302 ("ccedil")
12303 ("egrave")
12304 ("eacute")
12305 ("ecirc")
12306 ("euml")
12307 ("igrave")
12308 ("iacute")
12309 ("icirc")
12310 ("iuml")
12311 ("eth")
12312 ("ntilde")
12313 ("ograve")
12314 ("oacute")
12315 ("ocirc")
12316 ("otilde")
12317 ("ouml")
12318 ("divide")
12319 ("oslash")
12320 ("ugrave")
12321 ("uacute")
12322 ("ucirc")
12323 ("uuml")
12324 ("yacute")
12325 ("thorn")
12326 ("yuml")
12327 ("fnof")
12328 ("Alpha")
12329 ("Beta")
12330 ("Gamma")
12331 ("Delta")
12332 ("Epsilon")
12333 ("Zeta")
12334 ("Eta")
12335 ("Theta")
12336 ("Iota")
12337 ("Kappa")
12338 ("Lambda")
12339 ("Mu")
12340 ("Nu")
12341 ("Xi")
12342 ("Omicron")
12343 ("Pi")
12344 ("Rho")
12345 ("Sigma")
12346 ("Tau")
12347 ("Upsilon")
12348 ("Phi")
12349 ("Chi")
12350 ("Psi")
12351 ("Omega")
12352 ("alpha")
12353 ("beta")
12354 ("gamma")
12355 ("delta")
12356 ("epsilon")
12357 ("varepsilon"."&epsilon;")
12358 ("zeta")
12359 ("eta")
12360 ("theta")
12361 ("iota")
12362 ("kappa")
12363 ("lambda")
12364 ("mu")
12365 ("nu")
12366 ("xi")
12367 ("omicron")
12368 ("pi")
12369 ("rho")
12370 ("sigmaf") ("varsigma"."&sigmaf;")
12371 ("sigma")
12372 ("tau")
12373 ("upsilon")
12374 ("phi")
12375 ("chi")
12376 ("psi")
12377 ("omega")
12378 ("thetasym") ("vartheta"."&thetasym;")
12379 ("upsih")
12380 ("piv")
12381 ("bull") ("bullet"."&bull;")
12382 ("hellip") ("dots"."&hellip;")
12383 ("prime")
12384 ("Prime")
12385 ("oline")
12386 ("frasl")
12387 ("weierp")
12388 ("image")
12389 ("real")
12390 ("trade")
12391 ("alefsym")
12392 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
12393 ("uarr") ("uparrow"."&uarr;")
12394 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
12395 ("darr")("downarrow"."&darr;")
12396 ("harr") ("leftrightarrow"."&harr;")
12397 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
12398 ("lArr") ("Leftarrow"."&lArr;")
12399 ("uArr") ("Uparrow"."&uArr;")
12400 ("rArr") ("Rightarrow"."&rArr;")
12401 ("dArr") ("Downarrow"."&dArr;")
12402 ("hArr") ("Leftrightarrow"."&hArr;")
12403 ("forall")
12404 ("part") ("partial"."&part;")
12405 ("exist") ("exists"."&exist;")
12406 ("empty") ("emptyset"."&empty;")
12407 ("nabla")
12408 ("isin") ("in"."&isin;")
12409 ("notin")
12410 ("ni")
12411 ("prod")
12412 ("sum")
12413 ("minus")
12414 ("lowast") ("ast"."&lowast;")
12415 ("radic")
12416 ("prop") ("proptp"."&prop;")
12417 ("infin") ("infty"."&infin;")
12418 ("ang") ("angle"."&ang;")
12419 ("and") ("vee"."&and;")
12420 ("or") ("wedge"."&or;")
12421 ("cap")
12422 ("cup")
12423 ("int")
12424 ("there4")
12425 ("sim")
12426 ("cong") ("simeq"."&cong;")
12427 ("asymp")("approx"."&asymp;")
12428 ("ne") ("neq"."&ne;")
12429 ("equiv")
12430 ("le")
12431 ("ge")
12432 ("sub") ("subset"."&sub;")
12433 ("sup") ("supset"."&sup;")
12434 ("nsub")
12435 ("sube")
12436 ("supe")
12437 ("oplus")
12438 ("otimes")
12439 ("perp")
12440 ("sdot") ("cdot"."&sdot;")
12441 ("lceil")
12442 ("rceil")
12443 ("lfloor")
12444 ("rfloor")
12445 ("lang")
12446 ("rang")
12447 ("loz") ("Diamond"."&loz;")
12448 ("spades") ("spadesuit"."&spades;")
12449 ("clubs") ("clubsuit"."&clubs;")
12450 ("hearts") ("diamondsuit"."&hearts;")
12451 ("diams") ("diamondsuit"."&diams;")
12452 ("quot")
12453 ("amp")
12454 ("lt")
12455 ("gt")
12456 ("OElig")
12457 ("oelig")
12458 ("Scaron")
12459 ("scaron")
12460 ("Yuml")
12461 ("circ")
12462 ("tilde")
12463 ("ensp")
12464 ("emsp")
12465 ("thinsp")
12466 ("zwnj")
12467 ("zwj")
12468 ("lrm")
12469 ("rlm")
12470 ("ndash")
12471 ("mdash")
12472 ("lsquo")
12473 ("rsquo")
12474 ("sbquo")
12475 ("ldquo")
12476 ("rdquo")
12477 ("bdquo")
12478 ("dagger")
12479 ("Dagger")
12480 ("permil")
12481 ("lsaquo")
12482 ("rsaquo")
12483 ("euro")
12484
12485 ("arccos"."arccos")
12486 ("arcsin"."arcsin")
12487 ("arctan"."arctan")
12488 ("arg"."arg")
12489 ("cos"."cos")
12490 ("cosh"."cosh")
12491 ("cot"."cot")
12492 ("coth"."coth")
12493 ("csc"."csc")
12494 ("deg"."deg")
12495 ("det"."det")
12496 ("dim"."dim")
12497 ("exp"."exp")
12498 ("gcd"."gcd")
12499 ("hom"."hom")
12500 ("inf"."inf")
12501 ("ker"."ker")
12502 ("lg"."lg")
12503 ("lim"."lim")
12504 ("liminf"."liminf")
12505 ("limsup"."limsup")
12506 ("ln"."ln")
12507 ("log"."log")
12508 ("max"."max")
12509 ("min"."min")
12510 ("Pr"."Pr")
12511 ("sec"."sec")
12512 ("sin"."sin")
12513 ("sinh"."sinh")
12514 ("sup"."sup")
12515 ("tan"."tan")
12516 ("tanh"."tanh")
12517 )
12518 "Entities for TeX->HTML translation.
12519 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
12520 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
12521 In that case, \"\\ent\" will be translated to \"&other;\".
12522 The list contains HTML entities for Latin-1, Greek and other symbols.
12523 It is supplemented by a number of commonly used TeX macros with appropriate
12524 translations. There is currently no way for users to extend this.")
12525
12526 (defun org-cleaned-string-for-export (string &rest parameters)
12527 "Cleanup a buffer substring so that links can be created safely."
12528 (interactive)
12529 (let* ((cb (current-buffer))
12530 (re-radio (and org-target-link-regexp
12531 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
12532 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
12533 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
12534 rtn)
12535 (save-excursion
12536 (set-buffer (get-buffer-create " org-mode-tmp"))
12537 (erase-buffer)
12538 (insert string)
12539 (org-mode)
12540 ;; Find targets in comments and move them out of comments,
12541 ;; but mark them as targets that should be invisible
12542 (goto-char (point-min))
12543 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
12544 (replace-match "\\1(INVISIBLE)"))
12545 ;; Find matches for radio targets and turn them into internal links
12546 (goto-char (point-min))
12547 (when re-radio
12548 (while (re-search-forward re-radio nil t)
12549 (replace-match "\\1[[\\2]]")))
12550 ;; Find all links that contain a newline and put them into a single line
12551 (goto-char (point-min))
12552 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
12553 (replace-match "\\1 \\3")
12554 (goto-char (match-beginning 0)))
12555 ;; Normalize links: Convert angle and plain links into bracket links
12556 (goto-char (point-min))
12557 (while (re-search-forward re-plain-link nil t)
12558 (replace-match
12559 (concat
12560 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
12561 t t))
12562 (goto-char (point-min))
12563 (while (re-search-forward re-angle-link nil t)
12564 (replace-match
12565 (concat
12566 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
12567 t t))
12568 ;; Find multiline emphasis and put them into single line
12569 (when (assq :emph-multiline parameters)
12570 (goto-char (point-min))
12571 (while (re-search-forward org-emph-re nil t)
12572 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
12573 (goto-char (1- (match-end 0)))))
12574
12575 ;; Remove comments
12576 (goto-char (point-min))
12577 (while (re-search-forward "^#.*\n?" nil t)
12578 (replace-match ""))
12579 (setq rtn (buffer-string)))
12580 (kill-buffer " org-mode-tmp")
12581 rtn))
12582
12583 (defun org-solidify-link-text (s &optional alist)
12584 "Take link text and make a safe target out of it."
12585 (save-match-data
12586 (let* ((rtn
12587 (mapconcat
12588 'identity
12589 (org-split-string s "[ \t\r\n]+") "--"))
12590 (a (assoc rtn alist)))
12591 (or (cdr a) rtn))))
12592
12593 (defun org-convert-to-odd-levels ()
12594 "Convert an org-mode file with all levels allowed to one with odd levels.
12595 This will leave level 1 alone, convert level 2 to level 3, level 3 to
12596 level 5 etc."
12597 (interactive)
12598 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
12599 (let ((org-odd-levels-only nil) n)
12600 (save-excursion
12601 (goto-char (point-min))
12602 (while (re-search-forward "^\\*\\*+" nil t)
12603 (setq n (1- (length (match-string 0))))
12604 (while (>= (setq n (1- n)) 0)
12605 (org-demote))
12606 (end-of-line 1))))))
12607
12608
12609 (defun org-convert-to-oddeven-levels ()
12610 "Convert an org-mode file with only odd levels to one with odd and even levels.
12611 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
12612 section with an even level, conversion would destroy the structure of the file. An error
12613 is signaled in this case."
12614 (interactive)
12615 (goto-char (point-min))
12616 ;; First check if there are no even levels
12617 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
12618 (org-show-hierarchy-above)
12619 (error "Not all levels are odd in this file. Conversion not possible."))
12620 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
12621 (let ((org-odd-levels-only nil) n)
12622 (save-excursion
12623 (goto-char (point-min))
12624 (while (re-search-forward "^\\*\\*+" nil t)
12625 (setq n (/ (length (match-string 0)) 2))
12626 (while (>= (setq n (1- n)) 0)
12627 (org-promote))
12628 (end-of-line 1))))))
12629
12630 (defun org-tr-level (n)
12631 "Make N odd if required."
12632 (if org-odd-levels-only (1+ (/ n 2)) n))
12633
12634 (defvar org-last-level nil) ; dynamically scoped variable
12635 (defvar org-ascii-current-indentation nil) ; For communication
12636
12637 (defun org-export-as-ascii (arg)
12638 "Export the outline as a pretty ASCII file.
12639 If there is an active region, export only the region.
12640 The prefix ARG specifies how many levels of the outline should become
12641 underlined headlines. The default is 3."
12642 (interactive "P")
12643 (setq-default org-todo-line-regexp org-todo-line-regexp)
12644 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
12645 (org-infile-export-plist)))
12646 (region
12647 (buffer-substring
12648 (if (org-region-active-p) (region-beginning) (point-min))
12649 (if (org-region-active-p) (region-end) (point-max))))
12650 (lines (org-export-find-first-heading-line
12651 (org-skip-comments
12652 (org-split-string
12653 (org-cleaned-string-for-export region)
12654 "[\r\n]"))))
12655 (org-ascii-current-indentation '(0 . 0))
12656 (org-startup-with-deadline-check nil)
12657 (level 0) line txt
12658 (umax nil)
12659 (case-fold-search nil)
12660 (filename (concat (file-name-as-directory
12661 (org-export-directory :ascii opt-plist))
12662 (file-name-sans-extension
12663 (file-name-nondirectory buffer-file-name))
12664 ".txt"))
12665 (buffer (find-file-noselect filename))
12666 (levels-open (make-vector org-level-max nil))
12667 (odd org-odd-levels-only)
12668 (date (format-time-string "%Y/%m/%d" (current-time)))
12669 (time (format-time-string "%X" (org-current-time)))
12670 (author (plist-get opt-plist :author))
12671 (title (or (plist-get opt-plist :title)
12672 (file-name-sans-extension
12673 (file-name-nondirectory buffer-file-name))))
12674 (options nil)
12675 (email (plist-get opt-plist :email))
12676 (language (plist-get opt-plist :language))
12677 (text nil)
12678 (todo nil)
12679 (lang-words nil))
12680
12681 (setq org-last-level 1)
12682 (org-init-section-numbers)
12683
12684 (find-file-noselect filename)
12685
12686 (setq lang-words (or (assoc language org-export-language-setup)
12687 (assoc "en" org-export-language-setup)))
12688 (if org-export-ascii-show-new-buffer
12689 (switch-to-buffer-other-window buffer)
12690 (set-buffer buffer))
12691 (erase-buffer)
12692 (fundamental-mode)
12693 ;; create local variables for all options, to make sure all called
12694 ;; functions get the correct information
12695 (mapcar (lambda (x)
12696 (set (make-local-variable (cdr x))
12697 (plist-get opt-plist (car x))))
12698 org-export-plist-vars)
12699 (set (make-local-variable 'org-odd-levels-only) odd)
12700 (setq umax (if arg (prefix-numeric-value arg)
12701 org-export-headline-levels))
12702
12703 ;; File header
12704 (if title (org-insert-centered title ?=))
12705 (insert "\n")
12706 (if (or author email)
12707 (insert (concat (nth 1 lang-words) ": " (or author "")
12708 (if email (concat " <" email ">") "")
12709 "\n")))
12710 (if (and date time)
12711 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
12712 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
12713
12714 (insert "\n\n")
12715
12716 (if org-export-with-toc
12717 (progn
12718 (insert (nth 3 lang-words) "\n"
12719 (make-string (length (nth 3 lang-words)) ?=) "\n")
12720 (mapcar '(lambda (line)
12721 (if (string-match org-todo-line-regexp
12722 line)
12723 ;; This is a headline
12724 (progn
12725 (setq level (- (match-end 1) (match-beginning 1))
12726 level (org-tr-level level)
12727 txt (match-string 3 line)
12728 todo
12729 (or (and org-export-mark-todo-in-toc
12730 (match-beginning 2)
12731 (not (equal (match-string 2 line)
12732 org-done-string)))
12733 ; TODO, not DONE
12734 (and org-export-mark-todo-in-toc
12735 (= level umax)
12736 (org-search-todo-below
12737 line lines level))))
12738 (setq txt (org-html-expand-for-ascii txt))
12739
12740 (if org-export-with-section-numbers
12741 (setq txt (concat (org-section-number level)
12742 " " txt)))
12743 (if (<= level umax)
12744 (progn
12745 (insert
12746 (make-string (* (1- level) 4) ?\ )
12747 (format (if todo "%s (*)\n" "%s\n") txt))
12748 (setq org-last-level level))
12749 ))))
12750 lines)))
12751
12752 (org-init-section-numbers)
12753 (while (setq line (pop lines))
12754 ;; Remove the quoted HTML tags.
12755 (setq line (org-html-expand-for-ascii line))
12756 ;; Remove targets
12757 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
12758 (setq line (replace-match "" t t line)))
12759 ;; Replace internal links
12760 (while (string-match org-bracket-link-regexp line)
12761 (setq line (replace-match
12762 (if (match-end 3) "[\\3]" "[\\1]")
12763 t nil line)))
12764 (cond
12765 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
12766 ;; a Headline
12767 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
12768 txt (match-string 2 line))
12769 (org-ascii-level-start level txt umax lines))
12770 (t
12771 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
12772 (normal-mode)
12773 (save-buffer)
12774 ;; remove display and invisible chars
12775 (let (beg end s)
12776 (goto-char (point-min))
12777 (while (setq beg (next-single-property-change (point) 'display))
12778 (setq end (next-single-property-change beg 'display))
12779 (delete-region beg end)
12780 (goto-char beg)
12781 (insert "=>"))
12782 (goto-char (point-min))
12783 (while (setq beg (next-single-property-change (point) 'org-cwidth))
12784 (setq end (next-single-property-change beg 'org-cwidth))
12785 (delete-region beg end)
12786 (goto-char beg)))
12787 (goto-char (point-min))))
12788
12789 (defun org-search-todo-below (line lines level)
12790 "Search the subtree below LINE for any TODO entries."
12791 (let ((rest (cdr (memq line lines)))
12792 (re org-todo-line-regexp)
12793 line lv todo)
12794 (catch 'exit
12795 (while (setq line (pop rest))
12796 (if (string-match re line)
12797 (progn
12798 (setq lv (- (match-end 1) (match-beginning 1))
12799 todo (and (match-beginning 2)
12800 (not (equal (match-string 2 line)
12801 org-done-string))))
12802 ; TODO, not DONE
12803 (if (<= lv level) (throw 'exit nil))
12804 (if todo (throw 'exit t))))))))
12805
12806 (defun org-html-expand-for-ascii (line)
12807 "Handle quoted HTML for ASCII export."
12808 (if org-export-html-expand
12809 (while (string-match "@<[^<>\n]*>" line)
12810 ;; We just remove the tags for now.
12811 (setq line (replace-match "" nil nil line))))
12812 line)
12813
12814 (defun org-insert-centered (s &optional underline)
12815 "Insert the string S centered and underline it with character UNDERLINE."
12816 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
12817 (insert (make-string ind ?\ ) s "\n")
12818 (if underline
12819 (insert (make-string ind ?\ )
12820 (make-string (string-width s) underline)
12821 "\n"))))
12822
12823 (defun org-ascii-level-start (level title umax &optional lines)
12824 "Insert a new level in ASCII export."
12825 (let (char (n (- level umax 1)) (ind 0))
12826 (if (> level umax)
12827 (progn
12828 (insert (make-string (* 2 n) ?\ )
12829 (char-to-string (nth (% n (length org-export-ascii-bullets))
12830 org-export-ascii-bullets))
12831 " " title "\n")
12832 ;; find the indentation of the next non-empty line
12833 (catch 'stop
12834 (while lines
12835 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
12836 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
12837 (throw 'stop (setq ind (org-get-indentation (car lines)))))
12838 (pop lines)))
12839 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
12840 (if (or (not (equal (char-before) ?\n))
12841 (not (equal (char-before (1- (point))) ?\n)))
12842 (insert "\n"))
12843 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
12844 (if org-export-with-section-numbers
12845 (setq title (concat (org-section-number level) " " title)))
12846 (insert title "\n" (make-string (string-width title) char) "\n")
12847 (setq org-ascii-current-indentation '(0 . 0)))))
12848
12849 (defun org-export-visible (type arg)
12850 "Create a copy of the visible part of the current buffer, and export it.
12851 The copy is created in a temporary buffer and removed after use.
12852 TYPE is the final key (as a string) of the `C-c C-x' key sequence that will
12853 run the export command - in interactive use, the command prompts for this
12854 key. As a special case, if the you type SPC at the prompt, the temporary
12855 org-mode file will not be removed but presented to you so that you can
12856 continue to use it. The prefix arg ARG is passed through to the exporting
12857 command."
12858 (interactive
12859 (list (progn
12860 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
12861 (char-to-string (read-char-exclusive)))
12862 current-prefix-arg))
12863 (if (not (member type '("a" "\C-a" "b" "\C-b" "h" "x" " ")))
12864 (error "Invalid export key"))
12865 ;; FIXME: do this more explicit?
12866 (let* ((binding (key-binding (concat "\C-c\C-x" type)))
12867 (keepp (equal type " "))
12868 (file buffer-file-name)
12869 (buffer (get-buffer-create "*Org Export Visible*"))
12870 s e)
12871 (with-current-buffer buffer (erase-buffer))
12872 (save-excursion
12873 (setq s (goto-char (point-min)))
12874 (while (not (= (point) (point-max)))
12875 (goto-char (org-find-invisible))
12876 (append-to-buffer buffer s (point))
12877 (setq s (goto-char (org-find-visible))))
12878 (goto-char (point-min))
12879 (unless keepp
12880 ;; Copy all comment lines to the end, to make sure #+ settings are
12881 ;; still available for the second export step. Kind of a hack, but
12882 ;; does do the trick.
12883 (if (looking-at "#[^\r\n]*")
12884 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
12885 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
12886 (append-to-buffer buffer (1+ (match-beginning 0))
12887 (min (point-max) (1+ (match-end 0))))))
12888 (set-buffer buffer)
12889 (let ((buffer-file-name file)
12890 (org-inhibit-startup t))
12891 (org-mode)
12892 (show-all)
12893 (unless keepp (funcall binding arg))))
12894 (if (not keepp)
12895 (kill-buffer buffer)
12896 (switch-to-buffer-other-window buffer)
12897 (goto-char (point-min)))))
12898
12899 (defun org-find-visible ()
12900 (if (featurep 'noutline)
12901 (let ((s (point)))
12902 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
12903 (get-char-property s 'invisible)))
12904 s)
12905 (skip-chars-forward "^\n")
12906 (point)))
12907 (defun org-find-invisible ()
12908 (if (featurep 'noutline)
12909 (let ((s (point)))
12910 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
12911 (not (get-char-property s 'invisible))))
12912 s)
12913 (skip-chars-forward "^\r")
12914 (point)))
12915
12916
12917 ;; HTML
12918
12919 (defun org-get-current-options ()
12920 "Return a string with current options as keyword options.
12921 Does include HTML export options as well as TODO and CATEGORY stuff."
12922 (format
12923 "#+TITLE: %s
12924 #+AUTHOR: %s
12925 #+EMAIL: %s
12926 #+LANGUAGE: %s
12927 #+TEXT: Some descriptive text to be emitted. Several lines OK.
12928 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
12929 #+CATEGORY: %s
12930 #+SEQ_TODO: %s
12931 #+TYP_TODO: %s
12932 #+STARTUP: %s %s %s %s %s %s
12933 #+TAGS: %s
12934 #+ARCHIVE: %s
12935 "
12936 (buffer-name) (user-full-name) user-mail-address org-export-default-language
12937 org-export-headline-levels
12938 org-export-with-section-numbers
12939 org-export-with-toc
12940 org-export-preserve-breaks
12941 org-export-html-expand
12942 org-export-with-fixed-width
12943 org-export-with-tables
12944 org-export-with-sub-superscripts
12945 org-export-with-emphasize
12946 org-export-with-TeX-macros
12947 (file-name-nondirectory buffer-file-name)
12948 (if (equal org-todo-interpretation 'sequence)
12949 (mapconcat 'identity org-todo-keywords " ")
12950 "TODO FEEDBACK VERIFY DONE")
12951 (if (equal org-todo-interpretation 'type)
12952 (mapconcat 'identity org-todo-keywords " ")
12953 "Me Jason Marie DONE")
12954 (cdr (assoc org-startup-folded
12955 '((nil . "showall") (t . "overview") (content . "content"))))
12956 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
12957 (if org-odd-levels-only "odd" "oddeven")
12958 (if org-hide-leading-stars "hidestars" "showstars")
12959 (if org-startup-align-all-tables "align" "noalign")
12960 (if org-log-done "logging" "nologging")
12961 (if org-tag-alist (mapconcat 'car org-tag-alist " ") "")
12962 org-archive-location
12963 ))
12964
12965 (defun org-insert-export-options-template ()
12966 "Insert into the buffer a template with information for exporting."
12967 (interactive)
12968 (if (not (bolp)) (newline))
12969 (let ((s (org-get-current-options)))
12970 (and (string-match "#\\+CATEGORY" s)
12971 (setq s (substring s 0 (match-beginning 0))))
12972 (insert s)))
12973
12974 (defun org-toggle-fixed-width-section (arg)
12975 "Toggle the fixed-width export.
12976 If there is no active region, the QUOTE keyword at the current headline is
12977 inserted or removed. When present, it causes the text between this headline
12978 and the next to be exported as fixed-width text, and unmodified.
12979 If there is an active region, this command adds or removes a colon as the
12980 first character of this line. If the first character of a line is a colon,
12981 this line is also exported in fixed-width font."
12982 (interactive "P")
12983 (let* ((cc 0)
12984 (regionp (org-region-active-p))
12985 (beg (if regionp (region-beginning) (point)))
12986 (end (if regionp (region-end)))
12987 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
12988 (re "[ \t]*\\(:\\)")
12989 off)
12990 (if regionp
12991 (save-excursion
12992 (goto-char beg)
12993 (setq cc (current-column))
12994 (beginning-of-line 1)
12995 (setq off (looking-at re))
12996 (while (> nlines 0)
12997 (setq nlines (1- nlines))
12998 (beginning-of-line 1)
12999 (cond
13000 (arg
13001 (move-to-column cc t)
13002 (insert ":\n")
13003 (forward-line -1))
13004 ((and off (looking-at re))
13005 (replace-match "" t t nil 1))
13006 ((not off) (move-to-column cc t) (insert ":")))
13007 (forward-line 1)))
13008 (save-excursion
13009 (org-back-to-heading)
13010 (if (looking-at (concat outline-regexp
13011 "\\( +\\<" org-quote-string "\\>\\)"))
13012 (replace-match "" t t nil 1)
13013 (if (looking-at outline-regexp)
13014 (progn
13015 (goto-char (match-end 0))
13016 (insert " " org-quote-string))))))))
13017
13018 (defun org-export-as-html-and-open (arg)
13019 "Export the outline as HTML and immediately open it with a browser.
13020 If there is an active region, export only the region.
13021 The prefix ARG specifies how many levels of the outline should become
13022 headlines. The default is 3. Lower levels will become bulleted lists."
13023 (interactive "P")
13024 (org-export-as-html arg 'hidden)
13025 (org-open-file buffer-file-name))
13026
13027 (defun org-export-as-html-batch ()
13028 "Call `org-export-as-html', may be used in batch processing as
13029 emacs --batch
13030 --load=$HOME/lib/emacs/org.el
13031 --eval \"(setq org-export-headline-levels 2)\"
13032 --visit=MyFile --funcall org-export-as-html-batch"
13033 (org-export-as-html org-export-headline-levels 'hidden))
13034
13035 (defun org-export-as-html (arg &optional hidden ext-plist)
13036 "Export the outline as a pretty HTML file.
13037 If there is an active region, export only the region.
13038 The prefix ARG specifies how many levels of the outline should become
13039 headlines. The default is 3. Lower levels will become bulleted lists.
13040 When HIDDEN is non-nil, don't display the HTML buffer.
13041 EXT-PLIST is a property list with external parameters overriding
13042 org-mode's default settings, but still inferior to file-local settings."
13043 (interactive "P")
13044 (setq-default org-todo-line-regexp org-todo-line-regexp)
13045 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
13046 (setq-default org-done-string org-done-string)
13047 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13048 ext-plist
13049 (org-infile-export-plist)))
13050
13051 (style (plist-get opt-plist :style))
13052 (odd org-odd-levels-only)
13053 (region-p (org-region-active-p))
13054 (region
13055 (buffer-substring
13056 (if region-p (region-beginning) (point-min))
13057 (if region-p (region-end) (point-max))))
13058 (all_lines
13059 (org-skip-comments (org-split-string
13060 (org-cleaned-string-for-export
13061 region :emph-multiline)
13062 "[\r\n]")))
13063 (lines (org-export-find-first-heading-line all_lines))
13064 (level 0) (line "") (origline "") txt todo
13065 (umax nil)
13066 (filename (concat (file-name-as-directory
13067 (org-export-directory :html opt-plist))
13068 (file-name-sans-extension
13069 (file-name-nondirectory buffer-file-name))
13070 ".html"))
13071 (buffer (find-file-noselect filename))
13072 (levels-open (make-vector org-level-max nil))
13073 (date (format-time-string "%Y/%m/%d" (current-time)))
13074 (time (format-time-string "%X" (org-current-time)))
13075 (author (plist-get opt-plist :author))
13076 (title (or (plist-get opt-plist :title)
13077 (file-name-sans-extension
13078 (file-name-nondirectory buffer-file-name))))
13079 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
13080 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
13081 (inquote nil)
13082 (infixed nil)
13083 (in-local-list nil)
13084 (local-list-num nil)
13085 (local-list-indent nil)
13086 (llt org-plain-list-ordered-item-terminator)
13087 (email (plist-get opt-plist :email))
13088 (language (plist-get opt-plist :language))
13089 (text (plist-get opt-plist :text))
13090 (lang-words nil)
13091 (target-alist nil) tg
13092 (head-count 0) cnt
13093 (start 0)
13094 (coding-system (and (fboundp 'coding-system-get)
13095 (boundp 'buffer-file-coding-system)
13096 buffer-file-coding-system))
13097 (coding-system-for-write (or coding-system coding-system-for-write))
13098 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
13099 (charset (and coding-system
13100 (coding-system-get coding-system 'mime-charset)))
13101 table-open type
13102 table-buffer table-orig-buffer
13103 ind start-is-num starter
13104 rpl path desc descp desc1 desc2 link
13105 )
13106 (message "Exporting...")
13107
13108 (setq org-last-level 1)
13109 (org-init-section-numbers)
13110
13111 ;; Get the language-dependent settings
13112 (setq lang-words (or (assoc language org-export-language-setup)
13113 (assoc "en" org-export-language-setup)))
13114
13115 ;; Switch to the output buffer
13116 (if (or hidden (not org-export-html-show-new-buffer))
13117 (set-buffer buffer)
13118 (switch-to-buffer-other-window buffer))
13119 (erase-buffer)
13120 (fundamental-mode)
13121 (let ((case-fold-search nil)
13122 (org-odd-levels-only odd))
13123 ;; create local variables for all options, to make sure all called
13124 ;; functions get the correct information
13125 (mapcar (lambda (x)
13126 (set (make-local-variable (cdr x))
13127 (plist-get opt-plist (car x))))
13128 org-export-plist-vars)
13129 (setq umax (if arg (prefix-numeric-value arg)
13130 org-export-headline-levels))
13131
13132 ;; File header
13133 (insert (format
13134 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
13135 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
13136 <html xmlns=\"http://www.w3.org/1999/xhtml\"
13137 lang=\"%s\" xml:lang=\"%s\">
13138 <head>
13139 <title>%s</title>
13140 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
13141 <meta name=\"generator\" content=\"Org-mode\"/>
13142 <meta name=\"generated\" content=\"%s %s\"/>
13143 <meta name=\"author\" content=\"%s\"/>
13144 %s
13145 </head><body>
13146 "
13147 language language (org-html-expand title) (or charset "iso-8859-1")
13148 date time author style))
13149
13150
13151 (insert (or (plist-get opt-plist :preamble) ""))
13152
13153 (when (plist-get opt-plist :auto-preamble)
13154 (if title (insert (concat "<h1 class=\"title\">"
13155 (org-html-expand title) "</h1>\n")))
13156
13157 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
13158
13159 (if org-export-with-toc
13160 (progn
13161 (insert (format "<h2>%s</h2>\n" (nth 3 lang-words)))
13162 (insert "<ul>\n<li>")
13163 (setq lines
13164 (mapcar '(lambda (line)
13165 (if (string-match org-todo-line-regexp line)
13166 ;; This is a headline
13167 (progn
13168 (setq level (- (match-end 1) (match-beginning 1))
13169 level (org-tr-level level)
13170 txt (save-match-data
13171 (org-html-expand
13172 (org-html-cleanup-toc-line
13173 (match-string 3 line))))
13174 todo
13175 (or (and org-export-mark-todo-in-toc
13176 (match-beginning 2)
13177 (not (equal (match-string 2 line)
13178 org-done-string)))
13179 ; TODO, not DONE
13180 (and org-export-mark-todo-in-toc
13181 (= level umax)
13182 (org-search-todo-below
13183 line lines level))))
13184 (if org-export-with-section-numbers
13185 (setq txt (concat (org-section-number level)
13186 " " txt)))
13187 (if (<= level umax)
13188 (progn
13189 (setq head-count (+ head-count 1))
13190 (if (> level org-last-level)
13191 (progn
13192 (setq cnt (- level org-last-level))
13193 (while (>= (setq cnt (1- cnt)) 0)
13194 (insert "\n<ul>\n<li>"))
13195 (insert "\n")))
13196 (if (< level org-last-level)
13197 (progn
13198 (setq cnt (- org-last-level level))
13199 (while (>= (setq cnt (1- cnt)) 0)
13200 (insert "</li>\n</ul>"))
13201 (insert "\n")))
13202 ;; Check for targets
13203 (while (string-match org-target-regexp line)
13204 (setq tg (match-string 1 line)
13205 line (replace-match
13206 (concat "@<span class=\"target\">" tg "@</span> ")
13207 t t line))
13208 (push (cons (org-solidify-link-text tg)
13209 (format "sec-%d" head-count))
13210 target-alist))
13211 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
13212 (setq txt (replace-match "" t t txt)))
13213 (insert
13214 (format
13215 (if todo
13216 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
13217 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
13218 head-count txt))
13219
13220 (setq org-last-level level))
13221 )))
13222 line)
13223 lines))
13224 (while (> org-last-level 0)
13225 (setq org-last-level (1- org-last-level))
13226 (insert "</li>\n</ul>\n"))
13227 ))
13228 (setq head-count 0)
13229 (org-init-section-numbers)
13230
13231 (while (setq line (pop lines) origline line)
13232 (catch 'nextline
13233
13234 ;; end of quote section?
13235 (when (and inquote (string-match "^\\*+" line))
13236 (insert "</pre>\n")
13237 (setq inquote nil))
13238 ;; inside a quote section?
13239 (when inquote
13240 (insert (org-html-protect line) "\n")
13241 (throw 'nextline nil))
13242
13243 ;; verbatim lines
13244 (when (and org-export-with-fixed-width
13245 (string-match "^[ \t]*:\\(.*\\)" line))
13246 (when (not infixed)
13247 (setq infixed t)
13248 (insert "<pre>\n"))
13249 (insert (org-html-protect (match-string 1 line)) "\n")
13250 (when (and lines
13251 (not (string-match "^[ \t]*\\(:.*\\)"
13252 (car lines))))
13253 (setq infixed nil)
13254 (insert "</pre>\n"))
13255 (throw 'nextline nil))
13256
13257
13258 ;; make targets to anchors
13259 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
13260 (cond
13261 ((match-end 2)
13262 (setq line (replace-match
13263 (concat "@<a name=\""
13264 (org-solidify-link-text (match-string 1 line))
13265 "\">\\nbsp@</a>")
13266 t t line)))
13267 ((and org-export-with-toc (equal (string-to-char line) ?*))
13268 (setq line (replace-match
13269 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
13270 ; (concat "@<i>" (match-string 1 line) "@</i> ")
13271 t t line)))
13272 (t
13273 (setq line (replace-match
13274 (concat "@<a name=\""
13275 (org-solidify-link-text (match-string 1 line))
13276 "\" class=\"target\">" (match-string 1 line) "@</a> ")
13277 t t line)))))
13278
13279 (setq line (org-html-handle-time-stamps line))
13280
13281 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
13282 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
13283 ;; Also handle sub_superscripts and checkboxes
13284 (setq line (org-html-expand line))
13285
13286 ;; Format the links
13287 (setq start 0)
13288 (while (string-match org-bracket-link-analytic-regexp line start)
13289 (setq start (match-beginning 0))
13290 (setq type (if (match-end 2) (match-string 2 line) "internal"))
13291 (setq path (match-string 3 line))
13292 (setq desc1 (if (match-end 5) (match-string 5 line))
13293 desc2 (if (match-end 2) (concat type ":" path) path)
13294 descp (and desc1 (not (equal desc1 desc2)))
13295 desc (or desc1 desc2))
13296 ;; FIXME: do we need to unescape here somewhere?
13297 (cond
13298 ((equal type "internal")
13299 (setq rpl
13300 (concat
13301 "<a href=\"#"
13302 (org-solidify-link-text path target-alist)
13303 "\">" desc "</a>")))
13304 ((member type '("http" "https" "ftp" "mailto" "news"))
13305 ;; standard URL
13306 (setq link (concat type ":" path))
13307 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
13308 ((string= type "file")
13309 ;; FILE link
13310 (let* ((filename path)
13311 (abs-p (file-name-absolute-p filename))
13312 thefile file-is-image-p search)
13313 (save-match-data
13314 (if (string-match "::\\(.*\\)" filename)
13315 (setq search (match-string 1 filename)
13316 filename (replace-match "" t nil filename)))
13317 (setq file-is-image-p
13318 (string-match (org-image-file-name-regexp) filename))
13319 (setq thefile (if abs-p (expand-file-name filename) filename))
13320 (when (and org-export-html-link-org-files-as-html
13321 (string-match "\\.org$" thefile))
13322 (setq thefile (concat (substring thefile 0
13323 (match-beginning 0))
13324 ".html"))
13325 (if (and search
13326 ;; make sure this is can be used as target search
13327 (not (string-match "^[0-9]*$" search))
13328 (not (string-match "^\\*" search))
13329 (not (string-match "^/.*/$" search)))
13330 (setq thefile (concat thefile "#"
13331 (org-solidify-link-text
13332 (org-link-unescape search)))))
13333 (when (string-match "^file:" desc)
13334 (setq desc (replace-match "" t t desc))
13335 (if (string-match "\\.org$" desc)
13336 (setq desc (replace-match "" t t desc))))))
13337 (setq rpl (if (and file-is-image-p
13338 (or (eq t org-export-html-inline-images)
13339 (and org-export-html-inline-images
13340 (not descp))))
13341 (concat "<img src=\"" thefile "\"/>")
13342 (concat "<a href=\"" thefile "\">" desc "</a>")))))
13343 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
13344 (setq rpl (concat "<i>&lt;" type ":"
13345 (save-match-data (org-link-unescape path))
13346 "&gt;</i>"))))
13347 (setq line (replace-match rpl t t line)
13348 start (+ start (length rpl))))
13349 ;; TODO items
13350 (if (and (string-match org-todo-line-regexp line)
13351 (match-beginning 2))
13352 (if (equal (match-string 2 line) org-done-string)
13353 (setq line (replace-match
13354 "<span class=\"done\">\\2</span>"
13355 t nil line 2))
13356 (setq line (replace-match "<span class=\"todo\">\\2</span>"
13357 t nil line 2))))
13358
13359 (cond
13360 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
13361 ;; This is a headline
13362 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
13363 txt (match-string 2 line))
13364 (if (string-match quote-re0 txt)
13365 (setq txt (replace-match "" t t txt)))
13366 (if (<= level umax) (setq head-count (+ head-count 1)))
13367 (when in-local-list
13368 ;; Close any local lists before inserting a new header line
13369 (while local-list-num
13370 (org-close-li)
13371 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
13372 (pop local-list-num))
13373 (setq local-list-indent nil
13374 in-local-list nil))
13375 (org-html-level-start level txt umax
13376 (and org-export-with-toc (<= level umax))
13377 head-count)
13378 ;; QUOTES
13379 (when (string-match quote-re line)
13380 (insert "<pre>")
13381 (setq inquote t)))
13382
13383 ((and org-export-with-tables
13384 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
13385 (if (not table-open)
13386 ;; New table starts
13387 (setq table-open t table-buffer nil table-orig-buffer nil))
13388 ;; Accumulate lines
13389 (setq table-buffer (cons line table-buffer)
13390 table-orig-buffer (cons origline table-orig-buffer))
13391 (when (or (not lines)
13392 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
13393 (car lines))))
13394 (setq table-open nil
13395 table-buffer (nreverse table-buffer)
13396 table-orig-buffer (nreverse table-orig-buffer))
13397 (org-close-par-maybe)
13398 (insert (org-format-table-html table-buffer table-orig-buffer))))
13399 (t
13400 ;; Normal lines
13401 (when (string-match
13402 (cond
13403 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
13404 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
13405 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
13406 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
13407 line)
13408 (setq ind (org-get-string-indentation line)
13409 start-is-num (match-beginning 4)
13410 starter (if (match-beginning 2)
13411 (substring (match-string 2 line) 0 -1))
13412 line (substring line (match-beginning 5)))
13413 (unless (string-match "[^ \t]" line)
13414 ;; empty line. Pretend indentation is large.
13415 (setq ind (1+ (or (car local-list-indent) 1))))
13416 (while (and in-local-list
13417 (or (and (= ind (car local-list-indent))
13418 (not starter))
13419 (< ind (car local-list-indent))))
13420 (org-close-li)
13421 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
13422 (pop local-list-num) (pop local-list-indent)
13423 (setq in-local-list local-list-indent))
13424 (cond
13425 ((and starter
13426 (or (not in-local-list)
13427 (> ind (car local-list-indent))))
13428 ;; Start new (level of ) list
13429 (org-close-par-maybe)
13430 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
13431 (push start-is-num local-list-num)
13432 (push ind local-list-indent)
13433 (setq in-local-list t))
13434 (starter
13435 ;; continue current list
13436 (org-close-li)
13437 (insert "<li>\n")))
13438 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
13439 (setq line
13440 (replace-match
13441 (if (equal (match-string 1 line) "X")
13442 "<b>[X]</b>"
13443 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
13444 t t line))))
13445
13446 ;; Empty lines start a new paragraph. If hand-formatted lists
13447 ;; are not fully interpreted, lines starting with "-", "+", "*"
13448 ;; also start a new paragraph.
13449 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
13450
13451 ;; Check if the line break needs to be conserved
13452 (cond
13453 ((string-match "\\\\\\\\[ \t]*$" line)
13454 (setq line (replace-match "<br/>" t t line)))
13455 (org-export-preserve-breaks
13456 (setq line (concat line "<br/>"))))
13457
13458 (insert line "\n")))))
13459
13460 ;; Properly close all local lists and other lists
13461 (when inquote (insert "</pre>\n"))
13462 (when in-local-list
13463 ;; Close any local lists before inserting a new header line
13464 (while local-list-num
13465 (org-close-li)
13466 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
13467 (pop local-list-num))
13468 (setq local-list-indent nil
13469 in-local-list nil))
13470 (org-html-level-start 1 nil umax
13471 (and org-export-with-toc (<= level umax))
13472 head-count)
13473
13474 (when (plist-get opt-plist :auto-postamble)
13475 (when author
13476 (insert "<p class=\"author\"> "
13477 (nth 1 lang-words) ": " author "\n")
13478 (when email
13479 (insert "<a href=\"mailto:" email "\">&lt;"
13480 email "&gt;</a>\n"))
13481 (insert "</p>\n"))
13482 (when (and date time)
13483 (insert "<p class=\"date\"> "
13484 (nth 2 lang-words) ": "
13485 date " " time "</p>\n")))
13486
13487 (if org-export-html-with-timestamp
13488 (insert org-export-html-html-helper-timestamp))
13489 (insert (or (plist-get opt-plist :postamble) ""))
13490 (insert "</body>\n</html>\n")
13491 (normal-mode)
13492 ;; remove empty paragraphs and lists
13493 (goto-char (point-min))
13494 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
13495 (replace-match ""))
13496 (goto-char (point-min))
13497 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
13498 (replace-match ""))
13499 (save-buffer)
13500 (goto-char (point-min)))))
13501
13502 (defun org-format-table-html (lines olines)
13503 "Find out which HTML converter to use and return the HTML code."
13504 (if (string-match "^[ \t]*|" (car lines))
13505 ;; A normal org table
13506 (org-format-org-table-html lines)
13507 ;; Table made by table.el - test for spanning
13508 (let* ((hlines (delq nil (mapcar
13509 (lambda (x)
13510 (if (string-match "^[ \t]*\\+-" x) x
13511 nil))
13512 lines)))
13513 (first (car hlines))
13514 (ll (and (string-match "\\S-+" first)
13515 (match-string 0 first)))
13516 (re (concat "^[ \t]*" (regexp-quote ll)))
13517 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
13518 hlines))))
13519 (if (and (not spanning)
13520 (not org-export-prefer-native-exporter-for-tables))
13521 ;; We can use my own converter with HTML conversions
13522 (org-format-table-table-html lines)
13523 ;; Need to use the code generator in table.el, with the original text.
13524 (org-format-table-table-html-using-table-generate-source olines)))))
13525
13526 (defun org-format-org-table-html (lines)
13527 "Format a table into HTML."
13528 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
13529 (setq lines (nreverse lines))
13530 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
13531 (setq lines (nreverse lines))
13532 (when org-export-table-remove-special-lines
13533 ;; Check if the table has a marking column. If yes remove the
13534 ;; column and the special lines
13535 (let* ((special
13536 (not
13537 (memq nil
13538 (mapcar
13539 (lambda (x)
13540 (or (string-match "^[ \t]*|-" x)
13541 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
13542 lines)))))
13543 (if special
13544 (setq lines
13545 (delq nil
13546 (mapcar
13547 (lambda (x)
13548 (if (string-match "^[ \t]*| *[!_^] *|" x)
13549 nil ; ignore this line
13550 (and (or (string-match "^[ \t]*|-+\\+" x)
13551 (string-match "^[ \t]*|[^|]*|" x))
13552 (replace-match "|" t t x))))
13553 lines))))))
13554
13555 (let ((head (and org-export-highlight-first-table-line
13556 (delq nil (mapcar
13557 (lambda (x) (string-match "^[ \t]*|-" x))
13558 (cdr lines)))))
13559 line fields html)
13560 (setq html (concat org-export-html-table-tag "\n"))
13561 (while (setq line (pop lines))
13562 (catch 'next-line
13563 (if (string-match "^[ \t]*|-" line)
13564 (progn
13565 (setq head nil) ;; head ends here, first time around
13566 ;; ignore this line
13567 (throw 'next-line t)))
13568 ;; Break the line into fields
13569 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
13570 (setq html (concat
13571 html
13572 "<tr>"
13573 (mapconcat (lambda (x)
13574 (if head
13575 (concat "<th>" x "</th>")
13576 (concat "<td>" x "</td>")))
13577 fields "")
13578 "</tr>\n"))))
13579 (setq html (concat html "</table>\n"))
13580 html))
13581
13582 (defun org-fake-empty-table-line (line)
13583 "Replace everything except \"|\" with spaces."
13584 (let ((i (length line))
13585 (newstr (copy-sequence line)))
13586 (while (> i 0)
13587 (setq i (1- i))
13588 (if (not (eq (aref newstr i) ?|))
13589 (aset newstr i ?\ )))
13590 newstr))
13591
13592 (defun org-format-table-table-html (lines)
13593 "Format a table generated by table.el into HTML.
13594 This conversion does *not* use `table-generate-source' from table.el.
13595 This has the advantage that Org-mode's HTML conversions can be used.
13596 But it has the disadvantage, that no cell- or row-spanning is allowed."
13597 (let (line field-buffer
13598 (head org-export-highlight-first-table-line)
13599 fields html empty)
13600 (setq html (concat org-export-html-table-tag "\n"))
13601 (while (setq line (pop lines))
13602 (setq empty "&nbsp;")
13603 (catch 'next-line
13604 (if (string-match "^[ \t]*\\+-" line)
13605 (progn
13606 (if field-buffer
13607 (progn
13608 (setq html (concat
13609 html
13610 "<tr>"
13611 (mapconcat
13612 (lambda (x)
13613 (if (equal x "") (setq x empty))
13614 (if head
13615 (concat "<th>" x "</th>\n")
13616 (concat "<td>" x "</td>\n")))
13617 field-buffer "\n")
13618 "</tr>\n"))
13619 (setq head nil)
13620 (setq field-buffer nil)))
13621 ;; Ignore this line
13622 (throw 'next-line t)))
13623 ;; Break the line into fields and store the fields
13624 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
13625 (if field-buffer
13626 (setq field-buffer (mapcar
13627 (lambda (x)
13628 (concat x "<br/>" (pop fields)))
13629 field-buffer))
13630 (setq field-buffer fields))))
13631 (setq html (concat html "</table>\n"))
13632 html))
13633
13634 (defun org-format-table-table-html-using-table-generate-source (lines)
13635 "Format a table into html, using `table-generate-source' from table.el.
13636 This has the advantage that cell- or row-spanning is allowed.
13637 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
13638 (require 'table)
13639 (with-current-buffer (get-buffer-create " org-tmp1 ")
13640 (erase-buffer)
13641 (insert (mapconcat 'identity lines "\n"))
13642 (goto-char (point-min))
13643 (if (not (re-search-forward "|[^+]" nil t))
13644 (error "Error processing table"))
13645 (table-recognize-table)
13646 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
13647 (table-generate-source 'html " org-tmp2 ")
13648 (set-buffer " org-tmp2 ")
13649 (buffer-substring (point-min) (point-max))))
13650
13651 (defun org-html-handle-time-stamps (s)
13652 "Format time stamps in string S, or remove them."
13653 (let (r b)
13654 (while (string-match org-maybe-keyword-time-regexp s)
13655 (or b (setq b (substring s 0 (match-beginning 0))))
13656 (if (not org-export-with-timestamps)
13657 (setq r (concat r (substring s 0 (match-beginning 0)))
13658 s (substring s (match-end 0)))
13659 (setq r (concat
13660 r (substring s 0 (match-beginning 0))
13661 (if (match-end 1)
13662 (format "@<span class=\"timestamp-kwd\">%s @</span>"
13663 (match-string 1 s)))
13664 (format " @<span class=\"timestamp\">%s@</span>"
13665 (substring (match-string 3 s) 1 -1)))
13666 s (substring s (match-end 0)))))
13667 ;; Line break of line started and ended with time stamp stuff
13668 (if (not r)
13669 s
13670 (setq r (concat r s))
13671 (unless (string-match "\\S-" (concat b s))
13672 (setq r (concat r "@<br/>")))
13673 r)))
13674
13675 (defun org-html-protect (s)
13676 ;; convert & to &amp;, < to &lt; and > to &gt;
13677 (let ((start 0))
13678 (while (string-match "&" s start)
13679 (setq s (replace-match "&amp;" t t s)
13680 start (1+ (match-beginning 0))))
13681 (while (string-match "<" s)
13682 (setq s (replace-match "&lt;" t t s)))
13683 (while (string-match ">" s)
13684 (setq s (replace-match "&gt;" t t s))))
13685 s)
13686
13687 (defun org-html-cleanup-toc-line (s)
13688 "Remove tags and time staps from lines going into the toc."
13689 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
13690 (setq s (replace-match "" t t s)))
13691 (while (string-match org-maybe-keyword-time-regexp s)
13692 (setq s (replace-match "" t t s)))
13693 s)
13694
13695 (defun org-html-expand (string)
13696 "Prepare STRING for HTML export. Applies all active conversions.
13697 If there are links in the string, don't modify these."
13698 (let* (m s l res)
13699 (while (setq m (string-match org-bracket-link-regexp string))
13700 (setq s (substring string 0 m)
13701 l (match-string 0 string)
13702 string (substring string (match-end 0)))
13703 (push (org-html-do-expand s) res)
13704 (push l res))
13705 (push (org-html-do-expand string) res)
13706 (apply 'concat (nreverse res))))
13707
13708 (defun org-html-do-expand (s)
13709 "Apply all active conversions to translate special ASCII to HTML."
13710 (setq s (org-html-protect s))
13711 (if org-export-html-expand
13712 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
13713 (setq s (replace-match "<\\1>" t nil s))))
13714 (if org-export-with-emphasize
13715 (setq s (org-export-html-convert-emphasize s)))
13716 (if org-export-with-sub-superscripts
13717 (setq s (org-export-html-convert-sub-super s)))
13718 (if org-export-with-TeX-macros
13719 (let ((start 0) wd ass)
13720 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
13721 (setq wd (match-string 1 s))
13722 (if (setq ass (assoc wd org-html-entities))
13723 (setq s (replace-match (or (cdr ass)
13724 (concat "&" (car ass) ";"))
13725 t t s))
13726 (setq start (+ start (length wd)))))))
13727 s)
13728
13729 (defun org-create-multibrace-regexp (left right n)
13730 "Create a regular expression which will match a balanced sexp.
13731 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
13732 as single character strings.
13733 The regexp returned will match the entire expression including the
13734 delimiters. It will also define a single group which contains the
13735 match except for the outermost delimiters. The maximum depth of
13736 stacked delimiters is N. Escaping delimiters is not possible."
13737 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
13738 (or "\\|")
13739 (re nothing)
13740 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
13741 (while (> n 1)
13742 (setq n (1- n)
13743 re (concat re or next)
13744 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
13745 (concat left "\\(" re "\\)" right)))
13746
13747 (defvar org-match-substring-regexp
13748 (concat
13749 "\\([^\\]\\)\\([_^]\\)\\("
13750 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
13751 "\\|"
13752 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
13753 "\\|"
13754 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
13755 "The regular expression matching a sub- or superscript.")
13756
13757 (defun org-export-html-convert-sub-super (string)
13758 "Convert sub- and superscripts in STRING to HTML."
13759 (let (key c)
13760 (while (string-match org-match-substring-regexp string)
13761 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
13762 (setq c (or (match-string 8 string)
13763 (match-string 6 string)
13764 (match-string 5 string)))
13765 (setq string (replace-match
13766 (concat (match-string 1 string)
13767 "<" key ">" c "</" key ">")
13768 t t string)))
13769 (while (string-match "\\\\\\([_^]\\)" string)
13770 (setq string (replace-match (match-string 1 string) t t string))))
13771 string)
13772
13773 (defun org-export-html-convert-emphasize (string)
13774 "Apply emphasis."
13775 (while (string-match org-emph-re string)
13776 (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)))
13777 string)
13778
13779 (defvar org-par-open nil)
13780 (defun org-open-par ()
13781 "Insert <p>, but first close previous paragraph if any."
13782 (org-close-par-maybe)
13783 (insert "\n<p>")
13784 (setq org-par-open t))
13785 (defun org-close-par-maybe ()
13786 "Close paragraph if there is one open."
13787 (when org-par-open
13788 (insert "</p>")
13789 (setq org-par-open nil)))
13790 (defun org-close-li ()
13791 "Close <li> if necessary."
13792 (org-close-par-maybe)
13793 (insert "</li>\n"))
13794 ; (when (save-excursion
13795 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
13796 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
13797 ; (insert "</li>"))))
13798
13799 (defun org-html-level-start (level title umax with-toc head-count)
13800 "Insert a new level in HTML export.
13801 When TITLE is nil, just close all open levels."
13802 (org-close-par-maybe)
13803 (let ((l (1+ (max level umax))))
13804 (while (<= l org-level-max)
13805 (if (aref levels-open (1- l))
13806 (progn
13807 (org-html-level-close l)
13808 (aset levels-open (1- l) nil)))
13809 (setq l (1+ l)))
13810 (when title
13811 ;; If title is nil, this means this function is called to close
13812 ;; all levels, so the rest is done only if title is given
13813 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
13814 (setq title (replace-match
13815 (if org-export-with-tags
13816 (save-match-data
13817 (concat
13818 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
13819 (mapconcat 'identity (org-split-string
13820 (match-string 1 title) ":")
13821 "&nbsp;")
13822 "</span>"))
13823 "")
13824 t t title)))
13825 (if (> level umax)
13826 (progn
13827 (if (aref levels-open (1- level))
13828 (progn
13829 (org-close-li)
13830 (insert "<li>" title "<br/>\n"))
13831 (aset levels-open (1- level) t)
13832 (org-close-par-maybe)
13833 (insert "<ul>\n<li>" title "<br/>\n")))
13834 (if org-export-with-section-numbers
13835 (setq title (concat (org-section-number level) " " title)))
13836 (setq level (+ level 1))
13837 (if with-toc
13838 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
13839 level head-count title level))
13840 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
13841 (org-open-par)))))
13842
13843 (defun org-html-level-close (&rest args)
13844 "Terminate one level in HTML export."
13845 (org-close-li)
13846 (insert "</ul>"))
13847
13848 ;; Variable holding the vector with section numbers
13849 (defvar org-section-numbers (make-vector org-level-max 0))
13850
13851 (defun org-init-section-numbers ()
13852 "Initialize the vector for the section numbers."
13853 (let* ((level -1)
13854 (numbers (nreverse (org-split-string "" "\\.")))
13855 (depth (1- (length org-section-numbers)))
13856 (i depth) number-string)
13857 (while (>= i 0)
13858 (if (> i level)
13859 (aset org-section-numbers i 0)
13860 (setq number-string (or (car numbers) "0"))
13861 (if (string-match "\\`[A-Z]\\'" number-string)
13862 (aset org-section-numbers i
13863 (- (string-to-char number-string) ?A -1))
13864 (aset org-section-numbers i (string-to-number number-string)))
13865 (pop numbers))
13866 (setq i (1- i)))))
13867
13868 (defun org-section-number (&optional level)
13869 "Return a string with the current section number.
13870 When LEVEL is non-nil, increase section numbers on that level."
13871 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
13872 (when level
13873 (when (> level -1)
13874 (aset org-section-numbers
13875 level (1+ (aref org-section-numbers level))))
13876 (setq idx (1+ level))
13877 (while (<= idx depth)
13878 (if (not (= idx 1))
13879 (aset org-section-numbers idx 0))
13880 (setq idx (1+ idx))))
13881 (setq idx 0)
13882 (while (<= idx depth)
13883 (setq n (aref org-section-numbers idx))
13884 (setq string (concat string (if (not (string= string "")) "." "")
13885 (int-to-string n)))
13886 (setq idx (1+ idx)))
13887 (save-match-data
13888 (if (string-match "\\`\\([@0]\\.\\)+" string)
13889 (setq string (replace-match "" t nil string)))
13890 (if (string-match "\\(\\.0\\)+\\'" string)
13891 (setq string (replace-match "" t nil string))))
13892 string))
13893
13894
13895 ;;;###autoload
13896 (defun org-export-icalendar-this-file ()
13897 "Export current file as an iCalendar file.
13898 The iCalendar file will be located in the same directory as the Org-mode
13899 file, but with extension `.ics'."
13900 (interactive)
13901 (org-export-icalendar nil buffer-file-name))
13902
13903 (defun org-export-as-xoxo-insert-into (buffer &rest output)
13904 (with-current-buffer buffer
13905 (apply 'insert output)))
13906
13907 (defun org-export-as-xoxo (&optional buffer)
13908 "Export the org buffer as XOXO.
13909 The XOXO buffer is named *xoxo-<source buffer name>*"
13910 (interactive (list (current-buffer)))
13911 ;; A quickie abstraction
13912
13913 ;; Output everything as XOXO
13914 (with-current-buffer (get-buffer buffer)
13915 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
13916 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13917 (org-infile-export-plist)))
13918 (filename (concat (file-name-as-directory
13919 (org-export-directory :xoxo opt-plist))
13920 (file-name-sans-extension
13921 (file-name-nondirectory buffer-file-name))
13922 ".html"))
13923 (out (find-file-noselect filename))
13924 (last-level 1)
13925 (hanging-li nil))
13926 ;; Check the output buffer is empty.
13927 (with-current-buffer out (erase-buffer))
13928 ;; Kick off the output
13929 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
13930 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
13931 (let* ((hd (match-string-no-properties 1))
13932 (level (length hd))
13933 (text (concat
13934 (match-string-no-properties 2)
13935 (save-excursion
13936 (goto-char (match-end 0))
13937 (let ((str ""))
13938 (catch 'loop
13939 (while 't
13940 (forward-line)
13941 (if (looking-at "^[ \t]\\(.*\\)")
13942 (setq str (concat str (match-string-no-properties 1)))
13943 (throw 'loop str)))))))))
13944
13945 ;; Handle level rendering
13946 (cond
13947 ((> level last-level)
13948 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
13949
13950 ((< level last-level)
13951 (dotimes (- (- last-level level) 1)
13952 (if hanging-li
13953 (org-export-as-xoxo-insert-into out "</li>\n"))
13954 (org-export-as-xoxo-insert-into out "</ol>\n"))
13955 (when hanging-li
13956 (org-export-as-xoxo-insert-into out "</li>\n")
13957 (setq hanging-li nil)))
13958
13959 ((equal level last-level)
13960 (if hanging-li
13961 (org-export-as-xoxo-insert-into out "</li>\n")))
13962 )
13963
13964 (setq last-level level)
13965
13966 ;; And output the new li
13967 (setq hanging-li 't)
13968 (if (equal ?+ (elt text 0))
13969 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
13970 (org-export-as-xoxo-insert-into out "<li>" text))))
13971
13972 ;; Finally finish off the ol
13973 (dotimes (- last-level 1)
13974 (if hanging-li
13975 (org-export-as-xoxo-insert-into out "</li>\n"))
13976 (org-export-as-xoxo-insert-into out "</ol>\n"))
13977
13978 ;; Finish the buffer off and clean it up.
13979 (switch-to-buffer-other-window out)
13980 (indent-region (point-min) (point-max) nil)
13981 (save-buffer)
13982 (goto-char (point-min))
13983 )))
13984
13985 ;;;###autoload
13986 (defun org-export-icalendar-all-agenda-files ()
13987 "Export all files in `org-agenda-files' to iCalendar .ics files.
13988 Each iCalendar file will be located in the same directory as the Org-mode
13989 file, but with extension `.ics'."
13990 (interactive)
13991 (apply 'org-export-icalendar nil (org-agenda-files t)))
13992
13993 ;;;###autoload
13994 (defun org-export-icalendar-combine-agenda-files ()
13995 "Export all files in `org-agenda-files' to a single combined iCalendar file.
13996 The file is stored under the name `org-combined-agenda-icalendar-file'."
13997 (interactive)
13998 (apply 'org-export-icalendar t (org-agenda-files t)))
13999
14000 (defun org-export-icalendar (combine &rest files)
14001 "Create iCalendar files for all elements of FILES.
14002 If COMBINE is non-nil, combine all calendar entries into a single large
14003 file and store it under the name `org-combined-agenda-icalendar-file'."
14004 (save-excursion
14005 (let* ((dir (org-export-directory
14006 :ical (list :publishing-directory
14007 org-export-publishing-directory)))
14008 file ical-file ical-buffer category started org-agenda-new-buffers)
14009
14010 (when combine
14011 (setq ical-file
14012 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
14013 org-combined-agenda-icalendar-file
14014 (expand-file-name org-combined-agenda-icalendar-file dir))
14015 ical-buffer (org-get-agenda-file-buffer ical-file))
14016 (set-buffer ical-buffer) (erase-buffer))
14017 (while (setq file (pop files))
14018 (catch 'nextfile
14019 (org-check-agenda-file file)
14020 (set-buffer (org-get-agenda-file-buffer file))
14021 (unless combine
14022 (setq ical-file (concat (file-name-as-directory dir)
14023 (file-name-sans-extension
14024 (file-name-nondirectory buffer-file-name))
14025 ".ics"))
14026 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
14027 (with-current-buffer ical-buffer (erase-buffer)))
14028 (setq category (or org-category
14029 (file-name-sans-extension
14030 (file-name-nondirectory buffer-file-name))))
14031 (if (symbolp category) (setq category (symbol-name category)))
14032 (let ((standard-output ical-buffer))
14033 (if combine
14034 (and (not started) (setq started t)
14035 (org-start-icalendar-file org-icalendar-combined-name))
14036 (org-start-icalendar-file category))
14037 (org-print-icalendar-entries combine category)
14038 (when (or (and combine (not files)) (not combine))
14039 (org-finish-icalendar-file)
14040 (set-buffer ical-buffer)
14041 (save-buffer)
14042 (run-hooks 'org-after-save-iCalendar-file-hook)))))
14043 (org-release-buffers org-agenda-new-buffers))))
14044
14045 (defvar org-after-save-iCalendar-file-hook nil
14046 "Hook run after an iCalendar file has been saved.
14047 The iCalendar buffer is still current when this hook is run.
14048 A good way to use this is to tell a desktop calenndar application to re-read
14049 the iCalendar file.")
14050
14051 (defun org-print-icalendar-entries (&optional combine category)
14052 "Print iCalendar entries for the current Org-mode file to `standard-output'.
14053 When COMBINE is non nil, add the category to each line."
14054 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
14055 (dts (org-ical-ts-to-string
14056 (format-time-string (cdr org-time-stamp-formats) (current-time))
14057 "DTSTART"))
14058 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
14059 (save-excursion
14060 (goto-char (point-min))
14061 (while (re-search-forward org-ts-regexp nil t)
14062 (setq pos (match-beginning 0)
14063 ts (match-string 0)
14064 inc t
14065 hd (org-get-heading))
14066 (if (looking-at re2)
14067 (progn
14068 (goto-char (match-end 0))
14069 (setq ts2 (match-string 1) inc nil))
14070 (setq ts2 ts
14071 tmp (buffer-substring (max (point-min)
14072 (- pos org-ds-keyword-length))
14073 pos)
14074 deadlinep (string-match org-deadline-regexp tmp)
14075 scheduledp (string-match org-scheduled-regexp tmp)
14076 ;; donep (org-entry-is-done-p)
14077 ))
14078 (if (or (string-match org-tr-regexp hd)
14079 (string-match org-ts-regexp hd))
14080 (setq hd (replace-match "" t t hd)))
14081 (if combine
14082 (setq hd (concat hd " (category " category ")")))
14083 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
14084 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
14085 (princ (format "BEGIN:VEVENT
14086 %s
14087 %s
14088 SUMMARY:%s
14089 END:VEVENT\n"
14090 (org-ical-ts-to-string ts "DTSTART")
14091 (org-ical-ts-to-string ts2 "DTEND" inc)
14092 hd)))
14093 (when org-icalendar-include-todo
14094 (goto-char (point-min))
14095 (while (re-search-forward org-todo-line-regexp nil t)
14096 (setq state (match-string 1))
14097 (unless (equal state org-done-string)
14098 (setq hd (match-string 3))
14099 (if (string-match org-priority-regexp hd)
14100 (setq pri (string-to-char (match-string 2 hd))
14101 hd (concat (substring hd 0 (match-beginning 1))
14102 (substring hd (- (match-end 1)))))
14103 (setq pri org-default-priority))
14104 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
14105 (- org-lowest-priority ?A))))))
14106
14107 (princ (format "BEGIN:VTODO
14108 %s
14109 SUMMARY:%s
14110 SEQUENCE:1
14111 PRIORITY:%d
14112 END:VTODO\n"
14113 dts hd pri))))))))
14114
14115 (defun org-start-icalendar-file (name)
14116 "Start an iCalendar file by inserting the header."
14117 (let ((user user-full-name)
14118 (name (or name "unknown"))
14119 (timezone (cadr (current-time-zone))))
14120 (princ
14121 (format "BEGIN:VCALENDAR
14122 VERSION:2.0
14123 X-WR-CALNAME:%s
14124 PRODID:-//%s//Emacs with Org-mode//EN
14125 X-WR-TIMEZONE:%s
14126 CALSCALE:GREGORIAN\n" name user timezone))))
14127
14128 (defun org-finish-icalendar-file ()
14129 "Finish an iCalendar file by inserting the END statement."
14130 (princ "END:VCALENDAR\n"))
14131
14132 (defun org-ical-ts-to-string (s keyword &optional inc)
14133 "Take a time string S and convert it to iCalendar format.
14134 KEYWORD is added in front, to make a complete line like DTSTART....
14135 When INC is non-nil, increase the hour by two (if time string contains
14136 a time), or the day by one (if it does not contain a time)."
14137 (let ((t1 (org-parse-time-string s 'nodefault))
14138 t2 fmt have-time time)
14139 (if (and (car t1) (nth 1 t1) (nth 2 t1))
14140 (setq t2 t1 have-time t)
14141 (setq t2 (org-parse-time-string s)))
14142 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
14143 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
14144 (when inc
14145 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
14146 (setq time (encode-time s mi h d m y)))
14147 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
14148 (concat keyword (format-time-string fmt time))))
14149
14150
14151 ;;; Key bindings
14152
14153 ;; - Bindings in Org-mode map are currently
14154 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
14155 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
14156 ;; e (?) useful from outline-mode
14157 ;; i k @ expendable from outline-mode
14158 ;; 0123456789 % & ()_{} " ` free
14159
14160 ;; Make `C-c C-x' a prefix key
14161 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
14162
14163 ;; TAB key with modifiers
14164 (define-key org-mode-map "\C-i" 'org-cycle)
14165 (define-key org-mode-map [(tab)] 'org-cycle)
14166 (define-key org-mode-map [(meta tab)] 'org-complete)
14167 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
14168 ;; The following line is necessary under Suse GNU/Linux
14169 (unless (featurep 'xemacs)
14170 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
14171 (define-key org-mode-map [(shift tab)] 'org-shifttab)
14172
14173 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
14174 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
14175 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14176 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
14177 (define-key org-mode-map [(meta return)] 'org-meta-return)
14178 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
14179 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
14180
14181 ;; Cursor keys with modifiers
14182 (define-key org-mode-map [(meta left)] 'org-metaleft)
14183 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
14184 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
14185 (define-key org-mode-map [(meta right)] 'org-metaright)
14186 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
14187 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
14188 (define-key org-mode-map [(meta up)] 'org-metaup)
14189 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
14190 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
14191 (define-key org-mode-map [(meta down)] 'org-metadown)
14192 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
14193 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
14194
14195 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14196 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
14197 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
14198 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
14199 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
14200 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
14201 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
14202 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
14203 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
14204 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
14205 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
14206 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
14207 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
14208 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
14209 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
14210 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
14211
14212 ;; All the other keys
14213
14214 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14215 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
14216 (define-key org-mode-map "\C-c\C-j" 'org-goto)
14217 (define-key org-mode-map "\C-c\C-t" 'org-todo)
14218 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
14219 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
14220 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
14221 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14222 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
14223 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
14224 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
14225 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
14226 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
14227 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
14228 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
14229 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
14230 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
14231 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
14232 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14233 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14234 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14235 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14236 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
14237 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
14238 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14239 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
14240 (define-key org-mode-map "\C-c]" 'org-remove-file)
14241 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
14242 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
14243 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
14244 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14245 (define-key org-mode-map "\C-m" 'org-return)
14246 (define-key org-mode-map "\C-c?" 'org-table-current-column)
14247 (define-key org-mode-map "\C-c " 'org-table-blank-field)
14248 (define-key org-mode-map "\C-c+" 'org-table-sum)
14249 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
14250 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
14251 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
14252 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14253 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
14254 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14255 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
14256 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
14257 (define-key org-mode-map "\C-c\C-e" 'org-export)
14258 ;(define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
14259 ;(define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
14260 ;(define-key org-mode-map "\C-c\C-xv" 'org-export-visible)
14261 ;(define-key org-mode-map "\C-c\C-x\C-v" 'org-export-visible)
14262 ;; OPML support is only an option for the future
14263 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
14264 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
14265 ;(define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
14266 ;(define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
14267 ;(define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
14268 ;(define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
14269 ;(define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
14270 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14271 ;(define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
14272 ;(define-key org-mode-map "\C-c\C-xx" 'org-export-as-xoxo)
14273 ;(define-key org-mode-map "\C-c\C-x\C-x" 'org-export-as-xoxo)
14274 ;(define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
14275 ;(define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
14276
14277 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
14278 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14279 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14280 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14281
14282 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14283 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14284 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14285 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14286
14287 ;(define-key org-mode-map "\C-c\C-ef" 'org-publish-current-file)
14288 ;(define-key org-mode-map "\C-c\C-ep" 'org-publish-current-project)
14289 ;(define-key org-mode-map "\C-c\C-ec" 'org-publish)
14290 ;(define-key org-mode-map "\C-c\C-ea" 'org-publish-all)
14291 ;(define-key org-mode-map "\C-c\C-e\C-f" 'org-publish-current-file)
14292 ;(define-key org-mode-map "\C-c\C-e\C-p" 'org-publish-current-project)
14293 ;(define-key org-mode-map "\C-c\C-e\C-c" 'org-publish)
14294 ;(define-key org-mode-map "\C-c\C-e\C-a" 'org-publish-all)
14295
14296 (when (featurep 'xemacs)
14297 (define-key org-mode-map 'button3 'popup-mode-menu))
14298
14299 (defsubst org-table-p () (org-at-table-p))
14300
14301 (defun org-self-insert-command (N)
14302 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14303 If the cursor is in a table looking at whitespace, the whitespace is
14304 overwritten, and the table is not marked as requiring realignment."
14305 (interactive "p")
14306 (if (and (org-table-p)
14307 (progn
14308 ;; check if we blank the field, and if that triggers align
14309 (and org-table-auto-blank-field
14310 (member last-command
14311 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
14312 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14313 ;; got extra space, this field does not determine column width
14314 (let (org-table-may-need-update) (org-table-blank-field))
14315 ;; no extra space, this field may determine column width
14316 (org-table-blank-field)))
14317 t)
14318 (eq N 1)
14319 (looking-at "[^|\n]* |"))
14320 (let (org-table-may-need-update)
14321 (goto-char (1- (match-end 0)))
14322 (delete-backward-char 1)
14323 (goto-char (match-beginning 0))
14324 (self-insert-command N))
14325 (setq org-table-may-need-update t)
14326 (self-insert-command N)))
14327
14328 (defun org-delete-backward-char (N)
14329 "Like `delete-backward-char', insert whitespace at field end in tables.
14330 When deleting backwards, in tables this function will insert whitespace in
14331 front of the next \"|\" separator, to keep the table aligned. The table will
14332 still be marked for re-alignment if the field did fill the entire column,
14333 because, in this case the deletion might narrow the column."
14334 (interactive "p")
14335 (if (and (org-table-p)
14336 (eq N 1)
14337 (string-match "|" (buffer-substring (point-at-bol) (point)))
14338 (looking-at ".*?|"))
14339 (let ((pos (point))
14340 (noalign (looking-at "[^|\n\r]* |"))
14341 (c org-table-may-need-update))
14342 (backward-delete-char N)
14343 (skip-chars-forward "^|")
14344 (insert " ")
14345 (goto-char (1- pos))
14346 ;; noalign: if there were two spaces at the end, this field
14347 ;; does not determine the width of the column.
14348 (if noalign (setq org-table-may-need-update c)))
14349 (backward-delete-char N)))
14350
14351 (defun org-delete-char (N)
14352 "Like `delete-char', but insert whitespace at field end in tables.
14353 When deleting characters, in tables this function will insert whitespace in
14354 front of the next \"|\" separator, to keep the table aligned. The table will
14355 still be marked for re-alignment if the field did fill the entire column,
14356 because, in this case the deletion might narrow the column."
14357 (interactive "p")
14358 (if (and (org-table-p)
14359 (not (bolp))
14360 (not (= (char-after) ?|))
14361 (eq N 1))
14362 (if (looking-at ".*?|")
14363 (let ((pos (point))
14364 (noalign (looking-at "[^|\n\r]* |"))
14365 (c org-table-may-need-update))
14366 (replace-match (concat
14367 (substring (match-string 0) 1 -1)
14368 " |"))
14369 (goto-char pos)
14370 ;; noalign: if there were two spaces at the end, this field
14371 ;; does not determine the width of the column.
14372 (if noalign (setq org-table-may-need-update c)))
14373 (delete-char N))
14374 (delete-char N)))
14375
14376 ;; How to do this: Measure non-white length of current string
14377 ;; If equal to column width, we should realign.
14378
14379 (defun org-remap (map &rest commands)
14380 "In MAP, remap the functions given in COMMANDS.
14381 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14382 (let (new old)
14383 (while commands
14384 (setq old (pop commands) new (pop commands))
14385 (if (fboundp 'command-remapping)
14386 (define-key map (vector 'remap old) new)
14387 (substitute-key-definition old new map global-map)))))
14388
14389 (when (eq org-enable-table-editor 'optimized)
14390 ;; If the user wants maximum table support, we need to hijack
14391 ;; some standard editing functions
14392 (org-remap org-mode-map
14393 'self-insert-command 'org-self-insert-command
14394 'delete-char 'org-delete-char
14395 'delete-backward-char 'org-delete-backward-char)
14396 (define-key org-mode-map "|" 'org-force-self-insert))
14397
14398 (defun org-shiftcursor-error ()
14399 "Throw an error because Shift-Cursor command was applied in wrong context."
14400 (error "This command is active in special context like tables, headlines or timestamps"))
14401
14402 (defun org-shifttab (&optional arg)
14403 "Global visibility cycling or move to previous table field.
14404 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14405 on context.
14406 See the individual commands for more information."
14407 (interactive "P")
14408 (cond
14409 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14410 (t (call-interactively 'org-global-cycle))))
14411
14412 (defun org-shiftmetaleft ()
14413 "Promote subtree or delete table column.
14414 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
14415 See the individual commands for more information."
14416 (interactive)
14417 (cond
14418 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14419 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14420 ((org-at-item-p) (call-interactively 'org-outdent-item))
14421 (t (org-shiftcursor-error))))
14422
14423 (defun org-shiftmetaright ()
14424 "Demote subtree or insert table column.
14425 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
14426 See the individual commands for more information."
14427 (interactive)
14428 (cond
14429 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14430 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14431 ((org-at-item-p) (call-interactively 'org-indent-item))
14432 (t (org-shiftcursor-error))))
14433
14434 (defun org-shiftmetaup (&optional arg)
14435 "Move subtree up or kill table row.
14436 Calls `org-move-subtree-up' or `org-table-kill-row' or
14437 `org-move-item-up' depending on context. See the individual commands
14438 for more information."
14439 (interactive "P")
14440 (cond
14441 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14442 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14443 ((org-at-item-p) (call-interactively 'org-move-item-up))
14444 (t (org-shiftcursor-error))))
14445 (defun org-shiftmetadown (&optional arg)
14446 "Move subtree down or insert table row.
14447 Calls `org-move-subtree-down' or `org-table-insert-row' or
14448 `org-move-item-down', depending on context. See the individual
14449 commands for more information."
14450 (interactive "P")
14451 (cond
14452 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14453 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14454 ((org-at-item-p) (call-interactively 'org-move-item-down))
14455 (t (org-shiftcursor-error))))
14456
14457 (defun org-metaleft (&optional arg)
14458 "Promote heading or move table column to left.
14459 Calls `org-do-promote' or `org-table-move-column', depending on context.
14460 With no specific context, calls the Emacs default `backward-word'.
14461 See the individual commands for more information."
14462 (interactive "P")
14463 (cond
14464 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14465 ((or (org-on-heading-p) (org-region-active-p))
14466 (call-interactively 'org-do-promote))
14467 (t (call-interactively 'backward-word))))
14468
14469 (defun org-metaright (&optional arg)
14470 "Demote subtree or move table column to right.
14471 Calls `org-do-demote' or `org-table-move-column', depending on context.
14472 With no specific context, calls the Emacs default `forward-word'.
14473 See the individual commands for more information."
14474 (interactive "P")
14475 (cond
14476 ((org-at-table-p) (call-interactively 'org-table-move-column))
14477 ((or (org-on-heading-p) (org-region-active-p))
14478 (call-interactively 'org-do-demote))
14479 (t (call-interactively 'forward-word))))
14480
14481 (defun org-metaup (&optional arg)
14482 "Move subtree up or move table row up.
14483 Calls `org-move-subtree-up' or `org-table-move-row' or
14484 `org-move-item-up', depending on context. See the individual commands
14485 for more information."
14486 (interactive "P")
14487 (cond
14488 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14489 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14490 ((org-at-item-p) (call-interactively 'org-move-item-up))
14491 (t (org-shiftcursor-error))))
14492
14493 (defun org-metadown (&optional arg)
14494 "Move subtree down or move table row down.
14495 Calls `org-move-subtree-down' or `org-table-move-row' or
14496 `org-move-item-down', depending on context. See the individual
14497 commands for more information."
14498 (interactive "P")
14499 (cond
14500 ((org-at-table-p) (call-interactively 'org-table-move-row))
14501 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14502 ((org-at-item-p) (call-interactively 'org-move-item-down))
14503 (t (org-shiftcursor-error))))
14504
14505 (defun org-shiftup (&optional arg)
14506 "Increase item in timestamp or increase priority of current headline.
14507 Calls `org-timestamp-up' or `org-priority-up', depending on context.
14508 See the individual commands for more information."
14509 (interactive "P")
14510 (cond
14511 ((org-at-timestamp-p) (call-interactively 'org-timestamp-up))
14512 ((org-on-heading-p) (call-interactively 'org-priority-up))
14513 ((org-at-item-p) (call-interactively 'org-previous-item))
14514 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
14515
14516 (defun org-shiftdown (&optional arg)
14517 "Decrease item in timestamp or decrease priority of current headline.
14518 Calls `org-timestamp-down' or `org-priority-down', depending on context.
14519 See the individual commands for more information."
14520 (interactive "P")
14521 (cond
14522 ((org-at-timestamp-p) (call-interactively 'org-timestamp-down))
14523 ((org-on-heading-p) (call-interactively 'org-priority-down))
14524 (t (call-interactively 'org-next-item))))
14525
14526 (defun org-shiftright ()
14527 "Next TODO keyword or timestamp one day later, depending on context."
14528 (interactive)
14529 (cond
14530 ((org-at-timestamp-p) (call-interactively 'org-timestamp-up-day))
14531 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
14532 (t (org-shiftcursor-error))))
14533
14534 (defun org-shiftleft ()
14535 "Previous TODO keyword or timestamp one day earlier, depending on context."
14536 (interactive)
14537 (cond
14538 ((org-at-timestamp-p) (call-interactively 'org-timestamp-down-day))
14539 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
14540 (t (org-shiftcursor-error))))
14541
14542 (defun org-copy-special ()
14543 "Copy region in table or copy current subtree.
14544 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14545 See the individual commands for more information."
14546 (interactive)
14547 (call-interactively
14548 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14549
14550 (defun org-cut-special ()
14551 "Cut region in table or cut current subtree.
14552 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14553 See the individual commands for more information."
14554 (interactive)
14555 (call-interactively
14556 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14557
14558 (defun org-paste-special (arg)
14559 "Paste rectangular region into table, or past subtree relative to level.
14560 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14561 See the individual commands for more information."
14562 (interactive "P")
14563 (if (org-at-table-p)
14564 (org-table-paste-rectangle)
14565 (org-paste-subtree arg)))
14566
14567 (defun org-ctrl-c-ctrl-c (&optional arg)
14568 "Set tags in headline, or update according to changed information at point.
14569
14570 This command does many different things, depending on context:
14571
14572 - If the cursor is in a headline, prompt for tags and insert them
14573 into the current line, aligned to `org-tags-column'. When called
14574 with prefix arg, realign all tags in the current buffer.
14575
14576 - If the cursor is in one of the special #+KEYWORD lines, this
14577 triggers scanning the buffer for these lines and updating the
14578 information.
14579
14580 - If the cursor is inside a table, realign the table. This command
14581 works even if the automatic table editor has been turned off.
14582
14583 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14584 the entire table.
14585
14586 - If the cursor is inside a table created by the table.el package,
14587 activate that table.
14588
14589 - If the current buffer is a remember buffer, close note and file it.
14590 with a prefix argument, file it without further interaction to the default
14591 location.
14592
14593 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14594 links in this buffer.
14595
14596 - If the cursor is on a numbered item in a plain list, renumber the
14597 ordered list."
14598 (interactive "P")
14599 (let ((org-enable-table-editor t))
14600 (cond
14601 (org-clock-overlays
14602 (org-remove-clock-overlays)
14603 (message "Clock overlays removed"))
14604 (org-occur-highlights
14605 (org-remove-occur-highlights)
14606 (message "occur highlights removed"))
14607 ((and (local-variable-p 'org-finish-function (current-buffer))
14608 (fboundp org-finish-function))
14609 (funcall org-finish-function))
14610 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14611 ((org-on-heading-p) (call-interactively 'org-set-tags))
14612 ((org-at-table.el-p)
14613 (require 'table)
14614 (beginning-of-line 1)
14615 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14616 (call-interactively 'table-recognize-table))
14617 ((org-at-table-p)
14618 (org-table-maybe-eval-formula)
14619 (if arg
14620 (call-interactively 'org-table-recalculate)
14621 (org-table-maybe-recalculate-line))
14622 (call-interactively 'org-table-align))
14623 ((org-at-item-checkbox-p)
14624 (call-interactively 'org-toggle-checkbox))
14625 ((org-at-item-p)
14626 (call-interactively 'org-renumber-ordered-list))
14627 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14628 (cond
14629 ((equal (match-string 1) "TBLFM")
14630 ;; Recalculate the table before this line
14631 (save-excursion
14632 (beginning-of-line 1)
14633 (skip-chars-backward " \r\n\t")
14634 (if (org-at-table-p)
14635 (org-call-with-arg 'org-table-recalculate t))))
14636 (t
14637 (call-interactively 'org-mode-restart))))
14638 (t (error "C-c C-c can do nothing useful at this location.")))))
14639
14640 (defun org-mode-restart ()
14641 "Restart Org-mode, to scan again for special lines.
14642 Also updates the keyword regular expressions."
14643 (interactive)
14644 (let ((org-inhibit-startup t)) (org-mode))
14645 (message "Org-mode restarted to refresh keyword and special line setup"))
14646
14647 (defun org-return ()
14648 "Goto next table row or insert a newline.
14649 Calls `org-table-next-row' or `newline', depending on context.
14650 See the individual commands for more information."
14651 (interactive)
14652 (cond
14653 ((org-at-table-p)
14654 (org-table-justify-field-maybe)
14655 (call-interactively 'org-table-next-row))
14656 (t (newline))))
14657
14658 (defun org-meta-return (&optional arg)
14659 "Insert a new heading or wrap a region in a table.
14660 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14661 See the individual commands for more information."
14662 (interactive "P")
14663 (cond
14664 ((org-at-table-p)
14665 (call-interactively 'org-table-wrap-region))
14666 (t (call-interactively 'org-insert-heading))))
14667
14668 ;;; Menu entries
14669
14670 ;; Define the Org-mode menus
14671 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14672 '("Tbl"
14673 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
14674 ["Next Field" org-cycle (org-at-table-p)]
14675 ["Previous Field" org-shifttab (org-at-table-p)]
14676 ["Next Row" org-return (org-at-table-p)]
14677 "--"
14678 ["Blank Field" org-table-blank-field (org-at-table-p)]
14679 ["Edit Field" org-table-edit-field (org-at-table-p)]
14680 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14681 "--"
14682 ("Column"
14683 ["Move Column Left" org-metaleft (org-at-table-p)]
14684 ["Move Column Right" org-metaright (org-at-table-p)]
14685 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14686 ["Insert Column" org-shiftmetaright (org-at-table-p)]
14687 "--"
14688 ["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])
14689 ("Row"
14690 ["Move Row Up" org-metaup (org-at-table-p)]
14691 ["Move Row Down" org-metadown (org-at-table-p)]
14692 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14693 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14694 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14695 "--"
14696 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
14697 ("Rectangle"
14698 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14699 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14700 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14701 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14702 "--"
14703 ("Calculate"
14704 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14705 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14706 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
14707 "--"
14708 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14709 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14710 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14711 "--"
14712 ["Sum Column/Rectangle" org-table-sum
14713 (or (org-at-table-p) (org-region-active-p))]
14714 ["Which Column?" org-table-current-column (org-at-table-p)])
14715 ["Debug Formulas"
14716 (setq org-table-formula-debug (not org-table-formula-debug))
14717 :style toggle :selected org-table-formula-debug]
14718 "--"
14719 ["Create" org-table-create (and (not (org-at-table-p))
14720 org-enable-table-editor)]
14721 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14722 ["Import from File" org-table-import (not (org-at-table-p))]
14723 ["Export to File" org-table-export (org-at-table-p)]
14724 "--"
14725 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14726
14727 (easy-menu-define org-org-menu org-mode-map "Org menu"
14728 '("Org"
14729 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
14730 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
14731 ["Sparse Tree" org-occur t]
14732 ["Show All" show-all t]
14733 "--"
14734 ["New Heading" org-insert-heading t]
14735 ("Navigate Headings"
14736 ["Up" outline-up-heading t]
14737 ["Next" outline-next-visible-heading t]
14738 ["Previous" outline-previous-visible-heading t]
14739 ["Next Same Level" outline-forward-same-level t]
14740 ["Previous Same Level" outline-backward-same-level t]
14741 "--"
14742 ["Jump" org-goto t])
14743 ("Edit Structure"
14744 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14745 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14746 "--"
14747 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14748 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14749 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14750 "--"
14751 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14752 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14753 ["Demote Heading" org-metaright (not (org-at-table-p))]
14754 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14755 "--"
14756 ["Archive Subtree" org-archive-subtree t]
14757 "--"
14758 ["Convert to odd levels" org-convert-to-odd-levels t]
14759 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14760 "--"
14761 ("TODO Lists"
14762 ["TODO/DONE/-" org-todo t]
14763 ["Show TODO Tree" org-show-todo-tree t]
14764 ["Global TODO list" org-todo-list t]
14765 "--"
14766 ["Set Priority" org-priority t]
14767 ["Priority Up" org-shiftup t]
14768 ["Priority Down" org-shiftdown t])
14769 ("Dates and Scheduling"
14770 ["Timestamp" org-time-stamp t]
14771 ["Timestamp (inactive)" org-time-stamp-inactive t]
14772 ("Change Date"
14773 ["1 Day Later" org-timestamp-up-day t]
14774 ["1 Day Earlier" org-timestamp-down-day t]
14775 ["1 ... Later" org-shiftup t]
14776 ["1 ... Earlier" org-shiftdown t])
14777 ["Compute Time Range" org-evaluate-time-range t]
14778 ["Schedule Item" org-schedule t]
14779 ["Deadline" org-deadline t]
14780 "--"
14781 ["Goto Calendar" org-goto-calendar t]
14782 ["Date from Calendar" org-date-from-calendar t])
14783 ("Logging work"
14784 ["Clock in" org-clock-in t]
14785 ["Clock out" org-clock-out t]
14786 ["Clock cancel" org-clock-cancel t]
14787 ["Display times" org-clock-display t]
14788 "--"
14789 ["Record DONE time"
14790 (progn (setq org-log-done (not org-log-done))
14791 (message "Switching to %s will %s record a timestamp"
14792 org-done-string
14793 (if org-log-done "automatically" "not")))
14794 :style toggle :selected org-log-done])
14795 "--"
14796 ["Agenda Command" org-agenda t]
14797 ("File List for Agenda")
14798 ("Special views current file"
14799 ["TODO Tree" org-show-todo-tree t]
14800 ["Check Deadlines" org-check-deadlines t]
14801 ["Timeline" org-timeline t]
14802 ["Tags Tree" org-tags-sparse-tree t])
14803 "--"
14804 ("Hyperlinks"
14805 ["Store Link (Global)" org-store-link t]
14806 ["Insert Link" org-insert-link t]
14807 ["Follow Link" org-open-at-point t]
14808 "--"
14809 ["Descriptive Links"
14810 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14811 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
14812 ["Literal Links"
14813 (progn
14814 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14815 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
14816 "--"
14817 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
14818 (save-excursion (goto-char (point-min))
14819 (re-search-forward "<[a-z]+:" nil t))])
14820 "--"
14821 ["Export/Publish" org-export t]
14822 "--"
14823 ("Documentation"
14824 ["Show Version" org-version t]
14825 ["Info Documentation" org-info t])
14826 ("Customize"
14827 ["Browse Org Group" org-customize t]
14828 "--"
14829 ["Expand This Menu" org-create-customize-menu
14830 (fboundp 'customize-menu-create)])
14831 "--"
14832 ["Refresh setup" org-mode-restart t]
14833 ))
14834
14835 (defun org-info (&optional node)
14836 "Read documentation for Org-mode in the info system.
14837 With optional NODE, go directly to that node."
14838 (interactive)
14839 (require 'info)
14840 (Info-goto-node (format "(org)%s" (or node ""))))
14841
14842 (defun org-install-agenda-files-menu ()
14843 (let ((bl (buffer-list)))
14844 (save-excursion
14845 (while bl
14846 (set-buffer (pop bl))
14847 (if (eq major-mode 'org-mode) (setq bl nil)))
14848 (when (eq major-mode 'org-mode)
14849 (easy-menu-change
14850 '("Org") "File List for Agenda"
14851 (append
14852 (list
14853 ["Edit File List" (org-edit-agenda-file-list) t]
14854 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14855 ["Remove Current File from List" org-remove-file t]
14856 ["Cycle through agenda files" org-cycle-agenda-files t]
14857 "--")
14858 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14859
14860 ;;; Documentation
14861
14862 (defun org-customize ()
14863 "Call the customize function with org as argument."
14864 (interactive)
14865 (customize-browse 'org))
14866
14867 (defun org-create-customize-menu ()
14868 "Create a full customization menu for Org-mode, insert it into the menu."
14869 (interactive)
14870 (if (fboundp 'customize-menu-create)
14871 (progn
14872 (easy-menu-change
14873 '("Org") "Customize"
14874 `(["Browse Org group" org-customize t]
14875 "--"
14876 ,(customize-menu-create 'org)
14877 ["Set" Custom-set t]
14878 ["Save" Custom-save t]
14879 ["Reset to Current" Custom-reset-current t]
14880 ["Reset to Saved" Custom-reset-saved t]
14881 ["Reset to Standard Settings" Custom-reset-standard t]))
14882 (message "\"Org\"-menu now contains full customization menu"))
14883 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14884
14885 ;;; Miscellaneous stuff
14886
14887 (defun org-context ()
14888 "Return a list of contexts of the current cursor position.
14889 If several contexts apply, all are returned.
14890 Each context entry is a list with a symbol naming the context, and
14891 two positions indicating start and end of the context. Possible
14892 contexts are:
14893
14894 :headline anywhere in a headline
14895 :headline-stars on the leading stars in a headline
14896 :todo-keyword on a TODO keyword (including DONE) in a headline
14897 :tags on the TAGS in a headline
14898 :priority on the priority cookie in a headline
14899 :item on the first line of a plain list item
14900 :checkbox on the checkbox in a plain list item
14901 :table in an org-mode table
14902 :table-special on a special filed in a table
14903 :table-table in a table.el table
14904 :link on a hyperline
14905 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14906 :target on a <<target>>
14907 :radio-target on a <<<radio-target>>>
14908
14909 This function expects the position to be visible because it uses font-lock
14910 faces as a help to recognize the following contexts: :table-special, :link,
14911 and :keyword."
14912 (let* ((f (get-text-property (point) 'face))
14913 (faces (if (listp f) f (list f)))
14914 (p (point)) clist)
14915 ;; First the large context
14916 (cond
14917 ((org-on-heading-p)
14918 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14919 (when (progn
14920 (beginning-of-line 1)
14921 (looking-at org-todo-line-tags-regexp))
14922 (push (org-point-in-group p 1 :headline-stars) clist)
14923 (push (org-point-in-group p 2 :todo-keyword) clist)
14924 (push (org-point-in-group p 4 :tags) clist))
14925 (goto-char p)
14926 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14927 (if (looking-at "\\[#[A-Z]\\]")
14928 (push (org-point-in-group p 0 :priority) clist)))
14929
14930 ((org-at-item-p)
14931 (push (list :item (point-at-bol)
14932 (save-excursion (org-end-of-item) (point)))
14933 clist)
14934 (and (org-at-item-checkbox-p)
14935 (push (org-point-in-group p 0 :checkbox) clist)))
14936
14937 ((org-at-table-p)
14938 (push (list :table (org-table-begin) (org-table-end)) clist)
14939 (if (memq 'org-formula faces)
14940 (push (list :table-special
14941 (previous-single-property-change p 'face)
14942 (next-single-property-change p 'face)) clist)))
14943 ((org-at-table-p 'any)
14944 (push (list :table-table) clist)))
14945 (goto-char p)
14946
14947 ;; Now the small context
14948 (cond
14949 ((org-at-timestamp-p)
14950 (push (org-point-in-group p 0 :timestamp) clist))
14951 ((memq 'org-link faces)
14952 (push (list :link
14953 (previous-single-property-change p 'face)
14954 (next-single-property-change p 'face)) clist))
14955 ((memq 'org-special-keyword faces)
14956 (push (list :keyword
14957 (previous-single-property-change p 'face)
14958 (next-single-property-change p 'face)) clist))
14959 ((org-on-target-p)
14960 (push (org-point-in-group p 0 :target) clist)
14961 (goto-char (1- (match-beginning 0)))
14962 (if (looking-at org-radio-target-regexp)
14963 (push (org-point-in-group p 0 :radio-target) clist))
14964 (goto-char p)))
14965
14966 (setq clist (nreverse (delq nil clist)))
14967 clist))
14968
14969 (defun org-point-in-group (point group &optional context)
14970 "Check if POINT is in match-group GROUP.
14971 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14972 match. If the match group does ot exist or point is not inside it,
14973 return nil."
14974 (and (match-beginning group)
14975 (>= point (match-beginning group))
14976 (<= point (match-end group))
14977 (if context
14978 (list context (match-beginning group) (match-end group))
14979 t)))
14980
14981 (defun org-move-line-down (arg)
14982 "Move the current line down. With prefix argument, move it past ARG lines."
14983 (interactive "p")
14984 (let ((col (current-column))
14985 beg end pos)
14986 (beginning-of-line 1) (setq beg (point))
14987 (beginning-of-line 2) (setq end (point))
14988 (beginning-of-line (+ 1 arg))
14989 (setq pos (move-marker (make-marker) (point)))
14990 (insert (delete-and-extract-region beg end))
14991 (goto-char pos)
14992 (move-to-column col)))
14993
14994 (defun org-move-line-up (arg)
14995 "Move the current line up. With prefix argument, move it past ARG lines."
14996 (interactive "p")
14997 (let ((col (current-column))
14998 beg end pos)
14999 (beginning-of-line 1) (setq beg (point))
15000 (beginning-of-line 2) (setq end (point))
15001 (beginning-of-line (- arg))
15002 (setq pos (move-marker (make-marker) (point)))
15003 (insert (delete-and-extract-region beg end))
15004 (goto-char pos)
15005 (move-to-column col)))
15006
15007 ;; Paragraph filling stuff.
15008 ;; We want this to be just right, so use the full arsenal.
15009
15010 (defun org-set-autofill-regexps ()
15011 (interactive)
15012 ;; In the paragraph separator we include headlines, because filling
15013 ;; text in a line directly attached to a headline would otherwise
15014 ;; fill the headline as well.
15015 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
15016 ;; The paragraph starter includes hand-formatted lists.
15017 (set (make-local-variable 'paragraph-start)
15018 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15019 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15020 ;; But only if the user has not turned off tables or fixed-width regions
15021 (set (make-local-variable 'auto-fill-inhibit-regexp)
15022 (concat "\\*\\|#"
15023 "\\|[ \t]*" org-keyword-time-regexp
15024 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15025 (concat
15026 "\\|[ \t]*["
15027 (if org-enable-table-editor "|" "")
15028 (if org-enable-fixed-width-editor ":" "")
15029 "]"))))
15030 ;; We use our own fill-paragraph function, to make sure that tables
15031 ;; and fixed-width regions are not wrapped. That function will pass
15032 ;; through to `fill-paragraph' when appropriate.
15033 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
15034 ;; Adaptive filling: To get full control, first make sure that
15035 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15036 (set (make-local-variable 'adaptive-fill-regexp) "\000")
15037 (set (make-local-variable 'adaptive-fill-function)
15038 'org-adaptive-fill-function))
15039
15040 (defun org-fill-paragraph (&optional justify)
15041 "Re-align a table, pass through to fill-paragraph if no table."
15042 (let ((table-p (org-at-table-p))
15043 (table.el-p (org-at-table.el-p)))
15044 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
15045 (table.el-p t) ; skip table.el tables
15046 (table-p (org-table-align) t) ; align org-mode tables
15047 (t nil)))) ; call paragraph-fill
15048
15049 ;; For reference, this is the default value of adaptive-fill-regexp
15050 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15051
15052 (defun org-adaptive-fill-function ()
15053 "Return a fill prefix for org-mode files.
15054 In particular, this makes sure hanging paragraphs for hand-formatted lists
15055 work correctly."
15056 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
15057 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
15058
15059 ;; Functions needed for Emacs/XEmacs region compatibility
15060
15061 (defun org-add-hook (hook function &optional append local)
15062 "Add-hook, compatible with both Emacsen."
15063 (if (and local (featurep 'xemacs))
15064 (add-local-hook hook function append)
15065 (add-hook hook function append local)))
15066
15067 (defun org-region-active-p ()
15068 "Is `transient-mark-mode' on and the region active?
15069 Works on both Emacs and XEmacs."
15070 (if org-ignore-region
15071 nil
15072 (if (featurep 'xemacs)
15073 (and zmacs-regions (region-active-p))
15074 (and transient-mark-mode mark-active))))
15075
15076 (defun org-add-to-invisibility-spec (arg)
15077 "Add elements to `buffer-invisibility-spec'.
15078 See documentation for `buffer-invisibility-spec' for the kind of elements
15079 that can be added."
15080 (cond
15081 ((fboundp 'add-to-invisibility-spec)
15082 (add-to-invisibility-spec arg))
15083 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
15084 (setq buffer-invisibility-spec (list arg)))
15085 (t
15086 (setq buffer-invisibility-spec
15087 (cons arg buffer-invisibility-spec)))))
15088
15089 (defun org-remove-from-invisibility-spec (arg)
15090 "Remove elements from `buffer-invisibility-spec'."
15091 (if (fboundp 'remove-from-invisibility-spec)
15092 (remove-from-invisibility-spec arg)
15093 (if (consp buffer-invisibility-spec)
15094 (setq buffer-invisibility-spec
15095 (delete arg buffer-invisibility-spec)))))
15096
15097 (defun org-in-invisibility-spec-p (arg)
15098 "Is ARG a member of `buffer-invisibility-spec'?"
15099 (if (consp buffer-invisibility-spec)
15100 (member arg buffer-invisibility-spec)
15101 nil))
15102
15103 (defun org-image-file-name-regexp ()
15104 "Return regexp matching the file names of images."
15105 (if (fboundp 'image-file-name-regexp)
15106 (image-file-name-regexp)
15107 (let ((image-file-name-extensions
15108 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15109 "xbm" "xpm" "pbm" "pgm" "ppm")))
15110 (concat "\\."
15111 (regexp-opt (nconc (mapcar 'upcase
15112 image-file-name-extensions)
15113 image-file-name-extensions)
15114 t)
15115 "\\'"))))
15116
15117 ;; Functions needed for compatibility with old outline.el.
15118
15119 ;; Programming for the old outline.el (that uses selective display
15120 ;; instead of `invisible' text properties) is a nightmare, mostly
15121 ;; because regular expressions can no longer be anchored at
15122 ;; beginning/end of line. Therefore a number of function need special
15123 ;; treatment when the old outline.el is being used.
15124
15125 ;; The following functions capture almost the entire compatibility code
15126 ;; between the different versions of outline-mode. The only other
15127 ;; places where this is important are the font-lock-keywords, and in
15128 ;; `org-export-visible'. Search for `org-noutline-p' to find them.
15129
15130 ;; C-a should go to the beginning of a *visible* line, also in the
15131 ;; new outline.el. I guess this should be patched into Emacs?
15132 (defun org-beginning-of-line ()
15133 "Go to the beginning of the current line. If that is invisible, continue
15134 to a visible line beginning. This makes the function of C-a more intuitive."
15135 (interactive)
15136 (beginning-of-line 1)
15137 (if (bobp)
15138 nil
15139 (backward-char 1)
15140 (if (org-invisible-p)
15141 (while (and (not (bobp)) (org-invisible-p))
15142 (backward-char 1)
15143 (beginning-of-line 1))
15144 (forward-char 1))))
15145
15146 (when org-noutline-p
15147 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
15148
15149 (defun org-invisible-p ()
15150 "Check if point is at a character currently not visible."
15151 (if org-noutline-p
15152 ;; Early versions of noutline don't have `outline-invisible-p'.
15153 (if (fboundp 'outline-invisible-p)
15154 (outline-invisible-p)
15155 (get-char-property (point) 'invisible))
15156 (save-excursion
15157 (skip-chars-backward "^\r\n")
15158 (equal (char-before) ?\r))))
15159
15160 (defun org-invisible-p2 ()
15161 "Check if point is at a character currently not visible."
15162 (save-excursion
15163 (if org-noutline-p
15164 (progn
15165 (if (and (eolp) (not (bobp))) (backward-char 1))
15166 ;; Early versions of noutline don't have `outline-invisible-p'.
15167 (if (fboundp 'outline-invisible-p)
15168 (outline-invisible-p)
15169 (get-char-property (point) 'invisible)))
15170 (skip-chars-backward "^\r\n")
15171 (equal (char-before) ?\r))))
15172
15173 (defun org-back-to-heading (&optional invisible-ok)
15174 "Move to previous heading line, or beg of this line if it's a heading.
15175 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
15176 (if org-noutline-p
15177 (outline-back-to-heading invisible-ok)
15178 (if (and (or (bobp) (memq (char-before) '(?\n ?\r)))
15179 (looking-at outline-regexp))
15180 t
15181 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
15182 outline-regexp)
15183 nil t)
15184 (if invisible-ok
15185 (progn (goto-char (or (match-end 1) (match-beginning 0)))
15186 (looking-at outline-regexp)))
15187 (error "Before first heading")))))
15188
15189 (defun org-on-heading-p (&optional invisible-ok)
15190 "Return t if point is on a (visible) heading line.
15191 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
15192 (if org-noutline-p
15193 (outline-on-heading-p 'invisible-ok)
15194 (save-excursion
15195 (skip-chars-backward "^\n\r")
15196 (and (looking-at outline-regexp)
15197 (or invisible-ok
15198 (bobp)
15199 (equal (char-before) ?\n))))))
15200
15201 (defun org-on-target-p ()
15202 (let ((pos (point)))
15203 (save-excursion
15204 (skip-chars-forward "<")
15205 (and (re-search-backward "<<" nil t)
15206 (or (looking-at org-radio-target-regexp)
15207 (looking-at org-target-regexp))
15208 (<= (match-beginning 0) pos)
15209 (>= (1+ (match-end 0)) pos)))))
15210
15211 (defun org-up-heading-all (arg)
15212 "Move to the heading line of which the present line is a subheading.
15213 This function considers both visible and invisible heading lines.
15214 With argument, move up ARG levels."
15215 (if org-noutline-p
15216 (if (fboundp 'outline-up-heading-all)
15217 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15218 (outline-up-heading arg t)) ; emacs 22 version of outline.el
15219 (org-back-to-heading t)
15220 (looking-at outline-regexp)
15221 (if (<= (- (match-end 0) (match-beginning 0)) arg)
15222 (error "Cannot move up %d levels" arg)
15223 (re-search-backward
15224 (concat "[\n\r]" (regexp-quote
15225 (make-string (- (match-end 0) (match-beginning 0) arg)
15226 ?*))
15227 "[^*]"))
15228 (forward-char 1))))
15229
15230 (defun org-show-hidden-entry ()
15231 "Show an entry where even the heading is hidden."
15232 (save-excursion
15233 (if (not org-noutline-p)
15234 (progn
15235 (org-back-to-heading t)
15236 (org-flag-heading nil)))
15237 (org-show-entry)))
15238
15239 (defun org-check-occur-regexp (regexp)
15240 "If REGEXP starts with \"^\", modify it to check for \\r as well.
15241 Of course, only for the old outline mode."
15242 (if org-noutline-p
15243 regexp
15244 (if (string-match "^\\^" regexp)
15245 (concat "[\n\r]" (substring regexp 1))
15246 regexp)))
15247
15248 (defun org-flag-heading (flag &optional entry)
15249 "Flag the current heading. FLAG non-nil means make invisible.
15250 When ENTRY is non-nil, show the entire entry."
15251 (save-excursion
15252 (org-back-to-heading t)
15253 (if (not org-noutline-p)
15254 ;; Make the current headline visible
15255 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
15256 ;; Check if we should show the entire entry
15257 (if entry
15258 (progn
15259 (org-show-entry)
15260 (save-excursion
15261 (and (outline-next-heading)
15262 (org-flag-heading nil))))
15263 (outline-flag-region (max 1 (1- (point)))
15264 (save-excursion (outline-end-of-heading) (point))
15265 (if org-noutline-p
15266 flag
15267 (if flag ?\r ?\n))))))
15268
15269 (defun org-end-of-subtree (&optional invisible-OK)
15270 ;; This is an exact copy of the original function, but it uses
15271 ;; `org-back-to-heading', to make it work also in invisible
15272 ;; trees. And is uses an invisible-OK argument.
15273 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15274 (org-back-to-heading invisible-OK)
15275 (let ((first t)
15276 (level (funcall outline-level)))
15277 (while (and (not (eobp))
15278 (or first (> (funcall outline-level) level)))
15279 (setq first nil)
15280 (outline-next-heading))
15281 (if (memq (preceding-char) '(?\n ?\^M))
15282 (progn
15283 ;; Go to end of line before heading
15284 (forward-char -1)
15285 (if (memq (preceding-char) '(?\n ?\^M))
15286 ;; leave blank line before heading
15287 (forward-char -1))))))
15288
15289 (defun org-show-subtree ()
15290 "Show everything after this heading at deeper levels."
15291 (outline-flag-region
15292 (point)
15293 (save-excursion
15294 (outline-end-of-subtree) (outline-next-heading) (point))
15295 (if org-noutline-p nil ?\n)))
15296
15297 (defun org-show-entry ()
15298 "Show the body directly following this heading.
15299 Show the heading too, if it is currently invisible."
15300 (interactive)
15301 (save-excursion
15302 (org-back-to-heading t)
15303 (outline-flag-region
15304 (max 1 (1- (point)))
15305 (save-excursion
15306 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
15307 (or (match-beginning 1) (point-max)))
15308 (if org-noutline-p nil ?\n))))
15309
15310 (defun org-make-options-regexp (kwds)
15311 "Make a regular expression for keyword lines."
15312 (concat
15313 (if org-noutline-p "^" "[\n\r]")
15314 "#?[ \t]*\\+\\("
15315 (mapconcat 'regexp-quote kwds "\\|")
15316 "\\):[ \t]*"
15317 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
15318
15319 ;; Make `bookmark-jump' show the jump location if it was hidden.
15320 (eval-after-load "bookmark"
15321 '(if (boundp 'bookmark-after-jump-hook)
15322 ;; We can use the hook
15323 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15324 ;; Hook not available, use advice
15325 (defadvice bookmark-jump (after org-make-visible activate)
15326 "Make the position visible."
15327 (org-bookmark-jump-unhide))))
15328
15329 (defun org-bookmark-jump-unhide ()
15330 "Unhide the current position, to show the bookmark location."
15331 (and (eq major-mode 'org-mode)
15332 (or (org-invisible-p)
15333 (save-excursion (goto-char (max (point-min) (1- (point))))
15334 (org-invisible-p)))
15335 (org-show-hierarchy-above)))
15336
15337 ;;; Finish up
15338
15339 (provide 'org)
15340
15341 (run-hooks 'org-load-hook)
15342
15343 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15344 ;;; org.el ends here