]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
Require noutline, also on XEmacs.
[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.38
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.38
94 ;; - noutline.el is now required (important for XEmacs users only).
95 ;; - Dynamic blocks.
96 ;; - Archiving of all level 1 trees without open TODO items.
97 ;; - Clock reports can be inserted into the file in a special section.
98 ;; - FAQ removed from the manual, now only on the web.
99 ;; - Bug fixes.
100 ;;
101 ;; Version 4.37
102 ;; - Clock-feature for measuring time spent on specific items.
103 ;; - Improved emphasizing allows configuration and stacking.
104 ;;
105 ;; Version 4.36
106 ;; - Improved indentation of ASCII export, when headlines become items.
107 ;; - Handling of 12am and 12pm fixed. Times beyond 24:00 can be used
108 ;; and will not lead to conflicts.
109 ;; - Support for mutually exclusive TAGS with the fast tags interface.
110 ;; - Bug fixes.
111 ;;
112 ;; Version 4.35
113 ;; - HTML export is now valid XHTML.
114 ;; - Timeline can also show dates without entries. See new option
115 ;; `org-timeline-show-empty-dates'.
116 ;; - The bullets created by the ASCII exporter can now be configured.
117 ;; See the new option `org-export-ascii-bullets'.
118 ;; - New face `org-upcoming-deadline' (was `org-scheduled-previously').
119 ;; - New function `org-context' to allow testing for local context.
120 ;;
121 ;; Version 4.34
122 ;; - Bug fixes.
123 ;;
124 ;; Version 4.33
125 ;; - New commands to move through plain lists: S-up and S-down.
126 ;; - Bug fixes and documentation update.
127 ;;
128 ;; Version 4.32
129 ;; - Fast (single-key-per-tag) interface for setting TAGS.
130 ;; - The list of legal tags can be configured globally and locally.
131 ;; - Elisp and Info links (thanks to Todd Neal).
132 ;; - `org-export-publishing-directory' can be an alist, with different
133 ;; directories for different export types.
134 ;; - All context-sensitive commands use `call-interactively' to dispatch.
135 ;; - `org-confirm-shell-links' renamed to `org-confirm-shell-link-function'.
136 ;; - Bug fixes.
137 ;;
138 ;; Version 4.31
139 ;; - Bug fixes.
140 ;;
141 ;; Version 4.30
142 ;; - Modified installation: Autoloads have been collected in org-install.el.
143 ;; - Logging (org-log-done) is now a #+STARTUP option.
144 ;; - Checkboxes in plain list items, following up on Frank Ruell's idea.
145 ;; - File links inserted with C-c C-l will use relative paths if the linked
146 ;; file is in the current directory or a subdirectory of it.
147 ;; - New variable `org-link-file-path-type' to specify preference for
148 ;; relative and absolute paths.
149 ;; - New CSS classes for tags, timestamps, timestamp keywords.
150 ;; - Bug and typo fixes.
151 ;;
152 ;; Version 4.29
153 ;; - Inlining images in HTML export now depends on wheather the link
154 ;; contains a description or not.
155 ;; - TODO items can be scheduled from the global TODO list using C-c C-s.
156 ;; - TODO items already scheduled can be made to disappear from the global
157 ;; todo list, see `org-agenda-todo-ignore-scheduled'.
158 ;; - In Tables, formulas may also be Lisp forms.
159 ;; - Exporting the visible part of an outline with `C-c C-x v' works now
160 ;; for all available exporters.
161 ;; - Bug fixes, lots of them :-(
162 ;;
163 ;; Version 4.28
164 ;; - Bug fixes.
165 ;;
166 ;; Version 4.27
167 ;; - HTML exporter generalized to receive external options.
168 ;; As part of the process, author, email and date have been moved to the
169 ;; end of the HTML file.
170 ;; - Support for customizable file search in file links.
171 ;; - BibTeX database links as first application of the above.
172 ;; - New option `org-agenda-todo-list-sublevels' to turn off listing TODO
173 ;; entries that are sublevels of another TODO entry.
174 ;;
175 ;;
176 ;;; Code:
177
178 (eval-when-compile
179 (require 'cl)
180 (require 'calendar))
181 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
182 ;; the file noutline.el being loaded.
183 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
184 ;; We require noutline, which might be provided in outline.el
185 (require 'outline) (require 'noutline)
186 ;; Other stuff we need.
187 (require 'time-date)
188 (require 'easymenu)
189
190 ;;; Customization variables
191
192 (defvar org-version "4.38"
193 "The version number of the file org.el.")
194 (defun org-version ()
195 (interactive)
196 (message "Org-mode version %s" org-version))
197
198 ;; The following constant is for compatibility with different versions
199 ;; of outline.el.
200 (defconst org-noutline-p (featurep 'noutline)
201 "Are we using the new outline mode?")
202 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
203 (defconst org-format-transports-properties-p
204 (let ((x "a"))
205 (add-text-properties 0 1 '(test t) x)
206 (get-text-property 0 'test (format "%s" x)))
207 "Does format transport text properties?")
208
209 (defgroup org nil
210 "Outline-based notes management and organizer."
211 :tag "Org"
212 :group 'outlines
213 :group 'hypermedia
214 :group 'calendar)
215
216 (defgroup org-startup nil
217 "Options concerning startup of Org-mode."
218 :tag "Org Startup"
219 :group 'org)
220
221 (defcustom org-startup-folded t
222 "Non-nil means, entering Org-mode will switch to OVERVIEW.
223 This can also be configured on a per-file basis by adding one of
224 the following lines anywhere in the buffer:
225
226 #+STARTUP: fold
227 #+STARTUP: nofold
228 #+STARTUP: content"
229 :group 'org-startup
230 :type '(choice
231 (const :tag "nofold: show all" nil)
232 (const :tag "fold: overview" t)
233 (const :tag "content: all headlines" content)))
234
235 (defcustom org-startup-truncated t
236 "Non-nil means, entering Org-mode will set `truncate-lines'.
237 This is useful since some lines containing links can be very long and
238 uninteresting. Also tables look terrible when wrapped."
239 :group 'org-startup
240 :type 'boolean)
241
242 (defcustom org-startup-align-all-tables nil
243 "Non-nil means, align all tables when visiting a file.
244 This is useful when the column width in tables is forced with <N> cookies
245 in table fields. Such tables will look correct only after the first re-align.
246 This can also be configured on a per-file basis by adding one of
247 the following lines anywhere in the buffer:
248 #+STARTUP: align
249 #+STARTUP: noalign"
250 :group 'org-startup
251 :type 'boolean)
252
253 (defcustom org-startup-with-deadline-check nil
254 "Non-nil means, entering Org-mode will run the deadline check.
255 This means, if you start editing an org file, you will get an
256 immediate reminder of any due deadlines.
257 This can also be configured on a per-file basis by adding one of
258 the following lines anywhere in the buffer:
259 #+STARTUP: dlcheck
260 #+STARTUP: nodlcheck"
261 :group 'org-startup
262 :type 'boolean)
263
264 (defcustom org-insert-mode-line-in-empty-file nil
265 "Non-nil means insert the first line setting Org-mode in empty files.
266 When the function `org-mode' is called interactively in an empty file, this
267 normally means that the file name does not automatically trigger Org-mode.
268 To ensure that the file will always be in Org-mode in the future, a
269 line enforcing Org-mode will be inserted into the buffer, if this option
270 has been set."
271 :group 'org-startup
272 :type 'boolean)
273
274 (defcustom org-CUA-compatible nil
275 "Non-nil means use alternative key bindings for S-<cursor movement>.
276 Org-mode used S-<cursor movement> for changing timestamps and priorities.
277 S-<cursor movement> is also used for example by `CUA-mode' to select text.
278 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
279 alternative bindings. Setting this variable to t will replace the following
280 keys both in Org-mode and in the Org-agenda buffer.
281
282 S-RET -> C-S-RET
283 S-up -> M-p
284 S-down -> M-n
285 S-left -> M--
286 S-right -> M-+
287
288 If you do not like the alternative keys, take a look at the variable
289 `org-disputed-keys'.
290
291 This option is only relevant at load-time of Org-mode. Changing it requires
292 a restart of Emacs to become effective."
293 :group 'org-startup
294 :type 'boolean)
295
296 (defvar org-disputed-keys
297 '((S-up [(shift up)] [(meta ?p)])
298 (S-down [(shift down)] [(meta ?n)])
299 (S-left [(shift left)] [(meta ?-)])
300 (S-right [(shift right)] [(meta ?+)])
301 (S-return [(shift return)] [(control shift return)]))
302 "Keys for which Org-mode and other modes compete.
303 This is an alist, cars are symbols for lookup, 1st element is the default key,
304 second element will be used when `org-CUA-compatible' is t.")
305
306 (defun org-key (key)
307 "Select a key according to `org-CUA-compatible'."
308 (nth (if org-CUA-compatible 2 1)
309 (or (assq key org-disputed-keys)
310 (error "Invalid Key %s in `org-key'" key))))
311
312 (defcustom org-ellipsis nil
313 "The ellipsis to use in the Org-mode outline.
314 When nil, just use the standard three dots. When a string, use that instead,
315 and just in Org-mode (which will then use its own display table).
316 Changing this requires executing `M-x org-mode' in a buffer to become
317 effective."
318 :group 'org-startup
319 :type '(choice (const :tag "Default" nil)
320 (string :tag "String" :value "...#")))
321
322 (defvar org-display-table nil
323 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
324
325 (defgroup org-keywords nil
326 "Keywords in Org-mode."
327 :tag "Org Keywords"
328 :group 'org)
329
330 (defcustom org-deadline-string "DEADLINE:"
331 "String to mark deadline entries.
332 A deadline is this string, followed by a time stamp. Should be a word,
333 terminated by a colon. You can insert a schedule keyword and
334 a timestamp with \\[org-deadline].
335 Changes become only effective after restarting Emacs."
336 :group 'org-keywords
337 :type 'string)
338
339 (defcustom org-scheduled-string "SCHEDULED:"
340 "String to mark scheduled TODO entries.
341 A schedule is this string, followed by a time stamp. Should be a word,
342 terminated by a colon. You can insert a schedule keyword and
343 a timestamp with \\[org-schedule].
344 Changes become only effective after restarting Emacs."
345 :group 'org-keywords
346 :type 'string)
347
348 (defcustom org-closed-string "CLOSED:"
349 "String used as the prefix for timestamps logging closing a TODO entry."
350 :group 'org-keywords
351 :type 'string)
352
353 (defcustom org-clock-string "CLOCK:"
354 "String used as prefix for timestamps clocking work hours on an item."
355 :group 'org-keywords
356 :type 'string)
357
358 (defcustom org-comment-string "COMMENT"
359 "Entries starting with this keyword will never be exported.
360 An entry can be toggled between COMMENT and normal with
361 \\[org-toggle-comment].
362 Changes become only effective after restarting Emacs."
363 :group 'org-keywords
364 :type 'string)
365
366 (defcustom org-quote-string "QUOTE"
367 "Entries starting with this keyword will be exported in fixed-width font.
368 Quoting applies only to the text in the entry following the headline, and does
369 not extend beyond the next headline, even if that is lower level.
370 An entry can be toggled between QUOTE and normal with
371 \\[org-toggle-fixed-width-section]."
372 :group 'org-keywords
373 :type 'string)
374
375 (defgroup org-structure nil
376 "Options concerning the general structure of Org-mode files."
377 :tag "Org Structure"
378 :group 'org)
379
380 (defgroup org-cycle nil
381 "Options concerning visibility cycling in Org-mode."
382 :tag "Org Cycle"
383 :group 'org-structure)
384
385 (defcustom org-cycle-global-at-bob t
386 "Cycle globally if cursor is at beginning of buffer and not at a headline.
387 This makes it possible to do global cycling without having to use S-TAB or
388 C-u TAB. For this special case to work, the first line of the buffer
389 must not be a headline - it may be empty ot some other text. When used in
390 this way, `org-cycle-hook' is disables temporarily, to make sure the
391 cursor stays at the beginning of the buffer.
392 When this option is nil, don't do anything special at the beginning
393 of the buffer."
394 :group 'org-cycle
395 :type 'boolean)
396
397 (defcustom org-cycle-emulate-tab t
398 "Where should `org-cycle' emulate TAB.
399 nil Never
400 white Only in completely white lines
401 whitestart Only at the beginning of lines, before the first non-white char.
402 t Everywhere except in headlines
403 If TAB is used in a place where it does not emulate TAB, the current subtree
404 visibility is cycled."
405 :group 'org-cycle
406 :type '(choice (const :tag "Never" nil)
407 (const :tag "Only in completely white lines" white)
408 (const :tag "Before first char in a line" whitestart)
409 (const :tag "Everywhere except in headlines" t)
410 ))
411
412 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
413 "Hook that is run after `org-cycle' has changed the buffer visibility.
414 The function(s) in this hook must accept a single argument which indicates
415 the new state that was set by the most recent `org-cycle' command. The
416 argument is a symbol. After a global state change, it can have the values
417 `overview', `content', or `all'. After a local state change, it can have
418 the values `folded', `children', or `subtree'."
419 :group 'org-cycle
420 :type 'hook)
421
422 (defgroup org-edit-structure nil
423 "Options concerning structure editing in Org-mode."
424 :tag "Org Edit Structure"
425 :group 'org-structure)
426
427 (defcustom org-odd-levels-only nil
428 "Non-nil means, skip even levels and only use odd levels for the outline.
429 This has the effect that two stars are being added/taken away in
430 promotion/demotion commands. It also influences how levels are
431 handled by the exporters.
432 Changing it requires restart of `font-lock-mode' to become effective
433 for fontification also in regions already fontified.
434 You may also set this on a per-file basis by adding one of the following
435 lines to the buffer:
436
437 #+STARTUP: odd
438 #+STARTUP: oddeven"
439 :group 'org-edit-structure
440 :group 'org-font-lock
441 :type 'boolean)
442
443 (defcustom org-adapt-indentation t
444 "Non-nil means, adapt indentation when promoting and demoting.
445 When this is set and the *entire* text in an entry is indented, the
446 indentation is increased by one space in a demotion command, and
447 decreased by one in a promotion command. If any line in the entry
448 body starts at column 0, indentation is not changed at all."
449 :group 'org-edit-structure
450 :type 'boolean)
451
452 (defcustom org-insert-heading-hook nil
453 "Hook being run after inserting a new heading."
454 :group 'org-edit-structure
455 :type 'boolean)
456
457 (defcustom org-enable-fixed-width-editor t
458 "Non-nil means, lines starting with \":\" are treated as fixed-width.
459 This currently only means, they are never auto-wrapped.
460 When nil, such lines will be treated like ordinary lines.
461 See also the QUOTE keyword."
462 :group 'org-edit-structure
463 :type 'boolean)
464
465 (defgroup org-sparse-trees nil
466 "Options concerning sparse trees in Org-mode."
467 :tag "Org Sparse Trees"
468 :group 'org-structure)
469
470 (defcustom org-highlight-sparse-tree-matches t
471 "Non-nil means, highlight all matches that define a sparse tree.
472 The highlights will automatically disappear the next time the buffer is
473 changed by an edit command."
474 :group 'org-sparse-trees
475 :type 'boolean)
476
477 (defcustom org-show-hierarchy-above t
478 "Non-nil means, show full hierarchy when showing a spot in the tree.
479 Turning this off makes sparse trees more compact, but also less clear."
480 :group 'org-sparse-trees
481 :type 'boolean)
482
483 (defcustom org-show-following-heading t
484 "Non-nil means, show heading following match in `org-occur'.
485 When doing an `org-occur' it is useful to show the headline which
486 follows the match, even if they do not match the regexp. This makes it
487 easier to edit directly inside the sparse tree. However, if you use
488 `org-occur' mainly as an overview, the following headlines are
489 unnecessary clutter."
490 :group 'org-sparse-trees
491 :type 'boolean)
492
493 (defcustom org-occur-hook '(org-first-headline-recenter)
494 "Hook that is run after `org-occur' has constructed a sparse tree.
495 This can be used to recenter the window to show as much of the structure
496 as possible."
497 :group 'org-sparse-trees
498 :type 'hook)
499
500 (defgroup org-plain-lists nil
501 "Options concerning plain lists in Org-mode."
502 :tag "Org Plain lists"
503 :group 'org-structure)
504
505 (defcustom org-cycle-include-plain-lists nil
506 "Non-nil means, include plain lists into visibility cycling.
507 This means that during cycling, plain list items will *temporarily* be
508 interpreted as outline headlines with a level given by 1000+i where i is the
509 indentation of the bullet. In all other operations, plain list items are
510 not seen as headlines. For example, you cannot assign a TODO keyword to
511 such an item."
512 :group 'org-plain-lists
513 :type 'boolean)
514
515
516 (defcustom org-plain-list-ordered-item-terminator t
517 "The character that makes a line with leading number an ordered list item.
518 Valid values are ?. and ?\). To get both terminators, use t. While
519 ?. may look nicer, it creates the danger that a line with leading
520 number may be incorrectly interpreted as an item. ?\) therefore is
521 the safe choice."
522 :group 'org-plain-lists
523 :type '(choice (const :tag "dot like in \"2.\"" ?.)
524 (const :tag "paren like in \"2)\"" ?\))
525 (const :tab "both" t)))
526
527 (defcustom org-auto-renumber-ordered-lists t
528 "Non-nil means, automatically renumber ordered plain lists.
529 Renumbering happens when the sequence have been changed with
530 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
531 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
532 :group 'org-plain-lists
533 :type 'boolean)
534
535 (defgroup org-archive nil
536 "Options concerning archiving in Org-mode."
537 :tag "Org Archive"
538 :group 'org-structure)
539
540 (defcustom org-archive-location "%s_archive::"
541 "The location where subtrees should be archived.
542 This string consists of two parts, separated by a double-colon.
543
544 The first part is a file name - when omitted, archiving happens in the same
545 file. %s will be replaced by the current file name (without directory part).
546 Archiving to a different file is useful to keep archived entries from
547 contributing to the Org-mode Agenda.
548
549 The part after the double colon is a headline. The archived entries will be
550 filed under that headline. When omitted, the subtrees are simply filed away
551 at the end of the file, as top-level entries.
552
553 Here are a few examples:
554 \"%s_archive::\"
555 If the current file is Projects.org, archive in file
556 Projects.org_archive, as top-level trees. This is the default.
557
558 \"::* Archived Tasks\"
559 Archive in the current file, under the top-level headline
560 \"* Archived Tasks\".
561
562 \"~/org/archive.org::\"
563 Archive in file ~/org/archive.org (absolute path), as top-level trees.
564
565 \"basement::** Finished Tasks\"
566 Archive in file ./basement (relative path), as level 3 trees
567 below the level 2 heading \"** Finished Tasks\".
568
569 You may set this option on a per-file basis by adding to the buffer a
570 line like
571
572 #+ARCHIVE: basement::** Finished Tasks"
573 :group 'org-archive
574 :type 'string)
575
576 (defcustom org-archive-mark-done t
577 "Non-nil means, mark archived entries as DONE."
578 :group 'org-archive
579 :type 'boolean)
580
581 (defcustom org-archive-stamp-time t
582 "Non-nil means, add a time stamp to archived entries.
583 The time stamp will be added directly after the TODO state keyword in the
584 first line, so it is probably best to use this in combinations with
585 `org-archive-mark-done'."
586 :group 'org-archive
587 :type 'boolean)
588
589 (defgroup org-table nil
590 "Options concerning tables in Org-mode."
591 :tag "Org Table"
592 :group 'org)
593
594 (defcustom org-enable-table-editor 'optimized
595 "Non-nil means, lines starting with \"|\" are handled by the table editor.
596 When nil, such lines will be treated like ordinary lines.
597
598 When equal to the symbol `optimized', the table editor will be optimized to
599 do the following:
600 - Use automatic overwrite mode in front of whitespace in table fields.
601 This make the structure of the table stay in tact as long as the edited
602 field does not exceed the column width.
603 - Minimize the number of realigns. Normally, the table is aligned each time
604 TAB or RET are pressed to move to another field. With optimization this
605 happens only if changes to a field might have changed the column width.
606 Optimization requires replacing the functions `self-insert-command',
607 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
608 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
609 very good at guessing when a re-align will be necessary, but you can always
610 force one with \\[org-ctrl-c-ctrl-c].
611
612 If you would like to use the optimized version in Org-mode, but the
613 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
614
615 This variable can be used to turn on and off the table editor during a session,
616 but in order to toggle optimization, a restart is required.
617
618 See also the variable `org-table-auto-blank-field'."
619 :group 'org-table
620 :type '(choice
621 (const :tag "off" nil)
622 (const :tag "on" t)
623 (const :tag "on, optimized" optimized)))
624
625 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
626 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
627 In the optimized version, the table editor takes over all simple keys that
628 normally just insert a character. In tables, the characters are inserted
629 in a way to minimize disturbing the table structure (i.e. in overwrite mode
630 for empty fields). Outside tables, the correct binding of the keys is
631 restored.
632
633 The default for this option is t if the optimized version is also used in
634 Org-mode. See the variable `org-enable-table-editor' for details. Changing
635 this variable requires a restart of Emacs to become effective."
636 :group 'org-table
637 :type 'boolean)
638
639 (defgroup org-table-settings nil
640 "Settings for tables in Org-mode."
641 :tag "Org Table Settings"
642 :group 'org-table)
643
644 (defcustom org-table-default-size "5x2"
645 "The default size for newly created tables, Columns x Rows."
646 :group 'org-table-settings
647 :type 'string)
648
649 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
650 "Regular expression for recognizing numbers in table columns.
651 If a table column contains mostly numbers, it will be aligned to the
652 right. If not, it will be aligned to the left.
653
654 The default value of this option is a regular expression which allows
655 anything which looks remotely like a number as used in scientific
656 context. For example, all of the following will be considered a
657 number:
658 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
659
660 Other options offered by the customize interface are more restrictive."
661 :group 'org-table-settings
662 :type '(choice
663 (const :tag "Positive Integers"
664 "^[0-9]+$")
665 (const :tag "Integers"
666 "^[-+]?[0-9]+$")
667 (const :tag "Floating Point Numbers"
668 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
669 (const :tag "Floating Point Number or Integer"
670 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
671 (const :tag "Exponential, Floating point, Integer"
672 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
673 (const :tag "Very General Number-Like"
674 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
675 (string :tag "Regexp:")))
676
677 (defcustom org-table-number-fraction 0.5
678 "Fraction of numbers in a column required to make the column align right.
679 In a column all non-white fields are considered. If at least this
680 fraction of fields is matched by `org-table-number-fraction',
681 alignment to the right border applies."
682 :group 'org-table-settings
683 :type 'number)
684
685 (defgroup org-table-editing nil
686 "Bahavior of tables during editing in Org-mode."
687 :tag "Org Table Editing"
688 :group 'org-table)
689
690 (defcustom org-table-automatic-realign t
691 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
692 When nil, aligning is only done with \\[org-table-align], or after column
693 removal/insertion."
694 :group 'org-table-editing
695 :type 'boolean)
696
697 (defcustom org-table-limit-column-width t ;kw
698 "Non-nil means, allow to limit the width of table columns with <N> fields."
699 :group 'org-table-editing
700 :type 'boolean)
701
702 (defcustom org-table-auto-blank-field t
703 "Non-nil means, automatically blank table field when starting to type into it.
704 This only happens when typing immediately after a field motion
705 command (TAB, S-TAB or RET).
706 Only relevant when `org-enable-table-editor' is equal to `optimized'."
707 :group 'org-table-editing
708 :type 'boolean)
709
710 (defcustom org-table-tab-jumps-over-hlines t
711 "Non-nil means, tab in the last column of a table with jump over a hline.
712 If a horizontal separator line is following the current line,
713 `org-table-next-field' can either create a new row before that line, or jump
714 over the line. When this option is nil, a new line will be created before
715 this line."
716 :group 'org-table-editing
717 :type 'boolean)
718
719 (defcustom org-table-tab-recognizes-table.el t
720 "Non-nil means, TAB will automatically notice a table.el table.
721 When it sees such a table, it moves point into it and - if necessary -
722 calls `table-recognize-table'."
723 :group 'org-table-editing
724 :type 'boolean)
725
726 (defgroup org-table-calculation nil
727 "Options concerning tables in Org-mode."
728 :tag "Org Table Calculation"
729 :group 'org-table)
730
731 (defcustom org-table-copy-increment t
732 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
733 :group 'org-table-calculation
734 :type 'boolean)
735
736 (defcustom org-calc-default-modes
737 '(calc-internal-prec 12
738 calc-float-format (float 5)
739 calc-angle-mode deg
740 calc-prefer-frac nil
741 calc-symbolic-mode nil
742 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
743 calc-display-working-message t
744 )
745 "List with Calc mode settings for use in calc-eval for table formulas.
746 The list must contain alternating symbols (Calc modes variables and values).
747 Don't remove any of the default settings, just change the values. Org-mode
748 relies on the variables to be present in the list."
749 :group 'org-table-calculation
750 :type 'plist)
751
752 (defcustom org-table-formula-evaluate-inline t
753 "Non-nil means, TAB and RET evaluate a formula in current table field.
754 If the current field starts with an equal sign, it is assumed to be a formula
755 which should be evaluated as described in the manual and in the documentation
756 string of the command `org-table-eval-formula'. This feature requires the
757 Emacs calc package.
758 When this variable is nil, formula calculation is only available through
759 the command \\[org-table-eval-formula]."
760 :group 'org-table-calculation
761 :type 'boolean)
762
763
764 (defcustom org-table-formula-use-constants t
765 "Non-nil means, interpret constants in formulas in tables.
766 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
767 by the value given in `org-table-formula-constants', or by a value obtained
768 from the `constants.el' package."
769 :group 'org-table-calculation
770 :type 'boolean)
771
772 (defcustom org-table-formula-constants nil
773 "Alist with constant names and values, for use in table formulas.
774 The car of each element is a name of a constant, without the `$' before it.
775 The cdr is the value as a string. For example, if you'd like to use the
776 speed of light in a formula, you would configure
777
778 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
779
780 and then use it in an equation like `$1*$c'."
781 :group 'org-table-calculation
782 :type '(repeat
783 (cons (string :tag "name")
784 (string :tag "value"))))
785
786 (defcustom org-table-formula-numbers-only nil
787 "Non-nil means, calculate only with numbers in table formulas.
788 Then all input fields will be converted to a number, and the result
789 must also be a number. When nil, calc's full potential is available
790 in table calculations, including symbolics etc."
791 :group 'org-table-calculation
792 :type 'boolean)
793
794 (defcustom org-table-allow-automatic-line-recalculation t
795 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
796 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
797 :group 'org-table-calculation
798 :type 'boolean)
799
800 (defgroup org-link nil
801 "Options concerning links in Org-mode."
802 :tag "Org Link"
803 :group 'org)
804
805 (defcustom org-descriptive-links t
806 "Non-nil means, hide link part and only show description of bracket links.
807 Bracket links are like [[link][descritpion]]. This variable sets the initial
808 state in new org-mode buffers. The setting can then be toggled on a
809 per-buffer basis from the Org->Hyperlinks menu."
810 :group 'org-link
811 :type 'boolean)
812
813 (defcustom org-link-style 'bracket
814 "The style of links to be inserted with \\[org-insert-link].
815 Possible values are:
816 bracket [[link][description]]. This is recommended
817 plain Description \\n link. The old way, no longer recommended."
818 :group 'org-link
819 :type '(choice
820 (const :tag "Bracket (recommended)" bracket)
821 (const :tag "Plain (no longer recommended)" plain)))
822
823 (defcustom org-link-format "%s"
824 "Default format for external, URL-like linkes in the buffer.
825 This is a format string for printf, %s will be replaced by the link text.
826 The recommended value is just \"%s\", since links will be protected by
827 enclosing them in double brackets. If you prefer plain links (see variable
828 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
829 additional URL: prefix, so the format would be \"<URL:%s>\"."
830 :group 'org-link
831 :type '(choice
832 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
833 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
834 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
835 (string :tag "Other" :value "<%s>")))
836
837 (defcustom org-link-file-path-type 'adaptive
838 "How the path name in file links should be stored.
839 Valid values are:
840
841 relative relative to the current directory, i.e. the directory of the file
842 into which the link is being inserted.
843 absolute absolute path, if possible with ~ for home directory.
844 noabbrev absolute path, no abbreviation of home directory.
845 adaptive Use relative path for files in the current directory and sub-
846 directories of it. For other files, use an absolute path."
847 :group 'org-link
848 :type '(choice
849 (const relative)
850 (const absolute)
851 (const noabbrev)
852 (const adaptive)))
853
854 (defcustom org-activate-links '(bracket angle plain radio tag date)
855 "Types of links that should be activated in Org-mode files.
856 This is a list of symbols, each leading to the activation of a certain link
857 type. In principle, it does not hurt to turn on most link types - there may
858 be a small gain when turning off unused link types. The types are:
859
860 bracket The recommended [[link][description]] or [[link]] links with hiding.
861 angular Links in angular brackes that may contain whitespace like
862 <bbdb:Carsten Dominik>.
863 plain Plain links in normal text, no whitespace, like http://google.com.
864 radio Text that is matched by a radio target, see manual for details.
865 tag Tag settings in a headline (link to tag search).
866 date Time stamps (link to calendar).
867 camel CamelCase words defining text searches.
868
869 Changing this variable requires a restart of Emacs to become effective."
870 :group 'org-link
871 :type '(set (const :tag "Double bracket links (new style)" bracket)
872 (const :tag "Angular bracket links (old style)" angular)
873 (const :tag "plain text links" plain)
874 (const :tag "Radio target matches" radio)
875 (const :tag "Tags" tag)
876 (const :tag "Timestamps" date)
877 (const :tag "CamelCase words" camel)))
878
879 (defgroup org-link-store nil
880 "Options concerning storing links in Org-mode"
881 :tag "Org Store Link"
882 :group 'org-link)
883
884 (defcustom org-context-in-file-links t
885 "Non-nil means, file links from `org-store-link' contain context.
886 A search string will be added to the file name with :: as separator and
887 used to find the context when the link is activated by the command
888 `org-open-at-point'.
889 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
890 negates this setting for the duration of the command."
891 :group 'org-link-store
892 :type 'boolean)
893
894 (defcustom org-file-link-context-use-camel-case nil
895 "Non-nil means, use CamelCase to store a search context in a file link.
896 When nil, the search string simply consists of the words of the string.
897 CamelCase is deprecated, and support for it may be dropped in the future."
898 :group 'org-link-store
899 :type 'boolean)
900
901 (defcustom org-keep-stored-link-after-insertion nil
902 "Non-nil means, keep link in list for entire session.
903
904 The command `org-store-link' adds a link pointing to the current
905 location to an internal list. These links accumulate during a session.
906 The command `org-insert-link' can be used to insert links into any
907 Org-mode file (offering completion for all stored links). When this
908 option is nil, every link which has been inserted once using \\[org-insert-link]
909 will be removed from the list, to make completing the unused links
910 more efficient."
911 :group 'org-link-store
912 :type 'boolean)
913
914 (defcustom org-usenet-links-prefer-google nil
915 "Non-nil means, `org-store-link' will create web links to Google groups.
916 When nil, Gnus will be used for such links.
917 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
918 negates this setting for the duration of the command."
919 :group 'org-link-store
920 :type 'boolean)
921
922 (defgroup org-link-follow nil
923 "Options concerning following links in Org-mode"
924 :tag "Org Follow Link"
925 :group 'org-link)
926
927 (defcustom org-tab-follows-link nil
928 "Non-nil means, on links TAB will follow the link.
929 Needs to be set before org.el is loaded."
930 :group 'org-link-follow
931 :type 'boolean)
932
933 (defcustom org-return-follows-link nil
934 "Non-nil means, on links RET will follow the link.
935 Needs to be set before org.el is loaded."
936 :group 'org-link-follow
937 :type 'boolean)
938
939 (defcustom org-mouse-1-follows-link t
940 "Non-nil means, mouse-1 on a link will follow the link.
941 A longer mouse click will still set point. Does not wortk on XEmacs.
942 Needs to be set before org.el is loaded."
943 :group 'org-link-follow
944 :type 'boolean)
945
946 (defcustom org-mark-ring-length 4
947 "Number of different positions to be recorded in the ring
948 Changing this requires a restart of Emacs to work correctly."
949 :group 'org-link-follow
950 :type 'interger)
951
952 (defcustom org-link-frame-setup
953 '((vm . vm-visit-folder-other-frame)
954 (gnus . gnus-other-frame)
955 (file . find-file-other-window))
956 "Setup the frame configuration for following links.
957 When following a link with Emacs, it may often be useful to display
958 this link in another window or frame. This variable can be used to
959 set this up for the different types of links.
960 For VM, use any of
961 `vm-visit-folder'
962 `vm-visit-folder-other-frame'
963 For Gnus, use any of
964 `gnus'
965 `gnus-other-frame'
966 For FILE, use any of
967 `find-file'
968 `find-file-other-window'
969 `find-file-other-frame'
970 For the calendar, use the variable `calendar-setup'.
971 For BBDB, it is currently only possible to display the matches in
972 another window."
973 :group 'org-link-follow
974 :type '(list
975 (cons (const vm)
976 (choice
977 (const vm-visit-folder)
978 (const vm-visit-folder-other-window)
979 (const vm-visit-folder-other-frame)))
980 (cons (const gnus)
981 (choice
982 (const gnus)
983 (const gnus-other-frame)))
984 (cons (const file)
985 (choice
986 (const find-file)
987 (const find-file-other-window)
988 (const find-file-other-frame)))))
989
990 (defcustom org-open-non-existing-files nil
991 "Non-nil means, `org-open-file' will open non-existing file.
992 When nil, an error will be generated."
993 :group 'org-link-follow
994 :type 'boolean)
995
996 (defcustom org-confirm-shell-link-function 'yes-or-no-p
997 "Non-nil means, ask for confirmation before executing shell links.
998 Shell links can be dangerous, just thing about a link
999
1000 [[shell:rm -rf ~/*][Google Search]]
1001
1002 This link would show up in your Org-mode document as \"Google Search\"
1003 but really it would remove your entire home directory.
1004 Therefore I *definitely* advise against setting this variable to nil.
1005 Just change it to `y-or-n-p' of you want to confirm with a single key press
1006 rather than having to type \"yes\"."
1007 :group 'org-link-follow
1008 :type '(choice
1009 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1010 (const :tag "with y-or-n (faster)" y-or-n-p)
1011 (const :tag "no confirmation (dangerous)" nil)))
1012
1013 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1014 "Non-nil means, ask for confirmation before executing elisp links.
1015 Elisp links can be dangerous, just thing about a link
1016
1017 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1018
1019 This link would show up in your Org-mode document as \"Google Search\"
1020 but really it would remove your entire home directory.
1021 Therefore I *definitely* advise against setting this variable to nil.
1022 Just change it to `y-or-n-p' of you want to confirm with a single key press
1023 rather than having to type \"yes\"."
1024 :group 'org-link-follow
1025 :type '(choice
1026 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1027 (const :tag "with y-or-n (faster)" y-or-n-p)
1028 (const :tag "no confirmation (dangerous)" nil)))
1029
1030 (defconst org-file-apps-defaults-gnu
1031 '((t . mailcap))
1032 "Default file applications on a UNIX or GNU/Linux system.
1033 See `org-file-apps'.")
1034
1035 (defconst org-file-apps-defaults-macosx
1036 '((t . "open %s")
1037 ("ps" . "gv %s")
1038 ("ps.gz" . "gv %s")
1039 ("eps" . "gv %s")
1040 ("eps.gz" . "gv %s")
1041 ("dvi" . "xdvi %s")
1042 ("fig" . "xfig %s"))
1043 "Default file applications on a MacOS X system.
1044 The system \"open\" is known as a default, but we use X11 applications
1045 for some files for which the OS does not have a good default.
1046 See `org-file-apps'.")
1047
1048 (defconst org-file-apps-defaults-windowsnt
1049 (list (cons t
1050 (list (if (featurep 'xemacs)
1051 'mswindows-shell-execute
1052 'w32-shell-execute)
1053 "open" 'file)))
1054 "Default file applications on a Windows NT system.
1055 The system \"open\" is used for most files.
1056 See `org-file-apps'.")
1057
1058 (defcustom org-file-apps
1059 '(
1060 ("txt" . emacs)
1061 ("tex" . emacs)
1062 ("ltx" . emacs)
1063 ("org" . emacs)
1064 ("el" . emacs)
1065 ("bib" . emacs)
1066 )
1067 "External applications for opening `file:path' items in a document.
1068 Org-mode uses system defaults for different file types, but
1069 you can use this variable to set the application for a given file
1070 extension. The entries in this list are cons cells where the car identifies
1071 files and the cdr the corresponding command. Possible values for the
1072 file identifier are
1073 \"ext\" A string identifying an extension
1074 `directory' Matches a directory
1075 t Default for all remaining files
1076
1077 Possible values for the command are:
1078 `emacs' The file will be visited by the current Emacs process.
1079 `default' Use the default application for this file type.
1080 string A command to be executed by a shell; %s will be replaced
1081 by the path to the file.
1082 sexp A Lisp form which will be evaluated. The file path will
1083 be available in the Lisp variable `file'.
1084 For more examples, see the system specific constants
1085 `org-file-apps-defaults-macosx'
1086 `org-file-apps-defaults-windowsnt'
1087 `org-file-apps-defaults-gnu'."
1088 :group 'org-link-follow
1089 :type '(repeat
1090 (cons (choice :value ""
1091 (string :tag "Extension")
1092 (const :tag "Default for unrecognized files" t)
1093 (const :tag "Links to a directory" directory))
1094 (choice :value ""
1095 (const :tag "Visit with Emacs" emacs)
1096 (const :tag "Use system default" default)
1097 (string :tag "Command")
1098 (sexp :tag "Lisp form")))))
1099
1100 (defcustom org-mhe-search-all-folders nil
1101 "Non-nil means, that the search for the mh-message will be extended to
1102 all folders if the message cannot be found in the folder given in the link.
1103 Searching all folders is very effective with one of the search engines
1104 supported by MH-E, but will be slow with pick."
1105 :group 'org-link-follow
1106 :type 'boolean)
1107
1108 (defgroup org-remember nil
1109 "Options concerning interaction with remember.el."
1110 :tag "Org Remember"
1111 :group 'org)
1112
1113 (defcustom org-directory "~/org"
1114 "Directory with org files.
1115 This directory will be used as default to prompt for org files.
1116 Used by the hooks for remember.el."
1117 :group 'org-remember
1118 :type 'directory)
1119
1120 (defcustom org-default-notes-file "~/.notes"
1121 "Default target for storing notes.
1122 Used by the hooks for remember.el. This can be a string, or nil to mean
1123 the value of `remember-data-file'."
1124 :group 'org-remember
1125 :type '(choice
1126 (const :tag "Default from remember-data-file" nil)
1127 file))
1128
1129 (defcustom org-remember-templates nil
1130 "Templates for the creation of remember buffers.
1131 When nil, just let remember make the buffer.
1132 When not nil, this is a list of 3-element lists. In each entry, the first
1133 element is a character, a unique key to select this template.
1134 The second element is the template. The third element is optional and can
1135 specify a destination file for remember items created with this template.
1136 The default file is given by `org-default-notes-file'.
1137
1138 The template specifies the structure of the remember buffer. It should have
1139 a first line starting with a star, to act as the org-mode headline.
1140 Furthermore, the following %-escapes will be replaced with content:
1141 %t time stamp, date only
1142 %T time stamp with date and time
1143 %u inactive time stamp, date only
1144 %U inactive time stamp with date and time
1145 %n user name
1146 %a annotation, normally the link created with org-store-link
1147 %i initial content, the region when remember is called with C-u.
1148 If %i is indented, the entire inserted text will be indented as well.
1149 %? This will be removed, and the cursor placed at this position."
1150 :group 'org-remember
1151 :type '(repeat :tag "enabled"
1152 (list :value (?a "\n" nil)
1153 (character :tag "Selection Key")
1154 (string :tag "Template")
1155 (file :tag "Destination file (optional)"))))
1156
1157 (defcustom org-reverse-note-order nil
1158 "Non-nil means, store new notes at the beginning of a file or entry.
1159 When nil, new notes will be filed to the end of a file or entry."
1160 :group 'org-remember
1161 :type '(choice
1162 (const :tag "Reverse always" t)
1163 (const :tag "Reverse never" nil)
1164 (repeat :tag "By file name regexp"
1165 (cons regexp boolean))))
1166
1167 (defgroup org-todo nil
1168 "Options concerning TODO items in Org-mode."
1169 :tag "Org TODO"
1170 :group 'org)
1171
1172 (defcustom org-todo-keywords '("TODO" "DONE")
1173 "List of TODO entry keywords.
1174 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1175 considered to mean that the entry is \"done\". All the other mean that
1176 action is required, and will make the entry show up in todo lists, diaries
1177 etc.
1178 The command \\[org-todo] cycles an entry through these states, and an
1179 additional state where no keyword is present. For details about this
1180 cycling, see also the variable `org-todo-interpretation'
1181 Changes become only effective after restarting Emacs."
1182 :group 'org-todo
1183 :group 'org-keywords
1184 :type '(repeat (string :tag "Keyword")))
1185
1186 (defcustom org-todo-interpretation 'sequence
1187 "Controls how TODO keywords are interpreted.
1188 This variable is only relevant if `org-todo-keywords' contains more than two
1189 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1190
1191 When `sequence', \\[org-todo] will always switch to the next state in the
1192 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1193 to state when executed several times in direct succession. Otherwise, it
1194 switches directly to DONE from any state.
1195 See the manual for more information."
1196 :group 'org-todo
1197 :group 'org-keywords
1198 :type '(choice (const sequence)
1199 (const type)))
1200
1201 (defcustom org-after-todo-state-change-hook nil
1202 "Hook which is run after the state of a TODO item was changed.
1203 The new state (a string with a TODO keyword, or nil) is available in the
1204 Lisp variable `state'."
1205 :group 'org-todo
1206 :type 'hook)
1207
1208 (defcustom org-log-done nil
1209 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1210 When the state of an entry is changed from nothing to TODO, remove a previous
1211 closing date.
1212 This can also be configured on a per-file basis by adding one of
1213 the following lines anywhere in the buffer:
1214
1215 #+STARTUP: logging
1216 #+STARTUP: nologging"
1217 :group 'org-todo
1218 :type 'boolean)
1219
1220 (defgroup org-priorities nil
1221 "Priorities in Org-mode."
1222 :tag "Org Priorities"
1223 :group 'org-todo)
1224
1225 (defcustom org-default-priority ?B
1226 "The default priority of TODO items.
1227 This is the priority an item get if no explicit priority is given."
1228 :group 'org-priorities
1229 :type 'character)
1230
1231 (defcustom org-lowest-priority ?C
1232 "The lowest priority of TODO items. A character like ?A, ?B etc."
1233 :group 'org-priorities
1234 :type 'character)
1235
1236 (defgroup org-time nil
1237 "Options concerning time stamps and deadlines in Org-mode."
1238 :tag "Org Time"
1239 :group 'org)
1240
1241 (defcustom org-insert-labeled-timestamps-at-point nil
1242 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1243 When nil, these labeled time stamps are forces into the second line of an
1244 entry, just after the headline. When scheduling from the global TODO list,
1245 the time stamp will always be forced into the second line."
1246 :group 'org-time
1247 :type 'boolean)
1248
1249 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1250 "Formats for `format-time-string' which are used for time stamps.
1251 It is not recommended to change this constant.")
1252
1253 (defcustom org-time-stamp-rounding-minutes 0
1254 "Number of minutes to round time stamps to upon insertion.
1255 When zero, insert the time unmodified. Useful rounding numbers
1256 should be factors of 60, so for example 5, 10, 15.
1257 When this is not zero, you can still force an exact time-stamp by using
1258 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1259 :group 'org-time
1260 :type 'integer)
1261
1262 (defcustom org-deadline-warning-days 30
1263 "No. of days before expiration during which a deadline becomes active.
1264 This variable governs the display in the org file."
1265 :group 'org-time
1266 :type 'number)
1267
1268 (defcustom org-popup-calendar-for-date-prompt t
1269 "Non-nil means, pop up a calendar when prompting for a date.
1270 In the calendar, the date can be selected with mouse-1. However, the
1271 minibuffer will also be active, and you can simply enter the date as well.
1272 When nil, only the minibuffer will be available."
1273 :group 'org-time
1274 :type 'boolean)
1275
1276 (defcustom org-calendar-follow-timestamp-change t
1277 "Non-nil means, make the calendar window follow timestamp changes.
1278 When a timestamp is modified and the calendar window is visible, it will be
1279 moved to the new date."
1280 :group 'org-time
1281 :type 'boolean)
1282
1283 (defgroup org-tags nil
1284 "Options concerning tags in Org-mode."
1285 :tag "Org Tags"
1286 :group 'org)
1287
1288 (defcustom org-tag-alist nil
1289 "List of tags allowed in Org-mode files.
1290 When this list is nil, Org-mode will base TAG input on what is already in the
1291 buffer.
1292 The value of this variable is an alist, the car may be (and should) be a
1293 character that is used to select that tag through the fast-tag-selection
1294 interface. See the manual for details."
1295 :group 'org-tags
1296 :type '(repeat
1297 (choice
1298 (cons (string :tag "Tag name")
1299 (character :tag "Access char"))
1300 (const :tag "Start radio group" (:startgroup))
1301 (const :tag "End radio group" (:endgroup)))))
1302
1303 (defcustom org-use-fast-tag-selection 'auto
1304 "Non-nil means, use fast tag selection scheme.
1305 This is a special interface to select and deselect tags with single keys.
1306 When nil, fast selection is never used.
1307 When the symbol `auto', fast selection is used if and only if selection
1308 characters for tags have been configured, either through the variable
1309 `org-tag-alist' or through a #+TAGS line in the buffer.
1310 When t, fast selection is always used and selection keys are assigned
1311 automatically if necessary."
1312 :group 'org-tags
1313 :type '(choice
1314 (const :tag "Always" t)
1315 (const :tag "Never" nil)
1316 (const :tag "When selection characters are configured" 'auto)))
1317
1318 (defcustom org-tags-column 48
1319 "The column to which tags should be indented in a headline.
1320 If this number is positive, it specifies the column. If it is negative,
1321 it means that the tags should be flushright to that column. For example,
1322 -79 works well for a normal 80 character screen."
1323 :group 'org-tags
1324 :type 'integer)
1325
1326 (defcustom org-auto-align-tags t
1327 "Non-nil means, realign tags after pro/demotion of TODO state change.
1328 These operations change the length of a headline and therefore shift
1329 the tags around. With this options turned on, after each such operation
1330 the tags are again aligned to `org-tags-column'."
1331 :group 'org-tags
1332 :type 'boolean)
1333
1334 (defcustom org-use-tag-inheritance t
1335 "Non-nil means, tags in levels apply also for sublevels.
1336 When nil, only the tags directly given in a specific line apply there.
1337 If you turn off this option, you very likely want to turn on the
1338 companion option `org-tags-match-list-sublevels'."
1339 :group 'org-tags
1340 :type 'boolean)
1341
1342 (defcustom org-tags-match-list-sublevels nil
1343 "Non-nil means list also sublevels of headlines matching tag search.
1344 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1345 the sublevels of a headline matching a tag search often also match
1346 the same search. Listing all of them can create very long lists.
1347 Setting this variable to nil causes subtrees of a match to be skipped.
1348 This option is off by default, because inheritance in on. If you turn
1349 inheritance off, you very likely want to turn this option on.
1350
1351 As a special case, if the tag search is restricted to TODO items, the
1352 value of this variable is ignored and sublevels are always checked, to
1353 make sure all corresponding TODO items find their way into the list."
1354 :group 'org-tags
1355 :type 'boolean)
1356
1357 (defvar org-tags-history nil
1358 "History of minibuffer reads for tags.")
1359 (defvar org-last-tags-completion-table nil
1360 "The last used completion table for tags.")
1361
1362 (defgroup org-agenda nil
1363 "Options concerning agenda display Org-mode."
1364 :tag "Org Agenda"
1365 :group 'org)
1366
1367 (defvar org-category nil
1368 "Variable used by org files to set a category for agenda display.
1369 Such files should use a file variable to set it, for example
1370
1371 -*- mode: org; org-category: \"ELisp\"
1372
1373 or contain a special line
1374
1375 #+CATEGORY: ELisp
1376
1377 If the file does not specify a category, then file's base name
1378 is used instead.")
1379 (make-variable-buffer-local 'org-category)
1380
1381 (defcustom org-agenda-files nil
1382 "The files to be used for agenda display.
1383 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1384 \\[org-remove-file]. You can also use customize to edit the list.
1385
1386 If the value of the variable is not a list but a single file name, then
1387 the list of agenda files is actually stored and maintained in that file, one
1388 agenda file per line."
1389 :group 'org-agenda
1390 :type '(choice
1391 (repeat :tag "List of files" file)
1392 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1393
1394 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1395 "Custom commands for the agenda.
1396 These commands will be offered on the splash screen displayed by the
1397 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1398
1399 key The key (a single char as a string) to be associated with the command.
1400 type The command type, any of the following symbols:
1401 todo Entries with a specific TODO keyword, in all agenda files.
1402 tags Tags match in all agenda files.
1403 tags-todo Tags match in all agenda files, TODO entries only.
1404 todo-tree Sparse tree of specific TODO keyword in *current* file.
1405 tags-tree Sparse tree with all tags matches in *current* file.
1406 occur-tree Occur sparse tree for current file.
1407 match What to search for:
1408 - a single keyword for TODO keyword searches
1409 - a tags match expression for tags searches
1410 - a regular expression for occur searches"
1411 :group 'org-agenda
1412 :type '(repeat
1413 (list (string :tag "Key")
1414 (choice :tag "Type"
1415 (const :tag "Tags search in all agenda files" tags)
1416 (const :tag "Tags search of TODO entries, all agenda files" tags-todo)
1417 (const :tag "TODO keyword search in all agenda files" todo)
1418 (const :tag "Tags sparse tree in current buffer" tags-tree)
1419 (const :tag "TODO keyword tree in current buffer" todo-tree)
1420 (const :tag "Occur tree in current buffer" occur-tree))
1421 (string :tag "Match"))))
1422
1423 (defcustom org-agenda-todo-list-sublevels t
1424 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1425 When nil, the sublevels of a TODO entry are not checked, resulting in
1426 potentially much shorter TODO lists."
1427 :group 'org-agenda
1428 :group 'org-todo
1429 :type 'boolean)
1430
1431 (defcustom org-agenda-todo-ignore-scheduled nil
1432 "Non-nil means, don't show scheduled entries in the global todo list.
1433 The idea behind this is that by scheduling it, you have already taken care
1434 of this item."
1435 :group 'org-agenda
1436 :group 'org-todo
1437 :type 'boolean)
1438
1439 (defcustom org-agenda-include-all-todo nil
1440 "Non-nil means, the agenda will always contain all TODO entries.
1441 When nil, date-less entries will only be shown if `org-agenda' is called
1442 with a prefix argument.
1443 When non-nil, the TODO entries will be listed at the top of the agenda, before
1444 the entries for specific days."
1445 :group 'org-agenda
1446 :type 'boolean)
1447
1448 (defcustom org-agenda-include-diary nil
1449 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1450 :group 'org-agenda
1451 :type 'boolean)
1452
1453 (defcustom org-calendar-to-agenda-key [?c]
1454 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1455 The command `org-calendar-goto-agenda' will be bound to this key. The
1456 default is the character `c' because then `c' can be used to switch back and
1457 forth between agenda and calendar."
1458 :group 'org-agenda
1459 :type 'sexp)
1460
1461 (defgroup org-agenda-setup nil
1462 "Options concerning setting up the Agenda window in Org Mode."
1463 :tag "Org Agenda Window Setup"
1464 :group 'org-agenda)
1465
1466 (defcustom org-agenda-mouse-1-follows-link nil
1467 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1468 A longer mouse click will still set point. Does not wortk on XEmacs.
1469 Needs to be set before org.el is loaded."
1470 :group 'org-agenda-setup
1471 :type 'boolean)
1472
1473 (defcustom org-agenda-start-with-follow-mode nil
1474 "The initial value of follwo-mode in a newly created agenda window."
1475 :group 'org-agenda-setup
1476 :type 'boolean)
1477
1478 (defcustom org-select-agenda-window t
1479 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1480 When nil, cursor will remain in the current window."
1481 :group 'org-agenda-setup
1482 :type 'boolean)
1483
1484 (defcustom org-fit-agenda-window t
1485 "Non-nil means, change window size of agenda to fit content."
1486 :group 'org-agenda-setup
1487 :type 'boolean)
1488
1489 (defgroup org-agenda-display nil
1490 "Options concerning what to display initially in Agenda."
1491 :tag "Org Agenda Display"
1492 :group 'org-agenda)
1493
1494 (defcustom org-agenda-show-all-dates t
1495 "Non-nil means, `org-agenda' shows every day in the selected range.
1496 When nil, only the days which actually have entries are shown."
1497 :group 'org-agenda-display
1498 :type 'boolean)
1499
1500 (defcustom org-agenda-start-on-weekday 1
1501 "Non-nil means, start the overview always on the specified weekday.
1502 0 denotes Sunday, 1 denotes Monday etc.
1503 When nil, always start on the current day."
1504 :group 'org-agenda-display
1505 :type '(choice (const :tag "Today" nil)
1506 (number :tag "Weekday No.")))
1507
1508 (defcustom org-agenda-ndays 7
1509 "Number of days to include in overview display.
1510 Should be 1 or 7."
1511 :group 'org-agenda-display
1512 :type 'number)
1513
1514 (defcustom org-agenda-use-time-grid t
1515 "Non-nil means, show a time grid in the agenda schedule.
1516 A time grid is a set of lines for specific times (like every two hours between
1517 8:00 and 20:00). The items scheduled for a day at specific times are
1518 sorted in between these lines.
1519 For details about when the grid will be shown, and what it will look like, see
1520 the variable `org-agenda-time-grid'."
1521 :group 'org-agenda-display
1522 :type 'boolean)
1523
1524 (defcustom org-agenda-time-grid
1525 '((daily today require-timed)
1526 "----------------"
1527 (800 1000 1200 1400 1600 1800 2000))
1528
1529 "The settings for time grid for agenda display.
1530 This is a list of three items. The first item is again a list. It contains
1531 symbols specifying conditions when the grid should be displayed:
1532
1533 daily if the agenda shows a single day
1534 weekly if the agenda shows an entire week
1535 today show grid on current date, independent of daily/weekly display
1536 require-timed show grid only if at least on item has a time specification
1537
1538 The second item is a string which will be places behing the grid time.
1539
1540 The third item is a list of integers, indicating the times that should have
1541 a grid line."
1542 :group 'org-agenda-display
1543 :type
1544 '(list
1545 (set :greedy t :tag "Grid Display Options"
1546 (const :tag "Show grid in single day agenda display" daily)
1547 (const :tag "Show grid in weekly agenda display" weekly)
1548 (const :tag "Always show grid for today" today)
1549 (const :tag "Show grid only if any timed entries are present"
1550 require-timed)
1551 (const :tag "Skip grid times already present in an entry"
1552 remove-match))
1553 (string :tag "Grid String")
1554 (repeat :tag "Grid Times" (integer :tag "Time"))))
1555
1556 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1557 "Sorting structure for the agenda items of a single day.
1558 This is a list of symbols which will be used in sequence to determine
1559 if an entry should be listed before another entry. The following
1560 symbols are recognized:
1561
1562 time-up Put entries with time-of-day indications first, early first
1563 time-down Put entries with time-of-day indications first, late first
1564 category-keep Keep the default order of categories, corresponding to the
1565 sequence in `org-agenda-files'.
1566 category-up Sort alphabetically by category, A-Z.
1567 category-down Sort alphabetically by category, Z-A.
1568 priority-up Sort numerically by priority, high priority last.
1569 priority-down Sort numerically by priority, high priority first.
1570
1571 The different possibilities will be tried in sequence, and testing stops
1572 if one comparison returns a \"not-equal\". For example, the default
1573 '(time-up category-keep priority-down)
1574 means: Pull out all entries having a specified time of day and sort them,
1575 in order to make a time schedule for the current day the first thing in the
1576 agenda listing for the day. Of the entries without a time indication, keep
1577 the grouped in categories, don't sort the categories, but keep them in
1578 the sequence given in `org-agenda-files'. Within each category sort by
1579 priority.
1580
1581 Leaving out `category-keep' would mean that items will be sorted across
1582 categories by priority."
1583 :group 'org-agenda-display
1584 :type '(repeat
1585 (choice
1586 (const time-up)
1587 (const time-down)
1588 (const category-keep)
1589 (const category-up)
1590 (const category-down)
1591 (const priority-up)
1592 (const priority-down))))
1593
1594 (defcustom org-sort-agenda-notime-is-late t
1595 "Non-nil means, items without time are considered late.
1596 This is only relevant for sorting. When t, items which have no explicit
1597 time like 15:30 will be considered as 99:01, i.e. later than any items which
1598 do have a time. When nil, the default time is before 0:00. You can use this
1599 option to decide if the schedule for today should come before or after timeless
1600 agenda entries."
1601 :group 'org-agenda-display
1602 :type 'boolean)
1603
1604
1605 (defgroup org-agenda-prefix nil
1606 "Options concerning the entry prefix in the Org-mode agenda display."
1607 :tag "Org Agenda Prefix"
1608 :group 'org-agenda)
1609
1610 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1611 "Format specification for the prefix of items in the agenda buffer.
1612 This format works similar to a printf format, with the following meaning:
1613
1614 %c the category of the item, \"Diary\" for entries from the diary, or
1615 as given by the CATEGORY keyword or derived from the file name.
1616 %T the first tag of the item.
1617 %t the time-of-day specification if one applies to the entry, in the
1618 format HH:MM
1619 %s Scheduling/Deadline information, a short string
1620
1621 All specifiers work basically like the standard `%s' of printf, but may
1622 contain two additional characters: A question mark just after the `%' and
1623 a whitespace/punctuation character just before the final letter.
1624
1625 If the first character after `%' is a question mark, the entire field
1626 will only be included if the corresponding value applies to the
1627 current entry. This is useful for fields which should have fixed
1628 width when present, but zero width when absent. For example,
1629 \"%?-12t\" will result in a 12 character time field if a time of the
1630 day is specified, but will completely disappear in entries which do
1631 not contain a time.
1632
1633 If there is punctuation or whitespace character just before the final
1634 format letter, this character will be appended to the field value if
1635 the value is not empty. For example, the format \"%-12:c\" leads to
1636 \"Diary: \" if the category is \"Diary\". If the category were be
1637 empty, no additional colon would be interted.
1638
1639 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1640 - Indent the line with two space characters
1641 - Give the category in a 12 chars wide field, padded with whitespace on
1642 the right (because of `-'). Append a colon if there is a category
1643 (because of `:').
1644 - If there is a time-of-day, put it into a 12 chars wide field. If no
1645 time, don't put in an empty field, just skip it (because of '?').
1646 - Finally, put the scheduling information and append a whitespace.
1647
1648 As another example, if you don't want the time-of-day of entries in
1649 the prefix, you could use:
1650
1651 (setq org-agenda-prefix-format \" %-11:c% s\")
1652
1653 See also the variables `org-agenda-remove-times-when-in-prefix' and
1654 `org-agenda-remove-tags-when-in-prefix'."
1655 :type 'string
1656 :group 'org-agenda-prefix)
1657
1658 (defvar org-prefix-format-compiled nil
1659 "The compiled version of the most recently used prefix format.
1660 Depending on which command was used last, this may be the compiled version
1661 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1662
1663 (defcustom org-agenda-remove-times-when-in-prefix t
1664 "Non-nil means, remove duplicate time specifications in agenda items.
1665 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1666 time-of-day specification in a headline or diary entry is extracted and
1667 placed into the prefix. If this option is non-nil, the original specification
1668 \(a timestamp or -range, or just a plain time(range) specification like
1669 11:30-4pm) will be removed for agenda display. This makes the agenda less
1670 cluttered.
1671 The option can be t or nil. It may also be the symbol `beg', indicating
1672 that the time should only be removed what it is located at the beginning of
1673 the headline/diary entry."
1674 :group 'org-agenda-prefix
1675 :type '(choice
1676 (const :tag "Always" t)
1677 (const :tag "Never" nil)
1678 (const :tag "When at beginning of entry" beg)))
1679
1680 (defcustom org-agenda-remove-tags-when-in-prefix nil
1681 "Non-nil means, remove the tags from the headline copy in the agenda.
1682 When this is the symbol `prefix', only remove tags when
1683 `org-agenda-prefix-format' contains a `%T' specifier."
1684 :group 'org-agenda-prefix
1685 :type '(choice
1686 (const :tag "Always" t)
1687 (const :tag "Never" nil)
1688 (const :tag "When prefix format contains %T" prefix)))
1689
1690 (defgroup org-agenda-timeline nil
1691 "Options concerning the timeline buffer in Org Mode."
1692 :tag "Org Agenda Timeline"
1693 :group 'org-agenda)
1694
1695 (defcustom org-timeline-prefix-format " % s"
1696 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1697 :type 'string
1698 :group 'org-agenda-timeline)
1699
1700 (defcustom org-select-timeline-window t
1701 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1702 When nil, cursor will remain in the current window."
1703 :group 'org-agenda-timeline
1704 :type 'boolean)
1705
1706 (defcustom org-timeline-show-empty-dates 3
1707 "Non-nil means, `org-timeline' also shows dates without an entry.
1708 When nil, only the days which actually have entries are shown.
1709 When t, all days between the first and the last date are shown.
1710 When an integer, show also empty dates, but if there is a gap of more than
1711 N days, just insert a special line indicating the size of the gap."
1712 :group 'org-agenda-timeline
1713 :type '(choice
1714 (const :tag "None" nil)
1715 (const :tag "All" t)
1716 (number :tag "at most")))
1717
1718 (defgroup org-export nil
1719 "Options for exporting org-listings."
1720 :tag "Org Export"
1721 :group 'org)
1722
1723 (defgroup org-export-general nil
1724 "General options for exporting Org-mode files."
1725 :tag "Org Export General"
1726 :group 'org-export)
1727
1728 (defcustom org-export-publishing-directory "."
1729 "Path to the location where exported files should be located.
1730 This path may be relative to the directory where the Org-mode file lives.
1731 The default is to put them into the same directory as the Org-mode file.
1732 The variable may also be an alist with export types `:html', `:ascii',
1733 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1734 is relative, it is interpreted relative to the directory where the exported
1735 Org-mode files lives."
1736 :group 'org-export-general
1737 :type '(choice
1738 (directory)
1739 (repeat
1740 (cons
1741 (choice :tag "Type"
1742 (const :html) (const :ascii) (const :ical) (const :xoxo))
1743 (directory)))))
1744
1745 (defcustom org-export-language-setup
1746 '(("en" "Author" "Date" "Table of Contents")
1747 ("da" "Ophavsmand" "Dato" "Indhold")
1748 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1749 ("es" "Autor" "Fecha" "\xccndice")
1750 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1751 ("it" "Autore" "Data" "Indice")
1752 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1753 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1754 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1755 "Terms used in export text, translated to different languages.
1756 Use the variable `org-export-default-language' to set the language,
1757 or use the +OPTION lines for a per-file setting."
1758 :group 'org-export-general
1759 :type '(repeat
1760 (list
1761 (string :tag "HTML language tag")
1762 (string :tag "Author")
1763 (string :tag "Date")
1764 (string :tag "Table of Contents"))))
1765
1766 (defcustom org-export-default-language "en"
1767 "The default language of HTML export, as a string.
1768 This should have an association in `org-export-language-setup'."
1769 :group 'org-export-general
1770 :type 'string)
1771
1772 (defcustom org-export-headline-levels 3
1773 "The last level which is still exported as a headline.
1774 Inferior levels will produce itemize lists when exported.
1775 Note that a numeric prefix argument to an exporter function overrides
1776 this setting.
1777
1778 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1779 :group 'org-export-general
1780 :type 'number)
1781
1782 (defcustom org-export-with-section-numbers t
1783 "Non-nil means, add section numbers to headlines when exporting.
1784
1785 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1786 :group 'org-export-general
1787 :type 'boolean)
1788
1789 (defcustom org-export-with-toc t
1790 "Non-nil means, create a table of contents in exported files.
1791 The TOC contains headlines with levels up to`org-export-headline-levels'.
1792
1793 Headlines which contain any TODO items will be marked with \"(*)\" in
1794 ASCII export, and with red color in HTML output.
1795
1796 In HTML output, the TOC will be clickable.
1797
1798 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1799 :group 'org-export-general
1800 :type 'boolean)
1801
1802 (defcustom org-export-mark-todo-in-toc nil
1803 "Non-nil means, mark TOC lines that contain any open TODO items."
1804 :group 'org-export-general
1805 :type 'boolean)
1806
1807 (defcustom org-export-preserve-breaks nil
1808 "Non-nil means, preserve all line breaks when exporting.
1809 Normally, in HTML output paragraphs will be reformatted. In ASCII
1810 export, line breaks will always be preserved, regardless of this variable.
1811
1812 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1813 :group 'org-export-general
1814 :type 'boolean)
1815
1816 (defcustom org-export-with-timestamps t
1817 "Nil means, do not export time stamps and associated keywords."
1818 :group 'org-export
1819 :type 'boolean)
1820
1821 (defcustom org-export-with-tags t
1822 "Nil means, do not export tags, just remove them from headlines."
1823 :group 'org-export-general
1824 :type 'boolean)
1825
1826 (defcustom org-export-with-timestamps t
1827 "Nil means, do not export timestamps and associated keywords."
1828 :group 'org-export-general
1829 :type 'boolean)
1830
1831 (defgroup org-export-translation nil
1832 "Options for translating special ascii sequences for the export backends."
1833 :tag "Org Export Translation"
1834 :group 'org-export)
1835
1836 (defcustom org-export-with-emphasize t
1837 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1838 If the export target supports emphasizing text, the word will be
1839 typeset in bold, italic, or underlined, respectively. Works only for
1840 single words, but you can say: I *really* *mean* *this*.
1841 Not all export backends support this.
1842
1843 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1844 :group 'org-export-translation
1845 :type 'boolean)
1846
1847 (defcustom org-export-with-sub-superscripts t
1848 "Non-nil means, interpret \"_\" and \"^\" for export.
1849 When this option is turned on, you can use TeX-like syntax for sub- and
1850 superscripts. Several characters after \"_\" or \"^\" will be
1851 considered as a single item - so grouping with {} is normally not
1852 needed. For example, the following things will be parsed as single
1853 sub- or superscripts.
1854
1855 10^24 or 10^tau several digits will be considered 1 item.
1856 10^-12 or 10^-tau a leading sign with digits or a word
1857 x^2-y^3 will be read as x^2 - y^3, because items are
1858 terminated by almost any nonword/nondigit char.
1859 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1860
1861 Still, ambiguity is possible - so when in doubt use {} to enclose the
1862 sub/superscript.
1863 Not all export backends support this, but HTML does.
1864
1865 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1866 :group 'org-export-translation
1867 :type 'boolean)
1868
1869 (defcustom org-export-with-TeX-macros t
1870 "Non-nil means, interpret simple TeX-like macros when exporting.
1871 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1872 No only real TeX macros will work here, but the standard HTML entities
1873 for math can be used as macro names as well. For a list of supported
1874 names in HTML export, see the constant `org-html-entities'.
1875 Not all export backends support this.
1876
1877 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1878 :group 'org-export-translation
1879 :type 'boolean)
1880
1881 (defcustom org-export-with-fixed-width t
1882 "Non-nil means, lines starting with \":\" will be in fixed width font.
1883 This can be used to have pre-formatted text, fragments of code etc. For
1884 example:
1885 : ;; Some Lisp examples
1886 : (while (defc cnt)
1887 : (ding))
1888 will be looking just like this in also HTML. See also the QUOTE keyword.
1889 Not all export backends support this.
1890
1891 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1892 :group 'org-export-translation
1893 :type 'boolean)
1894
1895 (defcustom org-match-sexp-depth 3
1896 "Number of stacked braces for sub/superscript matching.
1897 This has to be set before loading org.el to be effective."
1898 :group 'org-export-translation
1899 :type 'integer)
1900
1901 (defgroup org-export-tables nil
1902 "Options for exporting tables in Org-mode."
1903 :tag "Org Export Tables"
1904 :group 'org-export)
1905
1906 (defcustom org-export-with-tables t
1907 "If non-nil, lines starting with \"|\" define a table.
1908 For example:
1909
1910 | Name | Address | Birthday |
1911 |-------------+----------+-----------|
1912 | Arthur Dent | England | 29.2.2100 |
1913
1914 Not all export backends support this.
1915
1916 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1917 :group 'org-export-tables
1918 :type 'boolean)
1919
1920 (defcustom org-export-highlight-first-table-line t
1921 "Non-nil means, highlight the first table line.
1922 In HTML export, this means use <th> instead of <td>.
1923 In tables created with table.el, this applies to the first table line.
1924 In Org-mode tables, all lines before the first horizontal separator
1925 line will be formatted with <th> tags."
1926 :group 'org-export-tables
1927 :type 'boolean)
1928
1929 (defcustom org-export-table-remove-special-lines t
1930 "Remove special lines and marking characters in calculating tables.
1931 This removes the special marking character column from tables that are set
1932 up for spreadsheet calculations. It also removes the entire lines
1933 marked with `!', `_', or `^'. The lines with `$' are kept, because
1934 the values of constants may be useful to have."
1935 :group 'org-export-tables
1936 :type 'boolean)
1937
1938 (defcustom org-export-prefer-native-exporter-for-tables nil
1939 "Non-nil means, always export tables created with table.el natively.
1940 Natively means, use the HTML code generator in table.el.
1941 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1942 the table does not use row- or column-spanning). This has the
1943 advantage, that the automatic HTML conversions for math symbols and
1944 sub/superscripts can be applied. Org-mode's HTML generator is also
1945 much faster."
1946 :group 'org-export-tables
1947 :type 'boolean)
1948
1949 (defgroup org-export-ascii nil
1950 "Options specific for ASCII export of Org-mode files."
1951 :tag "Org Export ASCII"
1952 :group 'org-export)
1953
1954 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
1955 "Characters for underlining headings in ASCII export.
1956 In the given sequence, these characters will be used for level 1, 2, ..."
1957 :group 'org-export-ascii
1958 :type '(repeat character))
1959
1960 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
1961 "Bullet characters for headlines converted to lists in ASCII export.
1962 The first character is is used for the first lest level generated in this
1963 way, and so on. If there are more levels than characters given here,
1964 the list will be repeated.
1965 Note that plain lists will keep the same bullets as the have in the
1966 Org-mode file."
1967 :group 'org-export-ascii
1968 :type '(repeat character))
1969
1970 (defcustom org-export-ascii-show-new-buffer t
1971 "Non-nil means, popup buffer containing the exported ASCII text.
1972 Otherwise the buffer will just be saved to a file and stay hidden."
1973 :group 'org-export-ascii
1974 :type 'boolean)
1975
1976 (defgroup org-export-xml nil
1977 "Options specific for XML export of Org-mode files."
1978 :tag "Org Export XML"
1979 :group 'org-export)
1980
1981 (defgroup org-export-html nil
1982 "Options specific for HTML export of Org-mode files."
1983 :tag "Org Export HTML"
1984 :group 'org-export)
1985
1986 (defcustom org-export-html-style
1987 "<style type=\"text/css\">
1988 html {
1989 font-family: Times, serif;
1990 font-size: 12pt;
1991 }
1992 .title { text-align: center; }
1993 .todo { color: red; }
1994 .done { color: green; }
1995 .timestamp { color: grey }
1996 .timestamp-kwd { color: CadetBlue }
1997 .tag { background-color:lightblue; font-weight:normal }
1998 .target { background-color: lavender; }
1999 pre {
2000 border: 1pt solid #AEBDCC;
2001 background-color: #F3F5F7;
2002 padding: 5pt;
2003 font-family: courier, monospace;
2004 }
2005 table { border-collapse: collapse; }
2006 td, th {
2007 vertical-align: top;
2008 border: 1pt solid #ADB9CC;
2009 }
2010 </style>"
2011 "The default style specification for exported HTML files.
2012 Since there are different ways of setting style information, this variable
2013 needs to contain the full HTML structure to provide a style, including the
2014 surrounding HTML tags. The style specifications should include definitions
2015 for new classes todo, done, title, and deadline. For example, legal values
2016 would be:
2017
2018 <style type=\"text/css\">
2019 p { font-weight: normal; color: gray; }
2020 h1 { color: black; }
2021 .title { text-align: center; }
2022 .todo, .deadline { color: red; }
2023 .done { color: green; }
2024 </style>
2025
2026 or, if you want to keep the style in a file,
2027
2028 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2029
2030 As the value of this option simply gets inserted into the HTML <head> header,
2031 you can \"misuse\" it to add arbitrary text to the header."
2032 :group 'org-export-html
2033 :type 'string)
2034
2035 (defcustom org-export-html-link-org-files-as-html t
2036 "Non-nil means, make file links to `file.org' point to `file.html'.
2037 When org-mode is exporting an org-mode file to HTML, links to
2038 non-html files are directly put into a href tag in HTML.
2039 However, links to other Org-mode files (recognized by the
2040 extension `.org.) should become links to the corresponding html
2041 file, assuming that the linked org-mode file will also be
2042 converted to HTML.
2043 When nil, the links still point to the plain `.org' file."
2044 :group 'org-export-html
2045 :type 'boolean)
2046
2047 (defcustom org-export-html-inline-images 'maybe
2048 "Non-nil means, inline images into exported HTML pages.
2049 This is done using an <img> tag. When nil, an anchor with href is used to
2050 link to the image. If this option is `maybe', then images in links with
2051 an empty description will be inlined, while images with a description will
2052 be linked only."
2053 :group 'org-export-html
2054 :type '(choice (const :tag "Never" nil)
2055 (const :tag "Always" t)
2056 (const :tag "When there is no description" maybe)))
2057
2058 (defcustom org-export-html-expand t
2059 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2060 When nil, these tags will be exported as plain text and therefore
2061 not be interpreted by a browser.
2062
2063 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2064 :group 'org-export-html
2065 :type 'boolean)
2066
2067 (defcustom org-export-html-table-tag
2068 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2069 "The HTML tag used to start a table.
2070 This must be a <table> tag, but you may change the options like
2071 borders and spacing."
2072 :group 'org-export-html
2073 :type 'string)
2074
2075 (defcustom org-export-html-with-timestamp nil
2076 "If non-nil, write `org-export-html-html-helper-timestamp'
2077 into the exported HTML text. Otherwise, the buffer will just be saved
2078 to a file."
2079 :group 'org-export-html
2080 :type 'boolean)
2081
2082 (defcustom org-export-html-html-helper-timestamp
2083 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2084 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2085 :group 'org-export-html
2086 :type 'string)
2087
2088 (defcustom org-export-html-show-new-buffer nil
2089 "Non-nil means, popup buffer containing the exported html text.
2090 Otherwise, the buffer will just be saved to a file and stay hidden."
2091 :group 'org-export-html
2092 :type 'boolean)
2093
2094 (defgroup org-export-icalendar nil
2095 "Options specific for iCalendar export of Org-mode files."
2096 :tag "Org Export iCalendar"
2097 :group 'org-export)
2098
2099 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2100 "The file name for the iCalendar file covering all agenda files.
2101 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2102 The file name should be absolute."
2103 :group 'org-export-icalendar
2104 :type 'file)
2105
2106 (defcustom org-icalendar-include-todo nil
2107 "Non-nil means, export to iCalendar files should also cover TODO items."
2108 :group 'org-export-icalendar
2109 :type 'boolean)
2110
2111 (defcustom org-icalendar-combined-name "OrgMode"
2112 "Calendar name for the combined iCalendar representing all agenda files."
2113 :group 'org-export-icalendar
2114 :type 'string)
2115
2116 (defgroup org-font-lock nil
2117 "Font-lock settings for highlighting in Org-mode."
2118 :tag "Org Font Lock"
2119 :group 'org)
2120
2121 (defcustom org-level-color-stars-only nil
2122 "Non-nil means fontify only the stars in each headline.
2123 When nil, the entire headline is fontified.
2124 Changing it requires restart of `font-lock-mode' to become effective
2125 also in regions already fontified."
2126 :group 'org-font-lock
2127 :type 'boolean)
2128
2129 (defcustom org-hide-leading-stars nil
2130 "Non-nil means, hide the first N-1 stars in a headline.
2131 This works by using the face `org-hide' for these stars. This
2132 face is white for a light background, and black for a dark
2133 background. You may have to customize the face `org-hide' to
2134 make this work.
2135 Changing it requires restart of `font-lock-mode' to become effective
2136 also in regions already fontified.
2137 You may also set this on a per-file basis by adding one of the following
2138 lines to the buffer:
2139
2140 #+STARTUP: hidestars
2141 #+STARTUP: showstars"
2142 :group 'org-font-lock
2143 :type 'boolean)
2144
2145 (defcustom org-fontify-done-headline nil
2146 "Non-nil means, change the face of a headline if it is marked DONE.
2147 Normally, only the TODO/DONE keyword indicates the state of a headline.
2148 When this is non-nil, the headline after the keyword is set to the
2149 `org-headline-done' as an additional indication."
2150 :group 'org-font-lock
2151 :type 'boolean)
2152
2153 (defcustom org-fontify-emphasized-text t
2154 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2155 Changing this variable requires a restart of Emacs to take effect."
2156 :group 'org-font-lock
2157 :type 'boolean)
2158
2159 (defvar org-emph-re nil
2160 "Regular expression for matching emphasis.")
2161 (defvar org-emphasis-regexp-components) ; defined just below
2162 (defvar org-emphasis-alist) ; defined just below
2163 (defun org-set-emph-re (var val)
2164 "Set variable and compute the emphasis regular expression."
2165 (set var val)
2166 (when (and (boundp 'org-emphasis-alist)
2167 (boundp 'org-emphasis-regexp-components)
2168 org-emphasis-alist org-emphasis-regexp-components)
2169 (let* ((e org-emphasis-regexp-components)
2170 (pre (car e))
2171 (post (nth 1 e))
2172 (border (nth 2 e))
2173 (body (nth 3 e))
2174 (nl (nth 4 e))
2175 (stacked (nth 5 e))
2176 (body1 (concat body "*?"))
2177 (markers (mapconcat 'car org-emphasis-alist "")))
2178 ;; make sure special characters appear at the right position in the class
2179 (if (string-match "\\^" markers)
2180 (setq markers (concat (replace-match "" t t markers) "^")))
2181 (if (string-match "-" markers)
2182 (setq markers (concat (replace-match "" t t markers) "-")))
2183 (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2184 ;; Make the regexp
2185 (setq org-emph-re
2186 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2187 "\\("
2188 "\\([" markers "]\\)"
2189 "\\("
2190 "[^" border markers "]"
2191 body1
2192 "[^" border markers "]"
2193 "\\)"
2194 "\\3\\)"
2195 "\\([" post (if stacked markers) "]\\|$\\)")))))
2196
2197 (defcustom org-emphasis-regexp-components
2198 '(" \t(" " \t.,?;:'\")" " \t\r\n,." "." 1 nil)
2199 "Components used to build the reqular expression for emphasis.
2200 This is a list with 6 entries. Terminology: In an emphasis string
2201 like \" *strong word* \", we call the initial space PREMATCH, the final
2202 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2203 and \"trong wor\" is the body. The different components in this variable
2204 specify what is allowed/forbidden in each part:
2205
2206 pre Chars allowed as prematch. Beginning of line will be allowed too.
2207 post Chars allowed as postmatch. End of line will be allowed too.
2208 border The chars *forbidden* as border characters. In addition to the
2209 characters given here, all marker characters are forbidden too.
2210 body-regexp A regexp like \".\" to match a body character. Don't use
2211 non-shy groups here, and don't allow newline here.
2212 newline The maximum number of newlines allowed in an emphasis exp.
2213 stacked Non-nil means, allow stacked styles. This works only in HTML
2214 export. When this is set, all marker characters (as given in
2215 `org-emphasis-alist') will be allowed as pre/post, aiding
2216 inside-out matching.
2217 Use customize to modify this, or restart emacs after changing it."
2218 :group 'org-font-lock
2219 :set 'org-set-emph-re
2220 :type '(list
2221 (sexp :tag "Allowed chars in pre ")
2222 (sexp :tag "Allowed chars in post ")
2223 (sexp :tag "Forbidden chars in border ")
2224 (sexp :tag "Regexp for body ")
2225 (integer :tag "number of newlines allowed")
2226 (boolean :tag "Stacking allowed ")))
2227
2228 (defcustom org-emphasis-alist
2229 '(("*" bold "<b>" "</b>")
2230 ("/" italic "<i>" "</i>")
2231 ("_" underline "<u>" "</u>")
2232 ("=" shadow "<code>" "</code>")
2233 ("+" (:strike-through t) "<del>" "</del>")
2234 )
2235 "Special syntax for emphasised text.
2236 Text starting and ending with a special character will be emphasized, for
2237 example *bold*, _underlined_ and /italic/. This variable sets the marker
2238 characters, the face to bbe used by font-lock for highlighting in Org-mode
2239 emacs buffers, and the HTML tags to be used for this.
2240 Use customize to modify this, or restart emacs after changing it."
2241 :group 'org-font-lock
2242 :set 'org-set-emph-re
2243 :type '(repeat
2244 (list
2245 (string :tag "Marker character")
2246 (choice
2247 (face :tag "Font-lock-face")
2248 (plist :tag "Face property list"))
2249 (string :tag "HTML start tag")
2250 (string :tag "HTML end tag"))))
2251
2252 (defgroup org-faces nil
2253 "Faces in Org-mode."
2254 :tag "Org Faces"
2255 :group 'org-font-lock)
2256
2257 (defun org-compatible-face (specs)
2258 "Make a compatible face specification.
2259 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2260 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2261 to the top of the list. The `min-colors' attribute will be removed from
2262 any other entries, and any resulting duplicates will be removed entirely."
2263 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2264 (let (r e a)
2265 (while (setq e (pop specs))
2266 (cond
2267 ((memq (car e) '(t default)) (push e r))
2268 ((setq a (member '(min-colors 8) (car e)))
2269 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2270 (cdr e)))))
2271 ((setq a (assq 'min-colors (car e)))
2272 (setq e (cons (delq a (car e)) (cdr e)))
2273 (or (assoc (car e) r) (push e r)))
2274 (t (or (assoc (car e) r) (push e r)))))
2275 (nreverse r))
2276 specs))
2277
2278 (defface org-hide
2279 '((((background light)) (:foreground "white"))
2280 (((background dark)) (:foreground "black")))
2281 "Face used to hide leading stars in headlines.
2282 The forground color of this face should be equal to the background
2283 color of the frame."
2284 :group 'org-faces)
2285
2286 (defface org-level-1 ;; font-lock-function-name-face
2287 (org-compatible-face
2288 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2289 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2290 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2291 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2292 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2293 (t (:bold t))))
2294 "Face used for level 1 headlines."
2295 :group 'org-faces)
2296
2297 (defface org-level-2 ;; font-lock-variable-name-face
2298 (org-compatible-face
2299 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2300 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2301 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2302 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2303 (t (:bold t))))
2304 "Face used for level 2 headlines."
2305 :group 'org-faces)
2306
2307 (defface org-level-3 ;; font-lock-keyword-face
2308 (org-compatible-face
2309 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2310 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2311 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2312 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2313 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2314 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2315 (t (:bold t))))
2316 "Face used for level 3 headlines."
2317 :group 'org-faces)
2318
2319 (defface org-level-4 ;; font-lock-comment-face
2320 (org-compatible-face
2321 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2322 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2323 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2324 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2325 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2326 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2327 (t (:bold t))))
2328 "Face used for level 4 headlines."
2329 :group 'org-faces)
2330
2331 (defface org-level-5 ;; font-lock-type-face
2332 (org-compatible-face
2333 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2334 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2335 (((class color) (min-colors 8)) (:foreground "green"))))
2336 "Face used for level 5 headlines."
2337 :group 'org-faces)
2338
2339 (defface org-level-6 ;; font-lock-constant-face
2340 (org-compatible-face
2341 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2342 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2343 (((class color) (min-colors 8)) (:foreground "magenta"))))
2344 "Face used for level 6 headlines."
2345 :group 'org-faces)
2346
2347 (defface org-level-7 ;; font-lock-builtin-face
2348 (org-compatible-face
2349 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2350 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2351 (((class color) (min-colors 8)) (:foreground "blue"))))
2352 "Face used for level 7 headlines."
2353 :group 'org-faces)
2354
2355 (defface org-level-8 ;; font-lock-string-face
2356 (org-compatible-face
2357 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2358 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2359 (((class color) (min-colors 8)) (:foreground "green"))))
2360 "Face used for level 8 headlines."
2361 :group 'org-faces)
2362
2363 (defface org-special-keyword ;; font-lock-string-face
2364 (org-compatible-face
2365 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2366 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2367 (t (:italic t))))
2368 "Face used for special keywords."
2369 :group 'org-faces)
2370
2371 (defface org-warning ;; font-lock-warning-face
2372 (org-compatible-face
2373 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2374 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2375 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2376 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2377 (t (:bold t))))
2378 "Face for deadlines and TODO keywords."
2379 :group 'org-faces)
2380
2381 (defface org-headline-done ;; font-lock-string-face
2382 (org-compatible-face
2383 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2384 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2385 (((class color) (min-colors 8) (background light)) (:bold nil))))
2386 "Face used to indicate that a headline is DONE.
2387 This face is only used if `org-fontify-done-headline' is set."
2388 :group 'org-faces)
2389
2390 (defface org-link
2391 '((((class color) (background light)) (:foreground "Purple" :underline t))
2392 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2393 (t (:underline t)))
2394 "Face for links."
2395 :group 'org-faces)
2396
2397 (defface org-date
2398 '((((class color) (background light)) (:foreground "Purple" :underline t))
2399 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2400 (t (:underline t)))
2401 "Face for links."
2402 :group 'org-faces)
2403
2404 (defface org-tag
2405 '((t (:bold t)))
2406 "Face for tags."
2407 :group 'org-faces)
2408
2409 (defface org-todo ;; font-lock-warning-face
2410 (org-compatible-face
2411 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2412 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2413 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2414 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2415 (t (:inverse-video t :bold t))))
2416 "Face for TODO keywords."
2417 :group 'org-faces)
2418
2419 (defface org-done ;; font-lock-type-face
2420 (org-compatible-face
2421 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2422 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2423 (((class color) (min-colors 8)) (:foreground "green"))
2424 (t (:bold t))))
2425 "Face used for DONE."
2426 :group 'org-faces)
2427
2428 (defface org-table ;; font-lock-function-name-face
2429 (org-compatible-face
2430 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2431 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2432 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2433 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2434 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2435 (((class color) (min-colors 8) (background dark)))))
2436 "Face used for tables."
2437 :group 'org-faces)
2438
2439 (defface org-formula
2440 (org-compatible-face
2441 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2442 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2443 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2444 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2445 (t (:bold t :italic t))))
2446 "Face for formulas."
2447 :group 'org-faces)
2448
2449 (defface org-scheduled-today
2450 (org-compatible-face
2451 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2452 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2453 (((class color) (min-colors 8)) (:foreground "green"))
2454 (t (:bold t :italic t))))
2455 "Face for items scheduled for a certain day."
2456 :group 'org-faces)
2457
2458 (defface org-scheduled-previously
2459 (org-compatible-face
2460 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2461 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2462 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2463 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2464 (t (:bold t))))
2465 "Face for items scheduled previously, and not yet done."
2466 :group 'org-faces)
2467
2468 (defface org-upcoming-deadline
2469 (org-compatible-face
2470 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2471 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2472 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2473 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2474 (t (:bold t))))
2475 "Face for items scheduled previously, and not yet done."
2476 :group 'org-faces)
2477
2478 (defface org-time-grid ;; font-lock-variable-name-face
2479 (org-compatible-face
2480 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2481 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2482 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2483 "Face used for time grids."
2484 :group 'org-faces)
2485
2486 (defconst org-level-faces
2487 '(org-level-1 org-level-2 org-level-3 org-level-4
2488 org-level-5 org-level-6 org-level-7 org-level-8
2489 ))
2490 (defconst org-n-levels (length org-level-faces))
2491
2492
2493 ;; Variables for pre-computed regular expressions, all buffer local
2494 (defvar org-done-string nil
2495 "The last string in `org-todo-keywords', indicating an item is DONE.")
2496 (make-variable-buffer-local 'org-done-string)
2497 (defvar org-todo-regexp nil
2498 "Matches any of the TODO state keywords.")
2499 (make-variable-buffer-local 'org-todo-regexp)
2500 (defvar org-not-done-regexp nil
2501 "Matches any of the TODO state keywords except the last one.")
2502 (make-variable-buffer-local 'org-not-done-regexp)
2503 (defvar org-todo-line-regexp nil
2504 "Matches a headline and puts TODO state into group 2 if present.")
2505 (make-variable-buffer-local 'org-todo-line-regexp)
2506 (defvar org-todo-line-tags-regexp nil
2507 "Matches a headline and puts TODO state into group 2 if present.
2508 Also put tags into group 4 if tags are present.")
2509 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2510 (defvar org-nl-done-regexp nil
2511 "Matches newline followed by a headline with the DONE keyword.")
2512 (make-variable-buffer-local 'org-nl-done-regexp)
2513 (defvar org-looking-at-done-regexp nil
2514 "Matches the DONE keyword a point.")
2515 (make-variable-buffer-local 'org-looking-at-done-regexp)
2516 (defvar org-todo-kwd-priority-p nil
2517 "Do TODO items have priorities?")
2518 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2519 (defvar org-todo-kwd-max-priority nil
2520 "Maximum priority of TODO items.")
2521 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2522 (defvar org-ds-keyword-length 12
2523 "Maximum length of the Deadline and SCHEDULED keywords.")
2524 (make-variable-buffer-local 'org-ds-keyword-length)
2525 (defvar org-deadline-regexp nil
2526 "Matches the DEADLINE keyword.")
2527 (make-variable-buffer-local 'org-deadline-regexp)
2528 (defvar org-deadline-time-regexp nil
2529 "Matches the DEADLINE keyword together with a time stamp.")
2530 (make-variable-buffer-local 'org-deadline-time-regexp)
2531 (defvar org-deadline-line-regexp nil
2532 "Matches the DEADLINE keyword and the rest of the line.")
2533 (make-variable-buffer-local 'org-deadline-line-regexp)
2534 (defvar org-scheduled-regexp nil
2535 "Matches the SCHEDULED keyword.")
2536 (make-variable-buffer-local 'org-scheduled-regexp)
2537 (defvar org-scheduled-time-regexp nil
2538 "Matches the SCHEDULED keyword together with a time stamp.")
2539 (make-variable-buffer-local 'org-scheduled-time-regexp)
2540 (defvar org-closed-time-regexp nil
2541 "Matches the CLOSED keyword together with a time stamp.")
2542 (make-variable-buffer-local 'org-closed-time-regexp)
2543
2544 (defvar org-keyword-time-regexp nil
2545 "Matches any of the 3 keywords, together with the time stamp.")
2546 (make-variable-buffer-local 'org-keyword-time-regexp)
2547 (defvar org-maybe-keyword-time-regexp nil
2548 "Matches a timestamp, possibly preceeded by a keyword.")
2549 (make-variable-buffer-local 'org-keyword-time-regexp)
2550
2551 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2552 mouse-map t)
2553 "Properties to remove when a string without properties is wanted.")
2554
2555 (defsubst org-match-string-no-properties (num &optional string)
2556 (if (featurep 'xemacs)
2557 (let ((s (match-string num string)))
2558 (remove-text-properties 0 (length s) org-rm-props s)
2559 s)
2560 (match-string-no-properties num string)))
2561
2562 (defsubst org-no-properties (s)
2563 (remove-text-properties 0 (length s) org-rm-props s)
2564 s)
2565
2566 (defun org-set-regexps-and-options ()
2567 "Precompute regular expressions for current buffer."
2568 (when (eq major-mode 'org-mode)
2569 (let ((re (org-make-options-regexp
2570 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2571 "STARTUP" "ARCHIVE" "TAGS")))
2572 (splitre "[ \t]+")
2573 kwds int key value cat arch tags)
2574 (save-excursion
2575 (save-restriction
2576 (widen)
2577 (goto-char (point-min))
2578 (while (re-search-forward re nil t)
2579 (setq key (match-string 1) value (org-match-string-no-properties 2))
2580 (cond
2581 ((equal key "CATEGORY")
2582 (if (string-match "[ \t]+$" value)
2583 (setq value (replace-match "" t t value)))
2584 (setq cat (intern value)))
2585 ((equal key "SEQ_TODO")
2586 (setq int 'sequence
2587 kwds (append kwds (org-split-string value splitre))))
2588 ((equal key "PRI_TODO")
2589 (setq int 'priority
2590 kwds (append kwds (org-split-string value splitre))))
2591 ((equal key "TYP_TODO")
2592 (setq int 'type
2593 kwds (append kwds (org-split-string value splitre))))
2594 ((equal key "TAGS")
2595 (setq tags (append tags (org-split-string value splitre))))
2596 ((equal key "STARTUP")
2597 (let ((opts (org-split-string value splitre))
2598 (set '(("fold" org-startup-folded t)
2599 ("overview" org-startup-folded t)
2600 ("nofold" org-startup-folded nil)
2601 ("showall" org-startup-folded nil)
2602 ("content" org-startup-folded content)
2603 ("hidestars" org-hide-leading-stars t)
2604 ("showstars" org-hide-leading-stars nil)
2605 ("odd" org-odd-levels-only t)
2606 ("oddeven" org-odd-levels-only nil)
2607 ("align" org-startup-align-all-tables t)
2608 ("noalign" org-startup-align-all-tables nil)
2609 ("logging" org-log-done t)
2610 ("nologging" org-log-done nil)
2611 ("dlcheck" org-startup-with-deadline-check t)
2612 ("nodlcheck" org-startup-with-deadline-check nil)))
2613 l var val)
2614 (while (setq l (assoc (pop opts) set))
2615 (setq var (nth 1 l) val (nth 2 l))
2616 (set (make-local-variable var) val))))
2617 ((equal key "ARCHIVE")
2618 (string-match " *$" value)
2619 (setq arch (replace-match "" t t value))
2620 (remove-text-properties 0 (length arch)
2621 '(face t fontified t) arch)))
2622 )))
2623 (and cat (set (make-local-variable 'org-category) cat))
2624 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2625 (and arch (set (make-local-variable 'org-archive-location) arch))
2626 (and int (set (make-local-variable 'org-todo-interpretation) int))
2627 (when tags
2628 (let (e tg c tgs)
2629 (while (setq e (pop tags))
2630 (cond
2631 ((equal e "{") (push '(:startgroup) tgs))
2632 ((equal e "}") (push '(:endgroup) tgs))
2633 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2634 (push (cons (match-string 1 e)
2635 (string-to-char (match-string 2 e)))
2636 tgs))
2637 (t (push (list e) tgs))))
2638 (set (make-local-variable 'org-tag-alist) nil)
2639 (while (setq e (pop tgs))
2640 (or (and (stringp (car e))
2641 (assoc (car e) org-tag-alist))
2642 (push e org-tag-alist))))))
2643
2644 ;; Compute the regular expressions and other local variables
2645 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2646 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2647 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2648 (length org-scheduled-string)))
2649 org-done-string
2650 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2651 org-todo-regexp
2652 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2653 "\\|") "\\)\\>")
2654 org-not-done-regexp
2655 (concat "\\<\\("
2656 (mapconcat 'regexp-quote
2657 (nreverse (cdr (reverse org-todo-keywords)))
2658 "\\|")
2659 "\\)\\>")
2660 org-todo-line-regexp
2661 (concat "^\\(\\*+\\)[ \t]*\\("
2662 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2663 "\\)? *\\(.*\\)")
2664 org-nl-done-regexp
2665 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2666 org-todo-line-tags-regexp
2667 (concat "^\\(\\*+\\)[ \t]*\\("
2668 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2669 "\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
2670 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2671 org-deadline-regexp (concat "\\<" org-deadline-string)
2672 org-deadline-time-regexp
2673 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2674 org-deadline-line-regexp
2675 (concat "\\<\\(" org-deadline-string "\\).*")
2676 org-scheduled-regexp
2677 (concat "\\<" org-scheduled-string)
2678 org-scheduled-time-regexp
2679 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2680 org-closed-time-regexp
2681 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2682 org-keyword-time-regexp
2683 (concat "\\<\\(" org-scheduled-string
2684 "\\|" org-deadline-string
2685 "\\|" org-closed-string
2686 "\\|" org-clock-string "\\)"
2687 " *[[<]\\([^]>]+\\)[]>]")
2688 org-maybe-keyword-time-regexp
2689 (concat "\\(\\<\\(" org-scheduled-string
2690 "\\|" org-deadline-string
2691 "\\|" org-closed-string
2692 "\\|" org-clock-string "\\)\\)?"
2693 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
2694
2695 (org-set-font-lock-defaults)))
2696
2697 ;; Tell the compiler about dynamically scoped variables,
2698 ;; and variables from other packages
2699 (defvar calc-embedded-close-formula) ; defined by the calc package
2700 (defvar calc-embedded-open-formula) ; defined by the calc package
2701 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
2702 (defvar zmacs-regions) ; XEmacs regions
2703 (defvar original-date) ; dynamically scoped in calendar
2704 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2705 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2706 (defvar org-html-entities) ; defined later in this file
2707 (defvar org-goto-start-pos) ; dynamically scoped parameter
2708 (defvar org-time-was-given) ; dynamically scoped parameter
2709 (defvar org-ts-what) ; dynamically scoped parameter
2710 (defvar mark-active) ; Emacs only, not available in XEmacs.
2711 (defvar timecnt) ; dynamically scoped parameter
2712 (defvar levels-open) ; dynamically scoped parameter
2713 (defvar entry) ; dynamically scoped parameter
2714 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
2715 (defvar date) ; dynamically scoped parameter
2716 (defvar description) ; dynamically scoped parameter
2717 (defvar ans1) ; dynamically scoped parameter
2718 (defvar ans2) ; dynamically scoped parameter
2719 (defvar starting-day) ; local variable
2720 (defvar include-all-loc) ; local variable
2721 (defvar vm-message-pointer) ; from vm
2722 (defvar vm-folder-directory) ; from vm
2723 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2724 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2725 (defvar gnus-group-name) ; from gnus
2726 (defvar gnus-article-current) ; from gnus
2727 (defvar w3m-current-url) ; from w3m
2728 (defvar w3m-current-title) ; from w3m
2729 (defvar mh-progs) ; from MH-E
2730 (defvar mh-current-folder) ; from MH-E
2731 (defvar mh-show-folder-buffer) ; from MH-E
2732 (defvar mh-index-folder) ; from MH-E
2733 (defvar mh-searcher) ; from MH-E
2734 (defvar org-selected-point) ; dynamically scoped parameter
2735 (defvar calendar-mode-map) ; from calendar.el
2736 (defvar last-arg) ; local variable
2737 (defvar remember-save-after-remembering) ; from remember.el
2738 (defvar remember-data-file) ; from remember.el
2739 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2740 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2741 (defvar orgtbl-mode) ; defined later in this file
2742 (defvar Info-current-file) ; from info.el
2743 (defvar Info-current-node) ; from info.el
2744
2745 ;;; Define the mode
2746
2747 (defvar org-mode-map
2748 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2749 (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.")
2750 (copy-keymap outline-mode-map))
2751 "Keymap for Org-mode.")
2752
2753 (defvar org-struct-menu) ; defined later in this file
2754 (defvar org-org-menu) ; defined later in this file
2755 (defvar org-tbl-menu) ; defined later in this file
2756
2757 ;; We use a before-change function to check if a table might need
2758 ;; an update.
2759 (defvar org-table-may-need-update t
2760 "Indicates that a table might need an update.
2761 This variable is set by `org-before-change-function'.
2762 `org-table-align' sets it back to nil.")
2763 (defvar org-mode-hook nil)
2764 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2765 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2766
2767
2768 ;;;###autoload
2769 (define-derived-mode org-mode outline-mode "Org"
2770 "Outline-based notes management and organizer, alias
2771 \"Carsten's outline-mode for keeping track of everything.\"
2772
2773 Org-mode develops organizational tasks around a NOTES file which
2774 contains information about projects as plain text. Org-mode is
2775 implemented on top of outline-mode, which is ideal to keep the content
2776 of large files well structured. It supports ToDo items, deadlines and
2777 time stamps, which magically appear in the diary listing of the Emacs
2778 calendar. Tables are easily created with a built-in table editor.
2779 Plain text URL-like links connect to websites, emails (VM), Usenet
2780 messages (Gnus), BBDB entries, and any files related to the project.
2781 For printing and sharing of notes, an Org-mode file (or a part of it)
2782 can be exported as a structured ASCII or HTML file.
2783
2784 The following commands are available:
2785
2786 \\{org-mode-map}"
2787
2788 ;; Get rid of Outline menus, they are not needed
2789 ;; Need to do this here because define-derived-mode sets up
2790 ;; the keymap so late.
2791 (if (featurep 'xemacs)
2792 (if org-noutline-p
2793 (progn
2794 (easy-menu-remove outline-mode-menu-heading)
2795 (easy-menu-remove outline-mode-menu-show)
2796 (easy-menu-remove outline-mode-menu-hide))
2797 (delete-menu-item '("Headings"))
2798 (delete-menu-item '("Show"))
2799 (delete-menu-item '("Hide"))
2800 (set-menubar-dirty-flag))
2801 (define-key org-mode-map [menu-bar headings] 'undefined)
2802 (define-key org-mode-map [menu-bar hide] 'undefined)
2803 (define-key org-mode-map [menu-bar show] 'undefined))
2804
2805 (easy-menu-add org-org-menu)
2806 (easy-menu-add org-tbl-menu)
2807 (org-install-agenda-files-menu)
2808 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2809 (org-add-to-invisibility-spec '(org-cwidth))
2810 (when (featurep 'xemacs)
2811 (set (make-local-variable 'line-move-ignore-invisible) t))
2812 (setq outline-regexp "\\*+")
2813 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2814 (setq outline-level 'org-outline-level)
2815 (when (and org-ellipsis (stringp org-ellipsis))
2816 (unless org-display-table
2817 (setq org-display-table (make-display-table)))
2818 (set-display-table-slot org-display-table
2819 4 (string-to-vector org-ellipsis))
2820 (setq buffer-display-table org-display-table))
2821 (org-set-regexps-and-options)
2822 (modify-syntax-entry ?# "<")
2823 (if org-startup-truncated (setq truncate-lines t))
2824 (set (make-local-variable 'font-lock-unfontify-region-function)
2825 'org-unfontify-region)
2826 ;; Activate before-change-function
2827 (set (make-local-variable 'org-table-may-need-update) t)
2828 (org-add-hook 'before-change-functions 'org-before-change-function nil
2829 'local)
2830 ;; Check for running clock before killing a buffer
2831 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
2832 ;; Paragraphs and auto-filling
2833 (org-set-autofill-regexps)
2834 (org-update-radio-target-regexp)
2835 ;; Settings for Calc embedded mode
2836 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2837 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2838 (if (and org-insert-mode-line-in-empty-file
2839 (interactive-p)
2840 (= (point-min) (point-max)))
2841 (insert " -*- mode: org -*-\n\n"))
2842
2843 (unless org-inhibit-startup
2844 (when org-startup-align-all-tables
2845 (let ((bmp (buffer-modified-p)))
2846 (org-table-map-tables 'org-table-align)
2847 (set-buffer-modified-p bmp)))
2848 (if org-startup-with-deadline-check
2849 (call-interactively 'org-check-deadlines)
2850 (cond
2851 ((eq org-startup-folded t)
2852 (org-cycle '(4)))
2853 ((eq org-startup-folded 'content)
2854 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2855 (org-cycle '(4)) (org-cycle '(4))))))))
2856
2857 (defsubst org-call-with-arg (command arg)
2858 "Call COMMAND interactively, but pretend prefix are was ARG."
2859 (let ((current-prefix-arg arg)) (call-interactively command)))
2860
2861 (defsubst org-current-line (&optional pos)
2862 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2863
2864 (defun org-current-time ()
2865 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2866 (if (> org-time-stamp-rounding-minutes 0)
2867 (let ((r org-time-stamp-rounding-minutes)
2868 (time (decode-time)))
2869 (apply 'encode-time
2870 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2871 (nthcdr 2 time))))
2872 (current-time)))
2873
2874 (defun org-add-props (string plist &rest props)
2875 "Add text properties to entire string, from beginning to end.
2876 PLIST may be a list of properties, PROPS are individual properties and values
2877 that will be added to PLIST. Returns the string that was modified."
2878 (add-text-properties
2879 0 (length string) (if props (append plist props) plist) string)
2880 string)
2881 (put 'org-add-props 'lisp-indent-function 2)
2882
2883
2884 ;;; Font-Lock stuff
2885
2886 (defvar org-mouse-map (make-sparse-keymap))
2887 (define-key org-mouse-map
2888 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2889 (define-key org-mouse-map
2890 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2891 (when org-mouse-1-follows-link
2892 (define-key org-mouse-map [follow-link] 'mouse-face))
2893 (when org-tab-follows-link
2894 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2895 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2896 (when org-return-follows-link
2897 (define-key org-mouse-map [(return)] 'org-open-at-point)
2898 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2899
2900 (require 'font-lock)
2901
2902 (defconst org-non-link-chars "]\t\n\r<>")
2903 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
2904 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
2905 (defconst org-link-re-with-space
2906 (concat
2907 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2908 "\\([^" org-non-link-chars " ]"
2909 "[^" org-non-link-chars "]*"
2910 "[^" org-non-link-chars " ]\\)>?")
2911 "Matches a link with spaces, optional angular brackets around it.")
2912
2913 (defconst org-link-re-with-space2
2914 (concat
2915 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2916 "\\([^" org-non-link-chars " ]"
2917 "[^]\t\n\r]*"
2918 "[^" org-non-link-chars " ]\\)>?")
2919 "Matches a link with spaces, optional angular brackets around it.")
2920
2921 (defconst org-angle-link-re
2922 (concat
2923 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2924 "\\([^" org-non-link-chars " ]"
2925 "[^" org-non-link-chars "]*"
2926 "\\)>")
2927 "Matches link with angular brackets, spaces are allowed.")
2928 (defconst org-plain-link-re
2929 (concat
2930 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2931 "\\([^]\t\n\r<>,;() ]+\\)")
2932 "Matches plain link, without spaces.")
2933
2934 (defconst org-bracket-link-regexp
2935 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2936 "Matches a link in double brackets.")
2937
2938 (defconst org-bracket-link-analytic-regexp
2939 (concat
2940 "\\[\\["
2941 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
2942 "\\([^]]+\\)"
2943 "\\]"
2944 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
2945 "\\]"))
2946 ; 1: http:
2947 ; 2: http
2948 ; 3: path
2949 ; 4: [desc]
2950 ; 5: desc
2951
2952
2953 (defconst org-ts-lengths
2954 (cons (length (format-time-string (car org-time-stamp-formats)))
2955 (length (format-time-string (cdr org-time-stamp-formats))))
2956 "This holds the lengths of the two different time formats.")
2957 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2958 "Regular expression for fast time stamp matching.")
2959 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2960 "Regular expression for fast time stamp matching.")
2961 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2962 "Regular expression matching time strings for analysis.")
2963 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2964 "Regular expression matching time stamps, with groups.")
2965 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2966 "Regular expression matching a time stamp range.")
2967 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2968 org-ts-regexp "\\)?")
2969 "Regular expression matching a time stamp or time stamp range.")
2970
2971 (defvar org-§emph-face nil)
2972
2973 (defun org-do-emphasis-faces (limit)
2974 "Run through the buffer and add overlays to links."
2975 (if (re-search-forward org-emph-re limit t)
2976 (progn
2977 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
2978 'face
2979 (nth 1 (assoc (match-string 3)
2980 org-emphasis-alist)))
2981 (add-text-properties (match-beginning 2) (match-end 2)
2982 '(font-lock-multiline t))
2983 (backward-char 1)
2984 t)))
2985
2986 (defun org-activate-plain-links (limit)
2987 "Run through the buffer and add overlays to links."
2988 (if (re-search-forward org-plain-link-re limit t)
2989 (progn
2990 (add-text-properties (match-beginning 0) (match-end 0)
2991 (list 'mouse-face 'highlight
2992 'keymap org-mouse-map
2993 ))
2994 t)))
2995
2996 (defun org-activate-angle-links (limit)
2997 "Run through the buffer and add overlays to links."
2998 (if (re-search-forward org-angle-link-re limit t)
2999 (progn
3000 (add-text-properties (match-beginning 0) (match-end 0)
3001 (list 'mouse-face 'highlight
3002 'keymap org-mouse-map
3003 ))
3004 t)))
3005
3006 (defun org-activate-bracket-links (limit)
3007 "Run through the buffer and add overlays to bracketed links."
3008 (if (re-search-forward org-bracket-link-regexp limit t)
3009 (let* ((help (concat "LINK: "
3010 (org-match-string-no-properties 1)))
3011 ;; FIXME: above we should remove the escapes.
3012 ;; but that requires another match, protecting match data,
3013 ;; a lot of overhead for font-lock.
3014 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
3015 'keymap org-mouse-map 'mouse-face 'highlight
3016 'help-echo help))
3017 (vp (list 'rear-nonsticky t
3018 'keymap org-mouse-map 'mouse-face 'highlight
3019 'help-echo help)))
3020 ;; We need to remove the invisible property here. Table narrowing
3021 ;; may have made some of this invisible.
3022 (remove-text-properties (match-beginning 0) (match-end 0)
3023 '(invisible nil))
3024 (if (match-end 3)
3025 (progn
3026 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3027 (add-text-properties (match-beginning 3) (match-end 3) vp)
3028 (add-text-properties (match-end 3) (match-end 0) ip))
3029 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3030 (add-text-properties (match-beginning 1) (match-end 1) vp)
3031 (add-text-properties (match-end 1) (match-end 0) ip))
3032 t)))
3033
3034 (defun org-activate-dates (limit)
3035 "Run through the buffer and add overlays to dates."
3036 (if (re-search-forward org-tsr-regexp limit t)
3037 (progn
3038 (add-text-properties (match-beginning 0) (match-end 0)
3039 (list 'mouse-face 'highlight
3040 'keymap org-mouse-map))
3041 t)))
3042
3043 (defvar org-target-link-regexp nil
3044 "Regular expression matching radio targets in plain text.")
3045 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3046 "Regular expression matching a link target.")
3047 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3048 "Regular expression matching a link target.")
3049
3050 (defun org-activate-target-links (limit)
3051 "Run through the buffer and add overlays to target matches."
3052 (when org-target-link-regexp
3053 (let ((case-fold-search t))
3054 (if (re-search-forward org-target-link-regexp limit t)
3055 (progn
3056 (add-text-properties (match-beginning 0) (match-end 0)
3057 (list 'mouse-face 'highlight
3058 'keymap org-mouse-map
3059 'help-echo "Radio target link"
3060 'org-linked-text t))
3061 t)))))
3062
3063 (defun org-update-radio-target-regexp ()
3064 "Find all radio targets in this file and update the regular expression."
3065 (interactive)
3066 (when (memq 'radio org-activate-links)
3067 (setq org-target-link-regexp
3068 (org-make-target-link-regexp (org-all-targets 'radio)))
3069 (org-restart-font-lock)))
3070
3071 (defun org-hide-wide-columns (limit)
3072 (let (s e)
3073 (setq s (text-property-any (point) (or limit (point-max))
3074 'org-cwidth t))
3075 (when s
3076 (setq e (next-single-property-change s 'org-cwidth))
3077 (add-text-properties s e '(invisible org-cwidth intangible t))
3078 (goto-char e)
3079 t)))
3080
3081 (defun org-restart-font-lock ()
3082 "Restart font-lock-mode, to force refontification."
3083 (when (and (boundp 'font-lock-mode) font-lock-mode)
3084 (font-lock-mode -1)
3085 (font-lock-mode 1)))
3086
3087 (defun org-all-targets (&optional radio)
3088 "Return a list of all targets in this file.
3089 With optional argument RADIO, only find radio targets."
3090 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3091 rtn)
3092 (save-excursion
3093 (goto-char (point-min))
3094 (while (re-search-forward re nil t)
3095 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3096 rtn)))
3097
3098 (defun org-make-target-link-regexp (targets)
3099 "Make regular expression matching all strings in TARGETS.
3100 The regular expression finds the targets also if there is a line break
3101 between words."
3102 (and targets
3103 (concat
3104 "\\<\\("
3105 (mapconcat
3106 (lambda (x)
3107 (while (string-match " +" x)
3108 (setq x (replace-match "\\s-+" t t x)))
3109 x)
3110 targets
3111 "\\|")
3112 "\\)\\>")))
3113
3114 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3115 "Matches CamelCase words, possibly with a star before it.")
3116
3117 (defun org-activate-camels (limit)
3118 "Run through the buffer and add overlays to dates."
3119 (if (re-search-forward org-camel-regexp limit t)
3120 (progn
3121 (add-text-properties (match-beginning 0) (match-end 0)
3122 (list 'mouse-face 'highlight
3123 'keymap org-mouse-map))
3124 t)))
3125
3126 (defun org-activate-tags (limit)
3127 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3128 (progn
3129 (add-text-properties (match-beginning 1) (match-end 1)
3130 (list 'mouse-face 'highlight
3131 'keymap org-mouse-map))
3132 t)))
3133
3134 (defun org-font-lock-level ()
3135 (save-excursion
3136 (org-back-to-heading t)
3137 (- (match-end 0) (match-beginning 0))))
3138
3139 (defun org-outline-level ()
3140 (save-excursion
3141 (looking-at outline-regexp)
3142 (if (match-beginning 1)
3143 (+ (org-get-string-indentation (match-string 1)) 1000)
3144 (- (match-end 0) (match-beginning 0)))))
3145
3146 (defvar org-font-lock-keywords nil)
3147
3148 (defun org-set-font-lock-defaults ()
3149 (let* ((em org-fontify-emphasized-text)
3150 (lk org-activate-links)
3151 (org-font-lock-extra-keywords
3152 ;; Headlines
3153 (list
3154 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3155 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3156 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3157 (1 'org-table))
3158 ;; Links
3159 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3160 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3161 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3162 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3163 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3164 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3165 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3166 (if org-table-limit-column-width
3167 '(org-hide-wide-columns (0 nil append)))
3168 ;; TODO lines
3169 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3170 '(1 'org-todo t))
3171 ;; Priorities
3172 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3173 ;; Special keywords
3174 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3175 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3176 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3177 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3178 ;; Emphasis
3179 (if em '(org-do-emphasis-faces))
3180 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3181 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3182 2 'bold prepend)
3183 ;; COMMENT
3184 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3185 "\\|" org-quote-string "\\)\\>")
3186 '(1 'org-special-keyword t))
3187 '("^#.*" (0 'font-lock-comment-face t))
3188 ;; DONE
3189 (if org-fontify-done-headline
3190 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3191 '(1 'org-done t) '(2 'org-headline-done t))
3192 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3193 '(1 'org-done t)))
3194 ;; Table stuff
3195 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3196 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3197 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3198 (if org-format-transports-properties-p
3199 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3200 )))
3201 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3202 ;; Now set the full font-lock-keywords
3203 (set (make-local-variable 'org-font-lock-keywords)
3204 org-font-lock-extra-keywords)
3205 (set (make-local-variable 'font-lock-defaults)
3206 '(org-font-lock-keywords t nil nil backward-paragraph))
3207 (kill-local-variable 'font-lock-keywords) nil))
3208
3209 (defvar org-m nil)
3210 (defvar org-l nil)
3211 (defvar org-f nil)
3212 (defun org-get-level-face (n)
3213 "Get the right face for match N in font-lock matching of healdines."
3214 (setq org-l (- (match-end 2) (match-beginning 1)))
3215 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3216 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3217 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3218 (cond
3219 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3220 ((eq n 2) org-f)
3221 (t (if org-level-color-stars-only nil org-f))))
3222
3223 (defun org-unfontify-region (beg end &optional maybe_loudly)
3224 "Remove fontification and activation overlays from links."
3225 (font-lock-default-unfontify-region beg end)
3226 (let* ((buffer-undo-list t)
3227 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3228 (inhibit-modification-hooks t)
3229 deactivate-mark buffer-file-name buffer-file-truename)
3230 (remove-text-properties beg end
3231 '(mouse-face nil keymap nil org-linked-text nil
3232 invisible nil intangible nil))))
3233 ;;; Visibility cycling
3234
3235 (defvar org-cycle-global-status nil)
3236 (make-variable-buffer-local 'org-cycle-global-status)
3237 (defvar org-cycle-subtree-status nil)
3238 (make-variable-buffer-local 'org-cycle-subtree-status)
3239
3240 ;;;###autoload
3241 (defun org-cycle (&optional arg)
3242 "Visibility cycling for Org-mode.
3243
3244 - When this function is called with a prefix argument, rotate the entire
3245 buffer through 3 states (global cycling)
3246 1. OVERVIEW: Show only top-level headlines.
3247 2. CONTENTS: Show all headlines of all levels, but no body text.
3248 3. SHOW ALL: Show everything.
3249
3250 - When point is at the beginning of a headline, rotate the subtree started
3251 by this line through 3 different states (local cycling)
3252 1. FOLDED: Only the main headline is shown.
3253 2. CHILDREN: The main headline and the direct children are shown.
3254 From this state, you can move to one of the children
3255 and zoom in further.
3256 3. SUBTREE: Show the entire subtree, including body text.
3257
3258 - When there is a numeric prefix, go up to a heading with level ARG, do
3259 a `show-subtree' and return to the previous cursor position. If ARG
3260 is negative, go up that many levels.
3261
3262 - When point is not at the beginning of a headline, execute
3263 `indent-relative', like TAB normally does. See the option
3264 `org-cycle-emulate-tab' for details.
3265
3266 - Special case: if point is the the beginning of the buffer and there is
3267 no headline in line 1, this function will act as if called with prefix arg."
3268 (interactive "P")
3269
3270 (let* ((outline-regexp
3271 (if org-cycle-include-plain-lists
3272 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
3273 outline-regexp))
3274 (bob-special (and org-cycle-global-at-bob (bobp)
3275 (not (looking-at outline-regexp))))
3276 (org-cycle-hook (if bob-special nil org-cycle-hook))
3277 (pos (point)))
3278
3279 (if (or bob-special (equal arg '(4)))
3280 ;; special case: use global cycling
3281 (setq arg t))
3282
3283 (cond
3284
3285 ((org-at-table-p 'any)
3286 ;; Enter the table or move to the next field in the table
3287 (or (org-table-recognize-table.el)
3288 (progn
3289 (if arg (org-table-edit-field t)
3290 (org-table-justify-field-maybe)
3291 (call-interactively 'org-table-next-field)))))
3292
3293 ((eq arg t) ;; Global cycling
3294
3295 (cond
3296 ((and (eq last-command this-command)
3297 (eq org-cycle-global-status 'overview))
3298 ;; We just created the overview - now do table of contents
3299 ;; This can be slow in very large buffers, so indicate action
3300 (message "CONTENTS...")
3301 (org-content)
3302 (message "CONTENTS...done")
3303 (setq org-cycle-global-status 'contents)
3304 (run-hook-with-args 'org-cycle-hook 'contents))
3305
3306 ((and (eq last-command this-command)
3307 (eq org-cycle-global-status 'contents))
3308 ;; We just showed the table of contents - now show everything
3309 (show-all)
3310 (message "SHOW ALL")
3311 (setq org-cycle-global-status 'all)
3312 (run-hook-with-args 'org-cycle-hook 'all))
3313
3314 (t
3315 ;; Default action: go to overview
3316 (org-overview)
3317 (message "OVERVIEW")
3318 (setq org-cycle-global-status 'overview)
3319 (run-hook-with-args 'org-cycle-hook 'overview))))
3320
3321 ((integerp arg)
3322 ;; Show-subtree, ARG levels up from here.
3323 (save-excursion
3324 (org-back-to-heading)
3325 (outline-up-heading (if (< arg 0) (- arg)
3326 (- (funcall outline-level) arg)))
3327 (org-show-subtree)))
3328
3329 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3330 ;; At a heading: rotate between three different views
3331 (org-back-to-heading)
3332 (let ((goal-column 0) eoh eol eos)
3333 ;; First, some boundaries
3334 (save-excursion
3335 (org-back-to-heading)
3336 (save-excursion
3337 (beginning-of-line 2)
3338 (while (and (not (eobp)) ;; this is like `next-line'
3339 (get-char-property (1- (point)) 'invisible))
3340 (beginning-of-line 2)) (setq eol (point)))
3341 (outline-end-of-heading) (setq eoh (point))
3342 (org-end-of-subtree t) (setq eos (point))
3343 (outline-next-heading))
3344 ;; Find out what to do next and set `this-command'
3345 (cond
3346 ((and (= eos eoh)
3347 ;; Nothing is hidden behind this heading
3348 (message "EMPTY ENTRY")
3349 (setq org-cycle-subtree-status nil)))
3350 ((>= eol eos)
3351 ;; Entire subtree is hidden in one line: open it
3352 (org-show-entry)
3353 (show-children)
3354 (message "CHILDREN")
3355 (setq org-cycle-subtree-status 'children)
3356 (run-hook-with-args 'org-cycle-hook 'children))
3357 ((and (eq last-command this-command)
3358 (eq org-cycle-subtree-status 'children))
3359 ;; We just showed the children, now show everything.
3360 (org-show-subtree)
3361 (message "SUBTREE")
3362 (setq org-cycle-subtree-status 'subtree)
3363 (run-hook-with-args 'org-cycle-hook 'subtree))
3364 (t
3365 ;; Default action: hide the subtree.
3366 (hide-subtree)
3367 (message "FOLDED")
3368 (setq org-cycle-subtree-status 'folded)
3369 (run-hook-with-args 'org-cycle-hook 'folded)))))
3370
3371 ;; TAB emulation
3372 (buffer-read-only (org-back-to-heading))
3373 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3374 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3375 (or (and (eq org-cycle-emulate-tab 'white)
3376 (= (match-end 0) (point-at-eol)))
3377 (and (eq org-cycle-emulate-tab 'whitestart)
3378 (>= (match-end 0) pos))))
3379 t
3380 (eq org-cycle-emulate-tab t))
3381 (if (and (looking-at "[ \n\r\t]")
3382 (string-match "^[ \t]*$" (buffer-substring
3383 (point-at-bol) (point))))
3384 (progn
3385 (beginning-of-line 1)
3386 (and (looking-at "[ \t]+") (replace-match ""))))
3387 (indent-relative))
3388
3389 (t (save-excursion
3390 (org-back-to-heading)
3391 (org-cycle))))))
3392
3393 ;;;###autoload
3394 (defun org-global-cycle (&optional arg)
3395 "Cycle the global visibility. For details see `org-cycle'."
3396 (interactive "P")
3397 (if (integerp arg)
3398 (progn
3399 (show-all)
3400 (hide-sublevels arg)
3401 (setq org-cycle-global-status 'contents))
3402 (org-cycle '(4))))
3403
3404 (defun org-overview ()
3405 "Switch to overview mode, shoing only top-level headlines.
3406 Really, this shows all headlines with level equal or greater than the level
3407 of the first headline in the buffer. This is important, because if the
3408 first headline is not level one, then (hide-sublevels 1) gives confusing
3409 results."
3410 (interactive)
3411 (hide-sublevels (save-excursion
3412 (goto-char (point-min))
3413 (if (re-search-forward (concat "^" outline-regexp) nil t)
3414 (progn
3415 (goto-char (match-beginning 0))
3416 (funcall outline-level))
3417 1))))
3418
3419 ;; FIXME: allow an argument to give a limiting level for this.
3420 (defun org-content ()
3421 "Show all headlines in the buffer, like a table of contents"
3422 (interactive)
3423 (save-excursion
3424 ;; Visit all headings and show their offspring
3425 (goto-char (point-max))
3426 (catch 'exit
3427 (while (and (progn (condition-case nil
3428 (outline-previous-visible-heading 1)
3429 (error (goto-char (point-min))))
3430 t)
3431 (looking-at outline-regexp))
3432 (show-branches)
3433 (if (bobp) (throw 'exit nil))))))
3434
3435
3436 (defun org-optimize-window-after-visibility-change (state)
3437 "Adjust the window after a change in outline visibility.
3438 This function is the default value of the hook `org-cycle-hook'."
3439 (when (get-buffer-window (current-buffer))
3440 (cond
3441 ((eq state 'overview) (org-first-headline-recenter 1))
3442 ((eq state 'content) nil)
3443 ((eq state 'all) nil)
3444 ((eq state 'folded) nil)
3445 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3446 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3447
3448 (defun org-subtree-end-visible-p ()
3449 "Is the end of the current subtree visible?"
3450 (pos-visible-in-window-p
3451 (save-excursion (org-end-of-subtree t) (point))))
3452
3453 (defun org-first-headline-recenter (&optional N)
3454 "Move cursor to the first headline and recenter the headline.
3455 Optional argument N means, put the headline into the Nth line of the window."
3456 (goto-char (point-min))
3457 (when (re-search-forward (concat "^" outline-regexp) nil t)
3458 (beginning-of-line)
3459 (recenter (prefix-numeric-value N))))
3460
3461 (defvar org-goto-window-configuration nil)
3462 (defvar org-goto-marker nil)
3463 (defvar org-goto-map (make-sparse-keymap))
3464 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3465 (while (setq cmd (pop cmds))
3466 (substitute-key-definition cmd cmd org-goto-map global-map)))
3467 (define-key org-goto-map "\C-m" 'org-goto-ret)
3468 (define-key org-goto-map [(left)] 'org-goto-left)
3469 (define-key org-goto-map [(right)] 'org-goto-right)
3470 (define-key org-goto-map [(?q)] 'org-goto-quit)
3471 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3472 (define-key org-goto-map "\C-i" 'org-cycle)
3473 (define-key org-goto-map [(tab)] 'org-cycle)
3474 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3475 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3476 (define-key org-goto-map "n" 'outline-next-visible-heading)
3477 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3478 (define-key org-goto-map "f" 'outline-forward-same-level)
3479 (define-key org-goto-map "b" 'outline-backward-same-level)
3480 (define-key org-goto-map "u" 'outline-up-heading)
3481 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3482 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3483 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3484 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3485 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3486 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3487 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3488
3489 (defconst org-goto-help
3490 "Select a location to jump to, press RET
3491 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3492
3493 (defun org-goto ()
3494 "Go to a different location of the document, keeping current visibility.
3495
3496 When you want to go to a different location in a document, the fastest way
3497 is often to fold the entire buffer and then dive into the tree. This
3498 method has the disadvantage, that the previous location will be folded,
3499 which may not be what you want.
3500
3501 This command works around this by showing a copy of the current buffer in
3502 overview mode. You can dive into the tree in that copy, to find the
3503 location you want to reach. When pressing RET, the command returns to the
3504 original buffer in which the visibility is still unchanged. It then jumps
3505 to the new location, making it and the headline hierarchy above it visible."
3506 (interactive)
3507 (let* ((org-goto-start-pos (point))
3508 (selected-point
3509 (org-get-location (current-buffer) org-goto-help)))
3510 (if selected-point
3511 (progn
3512 (org-mark-ring-push org-goto-start-pos)
3513 (goto-char selected-point)
3514 (if (or (org-invisible-p) (org-invisible-p2))
3515 (org-show-hierarchy-above)))
3516 (error "Quit"))))
3517
3518 (defun org-get-location (buf help)
3519 "Let the user select a location in the Org-mode buffer BUF.
3520 This function uses a recursive edit. It returns the selected position
3521 or nil."
3522 (let (org-selected-point)
3523 (save-excursion
3524 (save-window-excursion
3525 (delete-other-windows)
3526 (switch-to-buffer (get-buffer-create "*org-goto*"))
3527 (with-output-to-temp-buffer "*Help*"
3528 (princ help))
3529 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3530 (setq buffer-read-only nil)
3531 (erase-buffer)
3532 (insert-buffer-substring buf)
3533 (let ((org-startup-truncated t)
3534 (org-startup-folded t)
3535 (org-startup-align-all-tables nil)
3536 (org-startup-with-deadline-check nil))
3537 (org-mode))
3538 (setq buffer-read-only t)
3539 (if (boundp 'org-goto-start-pos)
3540 (goto-char org-goto-start-pos)
3541 (goto-char (point-min)))
3542 (org-beginning-of-line)
3543 (message "Select location and press RET")
3544 ;; now we make sure that during selection, ony very few keys work
3545 ;; and that it is impossible to switch to another window.
3546 (let ((gm (current-global-map))
3547 (overriding-local-map org-goto-map))
3548 (unwind-protect
3549 (progn
3550 (use-global-map org-goto-map)
3551 (recursive-edit))
3552 (use-global-map gm)))))
3553 (kill-buffer "*org-goto*")
3554 org-selected-point))
3555
3556 (defun org-goto-ret (&optional arg)
3557 "Finish `org-goto' by going to the new location."
3558 (interactive "P")
3559 (setq org-selected-point (point)
3560 current-prefix-arg arg)
3561 (throw 'exit nil))
3562
3563 (defun org-goto-left ()
3564 "Finish `org-goto' by going to the new location."
3565 (interactive)
3566 (if (org-on-heading-p)
3567 (progn
3568 (beginning-of-line 1)
3569 (setq org-selected-point (point)
3570 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3571 (throw 'exit nil))
3572 (error "Not on a heading")))
3573
3574 (defun org-goto-right ()
3575 "Finish `org-goto' by going to the new location."
3576 (interactive)
3577 (if (org-on-heading-p)
3578 (progn
3579 (outline-end-of-subtree)
3580 (or (eobp) (forward-char 1))
3581 (setq org-selected-point (point)
3582 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3583 (throw 'exit nil))
3584 (error "Not on a heading")))
3585
3586 (defun org-goto-quit ()
3587 "Finish `org-goto' without cursor motion."
3588 (interactive)
3589 (setq org-selected-point nil)
3590 (throw 'exit nil))
3591
3592 ;;; Promotion, Demotion, Inserting new headlines
3593
3594 (defvar org-ignore-region nil
3595 "To temporarily disable the active region.")
3596
3597 (defun org-insert-heading (&optional force-heading)
3598 "Insert a new heading or item with same depth at point.
3599 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3600 If point is at the beginning of a headline, insert a sibling before the
3601 current headline. If point is in the middle of a headline, split the headline
3602 at that position and make the rest of the headline part of the sibling below
3603 the current headline."
3604 (interactive "P")
3605 (if (= (buffer-size) 0)
3606 (insert "\n* ")
3607 (when (or force-heading (not (org-insert-item)))
3608 (let* ((head (save-excursion
3609 (condition-case nil
3610 (progn
3611 (org-back-to-heading)
3612 (match-string 0))
3613 (error "*"))))
3614 pos)
3615 (cond
3616 ((and (org-on-heading-p) (bolp)
3617 (save-excursion (backward-char 1) (not (org-invisible-p))))
3618 (open-line 1))
3619 ((and (bolp) (save-excursion
3620 (backward-char 1) (not (org-invisible-p))))
3621 nil)
3622 (t (newline)))
3623 (insert head) (just-one-space)
3624 (setq pos (point))
3625 (end-of-line 1)
3626 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3627 (run-hooks 'org-insert-heading-hook)))))
3628
3629 (defun org-insert-item (&optional checkbox)
3630 "Insert a new item at the current level.
3631 Return t when things worked, nil when we are not in an item."
3632 (when (save-excursion
3633 (condition-case nil
3634 (progn
3635 (org-beginning-of-item)
3636 (org-at-item-p)
3637 t)
3638 (error nil)))
3639 (let* ((bul (match-string 0))
3640 (end (match-end 0))
3641 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3642 (match-end 0)))
3643 (eowcol (save-excursion (goto-char eow) (current-column)))
3644 pos)
3645 (cond
3646 ((and (org-at-item-p) (<= (point) eow))
3647 ;; before the bullet
3648 (beginning-of-line 1)
3649 (open-line 1))
3650 ((<= (point) eow)
3651 (beginning-of-line 1))
3652 (t (newline)))
3653 (insert bul (if checkbox "[ ]" ""))
3654 (just-one-space)
3655 (setq pos (point))
3656 (end-of-line 1)
3657 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3658 (org-maybe-renumber-ordered-list)
3659 t))
3660
3661 (defun org-insert-todo-heading (arg)
3662 "Insert a new heading with the same level and TODO state as current heading.
3663 If the heading has no TODO state, or if the state is DONE, use the first
3664 state (TODO by default). Also with prefix arg, force first state."
3665 (interactive "P")
3666 (when (not (org-insert-item 'checkbox))
3667 (org-insert-heading)
3668 (save-excursion
3669 (org-back-to-heading)
3670 (if org-noutline-p
3671 (outline-previous-heading)
3672 (outline-previous-visible-heading t))
3673 (looking-at org-todo-line-regexp))
3674 (if (or arg
3675 (not (match-beginning 2))
3676 (equal (match-string 2) org-done-string))
3677 (insert (car org-todo-keywords) " ")
3678 (insert (match-string 2) " "))))
3679
3680 (defun org-promote-subtree ()
3681 "Promote the entire subtree.
3682 See also `org-promote'."
3683 (interactive)
3684 (save-excursion
3685 (org-map-tree 'org-promote)))
3686
3687 (defun org-demote-subtree ()
3688 "Demote the entire subtree. See `org-demote'.
3689 See also `org-promote'."
3690 (interactive)
3691 (save-excursion
3692 (org-map-tree 'org-demote)))
3693
3694 (defun org-do-promote ()
3695 "Promote the current heading higher up the tree.
3696 If the region is active in `transient-mark-mode', promote all headings
3697 in the region."
3698 (interactive)
3699 (save-excursion
3700 (if (org-region-active-p)
3701 (org-map-region 'org-promote (region-beginning) (region-end))
3702 (org-promote)))
3703 (org-fix-position-after-promote))
3704
3705 (defun org-do-demote ()
3706 "Demote the current heading lower down the tree.
3707 If the region is active in `transient-mark-mode', demote all headings
3708 in the region."
3709 (interactive)
3710 (save-excursion
3711 (if (org-region-active-p)
3712 (org-map-region 'org-demote (region-beginning) (region-end))
3713 (org-demote)))
3714 (org-fix-position-after-promote))
3715
3716 (defun org-fix-position-after-promote ()
3717 "Make sure that after pro/demotion cursor position is right."
3718 (and (equal (char-after) ?\ )
3719 (equal (char-before) ?*)
3720 (forward-char 1)))
3721
3722 (defun org-get-legal-level (level change)
3723 "Rectify a level change under the influence of `org-odd-levels-only'
3724 LEVEL is a current level, CHANGE is by how much the level should be
3725 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3726 even level numbers will become the next higher odd number."
3727 (if org-odd-levels-only
3728 (cond ((not change) (1+ (* 2 (/ level 2))))
3729 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3730 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3731 (max 1 (+ level change))))
3732
3733 (defun org-promote ()
3734 "Promote the current heading higher up the tree.
3735 If the region is active in `transient-mark-mode', promote all headings
3736 in the region."
3737 (org-back-to-heading t)
3738 (let* ((level (save-match-data (funcall outline-level)))
3739 (up-head (make-string (org-get-legal-level level -1) ?*))
3740 (diff (abs (- level (length up-head)))))
3741 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3742 (replace-match up-head nil t)
3743 ;; Fixup tag positioning
3744 (and org-auto-align-tags (org-set-tags nil t))
3745 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
3746
3747 (defun org-demote ()
3748 "Demote the current heading lower down the tree.
3749 If the region is active in `transient-mark-mode', demote all headings
3750 in the region."
3751 (org-back-to-heading t)
3752 (let* ((level (save-match-data (funcall outline-level)))
3753 (down-head (make-string (org-get-legal-level level 1) ?*))
3754 (diff (abs (- level (length down-head)))))
3755 (replace-match down-head nil t)
3756 ;; Fixup tag positioning
3757 (and org-auto-align-tags (org-set-tags nil t))
3758 (if org-adapt-indentation (org-fixup-indentation diff))))
3759
3760 (defun org-map-tree (fun)
3761 "Call FUN for every heading underneath the current one."
3762 (org-back-to-heading)
3763 (let ((level (funcall outline-level)))
3764 (save-excursion
3765 (funcall fun)
3766 (while (and (progn
3767 (outline-next-heading)
3768 (> (funcall outline-level) level))
3769 (not (eobp)))
3770 (funcall fun)))))
3771
3772 (defun org-map-region (fun beg end)
3773 "Call FUN for every heading between BEG and END."
3774 (let ((org-ignore-region t))
3775 (save-excursion
3776 (setq end (copy-marker end))
3777 (goto-char beg)
3778 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3779 (< (point) end))
3780 (funcall fun))
3781 (while (and (progn
3782 (outline-next-heading)
3783 (< (point) end))
3784 (not (eobp)))
3785 (funcall fun)))))
3786
3787 (defun org-fixup-indentation (diff)
3788 "Change the indentation in the current entry by DIFF
3789 However, if any line in the current entry has no indentation, or if it
3790 would end up with no indentation after the change, nothing at all is done."
3791 (save-excursion
3792 (let ((end (save-excursion (outline-next-heading)
3793 (point-marker)))
3794 (prohibit (if (> diff 0)
3795 "^\\S-"
3796 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
3797 col)
3798 (unless (save-excursion (re-search-forward prohibit end t))
3799 (while (re-search-forward "^[ \t]+" end t)
3800 (goto-char (match-end 0))
3801 (setq col (current-column))
3802 (if (< diff 0) (replace-match ""))
3803 (indent-to (+ diff col))))
3804 (move-marker end nil))))
3805
3806 ;;; Vertical tree motion, cutting and pasting of subtrees
3807
3808 (defun org-move-subtree-up (&optional arg)
3809 "Move the current subtree up past ARG headlines of the same level."
3810 (interactive "p")
3811 (org-move-subtree-down (- (prefix-numeric-value arg))))
3812
3813 (defun org-move-subtree-down (&optional arg)
3814 "Move the current subtree down past ARG headlines of the same level."
3815 (interactive "p")
3816 (setq arg (prefix-numeric-value arg))
3817 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3818 'outline-get-last-sibling))
3819 (ins-point (make-marker))
3820 (cnt (abs arg))
3821 beg end txt folded)
3822 ;; Select the tree
3823 (org-back-to-heading)
3824 (setq beg (point))
3825 (save-match-data
3826 (save-excursion (outline-end-of-heading)
3827 (setq folded (org-invisible-p)))
3828 (outline-end-of-subtree))
3829 (outline-next-heading)
3830 (setq end (point))
3831 ;; Find insertion point, with error handling
3832 (goto-char beg)
3833 (while (> cnt 0)
3834 (or (and (funcall movfunc) (looking-at outline-regexp))
3835 (progn (goto-char beg)
3836 (error "Cannot move past superior level or buffer limit")))
3837 (setq cnt (1- cnt)))
3838 (if (> arg 0)
3839 ;; Moving forward - still need to move over subtree
3840 (progn (outline-end-of-subtree)
3841 (outline-next-heading)
3842 (if (not (or (looking-at (concat "^" outline-regexp))
3843 (bolp)))
3844 (newline))))
3845 (move-marker ins-point (point))
3846 (setq txt (buffer-substring beg end))
3847 (delete-region beg end)
3848 (insert txt)
3849 (goto-char ins-point)
3850 (if folded (hide-subtree))
3851 (move-marker ins-point nil)))
3852
3853 (defvar org-subtree-clip ""
3854 "Clipboard for cut and paste of subtrees.
3855 This is actually only a copy of the kill, because we use the normal kill
3856 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3857
3858 (defvar org-subtree-clip-folded nil
3859 "Was the last copied subtree folded?
3860 This is used to fold the tree back after pasting.")
3861
3862 (defun org-cut-subtree ()
3863 "Cut the current subtree into the clipboard.
3864 This is a short-hand for marking the subtree and then cutting it."
3865 (interactive)
3866 (org-copy-subtree 'cut))
3867
3868 (defun org-copy-subtree (&optional cut)
3869 "Cut the current subtree into the clipboard.
3870 This is a short-hand for marking the subtree and then copying it.
3871 If CUT is non nil, actually cut the subtree."
3872 (interactive)
3873 (let (beg end folded)
3874 (org-back-to-heading)
3875 (setq beg (point))
3876 (save-match-data
3877 (save-excursion (outline-end-of-heading)
3878 (setq folded (org-invisible-p)))
3879 (outline-end-of-subtree))
3880 (if (equal (char-after) ?\n) (forward-char 1))
3881 (setq end (point))
3882 (goto-char beg)
3883 (when (> end beg)
3884 (setq org-subtree-clip-folded folded)
3885 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3886 (setq org-subtree-clip (current-kill 0))
3887 (message "%s: Subtree with %d characters"
3888 (if cut "Cut" "Copied")
3889 (length org-subtree-clip)))))
3890
3891 (defun org-paste-subtree (&optional level tree)
3892 "Paste the clipboard as a subtree, with modification of headline level.
3893 The entire subtree is promoted or demoted in order to match a new headline
3894 level. By default, the new level is derived from the visible headings
3895 before and after the insertion point, and taken to be the inferior headline
3896 level of the two. So if the previous visible heading is level 3 and the
3897 next is level 4 (or vice versa), level 4 will be used for insertion.
3898 This makes sure that the subtree remains an independent subtree and does
3899 not swallow low level entries.
3900
3901 You can also force a different level, either by using a numeric prefix
3902 argument, or by inserting the heading marker by hand. For example, if the
3903 cursor is after \"*****\", then the tree will be shifted to level 5.
3904
3905 If you want to insert the tree as is, just use \\[yank].
3906
3907 If optional TREE is given, use this text instead of the kill ring."
3908 (interactive "P")
3909 (unless (org-kill-is-subtree-p tree)
3910 (error
3911 (substitute-command-keys
3912 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3913 (let* ((txt (or tree (and kill-ring (current-kill 0))))
3914 (^re (concat "^\\(" outline-regexp "\\)"))
3915 (re (concat "\\(" outline-regexp "\\)"))
3916 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3917
3918 (old-level (if (string-match ^re txt)
3919 (- (match-end 0) (match-beginning 0))
3920 -1))
3921 (force-level (cond (level (prefix-numeric-value level))
3922 ((string-match
3923 ^re_ (buffer-substring (point-at-bol) (point)))
3924 (- (match-end 0) (match-beginning 0)))
3925 (t nil)))
3926 (previous-level (save-excursion
3927 (condition-case nil
3928 (progn
3929 (outline-previous-visible-heading 1)
3930 (if (looking-at re)
3931 (- (match-end 0) (match-beginning 0))
3932 1))
3933 (error 1))))
3934 (next-level (save-excursion
3935 (condition-case nil
3936 (progn
3937 (outline-next-visible-heading 1)
3938 (if (looking-at re)
3939 (- (match-end 0) (match-beginning 0))
3940 1))
3941 (error 1))))
3942 (new-level (or force-level (max previous-level next-level)))
3943 (shift (if (or (= old-level -1)
3944 (= new-level -1)
3945 (= old-level new-level))
3946 0
3947 (- new-level old-level)))
3948 (shift1 shift)
3949 (delta (if (> shift 0) -1 1))
3950 (func (if (> shift 0) 'org-demote 'org-promote))
3951 (org-odd-levels-only nil)
3952 beg end)
3953 ;; Remove the forces level indicator
3954 (if force-level
3955 (delete-region (point-at-bol) (point)))
3956 ;; Make sure we start at the beginning of an empty line
3957 (if (not (bolp)) (insert "\n"))
3958 (if (not (looking-at "[ \t]*$"))
3959 (progn (insert "\n") (backward-char 1)))
3960 ;; Paste
3961 (setq beg (point))
3962 (if (string-match "[ \t\r\n]+\\'" txt)
3963 (setq txt (replace-match "\n" t t txt)))
3964 (insert txt)
3965 (setq end (point))
3966 (if (looking-at "[ \t\r\n]+")
3967 (replace-match "\n"))
3968 (goto-char beg)
3969 ;; Shift if necessary
3970 (if (= shift 0)
3971 (message "Pasted at level %d, without shift" new-level)
3972 (save-restriction
3973 (narrow-to-region beg end)
3974 (while (not (= shift 0))
3975 (org-map-region func (point-min) (point-max))
3976 (setq shift (+ delta shift)))
3977 (goto-char (point-min))
3978 (message "Pasted at level %d, with shift by %d levels"
3979 new-level shift1)))
3980 (if (and kill-ring
3981 (eq org-subtree-clip (current-kill 0))
3982 org-subtree-clip-folded)
3983 ;; The tree was folded before it was killed/copied
3984 (hide-subtree))))
3985
3986 (defun org-kill-is-subtree-p (&optional txt)
3987 "Check if the current kill is an outline subtree, or a set of trees.
3988 Returns nil if kill does not start with a headline, or if the first
3989 headline level is not the largest headline level in the tree.
3990 So this will actually accept several entries of equal levels as well,
3991 which is OK for `org-paste-subtree'.
3992 If optional TXT is given, check this string instead of the current kill."
3993 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
3994 (start-level (and kill
3995 (string-match (concat "\\`" outline-regexp) kill)
3996 (- (match-end 0) (match-beginning 0))))
3997 (re (concat "^" outline-regexp))
3998 (start 1))
3999 (if (not start-level)
4000 nil ;; does not even start with a heading
4001 (catch 'exit
4002 (while (setq start (string-match re kill (1+ start)))
4003 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4004 (throw 'exit nil)))
4005 t))))
4006
4007 (defun org-narrow-to-subtree ()
4008 "Narrow buffer to the current subtree."
4009 (interactive)
4010 (save-excursion
4011 (narrow-to-region
4012 (progn (org-back-to-heading) (point))
4013 (progn (org-end-of-subtree t) (point)))))
4014
4015 ;;; Plain list items
4016
4017 (defun org-at-item-p ()
4018 "Is point in a line starting a hand-formatted item?"
4019 (let ((llt org-plain-list-ordered-item-terminator))
4020 (save-excursion
4021 (goto-char (point-at-bol))
4022 (looking-at
4023 (cond
4024 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4025 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4026 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4027 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4028
4029 (defun org-at-item-checkbox-p ()
4030 "Is point at a line starting a plain-list item with a checklet?"
4031 (and (org-at-item-p)
4032 (save-excursion
4033 (goto-char (match-end 0))
4034 (skip-chars-forward " \t")
4035 (looking-at "\\[[ X]\\]"))))
4036
4037 (defun org-toggle-checkbox ()
4038 "Toggle the checkbox in the current line."
4039 (interactive)
4040 (save-excursion
4041 (if (org-at-item-checkbox-p)
4042 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))))
4043
4044 (defun org-get-indentation (&optional line)
4045 "Get the indentation of the current line, interpreting tabs.
4046 When LINE is given, assume it represents a line and compute its indentation."
4047 (if line
4048 (if (string-match "^ *" (org-remove-tabs line))
4049 (match-end 0))
4050 (save-excursion
4051 (beginning-of-line 1)
4052 (skip-chars-forward " \t")
4053 (current-column))))
4054
4055 (defun org-remove-tabs (s &optional width)
4056 "Replace tabulators in S with spaces.
4057 Assumes that s is a single line, starting in column 0."
4058 (setq width (or width tab-width))
4059 (while (string-match "\t" s)
4060 (setq s (replace-match
4061 (make-string
4062 (- (* width (/ (+ (match-beginning 0) width) width))
4063 (match-beginning 0)) ?\ )
4064 t t s)))
4065 s)
4066
4067 ;; FIXME: document properly.
4068 (defun org-fix-indentation (line ind)
4069 "If the current indenation is smaller than ind1, leave it alone.
4070 If it is larger than ind, reduce it by ind."
4071 (let* ((l (org-remove-tabs line))
4072 (i (org-get-indentation l))
4073 (i1 (car ind)) (i2 (cdr ind)))
4074 (if (>= i i2) (setq l (substring line i2)))
4075 (if (> i1 0)
4076 (concat (make-string i1 ?\ ) l)
4077 l)))
4078
4079 (defun org-beginning-of-item ()
4080 "Go to the beginning of the current hand-formatted item.
4081 If the cursor is not in an item, throw an error."
4082 (interactive)
4083 (let ((pos (point))
4084 (limit (save-excursion (org-back-to-heading)
4085 (beginning-of-line 2) (point)))
4086 ind ind1)
4087 (if (org-at-item-p)
4088 (beginning-of-line 1)
4089 (beginning-of-line 1)
4090 (skip-chars-forward " \t")
4091 (setq ind (current-column))
4092 (if (catch 'exit
4093 (while t
4094 (beginning-of-line 0)
4095 (if (< (point) limit) (throw 'exit nil))
4096 (unless (looking-at " \t]*$")
4097 (skip-chars-forward " \t")
4098 (setq ind1 (current-column))
4099 (if (< ind1 ind)
4100 (throw 'exit (org-at-item-p))))))
4101 nil
4102 (goto-char pos)
4103 (error "Not in an item")))))
4104
4105 (defun org-end-of-item ()
4106 "Go to the end of the current hand-formatted item.
4107 If the cursor is not in an item, throw an error."
4108 (interactive)
4109 (let ((pos (point))
4110 (limit (save-excursion (outline-next-heading) (point)))
4111 (ind (save-excursion
4112 (org-beginning-of-item)
4113 (skip-chars-forward " \t")
4114 (current-column)))
4115 ind1)
4116 (if (catch 'exit
4117 (while t
4118 (beginning-of-line 2)
4119 (if (>= (point) limit) (throw 'exit t))
4120 (unless (looking-at "[ \t]*$")
4121 (skip-chars-forward " \t")
4122 (setq ind1 (current-column))
4123 (if (<= ind1 ind) (throw 'exit t)))))
4124 (beginning-of-line 1)
4125 (goto-char pos)
4126 (error "Not in an item"))))
4127
4128 (defun org-next-item ()
4129 "Move to the beginning of the next item in the current plain list.
4130 Error if not at a plain list, or if this is the last item in the list."
4131 (interactive)
4132 (let (beg end ind ind1 (pos (point)) txt)
4133 (org-beginning-of-item)
4134 (setq beg (point))
4135 (setq ind (org-get-indentation))
4136 (org-end-of-item)
4137 (setq end (point))
4138 (setq ind1 (org-get-indentation))
4139 (unless (and (org-at-item-p) (= ind ind1))
4140 (goto-char pos)
4141 (error "On last item"))))
4142
4143 (defun org-previous-item ()
4144 "Move to the beginning of the previous item in the current plain list.
4145 Error if not at a plain list, or if this is the last item in the list."
4146 (interactive)
4147 (let (beg end ind ind1 (pos (point)) txt)
4148 (org-beginning-of-item)
4149 (setq beg (point))
4150 (setq ind (org-get-indentation))
4151 (goto-char beg)
4152 (catch 'exit
4153 (while t
4154 (beginning-of-line 0)
4155 (if (looking-at "[ \t]*$")
4156 nil
4157 (if (<= (setq ind1 (org-get-indentation)) ind)
4158 (throw 'exit t)))))
4159 (condition-case nil
4160 (org-beginning-of-item)
4161 (error (goto-char pos)
4162 (error "On first item")))))
4163
4164 (defun org-move-item-down ()
4165 "Move the plain list item at point down, i.e. swap with following item.
4166 Subitems (items with larger indentation) are considered part of the item,
4167 so this really moves item trees."
4168 (interactive)
4169 (let (beg end ind ind1 (pos (point)) txt)
4170 (org-beginning-of-item)
4171 (setq beg (point))
4172 (setq ind (org-get-indentation))
4173 (org-end-of-item)
4174 (setq end (point))
4175 (setq ind1 (org-get-indentation))
4176 (if (and (org-at-item-p) (= ind ind1))
4177 (progn
4178 (org-end-of-item)
4179 (setq txt (buffer-substring beg end))
4180 (save-excursion
4181 (delete-region beg end))
4182 (setq pos (point))
4183 (insert txt)
4184 (goto-char pos)
4185 (org-maybe-renumber-ordered-list))
4186 (goto-char pos)
4187 (error "Cannot move this item further down"))))
4188
4189 (defun org-move-item-up (arg)
4190 "Move the plain list item at point up, i.e. swap with previous item.
4191 Subitems (items with larger indentation) are considered part of the item,
4192 so this really moves item trees."
4193 (interactive "p")
4194 (let (beg end ind ind1 (pos (point)) txt)
4195 (org-beginning-of-item)
4196 (setq beg (point))
4197 (setq ind (org-get-indentation))
4198 (org-end-of-item)
4199 (setq end (point))
4200 (goto-char beg)
4201 (catch 'exit
4202 (while t
4203 (beginning-of-line 0)
4204 (if (looking-at "[ \t]*$")
4205 nil
4206 (if (<= (setq ind1 (org-get-indentation)) ind)
4207 (throw 'exit t)))))
4208 (condition-case nil
4209 (org-beginning-of-item)
4210 (error (goto-char beg)
4211 (error "Cannot move this item further up")))
4212 (setq ind1 (org-get-indentation))
4213 (if (and (org-at-item-p) (= ind ind1))
4214 (progn
4215 (setq txt (buffer-substring beg end))
4216 (save-excursion
4217 (delete-region beg end))
4218 (setq pos (point))
4219 (insert txt)
4220 (goto-char pos)
4221 (org-maybe-renumber-ordered-list))
4222 (goto-char pos)
4223 (error "Cannot move this item further up"))))
4224
4225 (defun org-maybe-renumber-ordered-list ()
4226 "Renumber the ordered list at point if setup allows it.
4227 This tests the user option `org-auto-renumber-ordered-lists' before
4228 doing the renumbering."
4229 (and org-auto-renumber-ordered-lists
4230 (org-at-item-p)
4231 (match-beginning 3)
4232 (org-renumber-ordered-list 1)))
4233
4234 (defun org-get-string-indentation (s)
4235 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4236 (let ((n -1) (i 0) (w tab-width) c)
4237 (catch 'exit
4238 (while (< (setq n (1+ n)) (length s))
4239 (setq c (aref s n))
4240 (cond ((= c ?\ ) (setq i (1+ i)))
4241 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4242 (t (throw 'exit t)))))
4243 i))
4244
4245 (defun org-renumber-ordered-list (arg)
4246 "Renumber an ordered plain list.
4247 Cursor needs to be in the first line of an item, the line that starts
4248 with something like \"1.\" or \"2)\"."
4249 (interactive "p")
4250 (unless (and (org-at-item-p)
4251 (match-beginning 3))
4252 (error "This is not an ordered list"))
4253 (let ((line (org-current-line))
4254 (col (current-column))
4255 (ind (org-get-string-indentation
4256 (buffer-substring (point-at-bol) (match-beginning 3))))
4257 ;; (term (substring (match-string 3) -1))
4258 ind1 (n (1- arg)))
4259 ;; find where this list begins
4260 (catch 'exit
4261 (while t
4262 (catch 'next
4263 (beginning-of-line 0)
4264 (if (looking-at "[ \t]*$") (throw 'next t))
4265 (skip-chars-forward " \t") (setq ind1 (current-column))
4266 (if (or (< ind1 ind)
4267 (and (= ind1 ind)
4268 (not (org-at-item-p))))
4269 (throw 'exit t)))))
4270 ;; Walk forward and replace these numbers
4271 (catch 'exit
4272 (while t
4273 (catch 'next
4274 (beginning-of-line 2)
4275 (if (eobp) (throw 'exit nil))
4276 (if (looking-at "[ \t]*$") (throw 'next nil))
4277 (skip-chars-forward " \t") (setq ind1 (current-column))
4278 (if (> ind1 ind) (throw 'next t))
4279 (if (< ind1 ind) (throw 'exit t))
4280 (if (not (org-at-item-p)) (throw 'exit nil))
4281 (if (not (match-beginning 3))
4282 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4283 (delete-region (match-beginning 3) (1- (match-end 3)))
4284 (goto-char (match-beginning 3))
4285 (insert (format "%d" (setq n (1+ n)))))))
4286 (goto-line line)
4287 (move-to-column col)))
4288
4289 (defvar org-last-indent-begin-marker (make-marker))
4290 (defvar org-last-indent-end-marker (make-marker))
4291
4292 (defun org-outdent-item (arg)
4293 "Outdent a local list item."
4294 (interactive "p")
4295 (org-indent-item (- arg)))
4296
4297 (defun org-indent-item (arg)
4298 "Indent a local list item."
4299 (interactive "p")
4300 (unless (org-at-item-p)
4301 (error "Not on an item"))
4302 (save-excursion
4303 (let (beg end ind ind1)
4304 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4305 (setq beg org-last-indent-begin-marker
4306 end org-last-indent-end-marker)
4307 (org-beginning-of-item)
4308 (setq beg (move-marker org-last-indent-begin-marker (point)))
4309 (org-end-of-item)
4310 (setq end (move-marker org-last-indent-end-marker (point))))
4311 (goto-char beg)
4312 (skip-chars-forward " \t") (setq ind (current-column))
4313 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4314 (while (< (point) end)
4315 (beginning-of-line 1)
4316 (skip-chars-forward " \t") (setq ind1 (current-column))
4317 (delete-region (point-at-bol) (point))
4318 (indent-to-column (+ ind1 arg))
4319 (beginning-of-line 2)))))
4320
4321 ;;; Archiving
4322
4323 (defun org-archive-subtree (&optional find-done)
4324 "Move the current subtree to the archive.
4325 The archive can be a certain top-level heading in the current file, or in
4326 a different file. The tree will be moved to that location, the subtree
4327 heading be marked DONE, and the current time will be added.
4328
4329 When called with prefix argument FIND-DONE, find whole trees without any
4330 open TODO items and archive them (after getting confirmation from the user).
4331 If the cursor is not at a headline when this comand is called, try all level
4332 1 trees. If the cursor is on a headline, only try the direct children of
4333 this heading. "
4334 (interactive "P")
4335 (if find-done
4336 (org-archive-all-done)
4337 ;; Save all relevant TODO keyword-relatex variables
4338
4339 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4340 (tr-org-todo-keywords org-todo-keywords)
4341 (tr-org-todo-interpretation org-todo-interpretation)
4342 (tr-org-done-string org-done-string)
4343 (tr-org-todo-regexp org-todo-regexp)
4344 (tr-org-todo-line-regexp org-todo-line-regexp)
4345 (this-buffer (current-buffer))
4346 file heading buffer level newfile-p)
4347 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4348 (progn
4349 (setq file (format (match-string 1 org-archive-location)
4350 (file-name-nondirectory buffer-file-name))
4351 heading (match-string 2 org-archive-location)))
4352 (error "Invalid `org-archive-location'"))
4353 (if (> (length file) 0)
4354 (setq newfile-p (not (file-exists-p file))
4355 buffer (find-file-noselect file))
4356 (setq buffer (current-buffer)))
4357 (unless buffer
4358 (error "Cannot access file \"%s\"" file))
4359 (if (and (> (length heading) 0)
4360 (string-match "^\\*+" heading))
4361 (setq level (match-end 0))
4362 (setq heading nil level 0))
4363 (save-excursion
4364 ;; We first only copy, in case something goes wrong
4365 ;; we need to protect this-command, to avoid kill-region sets it,
4366 ;; which would lead to duplication of subtrees
4367 (let (this-command) (org-copy-subtree))
4368 (set-buffer buffer)
4369 ;; Enforce org-mode for the archive buffer
4370 (if (not (eq major-mode 'org-mode))
4371 ;; Force the mode for future visits.
4372 (let ((org-insert-mode-line-in-empty-file t))
4373 (call-interactively 'org-mode)))
4374 (when newfile-p
4375 (goto-char (point-max))
4376 (insert (format "\nArchived entries from file %s\n\n"
4377 (buffer-file-name this-buffer))))
4378 ;; Force the TODO keywords of the original buffer
4379 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4380 (org-todo-keywords tr-org-todo-keywords)
4381 (org-todo-interpretation tr-org-todo-interpretation)
4382 (org-done-string tr-org-done-string)
4383 (org-todo-regexp tr-org-todo-regexp)
4384 (org-todo-line-regexp tr-org-todo-line-regexp))
4385 (goto-char (point-min))
4386 (if heading
4387 (progn
4388 (if (re-search-forward
4389 (concat "\\(^\\|\r\\)"
4390 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4391 nil t)
4392 (goto-char (match-end 0))
4393 ;; Heading not found, just insert it at the end
4394 (goto-char (point-max))
4395 (or (bolp) (insert "\n"))
4396 (insert "\n" heading "\n")
4397 (end-of-line 0))
4398 ;; Make the subtree visible
4399 (show-subtree)
4400 (org-end-of-subtree t)
4401 (skip-chars-backward " \t\r\n]")
4402 (and (looking-at "[ \t\r\n]*")
4403 (replace-match "\n\n")))
4404 ;; No specific heading, just go to end of file.
4405 (goto-char (point-max)) (insert "\n"))
4406 ;; Paste
4407 (org-paste-subtree (1+ level))
4408 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4409 (if org-archive-mark-done
4410 (org-todo (length org-todo-keywords)))
4411 ;; Move cursor to right after the TODO keyword
4412 (when org-archive-stamp-time
4413 (beginning-of-line 1)
4414 (looking-at org-todo-line-regexp)
4415 (goto-char (or (match-end 2) (match-beginning 3)))
4416 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4417 (org-current-time))
4418 ")"))
4419 ;; Save the buffer, if it is not the same buffer.
4420 (if (not (eq this-buffer buffer)) (save-buffer))))
4421 ;; Here we are back in the original buffer. Everything seems to have
4422 ;; worked. So now cut the tree and finish up.
4423 (let (this-command) (org-cut-subtree))
4424 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4425 (message "Subtree archived %s"
4426 (if (eq this-buffer buffer)
4427 (concat "under heading: " heading)
4428 (concat "in file: " (abbreviate-file-name file)))))))
4429
4430 (defun org-archive-all-done ()
4431 "Archive sublevels of the current tree without open TODO items.
4432 If the cursor is not on a headline, try all level 1 trees. If
4433 it is on a headline, try all direct children."
4434 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4435 (begm (make-marker))
4436 (endm (make-marker))
4437 beg end (cntarch 0))
4438 (if (org-on-heading-p)
4439 (progn
4440 (setq re1 (concat "^" (regexp-quote
4441 (make-string
4442 (1+ (- (match-end 0) (match-beginning 0)))
4443 ?*))
4444 " "))
4445 (move-marker begm (point))
4446 (move-marker endm (org-end-of-subtree)))
4447 (setq re1 "^* ")
4448 (move-marker begm (point-min))
4449 (move-marker endm (point-max)))
4450 (save-excursion
4451 (goto-char begm)
4452 (while (re-search-forward re1 endm t)
4453 beg (match-beginning 0)
4454 end (save-excursion (org-end-of-subtree t) (point)))
4455 (goto-char beg)
4456 (if (re-search-forward re end t)
4457 (goto-char end)
4458 (goto-char beg)
4459 (if (y-or-n-p "Archive this subtree (no open TODO items)? ")
4460 (progn
4461 (org-archive-subtree)
4462 (setq cntarch (1+ cntarch)))
4463 (goto-char end))))
4464 (message "%d trees archived" cntarch)))
4465
4466 ;;; Dynamic blocks
4467
4468 (defun org-find-dblock (name)
4469 "Find the first dynamic block with name NAME in the buffer.
4470 If not found, stay at current position and return nil."
4471 (let (pos)
4472 (save-excursion
4473 (goto-char (point-min))
4474 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
4475 nil t)
4476 (match-beginning 0))))
4477 (if pos (goto-char pos))
4478 pos))
4479
4480 (defconst org-dblock-start-re
4481 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)[ \t]+\\(.*\\)"
4482 "Matches the startline of a dynamic block, with parameters.")
4483
4484 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
4485 "Matches the end of a dyhamic block.")
4486
4487 (defun org-create-dblock (plist)
4488 "Create a dynamic block section, with parameters taken from PLIST.
4489 PLIST must containe a :name entry which is used as name of the block."
4490 (unless (bolp) (newline))
4491 (let ((name (plist-get plist :name)))
4492 (insert "#+BEGIN: " name)
4493 (while plist
4494 (if (eq (car plist) :name)
4495 (setq plist (cddr plist))
4496 (insert " " (prin1-to-string (pop plist)))))
4497 (insert "\n\n#+END:\n")
4498 (beginning-of-line -2)))
4499
4500 (defun org-prepare-dblock ()
4501 "Prepare dynamic block for refresh.
4502 This empties the block, puts the cursor at the insert position and returns
4503 the property list including an extra property :name with the block name."
4504 (unless (looking-at org-dblock-start-re)
4505 (error "Not at a dynamic block"))
4506 (let* ((beg (match-beginning 0))
4507 (begdel (1+ (match-end 0)))
4508 (name (match-string 1))
4509 (params (append (list :name name)
4510 (read (concat "(" (match-string 2) ")")))))
4511 (unless (re-search-forward org-dblock-end-re nil t)
4512 (error "Dynamic block not terminated"))
4513 (delete-region begdel (match-beginning 0))
4514 (goto-char begdel)
4515 (open-line 1)
4516 params))
4517
4518 (defun org-map-dblocks (&optional command)
4519 "Apply COMMAND to all dynamic blocks in the current buffer.
4520 If COMMAND is not given, use `org-update-dblock'."
4521 (let ((cmd (or command 'org-update-dblock))
4522 pos)
4523 (save-excursion
4524 (goto-char (point-min))
4525 (while (re-search-forward org-dblock-start-re nil t)
4526 (goto-char (setq pos (match-beginning 0)))
4527 (condition-case nil
4528 (funcall cmd)
4529 (error (message "Error during update of dynamic block")))
4530 (goto-char pos)
4531 (unless (re-search-forward org-dblock-end-re nil t)
4532 (error "Dynamic block not terminated"))))))
4533
4534 (defun org-dblock-update (&optional arg)
4535 "User command for updating dynamic blocks.
4536 Update the dynamic block at point. With prefix ARG, update all dynamic
4537 blocks in the buffer."
4538 (interactive "P")
4539 (if arg
4540 (org-update-all-dblocks)
4541 (or (looking-at org-dblock-start-re)
4542 (org-beginning-of-dblock))
4543 (org-update-dblock)))
4544
4545 (defun org-update-dblock ()
4546 "Update the dynamic block at point
4547 This means to empty the block, parse for parameters and then call
4548 the correct writing function."
4549 (let* ((pos (point))
4550 (params (org-prepare-dblock))
4551 (name (plist-get params :name))
4552 (cmd (intern (concat "org-dblock-write:" name))))
4553 (funcall cmd params)
4554 (goto-char pos)))
4555
4556 (defun org-beginning-of-dblock ()
4557 "Find the beginning of the dynamic block at point.
4558 Error if there is no scuh block at point."
4559 (let ((pos (point))
4560 beg end)
4561 (end-of-line 1)
4562 (if (and (re-search-backward org-dblock-start-re nil t)
4563 (setq beg (match-beginning 0))
4564 (re-search-forward org-dblock-end-re nil t)
4565 (> (match-end 0) pos))
4566 (goto-char beg)
4567 (goto-char pos)
4568 (error "Not in a dynamic block"))))
4569
4570 (defun org-update-all-dblocks ()
4571 "Update all dynamic blocks in the buffer.
4572 This function can be used in a hook."
4573 (when (eq major-mode 'org-mode)
4574 (org-map-dblocks 'org-update-dblock)))
4575
4576
4577 ;;; Completion
4578
4579 (defun org-complete (&optional arg)
4580 "Perform completion on word at point.
4581 At the beginning of a headline, this completes TODO keywords as given in
4582 `org-todo-keywords'.
4583 If the current word is preceded by a backslash, completes the TeX symbols
4584 that are supported for HTML support.
4585 If the current word is preceded by \"#+\", completes special words for
4586 setting file options.
4587 At all other locations, this simply calls `ispell-complete-word'."
4588 (interactive "P")
4589 (catch 'exit
4590 (let* ((end (point))
4591 (beg1 (save-excursion
4592 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4593 (skip-chars-backward "a-zA-Z_@0-9")
4594 (point)))
4595 (beg (save-excursion
4596 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4597 (skip-chars-backward "a-zA-Z0-9_:$")
4598 (point)))
4599 (confirm (lambda (x) (stringp (car x))))
4600 (camel (equal (char-before beg) ?*))
4601 (tag (equal (char-before beg1) ?:))
4602 (texp (equal (char-before beg) ?\\))
4603 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
4604 beg)
4605 "#+"))
4606 (completion-ignore-case opt)
4607 (type nil)
4608 (tbl nil)
4609 (table (cond
4610 (opt
4611 (setq type :opt)
4612 (mapcar (lambda (x)
4613 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
4614 (cons (match-string 2 x) (match-string 1 x)))
4615 (org-split-string (org-get-current-options) "\n")))
4616 (texp
4617 (setq type :tex)
4618 org-html-entities)
4619 ((string-match "\\`\\*+[ \t]*\\'"
4620 (buffer-substring (point-at-bol) beg))
4621 (setq type :todo)
4622 (mapcar 'list org-todo-keywords))
4623 (camel
4624 (setq type :camel)
4625 (save-excursion
4626 (goto-char (point-min))
4627 (while (re-search-forward org-todo-line-regexp nil t)
4628 (push (list
4629 (if org-file-link-context-use-camel-case
4630 (org-make-org-heading-camel (match-string 3) t)
4631 (org-make-org-heading-search-string
4632 (match-string 3) t)))
4633 tbl)))
4634 tbl)
4635 (tag (setq type :tag beg beg1)
4636 (or org-tag-alist (org-get-buffer-tags)))
4637 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
4638 (pattern (buffer-substring-no-properties beg end))
4639 (completion (try-completion pattern table confirm)))
4640 (cond ((eq completion t)
4641 (if (equal type :opt)
4642 (insert (substring (cdr (assoc (upcase pattern) table))
4643 (length pattern)))))
4644 ((null completion)
4645 (message "Can't find completion for \"%s\"" pattern)
4646 (ding))
4647 ((not (string= pattern completion))
4648 (delete-region beg end)
4649 (if (string-match " +$" completion)
4650 (setq completion (replace-match "" t t completion)))
4651 (insert completion)
4652 (if (get-buffer-window "*Completions*")
4653 (delete-window (get-buffer-window "*Completions*")))
4654 (if (assoc completion table)
4655 (if (eq type :todo) (insert " ")
4656 (if (eq type :tag) (insert ":"))))
4657 (if (and (equal type :opt) (assoc completion table))
4658 (message "%s" (substitute-command-keys
4659 "Press \\[org-complete] again to insert example settings"))))
4660 (t
4661 (message "Making completion list...")
4662 (let ((list (sort (all-completions pattern table confirm)
4663 'string<)))
4664 (with-output-to-temp-buffer "*Completions*"
4665 (condition-case nil
4666 ;; Protection needed for XEmacs and emacs 21
4667 (display-completion-list list pattern)
4668 (error (display-completion-list list)))))
4669 (message "Making completion list...%s" "done"))))))
4670
4671 ;;; Comments, TODO and DEADLINE
4672
4673 (defun org-toggle-comment ()
4674 "Change the COMMENT state of an entry."
4675 (interactive)
4676 (save-excursion
4677 (org-back-to-heading)
4678 (if (looking-at (concat outline-regexp
4679 "\\( +\\<" org-comment-string "\\>\\)"))
4680 (replace-match "" t t nil 1)
4681 (if (looking-at outline-regexp)
4682 (progn
4683 (goto-char (match-end 0))
4684 (insert " " org-comment-string))))))
4685
4686 (defvar org-last-todo-state-is-todo nil
4687 "This is non-nil when the last TODO state change led to a TODO state.
4688 If the last change removed the TODO tag or switched to DONE, then
4689 this is nil.")
4690
4691 (defun org-todo (&optional arg)
4692 "Change the TODO state of an item.
4693 The state of an item is given by a keyword at the start of the heading,
4694 like
4695 *** TODO Write paper
4696 *** DONE Call mom
4697
4698 The different keywords are specified in the variable `org-todo-keywords'.
4699 By default the available states are \"TODO\" and \"DONE\".
4700 So for this example: when the item starts with TODO, it is changed to DONE.
4701 When it starts with DONE, the DONE is removed. And when neither TODO nor
4702 DONE are present, add TODO at the beginning of the heading.
4703
4704 With prefix arg, use completion to determine the new state. With numeric
4705 prefix arg, switch to that state."
4706 (interactive "P")
4707 (save-excursion
4708 (org-back-to-heading)
4709 (if (looking-at outline-regexp) (goto-char (match-end 0)))
4710 (or (looking-at (concat " +" org-todo-regexp " *"))
4711 (looking-at " *"))
4712 (let* ((this (match-string 1))
4713 (completion-ignore-case t)
4714 (member (member this org-todo-keywords))
4715 (tail (cdr member))
4716 (state (cond
4717 ((equal arg '(4))
4718 ;; Read a state with completion
4719 (completing-read "State: " (mapcar (lambda(x) (list x))
4720 org-todo-keywords)
4721 nil t))
4722 ((eq arg 'right)
4723 (if this
4724 (if tail (car tail) nil)
4725 (car org-todo-keywords)))
4726 ((eq arg 'left)
4727 (if (equal member org-todo-keywords)
4728 nil
4729 (if this
4730 (nth (- (length org-todo-keywords) (length tail) 2)
4731 org-todo-keywords)
4732 org-done-string)))
4733 (arg
4734 ;; user requests a specific state
4735 (nth (1- (prefix-numeric-value arg))
4736 org-todo-keywords))
4737 ((null member) (car org-todo-keywords))
4738 ((null tail) nil) ;; -> first entry
4739 ((eq org-todo-interpretation 'sequence)
4740 (car tail))
4741 ((memq org-todo-interpretation '(type priority))
4742 (if (eq this-command last-command)
4743 (car tail)
4744 (if (> (length tail) 0) org-done-string nil)))
4745 (t nil)))
4746 (next (if state (concat " " state " ") " ")))
4747 (replace-match next t t)
4748 (setq org-last-todo-state-is-todo
4749 (not (equal state org-done-string)))
4750 (when org-log-done
4751 (if (equal state org-done-string)
4752 (org-add-planning-info 'closed (current-time) 'scheduled)
4753 (if (not this)
4754 (org-add-planning-info nil nil 'closed))))
4755 ;; Fixup tag positioning
4756 (and org-auto-align-tags (org-set-tags nil t))
4757 (run-hooks 'org-after-todo-state-change-hook)))
4758 ;; Fixup cursor location if close to the keyword
4759 (if (and (outline-on-heading-p)
4760 (not (bolp))
4761 (save-excursion (beginning-of-line 1)
4762 (looking-at org-todo-line-regexp))
4763 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
4764 (progn
4765 (goto-char (or (match-end 2) (match-end 1)))
4766 (just-one-space))))
4767
4768 (defun org-log-done (&optional undone)
4769 "Add a time stamp logging that a TODO entry has been closed.
4770 When UNDONE is non-nil, remove such a time stamp again."
4771 (interactive)
4772 (let (beg end col)
4773 (save-excursion
4774 (org-back-to-heading t)
4775 (setq beg (point))
4776 (looking-at (concat outline-regexp " *"))
4777 (goto-char (match-end 0))
4778 (setq col (current-column))
4779 (outline-next-heading)
4780 (setq end (point))
4781 (goto-char beg)
4782 (when (re-search-forward (concat
4783 "[\r\n]\\([ \t]*"
4784 (regexp-quote org-closed-string)
4785 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
4786 (delete-region (match-beginning 1) (match-end 1)))
4787 (unless undone
4788 (org-back-to-heading t)
4789 (skip-chars-forward "^\n\r")
4790 (goto-char (min (1+ (point)) (point-max)))
4791 (when (not (member (char-before) '(?\r ?\n)))
4792 (insert "\n"))
4793 (indent-to col)
4794 (insert org-closed-string " "
4795 (format-time-string
4796 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4797 (org-current-time))
4798 "\n")))))
4799
4800 (defun org-show-todo-tree (arg)
4801 "Make a compact tree which shows all headlines marked with TODO.
4802 The tree will show the lines where the regexp matches, and all higher
4803 headlines above the match.
4804 With \\[universal-argument] prefix, also show the DONE entries.
4805 With a numeric prefix N, construct a sparse tree for the Nth element
4806 of `org-todo-keywords'."
4807 (interactive "P")
4808 (let ((case-fold-search nil)
4809 (kwd-re
4810 (cond ((null arg) org-not-done-regexp)
4811 ((equal arg '(4)) org-todo-regexp)
4812 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
4813 (regexp-quote (nth (1- (prefix-numeric-value arg))
4814 org-todo-keywords)))
4815 (t (error "Invalid prefix argument: %s" arg)))))
4816 (message "%d TODO entries found"
4817 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
4818
4819 (defun org-deadline ()
4820 "Insert the DEADLINE: string to make a deadline.
4821 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4822 to modify it to the correct date."
4823 (interactive)
4824 (org-add-planning-info 'deadline nil 'closed))
4825
4826 (defun org-schedule ()
4827 "Insert the SCHEDULED: string to schedule a TODO item.
4828 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4829 to modify it to the correct date."
4830 (interactive)
4831 (org-add-planning-info 'scheduled nil 'closed))
4832
4833 (defun org-add-planning-info (what &optional time &rest remove)
4834 "Insert new timestamp with keyword in the line directly after the headline.
4835 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
4836 If non is given, the user is prompted for a date.
4837 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
4838 be removed."
4839 (interactive)
4840 (when what (setq time (or time (org-read-date nil 'to-time))))
4841 (when (and org-insert-labeled-timestamps-at-point
4842 (member what '(scheduled deadline)))
4843 (insert
4844 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
4845 " "
4846 (format-time-string (car org-time-stamp-formats) time))
4847 (setq what nil))
4848 (save-excursion
4849 (let (beg end col list elt (buffer-invisibility-spec nil) ts)
4850 (org-back-to-heading t)
4851 (setq beg (point))
4852 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
4853 (goto-char (match-end 1))
4854 (setq col (current-column))
4855 (goto-char (1+ (match-end 0)))
4856 (if (and (not (looking-at outline-regexp))
4857 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
4858 "[^\r\n]*"))
4859 (not (equal (match-string 1) org-clock-string)))
4860 (narrow-to-region (match-beginning 0) (match-end 0))
4861 (insert "\n")
4862 (backward-char 1)
4863 (narrow-to-region (point) (point))
4864 (indent-to-column col))
4865 ;; Check if we have to remove something.
4866 (setq list (cons what remove))
4867 (while list
4868 (setq elt (pop list))
4869 (goto-char (point-min))
4870 (when (or (and (eq elt 'scheduled)
4871 (re-search-forward org-scheduled-time-regexp nil t))
4872 (and (eq elt 'deadline)
4873 (re-search-forward org-deadline-time-regexp nil t))
4874 (and (eq elt 'closed)
4875 (re-search-forward org-closed-time-regexp nil t)))
4876 (replace-match "")
4877 (if (looking-at " +") (replace-match ""))))
4878 (goto-char (point-max))
4879 (when what
4880 (insert
4881 (if (not (equal (char-before) ?\ )) " " "")
4882 (cond ((eq what 'scheduled) org-scheduled-string)
4883 ((eq what 'deadline) org-deadline-string)
4884 ((eq what 'closed) org-closed-string))
4885 " ")
4886 (insert
4887 (setq ts
4888 (format-time-string
4889 (if (eq what 'closed)
4890 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4891 (car org-time-stamp-formats))
4892 time))))
4893 (goto-char (point-min))
4894 (widen)
4895 (if (looking-at "[ \t]+\r?\n")
4896 (replace-match ""))
4897 ts)))
4898
4899 (defun org-occur (regexp &optional callback)
4900 "Make a compact tree which shows all matches of REGEXP.
4901 The tree will show the lines where the regexp matches, and all higher
4902 headlines above the match. It will also show the heading after the match,
4903 to make sure editing the matching entry is easy.
4904 If CALLBACK is non-nil, it is a function which is called to confirm
4905 that the match should indeed be shown."
4906 (interactive "sRegexp: ")
4907 (org-remove-occur-highlights nil nil t)
4908 (setq regexp (org-check-occur-regexp regexp))
4909 (let ((cnt 0))
4910 (save-excursion
4911 (goto-char (point-min))
4912 (org-overview)
4913 (while (re-search-forward regexp nil t)
4914 (when (or (not callback)
4915 (save-match-data (funcall callback)))
4916 (setq cnt (1+ cnt))
4917 (org-highlight-new-match (match-beginning 0) (match-end 0))
4918 (org-show-hierarchy-above))))
4919 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
4920 nil 'local)
4921 (run-hooks 'org-occur-hook)
4922 (if (interactive-p)
4923 (message "%d match(es) for regexp %s" cnt regexp))
4924 cnt))
4925
4926 (defun org-show-hierarchy-above ()
4927 "Make sure point and the headings hierarchy above is visible."
4928 (catch 'exit
4929 (if (org-on-heading-p t)
4930 (org-flag-heading nil) ; only show the heading
4931 (and (or (org-invisible-p) (org-invisible-p2))
4932 (org-show-hidden-entry))) ; show entire entry
4933 (save-excursion
4934 (and org-show-following-heading
4935 (outline-next-heading)
4936 (org-flag-heading nil))) ; show the next heading
4937 (when org-show-hierarchy-above
4938 (save-excursion ; show all higher headings
4939 (while (and (condition-case nil
4940 (progn (org-up-heading-all 1) t)
4941 (error nil))
4942 (not (bobp)))
4943 (org-flag-heading nil))))))
4944
4945 ;; Overlay compatibility functions
4946 (defun org-make-overlay (beg end &optional buffer)
4947 (if (featurep 'xemacs)
4948 (make-extent beg end buffer)
4949 (make-overlay beg end buffer)))
4950 (defun org-delete-overlay (ovl)
4951 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4952 (defun org-detatch-overlay (ovl)
4953 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4954 (defun org-move-overlay (ovl beg end &optional buffer)
4955 (if (featurep 'xemacs)
4956 (set-extent-endpoints ovl beg end buffer)
4957 (move-overlay ovl beg end buffer)))
4958 (defun org-overlay-put (ovl prop value)
4959 (if (featurep 'xemacs)
4960 (set-extent-property ovl prop value)
4961 (overlay-put ovl prop value)))
4962
4963 (defvar org-occur-highlights nil)
4964 (defun org-highlight-new-match (beg end)
4965 "Highlight from BEG to END and mark the highlight is an occur headline."
4966 (let ((ov (org-make-overlay beg end)))
4967 (org-overlay-put ov 'face 'secondary-selection)
4968 (push ov org-occur-highlights)))
4969
4970 (defvar org-inhibit-highlight-removal nil)
4971 (defun org-remove-occur-highlights (&optional beg end noremove)
4972 "Remove the occur highlights from the buffer.
4973 BEG and END are ignored. If NOREMOVE is nil, remove this function
4974 from the `before-change-functions' in the current buffer."
4975 (interactive)
4976 (unless org-inhibit-highlight-removal
4977 (mapc 'org-delete-overlay org-occur-highlights)
4978 (setq org-occur-highlights nil)
4979 (unless noremove
4980 (remove-hook 'before-change-functions
4981 'org-remove-occur-highlights 'local))))
4982
4983 ;;; Priorities
4984
4985 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
4986 "Regular expression matching the priority indicator.")
4987
4988 (defvar org-remove-priority-next-time nil)
4989
4990 (defun org-priority-up ()
4991 "Increase the priority of the current item."
4992 (interactive)
4993 (org-priority 'up))
4994
4995 (defun org-priority-down ()
4996 "Decrease the priority of the current item."
4997 (interactive)
4998 (org-priority 'down))
4999
5000 (defun org-priority (&optional action)
5001 "Change the priority of an item by ARG.
5002 ACTION can be set, up, or down."
5003 (interactive)
5004 (setq action (or action 'set))
5005 (let (current new news have remove)
5006 (save-excursion
5007 (org-back-to-heading)
5008 (if (looking-at org-priority-regexp)
5009 (setq current (string-to-char (match-string 2))
5010 have t)
5011 (setq current org-default-priority))
5012 (cond
5013 ((eq action 'set)
5014 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5015 (setq new (read-char-exclusive))
5016 (cond ((equal new ?\ ) (setq remove t))
5017 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5018 (error "Priority must be between `%c' and `%c'"
5019 ?A org-lowest-priority))))
5020 ((eq action 'up)
5021 (setq new (1- current)))
5022 ((eq action 'down)
5023 (setq new (1+ current)))
5024 (t (error "Invalid action")))
5025 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5026 (setq news (format "%c" new))
5027 (if have
5028 (if remove
5029 (replace-match "" t t nil 1)
5030 (replace-match news t t nil 2))
5031 (if remove
5032 (error "No priority cookie found in line")
5033 (looking-at org-todo-line-regexp)
5034 (if (match-end 2)
5035 (progn
5036 (goto-char (match-end 2))
5037 (insert " [#" news "]"))
5038 (goto-char (match-beginning 3))
5039 (insert "[#" news "] ")))))
5040 (if remove
5041 (message "Priority removed")
5042 (message "Priority of current item set to %s" news))))
5043
5044
5045 (defun org-get-priority (s)
5046 "Find priority cookie and return priority."
5047 (save-match-data
5048 (if (not (string-match org-priority-regexp s))
5049 (* 1000 (- org-lowest-priority org-default-priority))
5050 (* 1000 (- org-lowest-priority
5051 (string-to-char (match-string 2 s)))))))
5052
5053 ;;; Timestamps
5054
5055 (defvar org-last-changed-timestamp nil)
5056
5057 (defun org-time-stamp (arg)
5058 "Prompt for a date/time and insert a time stamp.
5059 If the user specifies a time like HH:MM, or if this command is called
5060 with a prefix argument, the time stamp will contain date and time.
5061 Otherwise, only the date will be included. All parts of a date not
5062 specified by the user will be filled in from the current date/time.
5063 So if you press just return without typing anything, the time stamp
5064 will represent the current date/time. If there is already a timestamp
5065 at the cursor, it will be modified."
5066 (interactive "P")
5067 (let ((fmt (if arg (cdr org-time-stamp-formats)
5068 (car org-time-stamp-formats)))
5069 (org-time-was-given nil)
5070 time)
5071 (cond
5072 ((and (org-at-timestamp-p)
5073 (eq last-command 'org-time-stamp)
5074 (eq this-command 'org-time-stamp))
5075 (insert "--")
5076 (setq time (let ((this-command this-command))
5077 (org-read-date arg 'totime)))
5078 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5079 (insert (format-time-string fmt time)))
5080 ((org-at-timestamp-p)
5081 (setq time (let ((this-command this-command))
5082 (org-read-date arg 'totime)))
5083 (and (org-at-timestamp-p) (replace-match
5084 (setq org-last-changed-timestamp
5085 (format-time-string fmt time))
5086 t t))
5087 (message "Timestamp updated"))
5088 (t
5089 (setq time (let ((this-command this-command))
5090 (org-read-date arg 'totime)))
5091 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5092 (insert (format-time-string fmt time))))))
5093
5094 (defun org-time-stamp-inactive (&optional arg)
5095 "Insert an inactive time stamp.
5096 An inactive time stamp is enclosed in square brackets instead of angle
5097 brackets. It is inactive in the sense that it does not trigger agenda entries,
5098 does not link to the calendar and cannot be changed with the S-cursor keys.
5099 So these are more for recording a certain time/date."
5100 (interactive "P")
5101 (let ((fmt (if arg (cdr org-time-stamp-formats)
5102 (car org-time-stamp-formats)))
5103 (org-time-was-given nil)
5104 time)
5105 (setq time (org-read-date arg 'totime))
5106 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5107 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
5108 (insert (format-time-string fmt time))))
5109
5110 (defvar org-date-ovl (org-make-overlay 1 1))
5111 (org-overlay-put org-date-ovl 'face 'org-warning)
5112 (org-detatch-overlay org-date-ovl)
5113
5114 (defun org-read-date (&optional with-time to-time)
5115 "Read a date and make things smooth for the user.
5116 The prompt will suggest to enter an ISO date, but you can also enter anything
5117 which will at least partially be understood by `parse-time-string'.
5118 Unrecognized parts of the date will default to the current day, month, year,
5119 hour and minute. For example,
5120 3-2-5 --> 2003-02-05
5121 feb 15 --> currentyear-02-15
5122 sep 12 9 --> 2009-09-12
5123 12:45 --> today 12:45
5124 22 sept 0:34 --> currentyear-09-22 0:34
5125 12 --> currentyear-currentmonth-12
5126 Fri --> nearest Friday (today or later)
5127 etc.
5128 The function understands only English month and weekday abbreviations,
5129 but this can be configured with the variables `parse-time-months' and
5130 `parse-time-weekdays'.
5131
5132 While prompting, a calendar is popped up - you can also select the
5133 date with the mouse (button 1). The calendar shows a period of three
5134 months. To scroll it to other months, use the keys `>' and `<'.
5135 If you don't like the calendar, turn it off with
5136 \(setq org-popup-calendar-for-date-prompt nil)
5137
5138 With optional argument TO-TIME, the date will immediately be converted
5139 to an internal time.
5140 With an optional argument WITH-TIME, the prompt will suggest to also
5141 insert a time. Note that when WITH-TIME is not set, you can still
5142 enter a time, and this function will inform the calling routine about
5143 this change. The calling routine may then choose to change the format
5144 used to insert the time stamp into the buffer to include the time."
5145 (require 'parse-time)
5146 (let* ((org-time-stamp-rounding-minutes
5147 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5148 (ct (org-current-time))
5149 (default-time
5150 ;; Default time is either today, or, when entering a range,
5151 ;; the range start.
5152 (if (save-excursion
5153 (re-search-backward
5154 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5155 (- (point) 20) t))
5156 (apply
5157 'encode-time
5158 (mapcar (lambda(x) (or x 0))
5159 (parse-time-string (match-string 1))))
5160 ct))
5161 (calendar-move-hook nil)
5162 (view-diary-entries-initially nil)
5163 (view-calendar-holidays-initially nil)
5164 (timestr (format-time-string
5165 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5166 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5167 ans ans1 ans2
5168 second minute hour day month year tl wday wday1)
5169
5170 (if org-popup-calendar-for-date-prompt
5171 (save-excursion
5172 (save-window-excursion
5173 (calendar)
5174 (calendar-forward-day (- (time-to-days default-time)
5175 (calendar-absolute-from-gregorian
5176 (calendar-current-date))))
5177 (org-eval-in-calendar nil)
5178 (let* ((old-map (current-local-map))
5179 (map (copy-keymap calendar-mode-map))
5180 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5181 (define-key map (kbd "RET") 'org-calendar-select)
5182 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5183 'org-calendar-select-mouse)
5184 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5185 'org-calendar-select-mouse)
5186 (define-key minibuffer-local-map [(meta shift left)]
5187 (lambda () (interactive)
5188 (org-eval-in-calendar '(calendar-backward-month 1))))
5189 (define-key minibuffer-local-map [(meta shift right)]
5190 (lambda () (interactive)
5191 (org-eval-in-calendar '(calendar-forward-month 1))))
5192 (define-key minibuffer-local-map [(shift up)]
5193 (lambda () (interactive)
5194 (org-eval-in-calendar '(calendar-backward-week 1))))
5195 (define-key minibuffer-local-map [(shift down)]
5196 (lambda () (interactive)
5197 (org-eval-in-calendar '(calendar-forward-week 1))))
5198 (define-key minibuffer-local-map [(shift left)]
5199 (lambda () (interactive)
5200 (org-eval-in-calendar '(calendar-backward-day 1))))
5201 (define-key minibuffer-local-map [(shift right)]
5202 (lambda () (interactive)
5203 (org-eval-in-calendar '(calendar-forward-day 1))))
5204 (define-key minibuffer-local-map ">"
5205 (lambda () (interactive)
5206 (org-eval-in-calendar '(scroll-calendar-left 1))))
5207 (define-key minibuffer-local-map "<"
5208 (lambda () (interactive)
5209 (org-eval-in-calendar '(scroll-calendar-right 1))))
5210 (unwind-protect
5211 (progn
5212 (use-local-map map)
5213 (setq ans (read-string prompt "" nil nil))
5214 (if (not (string-match "\\S-" ans)) (setq ans nil))
5215 (setq ans (or ans1 ans ans2)))
5216 (use-local-map old-map)))))
5217 ;; Naked prompt only
5218 (setq ans (read-string prompt "" nil timestr)))
5219 (org-detatch-overlay org-date-ovl)
5220
5221 (if (string-match
5222 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5223 (progn
5224 (setq year (if (match-end 2)
5225 (string-to-number (match-string 2 ans))
5226 (string-to-number (format-time-string "%Y")))
5227 month (string-to-number (match-string 3 ans))
5228 day (string-to-number (match-string 4 ans)))
5229 (if (< year 100) (setq year (+ 2000 year)))
5230 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
5231 t nil ans))))
5232 (setq tl (parse-time-string ans)
5233 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
5234 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
5235 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
5236 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
5237 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
5238 second (or (nth 0 tl) 0)
5239 wday (nth 6 tl))
5240 (when (and wday (not (nth 3 tl)))
5241 ;; Weekday was given, but no day, so pick that day in the week
5242 ;; on or after the derived date.
5243 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
5244 (unless (equal wday wday1)
5245 (setq day (+ day (% (- wday wday1 -7) 7)))))
5246 (if (and (boundp 'org-time-was-given)
5247 (nth 2 tl))
5248 (setq org-time-was-given t))
5249 (if (< year 100) (setq year (+ 2000 year)))
5250 (if to-time
5251 (encode-time second minute hour day month year)
5252 (if (or (nth 1 tl) (nth 2 tl))
5253 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
5254 (format "%04d-%02d-%02d" year month day)))))
5255
5256 (defun org-eval-in-calendar (form)
5257 "Eval FORM in the calendar window and return to current window.
5258 Also, store the cursor date in variable ans2."
5259 (let ((sw (selected-window)))
5260 (select-window (get-buffer-window "*Calendar*"))
5261 (eval form)
5262 (when (calendar-cursor-to-date)
5263 (let* ((date (calendar-cursor-to-date))
5264 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5265 (setq ans2 (format-time-string "%Y-%m-%d" time))))
5266 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
5267 (select-window sw)))
5268
5269 (defun org-calendar-select ()
5270 "Return to `org-read-date' with the date currently selected.
5271 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5272 (interactive)
5273 (when (calendar-cursor-to-date)
5274 (let* ((date (calendar-cursor-to-date))
5275 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5276 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5277 (if (active-minibuffer-window) (exit-minibuffer))))
5278
5279 (defun org-calendar-select-mouse (ev)
5280 "Return to `org-read-date' with the date currently selected.
5281 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5282 (interactive "e")
5283 (mouse-set-point ev)
5284 (when (calendar-cursor-to-date)
5285 (let* ((date (calendar-cursor-to-date))
5286 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5287 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5288 (if (active-minibuffer-window) (exit-minibuffer))))
5289
5290 (defun org-check-deadlines (ndays)
5291 "Check if there are any deadlines due or past due.
5292 A deadline is considered due if it happens within `org-deadline-warning-days'
5293 days from today's date. If the deadline appears in an entry marked DONE,
5294 it is not shown. The prefix arg NDAYS can be used to test that many
5295 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
5296 (interactive "P")
5297 (let* ((org-warn-days
5298 (cond
5299 ((equal ndays '(4)) 100000)
5300 (ndays (prefix-numeric-value ndays))
5301 (t org-deadline-warning-days)))
5302 (case-fold-search nil)
5303 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
5304 (callback
5305 (lambda ()
5306 (and (let ((d1 (time-to-days (current-time)))
5307 (d2 (time-to-days
5308 (org-time-string-to-time (match-string 1)))))
5309 (< (- d2 d1) org-warn-days))
5310 (not (org-entry-is-done-p))))))
5311 (message "%d deadlines past-due or due within %d days"
5312 (org-occur regexp callback)
5313 org-warn-days)))
5314
5315 (defun org-evaluate-time-range (&optional to-buffer)
5316 "Evaluate a time range by computing the difference between start and end.
5317 Normally the result is just printed in the echo area, but with prefix arg
5318 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
5319 If the time range is actually in a table, the result is inserted into the
5320 next column.
5321 For time difference computation, a year is assumed to be exactly 365
5322 days in order to avoid rounding problems."
5323 (interactive "P")
5324 (save-excursion
5325 (unless (org-at-date-range-p)
5326 (goto-char (point-at-bol))
5327 (re-search-forward org-tr-regexp (point-at-eol) t))
5328 (if (not (org-at-date-range-p))
5329 (error "Not at a time-stamp range, and none found in current line")))
5330 (let* ((ts1 (match-string 1))
5331 (ts2 (match-string 2))
5332 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
5333 (match-end (match-end 0))
5334 (time1 (org-time-string-to-time ts1))
5335 (time2 (org-time-string-to-time ts2))
5336 (t1 (time-to-seconds time1))
5337 (t2 (time-to-seconds time2))
5338 (diff (abs (- t2 t1)))
5339 (negative (< (- t2 t1) 0))
5340 ;; (ys (floor (* 365 24 60 60)))
5341 (ds (* 24 60 60))
5342 (hs (* 60 60))
5343 (fy "%dy %dd %02d:%02d")
5344 (fy1 "%dy %dd")
5345 (fd "%dd %02d:%02d")
5346 (fd1 "%dd")
5347 (fh "%02d:%02d")
5348 y d h m align)
5349 (if havetime
5350 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5351 y 0
5352 d (floor (/ diff ds)) diff (mod diff ds)
5353 h (floor (/ diff hs)) diff (mod diff hs)
5354 m (floor (/ diff 60)))
5355 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5356 y 0
5357 d (floor (+ (/ diff ds) 0.5))
5358 h 0 m 0))
5359 (if (not to-buffer)
5360 (message (org-make-tdiff-string y d h m))
5361 (when (org-at-table-p)
5362 (goto-char match-end)
5363 (setq align t)
5364 (and (looking-at " *|") (goto-char (match-end 0))))
5365 (if (looking-at
5366 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
5367 (replace-match ""))
5368 (if negative (insert " -"))
5369 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
5370 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
5371 (insert " " (format fh h m))))
5372 (if align (org-table-align))
5373 (message "Time difference inserted"))))
5374
5375 (defun org-make-tdiff-string (y d h m)
5376 (let ((fmt "")
5377 (l nil))
5378 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5379 l (push y l)))
5380 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5381 l (push d l)))
5382 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5383 l (push h l)))
5384 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5385 l (push m l)))
5386 (apply 'format fmt (nreverse l))))
5387
5388 (defun org-time-string-to-time (s)
5389 (apply 'encode-time (org-parse-time-string s)))
5390
5391 (defun org-parse-time-string (s &optional nodefault)
5392 "Parse the standard Org-mode time string.
5393 This should be a lot faster than the normal `parse-time-string'.
5394 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5395 hour and minute fields will be nil if not given."
5396 (if (string-match org-ts-regexp1 s)
5397 (list 0
5398 (if (or (match-beginning 8) (not nodefault))
5399 (string-to-number (or (match-string 8 s) "0")))
5400 (if (or (match-beginning 7) (not nodefault))
5401 (string-to-number (or (match-string 7 s) "0")))
5402 (string-to-number (match-string 4 s))
5403 (string-to-number (match-string 3 s))
5404 (string-to-number (match-string 2 s))
5405 nil nil nil)
5406 (make-list 9 0)))
5407
5408 (defun org-timestamp-up (&optional arg)
5409 "Increase the date item at the cursor by one.
5410 If the cursor is on the year, change the year. If it is on the month or
5411 the day, change that.
5412 With prefix ARG, change by that many units."
5413 (interactive "p")
5414 (org-timestamp-change (prefix-numeric-value arg)))
5415
5416 (defun org-timestamp-down (&optional arg)
5417 "Decrease the date item at the cursor by one.
5418 If the cursor is on the year, change the year. If it is on the month or
5419 the day, change that.
5420 With prefix ARG, change by that many units."
5421 (interactive "p")
5422 (org-timestamp-change (- (prefix-numeric-value arg))))
5423
5424 (defun org-timestamp-up-day (&optional arg)
5425 "Increase the date in the time stamp by one day.
5426 With prefix ARG, change that many days."
5427 (interactive "p")
5428 (if (and (not (org-at-timestamp-p))
5429 (org-on-heading-p))
5430 (org-todo 'up)
5431 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5432
5433 (defun org-timestamp-down-day (&optional arg)
5434 "Decrease the date in the time stamp by one day.
5435 With prefix ARG, change that many days."
5436 (interactive "p")
5437 (if (and (not (org-at-timestamp-p))
5438 (org-on-heading-p))
5439 (org-todo 'down)
5440 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5441
5442 (defsubst org-pos-in-match-range (pos n)
5443 (and (match-beginning n)
5444 (<= (match-beginning n) pos)
5445 (>= (match-end n) pos)))
5446
5447 (defun org-at-timestamp-p ()
5448 "Determine if the cursor is in or at a timestamp."
5449 (interactive)
5450 (let* ((tsr org-ts-regexp2)
5451 (pos (point))
5452 (ans (or (looking-at tsr)
5453 (save-excursion
5454 (skip-chars-backward "^<\n\r\t")
5455 (if (> (point) 1) (backward-char 1))
5456 (and (looking-at tsr)
5457 (> (- (match-end 0) pos) -1))))))
5458 (and (boundp 'org-ts-what)
5459 (setq org-ts-what
5460 (cond
5461 ((org-pos-in-match-range pos 2) 'year)
5462 ((org-pos-in-match-range pos 3) 'month)
5463 ((org-pos-in-match-range pos 7) 'hour)
5464 ((org-pos-in-match-range pos 8) 'minute)
5465 ((or (org-pos-in-match-range pos 4)
5466 (org-pos-in-match-range pos 5)) 'day)
5467 (t 'day))))
5468 ans))
5469
5470 (defun org-timestamp-change (n &optional what)
5471 "Change the date in the time stamp at point.
5472 The date will be changed by N times WHAT. WHAT can be `day', `month',
5473 `year', `minute', `second'. If WHAT is not given, the cursor position
5474 in the timestamp determines what will be changed."
5475 (let ((fmt (car org-time-stamp-formats))
5476 org-ts-what
5477 (pos (point))
5478 ts time time0)
5479 (if (not (org-at-timestamp-p))
5480 (error "Not at a timestamp"))
5481 (setq org-ts-what (or what org-ts-what))
5482 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5483 (- (match-end 0) (match-beginning 0))))
5484 1)
5485 (cdr org-time-stamp-formats)
5486 (car org-time-stamp-formats)))
5487 (setq ts (match-string 0))
5488 (replace-match "")
5489 (setq time0 (org-parse-time-string ts))
5490 (setq time
5491 (apply 'encode-time
5492 (append
5493 (list (or (car time0) 0))
5494 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5495 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5496 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5497 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5498 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5499 (nthcdr 6 time0))))
5500 (if (eq what 'calendar)
5501 (let ((cal-date
5502 (save-excursion
5503 (save-match-data
5504 (set-buffer "*Calendar*")
5505 (calendar-cursor-to-date)))))
5506 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5507 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5508 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5509 (setcar time0 (or (car time0) 0))
5510 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5511 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5512 (setq time (apply 'encode-time time0))))
5513 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5514 (goto-char pos)
5515 ;; Try to recenter the calendar window, if any
5516 (if (and org-calendar-follow-timestamp-change
5517 (get-buffer-window "*Calendar*" t)
5518 (memq org-ts-what '(day month year)))
5519 (org-recenter-calendar (time-to-days time)))))
5520
5521 (defun org-recenter-calendar (date)
5522 "If the calendar is visible, recenter it to DATE."
5523 (let* ((win (selected-window))
5524 (cwin (get-buffer-window "*Calendar*" t))
5525 (calendar-move-hook nil))
5526 (when cwin
5527 (select-window cwin)
5528 (calendar-goto-date (if (listp date) date
5529 (calendar-gregorian-from-absolute date)))
5530 (select-window win))))
5531
5532 (defun org-goto-calendar (&optional arg)
5533 "Go to the Emacs calendar at the current date.
5534 If there is a time stamp in the current line, go to that date.
5535 A prefix ARG can be used to force the current date."
5536 (interactive "P")
5537 (let ((tsr org-ts-regexp) diff
5538 (calendar-move-hook nil)
5539 (view-calendar-holidays-initially nil)
5540 (view-diary-entries-initially nil))
5541 (if (or (org-at-timestamp-p)
5542 (save-excursion
5543 (beginning-of-line 1)
5544 (looking-at (concat ".*" tsr))))
5545 (let ((d1 (time-to-days (current-time)))
5546 (d2 (time-to-days
5547 (org-time-string-to-time (match-string 1)))))
5548 (setq diff (- d2 d1))))
5549 (calendar)
5550 (calendar-goto-today)
5551 (if (and diff (not arg)) (calendar-forward-day diff))))
5552
5553 (defun org-date-from-calendar ()
5554 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
5555 If there is already a time stamp at the cursor position, update it."
5556 (interactive)
5557 (org-timestamp-change 0 'calendar))
5558
5559 ;;; The clock for measuring work time.
5560
5561 (defvar org-clock-marker (make-marker)
5562 "Marker recording the last clock-in.")
5563
5564 (defun org-clock-in ()
5565 "Start the clock on the current item.
5566 If necessary, clock-out of the currently active clock."
5567 (interactive)
5568 (org-clock-out t)
5569 (let (ts)
5570 (save-excursion
5571 (org-back-to-heading t)
5572 (beginning-of-line 2)
5573 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5574 (not (equal (match-string 1) org-clock-string)))
5575 (beginning-of-line 1))
5576 (insert "\n") (backward-char 1)
5577 (indent-relative)
5578 (insert org-clock-string " "
5579 (setq ts (concat "[" (format-time-string
5580 (substring
5581 (cdr org-time-stamp-formats) 1 -1)
5582 (current-time))
5583 "]")))
5584 (move-marker org-clock-marker (point))
5585 (message "Clock started at %s" ts))))
5586
5587 (defun org-clock-out (&optional fail-quietly)
5588 "Stop the currently running clock.
5589 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
5590 (interactive)
5591 (catch 'exit
5592 (if (not (marker-buffer org-clock-marker))
5593 (if fail-quietly (throw 'exit t) (error "No active clock")))
5594 (let (ts te s h m)
5595 (save-excursion
5596 (set-buffer (marker-buffer org-clock-marker))
5597 (goto-char org-clock-marker)
5598 (beginning-of-line 1)
5599 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5600 (equal (match-string 1) org-clock-string))
5601 (setq ts (match-string 2))
5602 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
5603 (goto-char org-clock-marker)
5604 (setq te (concat "[" (format-time-string
5605 (substring
5606 (cdr org-time-stamp-formats) 1 -1)
5607 (current-time))
5608 "]"))
5609 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
5610 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
5611 h (floor (/ s 3600))
5612 s (- s (* 3600 h))
5613 m (floor (/ s 60))
5614 s (- s (* 60 s)))
5615 (insert "--" te " => " (format "%2d:%02d" h m))
5616 (move-marker org-clock-marker nil)
5617 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
5618
5619 (defun org-clock-cancel ()
5620 "Cancel the running clock be removing the start timestamp."
5621 (interactive)
5622 (if (not (marker-buffer org-clock-marker))
5623 (error "No active clock"))
5624 (save-excursion
5625 (set-buffer (marker-buffer org-clock-marker))
5626 (goto-char org-clock-marker)
5627 (delete-region (1- (point-at-bol)) (point-at-eol)))
5628 (message "Clock canceled"))
5629
5630 (defvar org-clock-file-total-minutes nil
5631 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
5632 (make-variable-buffer-local 'org-clock-file-total-minutes)
5633
5634 (defun org-clock-sum ()
5635 "Sum the times for each subtree.
5636 Puts the resulting times in minutes as a text property on each headline."
5637 (interactive)
5638 (let* ((bmp (buffer-modified-p))
5639 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
5640 org-clock-string
5641 ".*=>[ \t]*\\([0-9]+\\):\\([0-9]+\\)[ \t]*$"))
5642 (lmax 30)
5643 (ltimes (make-vector lmax 0))
5644 (t1 0)
5645 (level 0)
5646 (lastlevel 0) time)
5647 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
5648 (save-excursion
5649 (goto-char (point-max))
5650 (while (re-search-backward re nil t)
5651 (if (match-end 2)
5652 ;; A time
5653 (setq t1 (+ t1 (* 60 (string-to-number (match-string 2)))
5654 (string-to-number (match-string 3))))
5655 ;; A headline
5656 (setq level (- (match-end 1) (match-beginning 1)))
5657 (when (or (> t1 0) (> (aref ltimes level) 0))
5658 (loop for l from 0 to level do
5659 (aset ltimes l (+ (aref ltimes l) t1)))
5660 (setq t1 0 time (aref ltimes level))
5661 (loop for l from level to (1- lmax) do
5662 (aset ltimes l 0))
5663 (goto-char (match-beginning 0))
5664 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
5665 (setq org-clock-file-total-minutes (aref ltimes 0)))
5666 (set-buffer-modified-p bmp)))
5667
5668 (defun org-clock-display (&optional total-only)
5669 "Show subtree times in the entire buffer.
5670 If TOTAL-ONLY is non-nil, only show the total time for the entire file
5671 in the echo area."
5672 (interactive)
5673 (org-remove-clock-overlays)
5674 (let (time h m p)
5675 (org-clock-sum)
5676 (unless total-only
5677 (save-excursion
5678 (goto-char (point-min))
5679 (while (setq p (next-single-property-change (point) :org-clock-minutes))
5680 (goto-char p)
5681 (when (setq time (get-text-property p :org-clock-minutes))
5682 (org-put-clock-overlay time (funcall outline-level))))
5683 (setq h (/ org-clock-file-total-minutes 60)
5684 m (- org-clock-file-total-minutes (* 60 h)))
5685 ;; Arrange to remove the overlays upon next change.
5686 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
5687 nil 'local)))
5688 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
5689
5690 (defvar org-clock-overlays nil)
5691 (defun org-put-clock-overlay (time &optional level)
5692 "Put an overlays on the current line, displaying TIME.
5693 If LEVEL is given, prefix time with a corresponding number of stars.
5694 This creates a new overlay and stores it in `org-clock-overlays', so that it
5695 will be easy to remove."
5696 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
5697 (l (if level (org-get-legal-level level 0) 0))
5698 (off 0)
5699 ov tx)
5700 (move-to-column c)
5701 (unless (eolp) (skip-chars-backward "^ \t"))
5702 (skip-chars-backward " \t")
5703 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
5704 tx (concat (buffer-substring (1- (point)) (point))
5705 (make-string (+ off (max 0 (- c (current-column)))) ?.)
5706 (org-add-props (format "%s %2d:%02d%s"
5707 (make-string l ?*) h m
5708 (make-string (- 10 l) ?\ ))
5709 '(face secondary-selection))
5710 ""))
5711 (org-overlay-put ov 'display tx)
5712 (push ov org-clock-overlays)))
5713
5714 (defun org-remove-clock-overlays (&optional beg end noremove)
5715 "Remove the occur highlights from the buffer.
5716 BEG and END are ignored. If NOREMOVE is nil, remove this function
5717 from the `before-change-functions' in the current buffer."
5718 (interactive)
5719 (unless org-inhibit-highlight-removal
5720 (mapc 'org-delete-overlay org-clock-overlays)
5721 (setq org-clock-overlays nil)
5722 (unless noremove
5723 (remove-hook 'before-change-functions
5724 'org-remove-clock-overlays 'local))))
5725
5726 (defun org-clock-out-if-current ()
5727 "Clock out if the current entry contains the running clock.
5728 This is used to stop the clock after a TODO entry is marked DONE."
5729 (when (and (equal state org-done-string)
5730 (equal (marker-buffer org-clock-marker) (current-buffer))
5731 (< (point) org-clock-marker)
5732 (> (save-excursion (outline-next-heading) (point))
5733 org-clock-marker))
5734 (org-clock-out)))
5735
5736 (add-hook 'org-after-todo-state-change-hook
5737 'org-clock-out-if-current)
5738
5739 (defun org-check-running-clock ()
5740 "Check if the current buffer contains the running clock.
5741 If yes, offer to stop it and to save the buffer with the changes."
5742 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
5743 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
5744 (buffer-name))))
5745 (org-clock-out)
5746 (when (y-or-n-p "Save changed buffer?")
5747 (save-buffer))))
5748
5749 (defun org-clock-report ()
5750 "Create a table containing a report about clocked time.
5751 If the buffer contains lines
5752 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
5753
5754 #+END: clocktable
5755 then the table will be inserted between these lines, replacing whatever
5756 is was there before. If these lines are not in the buffer, the table
5757 is inserted at point, surrounded by the special lines.
5758 The BEGIN line can contain parameters. Allowed are:
5759 :maxlevel The maximum level to be included in the table. Default is 3.
5760 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
5761 (interactive)
5762 (org-remove-clock-overlays)
5763 (unless (org-find-dblock "clocktable")
5764 (org-create-dblock (list :name "clocktable"
5765 :maxlevel 2 :emphasize nil)))
5766 (org-update-dblock))
5767
5768 (defun org-dblock-write:clocktable (params)
5769 "Write the standard clocktable."
5770 (let ((hlchars '((1 . "*") (2 . ?/)))
5771 (emph nil)
5772 (pos (point)) ipos
5773 (ins (make-marker))
5774 time h m p level hlc hdl maxlevel)
5775 (setq maxlevel (or (plist-get params :maxlevel) 3)
5776 emph (plist-get params :emphasize))
5777 (move-marker ins (point))
5778 (setq ipos (point))
5779 (insert-before-markers "Clock summary at ["
5780 (substring
5781 (format-time-string (cdr org-time-stamp-formats))
5782 1 -1)
5783 "]\n|L|Headline|Time|\n")
5784 (org-clock-sum)
5785 (setq h (/ org-clock-file-total-minutes 60)
5786 m (- org-clock-file-total-minutes (* 60 h)))
5787 (insert-before-markers "|-\n|0|" "*Total file time*| "
5788 (format "*%d:%02d*" h m)
5789 "|\n")
5790 (goto-char (point-min))
5791 (while (setq p (next-single-property-change (point) :org-clock-minutes))
5792 (goto-char p)
5793 (when (setq time (get-text-property p :org-clock-minutes))
5794 (beginning-of-line 1)
5795 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
5796 (setq level (- (match-end 1) (match-beginning 1)))
5797 (<= level maxlevel))
5798 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
5799 hdl (match-string 2)
5800 h (/ time 60)
5801 m (- time (* 60 h)))
5802 (save-excursion
5803 (goto-char ins)
5804 (if (= level 1) (insert-before-markers "|-\n"))
5805 (insert-before-markers
5806 "| " (int-to-string level) "|" hlc hdl hlc " |"
5807 (make-string (1- level) ?|)
5808 hlc
5809 (format "%d:%02d" h m)
5810 hlc
5811 " |\n")))))
5812 (goto-char ins)
5813 (backward-delete-char 1)
5814 (goto-char ipos)
5815 (skip-chars-forward "^|")
5816 (org-table-align)))
5817
5818 (defun org-collect-clock-time-entries ()
5819 "Return an internal list with clocking information.
5820 This list has one entry for each CLOCK interval.
5821 FIXME: describe the elements."
5822 (interactive)
5823 (let ((re (concat "^[ \t]*" org-clock-string
5824 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
5825 rtn beg end next cont level title total closedp leafp
5826 clockpos titlepos h m donep)
5827 (save-excursion
5828 (org-clock-sum)
5829 (goto-char (point-min))
5830 (while (re-search-forward re nil t)
5831 (setq clockpos (match-beginning 0)
5832 beg (match-string 1) end (match-string 2)
5833 cont (match-end 0))
5834 (setq beg (apply 'encode-time (org-parse-time-string beg))
5835 end (apply 'encode-time (org-parse-time-string end)))
5836 (org-back-to-heading t)
5837 (setq donep (org-entry-is-done-p))
5838 (setq titlepos (point)
5839 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
5840 h (/ total 60) m (- total (* 60 h))
5841 total (cons h m))
5842 (looking-at "\\(\\*+\\) +\\(.*\\)")
5843 (setq level (- (match-end 1) (match-beginning 1))
5844 title (org-match-string-no-properties 2))
5845 (save-excursion (outline-next-heading) (setq next (point)))
5846 (setq closedp (re-search-forward org-closed-time-regexp next t))
5847 (goto-char next)
5848 (setq leafp (and (looking-at "^\\*+ ")
5849 (<= (- (match-end 0) (point)) level)))
5850 (push (list beg end clockpos closedp donep
5851 total title titlepos level leafp)
5852 rtn)
5853 (goto-char cont)))
5854 (nreverse rtn)))
5855
5856 ;;; Agenda, and Diary Integration
5857
5858 ;;; Define the mode
5859
5860 (defvar org-agenda-mode-map (make-sparse-keymap)
5861 "Keymap for `org-agenda-mode'.")
5862
5863 (defvar org-agenda-menu) ; defined later in this file.
5864 (defvar org-agenda-follow-mode nil)
5865 (defvar org-agenda-show-log nil)
5866 (defvar org-agenda-buffer-name "*Org Agenda*")
5867 (defvar org-agenda-redo-command nil)
5868 (defvar org-agenda-mode-hook nil)
5869 (defvar org-agenda-type nil)
5870 (defvar org-agenda-force-single-file nil)
5871
5872 (defun org-agenda-mode ()
5873 "Mode for time-sorted view on action items in Org-mode files.
5874
5875 The following commands are available:
5876
5877 \\{org-agenda-mode-map}"
5878 (interactive)
5879 (kill-all-local-variables)
5880 (setq major-mode 'org-agenda-mode)
5881 (setq mode-name "Org-Agenda")
5882 (use-local-map org-agenda-mode-map)
5883 (easy-menu-add org-agenda-menu)
5884 (if org-startup-truncated (setq truncate-lines t))
5885 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
5886 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
5887 (unless org-agenda-keep-modes
5888 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
5889 org-agenda-show-log nil))
5890 (easy-menu-change
5891 '("Agenda") "Agenda Files"
5892 (append
5893 (list
5894 (vector
5895 (if (get 'org-agenda-files 'org-restrict)
5896 "Restricted to single file"
5897 "Edit File List")
5898 '(org-edit-agenda-file-list)
5899 (not (get 'org-agenda-files 'org-restrict)))
5900 "--")
5901 (mapcar 'org-file-menu-entry (org-agenda-files))))
5902 (org-agenda-set-mode-name)
5903 (apply
5904 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
5905 (list 'org-agenda-mode-hook)))
5906
5907 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
5908 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
5909 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
5910 (define-key org-agenda-mode-map " " 'org-agenda-show)
5911 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
5912 (define-key org-agenda-mode-map "o" 'delete-other-windows)
5913 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
5914 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
5915 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
5916 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
5917 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
5918 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
5919 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
5920 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
5921 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
5922 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
5923
5924 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
5925 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
5926 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
5927 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
5928 (while l (define-key org-agenda-mode-map
5929 (int-to-string (pop l)) 'digit-argument)))
5930
5931 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
5932 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
5933 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
5934 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
5935 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
5936 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
5937 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
5938 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
5939 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
5940 (define-key org-agenda-mode-map "n" 'next-line)
5941 (define-key org-agenda-mode-map "p" 'previous-line)
5942 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
5943 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
5944 (define-key org-agenda-mode-map "," 'org-agenda-priority)
5945 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
5946 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
5947 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
5948 (eval-after-load "calendar"
5949 '(define-key calendar-mode-map org-calendar-to-agenda-key
5950 'org-calendar-goto-agenda))
5951 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
5952 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
5953 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
5954 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
5955 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
5956 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
5957 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
5958 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
5959 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
5960 (define-key org-agenda-mode-map "O" 'org-clock-out)
5961 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
5962 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
5963 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
5964 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
5965 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
5966 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
5967 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
5968 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
5969 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
5970 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
5971 "Local keymap for agenda entries from Org-mode.")
5972
5973 (define-key org-agenda-keymap
5974 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
5975 (define-key org-agenda-keymap
5976 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
5977 (when org-agenda-mouse-1-follows-link
5978 (define-key org-agenda-keymap [follow-link] 'mouse-face))
5979 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
5980 '("Agenda"
5981 ("Agenda Files")
5982 "--"
5983 ["Show" org-agenda-show t]
5984 ["Go To (other window)" org-agenda-goto t]
5985 ["Go To (one window)" org-agenda-switch-to t]
5986 ["Follow Mode" org-agenda-follow-mode
5987 :style toggle :selected org-agenda-follow-mode :active t]
5988 "--"
5989 ["Cycle TODO" org-agenda-todo t]
5990 ("Tags"
5991 ["Show all Tags" org-agenda-show-tags t]
5992 ["Set Tags" org-agenda-set-tags t])
5993 ("Schedule"
5994 ["Schedule" org-agenda-schedule t]
5995 ["Set Deadline" org-agenda-deadline t]
5996 "--"
5997 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
5998 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
5999 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6000 ("Priority"
6001 ["Set Priority" org-agenda-priority t]
6002 ["Increase Priority" org-agenda-priority-up t]
6003 ["Decrease Priority" org-agenda-priority-down t]
6004 ["Show Priority" org-agenda-show-priority t])
6005 "--"
6006 ;; ["New agenda command" org-agenda t]
6007 ["Rebuild buffer" org-agenda-redo t]
6008 "--"
6009 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6010 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6011 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6012 "--"
6013 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6014 :style radio :selected (equal org-agenda-ndays 1)]
6015 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6016 :style radio :selected (equal org-agenda-ndays 7)]
6017 "--"
6018 ["Show Logbook entries" org-agenda-log-mode
6019 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6020 ["Include Diary" org-agenda-toggle-diary
6021 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6022 ["Use Time Grid" org-agenda-toggle-time-grid
6023 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6024 "--"
6025 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6026 ("Calendar Commands"
6027 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6028 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6029 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6030 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6031 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
6032 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
6033 "--"
6034 ["Quit" org-agenda-quit t]
6035 ["Exit and Release Buffers" org-agenda-exit t]
6036 ))
6037
6038 ;;;###autoload
6039 (defun org-agenda (arg)
6040 "Dispatch agenda commands to collect entries to the agenda buffer.
6041 Prompts for a character to select a command. Any prefix arg will be passed
6042 on to the selected command. The default selections are:
6043
6044 a Call `org-agenda' to display the agenda for the current day or week.
6045 t Call `org-todo-list' to display the global todo list.
6046 T Call `org-todo-list' to display the global todo list, select only
6047 entries with a specific TODO keyword (the user gets a prompt).
6048 m Call `org-tags-view' to display headlines with tags matching
6049 a condition (the user is prompted for the condition).
6050 M Like `m', but select only TODO entries, no ordinary headlines.
6051
6052 More commands can be added by configuring the variable
6053 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
6054 searches can be pre-defined in this way.
6055
6056 If the current buffer is in Org-mode and visiting a file, you can also
6057 first press `1' to indicate that the agenda should be temporarily (until the
6058 next use of \\[org-agenda]) restricted to the current file."
6059 (interactive "P")
6060 (catch 'exit
6061 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
6062 (bfn buffer-file-name)
6063 (custom org-agenda-custom-commands)
6064 c entry key type string)
6065 (put 'org-agenda-files 'org-restrict nil)
6066 (save-window-excursion
6067 (delete-other-windows)
6068 (switch-to-buffer-other-window " *Agenda Commands*")
6069 (erase-buffer)
6070 (insert
6071 "Press key for an agenda command:
6072 --------------------------------
6073 a Agenda for current week or day
6074 t List of all TODO entries T Entries with special TODO kwd
6075 m Match a TAGS query M Like m, but only TODO entries
6076 C Configure your own agenda commands")
6077 (while (setq entry (pop custom))
6078 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
6079 (insert (format "\n%-4s%-14s: %s"
6080 key
6081 (cond
6082 ((eq type 'tags) "Tags query")
6083 ((eq type 'todo) "TODO keyword")
6084 ((eq type 'tags-tree) "Tags tree")
6085 ((eq type 'todo-tree) "TODO kwd tree")
6086 ((eq type 'occur-tree) "Occur tree")
6087 (t "???"))
6088 (org-add-props string nil 'face 'org-warning))))
6089 (goto-char (point-min))
6090 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
6091 (message "Press key for agenda command%s"
6092 (if restrict-ok ", or [1] to restrict to current file" ""))
6093 (setq c (read-char-exclusive))
6094 (message "")
6095 (when (equal c ?1)
6096 (if restrict-ok
6097 (put 'org-agenda-files 'org-restrict (list bfn))
6098 (error "Cannot restrict agenda to current buffer"))
6099 (message "Press key for agenda command%s"
6100 (if restrict-ok " (restricted to current file)" ""))
6101 (setq c (read-char-exclusive))
6102 (message "")))
6103 (require 'calendar) ; FIXME: can we avoid this for some commands?
6104 ;; For example the todo list should not need it (but does...)
6105 (cond
6106 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
6107 ((equal c ?a) (call-interactively 'org-agenda-list))
6108 ((equal c ?t) (call-interactively 'org-todo-list))
6109 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
6110 ((equal c ?m) (call-interactively 'org-tags-view))
6111 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
6112 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
6113 (setq type (nth 1 entry) string (nth 2 entry))
6114 (cond
6115 ((eq type 'tags)
6116 (org-tags-view current-prefix-arg string))
6117 ((eq type 'tags-todo)
6118 (org-tags-view '(4) string))
6119 ((eq type 'todo)
6120 (org-todo-list string))
6121 ((eq type 'tags-tree)
6122 (org-check-for-org-mode)
6123 (org-tags-sparse-tree current-prefix-arg string))
6124 ((eq type 'todo-tree)
6125 (org-check-for-org-mode)
6126 (org-occur (concat "^" outline-regexp "[ \t]*"
6127 (regexp-quote string) "\\>")))
6128 ((eq type 'occur-tree)
6129 (org-check-for-org-mode)
6130 (org-occur string))
6131 (t (error "Invalid custom agenda command type %s" type))))
6132 (t (error "Invalid key"))))))
6133
6134 (defun org-check-for-org-mode ()
6135 "Make sure current buffer is in org-mode. Error if not."
6136 (or (eq major-mode 'org-mode)
6137 (error "Cannot execute org-mode agenda command on buffer in %s."
6138 major-mode)))
6139
6140 (defun org-fit-agenda-window ()
6141 "Fit the window to the buffer size."
6142 (and org-fit-agenda-window
6143 (fboundp 'fit-window-to-buffer)
6144 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
6145 (/ (frame-height) 2))))
6146
6147 (defun org-agenda-files (&optional unrestricted)
6148 "Get the list of agenda files.
6149 Optional UNRESTRICTED means return the full list even if a restriction
6150 is currently in place."
6151 (cond
6152 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
6153 ((stringp org-agenda-files) (org-read-agenda-file-list))
6154 ((listp org-agenda-files) org-agenda-files)
6155 (t (error "Invalid value of `org-agenda-files'"))))
6156
6157 (defvar org-window-configuration)
6158
6159 (defun org-edit-agenda-file-list ()
6160 "Edit the list of agenda files.
6161 Depending on setup, this either uses customize to edit the variable
6162 `org-agenda-files', or it visits the file that is holding the list. In the
6163 latter case, the buffer is set up in a way that saving it automatically kills
6164 the buffer and restores the previous window configuration."
6165 (interactive)
6166 (if (stringp org-agenda-files)
6167 (let ((cw (current-window-configuration)))
6168 (find-file org-agenda-files)
6169 (set (make-local-variable 'org-window-configuration) cw)
6170 (org-add-hook 'after-save-hook
6171 (lambda ()
6172 (set-window-configuration
6173 (prog1 org-window-configuration
6174 (kill-buffer (current-buffer))))
6175 (org-install-agenda-files-menu)
6176 (message "New agenda file list installed"))
6177 nil 'local)
6178 (message (substitute-command-keys
6179 "Edit list and finish with \\[save-buffer]")))
6180 (customize-variable 'org-agenda-files)))
6181
6182 (defun org-store-new-agenda-file-list (list)
6183 "Set new value for the agenda file list and save it correcly."
6184 (if (stringp org-agenda-files)
6185 (let ((f org-agenda-files) b)
6186 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
6187 (with-temp-file f
6188 (insert (mapconcat 'identity list "\n") "\n")))
6189 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
6190 (setq org-agenda-files list)
6191 (customize-save-variable 'org-agenda-files org-agenda-files))))
6192
6193 (defun org-read-agenda-file-list ()
6194 "Read the list of agenda files from a file."
6195 (when (stringp org-agenda-files)
6196 (with-temp-buffer
6197 (insert-file-contents org-agenda-files)
6198 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
6199
6200 (defvar org-agenda-markers nil
6201 "List of all currently active markers created by `org-agenda'.")
6202 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
6203 "Creation time of the last agenda marker.")
6204
6205 (defun org-agenda-new-marker (&optional pos)
6206 "Return a new agenda marker.
6207 Org-mode keeps a list of these markers and resets them when they are
6208 no longer in use."
6209 (let ((m (copy-marker (or pos (point)))))
6210 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
6211 (push m org-agenda-markers)
6212 m))
6213
6214 (defun org-agenda-maybe-reset-markers (&optional force)
6215 "Reset markers created by `org-agenda'. But only if they are old enough."
6216 (if (or force
6217 (> (- (time-to-seconds (current-time))
6218 org-agenda-last-marker-time)
6219 5))
6220 (while org-agenda-markers
6221 (move-marker (pop org-agenda-markers) nil))))
6222
6223 (defvar org-agenda-new-buffers nil
6224 "Buffers created to visit agenda files.")
6225
6226 (defun org-get-agenda-file-buffer (file)
6227 "Get a buffer visiting FILE. If the buffer needs to be created, add
6228 it to the list of buffers which might be released later."
6229 (let ((buf (find-buffer-visiting file)))
6230 (if buf
6231 buf ; just return it
6232 ;; Make a new buffer and remember it
6233 (setq buf (find-file-noselect file))
6234 (if buf (push buf org-agenda-new-buffers))
6235 buf)))
6236
6237 (defun org-release-buffers (blist)
6238 "Release all buffers in list, asking the user for confirmation when needed.
6239 When a buffer is unmodified, it is just killed. When modified, it is saved
6240 \(if the user agrees) and then killed."
6241 (let (buf file)
6242 (while (setq buf (pop blist))
6243 (setq file (buffer-file-name buf))
6244 (when (and (buffer-modified-p buf)
6245 file
6246 (y-or-n-p (format "Save file %s? " file)))
6247 (with-current-buffer buf (save-buffer)))
6248 (kill-buffer buf))))
6249
6250 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
6251
6252 (defun org-timeline (&optional include-all keep-modes)
6253 "Show a time-sorted view of the entries in the current org file.
6254 Only entries with a time stamp of today or later will be listed. With
6255 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
6256 under the current date.
6257 If the buffer contains an active region, only check the region for
6258 dates."
6259 (interactive "P")
6260 (require 'calendar)
6261 (org-agenda-maybe-reset-markers 'force)
6262 (org-compile-prefix-format org-timeline-prefix-format)
6263 (let* ((dopast t)
6264 (dotodo include-all)
6265 (doclosed org-agenda-show-log)
6266 (org-agenda-keep-modes keep-modes)
6267 (entry buffer-file-name)
6268 (org-agenda-files (list buffer-file-name))
6269 (date (calendar-current-date))
6270 (win (selected-window))
6271 (pos1 (point))
6272 (beg (if (org-region-active-p) (region-beginning) (point-min)))
6273 (end (if (org-region-active-p) (region-end) (point-max)))
6274 (day-numbers (org-get-all-dates beg end 'no-ranges
6275 t doclosed ; always include today
6276 org-timeline-show-empty-dates))
6277 (today (time-to-days (current-time)))
6278 (org-respect-restriction t)
6279 (past t)
6280 args
6281 s e rtn d emptyp)
6282 (setq org-agenda-redo-command
6283 (list 'progn
6284 (list 'switch-to-buffer-other-window (current-buffer))
6285 (list 'org-timeline (list 'quote include-all) t)))
6286 (if (not dopast)
6287 ;; Remove past dates from the list of dates.
6288 (setq day-numbers (delq nil (mapcar (lambda(x)
6289 (if (>= x today) x nil))
6290 day-numbers))))
6291 (switch-to-buffer-other-window
6292 (get-buffer-create org-agenda-buffer-name))
6293 (setq buffer-read-only nil)
6294 (erase-buffer)
6295 (org-agenda-mode) (setq buffer-read-only nil)
6296 (set (make-local-variable 'org-agenda-type) 'timeline)
6297 (if doclosed (push :closed args))
6298 (push :timestamp args)
6299 (if dotodo (push :todo args))
6300 (while (setq d (pop day-numbers))
6301 (if (and (listp d) (eq (car d) :omitted))
6302 (progn
6303 (setq s (point))
6304 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
6305 (put-text-property s (1- (point)) 'face 'org-level-3))
6306 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
6307 (if (and (>= d today)
6308 dopast
6309 past)
6310 (progn
6311 (setq past nil)
6312 (insert (make-string 79 ?-) "\n")))
6313 (setq date (calendar-gregorian-from-absolute d))
6314 (setq s (point))
6315 (setq rtn (and (not emptyp)
6316 (apply 'org-agenda-get-day-entries
6317 entry date args)))
6318 (if (or rtn (equal d today) org-timeline-show-empty-dates)
6319 (progn
6320 (insert (calendar-day-name date) " "
6321 (number-to-string (extract-calendar-day date)) " "
6322 (calendar-month-name (extract-calendar-month date)) " "
6323 (number-to-string (extract-calendar-year date)) "\n")
6324 (put-text-property s (1- (point)) 'face
6325 'org-level-3)
6326 (if (equal d today)
6327 (put-text-property s (1- (point)) 'org-today t))
6328 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
6329 (put-text-property s (1- (point)) 'day d)))))
6330 (goto-char (point-min))
6331 (setq buffer-read-only t)
6332 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6333 (point-min)))
6334 (when (not org-select-timeline-window)
6335 (select-window win)
6336 (goto-char pos1))))
6337
6338 ;;;###autoload
6339 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
6340 "Produce a weekly view from all files in variable `org-agenda-files'.
6341 The view will be for the current week, but from the overview buffer you
6342 will be able to go to other weeks.
6343 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
6344 also be shown, under the current date.
6345 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
6346 on the days are also shown. See the variable `org-log-done' for how
6347 to turn on logging.
6348 START-DAY defaults to TODAY, or to the most recent match for the weekday
6349 given in `org-agenda-start-on-weekday'.
6350 NDAYS defaults to `org-agenda-ndays'."
6351 (interactive "P")
6352 (org-agenda-maybe-reset-markers 'force)
6353 (org-compile-prefix-format org-agenda-prefix-format)
6354 (require 'calendar)
6355 (let* ((org-agenda-start-on-weekday
6356 (if (or (equal ndays 1)
6357 (and (null ndays) (equal 1 org-agenda-ndays)))
6358 nil org-agenda-start-on-weekday))
6359 (org-agenda-keep-modes keep-modes)
6360 (thefiles (org-agenda-files))
6361 (files thefiles)
6362 (win (selected-window))
6363 (today (time-to-days (current-time)))
6364 (sd (or start-day today))
6365 (start (if (or (null org-agenda-start-on-weekday)
6366 (< org-agenda-ndays 7))
6367 sd
6368 (let* ((nt (calendar-day-of-week
6369 (calendar-gregorian-from-absolute sd)))
6370 (n1 org-agenda-start-on-weekday)
6371 (d (- nt n1)))
6372 (- sd (+ (if (< d 0) 7 0) d)))))
6373 (day-numbers (list start))
6374 (inhibit-redisplay t)
6375 s e rtn rtnall file date d start-pos end-pos todayp nd)
6376 (setq org-agenda-redo-command
6377 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
6378 ;; Make the list of days
6379 (setq ndays (or ndays org-agenda-ndays)
6380 nd ndays)
6381 (while (> ndays 1)
6382 (push (1+ (car day-numbers)) day-numbers)
6383 (setq ndays (1- ndays)))
6384 (setq day-numbers (nreverse day-numbers))
6385 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6386 (progn
6387 (delete-other-windows)
6388 (switch-to-buffer-other-window
6389 (get-buffer-create org-agenda-buffer-name))))
6390 (setq buffer-read-only nil)
6391 (erase-buffer)
6392 (org-agenda-mode) (setq buffer-read-only nil)
6393 (set (make-local-variable 'org-agenda-type) 'agenda)
6394 (set (make-local-variable 'starting-day) (car day-numbers))
6395 (set (make-local-variable 'include-all-loc) include-all)
6396 (when (and (or include-all org-agenda-include-all-todo)
6397 (member today day-numbers))
6398 (setq files thefiles
6399 rtnall nil)
6400 (while (setq file (pop files))
6401 (catch 'nextfile
6402 (org-check-agenda-file file)
6403 (setq date (calendar-gregorian-from-absolute today)
6404 rtn (org-agenda-get-day-entries
6405 file date :todo))
6406 (setq rtnall (append rtnall rtn))))
6407 (when rtnall
6408 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
6409 (add-text-properties (point-min) (1- (point))
6410 (list 'face 'org-level-3))
6411 (insert (org-finalize-agenda-entries rtnall) "\n")))
6412 (while (setq d (pop day-numbers))
6413 (setq date (calendar-gregorian-from-absolute d)
6414 s (point))
6415 (if (or (setq todayp (= d today))
6416 (and (not start-pos) (= d sd)))
6417 (setq start-pos (point))
6418 (if (and start-pos (not end-pos))
6419 (setq end-pos (point))))
6420 (setq files thefiles
6421 rtnall nil)
6422 (while (setq file (pop files))
6423 (catch 'nextfile
6424 (org-check-agenda-file file)
6425 (if org-agenda-show-log
6426 (setq rtn (org-agenda-get-day-entries
6427 file date
6428 :deadline :scheduled :timestamp :closed))
6429 (setq rtn (org-agenda-get-day-entries
6430 file date
6431 :deadline :scheduled :timestamp)))
6432 (setq rtnall (append rtnall rtn))))
6433 (if org-agenda-include-diary
6434 (progn
6435 (require 'diary-lib)
6436 (setq rtn (org-get-entries-from-diary date))
6437 (setq rtnall (append rtnall rtn))))
6438 (if (or rtnall org-agenda-show-all-dates)
6439 (progn
6440 (insert (format "%-9s %2d %s %4d\n"
6441 (calendar-day-name date)
6442 (extract-calendar-day date)
6443 (calendar-month-name (extract-calendar-month date))
6444 (extract-calendar-year date)))
6445 (put-text-property s (1- (point)) 'face
6446 'org-level-3)
6447 (if rtnall (insert
6448 (org-finalize-agenda-entries
6449 (org-agenda-add-time-grid-maybe
6450 rtnall nd todayp))
6451 "\n"))
6452 (put-text-property s (1- (point)) 'day d))))
6453 (goto-char (point-min))
6454 (setq buffer-read-only t)
6455 (org-fit-agenda-window)
6456 (unless (and (pos-visible-in-window-p (point-min))
6457 (pos-visible-in-window-p (point-max)))
6458 (goto-char (1- (point-max)))
6459 (recenter -1)
6460 (if (not (pos-visible-in-window-p (or start-pos 1)))
6461 (progn
6462 (goto-char (or start-pos 1))
6463 (recenter 1))))
6464 (goto-char (or start-pos 1))
6465 (if (not org-select-agenda-window) (select-window win))
6466 (message "")))
6467
6468 (defvar org-select-this-todo-keyword nil)
6469
6470 ;;;###autoload
6471 (defun org-todo-list (arg &optional keep-modes)
6472 "Show all TODO entries from all agenda file in a single list.
6473 The prefix arg can be used to select a specific TODO keyword and limit
6474 the list to these. When using \\[universal-argument], you will be prompted
6475 for a keyword. A numeric prefix directly selects the Nth keyword in
6476 `org-todo-keywords'."
6477 (interactive "P")
6478 (org-agenda-maybe-reset-markers 'force)
6479 (org-compile-prefix-format org-agenda-prefix-format)
6480 (let* ((org-agenda-keep-modes keep-modes)
6481 (today (time-to-days (current-time)))
6482 (date (calendar-gregorian-from-absolute today))
6483 (win (selected-window))
6484 (kwds org-todo-keywords)
6485 (completion-ignore-case t)
6486 (org-select-this-todo-keyword
6487 (if (stringp arg) arg
6488 (and arg (integerp arg) (> arg 0)
6489 (nth (1- arg) org-todo-keywords))))
6490 rtn rtnall files file pos)
6491 (when (equal arg '(4))
6492 (setq org-select-this-todo-keyword
6493 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
6494 nil t)))
6495 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
6496 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6497 (progn
6498 (delete-other-windows)
6499 (switch-to-buffer-other-window
6500 (get-buffer-create org-agenda-buffer-name))))
6501 (setq buffer-read-only nil)
6502 (erase-buffer)
6503 (org-agenda-mode) (setq buffer-read-only nil)
6504 (set (make-local-variable 'org-agenda-type) 'todo)
6505 (set (make-local-variable 'last-arg) arg)
6506 (set (make-local-variable 'org-todo-keywords) kwds)
6507 (set (make-local-variable 'org-agenda-redo-command)
6508 '(org-todo-list (or current-prefix-arg last-arg) t))
6509 (setq files (org-agenda-files)
6510 rtnall nil)
6511 (while (setq file (pop files))
6512 (catch 'nextfile
6513 (org-check-agenda-file file)
6514 (setq rtn (org-agenda-get-day-entries file date :todo))
6515 (setq rtnall (append rtnall rtn))))
6516 (insert "Global list of TODO items of type: ")
6517 (add-text-properties (point-min) (1- (point))
6518 (list 'face 'org-level-3))
6519 (setq pos (point))
6520 (insert (or org-select-this-todo-keyword "ALL") "\n")
6521 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6522 (setq pos (point))
6523 (insert
6524 "Available with `N r': (0)ALL "
6525 (let ((n 0))
6526 (mapconcat (lambda (x)
6527 (format "(%d)%s" (setq n (1+ n)) x))
6528 org-todo-keywords " "))
6529 "\n")
6530 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
6531 (when rtnall
6532 (insert (org-finalize-agenda-entries rtnall) "\n"))
6533 (goto-char (point-min))
6534 (setq buffer-read-only t)
6535 (org-fit-agenda-window)
6536 (if (not org-select-agenda-window) (select-window win))))
6537
6538 (defun org-check-agenda-file (file)
6539 "Make sure FILE exists. If not, ask user what to do."
6540 (when (not (file-exists-p file))
6541 (message "non-existent file %s. [R]emove from list or [A]bort?"
6542 (abbreviate-file-name file))
6543 (let ((r (downcase (read-char-exclusive))))
6544 (cond
6545 ((equal r ?r)
6546 (org-remove-file file)
6547 (throw 'nextfile t))
6548 (t (error "Abort"))))))
6549
6550 (defun org-agenda-check-type (error &rest types)
6551 "Check if agenda buffer is of allowed type.
6552 If ERROR is non-nil, throw an error, otherwise just return nil."
6553 (if (memq org-agenda-type types)
6554 t
6555 (if error
6556 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
6557 nil)))
6558
6559 (defun org-agenda-quit ()
6560 "Exit agenda by removing the window or the buffer."
6561 (interactive)
6562 (let ((buf (current-buffer)))
6563 (if (not (one-window-p)) (delete-window))
6564 (kill-buffer buf)
6565 (org-agenda-maybe-reset-markers 'force)))
6566
6567 (defun org-agenda-exit ()
6568 "Exit agenda by removing the window or the buffer.
6569 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
6570 Org-mode buffers visited directly by the user will not be touched."
6571 (interactive)
6572 (org-release-buffers org-agenda-new-buffers)
6573 (setq org-agenda-new-buffers nil)
6574 (org-agenda-quit))
6575
6576 (defun org-agenda-redo ()
6577 "Rebuild Agenda.
6578 When this is the global TODO list, a prefix argument will be interpreted."
6579 (interactive)
6580 (message "Rebuilding agenda buffer...")
6581 (eval org-agenda-redo-command)
6582 (message "Rebuilding agenda buffer...done"))
6583
6584 (defun org-agenda-goto-today ()
6585 "Go to today."
6586 (interactive)
6587 (org-agenda-check-type t 'timeline 'agenda)
6588 (if (boundp 'starting-day)
6589 (let ((cmd (car org-agenda-redo-command))
6590 (iall (nth 1 org-agenda-redo-command))
6591 (nday (nth 3 org-agenda-redo-command))
6592 (keep (nth 4 org-agenda-redo-command)))
6593 (eval (list cmd iall nil nday keep)))
6594 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6595 (point-min)))))
6596
6597 (defun org-agenda-later (arg)
6598 "Go forward in time by `org-agenda-ndays' days.
6599 With prefix ARG, go forward that many times `org-agenda-ndays'."
6600 (interactive "p")
6601 (org-agenda-check-type t 'agenda)
6602 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6603 (+ starting-day (* arg org-agenda-ndays)) nil t))
6604
6605 (defun org-agenda-earlier (arg)
6606 "Go back in time by `org-agenda-ndays' days.
6607 With prefix ARG, go back that many times `org-agenda-ndays'."
6608 (interactive "p")
6609 (org-agenda-check-type t 'agenda)
6610 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6611 (- starting-day (* arg org-agenda-ndays)) nil t))
6612
6613 (defun org-agenda-week-view ()
6614 "Switch to weekly view for agenda."
6615 (interactive)
6616 (org-agenda-check-type t 'agenda)
6617 (setq org-agenda-ndays 7)
6618 (org-agenda-list include-all-loc
6619 (or (get-text-property (point) 'day)
6620 starting-day)
6621 nil t)
6622 (org-agenda-set-mode-name)
6623 (message "Switched to week view"))
6624
6625 (defun org-agenda-day-view ()
6626 "Switch to daily view for agenda."
6627 (interactive)
6628 (org-agenda-check-type t 'agenda)
6629 (setq org-agenda-ndays 1)
6630 (org-agenda-list include-all-loc
6631 (or (get-text-property (point) 'day)
6632 starting-day)
6633 nil t)
6634 (org-agenda-set-mode-name)
6635 (message "Switched to day view"))
6636
6637 (defun org-agenda-next-date-line (&optional arg)
6638 "Jump to the next line indicating a date in agenda buffer."
6639 (interactive "p")
6640 (org-agenda-check-type t 'agenda 'timeline)
6641 (beginning-of-line 1)
6642 (if (looking-at "^\\S-") (forward-char 1))
6643 (if (not (re-search-forward "^\\S-" nil t arg))
6644 (progn
6645 (backward-char 1)
6646 (error "No next date after this line in this buffer")))
6647 (goto-char (match-beginning 0)))
6648
6649 (defun org-agenda-previous-date-line (&optional arg)
6650 "Jump to the previous line indicating a date in agenda buffer."
6651 (interactive "p")
6652 (org-agenda-check-type t 'agenda 'timeline)
6653 (beginning-of-line 1)
6654 (if (not (re-search-backward "^\\S-" nil t arg))
6655 (error "No previous date before this line in this buffer")))
6656
6657 ;; Initialize the highlight
6658 (defvar org-hl (org-make-overlay 1 1))
6659 (org-overlay-put org-hl 'face 'highlight)
6660
6661 (defun org-highlight (begin end &optional buffer)
6662 "Highlight a region with overlay."
6663 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
6664 org-hl begin end (or buffer (current-buffer))))
6665
6666 (defun org-unhighlight ()
6667 "Detach overlay INDEX."
6668 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
6669
6670
6671 (defun org-agenda-follow-mode ()
6672 "Toggle follow mode in an agenda buffer."
6673 (interactive)
6674 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
6675 (org-agenda-set-mode-name)
6676 (message "Follow mode is %s"
6677 (if org-agenda-follow-mode "on" "off")))
6678
6679 (defun org-agenda-log-mode ()
6680 "Toggle log mode in an agenda buffer."
6681 (interactive)
6682 (org-agenda-check-type t 'agenda 'timeline)
6683 (setq org-agenda-show-log (not org-agenda-show-log))
6684 (org-agenda-set-mode-name)
6685 (org-agenda-redo)
6686 (message "Log mode is %s"
6687 (if org-agenda-show-log "on" "off")))
6688
6689 (defun org-agenda-toggle-diary ()
6690 "Toggle diary inclusion in an agenda buffer."
6691 (interactive)
6692 (org-agenda-check-type t 'agenda)
6693 (setq org-agenda-include-diary (not org-agenda-include-diary))
6694 (org-agenda-redo)
6695 (org-agenda-set-mode-name)
6696 (message "Diary inclusion turned %s"
6697 (if org-agenda-include-diary "on" "off")))
6698
6699 (defun org-agenda-toggle-time-grid ()
6700 "Toggle time grid in an agenda buffer."
6701 (interactive)
6702 (org-agenda-check-type t 'agenda)
6703 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
6704 (org-agenda-redo)
6705 (org-agenda-set-mode-name)
6706 (message "Time-grid turned %s"
6707 (if org-agenda-use-time-grid "on" "off")))
6708
6709 (defun org-agenda-set-mode-name ()
6710 "Set the mode name to indicate all the small mode settings."
6711 (setq mode-name
6712 (concat "Org-Agenda"
6713 (if (equal org-agenda-ndays 1) " Day" "")
6714 (if (equal org-agenda-ndays 7) " Week" "")
6715 (if org-agenda-follow-mode " Follow" "")
6716 (if org-agenda-include-diary " Diary" "")
6717 (if org-agenda-use-time-grid " Grid" "")
6718 (if org-agenda-show-log " Log" "")))
6719 (force-mode-line-update))
6720
6721 (defun org-agenda-post-command-hook ()
6722 (and (eolp) (not (bolp)) (backward-char 1))
6723 (if (and org-agenda-follow-mode
6724 (get-text-property (point) 'org-marker))
6725 (org-agenda-show)))
6726
6727 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
6728
6729 (defun org-get-entries-from-diary (date)
6730 "Get the (Emacs Calendar) diary entries for DATE."
6731 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
6732 (diary-display-hook '(fancy-diary-display))
6733 (list-diary-entries-hook
6734 (cons 'org-diary-default-entry list-diary-entries-hook))
6735 (diary-file-name-prefix-function nil) ; turn this feature off
6736 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
6737 entries
6738 (org-disable-agenda-to-diary t))
6739 (save-excursion
6740 (save-window-excursion
6741 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
6742 (if (not (get-buffer fancy-diary-buffer))
6743 (setq entries nil)
6744 (with-current-buffer fancy-diary-buffer
6745 (setq buffer-read-only nil)
6746 (if (= (point-max) 1)
6747 ;; No entries
6748 (setq entries nil)
6749 ;; Omit the date and other unnecessary stuff
6750 (org-agenda-cleanup-fancy-diary)
6751 ;; Add prefix to each line and extend the text properties
6752 (if (= (point-max) 1)
6753 (setq entries nil)
6754 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
6755 (set-buffer-modified-p nil)
6756 (kill-buffer fancy-diary-buffer)))
6757 (when entries
6758 (setq entries (org-split-string entries "\n"))
6759 (setq entries
6760 (mapcar
6761 (lambda (x)
6762 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
6763 ;; Extend the text properties to the beginning of the line
6764 (org-add-props x (text-properties-at (1- (length x)) x)))
6765 entries)))))
6766
6767 (defun org-agenda-cleanup-fancy-diary ()
6768 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
6769 This gets rid of the date, the underline under the date, and
6770 the dummy entry installed by `org-mode' to ensure non-empty diary for each
6771 date. It also removes lines that contain only whitespace."
6772 (goto-char (point-min))
6773 (if (looking-at ".*?:[ \t]*")
6774 (progn
6775 (replace-match "")
6776 (re-search-forward "\n=+$" nil t)
6777 (replace-match "")
6778 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
6779 (re-search-forward "\n=+$" nil t)
6780 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
6781 (goto-char (point-min))
6782 (while (re-search-forward "^ +\n" nil t)
6783 (replace-match ""))
6784 (goto-char (point-min))
6785 (if (re-search-forward "^Org-mode dummy\n?" nil t)
6786 (replace-match "")))
6787
6788 ;; Make sure entries from the diary have the right text properties.
6789 (eval-after-load "diary-lib"
6790 '(if (boundp 'diary-modify-entry-list-string-function)
6791 ;; We can rely on the hook, nothing to do
6792 nil
6793 ;; Hook not avaiable, must use advice to make this work
6794 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
6795 "Make the position visible."
6796 (if (and org-disable-agenda-to-diary ;; called from org-agenda
6797 (stringp string)
6798 buffer-file-name)
6799 (setq string (org-modify-diary-entry-string string))))))
6800
6801 (defun org-modify-diary-entry-string (string)
6802 "Add text properties to string, allowing org-mode to act on it."
6803 (org-add-props string nil
6804 'mouse-face 'highlight
6805 'keymap org-agenda-keymap
6806 'help-echo (format "mouse-2 or RET jump to diary file %s"
6807 (abbreviate-file-name buffer-file-name))
6808 'org-agenda-diary-link t
6809 'org-marker (org-agenda-new-marker (point-at-bol))))
6810
6811 (defun org-diary-default-entry ()
6812 "Add a dummy entry to the diary.
6813 Needed to avoid empty dates which mess up holiday display."
6814 ;; Catch the error if dealing with the new add-to-diary-alist
6815 (when org-disable-agenda-to-diary
6816 (condition-case nil
6817 (add-to-diary-list original-date "Org-mode dummy" "")
6818 (error
6819 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
6820
6821 (defun org-cycle-agenda-files ()
6822 "Cycle through the files in `org-agenda-files'.
6823 If the current buffer visits an agenda file, find the next one in the list.
6824 If the current buffer does not, find the first agenda file."
6825 (interactive)
6826 (let* ((fs (org-agenda-files t))
6827 (files (append fs (list (car fs))))
6828 (tcf (if buffer-file-name (file-truename buffer-file-name)))
6829 file)
6830 (unless files (error "No agenda files"))
6831 (catch 'exit
6832 (while (setq file (pop files))
6833 (if (equal (file-truename file) tcf)
6834 (when (car files)
6835 (find-file (car files))
6836 (throw 'exit t))))
6837 (find-file (car fs)))))
6838
6839 (defun org-agenda-file-to-end ()
6840 "Move/add the current file to the end of the agenda file list.
6841 If the file is not present in the list, it is appended to the list. If it is
6842 present, it is moved there."
6843 (interactive)
6844 (org-agenda-file-to-front 'to-end))
6845
6846 (defun org-agenda-file-to-front (&optional to-end)
6847 "Move/add the current file to the top of the agenda file list.
6848 If the file is not present in the list, it is added to the front. If it is
6849 present, it is moved there. With optional argument TO-END, add/move to the
6850 end of the list."
6851 (interactive "P")
6852 (let ((file-alist (mapcar (lambda (x)
6853 (cons (file-truename x) x))
6854 (org-agenda-files t)))
6855 (ctf (file-truename buffer-file-name))
6856 x had)
6857 (setq x (assoc ctf file-alist) had x)
6858
6859 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
6860 (if to-end
6861 (setq file-alist (append (delq x file-alist) (list x)))
6862 (setq file-alist (cons x (delq x file-alist))))
6863 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
6864 (org-install-agenda-files-menu)
6865 (message "File %s to %s of agenda file list"
6866 (if had "moved" "added") (if to-end "end" "front"))))
6867
6868 (defun org-remove-file (&optional file)
6869 "Remove current file from the list of files in variable `org-agenda-files'.
6870 These are the files which are being checked for agenda entries.
6871 Optional argument FILE means, use this file instead of the current."
6872 (interactive)
6873 (let* ((file (or file buffer-file-name))
6874 (true-file (file-truename file))
6875 (afile (abbreviate-file-name file))
6876 (files (delq nil (mapcar
6877 (lambda (x)
6878 (if (equal true-file
6879 (file-truename x))
6880 nil x))
6881 (org-agenda-files t)))))
6882 (if (not (= (length files) (length (org-agenda-files t))))
6883 (progn
6884 (org-store-new-agenda-file-list files)
6885 (org-install-agenda-files-menu)
6886 (message "Removed file: %s" afile))
6887 (message "File was not in list: %s" afile))))
6888
6889 (defun org-file-menu-entry (file)
6890 (vector file (list 'find-file file) t))
6891
6892 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
6893 "Return a list of all relevant day numbers from BEG to END buffer positions.
6894 If NO-RANGES is non-nil, include only the start and end dates of a range,
6895 not every single day in the range. If FORCE-TODAY is non-nil, make
6896 sure that TODAY is included in the list. If INACTIVE is non-nil, also
6897 inactive time stamps (those in square brackets) are included.
6898 When EMPTY is non-nil, also include days without any entries."
6899 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
6900 dates dates1 date day day1 day2 ts1 ts2)
6901 (if force-today
6902 (setq dates (list (time-to-days (current-time)))))
6903 (save-excursion
6904 (goto-char beg)
6905 (while (re-search-forward re end t)
6906 (setq day (time-to-days (org-time-string-to-time
6907 (substring (match-string 1) 0 10))))
6908 (or (memq day dates) (push day dates)))
6909 (unless no-ranges
6910 (goto-char beg)
6911 (while (re-search-forward org-tr-regexp end t)
6912 (setq ts1 (substring (match-string 1) 0 10)
6913 ts2 (substring (match-string 2) 0 10)
6914 day1 (time-to-days (org-time-string-to-time ts1))
6915 day2 (time-to-days (org-time-string-to-time ts2)))
6916 (while (< (setq day1 (1+ day1)) day2)
6917 (or (memq day1 dates) (push day1 dates)))))
6918 (setq dates (sort dates '<))
6919 (when empty
6920 (while (setq day (pop dates))
6921 (setq day2 (car dates))
6922 (push day dates1)
6923 (when (and day2 empty)
6924 (if (or (eq empty t)
6925 (and (numberp empty) (<= (- day2 day) empty)))
6926 (while (< (setq day (1+ day)) day2)
6927 (push (list day) dates1))
6928 (push (cons :omitted (- day2 day)) dates1))))
6929 (setq dates (nreverse dates1)))
6930 dates)))
6931
6932 ;;;###autoload
6933 (defun org-diary (&rest args)
6934 "Return diary information from org-files.
6935 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
6936 It accesses org files and extracts information from those files to be
6937 listed in the diary. The function accepts arguments specifying what
6938 items should be listed. The following arguments are allowed:
6939
6940 :timestamp List the headlines of items containing a date stamp or
6941 date range matching the selected date. Deadlines will
6942 also be listed, on the expiration day.
6943
6944 :deadline List any deadlines past due, or due within
6945 `org-deadline-warning-days'. The listing occurs only
6946 in the diary for *today*, not at any other date. If
6947 an entry is marked DONE, it is no longer listed.
6948
6949 :scheduled List all items which are scheduled for the given date.
6950 The diary for *today* also contains items which were
6951 scheduled earlier and are not yet marked DONE.
6952
6953 :todo List all TODO items from the org-file. This may be a
6954 long list - so this is not turned on by default.
6955 Like deadlines, these entries only show up in the
6956 diary for *today*, not at any other date.
6957
6958 The call in the diary file should look like this:
6959
6960 &%%(org-diary) ~/path/to/some/orgfile.org
6961
6962 Use a separate line for each org file to check. Or, if you omit the file name,
6963 all files listed in `org-agenda-files' will be checked automatically:
6964
6965 &%%(org-diary)
6966
6967 If you don't give any arguments (as in the example above), the default
6968 arguments (:deadline :scheduled :timestamp) are used. So the example above may
6969 also be written as
6970
6971 &%%(org-diary :deadline :timestamp :scheduled)
6972
6973 The function expects the lisp variables `entry' and `date' to be provided
6974 by the caller, because this is how the calendar works. Don't use this
6975 function from a program - use `org-agenda-get-day-entries' instead."
6976 (org-agenda-maybe-reset-markers)
6977 (org-compile-prefix-format org-agenda-prefix-format)
6978 (setq args (or args '(:deadline :scheduled :timestamp)))
6979 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
6980 (list entry)
6981 (org-agenda-files t)))
6982 file rtn results)
6983 ;; If this is called during org-agenda, don't return any entries to
6984 ;; the calendar. Org Agenda will list these entries itself.
6985 (if org-disable-agenda-to-diary (setq files nil))
6986 (while (setq file (pop files))
6987 (setq rtn (apply 'org-agenda-get-day-entries file date args))
6988 (setq results (append results rtn)))
6989 (if results
6990 (concat (org-finalize-agenda-entries results) "\n"))))
6991 (defvar org-category-table nil)
6992 (defun org-get-category-table ()
6993 "Get the table of categories and positions in current buffer."
6994 (let (tbl)
6995 (save-excursion
6996 (goto-char (point-min))
6997 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
6998 (push (cons (point) (org-trim (match-string 2))) tbl)))
6999 tbl))
7000 (defun org-get-category (&optional pos)
7001 "Get the category applying to position POS."
7002 (if (not org-category-table)
7003 (cond
7004 ((null org-category)
7005 (setq org-category
7006 (if buffer-file-name
7007 (file-name-sans-extension
7008 (file-name-nondirectory buffer-file-name))
7009 "???")))
7010 ((symbolp org-category) (symbol-name org-category))
7011 (t org-category))
7012 (let ((tbl org-category-table)
7013 (pos (or pos (point))))
7014 (while (and tbl (> (caar tbl) pos))
7015 (pop tbl))
7016 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
7017 org-category-table))))))
7018
7019 (defun org-agenda-get-day-entries (file date &rest args)
7020 "Does the work for `org-diary' and `org-agenda'.
7021 FILE is the path to a file to be checked for entries. DATE is date like
7022 the one returned by `calendar-current-date'. ARGS are symbols indicating
7023 which kind of entries should be extracted. For details about these, see
7024 the documentation of `org-diary'."
7025 (setq args (or args '(:deadline :scheduled :timestamp)))
7026 (let* ((org-startup-with-deadline-check nil)
7027 (org-startup-folded nil)
7028 (org-startup-align-all-tables nil)
7029 (buffer (if (file-exists-p file)
7030 (org-get-agenda-file-buffer file)
7031 (error "No such file %s" file)))
7032 arg results rtn)
7033 (if (not buffer)
7034 ;; If file does not exist, make sure an error message ends up in diary
7035 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7036 (with-current-buffer buffer
7037 (unless (eq major-mode 'org-mode)
7038 (error "Agenda file %s is not in `org-mode'" file))
7039 (setq org-category-table (org-get-category-table))
7040 (let ((case-fold-search nil))
7041 (save-excursion
7042 (save-restriction
7043 (if org-respect-restriction
7044 (if (org-region-active-p)
7045 ;; Respect a region to restrict search
7046 (narrow-to-region (region-beginning) (region-end)))
7047 ;; If we work for the calendar or many files,
7048 ;; get rid of any restriction
7049 (widen))
7050 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
7051 (while (setq arg (pop args))
7052 (cond
7053 ((and (eq arg :todo)
7054 (equal date (calendar-current-date)))
7055 (setq rtn (org-agenda-get-todos))
7056 (setq results (append results rtn)))
7057 ((eq arg :timestamp)
7058 (setq rtn (org-agenda-get-blocks))
7059 (setq results (append results rtn))
7060 (setq rtn (org-agenda-get-timestamps))
7061 (setq results (append results rtn)))
7062 ((eq arg :scheduled)
7063 (setq rtn (org-agenda-get-scheduled))
7064 (setq results (append results rtn)))
7065 ((eq arg :closed)
7066 (setq rtn (org-agenda-get-closed))
7067 (setq results (append results rtn)))
7068 ((and (eq arg :deadline)
7069 (equal date (calendar-current-date)))
7070 (setq rtn (org-agenda-get-deadlines))
7071 (setq results (append results rtn))))))))
7072 results))))
7073
7074 (defun org-entry-is-done-p ()
7075 "Is the current entry marked DONE?"
7076 (save-excursion
7077 (and (re-search-backward "[\r\n]\\*" nil t)
7078 (looking-at org-nl-done-regexp))))
7079
7080 (defun org-at-date-range-p ()
7081 "Is the cursor inside a date range?"
7082 (interactive)
7083 (save-excursion
7084 (catch 'exit
7085 (let ((pos (point)))
7086 (skip-chars-backward "^<\r\n")
7087 (skip-chars-backward "<")
7088 (and (looking-at org-tr-regexp)
7089 (>= (match-end 0) pos)
7090 (throw 'exit t))
7091 (skip-chars-backward "^<\r\n")
7092 (skip-chars-backward "<")
7093 (and (looking-at org-tr-regexp)
7094 (>= (match-end 0) pos)
7095 (throw 'exit t)))
7096 nil)))
7097
7098 (defun org-agenda-get-todos ()
7099 "Return the TODO information for agenda display."
7100 (let* ((props (list 'face nil
7101 'done-face 'org-done
7102 'org-not-done-regexp org-not-done-regexp
7103 'mouse-face 'highlight
7104 'keymap org-agenda-keymap
7105 'help-echo
7106 (format "mouse-2 or RET jump to org file %s"
7107 (abbreviate-file-name buffer-file-name))))
7108 (regexp (concat "[\n\r]\\*+ *\\("
7109 (if org-select-this-todo-keyword
7110 (concat "\\<\\(" org-select-this-todo-keyword
7111 "\\)\\>")
7112 org-not-done-regexp)
7113 "[^\n\r]*\\)"))
7114 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
7115 marker priority category tags
7116 ee txt)
7117 (goto-char (point-min))
7118 (while (re-search-forward regexp nil t)
7119 (when (not (and org-agenda-todo-ignore-scheduled
7120 (save-match-data (looking-at sched-re))))
7121 (goto-char (match-beginning 1))
7122 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
7123 category (org-get-category)
7124 tags (org-get-tags-at (point))
7125 txt (org-format-agenda-item "" (match-string 1) category tags)
7126 priority
7127 (+ (org-get-priority txt)
7128 (if org-todo-kwd-priority-p
7129 (- org-todo-kwd-max-priority -2
7130 (length
7131 (member (match-string 2) org-todo-keywords)))
7132 1)))
7133 (org-add-props txt props
7134 'org-marker marker 'org-hd-marker marker
7135 'priority priority 'category category)
7136 (push txt ee))
7137 (if org-agenda-todo-list-sublevels
7138 (goto-char (match-end 1))
7139 (org-end-of-subtree 'invisible)))
7140 (nreverse ee)))
7141
7142 (defconst org-agenda-no-heading-message
7143 "No heading for this item in buffer or region.")
7144
7145 (defun org-agenda-get-timestamps ()
7146 "Return the date stamp information for agenda display."
7147 (let* ((props (list 'face nil
7148 'org-not-done-regexp org-not-done-regexp
7149 'mouse-face 'highlight
7150 'keymap org-agenda-keymap
7151 'help-echo
7152 (format "mouse-2 or RET jump to org file %s"
7153 (abbreviate-file-name buffer-file-name))))
7154 (regexp (regexp-quote
7155 (substring
7156 (format-time-string
7157 (car org-time-stamp-formats)
7158 (apply 'encode-time ; DATE bound by calendar
7159 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7160 0 11)))
7161 marker hdmarker deadlinep scheduledp donep tmp priority category
7162 ee txt timestr tags)
7163 (goto-char (point-min))
7164 (while (re-search-forward regexp nil t)
7165 (if (not (save-match-data (org-at-date-range-p)))
7166 (progn
7167 (setq marker (org-agenda-new-marker (match-beginning 0))
7168 category (org-get-category (match-beginning 0))
7169 tmp (buffer-substring (max (point-min)
7170 (- (match-beginning 0)
7171 org-ds-keyword-length))
7172 (match-beginning 0))
7173 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7174 deadlinep (string-match org-deadline-regexp tmp)
7175 scheduledp (string-match org-scheduled-regexp tmp)
7176 donep (org-entry-is-done-p))
7177 (if (string-match ">" timestr)
7178 ;; substring should only run to end of time stamp
7179 (setq timestr (substring timestr 0 (match-end 0))))
7180 (save-excursion
7181 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7182 (progn
7183 (goto-char (match-end 1))
7184 (setq hdmarker (org-agenda-new-marker)
7185 tags (org-get-tags-at))
7186 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7187 (setq txt (org-format-agenda-item
7188 (format "%s%s"
7189 (if deadlinep "Deadline: " "")
7190 (if scheduledp "Scheduled: " ""))
7191 (match-string 1) category tags timestr)))
7192 (setq txt org-agenda-no-heading-message))
7193 (setq priority (org-get-priority txt))
7194 (org-add-props txt props
7195 'org-marker marker 'org-hd-marker hdmarker)
7196 (if deadlinep
7197 (org-add-props txt nil
7198 'face (if donep 'org-done 'org-warning)
7199 'undone-face 'org-warning 'done-face 'org-done
7200 'category category 'priority (+ 100 priority))
7201 (if scheduledp
7202 (org-add-props txt nil
7203 'face 'org-scheduled-today
7204 'undone-face 'org-scheduled-today 'done-face 'org-done
7205 'category category 'priority (+ 99 priority))
7206 (org-add-props txt nil 'priority priority 'category category)))
7207 (push txt ee))
7208 (outline-next-heading))))
7209 (nreverse ee)))
7210
7211 (defun org-agenda-get-closed ()
7212 "Return the logged TODO entries for agenda display."
7213 (let* ((props (list 'mouse-face 'highlight
7214 'org-not-done-regexp org-not-done-regexp
7215 'keymap org-agenda-keymap
7216 'help-echo
7217 (format "mouse-2 or RET jump to org file %s"
7218 (abbreviate-file-name buffer-file-name))))
7219 (regexp (concat
7220 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
7221 (regexp-quote
7222 (substring
7223 (format-time-string
7224 (car org-time-stamp-formats)
7225 (apply 'encode-time ; DATE bound by calendar
7226 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7227 1 11))))
7228 marker hdmarker priority category tags closedp
7229 ee txt timestr)
7230 (goto-char (point-min))
7231 (while (re-search-forward regexp nil t)
7232 (if (not (save-match-data (org-at-date-range-p)))
7233 (progn
7234 (setq marker (org-agenda-new-marker (match-beginning 0))
7235 closedp (equal (match-string 1) org-closed-string)
7236 category (org-get-category (match-beginning 0))
7237 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7238 ;; donep (org-entry-is-done-p)
7239 )
7240 (if (string-match "\\]" timestr)
7241 ;; substring should only run to end of time stamp
7242 (setq timestr (substring timestr 0 (match-end 0))))
7243 (save-excursion
7244 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7245 (progn
7246 (goto-char (match-end 1))
7247 (setq hdmarker (org-agenda-new-marker)
7248 tags (org-get-tags-at))
7249 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7250 (setq txt (org-format-agenda-item
7251 (if closedp "Closed: " "Clocked: ")
7252 (match-string 1) category tags timestr)))
7253 (setq txt org-agenda-no-heading-message))
7254 (setq priority 100000)
7255 (org-add-props txt props
7256 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
7257 'priority priority 'category category
7258 'undone-face 'org-warning 'done-face 'org-done)
7259 (push txt ee))
7260 (outline-next-heading))))
7261 (nreverse ee)))
7262
7263 (defun org-agenda-get-deadlines ()
7264 "Return the deadline information for agenda display."
7265 (let* ((wdays org-deadline-warning-days)
7266 (props (list 'mouse-face 'highlight
7267 'org-not-done-regexp org-not-done-regexp
7268 'keymap org-agenda-keymap
7269 'help-echo
7270 (format "mouse-2 or RET jump to org file %s"
7271 (abbreviate-file-name buffer-file-name))))
7272 (regexp org-deadline-time-regexp)
7273 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7274 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7275 d2 diff pos pos1 category tags
7276 ee txt head face)
7277 (goto-char (point-min))
7278 (while (re-search-forward regexp nil t)
7279 (setq pos (1- (match-beginning 1))
7280 d2 (time-to-days
7281 (org-time-string-to-time (match-string 1)))
7282 diff (- d2 d1))
7283 ;; When to show a deadline in the calendar:
7284 ;; If the expiration is within wdays warning time.
7285 ;; Past-due deadlines are only shown on the current date
7286 (if (and (< diff wdays) todayp (not (= diff 0)))
7287 (save-excursion
7288 (setq category (org-get-category))
7289 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7290 (progn
7291 (goto-char (match-end 0))
7292 (setq pos1 (match-end 1))
7293 (setq tags (org-get-tags-at pos1))
7294 (setq head (buffer-substring-no-properties
7295 (point)
7296 (progn (skip-chars-forward "^\r\n")
7297 (point))))
7298 (if (string-match org-looking-at-done-regexp head)
7299 (setq txt nil)
7300 (setq txt (org-format-agenda-item
7301 (format "In %3d d.: " diff) head category tags))))
7302 (setq txt org-agenda-no-heading-message))
7303 (when txt
7304 (setq face (cond ((<= diff 0) 'org-warning)
7305 ((<= diff 5) 'org-upcoming-deadline)
7306 (t nil)))
7307 (org-add-props txt props
7308 'org-marker (org-agenda-new-marker pos)
7309 'org-hd-marker (org-agenda-new-marker pos1)
7310 'priority (+ (- 10 diff) (org-get-priority txt))
7311 'category category
7312 'face face 'undone-face face 'done-face 'org-done)
7313 (push txt ee)))))
7314 ee))
7315
7316 (defun org-agenda-get-scheduled ()
7317 "Return the scheduled information for agenda display."
7318 (let* ((props (list 'face 'org-scheduled-previously
7319 'org-not-done-regexp org-not-done-regexp
7320 'undone-face 'org-scheduled-previously
7321 'done-face 'org-done
7322 'mouse-face 'highlight
7323 'keymap org-agenda-keymap
7324 'help-echo
7325 (format "mouse-2 or RET jump to org file %s"
7326 (abbreviate-file-name buffer-file-name))))
7327 (regexp org-scheduled-time-regexp)
7328 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7329 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7330 d2 diff pos pos1 category tags
7331 ee txt head)
7332 (goto-char (point-min))
7333 (while (re-search-forward regexp nil t)
7334 (setq pos (1- (match-beginning 1))
7335 d2 (time-to-days
7336 (org-time-string-to-time (match-string 1)))
7337 diff (- d2 d1))
7338 ;; When to show a scheduled item in the calendar:
7339 ;; If it is on or past the date.
7340 (if (and (< diff 0) todayp)
7341 (save-excursion
7342 (setq category (org-get-category))
7343 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7344 (progn
7345 (goto-char (match-end 0))
7346 (setq pos1 (match-end 1))
7347 (setq tags (org-get-tags-at))
7348 (setq head (buffer-substring-no-properties
7349 (point)
7350 (progn (skip-chars-forward "^\r\n") (point))))
7351 (if (string-match org-looking-at-done-regexp head)
7352 (setq txt nil)
7353 (setq txt (org-format-agenda-item
7354 (format "Sched.%2dx: " (- 1 diff)) head
7355 category tags))))
7356 (setq txt org-agenda-no-heading-message))
7357 (when txt
7358 (org-add-props txt props
7359 'org-marker (org-agenda-new-marker pos)
7360 'org-hd-marker (org-agenda-new-marker pos1)
7361 'priority (+ (- 5 diff) (org-get-priority txt))
7362 'category category)
7363 (push txt ee)))))
7364 ee))
7365
7366 (defun org-agenda-get-blocks ()
7367 "Return the date-range information for agenda display."
7368 (let* ((props (list 'face nil
7369 'org-not-done-regexp org-not-done-regexp
7370 'mouse-face 'highlight
7371 'keymap org-agenda-keymap
7372 'help-echo
7373 (format "mouse-2 or RET jump to org file %s"
7374 (abbreviate-file-name buffer-file-name))))
7375 (regexp org-tr-regexp)
7376 (d0 (calendar-absolute-from-gregorian date))
7377 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
7378 (goto-char (point-min))
7379 (while (re-search-forward regexp nil t)
7380 (setq timestr (match-string 0)
7381 s1 (match-string 1)
7382 s2 (match-string 2)
7383 d1 (time-to-days (org-time-string-to-time s1))
7384 d2 (time-to-days (org-time-string-to-time s2)))
7385 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
7386 ;; Only allow days between the limits, because the normal
7387 ;; date stamps will catch the limits.
7388 (save-excursion
7389 (setq marker (org-agenda-new-marker (point)))
7390 (setq category (org-get-category))
7391 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7392 (progn
7393 (setq hdmarker (org-agenda-new-marker (match-end 1)))
7394 (goto-char (match-end 1))
7395 (setq tags (org-get-tags-at))
7396 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7397 (setq txt (org-format-agenda-item
7398 (format (if (= d1 d2) "" "(%d/%d): ")
7399 (1+ (- d0 d1)) (1+ (- d2 d1)))
7400 (match-string 1) category tags
7401 (if (= d0 d1) timestr))))
7402 (setq txt org-agenda-no-heading-message))
7403 (org-add-props txt props
7404 'org-marker marker 'org-hd-marker hdmarker
7405 'priority (org-get-priority txt) 'category category)
7406 (push txt ee)))
7407 (outline-next-heading))
7408 ;; Sort the entries by expiration date.
7409 (nreverse ee)))
7410
7411 (defconst org-plain-time-of-day-regexp
7412 (concat
7413 "\\(\\<[012]?[0-9]"
7414 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7415 "\\(--?"
7416 "\\(\\<[012]?[0-9]"
7417 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7418 "\\)?")
7419 "Regular expression to match a plain time or time range.
7420 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
7421 groups carry important information:
7422 0 the full match
7423 1 the first time, range or not
7424 8 the second time, if it is a range.")
7425
7426 (defconst org-stamp-time-of-day-regexp
7427 (concat
7428 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
7429 "\\([012][0-9]:[0-5][0-9]\\)>"
7430 "\\(--?"
7431 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
7432 "Regular expression to match a timestamp time or time range.
7433 After a match, the following groups carry important information:
7434 0 the full match
7435 1 date plus weekday, for backreferencing to make sure both times on same day
7436 2 the first time, range or not
7437 4 the second time, if it is a range.")
7438
7439 (defvar org-prefix-has-time nil
7440 "A flag, set by `org-compile-prefix-format'.
7441 The flag is set if the currently compiled format contains a `%t'.")
7442 (defvar org-prefix-has-tag nil
7443 "A flag, set by `org-compile-prefix-format'.
7444 The flag is set if the currently compiled format contains a `%T'.")
7445
7446 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
7447 "Format TXT to be inserted into the agenda buffer.
7448 In particular, it adds the prefix and corresponding text properties. EXTRA
7449 must be a string and replaces the `%s' specifier in the prefix format.
7450 CATEGORY (string, symbol or nil) may be used to overrule the default
7451 category taken from local variable or file name. It will replace the `%c'
7452 specifier in the format. DOTIME, when non-nil, indicates that a
7453 time-of-day should be extracted from TXT for sorting of this entry, and for
7454 the `%t' specifier in the format. When DOTIME is a string, this string is
7455 searched for a time before TXT is. NOPREFIX is a flag and indicates that
7456 only the correctly processes TXT should be returned - this is used by
7457 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
7458 (save-match-data
7459 ;; Diary entries sometimes have extra whitespace at the beginning
7460 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
7461 (let* ((category (or category
7462 org-category
7463 (if buffer-file-name
7464 (file-name-sans-extension
7465 (file-name-nondirectory buffer-file-name))
7466 "")))
7467 (tag (if tags (nth (1- (length tags)) tags) ""))
7468 time ;; needed for the eval of the prefix format
7469 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
7470 (time-of-day (and dotime (org-get-time-of-day ts)))
7471 stamp plain s0 s1 s2 rtn)
7472 (when (and dotime time-of-day org-prefix-has-time)
7473 ;; Extract starting and ending time and move them to prefix
7474 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
7475 (setq plain (string-match org-plain-time-of-day-regexp ts)))
7476 (setq s0 (match-string 0 ts)
7477 s1 (match-string (if plain 1 2) ts)
7478 s2 (match-string (if plain 8 4) ts))
7479
7480 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
7481 ;; them, we might want to remove them there to avoid duplication.
7482 ;; The user can turn this off with a variable.
7483 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
7484 (string-match (concat (regexp-quote s0) " *") txt)
7485 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
7486 (= (match-beginning 0) 0)
7487 t))
7488 (setq txt (replace-match "" nil nil txt))))
7489 ;; Normalize the time(s) to 24 hour
7490 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
7491 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
7492
7493 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
7494 ;; Tags are in the string
7495 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
7496 (and org-agenda-remove-tags-when-in-prefix
7497 org-prefix-has-tag))
7498 (setq txt (replace-match "" t t txt))
7499 (setq txt (replace-match
7500 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
7501 (match-string 2 txt))
7502 t t txt))))
7503
7504 ;; Create the final string
7505 (if noprefix
7506 (setq rtn txt)
7507 ;; Prepare the variables needed in the eval of the compiled format
7508 (setq time (cond (s2 (concat s1 "-" s2))
7509 (s1 (concat s1 "......"))
7510 (t ""))
7511 extra (or extra "")
7512 category (if (symbolp category) (symbol-name category) category))
7513 ;; Evaluate the compiled format
7514 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
7515
7516 ;; And finally add the text properties
7517 (org-add-props rtn nil
7518 'category (downcase category) 'tags tags
7519 'prefix-length (- (length rtn) (length txt))
7520 'time-of-day time-of-day
7521 'dotime dotime))))
7522
7523 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
7524 (catch 'exit
7525 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
7526 ((and todayp (member 'today (car org-agenda-time-grid))))
7527 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
7528 ((member 'weekly (car org-agenda-time-grid)))
7529 (t (throw 'exit list)))
7530 (let* ((have (delq nil (mapcar
7531 (lambda (x) (get-text-property 1 'time-of-day x))
7532 list)))
7533 (string (nth 1 org-agenda-time-grid))
7534 (gridtimes (nth 2 org-agenda-time-grid))
7535 (req (car org-agenda-time-grid))
7536 (remove (member 'remove-match req))
7537 new time)
7538 (if (and (member 'require-timed req) (not have))
7539 ;; don't show empty grid
7540 (throw 'exit list))
7541 (while (setq time (pop gridtimes))
7542 (unless (and remove (member time have))
7543 (setq time (int-to-string time))
7544 (push (org-format-agenda-item
7545 nil string "" nil
7546 (concat (substring time 0 -2) ":" (substring time -2)))
7547 new)
7548 (put-text-property
7549 1 (length (car new)) 'face 'org-time-grid (car new))))
7550 (if (member 'time-up org-agenda-sorting-strategy)
7551 (append new list)
7552 (append list new)))))
7553
7554 (defun org-compile-prefix-format (format)
7555 "Compile the prefix format into a Lisp form that can be evaluated.
7556 The resulting form is returned and stored in the variable
7557 `org-prefix-format-compiled'."
7558 (setq org-prefix-has-time nil org-prefix-has-tag nil)
7559 (let ((start 0) varform vars var (s format)e c f opt)
7560 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
7561 s start)
7562 (setq var (cdr (assoc (match-string 4 s)
7563 '(("c" . category) ("t" . time) ("s" . extra)
7564 ("T" . tag))))
7565 c (or (match-string 3 s) "")
7566 opt (match-beginning 1)
7567 start (1+ (match-beginning 0)))
7568 (if (equal var 'time) (setq org-prefix-has-time t))
7569 (if (equal var 'tag) (setq org-prefix-has-tag t))
7570 (setq f (concat "%" (match-string 2 s) "s"))
7571 (if opt
7572 (setq varform
7573 `(if (equal "" ,var)
7574 ""
7575 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
7576 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
7577 (setq s (replace-match "%s" t nil s))
7578 (push varform vars))
7579 (setq vars (nreverse vars))
7580 (setq org-prefix-format-compiled `(format ,s ,@vars))))
7581
7582 (defun org-get-time-of-day (s &optional string mod24)
7583 "Check string S for a time of day.
7584 If found, return it as a military time number between 0 and 2400.
7585 If not found, return nil.
7586 The optional STRING argument forces conversion into a 5 character wide string
7587 HH:MM."
7588 (save-match-data
7589 (when
7590 (or
7591 (string-match
7592 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
7593 (string-match
7594 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
7595 (let* ((h (string-to-number (match-string 1 s)))
7596 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
7597 (ampm (if (match-end 4) (downcase (match-string 4 s))))
7598 (am-p (equal ampm "am"))
7599 (h1 (cond ((not ampm) h)
7600 ((= h 12) (if am-p 0 12))
7601 (t (+ h (if am-p 0 12)))))
7602 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
7603 (mod h1 24) h1))
7604 (t0 (+ (* 100 h2) m))
7605 (t1 (concat (if (>= h1 24) "+" " ")
7606 (if (< t0 100) "0" "")
7607 (if (< t0 10) "0" "")
7608 (int-to-string t0))))
7609 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
7610
7611 (defun org-finalize-agenda-entries (list)
7612 "Sort and concatenate the agenda items."
7613 (setq list (mapcar 'org-agenda-highlight-todo list))
7614 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
7615
7616 (defun org-agenda-highlight-todo (x)
7617 (let (re pl)
7618 (if (eq x 'line)
7619 (save-excursion
7620 (beginning-of-line 1)
7621 (setq re (get-text-property (point) 'org-not-done-regexp))
7622 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
7623 (and (looking-at (concat "[ \t]*" re))
7624 (add-text-properties (match-beginning 0) (match-end 0)
7625 '(face org-todo))))
7626 (setq re (get-text-property 0 'org-not-done-regexp x)
7627 pl (get-text-property 0 'prefix-length x))
7628 (and re (equal (string-match re x pl) pl)
7629 (add-text-properties (match-beginning 0) (match-end 0)
7630 '(face org-todo) x))
7631 x)))
7632
7633 (defsubst org-cmp-priority (a b)
7634 "Compare the priorities of string A and B."
7635 (let ((pa (or (get-text-property 1 'priority a) 0))
7636 (pb (or (get-text-property 1 'priority b) 0)))
7637 (cond ((> pa pb) +1)
7638 ((< pa pb) -1)
7639 (t nil))))
7640
7641 (defsubst org-cmp-category (a b)
7642 "Compare the string values of categories of strings A and B."
7643 (let ((ca (or (get-text-property 1 'category a) ""))
7644 (cb (or (get-text-property 1 'category b) "")))
7645 (cond ((string-lessp ca cb) -1)
7646 ((string-lessp cb ca) +1)
7647 (t nil))))
7648
7649 (defsubst org-cmp-time (a b)
7650 "Compare the time-of-day values of strings A and B."
7651 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
7652 (ta (or (get-text-property 1 'time-of-day a) def))
7653 (tb (or (get-text-property 1 'time-of-day b) def)))
7654 (cond ((< ta tb) -1)
7655 ((< tb ta) +1)
7656 (t nil))))
7657
7658 (defun org-entries-lessp (a b)
7659 "Predicate for sorting agenda entries."
7660 ;; The following variables will be used when the form is evaluated.
7661 (let* ((time-up (org-cmp-time a b))
7662 (time-down (if time-up (- time-up) nil))
7663 (priority-up (org-cmp-priority a b))
7664 (priority-down (if priority-up (- priority-up) nil))
7665 (category-up (org-cmp-category a b))
7666 (category-down (if category-up (- category-up) nil))
7667 (category-keep (if category-up +1 nil)))
7668 (cdr (assoc
7669 (eval (cons 'or org-agenda-sorting-strategy))
7670 '((-1 . t) (1 . nil) (nil . nil))))))
7671
7672 (defun org-agenda-show-priority ()
7673 "Show the priority of the current item.
7674 This priority is composed of the main priority given with the [#A] cookies,
7675 and by additional input from the age of a schedules or deadline entry."
7676 (interactive)
7677 (let* ((pri (get-text-property (point-at-bol) 'priority)))
7678 (message "Priority is %d" (if pri pri -1000))))
7679
7680 (defun org-agenda-show-tags ()
7681 "Show the tags applicable to the current item."
7682 (interactive)
7683 (let* ((tags (get-text-property (point-at-bol) 'tags)))
7684 (if tags
7685 (message "Tags are :%s:"
7686 (org-no-properties (mapconcat 'identity tags ":")))
7687 (message "No tags associated with this line"))))
7688
7689 (defun org-agenda-goto (&optional highlight)
7690 "Go to the Org-mode file which contains the item at point."
7691 (interactive)
7692 (let* ((marker (or (get-text-property (point) 'org-marker)
7693 (org-agenda-error)))
7694 (buffer (marker-buffer marker))
7695 (pos (marker-position marker)))
7696 (switch-to-buffer-other-window buffer)
7697 (widen)
7698 (goto-char pos)
7699 (when (eq major-mode 'org-mode)
7700 (org-show-hidden-entry)
7701 (save-excursion
7702 (and (outline-next-heading)
7703 (org-flag-heading nil)))) ; show the next heading
7704 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
7705
7706 (defun org-agenda-switch-to ()
7707 "Go to the Org-mode file which contains the item at point."
7708 (interactive)
7709 (let* ((marker (or (get-text-property (point) 'org-marker)
7710 (org-agenda-error)))
7711 (buffer (marker-buffer marker))
7712 (pos (marker-position marker)))
7713 (switch-to-buffer buffer)
7714 (delete-other-windows)
7715 (widen)
7716 (goto-char pos)
7717 (when (eq major-mode 'org-mode)
7718 (org-show-hidden-entry)
7719 (save-excursion
7720 (and (outline-next-heading)
7721 (org-flag-heading nil)))))) ; show the next heading
7722
7723 (defun org-agenda-goto-mouse (ev)
7724 "Go to the Org-mode file which contains the item at the mouse click."
7725 (interactive "e")
7726 (mouse-set-point ev)
7727 (org-agenda-goto))
7728
7729 (defun org-agenda-show ()
7730 "Display the Org-mode file which contains the item at point."
7731 (interactive)
7732 (let ((win (selected-window)))
7733 (org-agenda-goto t)
7734 (select-window win)))
7735
7736 (defun org-agenda-recenter (arg)
7737 "Display the Org-mode file which contains the item at point and recenter."
7738 (interactive "P")
7739 (let ((win (selected-window)))
7740 (org-agenda-goto t)
7741 (recenter arg)
7742 (select-window win)))
7743
7744 (defun org-agenda-show-mouse (ev)
7745 "Display the Org-mode file which contains the item at the mouse click."
7746 (interactive "e")
7747 (mouse-set-point ev)
7748 (org-agenda-show))
7749
7750 (defun org-agenda-check-no-diary ()
7751 "Check if the entry is a diary link and abort if yes."
7752 (if (get-text-property (point) 'org-agenda-diary-link)
7753 (org-agenda-error)))
7754
7755 (defun org-agenda-error ()
7756 (error "Command not allowed in this line"))
7757
7758 (defvar org-last-heading-marker (make-marker)
7759 "Marker pointing to the headline that last changed its TODO state
7760 by a remote command from the agenda.")
7761
7762 (defun org-agenda-todo (&optional arg)
7763 "Cycle TODO state of line at point, also in Org-mode file.
7764 This changes the line at point, all other lines in the agenda referring to
7765 the same tree node, and the headline of the tree node in the Org-mode file."
7766 (interactive "P")
7767 (org-agenda-check-no-diary)
7768 (let* ((col (current-column))
7769 (marker (or (get-text-property (point) 'org-marker)
7770 (org-agenda-error)))
7771 (buffer (marker-buffer marker))
7772 (pos (marker-position marker))
7773 (hdmarker (get-text-property (point) 'org-hd-marker))
7774 (buffer-read-only nil)
7775 newhead)
7776 (with-current-buffer buffer
7777 (widen)
7778 (goto-char pos)
7779 (org-show-hidden-entry)
7780 (save-excursion
7781 (and (outline-next-heading)
7782 (org-flag-heading nil))) ; show the next heading
7783 (org-todo arg)
7784 (and (bolp) (forward-char 1))
7785 (setq newhead (org-get-heading))
7786 (save-excursion
7787 (org-back-to-heading)
7788 (move-marker org-last-heading-marker (point))))
7789 (beginning-of-line 1)
7790 (save-excursion
7791 (org-agenda-change-all-lines newhead hdmarker 'fixface))
7792 (move-to-column col)))
7793
7794 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
7795 "Change all lines in the agenda buffer which match HDMARKER.
7796 The new content of the line will be NEWHEAD (as modified by
7797 `org-format-agenda-item'). HDMARKER is checked with
7798 `equal' against all `org-hd-marker' text properties in the file.
7799 If FIXFACE is non-nil, the face of each item is modified acording to
7800 the new TODO state."
7801 (let* (props m pl undone-face done-face finish new dotime cat tags)
7802 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
7803 (save-excursion
7804 (goto-char (point-max))
7805 (beginning-of-line 1)
7806 (while (not finish)
7807 (setq finish (bobp))
7808 (when (and (setq m (get-text-property (point) 'org-hd-marker))
7809 (equal m hdmarker))
7810 (setq props (text-properties-at (point))
7811 dotime (get-text-property (point) 'dotime)
7812 cat (get-text-property (point) 'category)
7813 tags (get-text-property (point) 'tags)
7814 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
7815 pl (get-text-property (point) 'prefix-length)
7816 undone-face (get-text-property (point) 'undone-face)
7817 done-face (get-text-property (point) 'done-face))
7818 (move-to-column pl)
7819 (if (looking-at ".*")
7820 (progn
7821 (replace-match new t t)
7822 (beginning-of-line 1)
7823 (add-text-properties (point-at-bol) (point-at-eol) props)
7824 (when fixface
7825 (add-text-properties
7826 (point-at-bol) (point-at-eol)
7827 (list 'face
7828 (if org-last-todo-state-is-todo
7829 undone-face done-face)))
7830 (org-agenda-highlight-todo 'line))
7831 (beginning-of-line 1))
7832 (error "Line update did not work")))
7833 (beginning-of-line 0)))))
7834
7835 (defun org-agenda-priority-up ()
7836 "Increase the priority of line at point, also in Org-mode file."
7837 (interactive)
7838 (org-agenda-priority 'up))
7839
7840 (defun org-agenda-priority-down ()
7841 "Decrease the priority of line at point, also in Org-mode file."
7842 (interactive)
7843 (org-agenda-priority 'down))
7844
7845 (defun org-agenda-priority (&optional force-direction)
7846 "Set the priority of line at point, also in Org-mode file.
7847 This changes the line at point, all other lines in the agenda referring to
7848 the same tree node, and the headline of the tree node in the Org-mode file."
7849 (interactive)
7850 (org-agenda-check-no-diary)
7851 (let* ((marker (or (get-text-property (point) 'org-marker)
7852 (org-agenda-error)))
7853 (buffer (marker-buffer marker))
7854 (pos (marker-position marker))
7855 (hdmarker (get-text-property (point) 'org-hd-marker))
7856 (buffer-read-only nil)
7857 newhead)
7858 (with-current-buffer buffer
7859 (widen)
7860 (goto-char pos)
7861 (org-show-hidden-entry)
7862 (save-excursion
7863 (and (outline-next-heading)
7864 (org-flag-heading nil))) ; show the next heading
7865 (funcall 'org-priority force-direction)
7866 (end-of-line 1)
7867 (setq newhead (org-get-heading)))
7868 (org-agenda-change-all-lines newhead hdmarker)
7869 (beginning-of-line 1)))
7870
7871 (defun org-get-tags-at (&optional pos)
7872 "Get a list of all headline tags applicable at POS.
7873 POS defaults to point. If tags are inherited, the list contains
7874 the targets in the same sequence as the headlines appear, i.e.
7875 the tags of the current headline come last."
7876 (interactive)
7877 (let (tags)
7878 (save-excursion
7879 (goto-char (or pos (point)))
7880 (save-match-data
7881 (org-back-to-heading t)
7882 (condition-case nil
7883 (while t
7884 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
7885 (setq tags (append (org-split-string
7886 (org-match-string-no-properties 1) ":")
7887 tags)))
7888 (or org-use-tag-inheritance (error ""))
7889 (org-up-heading-all 1))
7890 (error nil))))
7891 (message "%s" tags)
7892 tags))
7893
7894 (defun org-agenda-set-tags ()
7895 "Set tags for the current headline."
7896 (interactive)
7897 (org-agenda-check-no-diary)
7898 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
7899 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
7900 (org-agenda-error)))
7901 (buffer (marker-buffer hdmarker))
7902 (pos (marker-position hdmarker))
7903 (buffer-read-only nil)
7904 newhead)
7905 (with-current-buffer buffer
7906 (widen)
7907 (goto-char pos)
7908 (org-show-hidden-entry)
7909 (save-excursion
7910 (and (outline-next-heading)
7911 (org-flag-heading nil))) ; show the next heading
7912 (call-interactively 'org-set-tags)
7913 (end-of-line 1)
7914 (setq newhead (org-get-heading)))
7915 (org-agenda-change-all-lines newhead hdmarker)
7916 (beginning-of-line 1)))
7917
7918 (defun org-agenda-date-later (arg &optional what)
7919 "Change the date of this item to one day later."
7920 (interactive "p")
7921 (org-agenda-check-type t 'agenda 'timeline)
7922 (org-agenda-check-no-diary)
7923 (let* ((marker (or (get-text-property (point) 'org-marker)
7924 (org-agenda-error)))
7925 (buffer (marker-buffer marker))
7926 (pos (marker-position marker)))
7927 (with-current-buffer buffer
7928 (widen)
7929 (goto-char pos)
7930 (if (not (org-at-timestamp-p))
7931 (error "Cannot find time stamp"))
7932 (org-timestamp-change arg (or what 'day))
7933 (message "Time stamp changed to %s" org-last-changed-timestamp))))
7934
7935 (defun org-agenda-date-earlier (arg &optional what)
7936 "Change the date of this item to one day earlier."
7937 (interactive "p")
7938 (org-agenda-date-later (- arg) what))
7939
7940 (defun org-agenda-date-prompt (arg)
7941 "Change the date of this item. Date is prompted for, with default today.
7942 The prefix ARG is passed to the `org-time-stamp' command and can therefore
7943 be used to request time specification in the time stamp."
7944 (interactive "P")
7945 (org-agenda-check-type t 'agenda 'timeline)
7946 (org-agenda-check-no-diary)
7947 (let* ((marker (or (get-text-property (point) 'org-marker)
7948 (org-agenda-error)))
7949 (buffer (marker-buffer marker))
7950 (pos (marker-position marker)))
7951 (with-current-buffer buffer
7952 (widen)
7953 (goto-char pos)
7954 (if (not (org-at-timestamp-p))
7955 (error "Cannot find time stamp"))
7956 (org-time-stamp arg)
7957 (message "Time stamp changed to %s" org-last-changed-timestamp))))
7958
7959 (defun org-agenda-schedule (arg)
7960 "Schedule the item at point."
7961 (interactive "P")
7962 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
7963 (org-agenda-check-no-diary)
7964 (let* ((marker (or (get-text-property (point) 'org-marker)
7965 (org-agenda-error)))
7966 (buffer (marker-buffer marker))
7967 (pos (marker-position marker))
7968 (org-insert-labeled-timestamps-at-point nil)
7969 ts)
7970 (with-current-buffer buffer
7971 (widen)
7972 (goto-char pos)
7973 (setq ts (org-schedule))
7974 (message "Item scheduled for %s" ts))))
7975
7976 (defun org-agenda-deadline (arg)
7977 "Schedule the item at point."
7978 (interactive "P")
7979 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
7980 (org-agenda-check-no-diary)
7981 (let* ((marker (or (get-text-property (point) 'org-marker)
7982 (org-agenda-error)))
7983 (buffer (marker-buffer marker))
7984 (pos (marker-position marker))
7985 (org-insert-labeled-timestamps-at-point nil)
7986 ts)
7987 (with-current-buffer buffer
7988 (widen)
7989 (goto-char pos)
7990 (setq ts (org-deadline))
7991 (message "Deadline for this item set to %s" ts))))
7992
7993 (defun org-get-heading ()
7994 "Return the heading of the current entry, without the stars."
7995 (save-excursion
7996 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
7997 (if (and (re-search-backward "[\r\n]\\*" nil t)
7998 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
7999 (match-string 1)
8000 "")))
8001
8002 (defun org-agenda-clock-in (&optional arg)
8003 "Start the clock on the currently selected item."
8004 (interactive "P")
8005 (org-agenda-check-no-diary)
8006 (let* ((marker (or (get-text-property (point) 'org-marker)
8007 (org-agenda-error)))
8008 (buffer (marker-buffer marker))
8009 (pos (marker-position marker))
8010 (hdmarker (get-text-property (point) 'org-hd-marker)))
8011 (with-current-buffer (marker-buffer marker)
8012 (widen)
8013 (goto-char pos)
8014 (org-clock-in))))
8015
8016 (defun org-agenda-diary-entry ()
8017 "Make a diary entry, like the `i' command from the calendar.
8018 All the standard commands work: block, weekly etc."
8019 (interactive)
8020 (org-agenda-check-type t 'agenda 'timeline)
8021 (require 'diary-lib)
8022 (let* ((char (progn
8023 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
8024 (read-char-exclusive)))
8025 (cmd (cdr (assoc char
8026 '((?d . insert-diary-entry)
8027 (?w . insert-weekly-diary-entry)
8028 (?m . insert-monthly-diary-entry)
8029 (?y . insert-yearly-diary-entry)
8030 (?a . insert-anniversary-diary-entry)
8031 (?b . insert-block-diary-entry)
8032 (?c . insert-cyclic-diary-entry)))))
8033 (oldf (symbol-function 'calendar-cursor-to-date))
8034 (point (point))
8035 (mark (or (mark t) (point))))
8036 (unless cmd
8037 (error "No command associated with <%c>" char))
8038 (unless (and (get-text-property point 'day)
8039 (or (not (equal ?b char))
8040 (get-text-property mark 'day)))
8041 (error "Don't know which date to use for diary entry"))
8042 ;; We implement this by hacking the `calendar-cursor-to-date' function
8043 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
8044 (let ((calendar-mark-ring
8045 (list (calendar-gregorian-from-absolute
8046 (or (get-text-property mark 'day)
8047 (get-text-property point 'day))))))
8048 (unwind-protect
8049 (progn
8050 (fset 'calendar-cursor-to-date
8051 (lambda (&optional error)
8052 (calendar-gregorian-from-absolute
8053 (get-text-property point 'day))))
8054 (call-interactively cmd))
8055 (fset 'calendar-cursor-to-date oldf)))))
8056
8057
8058 (defun org-agenda-execute-calendar-command (cmd)
8059 "Execute a calendar command from the agenda, with the date associated to
8060 the cursor position."
8061 (org-agenda-check-type t 'agenda 'timeline)
8062 (require 'diary-lib)
8063 (unless (get-text-property (point) 'day)
8064 (error "Don't know which date to use for calendar command"))
8065 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
8066 (point (point))
8067 (date (calendar-gregorian-from-absolute
8068 (get-text-property point 'day)))
8069 (displayed-day (extract-calendar-day date))
8070 (displayed-month (extract-calendar-month date))
8071 (displayed-year (extract-calendar-year date)))
8072 (unwind-protect
8073 (progn
8074 (fset 'calendar-cursor-to-date
8075 (lambda (&optional error)
8076 (calendar-gregorian-from-absolute
8077 (get-text-property point 'day))))
8078 (call-interactively cmd))
8079 (fset 'calendar-cursor-to-date oldf))))
8080
8081 (defun org-agenda-phases-of-moon ()
8082 "Display the phases of the moon for the 3 months around the cursor date."
8083 (interactive)
8084 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
8085
8086 (defun org-agenda-holidays ()
8087 "Display the holidays for the 3 months around the cursor date."
8088 (interactive)
8089 (org-agenda-execute-calendar-command 'list-calendar-holidays))
8090
8091 (defun org-agenda-sunrise-sunset (arg)
8092 "Display sunrise and sunset for the cursor date.
8093 Latitude and longitude can be specified with the variables
8094 `calendar-latitude' and `calendar-longitude'. When called with prefix
8095 argument, latitude and longitude will be prompted for."
8096 (interactive "P")
8097 (let ((calendar-longitude (if arg nil calendar-longitude))
8098 (calendar-latitude (if arg nil calendar-latitude))
8099 (calendar-location-name
8100 (if arg "the given coordinates" calendar-location-name)))
8101 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
8102
8103 (defun org-agenda-goto-calendar ()
8104 "Open the Emacs calendar with the date at the cursor."
8105 (interactive)
8106 (org-agenda-check-type t 'agenda 'timeline)
8107 (let* ((day (or (get-text-property (point) 'day)
8108 (error "Don't know which date to open in calendar")))
8109 (date (calendar-gregorian-from-absolute day))
8110 (calendar-move-hook nil)
8111 (view-calendar-holidays-initially nil)
8112 (view-diary-entries-initially nil))
8113 (calendar)
8114 (calendar-goto-date date)))
8115
8116 (defun org-calendar-goto-agenda ()
8117 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
8118 This is a command that has to be installed in `calendar-mode-map'."
8119 (interactive)
8120 (org-agenda-list nil (calendar-absolute-from-gregorian
8121 (calendar-cursor-to-date))
8122 nil t))
8123
8124 (defun org-agenda-convert-date ()
8125 (interactive)
8126 (org-agenda-check-type t 'agenda 'timeline)
8127 (let ((day (get-text-property (point) 'day))
8128 date s)
8129 (unless day
8130 (error "Don't know which date to convert"))
8131 (setq date (calendar-gregorian-from-absolute day))
8132 (setq s (concat
8133 "Gregorian: " (calendar-date-string date) "\n"
8134 "ISO: " (calendar-iso-date-string date) "\n"
8135 "Day of Yr: " (calendar-day-of-year-string date) "\n"
8136 "Julian: " (calendar-julian-date-string date) "\n"
8137 "Astron. JD: " (calendar-astro-date-string date)
8138 " (Julian date number at noon UTC)\n"
8139 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
8140 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
8141 "French: " (calendar-french-date-string date) "\n"
8142 "Mayan: " (calendar-mayan-date-string date) "\n"
8143 "Coptic: " (calendar-coptic-date-string date) "\n"
8144 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
8145 "Persian: " (calendar-persian-date-string date) "\n"
8146 "Chinese: " (calendar-chinese-date-string date) "\n"))
8147 (with-output-to-temp-buffer "*Dates*"
8148 (princ s))
8149 (if (fboundp 'fit-window-to-buffer)
8150 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
8151
8152 ;;; Tags
8153
8154 (defun org-scan-tags (action matcher &optional todo-only)
8155 "Scan headline tags with inheritance and produce output ACTION.
8156 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8157 evaluated, testing if a given set of tags qualifies a headline for
8158 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8159 are included in the output."
8160 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8161 (mapconcat 'regexp-quote
8162 (nreverse (cdr (reverse org-todo-keywords)))
8163 "\\|")
8164 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
8165 (props (list 'face nil
8166 'done-face 'org-done
8167 'undone-face nil
8168 'mouse-face 'highlight
8169 'keymap org-agenda-keymap
8170 'help-echo
8171 (format "mouse-2 or RET jump to org file %s"
8172 (abbreviate-file-name buffer-file-name))))
8173 lspos
8174 tags tags-list tags-alist (llast 0) rtn level category i txt
8175 todo marker)
8176
8177 (save-excursion
8178 (goto-char (point-min))
8179 (when (eq action 'sparse-tree) (org-overview))
8180 (while (re-search-forward re nil t)
8181 (setq todo (if (match-end 1) (match-string 2))
8182 tags (if (match-end 4) (match-string 4)))
8183 (goto-char (setq lspos (1+ (match-beginning 0))))
8184 (setq level (funcall outline-level)
8185 category (org-get-category))
8186 (setq i llast llast level)
8187 ;; remove tag lists from same and sublevels
8188 (while (>= i level)
8189 (when (setq entry (assoc i tags-alist))
8190 (setq tags-alist (delete entry tags-alist)))
8191 (setq i (1- i)))
8192 ;; add the nex tags
8193 (when tags
8194 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8195 tags-alist
8196 (cons (cons level tags) tags-alist)))
8197 ;; compile tags for current headline
8198 (setq tags-list
8199 (if org-use-tag-inheritance
8200 (apply 'append (mapcar 'cdr tags-alist))
8201 tags))
8202 (when (and (or (not todo-only) todo)
8203 (eval matcher))
8204 ;; list this headline
8205 (if (eq action 'sparse-tree)
8206 (progn
8207 (org-show-hierarchy-above))
8208 (setq txt (org-format-agenda-item
8209 ""
8210 (concat
8211 (if org-tags-match-list-sublevels
8212 (make-string (1- level) ?.) "")
8213 (org-get-heading))
8214 category tags-list))
8215 (goto-char lspos)
8216 (setq marker (org-agenda-new-marker))
8217 (org-add-props txt props
8218 'org-marker marker 'org-hd-marker marker 'category category)
8219 (push txt rtn))
8220 ;; if we are to skip sublevels, jump to end of subtree
8221 (point)
8222 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
8223 (nreverse rtn)))
8224
8225 (defun org-tags-sparse-tree (&optional arg match)
8226 "Create a sparse tree according to tags search string MATCH.
8227 MATCH can contain positive and negative selection of tags, like
8228 \"+WORK+URGENT-WITHBOSS\"."
8229 (interactive "P")
8230 (let ((org-show-following-heading nil)
8231 (org-show-hierarchy-above nil))
8232 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
8233
8234 (defun org-make-tags-matcher (match)
8235 "Create the TAGS matcher form for the tags-selecting string MATCH."
8236 (unless match
8237 ;; Get a new match request, with completion
8238 (setq org-last-tags-completion-table
8239 (or (org-get-buffer-tags)
8240 org-last-tags-completion-table))
8241 (setq match (completing-read
8242 "Tags: " 'org-tags-completion-function nil nil nil
8243 'org-tags-history)))
8244 ;; parse the string and create a lisp form
8245 (let ((match0 match) minus tag mm matcher orterms term orlist)
8246 (setq orterms (org-split-string match "|"))
8247 (while (setq term (pop orterms))
8248 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
8249 (setq minus (and (match-end 1)
8250 (equal (match-string 1 term) "-"))
8251 tag (match-string 2 term)
8252 term (substring term (match-end 0))
8253 mm (list 'member (downcase tag) 'tags-list)
8254 mm (if minus (list 'not mm) mm))
8255 (push mm matcher))
8256 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
8257 orlist)
8258 (setq matcher nil))
8259 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8260 ;; Return the string and lisp forms of the matcher
8261 (cons match0 matcher)))
8262
8263 ;;;###autoload
8264 (defun org-tags-view (&optional todo-only match keep-modes)
8265 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
8266 The prefix arg TODO-ONLY limits the search to TODO entries."
8267 (interactive "P")
8268 (org-agenda-maybe-reset-markers 'force)
8269 (org-compile-prefix-format org-agenda-prefix-format)
8270 (let* ((org-agenda-keep-modes keep-modes)
8271 (org-tags-match-list-sublevels
8272 (if todo-only t org-tags-match-list-sublevels))
8273 (win (selected-window))
8274 (completion-ignore-case t)
8275 rtn rtnall files file pos matcher
8276 buffer)
8277 (setq matcher (org-make-tags-matcher match)
8278 match (car matcher) matcher (cdr matcher))
8279 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
8280 (progn
8281 (delete-other-windows)
8282 (switch-to-buffer-other-window
8283 (get-buffer-create org-agenda-buffer-name))))
8284 (setq buffer-read-only nil)
8285 (erase-buffer)
8286 (org-agenda-mode) (setq buffer-read-only nil)
8287 (set (make-local-variable 'org-agenda-type) 'tags)
8288 (set (make-local-variable 'org-agenda-redo-command)
8289 (list 'org-tags-view (list 'quote todo-only)
8290 (list 'if 'current-prefix-arg nil match) t))
8291 (setq files (org-agenda-files)
8292 rtnall nil)
8293 (while (setq file (pop files))
8294 (catch 'nextfile
8295 (org-check-agenda-file file)
8296 (setq buffer (if (file-exists-p file)
8297 (org-get-agenda-file-buffer file)
8298 (error "No such file %s" file)))
8299 (if (not buffer)
8300 ;; If file does not exist, merror message to agenda
8301 (setq rtn (list
8302 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8303 rtnall (append rtnall rtn))
8304 (with-current-buffer buffer
8305 (unless (eq major-mode 'org-mode)
8306 (error "Agenda file %s is not in `org-mode'" file))
8307 (setq org-category-table (org-get-category-table))
8308 (save-excursion
8309 (save-restriction
8310 (if org-respect-restriction
8311 (if (org-region-active-p)
8312 ;; Respect a region to restrict search
8313 (narrow-to-region (region-beginning) (region-end)))
8314 ;; If we work for the calendar or many files,
8315 ;; get rid of any restriction
8316 (widen))
8317 (setq rtn (org-scan-tags 'agenda matcher todo-only))
8318 (setq rtnall (append rtnall rtn))))))))
8319 (insert "Headlines with TAGS match: ")
8320 (add-text-properties (point-min) (1- (point))
8321 (list 'face 'org-level-3))
8322 (setq pos (point))
8323 (insert match "\n")
8324 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
8325 (setq pos (point))
8326 (insert "Press `C-u r' to search again with new search string\n")
8327 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
8328 (when rtnall
8329 (insert (mapconcat 'identity rtnall "\n")))
8330 (goto-char (point-min))
8331 (setq buffer-read-only t)
8332 (org-fit-agenda-window)
8333 (if (not org-select-agenda-window) (select-window win))))
8334
8335 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8336 (defun org-set-tags (&optional arg just-align)
8337 "Set the tags for the current headline.
8338 With prefix ARG, realign all tags in headings in the current buffer."
8339 (interactive "P")
8340 (let* ((re (concat "^" outline-regexp))
8341 (col (current-column))
8342 (current (org-get-tags))
8343 table current-tags inherited-tags ; computed below when needed
8344 tags hd empty invis)
8345 (if arg
8346 (save-excursion
8347 (goto-char (point-min))
8348 (while (re-search-forward re nil t)
8349 (org-set-tags nil t))
8350 (message "All tags realigned to column %d" org-tags-column))
8351 (if just-align
8352 (setq tags current)
8353 (setq table (or org-tag-alist (org-get-buffer-tags))
8354 org-last-tags-completion-table table
8355 current-tags (org-split-string current ":")
8356 inherited-tags (nreverse
8357 (nthcdr (length current-tags)
8358 (nreverse (org-get-tags-at))))
8359 tags
8360 (if (or (eq t org-use-fast-tag-selection)
8361 (and org-use-fast-tag-selection
8362 (delq nil (mapcar 'cdr table))))
8363 (org-fast-tag-selection current-tags inherited-tags table)
8364 (let ((org-add-colon-after-tag-completion t))
8365 (completing-read "Tags: " 'org-tags-completion-function
8366 nil nil current 'org-tags-history))))
8367 (while (string-match "[-+&]+" tags)
8368 (setq tags (replace-match ":" t t tags))))
8369
8370 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
8371 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8372 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8373 (if (equal current "")
8374 (progn
8375 (end-of-line 1)
8376 (or empty (insert-before-markers " ")))
8377 (beginning-of-line 1)
8378 (setq invis (org-invisible-p))
8379 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
8380 (setq hd (match-string 1))
8381 (delete-region (match-beginning 0) (match-end 0))
8382 (insert-before-markers (org-trim hd) (if empty "" " ")))
8383 (unless (equal tags "")
8384 (move-to-column (max (current-column)
8385 (if (> org-tags-column 0)
8386 org-tags-column
8387 (- (- org-tags-column) (length tags))))
8388 t)
8389 (insert-before-markers tags)
8390 (if (and (not invis) (org-invisible-p))
8391 (outline-flag-region (point-at-bol) (point) nil)))
8392 (move-to-column col))))
8393
8394 (defun org-tags-completion-function (string predicate &optional flag)
8395 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8396 (confirm (lambda (x) (stringp (car x)))))
8397 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8398 (setq s1 (match-string 1 string)
8399 s2 (match-string 2 string))
8400 (setq s1 "" s2 string))
8401 (cond
8402 ((eq flag nil)
8403 ;; try completion
8404 (setq rtn (try-completion s2 ctable confirm))
8405 (if (stringp rtn)
8406 (concat s1 s2 (substring rtn (length s2))
8407 (if (and org-add-colon-after-tag-completion
8408 (assoc rtn ctable))
8409 ":" "")))
8410 )
8411 ((eq flag t)
8412 ;; all-completions
8413 (all-completions s2 ctable confirm)
8414 )
8415 ((eq flag 'lambda)
8416 ;; exact match?
8417 (assoc s2 ctable)))
8418 ))
8419
8420 (defun org-fast-tag-insert (kwd tags face &optional end)
8421 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
8422 (insert (format "%-12s" (concat kwd ":"))
8423 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
8424 (or end "")))
8425
8426 (defun org-fast-tag-selection (current inherited table)
8427 "Fast tag selection with single keys.
8428 CURRENT is the current list of tags in the headline, INHERITED is the
8429 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
8430 possibly with grouping information.
8431 If the keys are nil, a-z are automatically assigned.
8432 Returns the new tags string, or nil to not change the current settings."
8433 (let* ((maxlen (apply 'max (mapcar
8434 (lambda (x)
8435 (if (stringp (car x)) (string-width (car x)) 0))
8436 table)))
8437 (fwidth (+ maxlen 3 1 3))
8438 (ncol (/ (- (window-width) 4) fwidth))
8439 (i-face 'org-done)
8440 (c-face 'org-tag)
8441 tg cnt e c char c1 c2 ntable tbl rtn
8442 groups ingroup)
8443 (save-window-excursion
8444 (delete-other-windows)
8445 (split-window-vertically)
8446 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
8447 (erase-buffer)
8448 (org-fast-tag-insert "Inherited" inherited i-face "\n")
8449 (org-fast-tag-insert "Current" current c-face "\n\n")
8450 (setq tbl table char ?a cnt 0)
8451 (while (setq e (pop tbl))
8452 (cond
8453 ((equal e '(:startgroup))
8454 (push '() groups) (setq ingroup t)
8455 (when (not (= cnt 0))
8456 (setq cnt 0)
8457 (insert "\n"))
8458 (insert "{ "))
8459 ((equal e '(:endgroup))
8460 (setq ingroup nil cnt 0)
8461 (insert "}\n"))
8462 (t
8463 (setq tg (car e) c2 nil)
8464 (if (cdr e)
8465 (setq c (cdr e))
8466 ;; automatically assign a character.
8467 (setq c1 (string-to-char
8468 (downcase (substring
8469 tg (if (= (string-to-char tg) ?@) 1 0)))))
8470 (if (or (rassoc c1 ntable) (rassoc c1 table))
8471 (while (or (rassoc char ntable) (rassoc char table))
8472 (setq char (1+ char)))
8473 (setq c2 c1))
8474 (setq c (or c2 char)))
8475 (if ingroup (push tg (car groups)))
8476 (setq tg (org-add-props tg nil 'face
8477 (cond
8478 ((member tg current) c-face)
8479 ((member tg inherited) i-face)
8480 (t nil))))
8481 (if (and (= cnt 0) (not ingroup)) (insert " "))
8482 (insert "[" c "] " tg (make-string
8483 (- fwidth 4 (length tg)) ?\ ))
8484 (push (cons tg c) ntable)
8485 (when (= (setq cnt (1+ cnt)) ncol)
8486 (insert "\n")
8487 (if ingroup (insert " "))
8488 (setq cnt 0)))))
8489 (setq ntable (nreverse ntable))
8490 (insert "\n")
8491 (goto-char (point-min))
8492 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
8493 (setq rtn
8494 (catch 'exit
8495 (while t
8496 (message "[key]:Toggle SPC: clear current RET accept%s"
8497 (if groups " [!] ignore goups" ""))
8498 (setq c (read-char-exclusive))
8499 (cond
8500 ((= c ?\r) (throw 'exit t))
8501 ((= c ?!)
8502 (setq groups nil)
8503 (goto-char (point-min))
8504 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
8505 ((or (= c ?\C-g)
8506 (and (= c ?q) (not (rassoc c ntable))))
8507 (setq quit-flag t))
8508 ((= c ?\ ) (setq current nil))
8509 ((setq e (rassoc c ntable) tg (car e))
8510 (if (member tg current)
8511 (setq current (delete tg current))
8512 (loop for g in groups do
8513 (if (member tg g)
8514 (mapcar (lambda (x)
8515 (setq current (delete x current)))
8516 g)))
8517 (setq current (cons tg current)))))
8518 ;; Create a sorted list
8519 (setq current
8520 (sort current
8521 (lambda (a b)
8522 (assoc b (cdr (memq (assoc a ntable) ntable))))))
8523 (goto-char (point-min))
8524 (beginning-of-line 2)
8525 (delete-region (point) (point-at-eol))
8526 (org-fast-tag-insert "Current" current c-face)
8527 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
8528 (setq tg (match-string 1))
8529 (add-text-properties (match-beginning 1) (match-end 1)
8530 (list 'face
8531 (cond
8532 ((member tg current) c-face)
8533 ((member tg inherited) i-face)
8534 (t nil)))))
8535 (goto-char (point-min)))))
8536 (if rtn
8537 (mapconcat 'identity current ":")
8538 nil))))
8539
8540 (defun org-get-tags ()
8541 "Get the TAGS string in the current headline."
8542 (unless (org-on-heading-p)
8543 (error "Not on a heading"))
8544 (save-excursion
8545 (beginning-of-line 1)
8546 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
8547 (org-match-string-no-properties 1)
8548 "")))
8549
8550 (defun org-get-buffer-tags ()
8551 "Get a table of all tags used in the buffer, for completion."
8552 (let (tags)
8553 (save-excursion
8554 (goto-char (point-min))
8555 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
8556 (mapc (lambda (x) (add-to-list 'tags x))
8557 (org-split-string (org-match-string-no-properties 1) ":"))))
8558 (mapcar 'list tags)))
8559
8560 ;;; Link Stuff
8561
8562 (defvar org-create-file-search-functions nil
8563 "List of functions to construct the right search string for a file link.
8564 These functions are called in turn with point at the location to
8565 which the link should point.
8566
8567 A function in the hook should first test if it would like to
8568 handle this file type, for example by checking the major-mode or
8569 the file extension. If it decides not to handle this file, it
8570 should just return nil to give other functions a chance. If it
8571 does handle the file, it must return the search string to be used
8572 when following the link. The search string will be part of the
8573 file link, given after a double colon, and `org-open-at-point'
8574 will automatically search for it. If special measures must be
8575 taken to make the search successful, another function should be
8576 added to the companion hook `org-execute-file-search-functions',
8577 which see.
8578
8579 A function in this hook may also use `setq' to set the variable
8580 `description' to provide a suggestion for the descriptive text to
8581 be used for this link when it gets inserted into an Org-mode
8582 buffer with \\[org-insert-link].")
8583
8584 (defvar org-execute-file-search-functions nil
8585 "List of functions to execute a file search triggered by a link.
8586
8587 Functions added to this hook must accept a single argument, the
8588 search string that was part of the file link, the part after the
8589 double colon. The function must first check if it would like to
8590 handle this search, for example by checking the major-mode or the
8591 file extension. If it decides not to handle this search, it
8592 should just return nil to give other functions a chance. If it
8593 does handle the search, it must return a non-nil value to keep
8594 other functions from trying.
8595
8596 Each function can access the current prefix argument through the
8597 variable `current-prefix-argument'. Note that a single prefix is
8598 used to force opening a link in Emacs, so it may be good to only
8599 use a numeric or double prefix to guide the search function.
8600
8601 In case this is needed, a function in this hook can also restore
8602 the window configuration before `org-open-at-point' was called using:
8603
8604 (set-window-configuration org-window-config-before-follow-link)")
8605
8606 (defun org-find-file-at-mouse (ev)
8607 "Open file link or URL at mouse."
8608 (interactive "e")
8609 (mouse-set-point ev)
8610 (org-open-at-point 'in-emacs))
8611
8612 (defun org-open-at-mouse (ev)
8613 "Open file link or URL at mouse."
8614 (interactive "e")
8615 (mouse-set-point ev)
8616 (org-open-at-point))
8617
8618 (defvar org-window-config-before-follow-link nil
8619 "The window configuration before following a link.
8620 This is saved in case the need arises to restore it.")
8621
8622 (defun org-open-at-point (&optional in-emacs)
8623 "Open link at or after point.
8624 If there is no link at point, this function will search forward up to
8625 the end of the current subtree.
8626 Normally, files will be opened by an appropriate application. If the
8627 optional argument IN-EMACS is non-nil, Emacs will visit the file."
8628 (interactive "P")
8629 (setq org-window-config-before-follow-link (current-window-configuration))
8630 (org-remove-occur-highlights nil nil t)
8631 (if (org-at-timestamp-p)
8632 (org-agenda-list nil (time-to-days (org-time-string-to-time
8633 (substring (match-string 1) 0 10)))
8634 1)
8635 (let (type path link line search (pos (point)))
8636 (catch 'match
8637 (save-excursion
8638 (skip-chars-forward "^]\n\r")
8639 (when (and (re-search-backward "\\[\\[" nil t)
8640 (looking-at org-bracket-link-regexp)
8641 (<= (match-beginning 0) pos)
8642 (>= (match-end 0) pos))
8643 (setq link (org-link-unescape (org-match-string-no-properties 1)))
8644 (while (string-match " *\n *" link)
8645 (setq link (replace-match " " t t link)))
8646 (if (string-match org-link-re-with-space2 link)
8647 (setq type (match-string 1 link)
8648 path (match-string 2 link))
8649 (setq type "thisfile"
8650 path link))
8651 (throw 'match t)))
8652
8653 (when (get-text-property (point) 'org-linked-text)
8654 (setq type "thisfile"
8655 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8656 (1+ (point)) (point))
8657 path (buffer-substring
8658 (previous-single-property-change pos 'org-linked-text)
8659 (next-single-property-change pos 'org-linked-text)))
8660 (throw 'match t))
8661
8662 (save-excursion
8663 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
8664 (if (equal (char-before) ?<) (backward-char 1))
8665 (when (or (looking-at org-angle-link-re)
8666 (looking-at org-plain-link-re)
8667 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
8668 (re-search-forward org-plain-link-re (point-at-eol) t))
8669 (<= (match-beginning 0) pos)
8670 (>= (match-end 0) pos)))
8671 (setq type (match-string 1)
8672 path (match-string 2))
8673 (throw 'match t)))
8674 (save-excursion
8675 (skip-chars-backward "^ \t\n\r")
8676 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
8677 (setq type "tags"
8678 path (match-string 1))
8679 (while (string-match ":" path)
8680 (setq path (replace-match "+" t t path)))
8681 (throw 'match t)))
8682 (save-excursion
8683 (skip-chars-backward "a-zA-Z_")
8684 (when (and (memq 'camel org-activate-links)
8685 (looking-at org-camel-regexp))
8686 (setq type "camel" path (match-string 0))
8687 (if (equal (char-before) ?*)
8688 (setq path (concat "*" path))))
8689 (throw 'match t)))
8690 (unless path
8691 (error "No link found"))
8692 ;; Remove any trailing spaces in path
8693 (if (string-match " +\\'" path)
8694 (setq path (replace-match "" t t path)))
8695
8696 (cond
8697
8698 ((member type '("http" "https" "ftp" "mailto" "news"))
8699 (browse-url (concat type ":" path)))
8700
8701 ((string= type "tags")
8702 (org-tags-view in-emacs path))
8703 ((or (string= type "camel")
8704 (string= type "thisfile"))
8705 (org-mark-ring-push)
8706 (org-link-search
8707 path
8708 (cond ((equal in-emacs '(4)) 'occur)
8709 ((equal in-emacs '(16)) 'org-occur)
8710 (t nil))))
8711
8712 ((string= type "file")
8713 (if (string-match "::\\([0-9]+\\)\\'" path)
8714 (setq line (string-to-number (match-string 1 path))
8715 path (substring path 0 (match-beginning 0)))
8716 (if (string-match "::\\(.+\\)\\'" path)
8717 (setq search (match-string 1 path)
8718 path (substring path 0 (match-beginning 0)))))
8719 (org-open-file path in-emacs line search))
8720
8721 ((string= type "news")
8722 (org-follow-gnus-link path))
8723
8724 ((string= type "bbdb")
8725 (org-follow-bbdb-link path))
8726
8727 ((string= type "info")
8728 (org-follow-info-link path))
8729
8730 ((string= type "gnus")
8731 (let (group article)
8732 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8733 (error "Error in Gnus link"))
8734 (setq group (match-string 1 path)
8735 article (match-string 3 path))
8736 (org-follow-gnus-link group article)))
8737
8738 ((string= type "vm")
8739 (let (folder article)
8740 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8741 (error "Error in VM link"))
8742 (setq folder (match-string 1 path)
8743 article (match-string 3 path))
8744 ;; in-emacs is the prefix arg, will be interpreted as read-only
8745 (org-follow-vm-link folder article in-emacs)))
8746
8747 ((string= type "wl")
8748 (let (folder article)
8749 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8750 (error "Error in Wanderlust link"))
8751 (setq folder (match-string 1 path)
8752 article (match-string 3 path))
8753 (org-follow-wl-link folder article)))
8754
8755 ((string= type "mhe")
8756 (let (folder article)
8757 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8758 (error "Error in MHE link"))
8759 (setq folder (match-string 1 path)
8760 article (match-string 3 path))
8761 (org-follow-mhe-link folder article)))
8762
8763 ((string= type "rmail")
8764 (let (folder article)
8765 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8766 (error "Error in RMAIL link"))
8767 (setq folder (match-string 1 path)
8768 article (match-string 3 path))
8769 (org-follow-rmail-link folder article)))
8770
8771 ((string= type "shell")
8772 (let ((cmd path))
8773 (while (string-match "@{" cmd)
8774 (setq cmd (replace-match "<" t t cmd)))
8775 (while (string-match "@}" cmd)
8776 (setq cmd (replace-match ">" t t cmd)))
8777 (if (or (not org-confirm-shell-link-function)
8778 (funcall org-confirm-shell-link-function
8779 (format "Execute \"%s\" in shell? "
8780 (org-add-props cmd nil
8781 'face 'org-warning))))
8782 (progn
8783 (message "Executing %s" cmd)
8784 (shell-command cmd))
8785 (error "Abort"))))
8786
8787 ((string= type "elisp")
8788 (let ((cmd path))
8789 (if (or (not org-confirm-elisp-link-function)
8790 (funcall org-confirm-elisp-link-function
8791 (format "Execute \"%s\" as elisp? "
8792 (org-add-props cmd nil
8793 'face 'org-warning))))
8794 (message "%s => %s" cmd (eval (read cmd)))
8795 (error "Abort"))))
8796
8797 (t
8798 (browse-url-at-point))))))
8799
8800 (defun org-link-search (s &optional type)
8801 "Search for a link search option.
8802 When S is a CamelCaseWord, search for a target, or for a sentence containing
8803 the words. If S is surrounded by forward slashes, it is interpreted as a
8804 regular expression. In org-mode files, this will create an `org-occur'
8805 sparse tree. In ordinary files, `occur' will be used to list matches.
8806 If the current buffer is in `dired-mode', grep will be used to search
8807 in all files."
8808 (let ((case-fold-search t)
8809 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8810 (pos (point))
8811 (pre "") (post "")
8812 words re0 re1 re2 re3 re4 re5 re2a reall camel)
8813 (cond
8814 ;; First check if there are any special
8815 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8816 ;; Now try the builtin stuff
8817 ((save-excursion
8818 (goto-char (point-min))
8819 (and
8820 (re-search-forward
8821 (concat "<<" (regexp-quote s0) ">>") nil t)
8822 (setq pos (match-beginning 0))))
8823 ;; There is an exact target for this
8824 (goto-char pos))
8825 ((string-match "^/\\(.*\\)/$" s)
8826 ;; A regular expression
8827 (cond
8828 ((eq major-mode 'org-mode)
8829 (org-occur (match-string 1 s)))
8830 ;;((eq major-mode 'dired-mode)
8831 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8832 (t (org-do-occur (match-string 1 s)))))
8833 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
8834 t)
8835 ;; A camel or a normal search string
8836 (when (equal (string-to-char s) ?*)
8837 ;; Anchor on headlines, post may include tags.
8838 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
8839 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
8840 s (substring s 1)))
8841 (remove-text-properties
8842 0 (length s)
8843 '(face nil mouse-face nil keymap nil fontified nil) s)
8844 ;; Make a series of regular expressions to find a match
8845 (setq words
8846 (if camel
8847 (org-camel-to-words s)
8848 (org-split-string s "[ \n\r\t]+"))
8849 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8850 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
8851 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8852 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8853 re1 (concat pre re2 post)
8854 re3 (concat pre re4 post)
8855 re5 (concat pre ".*" re4)
8856 re2 (concat pre re2)
8857 re2a (concat pre re2a)
8858 re4 (concat pre re4)
8859 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8860 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8861 re5 "\\)"
8862 ))
8863 (cond
8864 ((eq type 'org-occur) (org-occur reall))
8865 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8866 (t (goto-char (point-min))
8867 (if (or (org-search-not-link re0 nil t)
8868 (org-search-not-link re1 nil t)
8869 (org-search-not-link re2 nil t)
8870 (org-search-not-link re2a nil t)
8871 (org-search-not-link re3 nil t)
8872 (org-search-not-link re4 nil t)
8873 (org-search-not-link re5 nil t)
8874 )
8875 (goto-char (match-beginning 1))
8876 (goto-char pos)
8877 (error "No match")))))
8878 (t
8879 ;; Normal string-search
8880 (goto-char (point-min))
8881 (if (search-forward s nil t)
8882 (goto-char (match-beginning 0))
8883 (error "No match"))))
8884 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
8885
8886 (defun org-search-not-link (&rest args)
8887 "Execute `re-search-forward', but only accept matches that are not a link."
8888 (catch 'exit
8889 (let ((pos (point)) p1)
8890 (while (apply 're-search-forward args)
8891 (setq p1 (point))
8892 (if (not (save-match-data
8893 (and (re-search-backward "\\[\\[" nil t)
8894 (looking-at org-bracket-link-regexp)
8895 (<= (match-beginning 0) p1)
8896 (>= (match-end 0) p1))))
8897 (progn (goto-char (match-end 0))
8898 (throw 'exit (point)))
8899 (goto-char (match-end 0)))))))
8900
8901 (defun org-do-occur (regexp &optional cleanup)
8902 "Call the Emacs command `occur'.
8903 If CLEANUP is non-nil, remove the printout of the regular expression
8904 in the *Occur* buffer. This is useful if the regex is long and not useful
8905 to read."
8906 (occur regexp)
8907 (when cleanup
8908 (let ((cwin (selected-window)) win beg end)
8909 (when (setq win (get-buffer-window "*Occur*"))
8910 (select-window win))
8911 (goto-char (point-min))
8912 (when (re-search-forward "match[a-z]+" nil t)
8913 (setq beg (match-end 0))
8914 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8915 (setq end (1- (match-beginning 0)))))
8916 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
8917 (goto-char (point-min))
8918 (select-window cwin))))
8919
8920 (defvar org-mark-ring nil
8921 "Mark ring for positions before jumps in Org-mode.")
8922 (defvar org-mark-ring-last-goto nil
8923 "Last position in the mark ring used to go back.")
8924 ;; Fill and close the ring
8925 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8926 (loop for i from 1 to org-mark-ring-length do
8927 (push (make-marker) org-mark-ring))
8928 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8929 org-mark-ring)
8930
8931 (defun org-mark-ring-push (&optional pos buffer)
8932 "Put the current position or POS into the mark ring and rotate it."
8933 (interactive)
8934 (setq pos (or pos (point)))
8935 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8936 (move-marker (car org-mark-ring)
8937 (or pos (point))
8938 (or buffer (current-buffer)))
8939 (message
8940 (substitute-command-keys
8941 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8942
8943 (defun org-mark-ring-goto (&optional n)
8944 "Jump to the previous position in the mark ring.
8945 With prefix arg N, jump back that many stored positions. When
8946 called several times in succession, walk through the entire ring.
8947 Org-mode commands jumping to a different position in the current file,
8948 or to another Org-mode file, automatically push the old position
8949 onto the ring."
8950 (interactive "p")
8951 (let (p m)
8952 (if (eq last-command this-command)
8953 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8954 (setq p org-mark-ring))
8955 (setq org-mark-ring-last-goto p)
8956 (setq m (car p))
8957 (switch-to-buffer (marker-buffer m))
8958 (goto-char m)
8959 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
8960
8961 (defun org-camel-to-words (s)
8962 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
8963 (let ((case-fold-search nil)
8964 words)
8965 (while (string-match "[a-z][A-Z]" s)
8966 (push (substring s 0 (1+ (match-beginning 0))) words)
8967 (setq s (substring s (1+ (match-beginning 0)))))
8968 (nreverse (cons s words))))
8969
8970 (defun org-remove-angle-brackets (s)
8971 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8972 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8973 s)
8974 (defun org-add-angle-brackets (s)
8975 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8976 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8977 s)
8978
8979 (defun org-follow-bbdb-link (name)
8980 "Follow a BBDB link to NAME."
8981 (require 'bbdb)
8982 (let ((inhibit-redisplay t)
8983 (bbdb-electric-p nil))
8984 (catch 'exit
8985 ;; Exact match on name
8986 (bbdb-name (concat "\\`" name "\\'") nil)
8987 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8988 ;; Exact match on name
8989 (bbdb-company (concat "\\`" name "\\'") nil)
8990 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8991 ;; Partial match on name
8992 (bbdb-name name nil)
8993 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8994 ;; Partial match on company
8995 (bbdb-company name nil)
8996 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8997 ;; General match including network address and notes
8998 (bbdb name nil)
8999 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
9000 (delete-window (get-buffer-window "*BBDB*"))
9001 (error "No matching BBDB record")))))
9002
9003
9004 (defun org-follow-info-link (name)
9005 "Follow an info file & node link to NAME."
9006 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
9007 (string-match "\\(.*\\)" name))
9008 (progn
9009 (require 'info)
9010 (if (match-string 2 name) ; If there isn't a node, choose "Top"
9011 (Info-find-node (match-string 1 name) (match-string 2 name))
9012 (Info-find-node (match-string 1 name) "Top")))
9013 (message (concat "Could not open: " name))))
9014
9015 (defun org-follow-gnus-link (&optional group article)
9016 "Follow a Gnus link to GROUP and ARTICLE."
9017 (require 'gnus)
9018 (funcall (cdr (assq 'gnus org-link-frame-setup)))
9019 (if group (gnus-fetch-group group))
9020 (if article
9021 (or (gnus-summary-goto-article article nil 'force)
9022 (if (fboundp 'gnus-summary-insert-cached-articles)
9023 (progn
9024 (gnus-summary-insert-cached-articles)
9025 (gnus-summary-goto-article article nil 'force))
9026 (message "Message could not be found.")))))
9027
9028 (defun org-follow-vm-link (&optional folder article readonly)
9029 "Follow a VM link to FOLDER and ARTICLE."
9030 (require 'vm)
9031 (setq article (org-add-angle-brackets article))
9032 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
9033 ;; ange-ftp or efs or tramp access
9034 (let ((user (or (match-string 1 folder) (user-login-name)))
9035 (host (match-string 2 folder))
9036 (file (match-string 3 folder)))
9037 (cond
9038 ((featurep 'tramp)
9039 ;; use tramp to access the file
9040 (if (featurep 'xemacs)
9041 (setq folder (format "[%s@%s]%s" user host file))
9042 (setq folder (format "/%s@%s:%s" user host file))))
9043 (t
9044 ;; use ange-ftp or efs
9045 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
9046 (setq folder (format "/%s@%s:%s" user host file))))))
9047 (when folder
9048 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
9049 (sit-for 0.1)
9050 (when article
9051 (vm-select-folder-buffer)
9052 (widen)
9053 (let ((case-fold-search t))
9054 (goto-char (point-min))
9055 (if (not (re-search-forward
9056 (concat "^" "message-id: *" (regexp-quote article))))
9057 (error "Could not find the specified message in this folder"))
9058 (vm-isearch-update)
9059 (vm-isearch-narrow)
9060 (vm-beginning-of-message)
9061 (vm-summarize)))))
9062
9063 (defun org-follow-wl-link (folder article)
9064 "Follow a Wanderlust link to FOLDER and ARTICLE."
9065 (setq article (org-add-angle-brackets article))
9066 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
9067 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
9068 (wl-summary-redisplay))
9069
9070 (defun org-follow-rmail-link (folder article)
9071 "Follow an RMAIL link to FOLDER and ARTICLE."
9072 (setq article (org-add-angle-brackets article))
9073 (let (message-number)
9074 (save-excursion
9075 (save-window-excursion
9076 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9077 (setq message-number
9078 (save-restriction
9079 (widen)
9080 (goto-char (point-max))
9081 (if (re-search-backward
9082 (concat "^Message-ID:\\s-+" (regexp-quote
9083 (or article "")))
9084 nil t)
9085 (rmail-what-message))))))
9086 (if message-number
9087 (progn
9088 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9089 (rmail-show-message message-number)
9090 message-number)
9091 (error "Message not found"))))
9092
9093 ;; mh-e integration based on planner-mode
9094 (defun org-mhe-get-message-real-folder ()
9095 "Return the name of the current message real folder, so if you use
9096 sequences, it will now work."
9097 (save-excursion
9098 (let* ((folder
9099 (if (equal major-mode 'mh-folder-mode)
9100 mh-current-folder
9101 ;; Refer to the show buffer
9102 mh-show-folder-buffer))
9103 (end-index
9104 (if (boundp 'mh-index-folder)
9105 (min (length mh-index-folder) (length folder))))
9106 )
9107 ;; a simple test on mh-index-data does not work, because
9108 ;; mh-index-data is always nil in a show buffer.
9109 (if (and (boundp 'mh-index-folder)
9110 (string= mh-index-folder (substring folder 0 end-index)))
9111 (if (equal major-mode 'mh-show-mode)
9112 (save-window-excursion
9113 (when (buffer-live-p (get-buffer folder))
9114 (progn
9115 (pop-to-buffer folder)
9116 (org-mhe-get-message-folder-from-index)
9117 )
9118 ))
9119 (org-mhe-get-message-folder-from-index)
9120 )
9121 folder
9122 )
9123 )))
9124
9125 (defun org-mhe-get-message-folder-from-index ()
9126 "Returns the name of the message folder in a index folder buffer."
9127 (save-excursion
9128 (mh-index-previous-folder)
9129 (re-search-forward "^\\(+.*\\)$" nil t)
9130 (message (match-string 1))))
9131
9132 (defun org-mhe-get-message-folder ()
9133 "Return the name of the current message folder. Be careful if you
9134 use sequences."
9135 (save-excursion
9136 (if (equal major-mode 'mh-folder-mode)
9137 mh-current-folder
9138 ;; Refer to the show buffer
9139 mh-show-folder-buffer)))
9140
9141 (defun org-mhe-get-message-num ()
9142 "Return the number of the current message. Be careful if you
9143 use sequences."
9144 (save-excursion
9145 (if (equal major-mode 'mh-folder-mode)
9146 (mh-get-msg-num nil)
9147 ;; Refer to the show buffer
9148 (mh-show-buffer-message-number))))
9149
9150 (defun org-mhe-get-header (header)
9151 "Return a header of the message in folder mode. This will create a
9152 show buffer for the corresponding message. If you have a more clever
9153 idea..."
9154 (let* ((folder (org-mhe-get-message-folder))
9155 (num (org-mhe-get-message-num))
9156 (buffer (get-buffer-create (concat "show-" folder)))
9157 (header-field))
9158 (with-current-buffer buffer
9159 (mh-display-msg num folder)
9160 (if (equal major-mode 'mh-folder-mode)
9161 (mh-header-display)
9162 (mh-show-header-display))
9163 (set-buffer buffer)
9164 (setq header-field (mh-get-header-field header))
9165 (if (equal major-mode 'mh-folder-mode)
9166 (mh-show)
9167 (mh-show-show))
9168 header-field)))
9169
9170 (defun org-follow-mhe-link (folder article)
9171 "Follow an MHE link to FOLDER and ARTICLE.
9172 If ARTICLE is nil FOLDER is shown. If the configuration variable
9173 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9174 ARTICLE is searched in all folders. Indexed searches (swish++,
9175 namazu, and others supported by MH-E) will always search in all
9176 folders."
9177 (require 'mh-e)
9178 (require 'mh-search)
9179 (require 'mh-utils)
9180 (mh-find-path)
9181 (if (not article)
9182 (mh-visit-folder (mh-normalize-folder-name folder))
9183 (setq article (org-add-angle-brackets article))
9184 (mh-search-choose)
9185 (if (equal mh-searcher 'pick)
9186 (progn
9187 (mh-search folder (list "--message-id" article))
9188 (when (and org-mhe-search-all-folders
9189 (not (org-mhe-get-message-real-folder)))
9190 (kill-this-buffer)
9191 (mh-search "+" (list "--message-id" article))))
9192 (mh-search "+" article))
9193 (if (org-mhe-get-message-real-folder)
9194 (mh-show-msg 1)
9195 (kill-this-buffer)
9196 (error "Message not found"))))
9197
9198 ;; BibTeX links
9199
9200 ;; Use the custom search meachnism to construct and use search strings for
9201 ;; file links to BibTeX database entries.
9202
9203 (defun org-create-file-search-in-bibtex ()
9204 "Create the search string and description for a BibTeX database entry."
9205 (when (eq major-mode 'bibtex-mode)
9206 ;; yes, we want to construct this search string.
9207 ;; Make a good description for this entry, using names, year and the title
9208 ;; Put it into the `description' variable which is dynamically scoped.
9209 (let ((bibtex-autokey-names 1)
9210 (bibtex-autokey-names-stretch 1)
9211 (bibtex-autokey-name-case-convert-function 'identity)
9212 (bibtex-autokey-name-separator " & ")
9213 (bibtex-autokey-additional-names " et al.")
9214 (bibtex-autokey-year-length 4)
9215 (bibtex-autokey-name-year-separator " ")
9216 (bibtex-autokey-titlewords 3)
9217 (bibtex-autokey-titleword-separator " ")
9218 (bibtex-autokey-titleword-case-convert-function 'identity)
9219 (bibtex-autokey-titleword-length 'infty)
9220 (bibtex-autokey-year-title-separator ": "))
9221 (setq description (bibtex-generate-autokey)))
9222 ;; Now parse the entry, get the key and return it.
9223 (save-excursion
9224 (bibtex-beginning-of-entry)
9225 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9226
9227 (defun org-execute-file-search-in-bibtex (s)
9228 "Find the link search string S as a key for a database entry."
9229 (when (eq major-mode 'bibtex-mode)
9230 ;; Yes, we want to do the search in this file.
9231 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9232 (goto-char (point-min))
9233 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9234 (regexp-quote s) "[ \t\n]*,") nil t)
9235 (goto-char (match-beginning 0)))
9236 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9237 ;; Use double prefix to indicate that any web link should be browsed
9238 (let ((b (current-buffer)) (p (point)))
9239 ;; Restore the window configuration because we just use the web link
9240 (set-window-configuration org-window-config-before-follow-link)
9241 (save-excursion (set-buffer b) (goto-char p)
9242 (bibtex-url)))
9243 (recenter 0)) ; Move entry start to beginning of window
9244 ;; return t to indicate that the search is done.
9245 t))
9246
9247 ;; Finally add the functions to the right hooks.
9248 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
9249 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
9250
9251 ;; end of Bibtex link setup
9252
9253 (defun org-upgrade-old-links (&optional query-description)
9254 "Transfer old <...> style links to new [[...]] style links.
9255 With arg query-description, ask at each match for a description text to use
9256 for this link."
9257 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
9258 (save-excursion
9259 (goto-char (point-min))
9260 (let ((re (concat "\\([^[]\\)<\\("
9261 "\\(" (mapconcat 'identity org-link-types "\\|")
9262 "\\):"
9263 "[^" org-non-link-chars "]+\\)>"))
9264 l1 l2 (cnt 0))
9265 (while (re-search-forward re nil t)
9266 (setq cnt (1+ cnt)
9267 l1 (org-match-string-no-properties 2)
9268 l2 (save-match-data (org-link-escape l1)))
9269 (when query-description (setq l1 (read-string "Desc: " l1)))
9270 (if (equal l1 l2)
9271 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
9272 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
9273 (message "%d matches have beed treated" cnt))))
9274
9275 (defun org-open-file (path &optional in-emacs line search)
9276 "Open the file at PATH.
9277 First, this expands any special file name abbreviations. Then the
9278 configuration variable `org-file-apps' is checked if it contains an
9279 entry for this file type, and if yes, the corresponding command is launched.
9280 If no application is found, Emacs simply visits the file.
9281 With optional argument IN-EMACS, Emacs will visit the file.
9282 Optional LINE specifies a line to go to, optional SEARCH a string to
9283 search for. If LINE or SEARCH is given, the file will always be
9284 opened in Emacs.
9285 If the file does not exist, an error is thrown."
9286 (setq in-emacs (or in-emacs line search))
9287 (let* ((file (if (equal path "")
9288 buffer-file-name
9289 (convert-standard-filename (org-expand-file-name path))))
9290 (dirp (file-directory-p file))
9291 (dfile (downcase file))
9292 (old-buffer (current-buffer))
9293 (old-pos (point))
9294 (old-mode major-mode)
9295 ext cmd apps)
9296 (if (and (not (file-exists-p file))
9297 (not org-open-non-existing-files))
9298 (error "No such file: %s" file))
9299 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9300 (setq ext (match-string 1 dfile))
9301 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9302 (setq ext (match-string 1 dfile))))
9303 (setq apps (append org-file-apps (org-default-apps)))
9304 (if in-emacs
9305 (setq cmd 'emacs)
9306 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
9307 (cdr (assoc ext apps))
9308 (cdr (assoc t apps)))))
9309 (when (eq cmd 'mailcap)
9310 (require 'mailcap)
9311 (mailcap-parse-mailcaps)
9312 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9313 (command (mailcap-mime-info mime-type)))
9314 (if (stringp command)
9315 (setq cmd command)
9316 (setq cmd 'emacs))))
9317 (cond
9318 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9319 ;; Normalize use of quote, this can vary.
9320 (if (string-match "['\"]%s['\"]" cmd)
9321 (setq cmd (replace-match "'%s'" t t cmd)))
9322 (setq cmd (format cmd file))
9323 (save-window-excursion
9324 (shell-command (concat cmd " &"))))
9325 ((or (stringp cmd)
9326 (eq cmd 'emacs))
9327 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
9328 (funcall (cdr (assq 'file org-link-frame-setup)) file))
9329 (if line (goto-line line)
9330 (if search (org-link-search search))))
9331 ((consp cmd)
9332 (eval cmd))
9333 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9334 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
9335 (or (not (equal old-buffer (current-buffer)))
9336 (not (equal old-pos (point))))
9337 (org-mark-ring-push old-pos old-buffer))))
9338
9339 (defun org-default-apps ()
9340 "Return the default applications for this operating system."
9341 (cond
9342 ((eq system-type 'darwin)
9343 org-file-apps-defaults-macosx)
9344 ((eq system-type 'windows-nt)
9345 org-file-apps-defaults-windowsnt)
9346 (t org-file-apps-defaults-gnu)))
9347
9348 (defun org-expand-file-name (path)
9349 "Replace special path abbreviations and expand the file name."
9350 (expand-file-name path))
9351
9352
9353 (defvar org-insert-link-history nil
9354 "Minibuffer history for links inserted with `org-insert-link'.")
9355
9356 (defvar org-stored-links nil
9357 "Contains the links stored with `org-store-link'.")
9358
9359 ;;;###autoload
9360 (defun org-store-link (arg)
9361 "\\<org-mode-map>Store an org-link to the current location.
9362 This link can later be inserted into an org-buffer with
9363 \\[org-insert-link].
9364 For some link types, a prefix arg is interpreted:
9365 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9366 For file links, arg negates `org-context-in-file-links'."
9367 (interactive "P")
9368 (let (link cpltxt desc description search txt (pos (point)))
9369 (cond
9370
9371 ((eq major-mode 'bbdb-mode)
9372 (setq cpltxt (concat
9373 "bbdb:"
9374 (or (bbdb-record-name (bbdb-current-record))
9375 (bbdb-record-company (bbdb-current-record))))
9376 link (org-make-link cpltxt)))
9377
9378 ((eq major-mode 'Info-mode)
9379 (setq link (org-make-link "info:"
9380 (file-name-nondirectory Info-current-file)
9381 ":" Info-current-node))
9382 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9383 ":" Info-current-node)))
9384
9385 ((eq major-mode 'calendar-mode)
9386 (let ((cd (calendar-cursor-to-date)))
9387 (setq link
9388 (format-time-string
9389 (car org-time-stamp-formats)
9390 (apply 'encode-time
9391 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9392 nil nil nil))))))
9393
9394 ((or (eq major-mode 'vm-summary-mode)
9395 (eq major-mode 'vm-presentation-mode))
9396 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9397 (vm-follow-summary-cursor)
9398 (save-excursion
9399 (vm-select-folder-buffer)
9400 (let* ((message (car vm-message-pointer))
9401 (folder buffer-file-name)
9402 (subject (vm-su-subject message))
9403 (author (vm-su-full-name message))
9404 (message-id (vm-su-message-id message)))
9405 (setq message-id (org-remove-angle-brackets message-id))
9406 (setq folder (abbreviate-file-name folder))
9407 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9408 folder)
9409 (setq folder (replace-match "" t t folder)))
9410 (setq cpltxt (concat author " on: " subject))
9411 (setq link (org-make-link "vm:" folder "#" message-id)))))
9412
9413 ((eq major-mode 'wl-summary-mode)
9414 (let* ((msgnum (wl-summary-message-number))
9415 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9416 msgnum 'message-id))
9417 (wl-message-entity (elmo-msgdb-overview-get-entity
9418 msgnum (wl-summary-buffer-msgdb)))
9419 (author (wl-summary-line-from)) ; FIXME: correct?
9420 (subject "???")) ; FIXME:
9421 (setq message-id (org-remove-angle-brackets message-id))
9422 (setq cpltxt (concat author " on: " subject))
9423 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9424 "#" message-id))))
9425
9426 ((or (equal major-mode 'mh-folder-mode)
9427 (equal major-mode 'mh-show-mode))
9428 (let ((from-header (org-mhe-get-header "From:"))
9429 (to-header (org-mhe-get-header "To:"))
9430 (subject (org-mhe-get-header "Subject:")))
9431 (setq cpltxt (concat from-header " on: " subject))
9432 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9433 (org-remove-angle-brackets
9434 (org-mhe-get-header "Message-Id:"))))))
9435
9436 ((eq major-mode 'rmail-mode)
9437 (save-excursion
9438 (save-restriction
9439 (rmail-narrow-to-non-pruned-header)
9440 (let ((folder buffer-file-name)
9441 (message-id (mail-fetch-field "message-id"))
9442 (author (mail-fetch-field "from"))
9443 (subject (mail-fetch-field "subject")))
9444 (setq message-id (org-remove-angle-brackets message-id))
9445 (setq cpltxt (concat author " on: " subject))
9446 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9447
9448 ((eq major-mode 'gnus-group-mode)
9449 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9450 (gnus-group-group-name)) ; version
9451 ((fboundp 'gnus-group-name)
9452 (gnus-group-name))
9453 (t "???"))))
9454 (setq cpltxt (concat
9455 (if (org-xor arg org-usenet-links-prefer-google)
9456 "http://groups.google.com/groups?group="
9457 "gnus:")
9458 group)
9459 link (org-make-link cpltxt))))
9460
9461 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9462 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9463 (gnus-summary-beginning-of-article)
9464 (let* ((group (car gnus-article-current))
9465 (article (cdr gnus-article-current))
9466 (header (gnus-summary-article-header article))
9467 (author (mail-header-from header))
9468 (message-id (mail-header-id header))
9469 (date (mail-header-date header))
9470 (subject (gnus-summary-subject-string)))
9471 (setq cpltxt (concat author " on: " subject))
9472 (if (org-xor arg org-usenet-links-prefer-google)
9473 (setq link
9474 (concat
9475 cpltxt "\n "
9476 (format "http://groups.google.com/groups?as_umsgid=%s"
9477 (org-fixup-message-id-for-http message-id))))
9478 (setq link (org-make-link "gnus:" group
9479 "#" (number-to-string article))))))
9480
9481 ((eq major-mode 'w3-mode)
9482 (setq cpltxt (url-view-url t)
9483 link (org-make-link cpltxt)))
9484 ((eq major-mode 'w3m-mode)
9485 (setq cpltxt (or w3m-current-title w3m-current-url)
9486 link (org-make-link w3m-current-url)))
9487
9488 ((setq search (run-hook-with-args-until-success
9489 'org-create-file-search-functions))
9490 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9491 "::" search))
9492 (setq cpltxt (or description link)))
9493
9494 ((eq major-mode 'image-mode)
9495 (setq cpltxt (concat "file:"
9496 (abbreviate-file-name buffer-file-name))
9497 link (org-make-link cpltxt)))
9498
9499 ((eq major-mode 'org-mode)
9500 ;; Just link to current headline
9501 (setq cpltxt (concat "file:"
9502 (abbreviate-file-name buffer-file-name)))
9503 ;; Add a context search string
9504 (when (org-xor org-context-in-file-links arg)
9505 ;; Check if we are on a target
9506 (if (save-excursion
9507 (skip-chars-forward "^>\n\r")
9508 (and (re-search-backward "<<" nil t)
9509 (looking-at "<<\\(.*?\\)>>")
9510 (<= (match-beginning 0) pos)
9511 (>= (match-end 0) pos)))
9512 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9513 (setq txt (cond
9514 ((org-on-heading-p) nil)
9515 ((org-region-active-p)
9516 (buffer-substring (region-beginning) (region-end)))
9517 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9518 (when (or (null txt) (string-match "\\S-" txt))
9519 (setq cpltxt
9520 (concat cpltxt "::"
9521 (if org-file-link-context-use-camel-case
9522 (org-make-org-heading-camel txt)
9523 (org-make-org-heading-search-string txt)))
9524 desc "NONE"))))
9525 (if (string-match "::\\'" cpltxt)
9526 (setq cpltxt (substring cpltxt 0 -2)))
9527 (setq link (org-make-link cpltxt)))
9528
9529 (buffer-file-name
9530 ;; Just link to this file here.
9531 (setq cpltxt (concat "file:"
9532 (abbreviate-file-name buffer-file-name)))
9533 ;; Add a context string
9534 (when (org-xor org-context-in-file-links arg)
9535 (setq txt (if (org-region-active-p)
9536 (buffer-substring (region-beginning) (region-end))
9537 (buffer-substring (point-at-bol) (point-at-eol))))
9538 ;; Only use search option if there is some text.
9539 (when (string-match "\\S-" txt)
9540 (setq cpltxt
9541 (concat cpltxt "::"
9542 (if org-file-link-context-use-camel-case
9543 (org-make-org-heading-camel txt)
9544 (org-make-org-heading-search-string txt)))
9545 desc "NONE")))
9546 (setq link (org-make-link cpltxt)))
9547
9548 ((interactive-p)
9549 (error "Cannot link to a buffer which is not visiting a file"))
9550
9551 (t (setq link nil)))
9552
9553 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9554 (setq link (or link cpltxt)
9555 desc (or desc cpltxt))
9556 (if (equal desc "NONE") (setq desc nil))
9557
9558 (if (and (interactive-p) link)
9559 (progn
9560 (setq org-stored-links
9561 (cons (list cpltxt link desc) org-stored-links))
9562 (message "Stored: %s" (or cpltxt link)))
9563 (org-make-link-string link desc))))
9564
9565 (defun org-make-org-heading-search-string (&optional string heading)
9566 "Make search string for STRING or current headline."
9567 (interactive)
9568 (let ((s (or string (org-get-heading))))
9569 (unless (and string (not heading))
9570 ;; We are using a headline, clean up garbage in there.
9571 (if (string-match org-todo-regexp s)
9572 (setq s (replace-match "" t t s)))
9573 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9574 (setq s (replace-match "" t t s)))
9575 (setq s (org-trim s))
9576 (if (string-match (concat "^\\(" org-quote-string "\\|"
9577 org-comment-string "\\)") s)
9578 (setq s (replace-match "" t t s)))
9579 (while (string-match org-ts-regexp s)
9580 (setq s (replace-match "" t t s))))
9581 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
9582 (setq s (replace-match " " t t s)))
9583 (or string (setq s (concat "*" s))) ; Add * for headlines
9584 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9585
9586 (defun org-make-org-heading-camel (&optional string heading)
9587 "Make a CamelCase string for STRING or the current headline."
9588 (interactive)
9589 (let ((s (or string (org-get-heading))))
9590 (unless (and string (not heading))
9591 ;; We are using a headline, clean up garbage in there.
9592 (if (string-match org-todo-regexp s)
9593 (setq s (replace-match "" t t s)))
9594 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9595 (setq s (replace-match "" t t s)))
9596 (setq s (org-trim s))
9597 (if (string-match (concat "^\\(" org-quote-string "\\|"
9598 org-comment-string "\\)") s)
9599 (setq s (replace-match "" t t s)))
9600 (while (string-match org-ts-regexp s)
9601 (setq s (replace-match "" t t s))))
9602 (while (string-match "[^a-zA-Z_ \t]+" s)
9603 (setq s (replace-match " " t t s)))
9604 (or string (setq s (concat "*" s))) ; Add * for headlines
9605 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
9606
9607 (defun org-make-link (&rest strings)
9608 "Concatenate STRINGS, format resulting string with `org-link-format'."
9609 (format org-link-format (apply 'concat strings)))
9610
9611 (defun org-make-link-string (link &optional description)
9612 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9613 (if (eq org-link-style 'plain)
9614 (if (equal description link)
9615 link
9616 (concat description "\n" link))
9617 (when (stringp description)
9618 ;; Remove brackets from the description, they are fatal.
9619 (while (string-match "\\[\\|\\]" description)
9620 (setq description (replace-match "" t t description))))
9621 (when (equal (org-link-escape link) description)
9622 ;; No description needed, it is identical
9623 (setq description nil))
9624 (when (and (not description)
9625 (not (equal link (org-link-escape link))))
9626 (setq description link))
9627 (concat "[[" (org-link-escape link) "]"
9628 (if description (concat "[" description "]") "")
9629 "]")))
9630
9631 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
9632 "Association list of escapes for some characters problematic in links.")
9633
9634 (defun org-link-escape (text)
9635 "Escape charaters in TEXT that are problematic for links."
9636 (when text
9637 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
9638 org-link-escape-chars "\\|")))
9639 (while (string-match re text)
9640 (setq text
9641 (replace-match
9642 (cdr (assoc (match-string 0 text) org-link-escape-chars))
9643 t t text)))
9644 text)))
9645
9646 (defun org-link-unescape (text)
9647 "Reverse the action of `org-link-escape'."
9648 (when text
9649 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
9650 org-link-escape-chars "\\|")))
9651 (while (string-match re text)
9652 (setq text
9653 (replace-match
9654 (car (rassoc (match-string 0 text) org-link-escape-chars))
9655 t t text)))
9656 text)))
9657
9658 (defun org-xor (a b)
9659 "Exclusive or."
9660 (if a (not b) b))
9661
9662 (defun org-get-header (header)
9663 "Find a header field in the current buffer."
9664 (save-excursion
9665 (goto-char (point-min))
9666 (let ((case-fold-search t) s)
9667 (cond
9668 ((eq header 'from)
9669 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
9670 (setq s (match-string 1)))
9671 (while (string-match "\"" s)
9672 (setq s (replace-match "" t t s)))
9673 (if (string-match "[<(].*" s)
9674 (setq s (replace-match "" t t s))))
9675 ((eq header 'message-id)
9676 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
9677 (setq s (match-string 1))))
9678 ((eq header 'subject)
9679 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
9680 (setq s (match-string 1)))))
9681 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
9682 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
9683 s)))
9684
9685
9686 (defun org-fixup-message-id-for-http (s)
9687 "Replace special characters in a message id, so it can be used in an http query."
9688 (while (string-match "<" s)
9689 (setq s (replace-match "%3C" t t s)))
9690 (while (string-match ">" s)
9691 (setq s (replace-match "%3E" t t s)))
9692 (while (string-match "@" s)
9693 (setq s (replace-match "%40" t t s)))
9694 s)
9695
9696 (defun org-insert-link (&optional complete-file)
9697 "Insert a link. At the prompt, enter the link.
9698
9699 Completion can be used to select a link previously stored with
9700 `org-store-link'. When the empty string is entered (i.e. if you just
9701 press RET at the prompt), the link defaults to the most recently
9702 stored link. As SPC triggers completion in the minibuffer, you need to
9703 use M-SPC or C-q SPC to force the insertion of a space character.
9704
9705 You will also be prompted for a description, and if one is given, it will
9706 be displayed in the buffer instead of the link.
9707
9708 If there is already a link at point, this command will allow you to edit link
9709 and description parts.
9710
9711 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
9712 selected using completion. The path to the file will be relative to
9713 the current directory if the file is in the current directory or a
9714 subdirectory. Otherwise, the link will be the absolute path as
9715 completed in the minibuffer (i.e. normally ~/path/to/file).
9716
9717 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
9718 is in the current directory or below.
9719 With three \\[universal-argument] prefixes, negate the meaning of
9720 `org-keep-stored-link-after-insertion'."
9721 (interactive "P")
9722 (let (link desc entry remove file (pos (point)))
9723 (cond
9724 ((save-excursion
9725 (skip-chars-forward "^]\n\r")
9726 (and (re-search-backward "\\[\\[" nil t)
9727 (looking-at org-bracket-link-regexp)
9728 (<= (match-beginning 0) pos)
9729 (>= (match-end 0) pos)))
9730 ;; We do have a link at point, and we are going to edit it.
9731 (setq remove (list (match-beginning 0) (match-end 0)))
9732 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9733 (setq link (read-string "Link: "
9734 (org-link-unescape
9735 (org-match-string-no-properties 1)))))
9736 ((equal complete-file '(4))
9737 ;; Completing read for file names.
9738 (setq file (read-file-name "File: "))
9739 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9740 (pwd1 (file-name-as-directory (abbreviate-file-name
9741 (expand-file-name ".")))))
9742 (cond
9743 ((equal complete-file '(16))
9744 (setq link (org-make-link
9745 "file:"
9746 (abbreviate-file-name (expand-file-name file)))))
9747 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9748 (setq link (org-make-link "file:" (match-string 1 file))))
9749 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9750 (expand-file-name file))
9751 (setq link (org-make-link
9752 "file:" (match-string 1 (expand-file-name file)))))
9753 (t (setq link (org-make-link "file:" file))))))
9754 (t
9755 ;; Read link, with completion for stored links.
9756 (setq link (org-completing-read
9757 "Link: " org-stored-links nil nil nil
9758 org-insert-link-history
9759 (or (car (car org-stored-links)))))
9760 (setq entry (assoc link org-stored-links))
9761 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9762 (not org-keep-stored-link-after-insertion))
9763 (setq org-stored-links (delq (assoc link org-stored-links)
9764 org-stored-links)))
9765 (setq link (if entry (nth 1 entry) link)
9766 desc (or desc (nth 2 entry)))))
9767
9768 (if (string-match org-plain-link-re link)
9769 ;; URL-like link, normalize the use of angular brackets.
9770 (setq link (org-make-link (org-remove-angle-brackets link))))
9771
9772 ;; Check if we are linking to the current file with a search option
9773 ;; If yes, simplify the link by using only the search option.
9774 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
9775 (let* ((path (match-string 1 link))
9776 (case-fold-search nil)
9777 (search (match-string 2 link)))
9778 (save-match-data
9779 (if (equal (file-truename buffer-file-name) (file-truename path))
9780 ;; We are linking to this same file, with a search option
9781 (setq link search)))))
9782
9783 ;; Check if we can/should use a relative path. If yes, simplify the link
9784 (when (string-match "\\<file:\\(.*\\)" link)
9785 (let* ((path (match-string 1 link))
9786 (case-fold-search nil))
9787 (cond
9788 ((eq org-link-file-path-type 'absolute)
9789 (setq path (abbreviate-file-name (expand-file-name path))))
9790 ((eq org-link-file-path-type 'noabbrev)
9791 (setq path (expand-file-name path)))
9792 ((eq org-link-file-path-type 'relative)
9793 (setq path (file-relative-name path)))
9794 (t
9795 (save-match-data
9796 (if (string-match (concat "^" (regexp-quote
9797 (file-name-as-directory
9798 (expand-file-name "."))))
9799 (expand-file-name path))
9800 ;; We are linking a file with relative path name.
9801 (setq path (substring (expand-file-name path)
9802 (match-end 0)))))))
9803 (setq link (concat "file:" path))))
9804
9805 (setq desc (read-string "Description: " desc))
9806 (unless (string-match "\\S-" desc) (setq desc nil))
9807 (if remove (apply 'delete-region remove))
9808 (insert (org-make-link-string link desc))))
9809
9810 (defun org-completing-read (&rest args)
9811 (let ((minibuffer-local-completion-map
9812 (copy-keymap minibuffer-local-completion-map)))
9813 (define-key minibuffer-local-completion-map " " 'self-insert-command)
9814 (apply 'completing-read args)))
9815
9816 ;;; Hooks for remember.el
9817
9818 (defvar org-finish-function nil)
9819
9820 ;;;###autoload
9821 (defun org-remember-annotation ()
9822 "Return a link to the current location as an annotation for remember.el.
9823 If you are using Org-mode files as target for data storage with
9824 remember.el, then the annotations should include a link compatible with the
9825 conventions in Org-mode. This function returns such a link."
9826 (org-store-link nil))
9827
9828 (defconst org-remember-help
9829 "Select a destination location for the note.
9830 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
9831 RET at beg-of-buf -> Append to file as level 2 headline
9832 RET on headline -> Store as sublevel entry to current headline
9833 <left>/<right> -> before/after current headline, same headings level")
9834
9835 ;;;###autoload
9836 (defun org-remember-apply-template ()
9837 "Initialize *remember* buffer with template, invoke `org-mode'.
9838 This function should be placed into `remember-mode-hook' and in fact requires
9839 to be run from that hook to fucntion properly."
9840 (if org-remember-templates
9841
9842 (let* ((entry (if (= (length org-remember-templates) 1)
9843 (cdar org-remember-templates)
9844 (message "Select template: %s"
9845 (mapconcat
9846 (lambda (x) (char-to-string (car x)))
9847 org-remember-templates " "))
9848 (cdr (assoc (read-char-exclusive) org-remember-templates))))
9849 (tpl (car entry))
9850 (file (if (consp (cdr entry)) (nth 1 entry)))
9851 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
9852 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
9853 (v-u (concat "[" (substring v-t 1 -1) "]"))
9854 (v-U (concat "[" (substring v-T 1 -1) "]"))
9855 (v-a annotation) ; defined in `remember-mode'
9856 (v-i initial) ; defined in `remember-mode'
9857 (v-n user-full-name)
9858 )
9859 (unless tpl (setq tpl "") (message "No template") (ding))
9860 (insert tpl) (goto-char (point-min))
9861 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
9862 (when (and initial (equal (match-string 0) "%i"))
9863 (save-match-data
9864 (let* ((lead (buffer-substring
9865 (point-at-bol) (match-beginning 0))))
9866 (setq v-i (mapconcat 'identity
9867 (org-split-string initial "\n")
9868 (concat "\n" lead))))))
9869 (replace-match
9870 (or (eval (intern (concat "v-" (match-string 1)))) "")
9871 t t))
9872 (let ((org-startup-folded nil)
9873 (org-startup-with-deadline-check nil))
9874 (org-mode))
9875 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
9876 (set (make-local-variable 'org-default-notes-file) file))
9877 (goto-char (point-min))
9878 (if (re-search-forward "%\\?" nil t) (replace-match "")))
9879 (let ((org-startup-folded nil)
9880 (org-startup-with-deadline-check nil))
9881 (org-mode)))
9882 (set (make-local-variable 'org-finish-function) 'remember-buffer))
9883
9884 ;;;###autoload
9885 (defun org-remember-handler ()
9886 "Store stuff from remember.el into an org file.
9887 First prompts for an org file. If the user just presses return, the value
9888 of `org-default-notes-file' is used.
9889 Then the command offers the headings tree of the selected file in order to
9890 file the text at a specific location.
9891 You can either immediately press RET to get the note appended to the
9892 file, or you can use vertical cursor motion and visibility cycling (TAB) to
9893 find a better place. Then press RET or <left> or <right> in insert the note.
9894
9895 Key Cursor position Note gets inserted
9896 -----------------------------------------------------------------------------
9897 RET buffer-start as level 2 heading at end of file
9898 RET on headline as sublevel of the heading at cursor
9899 RET no heading at cursor position, level taken from context.
9900 Or use prefix arg to specify level manually.
9901 <left> on headline as same level, before current heading
9902 <right> on headline as same level, after current heading
9903
9904 So the fastest way to store the note is to press RET RET to append it to
9905 the default file. This way your current train of thought is not
9906 interrupted, in accordance with the principles of remember.el. But with
9907 little extra effort, you can push it directly to the correct location.
9908
9909 Before being stored away, the function ensures that the text has a
9910 headline, i.e. a first line that starts with a \"*\". If not, a headline
9911 is constructed from the current date and some additional data.
9912
9913 If the variable `org-adapt-indentation' is non-nil, the entire text is
9914 also indented so that it starts in the same column as the headline
9915 \(i.e. after the stars).
9916
9917 See also the variable `org-reverse-note-order'."
9918 (catch 'quit
9919 (let* ((txt (buffer-substring (point-min) (point-max)))
9920 (fastp current-prefix-arg)
9921 (file (if fastp org-default-notes-file (org-get-org-file)))
9922 (visiting (find-buffer-visiting file))
9923 (org-startup-with-deadline-check nil)
9924 (org-startup-folded nil)
9925 (org-startup-align-all-tables nil)
9926 spos level indent reversed)
9927 ;; Modify text so that it becomes a nice subtree which can be inserted
9928 ;; into an org tree.
9929 (let* ((lines (split-string txt "\n"))
9930 first)
9931 ;; remove empty lines at the beginning
9932 (while (and lines (string-match "^[ \t]*\n" (car lines)))
9933 (setq lines (cdr lines)))
9934 (setq first (car lines) lines (cdr lines))
9935 (if (string-match "^\\*+" first)
9936 ;; Is already a headline
9937 (setq indent nil)
9938 ;; We need to add a headline: Use time and first buffer line
9939 (setq lines (cons first lines)
9940 first (concat "* " (current-time-string)
9941 " (" (remember-buffer-desc) ")")
9942 indent " "))
9943 (if (and org-adapt-indentation indent)
9944 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
9945 (setq txt (concat first "\n"
9946 (mapconcat 'identity lines "\n"))))
9947 ;; Find the file
9948 (if (not visiting)
9949 (find-file-noselect file))
9950 (with-current-buffer (get-file-buffer file)
9951 (save-excursion (and (goto-char (point-min))
9952 (not (re-search-forward "^\\* " nil t))
9953 (insert "\n* Notes\n")))
9954 (setq reversed (org-notes-order-reversed-p))
9955 (save-excursion
9956 (save-restriction
9957 (widen)
9958 ;; Ask the User for a location
9959 (setq spos (if fastp 1 (org-get-location
9960 (current-buffer)
9961 org-remember-help)))
9962 (if (not spos) (throw 'quit nil)) ; return nil to show we did
9963 ; not handle this note
9964 (goto-char spos)
9965 (cond ((bobp)
9966 ;; Put it at the start or end, as level 2
9967 (save-restriction
9968 (widen)
9969 (goto-char (if reversed (point-min) (point-max)))
9970 (if (not (bolp)) (newline))
9971 (org-paste-subtree 2 txt)))
9972 ((and (org-on-heading-p nil) (not current-prefix-arg))
9973 ;; Put it below this entry, at the beg/end of the subtree
9974 (org-back-to-heading)
9975 (setq level (funcall outline-level))
9976 (if reversed
9977 (outline-end-of-heading)
9978 (outline-end-of-subtree))
9979 (if (not (bolp)) (newline))
9980 (beginning-of-line 1)
9981 (org-paste-subtree (1+ level) txt))
9982 (t
9983 ;; Put it right there, with automatic level determined by
9984 ;; org-paste-subtree or from prefix arg
9985 (org-paste-subtree current-prefix-arg txt)))
9986 (when remember-save-after-remembering
9987 (save-buffer)
9988 (if (not visiting) (kill-buffer (current-buffer)))))))))
9989 t) ;; return t to indicate that we took care of this note.
9990
9991 (defun org-get-org-file ()
9992 "Read a filename, with default directory `org-directory'."
9993 (let ((default (or org-default-notes-file remember-data-file)))
9994 (read-file-name (format "File name [%s]: " default)
9995 (file-name-as-directory org-directory)
9996 default)))
9997
9998 (defun org-notes-order-reversed-p ()
9999 "Check if the current file should receive notes in reversed order."
10000 (cond
10001 ((not org-reverse-note-order) nil)
10002 ((eq t org-reverse-note-order) t)
10003 ((not (listp org-reverse-note-order)) nil)
10004 (t (catch 'exit
10005 (let ((all org-reverse-note-order)
10006 entry)
10007 (while (setq entry (pop all))
10008 (if (string-match (car entry) buffer-file-name)
10009 (throw 'exit (cdr entry))))
10010 nil)))))
10011
10012 ;;; Tables
10013
10014 ;; Watch out: Here we are talking about two different kind of tables.
10015 ;; Most of the code is for the tables created with the Org-mode table editor.
10016 ;; Sometimes, we talk about tables created and edited with the table.el
10017 ;; Emacs package. We call the former org-type tables, and the latter
10018 ;; table.el-type tables.
10019
10020
10021 (defun org-before-change-function (beg end)
10022 "Every change indicates that a table might need an update."
10023 (setq org-table-may-need-update t))
10024
10025 (defconst org-table-line-regexp "^[ \t]*|"
10026 "Detects an org-type table line.")
10027 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
10028 "Detects an org-type table line.")
10029 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
10030 "Detects a table line marked for automatic recalculation.")
10031 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
10032 "Detects a table line marked for automatic recalculation.")
10033 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
10034 "Detects a table line marked for automatic recalculation.")
10035 (defconst org-table-hline-regexp "^[ \t]*|-"
10036 "Detects an org-type table hline.")
10037 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
10038 "Detects a table-type table hline.")
10039 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
10040 "Detects an org-type or table-type table.")
10041 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
10042 "Searching from within a table (any type) this finds the first line
10043 outside the table.")
10044 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
10045 "Searching from within a table (any type) this finds the first line
10046 outside the table.")
10047
10048 (defun org-table-create-with-table.el ()
10049 "Use the table.el package to insert a new table.
10050 If there is already a table at point, convert between Org-mode tables
10051 and table.el tables."
10052 (interactive)
10053 (require 'table)
10054 (cond
10055 ((org-at-table.el-p)
10056 (if (y-or-n-p "Convert table to Org-mode table? ")
10057 (org-table-convert)))
10058 ((org-at-table-p)
10059 (if (y-or-n-p "Convert table to table.el table? ")
10060 (org-table-convert)))
10061 (t (call-interactively 'table-insert))))
10062
10063 (defun org-table-create-or-convert-from-region (arg)
10064 "Convert region to table, or create an empty table.
10065 If there is an active region, convert it to a table. If there is no such
10066 region, create an empty table."
10067 (interactive "P")
10068 (if (org-region-active-p)
10069 (org-table-convert-region (region-beginning) (region-end) arg)
10070 (org-table-create arg)))
10071
10072 (defun org-table-create (&optional size)
10073 "Query for a size and insert a table skeleton.
10074 SIZE is a string Columns x Rows like for example \"3x2\"."
10075 (interactive "P")
10076 (unless size
10077 (setq size (read-string
10078 (concat "Table size Columns x Rows [e.g. "
10079 org-table-default-size "]: ")
10080 "" nil org-table-default-size)))
10081
10082 (let* ((pos (point))
10083 (indent (make-string (current-column) ?\ ))
10084 (split (org-split-string size " *x *"))
10085 (rows (string-to-number (nth 1 split)))
10086 (columns (string-to-number (car split)))
10087 (line (concat (apply 'concat indent "|" (make-list columns " |"))
10088 "\n")))
10089 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
10090 (point-at-bol) (point)))
10091 (beginning-of-line 1)
10092 (newline))
10093 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
10094 (dotimes (i rows) (insert line))
10095 (goto-char pos)
10096 (if (> rows 1)
10097 ;; Insert a hline after the first row.
10098 (progn
10099 (end-of-line 1)
10100 (insert "\n|-")
10101 (goto-char pos)))
10102 (org-table-align)))
10103
10104 (defun org-table-convert-region (beg0 end0 &optional nspace)
10105 "Convert region to a table.
10106 The region goes from BEG0 to END0, but these borders will be moved
10107 slightly, to make sure a beginning of line in the first line is included.
10108 When NSPACE is non-nil, it indicates the minimum number of spaces that
10109 separate columns (default: just one space)."
10110 (interactive "rP")
10111 (let* ((beg (min beg0 end0))
10112 (end (max beg0 end0))
10113 (tabsep t)
10114 re)
10115 (goto-char beg)
10116 (beginning-of-line 1)
10117 (setq beg (move-marker (make-marker) (point)))
10118 (goto-char end)
10119 (if (bolp) (backward-char 1) (end-of-line 1))
10120 (setq end (move-marker (make-marker) (point)))
10121 ;; Lets see if this is tab-separated material. If every nonempty line
10122 ;; contains a tab, we will assume that it is tab-separated material
10123 (if nspace
10124 (setq tabsep nil)
10125 (goto-char beg)
10126 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
10127 (if nspace (setq tabsep nil))
10128 (if tabsep
10129 (setq re "^\\|\t")
10130 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
10131 (max 1 (prefix-numeric-value nspace)))))
10132 (goto-char beg)
10133 (while (re-search-forward re end t)
10134 (replace-match "|" t t))
10135 (goto-char beg)
10136 (insert " ")
10137 (org-table-align)))
10138
10139 (defun org-table-import (file arg)
10140 "Import FILE as a table.
10141 The file is assumed to be tab-separated. Such files can be produced by most
10142 spreadsheet and database applications. If no tabs (at least one per line)
10143 are found, lines will be split on whitespace into fields."
10144 (interactive "f\nP")
10145 (or (bolp) (newline))
10146 (let ((beg (point))
10147 (pm (point-max)))
10148 (insert-file-contents file)
10149 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
10150
10151 (defun org-table-export ()
10152 "Export table as a tab-separated file.
10153 Such a file can be imported into a spreadsheet program like Excel."
10154 (interactive)
10155 (let* ((beg (org-table-begin))
10156 (end (org-table-end))
10157 (table (buffer-substring beg end))
10158 (file (read-file-name "Export table to: "))
10159 buf)
10160 (unless (or (not (file-exists-p file))
10161 (y-or-n-p (format "Overwrite file %s? " file)))
10162 (error "Abort"))
10163 (with-current-buffer (find-file-noselect file)
10164 (setq buf (current-buffer))
10165 (erase-buffer)
10166 (fundamental-mode)
10167 (insert table)
10168 (goto-char (point-min))
10169 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
10170 (replace-match "" t t)
10171 (end-of-line 1))
10172 (goto-char (point-min))
10173 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
10174 (replace-match "" t t)
10175 (goto-char (min (1+ (point)) (point-max))))
10176 (goto-char (point-min))
10177 (while (re-search-forward "^-[-+]*$" nil t)
10178 (replace-match "")
10179 (if (looking-at "\n")
10180 (delete-char 1)))
10181 (goto-char (point-min))
10182 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
10183 (replace-match "\t" t t))
10184 (save-buffer))
10185 (kill-buffer buf)))
10186
10187 (defvar org-table-aligned-begin-marker (make-marker)
10188 "Marker at the beginning of the table last aligned.
10189 Used to check if cursor still is in that table, to minimize realignment.")
10190 (defvar org-table-aligned-end-marker (make-marker)
10191 "Marker at the end of the table last aligned.
10192 Used to check if cursor still is in that table, to minimize realignment.")
10193 (defvar org-table-last-alignment nil
10194 "List of flags for flushright alignment, from the last re-alignment.
10195 This is being used to correctly align a single field after TAB or RET.")
10196 (defvar org-table-last-column-widths nil
10197 "List of max width of fields in each column.
10198 This is being used to correctly align a single field after TAB or RET.")
10199
10200 (defvar org-last-recalc-line nil)
10201 (defconst org-narrow-column-arrow "=>"
10202 "Used as display property in narrowed table columns.")
10203
10204 (defun org-table-align ()
10205 "Align the table at point by aligning all vertical bars."
10206 (interactive)
10207 (let* (
10208 ;; Limits of table
10209 (beg (org-table-begin))
10210 (end (org-table-end))
10211 ;; Current cursor position
10212 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10213 (colpos (org-table-current-column))
10214 (winstart (window-start))
10215 text lines (new "") lengths l typenums ty fields maxfields i
10216 column
10217 (indent "") cnt frac
10218 rfmt hfmt
10219 (spaces '(1 . 1))
10220 (sp1 (car spaces))
10221 (sp2 (cdr spaces))
10222 (rfmt1 (concat
10223 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
10224 (hfmt1 (concat
10225 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
10226 emptystrings xx links narrow fmax fmin f1 len c e)
10227 (untabify beg end)
10228 (remove-text-properties beg end '(org-cwidth t display t))
10229 ;; Check if we have links
10230 (goto-char beg)
10231 (setq links (re-search-forward org-bracket-link-regexp end t))
10232 ;; Make sure the link properties are right
10233 (when links (goto-char beg) (while (org-activate-bracket-links end)))
10234 ;; Check if we are narrowing any columns
10235 (goto-char beg)
10236 (setq narrow (and org-format-transports-properties-p
10237 (re-search-forward "<[0-9]+>" end t)))
10238 ;; Get the rows
10239 (setq lines (org-split-string
10240 (buffer-substring beg end) "\n"))
10241 ;; Store the indentation of the first line
10242 (if (string-match "^ *" (car lines))
10243 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
10244 ;; Mark the hlines by setting the corresponding element to nil
10245 ;; At the same time, we remove trailing space.
10246 (setq lines (mapcar (lambda (l)
10247 (if (string-match "^ *|-" l)
10248 nil
10249 (if (string-match "[ \t]+$" l)
10250 (substring l 0 (match-beginning 0))
10251 l)))
10252 lines))
10253 ;; Get the data fields by splitting the lines.
10254 (setq fields (mapcar
10255 (lambda (l)
10256 (org-split-string l " *| *"))
10257 (delq nil (copy-sequence lines))))
10258 ;; How many fields in the longest line?
10259 (condition-case nil
10260 (setq maxfields (apply 'max (mapcar 'length fields)))
10261 (error
10262 (kill-region beg end)
10263 (org-table-create org-table-default-size)
10264 (error "Empty table - created default table")))
10265 ;; A list of empty string to fill any short rows on output
10266 (setq emptystrings (make-list maxfields ""))
10267 ;; Check for special formatting.
10268 (setq i -1)
10269 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
10270 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
10271 ;; Check if there is an explicit width specified
10272 (when (and org-table-limit-column-width narrow)
10273 (setq c column fmax nil)
10274 (while c
10275 (setq e (pop c))
10276 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
10277 (setq fmax (string-to-number (match-string 1 e)) c nil)))
10278 ;; Find fields that are wider than fmax, and shorten them
10279 (when fmax
10280 (loop for xx in column do
10281 (when (and (stringp xx)
10282 (> (org-string-width xx) fmax))
10283 (org-add-props xx nil
10284 'help-echo
10285 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
10286 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
10287 (unless (> f1 1)
10288 (error "Cannot narrow field starting with wide link \"%s\""
10289 (match-string 0 xx)))
10290 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
10291 (add-text-properties (- f1 2) f1
10292 (list 'display org-narrow-column-arrow)
10293 xx)))))
10294 ;; Get the maximum width for each column
10295 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
10296 ;; Get the fraction of numbers, to decide about alignment of the column
10297 (setq cnt 0 frac 0.0)
10298 (loop for x in column do
10299 (if (equal x "")
10300 nil
10301 (setq frac ( / (+ (* frac cnt)
10302 (if (string-match org-table-number-regexp x) 1 0))
10303 (setq cnt (1+ cnt))))))
10304 (push (>= frac org-table-number-fraction) typenums))
10305 (setq lengths (nreverse lengths) typenums (nreverse typenums))
10306
10307 ;; Store the alignment of this table, for later editing of single fields
10308 (setq org-table-last-alignment typenums
10309 org-table-last-column-widths lengths)
10310
10311 ;; With invisible characters, `format' does not get the field width right
10312 ;; So we need to make these fields wide by hand.
10313 (when links
10314 (loop for i from 0 upto (1- maxfields) do
10315 (setq len (nth i lengths))
10316 (loop for j from 0 upto (1- (length fields)) do
10317 (setq c (nthcdr i (car (nthcdr j fields))))
10318 (if (and (stringp (car c))
10319 (string-match org-bracket-link-regexp (car c))
10320 (< (org-string-width (car c)) len))
10321 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
10322
10323 ;; Compute the formats needed for output of the table
10324 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
10325 (while (setq l (pop lengths))
10326 (setq ty (if (pop typenums) "" "-")) ; number types flushright
10327 (setq rfmt (concat rfmt (format rfmt1 ty l))
10328 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
10329 (setq rfmt (concat rfmt "\n")
10330 hfmt (concat (substring hfmt 0 -1) "|\n"))
10331
10332 (setq new (mapconcat
10333 (lambda (l)
10334 (if l (apply 'format rfmt
10335 (append (pop fields) emptystrings))
10336 hfmt))
10337 lines ""))
10338 ;; Replace the old one
10339 (delete-region beg end)
10340 (move-marker end nil)
10341 (move-marker org-table-aligned-begin-marker (point))
10342 (insert new)
10343 (move-marker org-table-aligned-end-marker (point))
10344 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
10345 (goto-char org-table-aligned-begin-marker)
10346 (while (org-hide-wide-columns org-table-aligned-end-marker)))
10347 ;; Try to move to the old location (approximately)
10348 (goto-line linepos)
10349 (set-window-start (selected-window) winstart 'noforce)
10350 (org-table-goto-column colpos)
10351 (setq org-table-may-need-update nil)
10352 ))
10353
10354 (defun org-string-width (s)
10355 "Compute width of string, ignoring invisible characters.
10356 This ignores character with invisibility property `org-link', and also
10357 characters with property `org-cwidth', because these will become invisible
10358 upon the next fontification round."
10359 (let (b)
10360 (when (or (eq t buffer-invisibility-spec)
10361 (assq 'org-link buffer-invisibility-spec))
10362 (while (setq b (text-property-any 0 (length s)
10363 'invisible 'org-link s))
10364 (setq s (concat (substring s 0 b)
10365 (substring s (or (next-single-property-change
10366 b 'invisible s) (length s)))))))
10367 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
10368 (setq s (concat (substring s 0 b)
10369 (substring s (or (next-single-property-change
10370 b 'org-cwidth s) (length s))))))
10371 (string-width s)))
10372
10373 (defun org-table-begin (&optional table-type)
10374 "Find the beginning of the table and return its position.
10375 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
10376 (save-excursion
10377 (if (not (re-search-backward
10378 (if table-type org-table-any-border-regexp
10379 org-table-border-regexp)
10380 nil t))
10381 (progn (goto-char (point-min)) (point))
10382 (goto-char (match-beginning 0))
10383 (beginning-of-line 2)
10384 (point))))
10385
10386 (defun org-table-end (&optional table-type)
10387 "Find the end of the table and return its position.
10388 With argument TABLE-TYPE, go to the end of a table.el-type table."
10389 (save-excursion
10390 (if (not (re-search-forward
10391 (if table-type org-table-any-border-regexp
10392 org-table-border-regexp)
10393 nil t))
10394 (goto-char (point-max))
10395 (goto-char (match-beginning 0)))
10396 (point-marker)))
10397
10398 (defun org-table-justify-field-maybe (&optional new)
10399 "Justify the current field, text to left, number to right.
10400 Optional argument NEW may specify text to replace the current field content."
10401 (cond
10402 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
10403 ((org-at-table-hline-p))
10404 ((and (not new)
10405 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
10406 (current-buffer)))
10407 (< (point) org-table-aligned-begin-marker)
10408 (>= (point) org-table-aligned-end-marker)))
10409 ;; This is not the same table, force a full re-align
10410 (setq org-table-may-need-update t))
10411 (t ;; realign the current field, based on previous full realign
10412 (let* ((pos (point)) s
10413 (col (org-table-current-column))
10414 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
10415 l f n o e)
10416 (when (> col 0)
10417 (skip-chars-backward "^|\n")
10418 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
10419 (progn
10420 (setq s (match-string 1)
10421 o (match-string 0)
10422 l (max 1 (- (match-end 0) (match-beginning 0) 3))
10423 e (not (= (match-beginning 2) (match-end 2))))
10424 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
10425 l (if e "|" (setq org-table-may-need-update t) ""))
10426 n (format f s))
10427 (if new
10428 (if (<= (length new) l) ;; FIXME: length -> str-width?
10429 (setq n (format f new))
10430 (setq n (concat new "|") org-table-may-need-update t)))
10431 (or (equal n o)
10432 (let (org-table-may-need-update)
10433 (replace-match n))))
10434 (setq org-table-may-need-update t))
10435 (goto-char pos))))))
10436
10437 (defun org-table-next-field ()
10438 "Go to the next field in the current table, creating new lines as needed.
10439 Before doing so, re-align the table if necessary."
10440 (interactive)
10441 (org-table-maybe-eval-formula)
10442 (org-table-maybe-recalculate-line)
10443 (if (and org-table-automatic-realign
10444 org-table-may-need-update)
10445 (org-table-align))
10446 (let ((end (org-table-end)))
10447 (if (org-at-table-hline-p)
10448 (end-of-line 1))
10449 (condition-case nil
10450 (progn
10451 (re-search-forward "|" end)
10452 (if (looking-at "[ \t]*$")
10453 (re-search-forward "|" end))
10454 (if (and (looking-at "-")
10455 org-table-tab-jumps-over-hlines
10456 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
10457 (goto-char (match-beginning 1)))
10458 (if (looking-at "-")
10459 (progn
10460 (beginning-of-line 0)
10461 (org-table-insert-row 'below))
10462 (if (looking-at " ") (forward-char 1))))
10463 (error
10464 (org-table-insert-row 'below)))))
10465
10466 (defun org-table-previous-field ()
10467 "Go to the previous field in the table.
10468 Before doing so, re-align the table if necessary."
10469 (interactive)
10470 (org-table-justify-field-maybe)
10471 (org-table-maybe-recalculate-line)
10472 (if (and org-table-automatic-realign
10473 org-table-may-need-update)
10474 (org-table-align))
10475 (if (org-at-table-hline-p)
10476 (end-of-line 1))
10477 (re-search-backward "|" (org-table-begin))
10478 (re-search-backward "|" (org-table-begin))
10479 (while (looking-at "|\\(-\\|[ \t]*$\\)")
10480 (re-search-backward "|" (org-table-begin)))
10481 (if (looking-at "| ?")
10482 (goto-char (match-end 0))))
10483
10484 (defun org-table-next-row ()
10485 "Go to the next row (same column) in the current table.
10486 Before doing so, re-align the table if necessary."
10487 (interactive)
10488 (org-table-maybe-eval-formula)
10489 (org-table-maybe-recalculate-line)
10490 (if (or (looking-at "[ \t]*$")
10491 (save-excursion (skip-chars-backward " \t") (bolp)))
10492 (newline)
10493 (if (and org-table-automatic-realign
10494 org-table-may-need-update)
10495 (org-table-align))
10496 (let ((col (org-table-current-column)))
10497 (beginning-of-line 2)
10498 (if (or (not (org-at-table-p))
10499 (org-at-table-hline-p))
10500 (progn
10501 (beginning-of-line 0)
10502 (org-table-insert-row 'below)))
10503 (org-table-goto-column col)
10504 (skip-chars-backward "^|\n\r")
10505 (if (looking-at " ") (forward-char 1)))))
10506
10507 (defun org-table-copy-down (n)
10508 "Copy a field down in the current column.
10509 If the field at the cursor is empty, copy into it the content of the nearest
10510 non-empty field above. With argument N, use the Nth non-empty field.
10511 If the current field is not empty, it is copied down to the next row, and
10512 the cursor is moved with it. Therefore, repeating this command causes the
10513 column to be filled row-by-row.
10514 If the variable `org-table-copy-increment' is non-nil and the field is an
10515 integer, it will be incremented while copying."
10516 (interactive "p")
10517 (let* ((colpos (org-table-current-column))
10518 (field (org-table-get-field))
10519 (non-empty (string-match "[^ \t]" field))
10520 (beg (org-table-begin))
10521 txt)
10522 (org-table-check-inside-data-field)
10523 (if non-empty
10524 (progn
10525 (setq txt (org-trim field))
10526 (org-table-next-row)
10527 (org-table-blank-field))
10528 (save-excursion
10529 (setq txt
10530 (catch 'exit
10531 (while (progn (beginning-of-line 1)
10532 (re-search-backward org-table-dataline-regexp
10533 beg t))
10534 (org-table-goto-column colpos t)
10535 (if (and (looking-at
10536 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
10537 (= (setq n (1- n)) 0))
10538 (throw 'exit (match-string 1))))))))
10539 (if txt
10540 (progn
10541 (if (and org-table-copy-increment
10542 (string-match "^[0-9]+$" txt))
10543 (setq txt (format "%d" (+ (string-to-number txt) 1))))
10544 (insert txt)
10545 (org-table-maybe-recalculate-line)
10546 (org-table-align))
10547 (error "No non-empty field found"))))
10548
10549 (defun org-table-check-inside-data-field ()
10550 "Is point inside a table data field?
10551 I.e. not on a hline or before the first or after the last column?
10552 This actually throws an error, so it aborts the current command."
10553 (if (or (not (org-at-table-p))
10554 (= (org-table-current-column) 0)
10555 (org-at-table-hline-p)
10556 (looking-at "[ \t]*$"))
10557 (error "Not in table data field")))
10558
10559 (defvar org-table-clip nil
10560 "Clipboard for table regions.")
10561
10562 (defun org-table-blank-field ()
10563 "Blank the current table field or active region."
10564 (interactive)
10565 (org-table-check-inside-data-field)
10566 (if (and (interactive-p) (org-region-active-p))
10567 (let (org-table-clip)
10568 (org-table-cut-region (region-beginning) (region-end)))
10569 (skip-chars-backward "^|")
10570 (backward-char 1)
10571 (if (looking-at "|[^|\n]+")
10572 (let* ((pos (match-beginning 0))
10573 (match (match-string 0))
10574 (len (org-string-width match)))
10575 (replace-match (concat "|" (make-string (1- len) ?\ )))
10576 (goto-char (+ 2 pos))
10577 (substring match 1)))))
10578
10579 (defun org-table-get-field (&optional n replace)
10580 "Return the value of the field in column N of current row.
10581 N defaults to current field.
10582 If REPLACE is a string, replace field with this value. The return value
10583 is always the old value."
10584 (and n (org-table-goto-column n))
10585 (skip-chars-backward "^|\n")
10586 (backward-char 1)
10587 (if (looking-at "|[^|\r\n]*")
10588 (let* ((pos (match-beginning 0))
10589 (val (buffer-substring (1+ pos) (match-end 0))))
10590 (if replace
10591 (replace-match (concat "|" replace)))
10592 (goto-char (min (point-at-eol) (+ 2 pos)))
10593 val)
10594 (forward-char 1) ""))
10595
10596 (defun org-table-current-column ()
10597 "Find out which column we are in.
10598 When called interactively, column is also displayed in echo area."
10599 (interactive)
10600 (if (interactive-p) (org-table-check-inside-data-field))
10601 (save-excursion
10602 (let ((cnt 0) (pos (point)))
10603 (beginning-of-line 1)
10604 (while (search-forward "|" pos t)
10605 (setq cnt (1+ cnt)))
10606 (if (interactive-p) (message "This is table column %d" cnt))
10607 cnt)))
10608
10609 (defun org-table-goto-column (n &optional on-delim force)
10610 "Move the cursor to the Nth column in the current table line.
10611 With optional argument ON-DELIM, stop with point before the left delimiter
10612 of the field.
10613 If there are less than N fields, just go to after the last delimiter.
10614 However, when FORCE is non-nil, create new columns if necessary."
10615 (interactive "p")
10616 (let ((pos (point-at-eol)))
10617 (beginning-of-line 1)
10618 (when (> n 0)
10619 (while (and (> (setq n (1- n)) -1)
10620 (or (search-forward "|" pos t)
10621 (and force
10622 (progn (end-of-line 1)
10623 (skip-chars-backward "^|")
10624 (insert " | "))))))
10625 ; (backward-char 2) t)))))
10626 (when (and force (not (looking-at ".*|")))
10627 (save-excursion (end-of-line 1) (insert " | ")))
10628 (if on-delim
10629 (backward-char 1)
10630 (if (looking-at " ") (forward-char 1))))))
10631
10632 (defun org-at-table-p (&optional table-type)
10633 "Return t if the cursor is inside an org-type table.
10634 If TABLE-TYPE is non-nil, also check for table.el-type tables."
10635 (if org-enable-table-editor
10636 (save-excursion
10637 (beginning-of-line 1)
10638 (looking-at (if table-type org-table-any-line-regexp
10639 org-table-line-regexp)))
10640 nil))
10641
10642 (defun org-at-table.el-p ()
10643 "Return t if and only if we are at a table.el table."
10644 (and (org-at-table-p 'any)
10645 (save-excursion
10646 (goto-char (org-table-begin 'any))
10647 (looking-at org-table1-hline-regexp))))
10648
10649 (defun org-table-recognize-table.el ()
10650 "If there is a table.el table nearby, recognize it and move into it."
10651 (if org-table-tab-recognizes-table.el
10652 (if (org-at-table.el-p)
10653 (progn
10654 (beginning-of-line 1)
10655 (if (looking-at org-table-dataline-regexp)
10656 nil
10657 (if (looking-at org-table1-hline-regexp)
10658 (progn
10659 (beginning-of-line 2)
10660 (if (looking-at org-table-any-border-regexp)
10661 (beginning-of-line -1)))))
10662 (if (re-search-forward "|" (org-table-end t) t)
10663 (progn
10664 (require 'table)
10665 (if (table--at-cell-p (point))
10666 t
10667 (message "recognizing table.el table...")
10668 (table-recognize-table)
10669 (message "recognizing table.el table...done")))
10670 (error "This should not happen..."))
10671 t)
10672 nil)
10673 nil))
10674
10675 (defun org-at-table-hline-p ()
10676 "Return t if the cursor is inside a hline in a table."
10677 (if org-enable-table-editor
10678 (save-excursion
10679 (beginning-of-line 1)
10680 (looking-at org-table-hline-regexp))
10681 nil))
10682
10683 (defun org-table-insert-column ()
10684 "Insert a new column into the table."
10685 (interactive)
10686 (if (not (org-at-table-p))
10687 (error "Not at a table"))
10688 (org-table-find-dataline)
10689 (let* ((col (max 1 (org-table-current-column)))
10690 (beg (org-table-begin))
10691 (end (org-table-end))
10692 ;; Current cursor position
10693 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10694 (colpos col))
10695 (goto-char beg)
10696 (while (< (point) end)
10697 (if (org-at-table-hline-p)
10698 nil
10699 (org-table-goto-column col t)
10700 (insert "| "))
10701 (beginning-of-line 2))
10702 (move-marker end nil)
10703 (goto-line linepos)
10704 (org-table-goto-column colpos)
10705 (org-table-align)
10706 (org-table-modify-formulas 'insert col)))
10707
10708 (defun org-table-find-dataline ()
10709 "Find a dataline in the current table, which is needed for column commands."
10710 (if (and (org-at-table-p)
10711 (not (org-at-table-hline-p)))
10712 t
10713 (let ((col (current-column))
10714 (end (org-table-end)))
10715 (move-to-column col)
10716 (while (and (< (point) end)
10717 (or (not (= (current-column) col))
10718 (org-at-table-hline-p)))
10719 (beginning-of-line 2)
10720 (move-to-column col))
10721 (if (and (org-at-table-p)
10722 (not (org-at-table-hline-p)))
10723 t
10724 (error
10725 "Please position cursor in a data line for column operations")))))
10726
10727 (defun org-table-delete-column ()
10728 "Delete a column from the table."
10729 (interactive)
10730 (if (not (org-at-table-p))
10731 (error "Not at a table"))
10732 (org-table-find-dataline)
10733 (org-table-check-inside-data-field)
10734 (let* ((col (org-table-current-column))
10735 (beg (org-table-begin))
10736 (end (org-table-end))
10737 ;; Current cursor position
10738 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10739 (colpos col))
10740 (goto-char beg)
10741 (while (< (point) end)
10742 (if (org-at-table-hline-p)
10743 nil
10744 (org-table-goto-column col t)
10745 (and (looking-at "|[^|\n]+|")
10746 (replace-match "|")))
10747 (beginning-of-line 2))
10748 (move-marker end nil)
10749 (goto-line linepos)
10750 (org-table-goto-column colpos)
10751 (org-table-align)
10752 (org-table-modify-formulas 'remove col)))
10753
10754 (defun org-table-move-column-right ()
10755 "Move column to the right."
10756 (interactive)
10757 (org-table-move-column nil))
10758 (defun org-table-move-column-left ()
10759 "Move column to the left."
10760 (interactive)
10761 (org-table-move-column 'left))
10762
10763 (defun org-table-move-column (&optional left)
10764 "Move the current column to the right. With arg LEFT, move to the left."
10765 (interactive "P")
10766 (if (not (org-at-table-p))
10767 (error "Not at a table"))
10768 (org-table-find-dataline)
10769 (org-table-check-inside-data-field)
10770 (let* ((col (org-table-current-column))
10771 (col1 (if left (1- col) col))
10772 (beg (org-table-begin))
10773 (end (org-table-end))
10774 ;; Current cursor position
10775 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10776 (colpos (if left (1- col) (1+ col))))
10777 (if (and left (= col 1))
10778 (error "Cannot move column further left"))
10779 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
10780 (error "Cannot move column further right"))
10781 (goto-char beg)
10782 (while (< (point) end)
10783 (if (org-at-table-hline-p)
10784 nil
10785 (org-table-goto-column col1 t)
10786 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
10787 (replace-match "|\\2|\\1|")))
10788 (beginning-of-line 2))
10789 (move-marker end nil)
10790 (goto-line linepos)
10791 (org-table-goto-column colpos)
10792 (org-table-align)
10793 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
10794
10795 (defun org-table-move-row-down ()
10796 "Move table row down."
10797 (interactive)
10798 (org-table-move-row nil))
10799 (defun org-table-move-row-up ()
10800 "Move table row up."
10801 (interactive)
10802 (org-table-move-row 'up))
10803
10804 (defun org-table-move-row (&optional up)
10805 "Move the current table line down. With arg UP, move it up."
10806 (interactive "P")
10807 (let ((col (current-column))
10808 (pos (point))
10809 (tonew (if up 0 2))
10810 txt)
10811 (beginning-of-line tonew)
10812 (if (not (org-at-table-p))
10813 (progn
10814 (goto-char pos)
10815 (error "Cannot move row further")))
10816 (goto-char pos)
10817 (beginning-of-line 1)
10818 (setq pos (point))
10819 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
10820 (delete-region (point) (1+ (point-at-eol)))
10821 (beginning-of-line tonew)
10822 (insert txt)
10823 (beginning-of-line 0)
10824 (move-to-column col)))
10825
10826 (defun org-table-insert-row (&optional arg)
10827 "Insert a new row above the current line into the table.
10828 With prefix ARG, insert below the current line."
10829 (interactive "P")
10830 (if (not (org-at-table-p))
10831 (error "Not at a table"))
10832 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
10833 (new (org-table-clean-line line)))
10834 ;; Fix the first field if necessary
10835 (if (string-match "^[ \t]*| *[#$] *|" line)
10836 (setq new (replace-match (match-string 0 line) t t new)))
10837 (beginning-of-line (if arg 2 1))
10838 (let (org-table-may-need-update) (insert-before-markers new "\n"))
10839 (beginning-of-line 0)
10840 (re-search-forward "| ?" (point-at-eol) t)
10841 (and org-table-may-need-update (org-table-align))))
10842
10843 (defun org-table-insert-hline (&optional arg)
10844 "Insert a horizontal-line below the current line into the table.
10845 With prefix ARG, insert above the current line."
10846 (interactive "P")
10847 (if (not (org-at-table-p))
10848 (error "Not at a table"))
10849 (let ((line (org-table-clean-line
10850 (buffer-substring (point-at-bol) (point-at-eol))))
10851 (col (current-column)))
10852 (while (string-match "|\\( +\\)|" line)
10853 (setq line (replace-match
10854 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
10855 ?-) "|") t t line)))
10856 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
10857 (beginning-of-line (if arg 1 2))
10858 (insert line "\n")
10859 (beginning-of-line (if arg 1 -1))
10860 (move-to-column col)))
10861
10862 (defun org-table-clean-line (s)
10863 "Convert a table line S into a string with only \"|\" and space.
10864 In particular, this does handle wide and invisible characters."
10865 (if (string-match "^[ \t]*|-" s)
10866 ;; It's a hline, just map the characters
10867 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
10868 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
10869 (setq s (replace-match
10870 (concat "|" (make-string (org-string-width (match-string 1 s))
10871 ?\ ) "|")
10872 t t s)))
10873 s))
10874
10875 (defun org-table-kill-row ()
10876 "Delete the current row or horizontal line from the table."
10877 (interactive)
10878 (if (not (org-at-table-p))
10879 (error "Not at a table"))
10880 (let ((col (current-column)))
10881 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
10882 (if (not (org-at-table-p)) (beginning-of-line 0))
10883 (move-to-column col)))
10884
10885 (defun org-table-sort-lines (beg end numericp)
10886 "Sort table lines in region.
10887 Point and mark define the first and last line to include. Both point and
10888 mark should be in the column that is used for sorting. For example, to
10889 sort according to column 3, put the mark in the first line to sort, in
10890 table column 3. Put point into the last line to be included in the sorting,
10891 also in table column 3. The command will prompt for the sorting method
10892 \(n for numerical, a for alphanumeric)."
10893 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
10894 (setq numericp (string-match "[nN]" numericp))
10895 (org-table-align) ;; Just to be safe
10896 (let* (bcol ecol cmp column lns)
10897 (goto-char beg)
10898 (org-table-check-inside-data-field)
10899 (setq column (org-table-current-column)
10900 beg (move-marker (make-marker) (point-at-bol)))
10901 (goto-char end)
10902 (org-table-check-inside-data-field)
10903 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
10904 (untabify beg end)
10905 (goto-char beg)
10906 (org-table-goto-column column)
10907 (skip-chars-backward "^|")
10908 (setq bcol (current-column))
10909 (org-table-goto-column (1+ column))
10910 (skip-chars-backward "^|")
10911 (setq ecol (1- (current-column)))
10912 (setq cmp (if numericp
10913 (lambda (a b) (< (car a) (car b)))
10914 (lambda (a b) (string< (car a) (car b)))))
10915 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
10916 (org-split-string (buffer-substring beg end) "\n")))
10917 (if numericp
10918 (setq lns (mapcar (lambda(x)
10919 (cons (string-to-number (car x)) (cdr x)))
10920 lns)))
10921 (delete-region beg end)
10922 (move-marker beg nil)
10923 (move-marker end nil)
10924 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
10925 (message "%d lines sorted %s based on column %d"
10926 (length lns)
10927 (if numericp "numerically" "alphabetically") column)))
10928
10929 (defun org-table-cut-region (beg end)
10930 "Copy region in table to the clipboard and blank all relevant fields."
10931 (interactive "r")
10932 (org-table-copy-region beg end 'cut))
10933
10934 (defun org-table-copy-region (beg end &optional cut)
10935 "Copy rectangular region in table to clipboard.
10936 A special clipboard is used which can only be accessed
10937 with `org-table-paste-rectangle'."
10938 (interactive "rP")
10939 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
10940 region cols
10941 (rpl (if cut " " nil)))
10942 (goto-char beg)
10943 (org-table-check-inside-data-field)
10944 (setq l01 (count-lines (point-min) (point))
10945 c01 (org-table-current-column))
10946 (goto-char end)
10947 (org-table-check-inside-data-field)
10948 (setq l02 (count-lines (point-min) (point))
10949 c02 (org-table-current-column))
10950 (setq l1 (min l01 l02) l2 (max l01 l02)
10951 c1 (min c01 c02) c2 (max c01 c02))
10952 (catch 'exit
10953 (while t
10954 (catch 'nextline
10955 (if (> l1 l2) (throw 'exit t))
10956 (goto-line l1)
10957 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
10958 (setq cols nil ic1 c1 ic2 c2)
10959 (while (< ic1 (1+ ic2))
10960 (push (org-table-get-field ic1 rpl) cols)
10961 (setq ic1 (1+ ic1)))
10962 (push (nreverse cols) region)
10963 (setq l1 (1+ l1)))))
10964 (setq org-table-clip (nreverse region))
10965 (if cut (org-table-align))
10966 org-table-clip))
10967
10968 (defun org-table-paste-rectangle ()
10969 "Paste a rectangular region into a table.
10970 The upper right corner ends up in the current field. All involved fields
10971 will be overwritten. If the rectangle does not fit into the present table,
10972 the table is enlarged as needed. The process ignores horizontal separator
10973 lines."
10974 (interactive)
10975 (unless (and org-table-clip (listp org-table-clip))
10976 (error "First cut/copy a region to paste!"))
10977 (org-table-check-inside-data-field)
10978 (let* ((clip org-table-clip)
10979 (line (count-lines (point-min) (point)))
10980 (col (org-table-current-column))
10981 (org-enable-table-editor t)
10982 (org-table-automatic-realign nil)
10983 c cols field)
10984 (while (setq cols (pop clip))
10985 (while (org-at-table-hline-p) (beginning-of-line 2))
10986 (if (not (org-at-table-p))
10987 (progn (end-of-line 0) (org-table-next-field)))
10988 (setq c col)
10989 (while (setq field (pop cols))
10990 (org-table-goto-column c nil 'force)
10991 (org-table-get-field nil field)
10992 (setq c (1+ c)))
10993 (beginning-of-line 2))
10994 (goto-line line)
10995 (org-table-goto-column col)
10996 (org-table-align)))
10997
10998 (defun org-table-convert ()
10999 "Convert from `org-mode' table to table.el and back.
11000 Obviously, this only works within limits. When an Org-mode table is
11001 converted to table.el, all horizontal separator lines get lost, because
11002 table.el uses these as cell boundaries and has no notion of horizontal lines.
11003 A table.el table can be converted to an Org-mode table only if it does not
11004 do row or column spanning. Multiline cells will become multiple cells.
11005 Beware, Org-mode does not test if the table can be successfully converted - it
11006 blindly applies a recipe that works for simple tables."
11007 (interactive)
11008 (require 'table)
11009 (if (org-at-table.el-p)
11010 ;; convert to Org-mode table
11011 (let ((beg (move-marker (make-marker) (org-table-begin t)))
11012 (end (move-marker (make-marker) (org-table-end t))))
11013 (table-unrecognize-region beg end)
11014 (goto-char beg)
11015 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
11016 (replace-match ""))
11017 (goto-char beg))
11018 (if (org-at-table-p)
11019 ;; convert to table.el table
11020 (let ((beg (move-marker (make-marker) (org-table-begin)))
11021 (end (move-marker (make-marker) (org-table-end))))
11022 ;; first, get rid of all horizontal lines
11023 (goto-char beg)
11024 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
11025 (replace-match ""))
11026 ;; insert a hline before first
11027 (goto-char beg)
11028 (org-table-insert-hline 'above)
11029 (beginning-of-line -1)
11030 ;; insert a hline after each line
11031 (while (progn (beginning-of-line 3) (< (point) end))
11032 (org-table-insert-hline))
11033 (goto-char beg)
11034 (setq end (move-marker end (org-table-end)))
11035 ;; replace "+" at beginning and ending of hlines
11036 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
11037 (replace-match "\\1+-"))
11038 (goto-char beg)
11039 (while (re-search-forward "-|[ \t]*$" end t)
11040 (replace-match "-+"))
11041 (goto-char beg)))))
11042
11043 (defun org-table-wrap-region (arg)
11044 "Wrap several fields in a column like a paragraph.
11045 This is useful if you'd like to spread the contents of a field over several
11046 lines, in order to keep the table compact.
11047
11048 If there is an active region, and both point and mark are in the same column,
11049 the text in the column is wrapped to minimum width for the given number of
11050 lines. Generally, this makes the table more compact. A prefix ARG may be
11051 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
11052 formats the selected text to two lines. If the region was longer than two
11053 lines, the remaining lines remain empty. A negative prefix argument reduces
11054 the current number of lines by that amount. The wrapped text is pasted back
11055 into the table. If you formatted it to more lines than it was before, fields
11056 further down in the table get overwritten - so you might need to make space in
11057 the table first.
11058
11059 If there is no region, the current field is split at the cursor position and
11060 the text fragment to the right of the cursor is prepended to the field one
11061 line down.
11062
11063 If there is no region, but you specify a prefix ARG, the current field gets
11064 blank, and the content is appended to the field above."
11065 (interactive "P")
11066 (org-table-check-inside-data-field)
11067 (if (org-region-active-p)
11068 ;; There is a region: fill as a paragraph
11069 (let ((beg (region-beginning))
11070 nlines)
11071 (org-table-cut-region (region-beginning) (region-end))
11072 (if (> (length (car org-table-clip)) 1)
11073 (error "Region must be limited to single column"))
11074 (setq nlines (if arg
11075 (if (< arg 1)
11076 (+ (length org-table-clip) arg)
11077 arg)
11078 (length org-table-clip)))
11079 (setq org-table-clip
11080 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
11081 nil nlines)))
11082 (goto-char beg)
11083 (org-table-paste-rectangle))
11084 ;; No region, split the current field at point
11085 (if arg
11086 ;; combine with field above
11087 (let ((s (org-table-blank-field))
11088 (col (org-table-current-column)))
11089 (beginning-of-line 0)
11090 (while (org-at-table-hline-p) (beginning-of-line 0))
11091 (org-table-goto-column col)
11092 (skip-chars-forward "^|")
11093 (skip-chars-backward " ")
11094 (insert " " (org-trim s))
11095 (org-table-align))
11096 ;; split field
11097 (when (looking-at "\\([^|]+\\)+|")
11098 (let ((s (match-string 1)))
11099 (replace-match " |")
11100 (goto-char (match-beginning 0))
11101 (org-table-next-row)
11102 (insert (org-trim s) " ")
11103 (org-table-align))))))
11104
11105 (defvar org-field-marker nil)
11106
11107 (defun org-table-edit-field (arg)
11108 "Edit table field in a different window.
11109 This is mainly useful for fields that contain hidden parts.
11110 When called with a \\[universal-argument] prefix, just make the full field visible so that
11111 it can be edited in place."
11112 (interactive "P")
11113 (if arg
11114 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
11115 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
11116 (remove-text-properties b e '(org-cwidth t invisible t
11117 display t intangible t))
11118 (if (and (boundp 'font-lock-mode) font-lock-mode)
11119 (font-lock-fontify-block)))
11120 (let ((pos (move-marker (make-marker) (point)))
11121 (field (org-table-get-field))
11122 (cw (current-window-configuration))
11123 p)
11124 (switch-to-buffer-other-window "*Org tmp*")
11125 (erase-buffer)
11126 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
11127 (org-mode)
11128 (goto-char (setq p (point-max)))
11129 (insert (org-trim field))
11130 (remove-text-properties p (point-max)
11131 '(invisible t org-cwidth t display t
11132 intangible t))
11133 (goto-char p)
11134 (set (make-local-variable 'org-finish-function)
11135 'org-table-finish-edit-field)
11136 (set (make-local-variable 'org-window-configuration) cw)
11137 (set (make-local-variable 'org-field-marker) pos)
11138 (message "Edit and finish with C-c C-c"))))
11139
11140 (defun org-table-finish-edit-field ()
11141 "Finish editing a table data field.
11142 Remove all newline characters, insert the result into the table, realign
11143 the table and kill the editing buffer."
11144 (let ((pos org-field-marker)
11145 (cw org-window-configuration)
11146 (cb (current-buffer))
11147 text)
11148 (goto-char (point-min))
11149 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
11150 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
11151 (replace-match " "))
11152 (setq text (org-trim (buffer-string)))
11153 (set-window-configuration cw)
11154 (kill-buffer cb)
11155 (select-window (get-buffer-window (marker-buffer pos)))
11156 (goto-char pos)
11157 (move-marker pos nil)
11158 (org-table-check-inside-data-field)
11159 (org-table-get-field nil text)
11160 (org-table-align)
11161 (message "New field value inserted")))
11162
11163 (defun org-trim (s)
11164 "Remove whitespace at beginning and end of string."
11165 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
11166 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
11167 s)
11168
11169 (defun org-wrap (string &optional width lines)
11170 "Wrap string to either a number of lines, or a width in characters.
11171 If WIDTH is non-nil, the string is wrapped to that width, however many lines
11172 that costs. If there is a word longer than WIDTH, the text is actually
11173 wrapped to the length of that word.
11174 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
11175 many lines, whatever width that takes.
11176 The return value is a list of lines, without newlines at the end."
11177 (let* ((words (org-split-string string "[ \t\n]+"))
11178 (maxword (apply 'max (mapcar 'org-string-width words)))
11179 w ll)
11180 (cond (width
11181 (org-do-wrap words (max maxword width)))
11182 (lines
11183 (setq w maxword)
11184 (setq ll (org-do-wrap words maxword))
11185 (if (<= (length ll) lines)
11186 ll
11187 (setq ll words)
11188 (while (> (length ll) lines)
11189 (setq w (1+ w))
11190 (setq ll (org-do-wrap words w)))
11191 ll))
11192 (t (error "Cannot wrap this")))))
11193
11194
11195 (defun org-do-wrap (words width)
11196 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
11197 (let (lines line)
11198 (while words
11199 (setq line (pop words))
11200 (while (and words (< (+ (length line) (length (car words))) width))
11201 (setq line (concat line " " (pop words))))
11202 (setq lines (push line lines)))
11203 (nreverse lines)))
11204
11205 (defun org-split-string (string &optional separators)
11206 "Splits STRING into substrings at SEPARATORS.
11207 No empty strings are returned if there are matches at the beginning
11208 and end of string."
11209 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
11210 (start 0)
11211 notfirst
11212 (list nil))
11213 (while (and (string-match rexp string
11214 (if (and notfirst
11215 (= start (match-beginning 0))
11216 (< start (length string)))
11217 (1+ start) start))
11218 (< (match-beginning 0) (length string)))
11219 (setq notfirst t)
11220 (or (eq (match-beginning 0) 0)
11221 (and (eq (match-beginning 0) (match-end 0))
11222 (eq (match-beginning 0) start))
11223 (setq list
11224 (cons (substring string start (match-beginning 0))
11225 list)))
11226 (setq start (match-end 0)))
11227 (or (eq start (length string))
11228 (setq list
11229 (cons (substring string start)
11230 list)))
11231 (nreverse list)))
11232
11233 (defun org-table-map-tables (function)
11234 "Apply FUNCTION to the start of all tables in the buffer."
11235 (save-excursion
11236 (save-restriction
11237 (widen)
11238 (goto-char (point-min))
11239 (while (re-search-forward org-table-any-line-regexp nil t)
11240 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
11241 (beginning-of-line 1)
11242 (if (looking-at org-table-line-regexp)
11243 (save-excursion (funcall function)))
11244 (re-search-forward org-table-any-border-regexp nil 1))))
11245 (message "Mapping tables: done"))
11246
11247 (defun org-table-sum (&optional beg end nlast)
11248 "Sum numbers in region of current table column.
11249 The result will be displayed in the echo area, and will be available
11250 as kill to be inserted with \\[yank].
11251
11252 If there is an active region, it is interpreted as a rectangle and all
11253 numbers in that rectangle will be summed. If there is no active
11254 region and point is located in a table column, sum all numbers in that
11255 column.
11256
11257 If at least one number looks like a time HH:MM or HH:MM:SS, all other
11258 numbers are assumed to be times as well (in decimal hours) and the
11259 numbers are added as such.
11260
11261 If NLAST is a number, only the NLAST fields will actually be summed."
11262 (interactive)
11263 (save-excursion
11264 (let (col (timecnt 0) diff h m s org-table-clip)
11265 (cond
11266 ((and beg end)) ; beg and end given explicitly
11267 ((org-region-active-p)
11268 (setq beg (region-beginning) end (region-end)))
11269 (t
11270 (setq col (org-table-current-column))
11271 (goto-char (org-table-begin))
11272 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
11273 (error "No table data"))
11274 (org-table-goto-column col)
11275 ;not needed? (skip-chars-backward "^|")
11276 (setq beg (point))
11277 (goto-char (org-table-end))
11278 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
11279 (error "No table data"))
11280 (org-table-goto-column col)
11281 ;not needed? (skip-chars-forward "^|")
11282 (setq end (point))))
11283 (let* ((items (apply 'append (org-table-copy-region beg end)))
11284 (items1 (cond ((not nlast) items)
11285 ((>= nlast (length items)) items)
11286 (t (setq items (reverse items))
11287 (setcdr (nthcdr (1- nlast) items) nil)
11288 (nreverse items))))
11289 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
11290 items1)))
11291 (res (apply '+ numbers))
11292 (sres (if (= timecnt 0)
11293 (format "%g" res)
11294 (setq diff (* 3600 res)
11295 h (floor (/ diff 3600)) diff (mod diff 3600)
11296 m (floor (/ diff 60)) diff (mod diff 60)
11297 s diff)
11298 (format "%d:%02d:%02d" h m s))))
11299 (kill-new sres)
11300 (if (interactive-p)
11301 (message "%s"
11302 (substitute-command-keys
11303 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
11304 (length numbers) sres))))
11305 sres))))
11306
11307 (defun org-table-get-number-for-summing (s)
11308 (let (n)
11309 (if (string-match "^ *|? *" s)
11310 (setq s (replace-match "" nil nil s)))
11311 (if (string-match " *|? *$" s)
11312 (setq s (replace-match "" nil nil s)))
11313 (setq n (string-to-number s))
11314 (cond
11315 ((and (string-match "0" s)
11316 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
11317 ((string-match "\\`[ \t]+\\'" s) nil)
11318 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
11319 (let ((h (string-to-number (or (match-string 1 s) "0")))
11320 (m (string-to-number (or (match-string 2 s) "0")))
11321 (s (string-to-number (or (match-string 4 s) "0"))))
11322 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
11323 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
11324 ((equal n 0) nil)
11325 (t n))))
11326
11327 (defun org-table-get-vertical-vector (desc &optional tbeg col)
11328 "Get a calc vector from a column, accorting to descriptor DESC.
11329 Optional arguments TBEG and COL can give the beginning of the table and
11330 the current column, to avoid unnecessary parsing."
11331 (save-excursion
11332 (or tbeg (setq tbeg (org-table-begin)))
11333 (or col (setq col (org-table-current-column)))
11334 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
11335 (cond
11336 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
11337 (setq n1 (- (match-end 1) (match-beginning 1)))
11338 (if (match-beginning 3)
11339 (setq n2 (- (match-end 2) (match-beginning 3))))
11340 (setq n (if n2 (max n1 n2) n1))
11341 (setq n1 (if n2 (min n1 n2)))
11342 (setq nn n)
11343 (while (and (> nn 0)
11344 (re-search-backward org-table-hline-regexp tbeg t))
11345 (push (org-current-line) hline-list)
11346 (setq nn (1- nn)))
11347 (setq hline-list (nreverse hline-list))
11348 (goto-line (nth (1- n) hline-list))
11349 (when (re-search-forward org-table-dataline-regexp)
11350 (org-table-goto-column col)
11351 (setq beg (point)))
11352 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
11353 (when (re-search-backward org-table-dataline-regexp)
11354 (org-table-goto-column col)
11355 (setq end (point)))
11356 (setq l (apply 'append (org-table-copy-region beg end)))
11357 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
11358 (if (equal x "") "0" x))
11359 l ",") "]"))
11360 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
11361 (setq n1 (string-to-number (match-string 1 desc))
11362 n2 (string-to-number (match-string 2 desc)))
11363 (beginning-of-line 1)
11364 (save-excursion
11365 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
11366 (org-table-goto-column col)
11367 (setq beg (point))))
11368 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
11369 (org-table-goto-column col)
11370 (setq end (point)))
11371 (setq l (apply 'append (org-table-copy-region beg end)))
11372 (concat "[" (mapconcat
11373 (lambda (x) (setq x (org-trim x))
11374 (if (equal x "") "0" x))
11375 l ",") "]"))
11376 ((string-match "\\([0-9]+\\)" desc)
11377 (beginning-of-line 1)
11378 (when (re-search-backward org-table-dataline-regexp tbeg t
11379 (string-to-number (match-string 0 desc)))
11380 (org-table-goto-column col)
11381 (org-trim (org-table-get-field))))))))
11382
11383 (defvar org-table-formula-history nil)
11384
11385 (defvar org-table-column-names nil
11386 "Alist with column names, derived from the `!' line.")
11387 (defvar org-table-column-name-regexp nil
11388 "Regular expression matching the current column names.")
11389 (defvar org-table-local-parameters nil
11390 "Alist with parameter names, derived from the `$' line.")
11391 (defvar org-table-named-field-locations nil
11392 "Alist with locations of named fields.")
11393
11394 (defun org-table-get-formula (&optional equation named)
11395 "Read a formula from the minibuffer, offer stored formula as default."
11396 (let* ((name (car (rassoc (list (org-current-line)
11397 (org-table-current-column))
11398 org-table-named-field-locations)))
11399 (scol (if named
11400 (if name name
11401 (error "Not in a named field"))
11402 (int-to-string (org-table-current-column))))
11403 (dummy (and name (not named)
11404 (not (y-or-n-p "Replace named-field formula with column equation? " ))
11405 (error "Abort")))
11406 (org-table-may-need-update nil)
11407 (stored-list (org-table-get-stored-formulas))
11408 (stored (cdr (assoc scol stored-list)))
11409 (eq (cond
11410 ((and stored equation (string-match "^ *=? *$" equation))
11411 stored)
11412 ((stringp equation)
11413 equation)
11414 (t (read-string
11415 (format "%s formula $%s=" (if named "Field" "Column") scol)
11416 (or stored "") 'org-table-formula-history
11417 ;stored
11418 ))))
11419 mustsave)
11420 (when (not (string-match "\\S-" eq))
11421 ;; remove formula
11422 (setq stored-list (delq (assoc scol stored-list) stored-list))
11423 (org-table-store-formulas stored-list)
11424 (error "Formula removed"))
11425 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
11426 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
11427 (if (and name (not named))
11428 ;; We set the column equation, delete the named one.
11429 (setq stored-list (delq (assoc name stored-list) stored-list)
11430 mustsave t))
11431 (if stored
11432 (setcdr (assoc scol stored-list) eq)
11433 (setq stored-list (cons (cons scol eq) stored-list)))
11434 (if (or mustsave (not (equal stored eq)))
11435 (org-table-store-formulas stored-list))
11436 eq))
11437
11438 (defun org-table-store-formulas (alist)
11439 "Store the list of formulas below the current table."
11440 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
11441 (save-excursion
11442 (goto-char (org-table-end))
11443 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
11444 (delete-region (point) (match-end 0)))
11445 (insert "#+TBLFM: "
11446 (mapconcat (lambda (x)
11447 (concat "$" (car x) "=" (cdr x)))
11448 alist "::")
11449 "\n")))
11450
11451 (defun org-table-get-stored-formulas ()
11452 "Return an alist with the stored formulas directly after current table."
11453 (interactive)
11454 (let (scol eq eq-alist strings string seen)
11455 (save-excursion
11456 (goto-char (org-table-end))
11457 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
11458 (setq strings (org-split-string (match-string 2) " *:: *"))
11459 (while (setq string (pop strings))
11460 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
11461 (setq scol (match-string 1 string)
11462 eq (match-string 2 string)
11463 eq-alist (cons (cons scol eq) eq-alist))
11464 (if (member scol seen)
11465 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
11466 (push scol seen))))))
11467 (nreverse eq-alist)))
11468
11469 (defun org-table-modify-formulas (action &rest columns)
11470 "Modify the formulas stored below the current table.
11471 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
11472 expected, for the other actions only a single column number is needed."
11473 (let ((list (org-table-get-stored-formulas))
11474 (nmax (length (org-split-string
11475 (buffer-substring (point-at-bol) (point-at-eol))
11476 "|")))
11477 col col1 col2 scol si sc1 sc2)
11478 (cond
11479 ((null list)) ; No action needed if there are no stored formulas
11480 ((eq action 'remove)
11481 (setq col (car columns)
11482 scol (int-to-string col))
11483 (org-table-replace-in-formulas list scol "INVALID")
11484 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
11485 (loop for i from (1+ col) upto nmax by 1 do
11486 (setq si (int-to-string i))
11487 (org-table-replace-in-formulas list si (int-to-string (1- i)))
11488 (if (assoc si list) (setcar (assoc si list)
11489 (int-to-string (1- i))))))
11490 ((eq action 'insert)
11491 (setq col (car columns))
11492 (loop for i from nmax downto col by 1 do
11493 (setq si (int-to-string i))
11494 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
11495 (if (assoc si list) (setcar (assoc si list)
11496 (int-to-string (1+ i))))))
11497 ((eq action 'swap)
11498 (setq col1 (car columns) col2 (nth 1 columns)
11499 sc1 (int-to-string col1) sc2 (int-to-string col2))
11500 ;; Hopefully, ZqZtZ will never be a name in a table
11501 (org-table-replace-in-formulas list sc1 "ZqZtZ")
11502 (org-table-replace-in-formulas list sc2 sc1)
11503 (org-table-replace-in-formulas list "ZqZtZ" sc2)
11504 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
11505 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
11506 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
11507 (t (error "Invalid action in `org-table-modify-formulas'")))
11508 (if list (org-table-store-formulas list))))
11509
11510 (defun org-table-replace-in-formulas (list s1 s2)
11511 (let (elt re s)
11512 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
11513 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
11514 re (concat (regexp-quote s1) "\\>"))
11515 (while (setq elt (pop list))
11516 (setq s (cdr elt))
11517 (while (string-match re s)
11518 (setq s (replace-match s2 t t s)))
11519 (setcdr elt s))))
11520
11521 (defun org-table-get-specials ()
11522 "Get the column names and local parameters for this table."
11523 (save-excursion
11524 (let ((beg (org-table-begin)) (end (org-table-end))
11525 names name fields fields1 field cnt c v line col)
11526 (setq org-table-column-names nil
11527 org-table-local-parameters nil
11528 org-table-named-field-locations nil)
11529 (goto-char beg)
11530 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
11531 (setq names (org-split-string (match-string 1) " *| *")
11532 cnt 1)
11533 (while (setq name (pop names))
11534 (setq cnt (1+ cnt))
11535 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
11536 (push (cons name (int-to-string cnt)) org-table-column-names))))
11537 (setq org-table-column-names (nreverse org-table-column-names))
11538 (setq org-table-column-name-regexp
11539 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
11540 (goto-char beg)
11541 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
11542 (setq fields (org-split-string (match-string 1) " *| *"))
11543 (while (setq field (pop fields))
11544 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
11545 (push (cons (match-string 1 field) (match-string 2 field))
11546 org-table-local-parameters))))
11547 (goto-char beg)
11548 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
11549 (setq c (match-string 1)
11550 fields (org-split-string (match-string 2) " *| *"))
11551 (save-excursion
11552 (beginning-of-line (if (equal c "_") 2 0))
11553 (setq line (org-current-line) col 1)
11554 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
11555 (setq fields1 (org-split-string (match-string 1) " *| *"))))
11556 (while (and fields1 (setq field (pop fields)))
11557 (setq v (pop fields1) col (1+ col))
11558 (when (and (stringp field) (stringp v)
11559 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
11560 (push (cons field v) org-table-local-parameters)
11561 (push (list field line col) org-table-named-field-locations)))))))
11562
11563 (defun org-this-word ()
11564 ;; Get the current word
11565 (save-excursion
11566 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
11567 (end (progn (skip-chars-forward "^ \t\n") (point))))
11568 (buffer-substring-no-properties beg end))))
11569
11570 (defun org-table-maybe-eval-formula ()
11571 "Check if the current field starts with \"=\" or \":=\".
11572 If yes, store the formula and apply it."
11573 ;; We already know we are in a table. Get field will only return a formula
11574 ;; when appropriate. It might return a separator line, but no problem.
11575 (when org-table-formula-evaluate-inline
11576 (let* ((field (org-trim (or (org-table-get-field) "")))
11577 named eq)
11578 (when (string-match "^:?=\\(.*\\)" field)
11579 (setq named (equal (string-to-char field) ?:)
11580 eq (match-string 1 field))
11581 (if (fboundp 'calc-eval)
11582 (org-table-eval-formula (if named '(4) nil) eq))))))
11583
11584 (defvar org-recalc-commands nil
11585 "List of commands triggering the recalculation of a line.
11586 Will be filled automatically during use.")
11587
11588 (defvar org-recalc-marks
11589 '((" " . "Unmarked: no special line, no automatic recalculation")
11590 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
11591 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
11592 ("!" . "Column name definition line. Reference in formula as $name.")
11593 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
11594 ("_" . "Names for values in row below this one.")
11595 ("^" . "Names for values in row above this one.")))
11596
11597 (defun org-table-rotate-recalc-marks (&optional newchar)
11598 "Rotate the recalculation mark in the first column.
11599 If in any row, the first field is not consistent with a mark,
11600 insert a new column for the markers.
11601 When there is an active region, change all the lines in the region,
11602 after prompting for the marking character.
11603 After each change, a message will be displayed indicating the meaning
11604 of the new mark."
11605 (interactive)
11606 (unless (org-at-table-p) (error "Not at a table"))
11607 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
11608 (beg (org-table-begin))
11609 (end (org-table-end))
11610 (l (org-current-line))
11611 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
11612 (l2 (if (org-region-active-p) (org-current-line (region-end))))
11613 (have-col
11614 (save-excursion
11615 (goto-char beg)
11616 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
11617 (col (org-table-current-column))
11618 (forcenew (car (assoc newchar org-recalc-marks)))
11619 epos new)
11620 (when l1
11621 (message "Change region to what mark? Type # * ! $ or SPC: ")
11622 (setq newchar (char-to-string (read-char-exclusive))
11623 forcenew (car (assoc newchar org-recalc-marks))))
11624 (if (and newchar (not forcenew))
11625 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
11626 newchar))
11627 (if l1 (goto-line l1))
11628 (save-excursion
11629 (beginning-of-line 1)
11630 (unless (looking-at org-table-dataline-regexp)
11631 (error "Not at a table data line")))
11632 (unless have-col
11633 (org-table-goto-column 1)
11634 (org-table-insert-column)
11635 (org-table-goto-column (1+ col)))
11636 (setq epos (point-at-eol))
11637 (save-excursion
11638 (beginning-of-line 1)
11639 (org-table-get-field
11640 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
11641 (concat " "
11642 (setq new (or forcenew
11643 (cadr (member (match-string 1) marks))))
11644 " ")
11645 " # ")))
11646 (if (and l1 l2)
11647 (progn
11648 (goto-line l1)
11649 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
11650 (and (looking-at org-table-dataline-regexp)
11651 (org-table-get-field 1 (concat " " new " "))))
11652 (goto-line l1)))
11653 (if (not (= epos (point-at-eol))) (org-table-align))
11654 (goto-line l)
11655 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
11656
11657 (defun org-table-maybe-recalculate-line ()
11658 "Recompute the current line if marked for it, and if we haven't just done it."
11659 (interactive)
11660 (and org-table-allow-automatic-line-recalculation
11661 (not (and (memq last-command org-recalc-commands)
11662 (equal org-last-recalc-line (org-current-line))))
11663 (save-excursion (beginning-of-line 1)
11664 (looking-at org-table-auto-recalculate-regexp))
11665 (fboundp 'calc-eval)
11666 (org-table-recalculate) t))
11667
11668 (defvar org-table-formula-debug nil
11669 "Non-nil means, debug table formulas.
11670 When nil, simply write \"#ERROR\" in corrupted fields.")
11671
11672 (defvar modes)
11673 (defsubst org-set-calc-mode (var &optional value)
11674 (if (stringp var)
11675 (setq var (assoc var '(("D" calc-angle-mode deg)
11676 ("R" calc-angle-mode rad)
11677 ("F" calc-prefer-frac t)
11678 ("S" calc-symbolic-mode t)))
11679 value (nth 2 var) var (nth 1 var)))
11680 (if (memq var modes)
11681 (setcar (cdr (memq var modes)) value)
11682 (cons var (cons value modes)))
11683 modes)
11684
11685 (defun org-table-eval-formula (&optional arg equation
11686 suppress-align suppress-const
11687 suppress-store)
11688 "Replace the table field value at the cursor by the result of a calculation.
11689
11690 This function makes use of Dave Gillespie's Calc package, in my view the
11691 most exciting program ever written for GNU Emacs. So you need to have Calc
11692 installed in order to use this function.
11693
11694 In a table, this command replaces the value in the current field with the
11695 result of a formula. It also installs the formula as the \"current\" column
11696 formula, by storing it in a special line below the table. When called
11697 with a `C-u' prefix, the current field must ba a named field, and the
11698 formula is installed as valid in only this specific field.
11699
11700 When called, the command first prompts for a formula, which is read in
11701 the minibuffer. Previously entered formulas are available through the
11702 history list, and the last used formula is offered as a default.
11703 These stored formulas are adapted correctly when moving, inserting, or
11704 deleting columns with the corresponding commands.
11705
11706 The formula can be any algebraic expression understood by the Calc package.
11707 For details, see the Org-mode manual.
11708
11709 This function can also be called from Lisp programs and offers
11710 additional arguments: EQUATION can be the formula to apply. If this
11711 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
11712 used to speed-up recursive calls by by-passing unnecessary aligns.
11713 SUPPRESS-CONST suppresses the interpretation of constants in the
11714 formula, assuming that this has been done already outside the function.
11715 SUPPRESS-STORE means the formula should not be stored, either because
11716 it is already stored, or because it is a modified equation that should
11717 not overwrite the stored one."
11718 (interactive "P")
11719 (require 'calc)
11720 (org-table-check-inside-data-field)
11721 (org-table-get-specials)
11722 (let* (fields
11723 (ndown (if (integerp arg) arg 1))
11724 (org-table-automatic-realign nil)
11725 (case-fold-search nil)
11726 (down (> ndown 1))
11727 (formula (if (and equation suppress-store)
11728 equation
11729 (org-table-get-formula equation (equal arg '(4)))))
11730 (n0 (org-table-current-column))
11731 (modes (copy-sequence org-calc-default-modes))
11732 n form fmt x ev orig c lispp)
11733 ;; Parse the format string. Since we have a lot of modes, this is
11734 ;; a lot of work. However, I think calc still uses most of the time.
11735 (if (string-match ";" formula)
11736 (let ((tmp (org-split-string formula ";")))
11737 (setq formula (car tmp)
11738 fmt (concat (cdr (assoc "%" org-table-local-parameters))
11739 (nth 1 tmp)))
11740 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
11741 (setq c (string-to-char (match-string 1 fmt))
11742 n (string-to-number (or (match-string 1 fmt) "")))
11743 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
11744 (setq modes (org-set-calc-mode
11745 'calc-float-format
11746 (list (cdr (assoc c '((?n . float) (?f . fix)
11747 (?s . sci) (?e . eng))))
11748 n))))
11749 (setq fmt (replace-match "" t t fmt)))
11750 (while (string-match "[DRFS]" fmt)
11751 (setq modes (org-set-calc-mode (match-string 0 fmt)))
11752 (setq fmt (replace-match "" t t fmt)))
11753 (unless (string-match "\\S-" fmt)
11754 (setq fmt nil))))
11755 (if (and (not suppress-const) org-table-formula-use-constants)
11756 (setq formula (org-table-formula-substitute-names formula)))
11757 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
11758 (while (> ndown 0)
11759 (setq fields (org-split-string
11760 (buffer-substring
11761 (point-at-bol) (point-at-eol)) " *| *"))
11762 (if org-table-formula-numbers-only
11763 (setq fields (mapcar
11764 (lambda (x) (number-to-string (string-to-number x)))
11765 fields)))
11766 (setq ndown (1- ndown))
11767 (setq form (copy-sequence formula)
11768 lispp (equal (substring form 0 2) "'("))
11769 ;; Insert the references to fields in same row
11770 (while (string-match "\\$\\([0-9]+\\)?" form)
11771 (setq n (if (match-beginning 1)
11772 (string-to-number (match-string 1 form))
11773 n0)
11774 x (nth (1- n) fields))
11775 (unless x (error "Invalid field specifier \"%s\""
11776 (match-string 0 form)))
11777 (if (equal x "") (setq x "0"))
11778 (setq form (replace-match
11779 (if lispp x (concat "(" x ")"))
11780 t t form)))
11781 ;; Insert ranges in current column
11782 (while (string-match "\\&[-I0-9]+" form)
11783 (setq form (replace-match
11784 (save-match-data
11785 (org-table-get-vertical-vector (match-string 0 form)
11786 nil n0))
11787 t t form)))
11788 (if lispp
11789 (setq ev (eval (eval (read form)))
11790 ev (if (numberp ev) (number-to-string ev) ev))
11791 (setq ev (calc-eval (cons form modes)
11792 (if org-table-formula-numbers-only 'num))))
11793
11794 (when org-table-formula-debug
11795 (with-output-to-temp-buffer "*Help*"
11796 (princ (format "Substitution history of formula
11797 Orig: %s
11798 $xyz-> %s
11799 $1-> %s\n" orig formula form))
11800 (if (listp ev)
11801 (princ (format " %s^\nError: %s"
11802 (make-string (car ev) ?\-) (nth 1 ev)))
11803 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
11804 ev (or fmt "NONE")
11805 (if fmt (format fmt (string-to-number ev)) ev)))))
11806 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
11807 (unless (and (interactive-p) (not ndown))
11808 (unless (let (inhibit-redisplay)
11809 (y-or-n-p "Debugging Formula. Continue to next? "))
11810 (org-table-align)
11811 (error "Abort"))
11812 (delete-window (get-buffer-window "*Help*"))
11813 (message "")))
11814 (if (listp ev) (setq fmt nil ev "#ERROR"))
11815 (org-table-justify-field-maybe
11816 (if fmt (format fmt (string-to-number ev)) ev))
11817 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
11818 (call-interactively 'org-return)
11819 (setq ndown 0)))
11820 (and down (org-table-maybe-recalculate-line))
11821 (or suppress-align (and org-table-may-need-update
11822 (org-table-align)))))
11823
11824 (defun org-table-recalculate (&optional all noalign)
11825 "Recalculate the current table line by applying all stored formulas.
11826 With prefix arg ALL, do this for all lines in the table."
11827 (interactive "P")
11828 (or (memq this-command org-recalc-commands)
11829 (setq org-recalc-commands (cons this-command org-recalc-commands)))
11830 (unless (org-at-table-p) (error "Not at a table"))
11831 (org-table-get-specials)
11832 (let* ((eqlist (sort (org-table-get-stored-formulas)
11833 (lambda (a b) (string< (car a) (car b)))))
11834 (inhibit-redisplay t)
11835 (line-re org-table-dataline-regexp)
11836 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11837 (thiscol (org-table-current-column))
11838 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
11839 ;; Insert constants in all formulas
11840 (setq eqlist
11841 (mapcar (lambda (x)
11842 (setcdr x (org-table-formula-substitute-names (cdr x)))
11843 x)
11844 eqlist))
11845 ;; Split the equation list
11846 (while (setq eq (pop eqlist))
11847 (if (<= (string-to-char (car eq)) ?9)
11848 (push eq eqlnum)
11849 (push eq eqlname)))
11850 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
11851 (if all
11852 (progn
11853 (setq end (move-marker (make-marker) (1+ (org-table-end))))
11854 (goto-char (setq beg (org-table-begin)))
11855 (if (re-search-forward org-table-calculate-mark-regexp end t)
11856 ;; This is a table with marked lines, only compute selected lines
11857 (setq line-re org-table-recalculate-regexp)
11858 ;; Move forward to the first non-header line
11859 (if (and (re-search-forward org-table-dataline-regexp end t)
11860 (re-search-forward org-table-hline-regexp end t)
11861 (re-search-forward org-table-dataline-regexp end t))
11862 (setq beg (match-beginning 0))
11863 nil))) ;; just leave beg where it is
11864 (setq beg (point-at-bol)
11865 end (move-marker (make-marker) (1+ (point-at-eol)))))
11866 (goto-char beg)
11867 (and all (message "Re-applying formulas to full table..."))
11868 (while (re-search-forward line-re end t)
11869 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
11870 ;; Unprotected line, recalculate
11871 (and all (message "Re-applying formulas to full table...(line %d)"
11872 (setq cnt (1+ cnt))))
11873 (setq org-last-recalc-line (org-current-line))
11874 (setq eql eqlnum)
11875 (while (setq entry (pop eql))
11876 (goto-line org-last-recalc-line)
11877 (org-table-goto-column (string-to-number (car entry)) nil 'force)
11878 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
11879 (goto-line thisline)
11880 (org-table-goto-column thiscol)
11881 (or noalign (and org-table-may-need-update (org-table-align))
11882 (and all (message "Re-applying formulas to %d lines...done" cnt)))
11883 ;; Now do the names fields
11884 (while (setq eq (pop eqlname))
11885 (setq name (car eq)
11886 a (assoc name org-table-named-field-locations))
11887 (when a
11888 (message "Re-applying formula to named field: %s" name)
11889 (goto-line (nth 1 a))
11890 (org-table-goto-column (nth 2 a))
11891 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
11892 ;; back to initial position
11893 (goto-line thisline)
11894 (org-table-goto-column thiscol)
11895 (or noalign (and org-table-may-need-update (org-table-align))
11896 (and all (message "Re-applying formulas...done")))))
11897
11898 (defun org-table-formula-substitute-names (f)
11899 "Replace $const with values in string F."
11900 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
11901 ;; First, check for column names
11902 (while (setq start (string-match org-table-column-name-regexp f start))
11903 (setq start (1+ start))
11904 (setq a (assoc (match-string 1 f) org-table-column-names))
11905 (setq f (replace-match (concat "$" (cdr a)) t t f)))
11906 ;; Expand ranges to vectors
11907 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
11908 (setq n1 (string-to-number (match-string 1 f))
11909 n2 (string-to-number (match-string 2 f))
11910 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
11911 s (concat "[($" (number-to-string (1- nn1)) ")"))
11912 (loop for i from nn1 upto nn2 do
11913 (setq s (concat s ",($" (int-to-string i) ")")))
11914 (setq s (concat s "]"))
11915 (if (< n2 n1) (setq s (concat "rev(" s ")")))
11916 (setq f (replace-match s t t f)))
11917 ;; Parameters and constants
11918 (setq start 0)
11919 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
11920 (setq start (1+ start))
11921 (if (setq a (save-match-data
11922 (org-table-get-constant (match-string 1 f))))
11923 (setq f (replace-match (concat "(" a ")") t t f))))
11924 (if org-table-formula-debug
11925 (put-text-property 0 (length f) :orig-formula f1 f))
11926 f))
11927
11928 (defun org-table-get-constant (const)
11929 "Find the value for a parameter or constant in a formula.
11930 Parameters get priority."
11931 (or (cdr (assoc const org-table-local-parameters))
11932 (cdr (assoc const org-table-formula-constants))
11933 (and (fboundp 'constants-get) (constants-get const))
11934 "#UNDEFINED_NAME"))
11935
11936 (defvar org-edit-formulas-map (make-sparse-keymap))
11937 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
11938 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
11939 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
11940
11941 (defvar org-pos)
11942
11943 (defun org-table-edit-formulas ()
11944 "Edit the formulas of the current table in a separate buffer."
11945 (interactive)
11946 (unless (org-at-table-p)
11947 (error "Not at a table"))
11948 (org-table-get-specials)
11949 (let ((eql (org-table-get-stored-formulas))
11950 (pos (move-marker (make-marker) (point)))
11951 (wc (current-window-configuration))
11952 entry loc s)
11953 (switch-to-buffer-other-window "*Edit Formulas*")
11954 (erase-buffer)
11955 (fundamental-mode)
11956 (set (make-local-variable 'org-pos) pos)
11957 (set (make-local-variable 'org-window-configuration) wc)
11958 (use-local-map org-edit-formulas-map)
11959 (setq s "# Edit formulas and finish with `C-c C-c'.
11960 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
11961 # Use `C-c ?' to get information about $name at point.
11962 # To cancel editing, press `C-c C-q'.\n")
11963 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
11964 (insert s)
11965 (while (setq entry (pop eql))
11966 (when (setq loc (assoc (car entry) org-table-named-field-locations))
11967 (setq s (format "# Named formula, referring to column %d in line %d\n"
11968 (nth 2 loc) (nth 1 loc)))
11969 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
11970 (insert s))
11971 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
11972 (remove-text-properties 0 (length s) '(face nil) s)
11973 (insert s))
11974 (goto-char (point-min))
11975 (message "Edit formulas and finish with `C-c C-c'.")))
11976
11977 (defun org-show-variable ()
11978 "Show the location/value of the $ expression at point."
11979 (interactive)
11980 (let (var (pos org-pos) (win (selected-window)) e)
11981 (save-excursion
11982 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
11983 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
11984 (setq var (match-string 1))
11985 (error "No variable at point")))
11986 (cond
11987 ((setq e (assoc var org-table-named-field-locations))
11988 (switch-to-buffer-other-window (marker-buffer pos))
11989 (goto-line (nth 1 e))
11990 (org-table-goto-column (nth 2 e))
11991 (select-window win)
11992 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11993 ((setq e (assoc var org-table-column-names))
11994 (switch-to-buffer-other-window (marker-buffer pos))
11995 (goto-char pos)
11996 (goto-char (org-table-begin))
11997 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11998 (org-table-end) t)
11999 (progn
12000 (goto-char (match-beginning 1))
12001 (message "Named column (column %s)" (cdr e)))
12002 (error "Column name not found"))
12003 (select-window win))
12004 ((string-match "^[0-9]$" var)
12005 ;; column number
12006 (switch-to-buffer-other-window (marker-buffer pos))
12007 (goto-char pos)
12008 (goto-char (org-table-begin))
12009 (recenter 1)
12010 (if (re-search-forward org-table-dataline-regexp
12011 (org-table-end) t)
12012 (progn
12013 (goto-char (match-beginning 0))
12014 (org-table-goto-column (string-to-number var))
12015 (message "Column %s" var))
12016 (error "Column name not found"))
12017 (select-window win))
12018 ((setq e (assoc var org-table-local-parameters))
12019 (switch-to-buffer-other-window (marker-buffer pos))
12020 (goto-char pos)
12021 (goto-char (org-table-begin))
12022 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
12023 (progn
12024 (goto-char (match-beginning 1))
12025 (message "Local parameter."))
12026 (error "Parameter not found"))
12027 (select-window win))
12028 (t
12029 (cond
12030 ((setq e (assoc var org-table-formula-constants))
12031 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
12032 ((setq e (and (fboundp 'constants-get) (constants-get var)))
12033 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
12034 (t (error "Undefined name $%s" var)))))))
12035
12036 (defun org-finish-edit-formulas (&optional arg)
12037 "Parse the buffer for formula definitions and install them.
12038 With prefix ARG, apply the new formulas to the table."
12039 (interactive "P")
12040 (let ((pos org-pos) eql)
12041 (goto-char (point-min))
12042 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
12043 (push (cons (match-string 1) (match-string 2)) eql))
12044 (set-window-configuration org-window-configuration)
12045 (select-window (get-buffer-window (marker-buffer pos)))
12046 (goto-char pos)
12047 (unless (org-at-table-p)
12048 (error "Lost table position - cannot install formulae"))
12049 (org-table-store-formulas eql)
12050 (move-marker pos nil)
12051 (kill-buffer "*Edit Formulas*")
12052 (if arg
12053 (org-table-recalculate 'all)
12054 (message "New formulas installed - press C-u C-c C-c to apply."))))
12055
12056 (defun org-abort-edit-formulas ()
12057 "Abort editing formulas, without installing the changes."
12058 (interactive)
12059 (let ((pos org-pos))
12060 (set-window-configuration org-window-configuration)
12061 (select-window (get-buffer-window (marker-buffer pos)))
12062 (goto-char pos)
12063 (message "Formula editing aborted without installing changes")))
12064
12065 ;;; The orgtbl minor mode
12066
12067 ;; Define a minor mode which can be used in other modes in order to
12068 ;; integrate the org-mode table editor.
12069
12070 ;; This is really a hack, because the org-mode table editor uses several
12071 ;; keys which normally belong to the major mode, for example the TAB and
12072 ;; RET keys. Here is how it works: The minor mode defines all the keys
12073 ;; necessary to operate the table editor, but wraps the commands into a
12074 ;; function which tests if the cursor is currently inside a table. If that
12075 ;; is the case, the table editor command is executed. However, when any of
12076 ;; those keys is used outside a table, the function uses `key-binding' to
12077 ;; look up if the key has an associated command in another currently active
12078 ;; keymap (minor modes, major mode, global), and executes that command.
12079 ;; There might be problems if any of the keys used by the table editor is
12080 ;; otherwise used as a prefix key.
12081
12082 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
12083 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
12084 ;; addresses this by checking explicitly for both bindings.
12085
12086 ;; The optimized version (see variable `orgtbl-optimized') takes over
12087 ;; all keys which are bound to `self-insert-command' in the *global map*.
12088 ;; Some modes bind other commands to simple characters, for example
12089 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
12090 ;; active, this binding is ignored inside tables and replaced with a
12091 ;; modified self-insert.
12092
12093 (defvar orgtbl-mode nil
12094 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
12095 table editor in arbitrary modes.")
12096 (make-variable-buffer-local 'orgtbl-mode)
12097
12098 (defvar orgtbl-mode-map (make-keymap)
12099 "Keymap for `orgtbl-mode'.")
12100
12101 ;;;###autoload
12102 (defun turn-on-orgtbl ()
12103 "Unconditionally turn on `orgtbl-mode'."
12104 (orgtbl-mode 1))
12105
12106 ;;;###autoload
12107 (defun orgtbl-mode (&optional arg)
12108 "The `org-mode' table editor as a minor mode for use in other modes."
12109 (interactive)
12110 (if (eq major-mode 'org-mode)
12111 ;; Exit without error, in case some hook functions calls this
12112 ;; by accident in org-mode.
12113 (message "Orgtbl-mode is not useful in org-mode, command ignored")
12114 (setq orgtbl-mode
12115 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
12116 (if orgtbl-mode
12117 (progn
12118 (and (orgtbl-setup) (defun orgtbl-setup () nil))
12119 ;; Make sure we are first in minor-mode-map-alist
12120 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
12121 (and c (setq minor-mode-map-alist
12122 (cons c (delq c minor-mode-map-alist)))))
12123 (set (make-local-variable (quote org-table-may-need-update)) t)
12124 (org-add-hook 'before-change-functions 'org-before-change-function
12125 nil 'local)
12126 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
12127 auto-fill-inhibit-regexp)
12128 (set (make-local-variable 'auto-fill-inhibit-regexp)
12129 (if auto-fill-inhibit-regexp
12130 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
12131 "[ \t]*|"))
12132 (org-add-to-invisibility-spec '(org-cwidth))
12133 (easy-menu-add orgtbl-mode-menu)
12134 (run-hooks 'orgtbl-mode-hook))
12135 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
12136 (org-cleanup-narrow-column-properties)
12137 (org-remove-from-invisibility-spec '(org-cwidth))
12138 (remove-hook 'before-change-functions 'org-before-change-function t)
12139 (easy-menu-remove orgtbl-mode-menu)
12140 (force-mode-line-update 'all))))
12141
12142 (defun org-cleanup-narrow-column-properties ()
12143 "Remove all properties related to narrow-column invisibility."
12144 (let ((s 1))
12145 (while (setq s (text-property-any s (point-max)
12146 'display org-narrow-column-arrow))
12147 (remove-text-properties s (1+ s) '(display t)))
12148 (setq s 1)
12149 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
12150 (remove-text-properties s (1+ s) '(org-cwidth t)))
12151 (setq s 1)
12152 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
12153 (remove-text-properties s (1+ s) '(invisible t)))))
12154
12155 ;; Install it as a minor mode.
12156 (put 'orgtbl-mode :included t)
12157 (put 'orgtbl-mode :menu-tag "Org Table Mode")
12158 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
12159
12160 (defun orgtbl-make-binding (fun n &rest keys)
12161 "Create a function for binding in the table minor mode.
12162 FUN is the command to call inside a table. N is used to create a unique
12163 command name. KEYS are keys that should be checked in for a command
12164 to execute outside of tables."
12165 (eval
12166 (list 'defun
12167 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
12168 '(arg)
12169 (concat "In tables, run `" (symbol-name fun) "'.\n"
12170 "Outside of tables, run the binding of `"
12171 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
12172 "'.")
12173 '(interactive "p")
12174 (list 'if
12175 '(org-at-table-p)
12176 (list 'call-interactively (list 'quote fun))
12177 (list 'let '(orgtbl-mode)
12178 (list 'call-interactively
12179 (append '(or)
12180 (mapcar (lambda (k)
12181 (list 'key-binding k))
12182 keys)
12183 '('orgtbl-error))))))))
12184
12185 (defun orgtbl-error ()
12186 "Error when there is no default binding for a table key."
12187 (interactive)
12188 (error "This key is has no function outside tables"))
12189
12190 (defun orgtbl-setup ()
12191 "Setup orgtbl keymaps."
12192 (let ((nfunc 0)
12193 (bindings
12194 (list
12195 '([(meta shift left)] org-table-delete-column)
12196 '([(meta left)] org-table-move-column-left)
12197 '([(meta right)] org-table-move-column-right)
12198 '([(meta shift right)] org-table-insert-column)
12199 '([(meta shift up)] org-table-kill-row)
12200 '([(meta shift down)] org-table-insert-row)
12201 '([(meta up)] org-table-move-row-up)
12202 '([(meta down)] org-table-move-row-down)
12203 '("\C-c\C-w" org-table-cut-region)
12204 '("\C-c\M-w" org-table-copy-region)
12205 '("\C-c\C-y" org-table-paste-rectangle)
12206 '("\C-c-" org-table-insert-hline)
12207 ; '([(shift tab)] org-table-previous-field)
12208 '("\C-m" org-table-next-row)
12209 (list (org-key 'S-return) 'org-table-copy-down)
12210 '([(meta return)] org-table-wrap-region)
12211 '("\C-c\C-q" org-table-wrap-region)
12212 '("\C-c?" org-table-current-column)
12213 '("\C-c " org-table-blank-field)
12214 '("\C-c+" org-table-sum)
12215 '("\C-c=" org-table-eval-formula)
12216 '("\C-c'" org-table-edit-formulas)
12217 '("\C-c`" org-table-edit-field)
12218 '("\C-c*" org-table-recalculate)
12219 '("\C-c|" org-table-create-or-convert-from-region)
12220 '("\C-c^" org-table-sort-lines)
12221 '([(control ?#)] org-table-rotate-recalc-marks)))
12222 elt key fun cmd)
12223 (while (setq elt (pop bindings))
12224 (setq nfunc (1+ nfunc))
12225 (setq key (car elt)
12226 fun (nth 1 elt)
12227 cmd (orgtbl-make-binding fun nfunc key))
12228 (define-key orgtbl-mode-map key cmd))
12229 ;; Special treatment needed for TAB and RET
12230 (define-key orgtbl-mode-map [(return)]
12231 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
12232 (define-key orgtbl-mode-map "\C-m"
12233 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
12234 (define-key orgtbl-mode-map [(tab)]
12235 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
12236 (define-key orgtbl-mode-map "\C-i"
12237 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
12238 (define-key orgtbl-mode-map "\C-i"
12239 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
12240 (define-key orgtbl-mode-map "\C-c\C-c"
12241 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
12242 (when orgtbl-optimized
12243 ;; If the user wants maximum table support, we need to hijack
12244 ;; some standard editing functions
12245 (org-remap orgtbl-mode-map
12246 'self-insert-command 'orgtbl-self-insert-command
12247 'delete-char 'org-delete-char
12248 'delete-backward-char 'org-delete-backward-char)
12249 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
12250 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
12251 '("OrgTbl"
12252 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
12253 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
12254 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
12255 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
12256 "--"
12257 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
12258 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
12259 ["Copy Field from Above"
12260 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
12261 "--"
12262 ("Column"
12263 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
12264 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
12265 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
12266 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
12267 "--"
12268 ["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])
12269 ("Row"
12270 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
12271 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
12272 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
12273 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
12274 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
12275 "--"
12276 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
12277 ("Rectangle"
12278 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
12279 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
12280 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
12281 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
12282 "--"
12283 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
12284 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12285 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
12286 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
12287 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
12288 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
12289 ["Sum Column/Rectangle" org-table-sum
12290 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
12291 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
12292 ["Debug Formulas"
12293 (setq org-table-formula-debug (not org-table-formula-debug))
12294 :style toggle :selected org-table-formula-debug]
12295 ))
12296 t)
12297
12298 (defun orgtbl-tab (arg)
12299 "Justification and field motion for `orgtbl-mode'."
12300 (interactive "P")
12301 (if arg (org-table-edit-field t)
12302 (org-table-justify-field-maybe)
12303 (org-table-next-field)))
12304
12305 (defun orgtbl-ret ()
12306 "Justification and field motion for `orgtbl-mode'."
12307 (interactive)
12308 (org-table-justify-field-maybe)
12309 (org-table-next-row))
12310
12311 (defun orgtbl-self-insert-command (N)
12312 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12313 If the cursor is in a table looking at whitespace, the whitespace is
12314 overwritten, and the table is not marked as requiring realignment."
12315 (interactive "p")
12316 (if (and (org-at-table-p)
12317 (or
12318 (and org-table-auto-blank-field
12319 (member last-command
12320 '(orgtbl-hijacker-command-100
12321 orgtbl-hijacker-command-101
12322 orgtbl-hijacker-command-102
12323 orgtbl-hijacker-command-103
12324 orgtbl-hijacker-command-104
12325 orgtbl-hijacker-command-105))
12326 (org-table-blank-field))
12327 t)
12328 (eq N 1)
12329 (looking-at "[^|\n]* +|"))
12330 (let (org-table-may-need-update)
12331 (goto-char (1- (match-end 0)))
12332 (delete-backward-char 1)
12333 (goto-char (match-beginning 0))
12334 (self-insert-command N))
12335 (setq org-table-may-need-update t)
12336 (let (orgtbl-mode)
12337 (call-interactively (key-binding (vector last-input-event))))))
12338
12339 (defun org-force-self-insert (N)
12340 "Needed to enforce self-insert under remapping."
12341 (interactive "p")
12342 (self-insert-command N))
12343
12344 ;;; Exporting
12345
12346 (defconst org-level-max 20)
12347
12348 (defvar org-export-html-preamble nil
12349 "Preamble, to be inserted just after <body>. Set by publishing functions.")
12350 (defvar org-export-html-postamble nil
12351 "Preamble, to be inserted just before </body>. Set by publishing functions.")
12352 (defvar org-export-html-auto-preamble t
12353 "Should default preamble be inserted? Set by publishing functions.")
12354 (defvar org-export-html-auto-postamble t
12355 "Should default postamble be inserted? Set by publishing functions.")
12356
12357 (defconst org-export-plist-vars
12358 '((:language . org-export-default-language)
12359 (:headline-levels . org-export-headline-levels)
12360 (:section-numbers . org-export-with-section-numbers)
12361 (:table-of-contents . org-export-with-toc)
12362 (:emphasize . org-export-with-emphasize)
12363 (:sub-superscript . org-export-with-sub-superscripts)
12364 (:TeX-macros . org-export-with-TeX-macros)
12365 (:fixed-width . org-export-with-fixed-width)
12366 (:timestamps . org-export-with-timestamps)
12367 (:tables . org-export-with-tables)
12368 (:table-auto-headline . org-export-highlight-first-table-line)
12369 (:style . org-export-html-style)
12370 (:convert-org-links . org-export-html-link-org-files-as-html)
12371 (:inline-images . org-export-html-inline-images)
12372 (:expand-quoted-html . org-export-html-expand)
12373 (:timestamp . org-export-html-with-timestamp)
12374 (:publishing-directory . org-export-publishing-directory)
12375 (:preamble . org-export-html-preamble)
12376 (:postamble . org-export-html-postamble)
12377 (:auto-preamble . org-export-html-auto-preamble)
12378 (:auto-postamble . org-export-html-auto-postamble)
12379 (:author . user-full-name)
12380 (:email . user-mail-address)))
12381
12382 (defun org-default-export-plist ()
12383 "Return the property list with default settings for the export variables."
12384 (let ((l org-export-plist-vars) rtn e)
12385 (while (setq e (pop l))
12386 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
12387 rtn))
12388
12389 (defun org-infile-export-plist ()
12390 "Return the property list with file-local settings for export."
12391 (save-excursion
12392 (goto-char 0)
12393 (let ((re (org-make-options-regexp
12394 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12395 (text nil)
12396 p key val text options)
12397 (while (re-search-forward re nil t)
12398 (setq key (org-match-string-no-properties 1)
12399 val (org-match-string-no-properties 2))
12400 (cond
12401 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
12402 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
12403 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
12404 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
12405 ((string-equal key "TEXT")
12406 (setq text (if text (concat text "\n" val) val)))
12407 ((string-equal key "OPTIONS") (setq options val))))
12408 (setq p (plist-put p :text text))
12409 (when options
12410 (let ((op '(("H" . :headline-levels)
12411 ("num" . :section-numbers)
12412 ("toc" . :table-of-contents)
12413 ("\\n" . :preserve-breaks)
12414 ("@" . :expand-quoted-html)
12415 (":" . :fixed-width)
12416 ("|" . :tables)
12417 ("^" . :sub-superscript)
12418 ("*" . :emphasize)
12419 ("TeX" . :TeX-macros)))
12420 o)
12421 (while (setq o (pop op))
12422 (if (string-match (concat (regexp-quote (car o))
12423 ":\\([^ \t\n\r;,.]*\\)")
12424 options)
12425 (setq p (plist-put p (cdr o)
12426 (car (read-from-string
12427 (match-string 1 options)))))))))
12428 p)))
12429
12430 (defun org-combine-plists (&rest plists)
12431 "Create a single property list from all plists in PLISTS.
12432 The process starts by copying the last list, and then setting properties
12433 from the other lists. Settings in the first list are the most significant
12434 ones and overrule settings in the other lists."
12435 (let ((rtn (copy-sequence (pop plists)))
12436 p v ls)
12437 (while plists
12438 (setq ls (pop plists))
12439 (while ls
12440 (setq p (pop ls) v (pop ls))
12441 (setq rtn (plist-put rtn p v))))
12442 rtn))
12443
12444 (defun org-export-directory (type plist)
12445 (let* ((val (plist-get plist :publishing-directory))
12446 (dir (if (listp val)
12447 (or (cdr (assoc type val)) ".")
12448 val)))
12449 dir))
12450
12451 (defun org-export-find-first-heading-line (list)
12452 "Remove all lines from LIST which are before the first headline."
12453 (let ((orig-list list)
12454 (re (concat "^" outline-regexp)))
12455 (while (and list
12456 (not (string-match re (car list))))
12457 (pop list))
12458 (or list orig-list)))
12459
12460 (defun org-skip-comments (lines)
12461 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
12462 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
12463 (re2 "^\\(\\*+\\)[ \t\n\r]")
12464 rtn line level)
12465 (while (setq line (pop lines))
12466 (cond
12467 ((and (string-match re1 line)
12468 (setq level (- (match-end 1) (match-beginning 1))))
12469 ;; Beginning of a COMMENT subtree. Skip it.
12470 (while (and (setq line (pop lines))
12471 (or (not (string-match re2 line))
12472 (> (- (match-end 1) (match-beginning 1)) level))))
12473 (setq lines (cons line lines)))
12474 ((string-match "^#" line)
12475 ;; an ordinary comment line
12476 )
12477 ((and org-export-table-remove-special-lines
12478 (string-match "^[ \t]*|" line)
12479 (or (string-match "^[ \t]*| *[!_^] *|" line)
12480 (and (string-match "| *<[0-9]+> *|" line)
12481 (not (string-match "| *[^ <|]" line)))))
12482 ;; a special table line that should be removed
12483 )
12484 (t (setq rtn (cons line rtn)))))
12485 (nreverse rtn)))
12486
12487 (defun org-export (&optional arg)
12488 (interactive)
12489 (let ((help "[t] insert the export option template
12490 \[v] limit export to visible part of outline tree
12491
12492 \[a] export as ASCII
12493 \[h] export as HTML
12494 \[b] export as HTML and browse immediately
12495 \[x] export as XOXO
12496
12497 \[i] export current file as iCalendar file
12498 \[I] export all agenda files as iCalendar files
12499 \[c] export agenda files into combined iCalendar file
12500
12501 \[F] publish current file
12502 \[P] publish current project
12503 \[X] publish... (project will be prompted for)
12504 \[A] publish all projects")
12505 (cmds
12506 '((?t . org-insert-export-options-template)
12507 (?v . org-export-visible)
12508 (?a . org-export-as-ascii)
12509 (?h . org-export-as-html)
12510 (?b . org-export-as-html-and-open)
12511 (?x . org-export-as-xoxo)
12512 (?i . org-export-icalendar-this-file)
12513 (?I . org-export-icalendar-all-agenda-files)
12514 (?c . org-export-icalendar-combine-agenda-files)
12515 (?F . org-publish-current-file)
12516 (?P . org-publish-current-project)
12517 (?X . org-publish)
12518 (?A . org-publish-all)))
12519 r1 r2 ass)
12520 (save-window-excursion
12521 (delete-other-windows)
12522 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
12523 (princ help))
12524 (message "Select command: ")
12525 (setq r1 (read-char-exclusive)))
12526 (setq r2 (if (< r1 27) (+ r1 96) r1))
12527 (if (setq ass (assq r2 cmds))
12528 (call-interactively (cdr ass))
12529 (error "No command associated with key %c" r1))))
12530
12531 ;; ASCII
12532
12533 (defconst org-html-entities
12534 '(("nbsp")
12535 ("iexcl")
12536 ("cent")
12537 ("pound")
12538 ("curren")
12539 ("yen")
12540 ("brvbar")
12541 ("sect")
12542 ("uml")
12543 ("copy")
12544 ("ordf")
12545 ("laquo")
12546 ("not")
12547 ("shy")
12548 ("reg")
12549 ("macr")
12550 ("deg")
12551 ("plusmn")
12552 ("sup2")
12553 ("sup3")
12554 ("acute")
12555 ("micro")
12556 ("para")
12557 ("middot")
12558 ("odot"."o")
12559 ("star"."*")
12560 ("cedil")
12561 ("sup1")
12562 ("ordm")
12563 ("raquo")
12564 ("frac14")
12565 ("frac12")
12566 ("frac34")
12567 ("iquest")
12568 ("Agrave")
12569 ("Aacute")
12570 ("Acirc")
12571 ("Atilde")
12572 ("Auml")
12573 ("Aring") ("AA"."&Aring;")
12574 ("AElig")
12575 ("Ccedil")
12576 ("Egrave")
12577 ("Eacute")
12578 ("Ecirc")
12579 ("Euml")
12580 ("Igrave")
12581 ("Iacute")
12582 ("Icirc")
12583 ("Iuml")
12584 ("ETH")
12585 ("Ntilde")
12586 ("Ograve")
12587 ("Oacute")
12588 ("Ocirc")
12589 ("Otilde")
12590 ("Ouml")
12591 ("times")
12592 ("Oslash")
12593 ("Ugrave")
12594 ("Uacute")
12595 ("Ucirc")
12596 ("Uuml")
12597 ("Yacute")
12598 ("THORN")
12599 ("szlig")
12600 ("agrave")
12601 ("aacute")
12602 ("acirc")
12603 ("atilde")
12604 ("auml")
12605 ("aring")
12606 ("aelig")
12607 ("ccedil")
12608 ("egrave")
12609 ("eacute")
12610 ("ecirc")
12611 ("euml")
12612 ("igrave")
12613 ("iacute")
12614 ("icirc")
12615 ("iuml")
12616 ("eth")
12617 ("ntilde")
12618 ("ograve")
12619 ("oacute")
12620 ("ocirc")
12621 ("otilde")
12622 ("ouml")
12623 ("divide")
12624 ("oslash")
12625 ("ugrave")
12626 ("uacute")
12627 ("ucirc")
12628 ("uuml")
12629 ("yacute")
12630 ("thorn")
12631 ("yuml")
12632 ("fnof")
12633 ("Alpha")
12634 ("Beta")
12635 ("Gamma")
12636 ("Delta")
12637 ("Epsilon")
12638 ("Zeta")
12639 ("Eta")
12640 ("Theta")
12641 ("Iota")
12642 ("Kappa")
12643 ("Lambda")
12644 ("Mu")
12645 ("Nu")
12646 ("Xi")
12647 ("Omicron")
12648 ("Pi")
12649 ("Rho")
12650 ("Sigma")
12651 ("Tau")
12652 ("Upsilon")
12653 ("Phi")
12654 ("Chi")
12655 ("Psi")
12656 ("Omega")
12657 ("alpha")
12658 ("beta")
12659 ("gamma")
12660 ("delta")
12661 ("epsilon")
12662 ("varepsilon"."&epsilon;")
12663 ("zeta")
12664 ("eta")
12665 ("theta")
12666 ("iota")
12667 ("kappa")
12668 ("lambda")
12669 ("mu")
12670 ("nu")
12671 ("xi")
12672 ("omicron")
12673 ("pi")
12674 ("rho")
12675 ("sigmaf") ("varsigma"."&sigmaf;")
12676 ("sigma")
12677 ("tau")
12678 ("upsilon")
12679 ("phi")
12680 ("chi")
12681 ("psi")
12682 ("omega")
12683 ("thetasym") ("vartheta"."&thetasym;")
12684 ("upsih")
12685 ("piv")
12686 ("bull") ("bullet"."&bull;")
12687 ("hellip") ("dots"."&hellip;")
12688 ("prime")
12689 ("Prime")
12690 ("oline")
12691 ("frasl")
12692 ("weierp")
12693 ("image")
12694 ("real")
12695 ("trade")
12696 ("alefsym")
12697 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
12698 ("uarr") ("uparrow"."&uarr;")
12699 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
12700 ("darr")("downarrow"."&darr;")
12701 ("harr") ("leftrightarrow"."&harr;")
12702 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
12703 ("lArr") ("Leftarrow"."&lArr;")
12704 ("uArr") ("Uparrow"."&uArr;")
12705 ("rArr") ("Rightarrow"."&rArr;")
12706 ("dArr") ("Downarrow"."&dArr;")
12707 ("hArr") ("Leftrightarrow"."&hArr;")
12708 ("forall")
12709 ("part") ("partial"."&part;")
12710 ("exist") ("exists"."&exist;")
12711 ("empty") ("emptyset"."&empty;")
12712 ("nabla")
12713 ("isin") ("in"."&isin;")
12714 ("notin")
12715 ("ni")
12716 ("prod")
12717 ("sum")
12718 ("minus")
12719 ("lowast") ("ast"."&lowast;")
12720 ("radic")
12721 ("prop") ("proptp"."&prop;")
12722 ("infin") ("infty"."&infin;")
12723 ("ang") ("angle"."&ang;")
12724 ("and") ("vee"."&and;")
12725 ("or") ("wedge"."&or;")
12726 ("cap")
12727 ("cup")
12728 ("int")
12729 ("there4")
12730 ("sim")
12731 ("cong") ("simeq"."&cong;")
12732 ("asymp")("approx"."&asymp;")
12733 ("ne") ("neq"."&ne;")
12734 ("equiv")
12735 ("le")
12736 ("ge")
12737 ("sub") ("subset"."&sub;")
12738 ("sup") ("supset"."&sup;")
12739 ("nsub")
12740 ("sube")
12741 ("supe")
12742 ("oplus")
12743 ("otimes")
12744 ("perp")
12745 ("sdot") ("cdot"."&sdot;")
12746 ("lceil")
12747 ("rceil")
12748 ("lfloor")
12749 ("rfloor")
12750 ("lang")
12751 ("rang")
12752 ("loz") ("Diamond"."&loz;")
12753 ("spades") ("spadesuit"."&spades;")
12754 ("clubs") ("clubsuit"."&clubs;")
12755 ("hearts") ("diamondsuit"."&hearts;")
12756 ("diams") ("diamondsuit"."&diams;")
12757 ("quot")
12758 ("amp")
12759 ("lt")
12760 ("gt")
12761 ("OElig")
12762 ("oelig")
12763 ("Scaron")
12764 ("scaron")
12765 ("Yuml")
12766 ("circ")
12767 ("tilde")
12768 ("ensp")
12769 ("emsp")
12770 ("thinsp")
12771 ("zwnj")
12772 ("zwj")
12773 ("lrm")
12774 ("rlm")
12775 ("ndash")
12776 ("mdash")
12777 ("lsquo")
12778 ("rsquo")
12779 ("sbquo")
12780 ("ldquo")
12781 ("rdquo")
12782 ("bdquo")
12783 ("dagger")
12784 ("Dagger")
12785 ("permil")
12786 ("lsaquo")
12787 ("rsaquo")
12788 ("euro")
12789
12790 ("arccos"."arccos")
12791 ("arcsin"."arcsin")
12792 ("arctan"."arctan")
12793 ("arg"."arg")
12794 ("cos"."cos")
12795 ("cosh"."cosh")
12796 ("cot"."cot")
12797 ("coth"."coth")
12798 ("csc"."csc")
12799 ("deg"."deg")
12800 ("det"."det")
12801 ("dim"."dim")
12802 ("exp"."exp")
12803 ("gcd"."gcd")
12804 ("hom"."hom")
12805 ("inf"."inf")
12806 ("ker"."ker")
12807 ("lg"."lg")
12808 ("lim"."lim")
12809 ("liminf"."liminf")
12810 ("limsup"."limsup")
12811 ("ln"."ln")
12812 ("log"."log")
12813 ("max"."max")
12814 ("min"."min")
12815 ("Pr"."Pr")
12816 ("sec"."sec")
12817 ("sin"."sin")
12818 ("sinh"."sinh")
12819 ("sup"."sup")
12820 ("tan"."tan")
12821 ("tanh"."tanh")
12822 )
12823 "Entities for TeX->HTML translation.
12824 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
12825 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
12826 In that case, \"\\ent\" will be translated to \"&other;\".
12827 The list contains HTML entities for Latin-1, Greek and other symbols.
12828 It is supplemented by a number of commonly used TeX macros with appropriate
12829 translations. There is currently no way for users to extend this.")
12830
12831 (defun org-cleaned-string-for-export (string &rest parameters)
12832 "Cleanup a buffer substring so that links can be created safely."
12833 (interactive)
12834 (let* ((cb (current-buffer))
12835 (re-radio (and org-target-link-regexp
12836 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
12837 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
12838 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
12839 rtn)
12840 (save-excursion
12841 (set-buffer (get-buffer-create " org-mode-tmp"))
12842 (erase-buffer)
12843 (insert string)
12844 (org-mode)
12845 ;; Find targets in comments and move them out of comments,
12846 ;; but mark them as targets that should be invisible
12847 (goto-char (point-min))
12848 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
12849 (replace-match "\\1(INVISIBLE)"))
12850 ;; Find matches for radio targets and turn them into internal links
12851 (goto-char (point-min))
12852 (when re-radio
12853 (while (re-search-forward re-radio nil t)
12854 (replace-match "\\1[[\\2]]")))
12855 ;; Find all links that contain a newline and put them into a single line
12856 (goto-char (point-min))
12857 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
12858 (replace-match "\\1 \\3")
12859 (goto-char (match-beginning 0)))
12860 ;; Normalize links: Convert angle and plain links into bracket links
12861 (goto-char (point-min))
12862 (while (re-search-forward re-plain-link nil t)
12863 (replace-match
12864 (concat
12865 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
12866 t t))
12867 (goto-char (point-min))
12868 (while (re-search-forward re-angle-link nil t)
12869 (replace-match
12870 (concat
12871 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
12872 t t))
12873 ;; Find multiline emphasis and put them into single line
12874 (when (memq :emph-multiline parameters)
12875 (goto-char (point-min))
12876 (while (re-search-forward org-emph-re nil t)
12877 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
12878 (goto-char (1- (match-end 0)))))
12879
12880 ;; Remove comments
12881 (goto-char (point-min))
12882 (while (re-search-forward "^#.*\n?" nil t)
12883 (replace-match ""))
12884 (setq rtn (buffer-string)))
12885 (kill-buffer " org-mode-tmp")
12886 rtn))
12887
12888 (defun org-solidify-link-text (s &optional alist)
12889 "Take link text and make a safe target out of it."
12890 (save-match-data
12891 (let* ((rtn
12892 (mapconcat
12893 'identity
12894 (org-split-string s "[ \t\r\n]+") "--"))
12895 (a (assoc rtn alist)))
12896 (or (cdr a) rtn))))
12897
12898 (defun org-convert-to-odd-levels ()
12899 "Convert an org-mode file with all levels allowed to one with odd levels.
12900 This will leave level 1 alone, convert level 2 to level 3, level 3 to
12901 level 5 etc."
12902 (interactive)
12903 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
12904 (let ((org-odd-levels-only nil) n)
12905 (save-excursion
12906 (goto-char (point-min))
12907 (while (re-search-forward "^\\*\\*+" nil t)
12908 (setq n (1- (length (match-string 0))))
12909 (while (>= (setq n (1- n)) 0)
12910 (org-demote))
12911 (end-of-line 1))))))
12912
12913
12914 (defun org-convert-to-oddeven-levels ()
12915 "Convert an org-mode file with only odd levels to one with odd and even levels.
12916 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
12917 section with an even level, conversion would destroy the structure of the file. An error
12918 is signaled in this case."
12919 (interactive)
12920 (goto-char (point-min))
12921 ;; First check if there are no even levels
12922 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
12923 (org-show-hierarchy-above)
12924 (error "Not all levels are odd in this file. Conversion not possible."))
12925 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
12926 (let ((org-odd-levels-only nil) n)
12927 (save-excursion
12928 (goto-char (point-min))
12929 (while (re-search-forward "^\\*\\*+" nil t)
12930 (setq n (/ (length (match-string 0)) 2))
12931 (while (>= (setq n (1- n)) 0)
12932 (org-promote))
12933 (end-of-line 1))))))
12934
12935 (defun org-tr-level (n)
12936 "Make N odd if required."
12937 (if org-odd-levels-only (1+ (/ n 2)) n))
12938
12939 (defvar org-last-level nil) ; dynamically scoped variable
12940 (defvar org-ascii-current-indentation nil) ; For communication
12941
12942 (defun org-export-as-ascii (arg)
12943 "Export the outline as a pretty ASCII file.
12944 If there is an active region, export only the region.
12945 The prefix ARG specifies how many levels of the outline should become
12946 underlined headlines. The default is 3."
12947 (interactive "P")
12948 (setq-default org-todo-line-regexp org-todo-line-regexp)
12949 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
12950 (org-infile-export-plist)))
12951 (region
12952 (buffer-substring
12953 (if (org-region-active-p) (region-beginning) (point-min))
12954 (if (org-region-active-p) (region-end) (point-max))))
12955 (lines (org-export-find-first-heading-line
12956 (org-skip-comments
12957 (org-split-string
12958 (org-cleaned-string-for-export region)
12959 "[\r\n]"))))
12960 (org-ascii-current-indentation '(0 . 0))
12961 (org-startup-with-deadline-check nil)
12962 (level 0) line txt
12963 (umax nil)
12964 (case-fold-search nil)
12965 (filename (concat (file-name-as-directory
12966 (org-export-directory :ascii opt-plist))
12967 (file-name-sans-extension
12968 (file-name-nondirectory buffer-file-name))
12969 ".txt"))
12970 (buffer (find-file-noselect filename))
12971 (levels-open (make-vector org-level-max nil))
12972 (odd org-odd-levels-only)
12973 (date (format-time-string "%Y/%m/%d" (current-time)))
12974 (time (format-time-string "%X" (org-current-time)))
12975 (author (plist-get opt-plist :author))
12976 (title (or (plist-get opt-plist :title)
12977 (file-name-sans-extension
12978 (file-name-nondirectory buffer-file-name))))
12979 (options nil)
12980 (email (plist-get opt-plist :email))
12981 (language (plist-get opt-plist :language))
12982 (text nil)
12983 (todo nil)
12984 (lang-words nil))
12985
12986 (setq org-last-level 1)
12987 (org-init-section-numbers)
12988
12989 (find-file-noselect filename)
12990
12991 (setq lang-words (or (assoc language org-export-language-setup)
12992 (assoc "en" org-export-language-setup)))
12993 (if org-export-ascii-show-new-buffer
12994 (switch-to-buffer-other-window buffer)
12995 (set-buffer buffer))
12996 (erase-buffer)
12997 (fundamental-mode)
12998 ;; create local variables for all options, to make sure all called
12999 ;; functions get the correct information
13000 (mapcar (lambda (x)
13001 (set (make-local-variable (cdr x))
13002 (plist-get opt-plist (car x))))
13003 org-export-plist-vars)
13004 (set (make-local-variable 'org-odd-levels-only) odd)
13005 (setq umax (if arg (prefix-numeric-value arg)
13006 org-export-headline-levels))
13007
13008 ;; File header
13009 (if title (org-insert-centered title ?=))
13010 (insert "\n")
13011 (if (or author email)
13012 (insert (concat (nth 1 lang-words) ": " (or author "")
13013 (if email (concat " <" email ">") "")
13014 "\n")))
13015 (if (and date time)
13016 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
13017 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
13018
13019 (insert "\n\n")
13020
13021 (if org-export-with-toc
13022 (progn
13023 (insert (nth 3 lang-words) "\n"
13024 (make-string (length (nth 3 lang-words)) ?=) "\n")
13025 (mapcar '(lambda (line)
13026 (if (string-match org-todo-line-regexp
13027 line)
13028 ;; This is a headline
13029 (progn
13030 (setq level (- (match-end 1) (match-beginning 1))
13031 level (org-tr-level level)
13032 txt (match-string 3 line)
13033 todo
13034 (or (and org-export-mark-todo-in-toc
13035 (match-beginning 2)
13036 (not (equal (match-string 2 line)
13037 org-done-string)))
13038 ; TODO, not DONE
13039 (and org-export-mark-todo-in-toc
13040 (= level umax)
13041 (org-search-todo-below
13042 line lines level))))
13043 (setq txt (org-html-expand-for-ascii txt))
13044
13045 (if org-export-with-section-numbers
13046 (setq txt (concat (org-section-number level)
13047 " " txt)))
13048 (if (<= level umax)
13049 (progn
13050 (insert
13051 (make-string (* (1- level) 4) ?\ )
13052 (format (if todo "%s (*)\n" "%s\n") txt))
13053 (setq org-last-level level))
13054 ))))
13055 lines)))
13056
13057 (org-init-section-numbers)
13058 (while (setq line (pop lines))
13059 ;; Remove the quoted HTML tags.
13060 (setq line (org-html-expand-for-ascii line))
13061 ;; Remove targets
13062 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
13063 (setq line (replace-match "" t t line)))
13064 ;; Replace internal links
13065 (while (string-match org-bracket-link-regexp line)
13066 (setq line (replace-match
13067 (if (match-end 3) "[\\3]" "[\\1]")
13068 t nil line)))
13069 (cond
13070 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
13071 ;; a Headline
13072 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
13073 txt (match-string 2 line))
13074 (org-ascii-level-start level txt umax lines))
13075 (t
13076 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
13077 (normal-mode)
13078 (save-buffer)
13079 ;; remove display and invisible chars
13080 (let (beg end s)
13081 (goto-char (point-min))
13082 (while (setq beg (next-single-property-change (point) 'display))
13083 (setq end (next-single-property-change beg 'display))
13084 (delete-region beg end)
13085 (goto-char beg)
13086 (insert "=>"))
13087 (goto-char (point-min))
13088 (while (setq beg (next-single-property-change (point) 'org-cwidth))
13089 (setq end (next-single-property-change beg 'org-cwidth))
13090 (delete-region beg end)
13091 (goto-char beg)))
13092 (goto-char (point-min))))
13093
13094 (defun org-search-todo-below (line lines level)
13095 "Search the subtree below LINE for any TODO entries."
13096 (let ((rest (cdr (memq line lines)))
13097 (re org-todo-line-regexp)
13098 line lv todo)
13099 (catch 'exit
13100 (while (setq line (pop rest))
13101 (if (string-match re line)
13102 (progn
13103 (setq lv (- (match-end 1) (match-beginning 1))
13104 todo (and (match-beginning 2)
13105 (not (equal (match-string 2 line)
13106 org-done-string))))
13107 ; TODO, not DONE
13108 (if (<= lv level) (throw 'exit nil))
13109 (if todo (throw 'exit t))))))))
13110
13111 (defun org-html-expand-for-ascii (line)
13112 "Handle quoted HTML for ASCII export."
13113 (if org-export-html-expand
13114 (while (string-match "@<[^<>\n]*>" line)
13115 ;; We just remove the tags for now.
13116 (setq line (replace-match "" nil nil line))))
13117 line)
13118
13119 (defun org-insert-centered (s &optional underline)
13120 "Insert the string S centered and underline it with character UNDERLINE."
13121 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
13122 (insert (make-string ind ?\ ) s "\n")
13123 (if underline
13124 (insert (make-string ind ?\ )
13125 (make-string (string-width s) underline)
13126 "\n"))))
13127
13128 (defun org-ascii-level-start (level title umax &optional lines)
13129 "Insert a new level in ASCII export."
13130 (let (char (n (- level umax 1)) (ind 0))
13131 (if (> level umax)
13132 (progn
13133 (insert (make-string (* 2 n) ?\ )
13134 (char-to-string (nth (% n (length org-export-ascii-bullets))
13135 org-export-ascii-bullets))
13136 " " title "\n")
13137 ;; find the indentation of the next non-empty line
13138 (catch 'stop
13139 (while lines
13140 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
13141 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
13142 (throw 'stop (setq ind (org-get-indentation (car lines)))))
13143 (pop lines)))
13144 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
13145 (if (or (not (equal (char-before) ?\n))
13146 (not (equal (char-before (1- (point))) ?\n)))
13147 (insert "\n"))
13148 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
13149 (if org-export-with-section-numbers
13150 (setq title (concat (org-section-number level) " " title)))
13151 (insert title "\n" (make-string (string-width title) char) "\n")
13152 (setq org-ascii-current-indentation '(0 . 0)))))
13153
13154 (defun org-export-visible (type arg)
13155 "Create a copy of the visible part of the current buffer, and export it.
13156 The copy is created in a temporary buffer and removed after use.
13157 TYPE is the final key (as a string) of the `C-c C-x' key sequence that will
13158 run the export command - in interactive use, the command prompts for this
13159 key. As a special case, if the you type SPC at the prompt, the temporary
13160 org-mode file will not be removed but presented to you so that you can
13161 continue to use it. The prefix arg ARG is passed through to the exporting
13162 command."
13163 (interactive
13164 (list (progn
13165 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
13166 (read-char-exclusive))
13167 current-prefix-arg))
13168 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
13169 (error "Invalid export key"))
13170 (let* ((binding (cdr (assoc type
13171 '((?a . org-export-as-ascii)
13172 (?\C-a . org-export-as-ascii)
13173 (?b . org-export-as-html-and-open)
13174 (?\C-b . org-export-as-html-and-open)
13175 (?h . org-export-as-html)
13176 (?x . org-export-as-xoxo)))))
13177 (keepp (equal type ?\ ))
13178 (file buffer-file-name)
13179 (buffer (get-buffer-create "*Org Export Visible*"))
13180 s e)
13181 (with-current-buffer buffer (erase-buffer))
13182 (save-excursion
13183 (setq s (goto-char (point-min)))
13184 (while (not (= (point) (point-max)))
13185 (goto-char (org-find-invisible))
13186 (append-to-buffer buffer s (point))
13187 (setq s (goto-char (org-find-visible))))
13188 (goto-char (point-min))
13189 (unless keepp
13190 ;; Copy all comment lines to the end, to make sure #+ settings are
13191 ;; still available for the second export step. Kind of a hack, but
13192 ;; does do the trick.
13193 (if (looking-at "#[^\r\n]*")
13194 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
13195 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
13196 (append-to-buffer buffer (1+ (match-beginning 0))
13197 (min (point-max) (1+ (match-end 0))))))
13198 (set-buffer buffer)
13199 (let ((buffer-file-name file)
13200 (org-inhibit-startup t))
13201 (org-mode)
13202 (show-all)
13203 (unless keepp (funcall binding arg))))
13204 (if (not keepp)
13205 (kill-buffer buffer)
13206 (switch-to-buffer-other-window buffer)
13207 (goto-char (point-min)))))
13208
13209 (defun org-find-visible ()
13210 (if (featurep 'noutline)
13211 (let ((s (point)))
13212 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13213 (get-char-property s 'invisible)))
13214 s)
13215 (skip-chars-forward "^\n")
13216 (point)))
13217 (defun org-find-invisible ()
13218 (if (featurep 'noutline)
13219 (let ((s (point)))
13220 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13221 (not (get-char-property s 'invisible))))
13222 s)
13223 (skip-chars-forward "^\r")
13224 (point)))
13225
13226
13227 ;; HTML
13228
13229 (defun org-get-current-options ()
13230 "Return a string with current options as keyword options.
13231 Does include HTML export options as well as TODO and CATEGORY stuff."
13232 (format
13233 "#+TITLE: %s
13234 #+AUTHOR: %s
13235 #+EMAIL: %s
13236 #+LANGUAGE: %s
13237 #+TEXT: Some descriptive text to be emitted. Several lines OK.
13238 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
13239 #+CATEGORY: %s
13240 #+SEQ_TODO: %s
13241 #+TYP_TODO: %s
13242 #+STARTUP: %s %s %s %s %s %s
13243 #+TAGS: %s
13244 #+ARCHIVE: %s
13245 "
13246 (buffer-name) (user-full-name) user-mail-address org-export-default-language
13247 org-export-headline-levels
13248 org-export-with-section-numbers
13249 org-export-with-toc
13250 org-export-preserve-breaks
13251 org-export-html-expand
13252 org-export-with-fixed-width
13253 org-export-with-tables
13254 org-export-with-sub-superscripts
13255 org-export-with-emphasize
13256 org-export-with-TeX-macros
13257 (file-name-nondirectory buffer-file-name)
13258 (if (equal org-todo-interpretation 'sequence)
13259 (mapconcat 'identity org-todo-keywords " ")
13260 "TODO FEEDBACK VERIFY DONE")
13261 (if (equal org-todo-interpretation 'type)
13262 (mapconcat 'identity org-todo-keywords " ")
13263 "Me Jason Marie DONE")
13264 (cdr (assoc org-startup-folded
13265 '((nil . "showall") (t . "overview") (content . "content"))))
13266 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
13267 (if org-odd-levels-only "odd" "oddeven")
13268 (if org-hide-leading-stars "hidestars" "showstars")
13269 (if org-startup-align-all-tables "align" "noalign")
13270 (if org-log-done "logging" "nologging")
13271 (if org-tag-alist (mapconcat 'car org-tag-alist " ") "")
13272 org-archive-location
13273 ))
13274
13275 (defun org-insert-export-options-template ()
13276 "Insert into the buffer a template with information for exporting."
13277 (interactive)
13278 (if (not (bolp)) (newline))
13279 (let ((s (org-get-current-options)))
13280 (and (string-match "#\\+CATEGORY" s)
13281 (setq s (substring s 0 (match-beginning 0))))
13282 (insert s)))
13283
13284 (defun org-toggle-fixed-width-section (arg)
13285 "Toggle the fixed-width export.
13286 If there is no active region, the QUOTE keyword at the current headline is
13287 inserted or removed. When present, it causes the text between this headline
13288 and the next to be exported as fixed-width text, and unmodified.
13289 If there is an active region, this command adds or removes a colon as the
13290 first character of this line. If the first character of a line is a colon,
13291 this line is also exported in fixed-width font."
13292 (interactive "P")
13293 (let* ((cc 0)
13294 (regionp (org-region-active-p))
13295 (beg (if regionp (region-beginning) (point)))
13296 (end (if regionp (region-end)))
13297 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13298 (re "[ \t]*\\(:\\)")
13299 off)
13300 (if regionp
13301 (save-excursion
13302 (goto-char beg)
13303 (setq cc (current-column))
13304 (beginning-of-line 1)
13305 (setq off (looking-at re))
13306 (while (> nlines 0)
13307 (setq nlines (1- nlines))
13308 (beginning-of-line 1)
13309 (cond
13310 (arg
13311 (move-to-column cc t)
13312 (insert ":\n")
13313 (forward-line -1))
13314 ((and off (looking-at re))
13315 (replace-match "" t t nil 1))
13316 ((not off) (move-to-column cc t) (insert ":")))
13317 (forward-line 1)))
13318 (save-excursion
13319 (org-back-to-heading)
13320 (if (looking-at (concat outline-regexp
13321 "\\( +\\<" org-quote-string "\\>\\)"))
13322 (replace-match "" t t nil 1)
13323 (if (looking-at outline-regexp)
13324 (progn
13325 (goto-char (match-end 0))
13326 (insert " " org-quote-string))))))))
13327
13328 (defun org-export-as-html-and-open (arg)
13329 "Export the outline as HTML and immediately open it with a browser.
13330 If there is an active region, export only the region.
13331 The prefix ARG specifies how many levels of the outline should become
13332 headlines. The default is 3. Lower levels will become bulleted lists."
13333 (interactive "P")
13334 (org-export-as-html arg 'hidden)
13335 (org-open-file buffer-file-name))
13336
13337 (defun org-export-as-html-batch ()
13338 "Call `org-export-as-html', may be used in batch processing as
13339 emacs --batch
13340 --load=$HOME/lib/emacs/org.el
13341 --eval \"(setq org-export-headline-levels 2)\"
13342 --visit=MyFile --funcall org-export-as-html-batch"
13343 (org-export-as-html org-export-headline-levels 'hidden))
13344
13345 (defun org-export-as-html (arg &optional hidden ext-plist)
13346 "Export the outline as a pretty HTML file.
13347 If there is an active region, export only the region.
13348 The prefix ARG specifies how many levels of the outline should become
13349 headlines. The default is 3. Lower levels will become bulleted lists.
13350 When HIDDEN is non-nil, don't display the HTML buffer.
13351 EXT-PLIST is a property list with external parameters overriding
13352 org-mode's default settings, but still inferior to file-local settings."
13353 (interactive "P")
13354 (setq-default org-todo-line-regexp org-todo-line-regexp)
13355 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
13356 (setq-default org-done-string org-done-string)
13357 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13358 ext-plist
13359 (org-infile-export-plist)))
13360
13361 (style (plist-get opt-plist :style))
13362 (link-validate (plist-get opt-plist :link-validation-function))
13363 valid
13364 (odd org-odd-levels-only)
13365 (region-p (org-region-active-p))
13366 (region
13367 (buffer-substring
13368 (if region-p (region-beginning) (point-min))
13369 (if region-p (region-end) (point-max))))
13370 (all_lines
13371 (org-skip-comments (org-split-string
13372 (org-cleaned-string-for-export
13373 region :emph-multiline)
13374 "[\r\n]")))
13375 (lines (org-export-find-first-heading-line all_lines))
13376 (level 0) (line "") (origline "") txt todo
13377 (umax nil)
13378 (filename (concat (file-name-as-directory
13379 (org-export-directory :html opt-plist))
13380 (file-name-sans-extension
13381 (file-name-nondirectory buffer-file-name))
13382 ".html"))
13383 (current-dir (file-name-directory buffer-file-name))
13384 (buffer (find-file-noselect filename))
13385 (levels-open (make-vector org-level-max nil))
13386 (date (format-time-string "%Y/%m/%d" (current-time)))
13387 (time (format-time-string "%X" (org-current-time)))
13388 (author (plist-get opt-plist :author))
13389 (title (or (plist-get opt-plist :title)
13390 (file-name-sans-extension
13391 (file-name-nondirectory buffer-file-name))))
13392 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
13393 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
13394 (inquote nil)
13395 (infixed nil)
13396 (in-local-list nil)
13397 (local-list-num nil)
13398 (local-list-indent nil)
13399 (llt org-plain-list-ordered-item-terminator)
13400 (email (plist-get opt-plist :email))
13401 (language (plist-get opt-plist :language))
13402 (text (plist-get opt-plist :text))
13403 (lang-words nil)
13404 (target-alist nil) tg
13405 (head-count 0) cnt
13406 (start 0)
13407 (coding-system (and (fboundp 'coding-system-get)
13408 (boundp 'buffer-file-coding-system)
13409 buffer-file-coding-system))
13410 (coding-system-for-write (or coding-system coding-system-for-write))
13411 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
13412 (charset (and coding-system
13413 (coding-system-get coding-system 'mime-charset)))
13414 table-open type
13415 table-buffer table-orig-buffer
13416 ind start-is-num starter
13417 rpl path desc descp desc1 desc2 link
13418 )
13419 (message "Exporting...")
13420
13421 (setq org-last-level 1)
13422 (org-init-section-numbers)
13423
13424 ;; Get the language-dependent settings
13425 (setq lang-words (or (assoc language org-export-language-setup)
13426 (assoc "en" org-export-language-setup)))
13427
13428 ;; Switch to the output buffer
13429 (if (or hidden (not org-export-html-show-new-buffer))
13430 (set-buffer buffer)
13431 (switch-to-buffer-other-window buffer))
13432 (erase-buffer)
13433 (fundamental-mode)
13434 (let ((case-fold-search nil)
13435 (org-odd-levels-only odd))
13436 ;; create local variables for all options, to make sure all called
13437 ;; functions get the correct information
13438 (mapcar (lambda (x)
13439 (set (make-local-variable (cdr x))
13440 (plist-get opt-plist (car x))))
13441 org-export-plist-vars)
13442 (setq umax (if arg (prefix-numeric-value arg)
13443 org-export-headline-levels))
13444
13445 ;; File header
13446 (insert (format
13447 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
13448 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
13449 <html xmlns=\"http://www.w3.org/1999/xhtml\"
13450 lang=\"%s\" xml:lang=\"%s\">
13451 <head>
13452 <title>%s</title>
13453 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
13454 <meta name=\"generator\" content=\"Org-mode\"/>
13455 <meta name=\"generated\" content=\"%s %s\"/>
13456 <meta name=\"author\" content=\"%s\"/>
13457 %s
13458 </head><body>
13459 "
13460 language language (org-html-expand title) (or charset "iso-8859-1")
13461 date time author style))
13462
13463
13464 (insert (or (plist-get opt-plist :preamble) ""))
13465
13466 (when (plist-get opt-plist :auto-preamble)
13467 (if title (insert (concat "<h1 class=\"title\">"
13468 (org-html-expand title) "</h1>\n")))
13469
13470 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
13471
13472 (if org-export-with-toc
13473 (progn
13474 (insert (format "<h2>%s</h2>\n" (nth 3 lang-words)))
13475 (insert "<ul>\n<li>")
13476 (setq lines
13477 (mapcar '(lambda (line)
13478 (if (string-match org-todo-line-regexp line)
13479 ;; This is a headline
13480 (progn
13481 (setq level (- (match-end 1) (match-beginning 1))
13482 level (org-tr-level level)
13483 txt (save-match-data
13484 (org-html-expand
13485 (org-html-cleanup-toc-line
13486 (match-string 3 line))))
13487 todo
13488 (or (and org-export-mark-todo-in-toc
13489 (match-beginning 2)
13490 (not (equal (match-string 2 line)
13491 org-done-string)))
13492 ; TODO, not DONE
13493 (and org-export-mark-todo-in-toc
13494 (= level umax)
13495 (org-search-todo-below
13496 line lines level))))
13497 (if org-export-with-section-numbers
13498 (setq txt (concat (org-section-number level)
13499 " " txt)))
13500 (if (<= level umax)
13501 (progn
13502 (setq head-count (+ head-count 1))
13503 (if (> level org-last-level)
13504 (progn
13505 (setq cnt (- level org-last-level))
13506 (while (>= (setq cnt (1- cnt)) 0)
13507 (insert "\n<ul>\n<li>"))
13508 (insert "\n")))
13509 (if (< level org-last-level)
13510 (progn
13511 (setq cnt (- org-last-level level))
13512 (while (>= (setq cnt (1- cnt)) 0)
13513 (insert "</li>\n</ul>"))
13514 (insert "\n")))
13515 ;; Check for targets
13516 (while (string-match org-target-regexp line)
13517 (setq tg (match-string 1 line)
13518 line (replace-match
13519 (concat "@<span class=\"target\">" tg "@</span> ")
13520 t t line))
13521 (push (cons (org-solidify-link-text tg)
13522 (format "sec-%d" head-count))
13523 target-alist))
13524 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
13525 (setq txt (replace-match "" t t txt)))
13526 (insert
13527 (format
13528 (if todo
13529 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
13530 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
13531 head-count txt))
13532
13533 (setq org-last-level level))
13534 )))
13535 line)
13536 lines))
13537 (while (> org-last-level 0)
13538 (setq org-last-level (1- org-last-level))
13539 (insert "</li>\n</ul>\n"))
13540 ))
13541 (setq head-count 0)
13542 (org-init-section-numbers)
13543
13544 (while (setq line (pop lines) origline line)
13545 (catch 'nextline
13546
13547 ;; end of quote section?
13548 (when (and inquote (string-match "^\\*+" line))
13549 (insert "</pre>\n")
13550 (setq inquote nil))
13551 ;; inside a quote section?
13552 (when inquote
13553 (insert (org-html-protect line) "\n")
13554 (throw 'nextline nil))
13555
13556 ;; verbatim lines
13557 (when (and org-export-with-fixed-width
13558 (string-match "^[ \t]*:\\(.*\\)" line))
13559 (when (not infixed)
13560 (setq infixed t)
13561 (insert "<pre>\n"))
13562 (insert (org-html-protect (match-string 1 line)) "\n")
13563 (when (and lines
13564 (not (string-match "^[ \t]*\\(:.*\\)"
13565 (car lines))))
13566 (setq infixed nil)
13567 (insert "</pre>\n"))
13568 (throw 'nextline nil))
13569
13570
13571 ;; make targets to anchors
13572 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
13573 (cond
13574 ((match-end 2)
13575 (setq line (replace-match
13576 (concat "@<a name=\""
13577 (org-solidify-link-text (match-string 1 line))
13578 "\">\\nbsp@</a>")
13579 t t line)))
13580 ((and org-export-with-toc (equal (string-to-char line) ?*))
13581 (setq line (replace-match
13582 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
13583 ; (concat "@<i>" (match-string 1 line) "@</i> ")
13584 t t line)))
13585 (t
13586 (setq line (replace-match
13587 (concat "@<a name=\""
13588 (org-solidify-link-text (match-string 1 line))
13589 "\" class=\"target\">" (match-string 1 line) "@</a> ")
13590 t t line)))))
13591
13592 (setq line (org-html-handle-time-stamps line))
13593
13594 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
13595 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
13596 ;; Also handle sub_superscripts and checkboxes
13597 (setq line (org-html-expand line))
13598
13599 ;; Format the links
13600 (setq start 0)
13601 (while (string-match org-bracket-link-analytic-regexp line start)
13602 (setq start (match-beginning 0))
13603 (setq type (if (match-end 2) (match-string 2 line) "internal"))
13604 (setq path (match-string 3 line))
13605 (setq desc1 (if (match-end 5) (match-string 5 line))
13606 desc2 (if (match-end 2) (concat type ":" path) path)
13607 descp (and desc1 (not (equal desc1 desc2)))
13608 desc (or desc1 desc2))
13609 ;; FIXME: do we need to unescape here somewhere?
13610 (cond
13611 ((equal type "internal")
13612 (setq rpl
13613 (concat
13614 "<a href=\"#"
13615 (org-solidify-link-text path target-alist)
13616 "\">" desc "</a>")))
13617 ((member type '("http" "https" "ftp" "mailto" "news"))
13618 ;; standard URL
13619 (setq link (concat type ":" path))
13620 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
13621 ((string= type "file")
13622 ;; FILE link
13623 (let* ((filename path)
13624 (abs-p (file-name-absolute-p filename))
13625 thefile file-is-image-p search)
13626 (save-match-data
13627 (if (string-match "::\\(.*\\)" filename)
13628 (setq search (match-string 1 filename)
13629 filename (replace-match "" t nil filename)))
13630 (setq valid
13631 (if (functionp link-validate)
13632 (funcall link-validate filename current-dir)
13633 t))
13634 (setq file-is-image-p
13635 (string-match (org-image-file-name-regexp) filename))
13636 (setq thefile (if abs-p (expand-file-name filename) filename))
13637 (when (and org-export-html-link-org-files-as-html
13638 (string-match "\\.org$" thefile))
13639 (setq thefile (concat (substring thefile 0
13640 (match-beginning 0))
13641 ".html"))
13642 (if (and search
13643 ;; make sure this is can be used as target search
13644 (not (string-match "^[0-9]*$" search))
13645 (not (string-match "^\\*" search))
13646 (not (string-match "^/.*/$" search)))
13647 (setq thefile (concat thefile "#"
13648 (org-solidify-link-text
13649 (org-link-unescape search)))))
13650 (when (string-match "^file:" desc)
13651 (setq desc (replace-match "" t t desc))
13652 (if (string-match "\\.org$" desc)
13653 (setq desc (replace-match "" t t desc))))))
13654 (setq rpl (if (and file-is-image-p
13655 (or (eq t org-export-html-inline-images)
13656 (and org-export-html-inline-images
13657 (not descp))))
13658 (concat "<img src=\"" thefile "\"/>")
13659 (concat "<a href=\"" thefile "\">" desc "</a>")))
13660 (if (not valid) (setq rpl desc))))
13661 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
13662 (setq rpl (concat "<i>&lt;" type ":"
13663 (save-match-data (org-link-unescape path))
13664 "&gt;</i>"))))
13665 (setq line (replace-match rpl t t line)
13666 start (+ start (length rpl))))
13667 ;; TODO items
13668 (if (and (string-match org-todo-line-regexp line)
13669 (match-beginning 2))
13670 (if (equal (match-string 2 line) org-done-string)
13671 (setq line (replace-match
13672 "<span class=\"done\">\\2</span>"
13673 t nil line 2))
13674 (setq line (replace-match "<span class=\"todo\">\\2</span>"
13675 t nil line 2))))
13676
13677 (cond
13678 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
13679 ;; This is a headline
13680 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
13681 txt (match-string 2 line))
13682 (if (string-match quote-re0 txt)
13683 (setq txt (replace-match "" t t txt)))
13684 (if (<= level umax) (setq head-count (+ head-count 1)))
13685 (when in-local-list
13686 ;; Close any local lists before inserting a new header line
13687 (while local-list-num
13688 (org-close-li)
13689 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
13690 (pop local-list-num))
13691 (setq local-list-indent nil
13692 in-local-list nil))
13693 (org-html-level-start level txt umax
13694 (and org-export-with-toc (<= level umax))
13695 head-count)
13696 ;; QUOTES
13697 (when (string-match quote-re line)
13698 (insert "<pre>")
13699 (setq inquote t)))
13700
13701 ((and org-export-with-tables
13702 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
13703 (if (not table-open)
13704 ;; New table starts
13705 (setq table-open t table-buffer nil table-orig-buffer nil))
13706 ;; Accumulate lines
13707 (setq table-buffer (cons line table-buffer)
13708 table-orig-buffer (cons origline table-orig-buffer))
13709 (when (or (not lines)
13710 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
13711 (car lines))))
13712 (setq table-open nil
13713 table-buffer (nreverse table-buffer)
13714 table-orig-buffer (nreverse table-orig-buffer))
13715 (org-close-par-maybe)
13716 (insert (org-format-table-html table-buffer table-orig-buffer))))
13717 (t
13718 ;; Normal lines
13719 (when (string-match
13720 (cond
13721 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
13722 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
13723 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
13724 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
13725 line)
13726 (setq ind (org-get-string-indentation line)
13727 start-is-num (match-beginning 4)
13728 starter (if (match-beginning 2)
13729 (substring (match-string 2 line) 0 -1))
13730 line (substring line (match-beginning 5)))
13731 (unless (string-match "[^ \t]" line)
13732 ;; empty line. Pretend indentation is large.
13733 (setq ind (1+ (or (car local-list-indent) 1))))
13734 (while (and in-local-list
13735 (or (and (= ind (car local-list-indent))
13736 (not starter))
13737 (< ind (car local-list-indent))))
13738 (org-close-li)
13739 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
13740 (pop local-list-num) (pop local-list-indent)
13741 (setq in-local-list local-list-indent))
13742 (cond
13743 ((and starter
13744 (or (not in-local-list)
13745 (> ind (car local-list-indent))))
13746 ;; Start new (level of ) list
13747 (org-close-par-maybe)
13748 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
13749 (push start-is-num local-list-num)
13750 (push ind local-list-indent)
13751 (setq in-local-list t))
13752 (starter
13753 ;; continue current list
13754 (org-close-li)
13755 (insert "<li>\n")))
13756 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
13757 (setq line
13758 (replace-match
13759 (if (equal (match-string 1 line) "X")
13760 "<b>[X]</b>"
13761 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
13762 t t line))))
13763
13764 ;; Empty lines start a new paragraph. If hand-formatted lists
13765 ;; are not fully interpreted, lines starting with "-", "+", "*"
13766 ;; also start a new paragraph.
13767 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
13768
13769 ;; Check if the line break needs to be conserved
13770 (cond
13771 ((string-match "\\\\\\\\[ \t]*$" line)
13772 (setq line (replace-match "<br/>" t t line)))
13773 (org-export-preserve-breaks
13774 (setq line (concat line "<br/>"))))
13775
13776 (insert line "\n")))))
13777
13778 ;; Properly close all local lists and other lists
13779 (when inquote (insert "</pre>\n"))
13780 (when in-local-list
13781 ;; Close any local lists before inserting a new header line
13782 (while local-list-num
13783 (org-close-li)
13784 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
13785 (pop local-list-num))
13786 (setq local-list-indent nil
13787 in-local-list nil))
13788 (org-html-level-start 1 nil umax
13789 (and org-export-with-toc (<= level umax))
13790 head-count)
13791
13792 (when (plist-get opt-plist :auto-postamble)
13793 (when author
13794 (insert "<p class=\"author\"> "
13795 (nth 1 lang-words) ": " author "\n")
13796 (when email
13797 (insert "<a href=\"mailto:" email "\">&lt;"
13798 email "&gt;</a>\n"))
13799 (insert "</p>\n"))
13800 (when (and date time)
13801 (insert "<p class=\"date\"> "
13802 (nth 2 lang-words) ": "
13803 date " " time "</p>\n")))
13804
13805 (if org-export-html-with-timestamp
13806 (insert org-export-html-html-helper-timestamp))
13807 (insert (or (plist-get opt-plist :postamble) ""))
13808 (insert "</body>\n</html>\n")
13809 (normal-mode)
13810 ;; remove empty paragraphs and lists
13811 (goto-char (point-min))
13812 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
13813 (replace-match ""))
13814 (goto-char (point-min))
13815 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
13816 (replace-match ""))
13817 (save-buffer)
13818 (goto-char (point-min)))))
13819
13820 (defun org-format-table-html (lines olines)
13821 "Find out which HTML converter to use and return the HTML code."
13822 (if (string-match "^[ \t]*|" (car lines))
13823 ;; A normal org table
13824 (org-format-org-table-html lines)
13825 ;; Table made by table.el - test for spanning
13826 (let* ((hlines (delq nil (mapcar
13827 (lambda (x)
13828 (if (string-match "^[ \t]*\\+-" x) x
13829 nil))
13830 lines)))
13831 (first (car hlines))
13832 (ll (and (string-match "\\S-+" first)
13833 (match-string 0 first)))
13834 (re (concat "^[ \t]*" (regexp-quote ll)))
13835 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
13836 hlines))))
13837 (if (and (not spanning)
13838 (not org-export-prefer-native-exporter-for-tables))
13839 ;; We can use my own converter with HTML conversions
13840 (org-format-table-table-html lines)
13841 ;; Need to use the code generator in table.el, with the original text.
13842 (org-format-table-table-html-using-table-generate-source olines)))))
13843
13844 (defun org-format-org-table-html (lines)
13845 "Format a table into HTML."
13846 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
13847 (setq lines (nreverse lines))
13848 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
13849 (setq lines (nreverse lines))
13850 (when org-export-table-remove-special-lines
13851 ;; Check if the table has a marking column. If yes remove the
13852 ;; column and the special lines
13853 (let* ((special
13854 (not
13855 (memq nil
13856 (mapcar
13857 (lambda (x)
13858 (or (string-match "^[ \t]*|-" x)
13859 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
13860 lines)))))
13861 (if special
13862 (setq lines
13863 (delq nil
13864 (mapcar
13865 (lambda (x)
13866 (if (string-match "^[ \t]*| *[!_^] *|" x)
13867 nil ; ignore this line
13868 (and (or (string-match "^[ \t]*|-+\\+" x)
13869 (string-match "^[ \t]*|[^|]*|" x))
13870 (replace-match "|" t t x))))
13871 lines))))))
13872
13873 (let ((head (and org-export-highlight-first-table-line
13874 (delq nil (mapcar
13875 (lambda (x) (string-match "^[ \t]*|-" x))
13876 (cdr lines)))))
13877 line fields html)
13878 (setq html (concat org-export-html-table-tag "\n"))
13879 (while (setq line (pop lines))
13880 (catch 'next-line
13881 (if (string-match "^[ \t]*|-" line)
13882 (progn
13883 (setq head nil) ;; head ends here, first time around
13884 ;; ignore this line
13885 (throw 'next-line t)))
13886 ;; Break the line into fields
13887 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
13888 (setq html (concat
13889 html
13890 "<tr>"
13891 (mapconcat (lambda (x)
13892 (if head
13893 (concat "<th>" x "</th>")
13894 (concat "<td>" x "</td>")))
13895 fields "")
13896 "</tr>\n"))))
13897 (setq html (concat html "</table>\n"))
13898 html))
13899
13900 (defun org-fake-empty-table-line (line)
13901 "Replace everything except \"|\" with spaces."
13902 (let ((i (length line))
13903 (newstr (copy-sequence line)))
13904 (while (> i 0)
13905 (setq i (1- i))
13906 (if (not (eq (aref newstr i) ?|))
13907 (aset newstr i ?\ )))
13908 newstr))
13909
13910 (defun org-format-table-table-html (lines)
13911 "Format a table generated by table.el into HTML.
13912 This conversion does *not* use `table-generate-source' from table.el.
13913 This has the advantage that Org-mode's HTML conversions can be used.
13914 But it has the disadvantage, that no cell- or row-spanning is allowed."
13915 (let (line field-buffer
13916 (head org-export-highlight-first-table-line)
13917 fields html empty)
13918 (setq html (concat org-export-html-table-tag "\n"))
13919 (while (setq line (pop lines))
13920 (setq empty "&nbsp;")
13921 (catch 'next-line
13922 (if (string-match "^[ \t]*\\+-" line)
13923 (progn
13924 (if field-buffer
13925 (progn
13926 (setq html (concat
13927 html
13928 "<tr>"
13929 (mapconcat
13930 (lambda (x)
13931 (if (equal x "") (setq x empty))
13932 (if head
13933 (concat "<th>" x "</th>\n")
13934 (concat "<td>" x "</td>\n")))
13935 field-buffer "\n")
13936 "</tr>\n"))
13937 (setq head nil)
13938 (setq field-buffer nil)))
13939 ;; Ignore this line
13940 (throw 'next-line t)))
13941 ;; Break the line into fields and store the fields
13942 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
13943 (if field-buffer
13944 (setq field-buffer (mapcar
13945 (lambda (x)
13946 (concat x "<br/>" (pop fields)))
13947 field-buffer))
13948 (setq field-buffer fields))))
13949 (setq html (concat html "</table>\n"))
13950 html))
13951
13952 (defun org-format-table-table-html-using-table-generate-source (lines)
13953 "Format a table into html, using `table-generate-source' from table.el.
13954 This has the advantage that cell- or row-spanning is allowed.
13955 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
13956 (require 'table)
13957 (with-current-buffer (get-buffer-create " org-tmp1 ")
13958 (erase-buffer)
13959 (insert (mapconcat 'identity lines "\n"))
13960 (goto-char (point-min))
13961 (if (not (re-search-forward "|[^+]" nil t))
13962 (error "Error processing table"))
13963 (table-recognize-table)
13964 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
13965 (table-generate-source 'html " org-tmp2 ")
13966 (set-buffer " org-tmp2 ")
13967 (buffer-substring (point-min) (point-max))))
13968
13969 (defun org-html-handle-time-stamps (s)
13970 "Format time stamps in string S, or remove them."
13971 (catch 'exit
13972 (let (r b)
13973 (while (string-match org-maybe-keyword-time-regexp s)
13974 ;; FIXME: is it good to never export CLOCK, or do we need control?
13975 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
13976 (throw 'exit ""))
13977 (or b (setq b (substring s 0 (match-beginning 0))))
13978 (if (not org-export-with-timestamps)
13979 (setq r (concat r (substring s 0 (match-beginning 0)))
13980 s (substring s (match-end 0)))
13981 (setq r (concat
13982 r (substring s 0 (match-beginning 0))
13983 (if (match-end 1)
13984 (format "@<span class=\"timestamp-kwd\">%s @</span>"
13985 (match-string 1 s)))
13986 (format " @<span class=\"timestamp\">%s@</span>"
13987 (substring (match-string 3 s) 1 -1)))
13988 s (substring s (match-end 0)))))
13989 ;; Line break if line started and ended with time stamp stuff
13990 (if (not r)
13991 s
13992 (setq r (concat r s))
13993 (unless (string-match "\\S-" (concat b s))
13994 (setq r (concat r "@<br/>")))
13995 r))))
13996
13997 (defun org-html-protect (s)
13998 ;; convert & to &amp;, < to &lt; and > to &gt;
13999 (let ((start 0))
14000 (while (string-match "&" s start)
14001 (setq s (replace-match "&amp;" t t s)
14002 start (1+ (match-beginning 0))))
14003 (while (string-match "<" s)
14004 (setq s (replace-match "&lt;" t t s)))
14005 (while (string-match ">" s)
14006 (setq s (replace-match "&gt;" t t s))))
14007 s)
14008
14009 (defun org-html-cleanup-toc-line (s)
14010 "Remove tags and time staps from lines going into the toc."
14011 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
14012 (setq s (replace-match "" t t s)))
14013 (while (string-match org-maybe-keyword-time-regexp s)
14014 (setq s (replace-match "" t t s)))
14015 s)
14016
14017 (defun org-html-expand (string)
14018 "Prepare STRING for HTML export. Applies all active conversions.
14019 If there are links in the string, don't modify these."
14020 (let* (m s l res)
14021 (while (setq m (string-match org-bracket-link-regexp string))
14022 (setq s (substring string 0 m)
14023 l (match-string 0 string)
14024 string (substring string (match-end 0)))
14025 (push (org-html-do-expand s) res)
14026 (push l res))
14027 (push (org-html-do-expand string) res)
14028 (apply 'concat (nreverse res))))
14029
14030 (defun org-html-do-expand (s)
14031 "Apply all active conversions to translate special ASCII to HTML."
14032 (setq s (org-html-protect s))
14033 (if org-export-html-expand
14034 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
14035 (setq s (replace-match "<\\1>" t nil s))))
14036 (if org-export-with-emphasize
14037 (setq s (org-export-html-convert-emphasize s)))
14038 (if org-export-with-sub-superscripts
14039 (setq s (org-export-html-convert-sub-super s)))
14040 (if org-export-with-TeX-macros
14041 (let ((start 0) wd ass)
14042 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
14043 (setq wd (match-string 1 s))
14044 (if (setq ass (assoc wd org-html-entities))
14045 (setq s (replace-match (or (cdr ass)
14046 (concat "&" (car ass) ";"))
14047 t t s))
14048 (setq start (+ start (length wd)))))))
14049 s)
14050
14051 (defun org-create-multibrace-regexp (left right n)
14052 "Create a regular expression which will match a balanced sexp.
14053 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
14054 as single character strings.
14055 The regexp returned will match the entire expression including the
14056 delimiters. It will also define a single group which contains the
14057 match except for the outermost delimiters. The maximum depth of
14058 stacked delimiters is N. Escaping delimiters is not possible."
14059 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
14060 (or "\\|")
14061 (re nothing)
14062 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
14063 (while (> n 1)
14064 (setq n (1- n)
14065 re (concat re or next)
14066 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
14067 (concat left "\\(" re "\\)" right)))
14068
14069 (defvar org-match-substring-regexp
14070 (concat
14071 "\\([^\\]\\)\\([_^]\\)\\("
14072 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
14073 "\\|"
14074 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
14075 "\\|"
14076 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
14077 "The regular expression matching a sub- or superscript.")
14078
14079 (defun org-export-html-convert-sub-super (string)
14080 "Convert sub- and superscripts in STRING to HTML."
14081 (let (key c)
14082 (while (string-match org-match-substring-regexp string)
14083 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
14084 (setq c (or (match-string 8 string)
14085 (match-string 6 string)
14086 (match-string 5 string)))
14087 (setq string (replace-match
14088 (concat (match-string 1 string)
14089 "<" key ">" c "</" key ">")
14090 t t string)))
14091 (while (string-match "\\\\\\([_^]\\)" string)
14092 (setq string (replace-match (match-string 1 string) t t string))))
14093 string)
14094
14095 (defun org-export-html-convert-emphasize (string)
14096 "Apply emphasis."
14097 (while (string-match org-emph-re string)
14098 (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)))
14099 string)
14100
14101 (defvar org-par-open nil)
14102 (defun org-open-par ()
14103 "Insert <p>, but first close previous paragraph if any."
14104 (org-close-par-maybe)
14105 (insert "\n<p>")
14106 (setq org-par-open t))
14107 (defun org-close-par-maybe ()
14108 "Close paragraph if there is one open."
14109 (when org-par-open
14110 (insert "</p>")
14111 (setq org-par-open nil)))
14112 (defun org-close-li ()
14113 "Close <li> if necessary."
14114 (org-close-par-maybe)
14115 (insert "</li>\n"))
14116 ; (when (save-excursion
14117 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
14118 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
14119 ; (insert "</li>"))))
14120
14121 (defun org-html-level-start (level title umax with-toc head-count)
14122 "Insert a new level in HTML export.
14123 When TITLE is nil, just close all open levels."
14124 (org-close-par-maybe)
14125 (let ((l (1+ (max level umax))))
14126 (while (<= l org-level-max)
14127 (if (aref levels-open (1- l))
14128 (progn
14129 (org-html-level-close l)
14130 (aset levels-open (1- l) nil)))
14131 (setq l (1+ l)))
14132 (when title
14133 ;; If title is nil, this means this function is called to close
14134 ;; all levels, so the rest is done only if title is given
14135 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14136 (setq title (replace-match
14137 (if org-export-with-tags
14138 (save-match-data
14139 (concat
14140 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
14141 (mapconcat 'identity (org-split-string
14142 (match-string 1 title) ":")
14143 "&nbsp;")
14144 "</span>"))
14145 "")
14146 t t title)))
14147 (if (> level umax)
14148 (progn
14149 (if (aref levels-open (1- level))
14150 (progn
14151 (org-close-li)
14152 (insert "<li>" title "<br/>\n"))
14153 (aset levels-open (1- level) t)
14154 (org-close-par-maybe)
14155 (insert "<ul>\n<li>" title "<br/>\n")))
14156 (if org-export-with-section-numbers
14157 (setq title (concat (org-section-number level) " " title)))
14158 (setq level (+ level 1))
14159 (if with-toc
14160 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
14161 level head-count title level))
14162 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
14163 (org-open-par)))))
14164
14165 (defun org-html-level-close (&rest args)
14166 "Terminate one level in HTML export."
14167 (org-close-li)
14168 (insert "</ul>"))
14169
14170 ;; Variable holding the vector with section numbers
14171 (defvar org-section-numbers (make-vector org-level-max 0))
14172
14173 (defun org-init-section-numbers ()
14174 "Initialize the vector for the section numbers."
14175 (let* ((level -1)
14176 (numbers (nreverse (org-split-string "" "\\.")))
14177 (depth (1- (length org-section-numbers)))
14178 (i depth) number-string)
14179 (while (>= i 0)
14180 (if (> i level)
14181 (aset org-section-numbers i 0)
14182 (setq number-string (or (car numbers) "0"))
14183 (if (string-match "\\`[A-Z]\\'" number-string)
14184 (aset org-section-numbers i
14185 (- (string-to-char number-string) ?A -1))
14186 (aset org-section-numbers i (string-to-number number-string)))
14187 (pop numbers))
14188 (setq i (1- i)))))
14189
14190 (defun org-section-number (&optional level)
14191 "Return a string with the current section number.
14192 When LEVEL is non-nil, increase section numbers on that level."
14193 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
14194 (when level
14195 (when (> level -1)
14196 (aset org-section-numbers
14197 level (1+ (aref org-section-numbers level))))
14198 (setq idx (1+ level))
14199 (while (<= idx depth)
14200 (if (not (= idx 1))
14201 (aset org-section-numbers idx 0))
14202 (setq idx (1+ idx))))
14203 (setq idx 0)
14204 (while (<= idx depth)
14205 (setq n (aref org-section-numbers idx))
14206 (setq string (concat string (if (not (string= string "")) "." "")
14207 (int-to-string n)))
14208 (setq idx (1+ idx)))
14209 (save-match-data
14210 (if (string-match "\\`\\([@0]\\.\\)+" string)
14211 (setq string (replace-match "" t nil string)))
14212 (if (string-match "\\(\\.0\\)+\\'" string)
14213 (setq string (replace-match "" t nil string))))
14214 string))
14215
14216
14217 ;;;###autoload
14218 (defun org-export-icalendar-this-file ()
14219 "Export current file as an iCalendar file.
14220 The iCalendar file will be located in the same directory as the Org-mode
14221 file, but with extension `.ics'."
14222 (interactive)
14223 (org-export-icalendar nil buffer-file-name))
14224
14225 (defun org-export-as-xoxo-insert-into (buffer &rest output)
14226 (with-current-buffer buffer
14227 (apply 'insert output)))
14228
14229 (defun org-export-as-xoxo (&optional buffer)
14230 "Export the org buffer as XOXO.
14231 The XOXO buffer is named *xoxo-<source buffer name>*"
14232 (interactive (list (current-buffer)))
14233 ;; A quickie abstraction
14234
14235 ;; Output everything as XOXO
14236 (with-current-buffer (get-buffer buffer)
14237 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
14238 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14239 (org-infile-export-plist)))
14240 (filename (concat (file-name-as-directory
14241 (org-export-directory :xoxo opt-plist))
14242 (file-name-sans-extension
14243 (file-name-nondirectory buffer-file-name))
14244 ".html"))
14245 (out (find-file-noselect filename))
14246 (last-level 1)
14247 (hanging-li nil))
14248 ;; Check the output buffer is empty.
14249 (with-current-buffer out (erase-buffer))
14250 ;; Kick off the output
14251 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
14252 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
14253 (let* ((hd (match-string-no-properties 1))
14254 (level (length hd))
14255 (text (concat
14256 (match-string-no-properties 2)
14257 (save-excursion
14258 (goto-char (match-end 0))
14259 (let ((str ""))
14260 (catch 'loop
14261 (while 't
14262 (forward-line)
14263 (if (looking-at "^[ \t]\\(.*\\)")
14264 (setq str (concat str (match-string-no-properties 1)))
14265 (throw 'loop str)))))))))
14266
14267 ;; Handle level rendering
14268 (cond
14269 ((> level last-level)
14270 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
14271
14272 ((< level last-level)
14273 (dotimes (- (- last-level level) 1)
14274 (if hanging-li
14275 (org-export-as-xoxo-insert-into out "</li>\n"))
14276 (org-export-as-xoxo-insert-into out "</ol>\n"))
14277 (when hanging-li
14278 (org-export-as-xoxo-insert-into out "</li>\n")
14279 (setq hanging-li nil)))
14280
14281 ((equal level last-level)
14282 (if hanging-li
14283 (org-export-as-xoxo-insert-into out "</li>\n")))
14284 )
14285
14286 (setq last-level level)
14287
14288 ;; And output the new li
14289 (setq hanging-li 't)
14290 (if (equal ?+ (elt text 0))
14291 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
14292 (org-export-as-xoxo-insert-into out "<li>" text))))
14293
14294 ;; Finally finish off the ol
14295 (dotimes (- last-level 1)
14296 (if hanging-li
14297 (org-export-as-xoxo-insert-into out "</li>\n"))
14298 (org-export-as-xoxo-insert-into out "</ol>\n"))
14299
14300 ;; Finish the buffer off and clean it up.
14301 (switch-to-buffer-other-window out)
14302 (indent-region (point-min) (point-max) nil)
14303 (save-buffer)
14304 (goto-char (point-min))
14305 )))
14306
14307 ;;;###autoload
14308 (defun org-export-icalendar-all-agenda-files ()
14309 "Export all files in `org-agenda-files' to iCalendar .ics files.
14310 Each iCalendar file will be located in the same directory as the Org-mode
14311 file, but with extension `.ics'."
14312 (interactive)
14313 (apply 'org-export-icalendar nil (org-agenda-files t)))
14314
14315 ;;;###autoload
14316 (defun org-export-icalendar-combine-agenda-files ()
14317 "Export all files in `org-agenda-files' to a single combined iCalendar file.
14318 The file is stored under the name `org-combined-agenda-icalendar-file'."
14319 (interactive)
14320 (apply 'org-export-icalendar t (org-agenda-files t)))
14321
14322 (defun org-export-icalendar (combine &rest files)
14323 "Create iCalendar files for all elements of FILES.
14324 If COMBINE is non-nil, combine all calendar entries into a single large
14325 file and store it under the name `org-combined-agenda-icalendar-file'."
14326 (save-excursion
14327 (let* ((dir (org-export-directory
14328 :ical (list :publishing-directory
14329 org-export-publishing-directory)))
14330 file ical-file ical-buffer category started org-agenda-new-buffers)
14331
14332 (when combine
14333 (setq ical-file
14334 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
14335 org-combined-agenda-icalendar-file
14336 (expand-file-name org-combined-agenda-icalendar-file dir))
14337 ical-buffer (org-get-agenda-file-buffer ical-file))
14338 (set-buffer ical-buffer) (erase-buffer))
14339 (while (setq file (pop files))
14340 (catch 'nextfile
14341 (org-check-agenda-file file)
14342 (set-buffer (org-get-agenda-file-buffer file))
14343 (unless combine
14344 (setq ical-file (concat (file-name-as-directory dir)
14345 (file-name-sans-extension
14346 (file-name-nondirectory buffer-file-name))
14347 ".ics"))
14348 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
14349 (with-current-buffer ical-buffer (erase-buffer)))
14350 (setq category (or org-category
14351 (file-name-sans-extension
14352 (file-name-nondirectory buffer-file-name))))
14353 (if (symbolp category) (setq category (symbol-name category)))
14354 (let ((standard-output ical-buffer))
14355 (if combine
14356 (and (not started) (setq started t)
14357 (org-start-icalendar-file org-icalendar-combined-name))
14358 (org-start-icalendar-file category))
14359 (org-print-icalendar-entries combine category)
14360 (when (or (and combine (not files)) (not combine))
14361 (org-finish-icalendar-file)
14362 (set-buffer ical-buffer)
14363 (save-buffer)
14364 (run-hooks 'org-after-save-iCalendar-file-hook)))))
14365 (org-release-buffers org-agenda-new-buffers))))
14366
14367 (defvar org-after-save-iCalendar-file-hook nil
14368 "Hook run after an iCalendar file has been saved.
14369 The iCalendar buffer is still current when this hook is run.
14370 A good way to use this is to tell a desktop calenndar application to re-read
14371 the iCalendar file.")
14372
14373 (defun org-print-icalendar-entries (&optional combine category)
14374 "Print iCalendar entries for the current Org-mode file to `standard-output'.
14375 When COMBINE is non nil, add the category to each line."
14376 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
14377 (dts (org-ical-ts-to-string
14378 (format-time-string (cdr org-time-stamp-formats) (current-time))
14379 "DTSTART"))
14380 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
14381 (save-excursion
14382 (goto-char (point-min))
14383 (while (re-search-forward org-ts-regexp nil t)
14384 (setq pos (match-beginning 0)
14385 ts (match-string 0)
14386 inc t
14387 hd (org-get-heading))
14388 (if (looking-at re2)
14389 (progn
14390 (goto-char (match-end 0))
14391 (setq ts2 (match-string 1) inc nil))
14392 (setq ts2 ts
14393 tmp (buffer-substring (max (point-min)
14394 (- pos org-ds-keyword-length))
14395 pos)
14396 deadlinep (string-match org-deadline-regexp tmp)
14397 scheduledp (string-match org-scheduled-regexp tmp)
14398 ;; donep (org-entry-is-done-p)
14399 ))
14400 (if (or (string-match org-tr-regexp hd)
14401 (string-match org-ts-regexp hd))
14402 (setq hd (replace-match "" t t hd)))
14403 (if combine
14404 (setq hd (concat hd " (category " category ")")))
14405 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
14406 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
14407 (princ (format "BEGIN:VEVENT
14408 %s
14409 %s
14410 SUMMARY:%s
14411 END:VEVENT\n"
14412 (org-ical-ts-to-string ts "DTSTART")
14413 (org-ical-ts-to-string ts2 "DTEND" inc)
14414 hd)))
14415 (when org-icalendar-include-todo
14416 (goto-char (point-min))
14417 (while (re-search-forward org-todo-line-regexp nil t)
14418 (setq state (match-string 1))
14419 (unless (equal state org-done-string)
14420 (setq hd (match-string 3))
14421 (if (string-match org-priority-regexp hd)
14422 (setq pri (string-to-char (match-string 2 hd))
14423 hd (concat (substring hd 0 (match-beginning 1))
14424 (substring hd (- (match-end 1)))))
14425 (setq pri org-default-priority))
14426 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
14427 (- org-lowest-priority ?A))))))
14428
14429 (princ (format "BEGIN:VTODO
14430 %s
14431 SUMMARY:%s
14432 SEQUENCE:1
14433 PRIORITY:%d
14434 END:VTODO\n"
14435 dts hd pri))))))))
14436
14437 (defun org-start-icalendar-file (name)
14438 "Start an iCalendar file by inserting the header."
14439 (let ((user user-full-name)
14440 (name (or name "unknown"))
14441 (timezone (cadr (current-time-zone))))
14442 (princ
14443 (format "BEGIN:VCALENDAR
14444 VERSION:2.0
14445 X-WR-CALNAME:%s
14446 PRODID:-//%s//Emacs with Org-mode//EN
14447 X-WR-TIMEZONE:%s
14448 CALSCALE:GREGORIAN\n" name user timezone))))
14449
14450 (defun org-finish-icalendar-file ()
14451 "Finish an iCalendar file by inserting the END statement."
14452 (princ "END:VCALENDAR\n"))
14453
14454 (defun org-ical-ts-to-string (s keyword &optional inc)
14455 "Take a time string S and convert it to iCalendar format.
14456 KEYWORD is added in front, to make a complete line like DTSTART....
14457 When INC is non-nil, increase the hour by two (if time string contains
14458 a time), or the day by one (if it does not contain a time)."
14459 (let ((t1 (org-parse-time-string s 'nodefault))
14460 t2 fmt have-time time)
14461 (if (and (car t1) (nth 1 t1) (nth 2 t1))
14462 (setq t2 t1 have-time t)
14463 (setq t2 (org-parse-time-string s)))
14464 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
14465 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
14466 (when inc
14467 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
14468 (setq time (encode-time s mi h d m y)))
14469 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
14470 (concat keyword (format-time-string fmt time))))
14471
14472
14473 ;;; Key bindings
14474
14475 ;; - Bindings in Org-mode map are currently
14476 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
14477 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
14478 ;; e (?) useful from outline-mode
14479 ;; i k @ expendable from outline-mode
14480 ;; 0123456789 % & ()_{} " ` free
14481
14482 ;; Make `C-c C-x' a prefix key
14483 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
14484
14485 ;; TAB key with modifiers
14486 (define-key org-mode-map "\C-i" 'org-cycle)
14487 (define-key org-mode-map [(tab)] 'org-cycle)
14488 (define-key org-mode-map [(meta tab)] 'org-complete)
14489 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
14490 ;; The following line is necessary under Suse GNU/Linux
14491 (unless (featurep 'xemacs)
14492 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
14493 (define-key org-mode-map [(shift tab)] 'org-shifttab)
14494
14495 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
14496 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
14497 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14498 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
14499 (define-key org-mode-map [(meta return)] 'org-meta-return)
14500 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
14501 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
14502
14503 ;; Cursor keys with modifiers
14504 (define-key org-mode-map [(meta left)] 'org-metaleft)
14505 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
14506 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
14507 (define-key org-mode-map [(meta right)] 'org-metaright)
14508 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
14509 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
14510 (define-key org-mode-map [(meta up)] 'org-metaup)
14511 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
14512 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
14513 (define-key org-mode-map [(meta down)] 'org-metadown)
14514 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
14515 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
14516
14517 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14518 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
14519 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
14520 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
14521 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
14522 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
14523 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
14524 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
14525 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
14526 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
14527 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
14528 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
14529 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
14530 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
14531 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
14532 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
14533
14534 ;; All the other keys
14535
14536 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14537 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
14538 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
14539 (define-key org-mode-map "\C-c\C-j" 'org-goto)
14540 (define-key org-mode-map "\C-c\C-t" 'org-todo)
14541 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
14542 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
14543 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
14544 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14545 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
14546 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
14547 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
14548 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
14549 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
14550 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
14551 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
14552 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
14553 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
14554 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
14555 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14556 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14557 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14558 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14559 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
14560 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
14561 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14562 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
14563 (define-key org-mode-map "\C-c]" 'org-remove-file)
14564 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
14565 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
14566 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
14567 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14568 (define-key org-mode-map "\C-m" 'org-return)
14569 (define-key org-mode-map "\C-c?" 'org-table-current-column)
14570 (define-key org-mode-map "\C-c " 'org-table-blank-field)
14571 (define-key org-mode-map "\C-c+" 'org-table-sum)
14572 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
14573 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
14574 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
14575 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14576 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
14577 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14578 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
14579 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
14580 (define-key org-mode-map "\C-c\C-e" 'org-export)
14581 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14582
14583 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
14584 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14585 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14586 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14587
14588 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14589 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14590 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14591 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14592 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14593
14594 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14595
14596 (when (featurep 'xemacs)
14597 (define-key org-mode-map 'button3 'popup-mode-menu))
14598
14599 (defsubst org-table-p () (org-at-table-p))
14600
14601 (defun org-self-insert-command (N)
14602 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14603 If the cursor is in a table looking at whitespace, the whitespace is
14604 overwritten, and the table is not marked as requiring realignment."
14605 (interactive "p")
14606 (if (and (org-table-p)
14607 (progn
14608 ;; check if we blank the field, and if that triggers align
14609 (and org-table-auto-blank-field
14610 (member last-command
14611 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
14612 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14613 ;; got extra space, this field does not determine column width
14614 (let (org-table-may-need-update) (org-table-blank-field))
14615 ;; no extra space, this field may determine column width
14616 (org-table-blank-field)))
14617 t)
14618 (eq N 1)
14619 (looking-at "[^|\n]* |"))
14620 (let (org-table-may-need-update)
14621 (goto-char (1- (match-end 0)))
14622 (delete-backward-char 1)
14623 (goto-char (match-beginning 0))
14624 (self-insert-command N))
14625 (setq org-table-may-need-update t)
14626 (self-insert-command N)))
14627
14628 (defun org-delete-backward-char (N)
14629 "Like `delete-backward-char', insert whitespace at field end in tables.
14630 When deleting backwards, in tables this function will insert whitespace in
14631 front of the next \"|\" separator, to keep the table aligned. The table will
14632 still be marked for re-alignment if the field did fill the entire column,
14633 because, in this case the deletion might narrow the column."
14634 (interactive "p")
14635 (if (and (org-table-p)
14636 (eq N 1)
14637 (string-match "|" (buffer-substring (point-at-bol) (point)))
14638 (looking-at ".*?|"))
14639 (let ((pos (point))
14640 (noalign (looking-at "[^|\n\r]* |"))
14641 (c org-table-may-need-update))
14642 (backward-delete-char N)
14643 (skip-chars-forward "^|")
14644 (insert " ")
14645 (goto-char (1- pos))
14646 ;; noalign: if there were two spaces at the end, this field
14647 ;; does not determine the width of the column.
14648 (if noalign (setq org-table-may-need-update c)))
14649 (backward-delete-char N)))
14650
14651 (defun org-delete-char (N)
14652 "Like `delete-char', but insert whitespace at field end in tables.
14653 When deleting characters, in tables this function will insert whitespace in
14654 front of the next \"|\" separator, to keep the table aligned. The table will
14655 still be marked for re-alignment if the field did fill the entire column,
14656 because, in this case the deletion might narrow the column."
14657 (interactive "p")
14658 (if (and (org-table-p)
14659 (not (bolp))
14660 (not (= (char-after) ?|))
14661 (eq N 1))
14662 (if (looking-at ".*?|")
14663 (let ((pos (point))
14664 (noalign (looking-at "[^|\n\r]* |"))
14665 (c org-table-may-need-update))
14666 (replace-match (concat
14667 (substring (match-string 0) 1 -1)
14668 " |"))
14669 (goto-char pos)
14670 ;; noalign: if there were two spaces at the end, this field
14671 ;; does not determine the width of the column.
14672 (if noalign (setq org-table-may-need-update c)))
14673 (delete-char N))
14674 (delete-char N)))
14675
14676 ;; How to do this: Measure non-white length of current string
14677 ;; If equal to column width, we should realign.
14678
14679 (defun org-remap (map &rest commands)
14680 "In MAP, remap the functions given in COMMANDS.
14681 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14682 (let (new old)
14683 (while commands
14684 (setq old (pop commands) new (pop commands))
14685 (if (fboundp 'command-remapping)
14686 (define-key map (vector 'remap old) new)
14687 (substitute-key-definition old new map global-map)))))
14688
14689 (when (eq org-enable-table-editor 'optimized)
14690 ;; If the user wants maximum table support, we need to hijack
14691 ;; some standard editing functions
14692 (org-remap org-mode-map
14693 'self-insert-command 'org-self-insert-command
14694 'delete-char 'org-delete-char
14695 'delete-backward-char 'org-delete-backward-char)
14696 (define-key org-mode-map "|" 'org-force-self-insert))
14697
14698 (defun org-shiftcursor-error ()
14699 "Throw an error because Shift-Cursor command was applied in wrong context."
14700 (error "This command is active in special context like tables, headlines or timestamps"))
14701
14702 (defun org-shifttab (&optional arg)
14703 "Global visibility cycling or move to previous table field.
14704 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14705 on context.
14706 See the individual commands for more information."
14707 (interactive "P")
14708 (cond
14709 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14710 (t (call-interactively 'org-global-cycle))))
14711
14712 (defun org-shiftmetaleft ()
14713 "Promote subtree or delete table column.
14714 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
14715 See the individual commands for more information."
14716 (interactive)
14717 (cond
14718 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14719 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14720 ((org-at-item-p) (call-interactively 'org-outdent-item))
14721 (t (org-shiftcursor-error))))
14722
14723 (defun org-shiftmetaright ()
14724 "Demote subtree or insert table column.
14725 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
14726 See the individual commands for more information."
14727 (interactive)
14728 (cond
14729 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14730 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14731 ((org-at-item-p) (call-interactively 'org-indent-item))
14732 (t (org-shiftcursor-error))))
14733
14734 (defun org-shiftmetaup (&optional arg)
14735 "Move subtree up or kill table row.
14736 Calls `org-move-subtree-up' or `org-table-kill-row' or
14737 `org-move-item-up' depending on context. See the individual commands
14738 for more information."
14739 (interactive "P")
14740 (cond
14741 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14742 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14743 ((org-at-item-p) (call-interactively 'org-move-item-up))
14744 (t (org-shiftcursor-error))))
14745 (defun org-shiftmetadown (&optional arg)
14746 "Move subtree down or insert table row.
14747 Calls `org-move-subtree-down' or `org-table-insert-row' or
14748 `org-move-item-down', depending on context. See the individual
14749 commands for more information."
14750 (interactive "P")
14751 (cond
14752 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14753 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14754 ((org-at-item-p) (call-interactively 'org-move-item-down))
14755 (t (org-shiftcursor-error))))
14756
14757 (defun org-metaleft (&optional arg)
14758 "Promote heading or move table column to left.
14759 Calls `org-do-promote' or `org-table-move-column', depending on context.
14760 With no specific context, calls the Emacs default `backward-word'.
14761 See the individual commands for more information."
14762 (interactive "P")
14763 (cond
14764 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14765 ((or (org-on-heading-p) (org-region-active-p))
14766 (call-interactively 'org-do-promote))
14767 (t (call-interactively 'backward-word))))
14768
14769 (defun org-metaright (&optional arg)
14770 "Demote subtree or move table column to right.
14771 Calls `org-do-demote' or `org-table-move-column', depending on context.
14772 With no specific context, calls the Emacs default `forward-word'.
14773 See the individual commands for more information."
14774 (interactive "P")
14775 (cond
14776 ((org-at-table-p) (call-interactively 'org-table-move-column))
14777 ((or (org-on-heading-p) (org-region-active-p))
14778 (call-interactively 'org-do-demote))
14779 (t (call-interactively 'forward-word))))
14780
14781 (defun org-metaup (&optional arg)
14782 "Move subtree up or move table row up.
14783 Calls `org-move-subtree-up' or `org-table-move-row' or
14784 `org-move-item-up', depending on context. See the individual commands
14785 for more information."
14786 (interactive "P")
14787 (cond
14788 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14789 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14790 ((org-at-item-p) (call-interactively 'org-move-item-up))
14791 (t (org-shiftcursor-error))))
14792
14793 (defun org-metadown (&optional arg)
14794 "Move subtree down or move table row down.
14795 Calls `org-move-subtree-down' or `org-table-move-row' or
14796 `org-move-item-down', depending on context. See the individual
14797 commands for more information."
14798 (interactive "P")
14799 (cond
14800 ((org-at-table-p) (call-interactively 'org-table-move-row))
14801 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14802 ((org-at-item-p) (call-interactively 'org-move-item-down))
14803 (t (org-shiftcursor-error))))
14804
14805 (defun org-shiftup (&optional arg)
14806 "Increase item in timestamp or increase priority of current headline.
14807 Calls `org-timestamp-up' or `org-priority-up', depending on context.
14808 See the individual commands for more information."
14809 (interactive "P")
14810 (cond
14811 ((org-at-timestamp-p) (call-interactively 'org-timestamp-up))
14812 ((org-on-heading-p) (call-interactively 'org-priority-up))
14813 ((org-at-item-p) (call-interactively 'org-previous-item))
14814 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
14815
14816 (defun org-shiftdown (&optional arg)
14817 "Decrease item in timestamp or decrease priority of current headline.
14818 Calls `org-timestamp-down' or `org-priority-down', depending on context.
14819 See the individual commands for more information."
14820 (interactive "P")
14821 (cond
14822 ((org-at-timestamp-p) (call-interactively 'org-timestamp-down))
14823 ((org-on-heading-p) (call-interactively 'org-priority-down))
14824 (t (call-interactively 'org-next-item))))
14825
14826 (defun org-shiftright ()
14827 "Next TODO keyword or timestamp one day later, depending on context."
14828 (interactive)
14829 (cond
14830 ((org-at-timestamp-p) (call-interactively 'org-timestamp-up-day))
14831 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
14832 (t (org-shiftcursor-error))))
14833
14834 (defun org-shiftleft ()
14835 "Previous TODO keyword or timestamp one day earlier, depending on context."
14836 (interactive)
14837 (cond
14838 ((org-at-timestamp-p) (call-interactively 'org-timestamp-down-day))
14839 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
14840 (t (org-shiftcursor-error))))
14841
14842 (defun org-copy-special ()
14843 "Copy region in table or copy current subtree.
14844 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14845 See the individual commands for more information."
14846 (interactive)
14847 (call-interactively
14848 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14849
14850 (defun org-cut-special ()
14851 "Cut region in table or cut current subtree.
14852 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14853 See the individual commands for more information."
14854 (interactive)
14855 (call-interactively
14856 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14857
14858 (defun org-paste-special (arg)
14859 "Paste rectangular region into table, or past subtree relative to level.
14860 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14861 See the individual commands for more information."
14862 (interactive "P")
14863 (if (org-at-table-p)
14864 (org-table-paste-rectangle)
14865 (org-paste-subtree arg)))
14866
14867 (defun org-ctrl-c-ctrl-c (&optional arg)
14868 "Set tags in headline, or update according to changed information at point.
14869
14870 This command does many different things, depending on context:
14871
14872 - If the cursor is in a headline, prompt for tags and insert them
14873 into the current line, aligned to `org-tags-column'. When called
14874 with prefix arg, realign all tags in the current buffer.
14875
14876 - If the cursor is in one of the special #+KEYWORD lines, this
14877 triggers scanning the buffer for these lines and updating the
14878 information.
14879
14880 - If the cursor is inside a table, realign the table. This command
14881 works even if the automatic table editor has been turned off.
14882
14883 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14884 the entire table.
14885
14886 - If the cursor is inside a table created by the table.el package,
14887 activate that table.
14888
14889 - If the current buffer is a remember buffer, close note and file it.
14890 with a prefix argument, file it without further interaction to the default
14891 location.
14892
14893 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14894 links in this buffer.
14895
14896 - If the cursor is on a numbered item in a plain list, renumber the
14897 ordered list."
14898 (interactive "P")
14899 (let ((org-enable-table-editor t))
14900 (cond
14901 (org-clock-overlays
14902 (org-remove-clock-overlays)
14903 (message "Clock overlays removed"))
14904 (org-occur-highlights
14905 (org-remove-occur-highlights)
14906 (message "occur highlights removed"))
14907 ((and (local-variable-p 'org-finish-function (current-buffer))
14908 (fboundp org-finish-function))
14909 (funcall org-finish-function))
14910 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14911 ((org-on-heading-p) (call-interactively 'org-set-tags))
14912 ((org-at-table.el-p)
14913 (require 'table)
14914 (beginning-of-line 1)
14915 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14916 (call-interactively 'table-recognize-table))
14917 ((org-at-table-p)
14918 (org-table-maybe-eval-formula)
14919 (if arg
14920 (call-interactively 'org-table-recalculate)
14921 (org-table-maybe-recalculate-line))
14922 (call-interactively 'org-table-align))
14923 ((org-at-item-checkbox-p)
14924 (call-interactively 'org-toggle-checkbox))
14925 ((org-at-item-p)
14926 (call-interactively 'org-renumber-ordered-list))
14927 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14928 (cond
14929 ((equal (match-string 1) "TBLFM")
14930 ;; Recalculate the table before this line
14931 (save-excursion
14932 (beginning-of-line 1)
14933 (skip-chars-backward " \r\n\t")
14934 (if (org-at-table-p)
14935 (org-call-with-arg 'org-table-recalculate t))))
14936 (t
14937 (call-interactively 'org-mode-restart))))
14938 (t (error "C-c C-c can do nothing useful at this location.")))))
14939
14940 (defun org-mode-restart ()
14941 "Restart Org-mode, to scan again for special lines.
14942 Also updates the keyword regular expressions."
14943 (interactive)
14944 (let ((org-inhibit-startup t)) (org-mode))
14945 (message "Org-mode restarted to refresh keyword and special line setup"))
14946
14947 (defun org-return ()
14948 "Goto next table row or insert a newline.
14949 Calls `org-table-next-row' or `newline', depending on context.
14950 See the individual commands for more information."
14951 (interactive)
14952 (cond
14953 ((org-at-table-p)
14954 (org-table-justify-field-maybe)
14955 (call-interactively 'org-table-next-row))
14956 (t (newline))))
14957
14958 (defun org-meta-return (&optional arg)
14959 "Insert a new heading or wrap a region in a table.
14960 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14961 See the individual commands for more information."
14962 (interactive "P")
14963 (cond
14964 ((org-at-table-p)
14965 (call-interactively 'org-table-wrap-region))
14966 (t (call-interactively 'org-insert-heading))))
14967
14968 ;;; Menu entries
14969
14970 ;; Define the Org-mode menus
14971 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14972 '("Tbl"
14973 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
14974 ["Next Field" org-cycle (org-at-table-p)]
14975 ["Previous Field" org-shifttab (org-at-table-p)]
14976 ["Next Row" org-return (org-at-table-p)]
14977 "--"
14978 ["Blank Field" org-table-blank-field (org-at-table-p)]
14979 ["Edit Field" org-table-edit-field (org-at-table-p)]
14980 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14981 "--"
14982 ("Column"
14983 ["Move Column Left" org-metaleft (org-at-table-p)]
14984 ["Move Column Right" org-metaright (org-at-table-p)]
14985 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14986 ["Insert Column" org-shiftmetaright (org-at-table-p)]
14987 "--"
14988 ["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])
14989 ("Row"
14990 ["Move Row Up" org-metaup (org-at-table-p)]
14991 ["Move Row Down" org-metadown (org-at-table-p)]
14992 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14993 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14994 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14995 "--"
14996 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
14997 ("Rectangle"
14998 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14999 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15000 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15001 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15002 "--"
15003 ("Calculate"
15004 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15005 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15006 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
15007 "--"
15008 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15009 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15010 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15011 "--"
15012 ["Sum Column/Rectangle" org-table-sum
15013 (or (org-at-table-p) (org-region-active-p))]
15014 ["Which Column?" org-table-current-column (org-at-table-p)])
15015 ["Debug Formulas"
15016 (setq org-table-formula-debug (not org-table-formula-debug))
15017 :style toggle :selected org-table-formula-debug]
15018 "--"
15019 ["Create" org-table-create (and (not (org-at-table-p))
15020 org-enable-table-editor)]
15021 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15022 ["Import from File" org-table-import (not (org-at-table-p))]
15023 ["Export to File" org-table-export (org-at-table-p)]
15024 "--"
15025 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15026
15027 (easy-menu-define org-org-menu org-mode-map "Org menu"
15028 '("Org"
15029 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
15030 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
15031 ["Sparse Tree" org-occur t]
15032 ["Show All" show-all t]
15033 "--"
15034 ["New Heading" org-insert-heading t]
15035 ("Navigate Headings"
15036 ["Up" outline-up-heading t]
15037 ["Next" outline-next-visible-heading t]
15038 ["Previous" outline-previous-visible-heading t]
15039 ["Next Same Level" outline-forward-same-level t]
15040 ["Previous Same Level" outline-backward-same-level t]
15041 "--"
15042 ["Jump" org-goto t])
15043 ("Edit Structure"
15044 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15045 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15046 "--"
15047 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15048 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15049 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15050 "--"
15051 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15052 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15053 ["Demote Heading" org-metaright (not (org-at-table-p))]
15054 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15055 "--"
15056 ["Archive Subtree" org-archive-subtree t]
15057 "--"
15058 ["Convert to odd levels" org-convert-to-odd-levels t]
15059 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15060 "--"
15061 ("TODO Lists"
15062 ["TODO/DONE/-" org-todo t]
15063 ["Show TODO Tree" org-show-todo-tree t]
15064 ["Global TODO list" org-todo-list t]
15065 "--"
15066 ["Set Priority" org-priority t]
15067 ["Priority Up" org-shiftup t]
15068 ["Priority Down" org-shiftdown t])
15069 ("Dates and Scheduling"
15070 ["Timestamp" org-time-stamp t]
15071 ["Timestamp (inactive)" org-time-stamp-inactive t]
15072 ("Change Date"
15073 ["1 Day Later" org-timestamp-up-day t]
15074 ["1 Day Earlier" org-timestamp-down-day t]
15075 ["1 ... Later" org-shiftup t]
15076 ["1 ... Earlier" org-shiftdown t])
15077 ["Compute Time Range" org-evaluate-time-range t]
15078 ["Schedule Item" org-schedule t]
15079 ["Deadline" org-deadline t]
15080 "--"
15081 ["Goto Calendar" org-goto-calendar t]
15082 ["Date from Calendar" org-date-from-calendar t])
15083 ("Logging work"
15084 ["Clock in" org-clock-in t]
15085 ["Clock out" org-clock-out t]
15086 ["Clock cancel" org-clock-cancel t]
15087 ["Display times" org-clock-display t]
15088 ["Create clock table" org-clock-report t]
15089 "--"
15090 ["Record DONE time"
15091 (progn (setq org-log-done (not org-log-done))
15092 (message "Switching to %s will %s record a timestamp"
15093 org-done-string
15094 (if org-log-done "automatically" "not")))
15095 :style toggle :selected org-log-done])
15096 "--"
15097 ["Agenda Command" org-agenda t]
15098 ("File List for Agenda")
15099 ("Special views current file"
15100 ["TODO Tree" org-show-todo-tree t]
15101 ["Check Deadlines" org-check-deadlines t]
15102 ["Timeline" org-timeline t]
15103 ["Tags Tree" org-tags-sparse-tree t])
15104 "--"
15105 ("Hyperlinks"
15106 ["Store Link (Global)" org-store-link t]
15107 ["Insert Link" org-insert-link t]
15108 ["Follow Link" org-open-at-point t]
15109 "--"
15110 ["Descriptive Links"
15111 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15112 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
15113 ["Literal Links"
15114 (progn
15115 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15116 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
15117 "--"
15118 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
15119 (save-excursion (goto-char (point-min))
15120 (re-search-forward "<[a-z]+:" nil t))])
15121 "--"
15122 ["Export/Publish" org-export t]
15123 "--"
15124 ("Documentation"
15125 ["Show Version" org-version t]
15126 ["Info Documentation" org-info t])
15127 ("Customize"
15128 ["Browse Org Group" org-customize t]
15129 "--"
15130 ["Expand This Menu" org-create-customize-menu
15131 (fboundp 'customize-menu-create)])
15132 "--"
15133 ["Refresh setup" org-mode-restart t]
15134 ))
15135
15136 (defun org-info (&optional node)
15137 "Read documentation for Org-mode in the info system.
15138 With optional NODE, go directly to that node."
15139 (interactive)
15140 (require 'info)
15141 (Info-goto-node (format "(org)%s" (or node ""))))
15142
15143 (defun org-install-agenda-files-menu ()
15144 (let ((bl (buffer-list)))
15145 (save-excursion
15146 (while bl
15147 (set-buffer (pop bl))
15148 (if (eq major-mode 'org-mode) (setq bl nil)))
15149 (when (eq major-mode 'org-mode)
15150 (easy-menu-change
15151 '("Org") "File List for Agenda"
15152 (append
15153 (list
15154 ["Edit File List" (org-edit-agenda-file-list) t]
15155 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15156 ["Remove Current File from List" org-remove-file t]
15157 ["Cycle through agenda files" org-cycle-agenda-files t]
15158 "--")
15159 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15160
15161 ;;; Documentation
15162
15163 (defun org-customize ()
15164 "Call the customize function with org as argument."
15165 (interactive)
15166 (customize-browse 'org))
15167
15168 (defun org-create-customize-menu ()
15169 "Create a full customization menu for Org-mode, insert it into the menu."
15170 (interactive)
15171 (if (fboundp 'customize-menu-create)
15172 (progn
15173 (easy-menu-change
15174 '("Org") "Customize"
15175 `(["Browse Org group" org-customize t]
15176 "--"
15177 ,(customize-menu-create 'org)
15178 ["Set" Custom-set t]
15179 ["Save" Custom-save t]
15180 ["Reset to Current" Custom-reset-current t]
15181 ["Reset to Saved" Custom-reset-saved t]
15182 ["Reset to Standard Settings" Custom-reset-standard t]))
15183 (message "\"Org\"-menu now contains full customization menu"))
15184 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15185
15186 ;;; Miscellaneous stuff
15187
15188 (defun org-context ()
15189 "Return a list of contexts of the current cursor position.
15190 If several contexts apply, all are returned.
15191 Each context entry is a list with a symbol naming the context, and
15192 two positions indicating start and end of the context. Possible
15193 contexts are:
15194
15195 :headline anywhere in a headline
15196 :headline-stars on the leading stars in a headline
15197 :todo-keyword on a TODO keyword (including DONE) in a headline
15198 :tags on the TAGS in a headline
15199 :priority on the priority cookie in a headline
15200 :item on the first line of a plain list item
15201 :checkbox on the checkbox in a plain list item
15202 :table in an org-mode table
15203 :table-special on a special filed in a table
15204 :table-table in a table.el table
15205 :link on a hyperline
15206 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15207 :target on a <<target>>
15208 :radio-target on a <<<radio-target>>>
15209
15210 This function expects the position to be visible because it uses font-lock
15211 faces as a help to recognize the following contexts: :table-special, :link,
15212 and :keyword."
15213 (let* ((f (get-text-property (point) 'face))
15214 (faces (if (listp f) f (list f)))
15215 (p (point)) clist)
15216 ;; First the large context
15217 (cond
15218 ((org-on-heading-p)
15219 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15220 (when (progn
15221 (beginning-of-line 1)
15222 (looking-at org-todo-line-tags-regexp))
15223 (push (org-point-in-group p 1 :headline-stars) clist)
15224 (push (org-point-in-group p 2 :todo-keyword) clist)
15225 (push (org-point-in-group p 4 :tags) clist))
15226 (goto-char p)
15227 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15228 (if (looking-at "\\[#[A-Z]\\]")
15229 (push (org-point-in-group p 0 :priority) clist)))
15230
15231 ((org-at-item-p)
15232 (push (list :item (point-at-bol)
15233 (save-excursion (org-end-of-item) (point)))
15234 clist)
15235 (and (org-at-item-checkbox-p)
15236 (push (org-point-in-group p 0 :checkbox) clist)))
15237
15238 ((org-at-table-p)
15239 (push (list :table (org-table-begin) (org-table-end)) clist)
15240 (if (memq 'org-formula faces)
15241 (push (list :table-special
15242 (previous-single-property-change p 'face)
15243 (next-single-property-change p 'face)) clist)))
15244 ((org-at-table-p 'any)
15245 (push (list :table-table) clist)))
15246 (goto-char p)
15247
15248 ;; Now the small context
15249 (cond
15250 ((org-at-timestamp-p)
15251 (push (org-point-in-group p 0 :timestamp) clist))
15252 ((memq 'org-link faces)
15253 (push (list :link
15254 (previous-single-property-change p 'face)
15255 (next-single-property-change p 'face)) clist))
15256 ((memq 'org-special-keyword faces)
15257 (push (list :keyword
15258 (previous-single-property-change p 'face)
15259 (next-single-property-change p 'face)) clist))
15260 ((org-on-target-p)
15261 (push (org-point-in-group p 0 :target) clist)
15262 (goto-char (1- (match-beginning 0)))
15263 (if (looking-at org-radio-target-regexp)
15264 (push (org-point-in-group p 0 :radio-target) clist))
15265 (goto-char p)))
15266
15267 (setq clist (nreverse (delq nil clist)))
15268 clist))
15269
15270 (defun org-point-in-group (point group &optional context)
15271 "Check if POINT is in match-group GROUP.
15272 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15273 match. If the match group does ot exist or point is not inside it,
15274 return nil."
15275 (and (match-beginning group)
15276 (>= point (match-beginning group))
15277 (<= point (match-end group))
15278 (if context
15279 (list context (match-beginning group) (match-end group))
15280 t)))
15281
15282 (defun org-move-line-down (arg)
15283 "Move the current line down. With prefix argument, move it past ARG lines."
15284 (interactive "p")
15285 (let ((col (current-column))
15286 beg end pos)
15287 (beginning-of-line 1) (setq beg (point))
15288 (beginning-of-line 2) (setq end (point))
15289 (beginning-of-line (+ 1 arg))
15290 (setq pos (move-marker (make-marker) (point)))
15291 (insert (delete-and-extract-region beg end))
15292 (goto-char pos)
15293 (move-to-column col)))
15294
15295 (defun org-move-line-up (arg)
15296 "Move the current line up. With prefix argument, move it past ARG lines."
15297 (interactive "p")
15298 (let ((col (current-column))
15299 beg end pos)
15300 (beginning-of-line 1) (setq beg (point))
15301 (beginning-of-line 2) (setq end (point))
15302 (beginning-of-line (- arg))
15303 (setq pos (move-marker (make-marker) (point)))
15304 (insert (delete-and-extract-region beg end))
15305 (goto-char pos)
15306 (move-to-column col)))
15307
15308 ;; Paragraph filling stuff.
15309 ;; We want this to be just right, so use the full arsenal.
15310
15311 (defun org-set-autofill-regexps ()
15312 (interactive)
15313 ;; In the paragraph separator we include headlines, because filling
15314 ;; text in a line directly attached to a headline would otherwise
15315 ;; fill the headline as well.
15316 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
15317 ;; The paragraph starter includes hand-formatted lists.
15318 (set (make-local-variable 'paragraph-start)
15319 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15320 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15321 ;; But only if the user has not turned off tables or fixed-width regions
15322 (set (make-local-variable 'auto-fill-inhibit-regexp)
15323 (concat "\\*\\|#"
15324 "\\|[ \t]*" org-keyword-time-regexp
15325 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15326 (concat
15327 "\\|[ \t]*["
15328 (if org-enable-table-editor "|" "")
15329 (if org-enable-fixed-width-editor ":" "")
15330 "]"))))
15331 ;; We use our own fill-paragraph function, to make sure that tables
15332 ;; and fixed-width regions are not wrapped. That function will pass
15333 ;; through to `fill-paragraph' when appropriate.
15334 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
15335 ;; Adaptive filling: To get full control, first make sure that
15336 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15337 (set (make-local-variable 'adaptive-fill-regexp) "\000")
15338 (set (make-local-variable 'adaptive-fill-function)
15339 'org-adaptive-fill-function))
15340
15341 (defun org-fill-paragraph (&optional justify)
15342 "Re-align a table, pass through to fill-paragraph if no table."
15343 (let ((table-p (org-at-table-p))
15344 (table.el-p (org-at-table.el-p)))
15345 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
15346 (table.el-p t) ; skip table.el tables
15347 (table-p (org-table-align) t) ; align org-mode tables
15348 (t nil)))) ; call paragraph-fill
15349
15350 ;; For reference, this is the default value of adaptive-fill-regexp
15351 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15352
15353 (defun org-adaptive-fill-function ()
15354 "Return a fill prefix for org-mode files.
15355 In particular, this makes sure hanging paragraphs for hand-formatted lists
15356 work correctly."
15357 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
15358 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
15359
15360 ;; Functions needed for Emacs/XEmacs region compatibility
15361
15362 (defun org-add-hook (hook function &optional append local)
15363 "Add-hook, compatible with both Emacsen."
15364 (if (and local (featurep 'xemacs))
15365 (add-local-hook hook function append)
15366 (add-hook hook function append local)))
15367
15368 (defun org-region-active-p ()
15369 "Is `transient-mark-mode' on and the region active?
15370 Works on both Emacs and XEmacs."
15371 (if org-ignore-region
15372 nil
15373 (if (featurep 'xemacs)
15374 (and zmacs-regions (region-active-p))
15375 (and transient-mark-mode mark-active))))
15376
15377 (defun org-add-to-invisibility-spec (arg)
15378 "Add elements to `buffer-invisibility-spec'.
15379 See documentation for `buffer-invisibility-spec' for the kind of elements
15380 that can be added."
15381 (cond
15382 ((fboundp 'add-to-invisibility-spec)
15383 (add-to-invisibility-spec arg))
15384 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
15385 (setq buffer-invisibility-spec (list arg)))
15386 (t
15387 (setq buffer-invisibility-spec
15388 (cons arg buffer-invisibility-spec)))))
15389
15390 (defun org-remove-from-invisibility-spec (arg)
15391 "Remove elements from `buffer-invisibility-spec'."
15392 (if (fboundp 'remove-from-invisibility-spec)
15393 (remove-from-invisibility-spec arg)
15394 (if (consp buffer-invisibility-spec)
15395 (setq buffer-invisibility-spec
15396 (delete arg buffer-invisibility-spec)))))
15397
15398 (defun org-in-invisibility-spec-p (arg)
15399 "Is ARG a member of `buffer-invisibility-spec'?"
15400 (if (consp buffer-invisibility-spec)
15401 (member arg buffer-invisibility-spec)
15402 nil))
15403
15404 (defun org-image-file-name-regexp ()
15405 "Return regexp matching the file names of images."
15406 (if (fboundp 'image-file-name-regexp)
15407 (image-file-name-regexp)
15408 (let ((image-file-name-extensions
15409 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15410 "xbm" "xpm" "pbm" "pgm" "ppm")))
15411 (concat "\\."
15412 (regexp-opt (nconc (mapcar 'upcase
15413 image-file-name-extensions)
15414 image-file-name-extensions)
15415 t)
15416 "\\'"))))
15417
15418 ;; Functions needed for compatibility with old outline.el.
15419
15420 ;; Programming for the old outline.el (that uses selective display
15421 ;; instead of `invisible' text properties) is a nightmare, mostly
15422 ;; because regular expressions can no longer be anchored at
15423 ;; beginning/end of line. Therefore a number of function need special
15424 ;; treatment when the old outline.el is being used.
15425
15426 ;; The following functions capture almost the entire compatibility code
15427 ;; between the different versions of outline-mode. The only other
15428 ;; places where this is important are the font-lock-keywords, and in
15429 ;; `org-export-visible'. Search for `org-noutline-p' to find them.
15430
15431 ;; C-a should go to the beginning of a *visible* line, also in the
15432 ;; new outline.el. I guess this should be patched into Emacs?
15433 (defun org-beginning-of-line ()
15434 "Go to the beginning of the current line. If that is invisible, continue
15435 to a visible line beginning. This makes the function of C-a more intuitive."
15436 (interactive)
15437 (beginning-of-line 1)
15438 (if (bobp)
15439 nil
15440 (backward-char 1)
15441 (if (org-invisible-p)
15442 (while (and (not (bobp)) (org-invisible-p))
15443 (backward-char 1)
15444 (beginning-of-line 1))
15445 (forward-char 1))))
15446
15447 (when org-noutline-p
15448 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
15449
15450 (defun org-invisible-p ()
15451 "Check if point is at a character currently not visible."
15452 (if org-noutline-p
15453 ;; Early versions of noutline don't have `outline-invisible-p'.
15454 (if (fboundp 'outline-invisible-p)
15455 (outline-invisible-p)
15456 (get-char-property (point) 'invisible))
15457 (save-excursion
15458 (skip-chars-backward "^\r\n")
15459 (equal (char-before) ?\r))))
15460
15461 (defun org-invisible-p2 ()
15462 "Check if point is at a character currently not visible."
15463 (save-excursion
15464 (if org-noutline-p
15465 (progn
15466 (if (and (eolp) (not (bobp))) (backward-char 1))
15467 ;; Early versions of noutline don't have `outline-invisible-p'.
15468 (if (fboundp 'outline-invisible-p)
15469 (outline-invisible-p)
15470 (get-char-property (point) 'invisible)))
15471 (skip-chars-backward "^\r\n")
15472 (equal (char-before) ?\r))))
15473
15474 (defun org-back-to-heading (&optional invisible-ok)
15475 "Move to previous heading line, or beg of this line if it's a heading.
15476 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
15477 (if org-noutline-p
15478 (outline-back-to-heading invisible-ok)
15479 (if (and (or (bobp) (memq (char-before) '(?\n ?\r)))
15480 (looking-at outline-regexp))
15481 t
15482 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
15483 outline-regexp)
15484 nil t)
15485 (if invisible-ok
15486 (progn (goto-char (or (match-end 1) (match-beginning 0)))
15487 (looking-at outline-regexp)))
15488 (error "Before first heading")))))
15489
15490 (defun org-on-heading-p (&optional invisible-ok)
15491 "Return t if point is on a (visible) heading line.
15492 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
15493 (if org-noutline-p
15494 (outline-on-heading-p 'invisible-ok)
15495 (save-excursion
15496 (skip-chars-backward "^\n\r")
15497 (and (looking-at outline-regexp)
15498 (or invisible-ok
15499 (bobp)
15500 (equal (char-before) ?\n))))))
15501
15502 (defun org-on-target-p ()
15503 (let ((pos (point)))
15504 (save-excursion
15505 (skip-chars-forward "<")
15506 (and (re-search-backward "<<" nil t)
15507 (or (looking-at org-radio-target-regexp)
15508 (looking-at org-target-regexp))
15509 (<= (match-beginning 0) pos)
15510 (>= (1+ (match-end 0)) pos)))))
15511
15512 (defun org-up-heading-all (arg)
15513 "Move to the heading line of which the present line is a subheading.
15514 This function considers both visible and invisible heading lines.
15515 With argument, move up ARG levels."
15516 (if org-noutline-p
15517 (if (fboundp 'outline-up-heading-all)
15518 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15519 (outline-up-heading arg t)) ; emacs 22 version of outline.el
15520 (org-back-to-heading t)
15521 (looking-at outline-regexp)
15522 (if (<= (- (match-end 0) (match-beginning 0)) arg)
15523 (error "Cannot move up %d levels" arg)
15524 (re-search-backward
15525 (concat "[\n\r]" (regexp-quote
15526 (make-string (- (match-end 0) (match-beginning 0) arg)
15527 ?*))
15528 "[^*]"))
15529 (forward-char 1))))
15530
15531 (defun org-show-hidden-entry ()
15532 "Show an entry where even the heading is hidden."
15533 (save-excursion
15534 (if (not org-noutline-p)
15535 (progn
15536 (org-back-to-heading t)
15537 (org-flag-heading nil)))
15538 (org-show-entry)))
15539
15540 (defun org-check-occur-regexp (regexp)
15541 "If REGEXP starts with \"^\", modify it to check for \\r as well.
15542 Of course, only for the old outline mode."
15543 (if org-noutline-p
15544 regexp
15545 (if (string-match "^\\^" regexp)
15546 (concat "[\n\r]" (substring regexp 1))
15547 regexp)))
15548
15549 (defun org-flag-heading (flag &optional entry)
15550 "Flag the current heading. FLAG non-nil means make invisible.
15551 When ENTRY is non-nil, show the entire entry."
15552 (save-excursion
15553 (org-back-to-heading t)
15554 (if (not org-noutline-p)
15555 ;; Make the current headline visible
15556 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
15557 ;; Check if we should show the entire entry
15558 (if entry
15559 (progn
15560 (org-show-entry)
15561 (save-excursion
15562 (and (outline-next-heading)
15563 (org-flag-heading nil))))
15564 (outline-flag-region (max 1 (1- (point)))
15565 (save-excursion (outline-end-of-heading) (point))
15566 (if org-noutline-p
15567 flag
15568 (if flag ?\r ?\n))))))
15569
15570 (defun org-end-of-subtree (&optional invisible-OK)
15571 ;; This is an exact copy of the original function, but it uses
15572 ;; `org-back-to-heading', to make it work also in invisible
15573 ;; trees. And is uses an invisible-OK argument.
15574 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15575 (org-back-to-heading invisible-OK)
15576 (let ((first t)
15577 (level (funcall outline-level)))
15578 (while (and (not (eobp))
15579 (or first (> (funcall outline-level) level)))
15580 (setq first nil)
15581 (outline-next-heading))
15582 (if (memq (preceding-char) '(?\n ?\^M))
15583 (progn
15584 ;; Go to end of line before heading
15585 (forward-char -1)
15586 (if (memq (preceding-char) '(?\n ?\^M))
15587 ;; leave blank line before heading
15588 (forward-char -1)))))
15589 (point))
15590
15591 (defun org-show-subtree ()
15592 "Show everything after this heading at deeper levels."
15593 (outline-flag-region
15594 (point)
15595 (save-excursion
15596 (outline-end-of-subtree) (outline-next-heading) (point))
15597 (if org-noutline-p nil ?\n)))
15598
15599 (defun org-show-entry ()
15600 "Show the body directly following this heading.
15601 Show the heading too, if it is currently invisible."
15602 (interactive)
15603 (save-excursion
15604 (org-back-to-heading t)
15605 (outline-flag-region
15606 (max 1 (1- (point)))
15607 (save-excursion
15608 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
15609 (or (match-beginning 1) (point-max)))
15610 (if org-noutline-p nil ?\n))))
15611
15612 (defun org-make-options-regexp (kwds)
15613 "Make a regular expression for keyword lines."
15614 (concat
15615 (if org-noutline-p "^" "[\n\r]")
15616 "#?[ \t]*\\+\\("
15617 (mapconcat 'regexp-quote kwds "\\|")
15618 "\\):[ \t]*"
15619 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
15620
15621 ;; Make `bookmark-jump' show the jump location if it was hidden.
15622 (eval-after-load "bookmark"
15623 '(if (boundp 'bookmark-after-jump-hook)
15624 ;; We can use the hook
15625 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15626 ;; Hook not available, use advice
15627 (defadvice bookmark-jump (after org-make-visible activate)
15628 "Make the position visible."
15629 (org-bookmark-jump-unhide))))
15630
15631 (defun org-bookmark-jump-unhide ()
15632 "Unhide the current position, to show the bookmark location."
15633 (and (eq major-mode 'org-mode)
15634 (or (org-invisible-p)
15635 (save-excursion (goto-char (max (point-min) (1- (point))))
15636 (org-invisible-p)))
15637 (org-show-hierarchy-above)))
15638
15639
15640 ;;; Experimental code
15641
15642
15643 ;;; Finish up
15644
15645 (provide 'org)
15646
15647 (run-hooks 'org-load-hook)
15648
15649 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15650 ;;; org.el ends here